branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/main
<repo_name>pret-a-porter/obsidian-outliner<file_sep>/specs/SelectionShouldIgnoreBulletsFeature.spec.ts /** * @jest-environment ./jest/obsidian-environment */ test("Cmd-Shift-Left should select content only", async () => { // arrange await applyState(["- one|"]); // act await simulateKeydown("Cmd-Shift-Left"); // assert await expect(await getCurrentState()).toEqualEditorState(["- |one|"]); }); <file_sep>/src/list_utils.ts import { diffLines } from "diff"; import { Logger } from "./logger"; import { ObsidianUtils } from "./obsidian_utils"; import { IList, List, Root } from "./root"; const bulletSign = "-*+"; export class ListUtils { constructor(private logger: Logger, private obsidianUtils: ObsidianUtils) {} getListLineInfo(line: string, indentSign: string) { const prefixRe = new RegExp(`^(?:${indentSign})*([${bulletSign}]) `); const matches = prefixRe.exec(line); if (!matches) { return null; } const prefixLength = matches[0].length; const bullet = matches[1]; const content = line.slice(prefixLength); const indentLevel = (prefixLength - 2) / indentSign.length; return { bullet, content, prefixLength, indentLevel, }; } parseList(editor: CodeMirror.Editor, cursor = editor.getCursor()): Root { const cursorLine = cursor.line; const cursorCh = cursor.ch; const line = editor.getLine(cursorLine); const indentSign = this.detectListIndentSign(editor, cursor); if (indentSign === null) { return null; } let listStartLine = cursorLine; const listStartCh = 0; while (listStartLine >= 1) { const line = editor.getLine(listStartLine - 1); if (!this.getListLineInfo(line, indentSign)) { break; } listStartLine--; } let listEndLine = cursorLine; let listEndCh = line.length; while (listEndLine < editor.lineCount()) { const line = editor.getLine(listEndLine + 1); if (!this.getListLineInfo(line, indentSign)) { break; } listEndCh = line.length; listEndLine++; } const root = new Root( indentSign, { line: listStartLine, ch: listStartCh }, { line: listEndLine, ch: listEndCh }, { line: cursorLine, ch: cursorCh } ); let currentLevel: IList = root; let lastList: IList = root; for (let l = listStartLine; l <= listEndLine; l++) { const line = editor.getLine(l); const { bullet, content, indentLevel } = this.getListLineInfo( line, indentSign ); const folded = (editor as any).isFolded({ line: l, ch: 0, }); if (indentLevel === currentLevel.getLevel() + 1) { currentLevel = lastList; } else if (indentLevel < currentLevel.getLevel()) { while (indentLevel < currentLevel.getLevel()) { currentLevel = currentLevel.getParent(); } } else if (indentLevel != currentLevel.getLevel()) { console.error(`Unable to parse list`); return null; } const list = new List(indentSign, bullet, content, folded); currentLevel.addAfterAll(list); lastList = list; } return root; } applyChanges(editor: CodeMirror.Editor, root: Root) { const oldString = editor.getRange( root.getListStartPosition(), root.getListEndPosition() ); const newString = root.print(); const fromLine = root.getListStartPosition().line; const toLine = root.getListEndPosition().line; for (let l = fromLine; l <= toLine; l++) { (editor as any).foldCode(l, null, "unfold"); } const diff = diffLines(oldString, newString); let l = root.getListStartPosition().line; for (const change of diff) { if (change.added) { editor.replaceRange(change.value, { line: l, ch: 0 }); l += change.count; } else if (change.removed) { const withNewline = /\n$/.test(change.value); const tillLine = withNewline ? l + change.count : l + change.count - 1; const tillCh = withNewline ? 0 : editor.getLine(tillLine).length; editor.replaceRange( "", { line: l, ch: 0 }, { line: tillLine, ch: tillCh } ); } else { l += change.count; } } const oldCursor = editor.getCursor(); const newCursor = root.getCursor(); if (oldCursor.line != newCursor.line || oldCursor.ch != newCursor.ch) { editor.setCursor(newCursor); } for (let l = fromLine; l <= toLine; l++) { const line = root.getListUnderLine(l); if (line && line.isFoldRoot()) { // TODO: why working only with -1? (editor as any).foldCode(l - 1); } } } detectListIndentSign(editor: CodeMirror.Editor, cursor: CodeMirror.Position) { const d = this.logger.bind("ObsidianOutlinerPlugin::detectListIndentSign"); const { useTab, tabSize } = this.obsidianUtils.getObsidianTabsSettigns(); const defaultIndentSign = useTab ? "\t" : new Array(tabSize).fill(" ").join(""); const line = editor.getLine(cursor.line); const withTabsRe = new RegExp(`^\t+[${bulletSign}] `); const withSpacesRe = new RegExp(`^[ ]+[${bulletSign}] `); const mayBeWithSpacesRe = new RegExp(`^[ ]*[${bulletSign}] `); if (withTabsRe.test(line)) { d("detected tab on current line"); return "\t"; } if (withSpacesRe.test(line)) { d("detected whitespaces on current line, trying to count"); const spacesA = line.length - line.trimLeft().length; let lineNo = cursor.line - 1; while (lineNo >= editor.firstLine()) { const line = editor.getLine(lineNo); if (!mayBeWithSpacesRe.test(line)) { break; } const spacesB = line.length - line.trimLeft().length; if (spacesB < spacesA) { const l = spacesA - spacesB; d(`detected ${l} whitespaces`); return new Array(l).fill(" ").join(""); } lineNo--; } d("unable to detect"); return null; } if (mayBeWithSpacesRe.test(line)) { d("detected nothing on current line, looking forward"); const spacesA = line.length - line.trimLeft().length; let lineNo = cursor.line + 1; while (lineNo <= editor.lastLine()) { const line = editor.getLine(lineNo); if (withTabsRe.test(line)) { d("detected tab"); return "\t"; } if (!mayBeWithSpacesRe.test(line)) { break; } const spacesB = line.length - line.trimLeft().length; if (spacesB > spacesA) { const l = spacesB - spacesA; d(`detected ${l} whitespaces`); return new Array(l).fill(" ").join(""); } lineNo++; } d(`detected nothing, using default useTab=${useTab} tabSize=${tabSize}`); return defaultIndentSign; } d("unable to detect"); return null; } isCursorInList(editor: CodeMirror.Editor) { return this.detectListIndentSign(editor, editor.getCursor()) !== null; } } <file_sep>/src/features/SelectionShouldIgnoreBulletsFeature.ts import { Plugin_2 } from "obsidian"; import { ListUtils } from "src/list_utils"; import { IFeature } from "../feature"; import { Settings } from "../settings"; export class SelectionShouldIgnoreBulletsFeature implements IFeature { constructor( private plugin: Plugin_2, private settings: Settings, private listsUtils: ListUtils ) {} async load() { this.plugin.registerCodeMirror((cm) => { cm.on("beforeSelectionChange", this.handleBeforeSelectionChange); }); } async unload() { this.plugin.app.workspace.iterateCodeMirrors((cm) => { cm.off("beforeSelectionChange", this.handleBeforeSelectionChange); }); } private handleBeforeSelectionChange = ( cm: CodeMirror.Editor, changeObj: CodeMirror.EditorSelectionChange ) => { if ( !this.settings.stickCursor || changeObj.origin !== "+move" || changeObj.ranges.length > 1 ) { return; } const range = changeObj.ranges[0]; if ( range.anchor.line !== range.head.line || range.anchor.ch === range.head.ch ) { return; } const root = this.listsUtils.parseList(cm); if (!root) { return; } const list = root.getListUnderCursor(); const listContentStartCh = list.getContentStartCh(); if (range.from().ch < listContentStartCh) { range.from().ch = listContentStartCh; changeObj.update([range]); } }; } <file_sep>/src/features/MoveItemsFeature.ts import { Plugin_2 } from "obsidian"; import { ListUtils } from "src/list_utils"; import { ObsidianUtils } from "src/obsidian_utils"; import { Root } from "src/root"; import { IFeature } from "../feature"; export class MoveItemsFeature implements IFeature { constructor( private plugin: Plugin_2, private obsidianUtils: ObsidianUtils, private listsUtils: ListUtils ) {} async load() { this.plugin.addCommand({ id: "move-list-item-up", name: "Move list and sublists up", callback: this.obsidianUtils.createCommandCallback( this.moveListElementUp.bind(this) ), hotkeys: [ { modifiers: ["Mod", "Shift"], key: "ArrowUp", }, ], }); this.plugin.addCommand({ id: "move-list-item-down", name: "Move list and sublists down", callback: this.obsidianUtils.createCommandCallback( this.moveListElementDown.bind(this) ), hotkeys: [ { modifiers: ["Mod", "Shift"], key: "ArrowDown", }, ], }); this.plugin.addCommand({ id: "indent-list", name: "Indent the list and sublists", callback: this.obsidianUtils.createCommandCallback( this.moveListElementRight.bind(this) ), hotkeys: [ { modifiers: [], key: "Tab", }, ], }); this.plugin.addCommand({ id: "outdent-list", name: "Outdent the list and sublists", callback: this.obsidianUtils.createCommandCallback( this.moveListElementLeft.bind(this) ), hotkeys: [ { modifiers: ["Shift"], key: "Tab", }, ], }); } async unload() {} private execute( editor: CodeMirror.Editor, cb: (root: Root) => boolean ): boolean { const root = this.listsUtils.parseList(editor, editor.getCursor()); if (!root) { return false; } const result = cb(root); if (result) { this.listsUtils.applyChanges(editor, root); } return result; } private moveListElementDown(editor: CodeMirror.Editor) { return this.execute(editor, (root) => root.moveDown()); } private moveListElementUp(editor: CodeMirror.Editor) { return this.execute(editor, (root) => root.moveUp()); } private moveListElementRight(editor: CodeMirror.Editor) { return this.execute(editor, (root) => root.moveRight()); } private moveListElementLeft(editor: CodeMirror.Editor) { return this.execute(editor, (root) => root.moveLeft()); } } <file_sep>/src/features/FoldFeature.ts import { Notice, Plugin_2 } from "obsidian"; import { ListUtils } from "src/list_utils"; import { ObsidianUtils } from "src/obsidian_utils"; import { IFeature } from "../feature"; export class FoldFeature implements IFeature { constructor( private plugin: Plugin_2, private obsidianUtils: ObsidianUtils, private listsUtils: ListUtils ) {} async load() { this.plugin.addCommand({ id: "fold", name: "Fold the list", callback: this.obsidianUtils.createCommandCallback(this.fold.bind(this)), hotkeys: [ { modifiers: ["Mod"], key: "ArrowUp", }, ], }); this.plugin.addCommand({ id: "unfold", name: "Unfold the list", callback: this.obsidianUtils.createCommandCallback( this.unfold.bind(this) ), hotkeys: [ { modifiers: ["Mod"], key: "ArrowDown", }, ], }); } async unload() {} private setFold(editor: CodeMirror.Editor, type: "fold" | "unfold") { if (!this.listsUtils.isCursorInList(editor)) { return false; } if (!this.obsidianUtils.getObsidianFoldSettigns().foldIndent) { new Notice( `Unable to ${type} because folding is disabled. Please enable "Fold indent" in Obsidian settings.`, 5000 ); return true; } (editor as any).foldCode(editor.getCursor(), null, type); return true; } private fold(editor: CodeMirror.Editor) { return this.setFold(editor, "fold"); } private unfold(editor: CodeMirror.Editor) { return this.setFold(editor, "unfold"); } } <file_sep>/src/features/DeleteShouldIgnoreBulletsFeature.ts import { Plugin_2 } from "obsidian"; import { EditorUtils } from "src/editor_utils"; import { IFeature } from "src/feature"; import { ListUtils } from "src/list_utils"; import { Root } from "src/root"; import { Settings } from "src/settings"; export class DeleteShouldIgnoreBulletsFeature implements IFeature { constructor( private plugin: Plugin_2, private settings: Settings, private editorUtils: EditorUtils, private listsUtils: ListUtils ) {} async load() { this.plugin.registerCodeMirror((cm) => { cm.on("beforeChange", this.handleBeforeChange); }); } async unload() { this.plugin.app.workspace.iterateCodeMirrors((cm) => { cm.off("beforeChange", this.handleBeforeChange); }); } private handleBeforeChange = ( cm: CodeMirror.Editor, changeObj: CodeMirror.EditorChangeCancellable ) => { if ( changeObj.origin !== "+delete" || !this.settings.stickCursor || !this.editorUtils.containsSingleCursor(cm) ) { return; } const root = this.listsUtils.parseList(cm); if (!root) { return; } const list = root.getListUnderCursor(); const listContentStartCh = list.getContentStartCh(); const listContentEndCh = list.getContentEndCh(); if (this.isBackspaceOnContentStart(changeObj, listContentStartCh)) { this.deleteItemAndMergeContentWithPreviousLine(cm, root, changeObj); } else if (this.isDeletionIncludesBullet(changeObj, listContentStartCh)) { this.limitDeleteRangeToContentRange(changeObj, listContentStartCh); } else if (this.isDeleteOnLineEnd(changeObj, listContentEndCh)) { this.deleteNextItemAndMergeContentWithCurrentLine(cm, root, changeObj); } }; private isDeleteOnLineEnd( changeObj: CodeMirror.EditorChangeCancellable, listContentEndCh: number ) { return ( changeObj.from.line + 1 === changeObj.to.line && changeObj.from.ch === listContentEndCh && changeObj.to.ch === 0 ); } private isDeletionIncludesBullet( changeObj: CodeMirror.EditorChangeCancellable, listContentStartCh: number ) { return ( changeObj.from.line === changeObj.to.line && changeObj.from.ch < listContentStartCh ); } private isBackspaceOnContentStart( changeObj: CodeMirror.EditorChangeCancellable, listContentStartCh: number ) { return ( changeObj.from.line === changeObj.to.line && changeObj.from.ch === listContentStartCh - 1 && changeObj.to.ch === listContentStartCh ); } private limitDeleteRangeToContentRange( changeObj: CodeMirror.EditorChangeCancellable, listContentStartCh: number ) { const from = { line: changeObj.from.line, ch: listContentStartCh, }; changeObj.update(from, changeObj.to, changeObj.text); } private deleteItemAndMergeContentWithPreviousLine( editor: CodeMirror.Editor, root: Root, changeObj: CodeMirror.EditorChangeCancellable ) { const list = root.getListUnderCursor(); if ( root.getListStartPosition().line === root.getLineNumberOf(list) && list.getChildren().length === 0 ) { return false; } const res = root.deleteAndMergeWithPrevious(); if (res) { changeObj.cancel(); this.listsUtils.applyChanges(editor, root); } return res; } private deleteNextItemAndMergeContentWithCurrentLine( editor: CodeMirror.Editor, root: Root, changeObj: CodeMirror.EditorChangeCancellable ) { const list = root.getListUnderCursor(); const nextLineNo = root.getCursor().line + 1; const nextList = root.getListUnderLine(nextLineNo); if (!nextList || root.getCursor().ch !== list.getContentEndCh()) { return false; } root.replaceCursor({ line: nextLineNo, ch: nextList.getContentStartCh(), }); const res = root.deleteAndMergeWithPrevious(); const reallyChanged = root.getCursor().line !== nextLineNo; if (reallyChanged) { changeObj.cancel(); this.listsUtils.applyChanges(editor, root); } return res; } } <file_sep>/src/root.ts export interface IList { getLevel(): number; getParent(): IList | null; addAfterAll(list: IList): void; } export class List implements IList { private indentSign: string; private bullet: string; private content: string; private folded: boolean; private children: List[]; private parent: List; constructor( indentSign: string, bullet: string, content: string, folded: boolean ) { this.indentSign = indentSign; this.bullet = bullet; this.content = content; this.folded = folded; this.children = []; this.parent = null; } isFolded() { return this.folded; } isFoldRoot() { let parent = this.getParent(); while (parent) { if (parent.isFolded()) { return false; } parent = parent.getParent(); } return this.isFolded(); } getChildren() { return this.children.concat(); } appendContent(content: string) { this.content += content; } getContent() { return this.content; } isEmpty() { return this.children.length === 0; } getContentStartCh() { const indentLength = (this.getLevel() - 1) * this.indentSign.length; return indentLength + 2; } getContentEndCh() { return this.getContentStartCh() + this.content.length; } getParent() { return this.parent; } getPrevSiblingOf(list: List) { const i = this.children.indexOf(list); return i > 0 ? this.children[i - 1] : null; } getNextSiblingOf(list: List) { const i = this.children.indexOf(list); return i >= 0 && i < this.children.length ? this.children[i + 1] : null; } getLevel() { let level = 0; let ref: List = this; while (ref.parent) { ref = ref.parent; level++; } return level; } addAfterAll(list: List) { this.children.push(list); list.parent = this; } addBeforeAll(list: List) { this.children.unshift(list); list.parent = this; } addBefore(before: List, list: List) { const i = this.children.indexOf(before); this.children.splice(i, 0, list); list.parent = this; } addAfter(before: List, list: List) { const i = this.children.indexOf(before); this.children.splice(i + 1, 0, list); list.parent = this; } removeChild(list: List) { const i = this.children.indexOf(list); this.children.splice(i, 1); list.parent = null; } print() { let res = this.getFullContent() + "\n"; for (const child of this.children) { res += child.print(); } return res; } private getFullContent() { return ( new Array(this.getLevel() - 1).fill(this.indentSign).join("") + this.bullet + " " + this.content ); } } export class Root implements IList { private indentSign: string; private rootList: List; private start: CodeMirror.Position; private end: CodeMirror.Position; private cursor: CodeMirror.Position; constructor( indentSign: string, start: CodeMirror.Position, end: CodeMirror.Position, cursor: CodeMirror.Position ) { this.indentSign = indentSign; this.start = start; this.end = end; this.cursor = cursor; this.rootList = new List("", "", "", false); } replaceCursor(cursor: CodeMirror.Position) { this.cursor = cursor; } getTotalLines() { return this.end.line - this.start.line + 1; } getChildren() { return this.rootList.getChildren(); } getIndentSign() { return this.indentSign; } getLevel() { return 0; } getParent(): List | null { return null; } addAfterAll(list: List) { this.rootList.addAfterAll(list); } getListStartPosition() { return this.start; } getListEndPosition() { return this.end; } getCursor() { return this.cursor; } getListUnderCursor(): List { return this.getListUnderLine(this.cursor.line); } print() { let res = ""; for (const child of this.rootList.getChildren()) { res += child.print(); } return res.replace(/\n$/, ""); } getLineNumberOf(list: List) { let result: number = null; let line: number = 0; const visitArr = (ll: List[]) => { for (const l of ll) { if (l === list) { result = line; } else { line++; visitArr(l.getChildren()); } if (result !== null) { return; } } }; visitArr(this.rootList.getChildren()); return result + this.start.line; } getListUnderLine(line: number) { if (line < this.start.line) { return; } let result: List = null; let index: number = 0; const visitArr = (ll: List[]) => { for (const l of ll) { if (index + this.start.line === line) { result = l; } else { index++; visitArr(l.getChildren()); } if (result !== null) { return; } } }; visitArr(this.rootList.getChildren()); return result; } moveUp() { const list = this.getListUnderCursor(); const parent = list.getParent(); const grandParent = parent.getParent(); const prev = parent.getPrevSiblingOf(list); if (!prev && grandParent) { const newParent = grandParent.getPrevSiblingOf(parent); if (newParent) { parent.removeChild(list); newParent.addAfterAll(list); this.cursor.line = this.getLineNumberOf(list); } } else if (prev) { parent.removeChild(list); parent.addBefore(prev, list); this.cursor.line = this.getLineNumberOf(list); } return true; } moveDown() { const list = this.getListUnderCursor(); const parent = list.getParent(); const grandParent = parent.getParent(); const next = parent.getNextSiblingOf(list); if (!next && grandParent) { const newParent = grandParent.getNextSiblingOf(parent); if (newParent) { parent.removeChild(list); newParent.addBeforeAll(list); this.cursor.line = this.getLineNumberOf(list); } } else if (next) { parent.removeChild(list); parent.addAfter(next, list); this.cursor.line = this.getLineNumberOf(list); } return true; } moveLeft() { const list = this.getListUnderCursor(); const parent = list.getParent(); const grandParent = parent.getParent(); if (!grandParent) { return true; } parent.removeChild(list); grandParent.addAfter(parent, list); this.cursor.line = this.getLineNumberOf(list); this.cursor.ch -= this.getIndentSign().length; return true; } moveRight() { const list = this.getListUnderCursor(); const parent = list.getParent(); const prev = parent.getPrevSiblingOf(list); if (!prev) { return true; } parent.removeChild(list); prev.addAfterAll(list); this.cursor.line = this.getLineNumberOf(list); this.cursor.ch += this.getIndentSign().length; return true; } deleteAndMergeWithPrevious() { const list = this.getListUnderCursor(); if (this.cursor.ch !== list.getContentStartCh()) { return false; } const prev = this.getListUnderLine(this.cursor.line - 1); if (!prev) { return true; } const bothAreEmpty = prev.isEmpty() && list.isEmpty(); const prevIsEmptyAndSameLevel = prev.isEmpty() && !list.isEmpty() && prev.getLevel() == list.getLevel(); const listIsEmptyAndPrevIsParent = list.isEmpty() && prev.getLevel() == list.getLevel() - 1; if (bothAreEmpty || prevIsEmptyAndSameLevel || listIsEmptyAndPrevIsParent) { const parent = list.getParent(); const prevEndCh = prev.getContentEndCh(); prev.appendContent(list.getContent()); parent.removeChild(list); for (const c of list.getChildren()) { list.removeChild(c); prev.addAfterAll(c); } this.cursor.line = this.getLineNumberOf(prev); this.cursor.ch = prevEndCh; } return true; } } <file_sep>/src/__tests__/list_utils.test.ts import { ListUtils } from "../list_utils"; interface EditorMockParams { text: string; cursor: { line: number; ch: number }; } function makeEditor(params: EditorMockParams) { let text = params.text; let cursor = { ...params.cursor }; const editor = { getCursor: () => cursor, getLine: (l: number) => text.split("\n")[l], lastLine: () => text.split("\n").length - 1, lineCount: () => text.split("\n").length, isFolded: (l: number) => false, }; return editor; } function makeListUtils() { const logger: any = { bind: jest.fn().mockReturnValue(jest.fn()), }; const obsidianUtils: any = { getObsidianTabsSettigns: jest .fn() .mockReturnValue({ useTab: true, tabSize: 4 }), }; const listUtils = new ListUtils(logger, obsidianUtils); return listUtils; } test("parse list with dash bullet", () => { const listUtils = makeListUtils(); const editor = makeEditor({ text: "- qwe", cursor: { line: 0, ch: 0 }, }); const list = listUtils.parseList(editor as any); expect(list).toBeDefined(); expect(list.print()).toBe(`- qwe`); }); test("parse list with asterisk bullet", () => { const listUtils = makeListUtils(); const editor = makeEditor({ text: "* qwe", cursor: { line: 0, ch: 0 }, }); const list = listUtils.parseList(editor as any); expect(list).toBeDefined(); expect(list.print()).toBe(`* qwe`); }); test("parse list with plus bullet", () => { const listUtils = makeListUtils(); const editor = makeEditor({ text: "+ qwe", cursor: { line: 0, ch: 0 }, }); const list = listUtils.parseList(editor as any); expect(list).toBeDefined(); expect(list.print()).toBe(`+ qwe`); }); <file_sep>/specs/SelectAllFeature.spec.ts /** * @jest-environment ./jest/obsidian-environment */ test("obsidian-outliner:select-all should select list item content", async () => { // arrange await applyState(["- one", "\t- two|"]); // act await executeCommandById("obsidian-outliner:select-all"); // assert await expect(await getCurrentState()).toEqualEditorState([ "- one", "\t- |two|", ]); }); test("obsidian-outliner:select-all should select list whole list after second invoke", async () => { // arrange await applyState(["a", "- one", "\t- two|", "b"]); // act await executeCommandById("obsidian-outliner:select-all"); await executeCommandById("obsidian-outliner:select-all"); // assert await expect(await getCurrentState()).toEqualEditorState([ "a", "|- one", "\t- two|", "b", ]); }); <file_sep>/specs/MoveCursorToPreviousUnfoldedLineFeature.spec.ts /** * @jest-environment ./jest/obsidian-environment */ test("cursor should be moved to previous line", async () => { // arrange await applyState(["- one", "- |two"]); // act await simulateKeydown("Left"); // assert await expect(await getCurrentState()).toEqualEditorState(["- one|", "- two"]); }); <file_sep>/src/editor_utils.ts export class EditorUtils { containsSingleCursor(editor: CodeMirror.Editor) { const selections = editor.listSelections(); return selections.length === 1 && this.rangeIsCursor(selections[0]); } rangeIsCursor(selection: CodeMirror.Range) { return ( selection.anchor.line === selection.head.line && selection.anchor.ch === selection.head.ch ); } } <file_sep>/src/features/MoveCursorToPreviousUnfoldedLineFeature.ts import { Plugin_2 } from "obsidian"; import { IFeature } from "src/feature"; import { ListUtils } from "src/list_utils"; import { Settings } from "src/settings"; export class MoveCursorToPreviousUnfoldedLineFeature implements IFeature { constructor( private plugin: Plugin_2, private settings: Settings, private listsUtils: ListUtils ) {} async load() { this.plugin.registerCodeMirror((cm) => { cm.on("beforeSelectionChange", this.handleBeforeSelectionChange); }); } async unload() { this.plugin.app.workspace.iterateCodeMirrors((cm) => { cm.off("beforeSelectionChange", this.handleBeforeSelectionChange); }); } private iterateWhileFolded( editor: CodeMirror.Editor, pos: CodeMirror.Position, inc: (pos: CodeMirror.Position) => void ) { let folded = false; do { inc(pos); folded = (editor as any).isFolded(pos); } while (folded); return pos; } private handleBeforeSelectionChange = ( cm: CodeMirror.Editor, changeObj: CodeMirror.EditorSelectionChange ) => { if ( !this.settings.stickCursor || changeObj.origin !== "+move" || changeObj.ranges.length > 1 ) { return; } const range = changeObj.ranges[0]; const cursor = cm.getCursor(); if ( range.anchor.line !== range.head.line || range.anchor.ch !== range.head.ch ) { return; } if (cursor.line <= 0 || cursor.line !== range.anchor.line) { return; } const root = this.listsUtils.parseList(cm); if (!root) { return; } const list = root.getListUnderCursor(); const listContentStartCh = list.getContentStartCh(); if ( cursor.ch === listContentStartCh && range.anchor.ch === listContentStartCh - 1 ) { const newCursor = this.iterateWhileFolded( cm, { line: cursor.line, ch: 0, }, (pos) => { pos.line--; pos.ch = cm.getLine(pos.line).length - 1; } ); newCursor.ch++; range.anchor.line = newCursor.line; range.anchor.ch = newCursor.ch; range.head.line = newCursor.line; range.head.ch = newCursor.ch; changeObj.update([range]); } }; } <file_sep>/src/index.ts import { Plugin } from "obsidian"; import { ObsidianOutlinerPluginSettingTab, Settings } from "./settings"; import { IFeature } from "./feature"; import { ObsidianUtils } from "./obsidian_utils"; import { EditorUtils } from "./editor_utils"; import { ListUtils } from "./list_utils"; import { Logger } from "./logger"; import { ListsStylesFeature } from "./features/ListsStylesFeature"; import { EnterOutdentIfLineIsEmptyFeature } from "./features/EnterOutdentIfLineIsEmptyFeature"; import { EnterShouldCreateNewlineOnChildLevelFeature } from "./features/EnterShouldCreateNewlineOnChildLevelFeature"; import { MoveCursorToPreviousUnfoldedLineFeature } from "./features/MoveCursorToPreviousUnfoldedLineFeature"; import { EnsureCursorInListContentFeature } from "./features/EnsureCursorInListContentFeature"; import { DeleteShouldIgnoreBulletsFeature } from "./features/DeleteShouldIgnoreBulletsFeature"; import { SelectionShouldIgnoreBulletsFeature } from "./features/SelectionShouldIgnoreBulletsFeature"; import { ZoomFeature } from "./features/ZoomFeature"; import { FoldFeature } from "./features/FoldFeature"; import { SelectAllFeature } from "./features/SelectAllFeature"; import { MoveItemsFeature } from "./features/MoveItemsFeature"; export default class ObsidianOutlinerPlugin extends Plugin { private features: IFeature[]; private settings: Settings; private logger: Logger; private obsidianUtils: ObsidianUtils; private editorUtils: EditorUtils; private listsUtils: ListUtils; async onload() { console.log(`Loading obsidian-outliner`); this.settings = new Settings(this); await this.settings.load(); this.logger = new Logger(this.settings); this.obsidianUtils = new ObsidianUtils(this.app); this.editorUtils = new EditorUtils(); this.listsUtils = new ListUtils(this.logger, this.obsidianUtils); this.addSettingTab( new ObsidianOutlinerPluginSettingTab(this.app, this, this.settings) ); this.features = [ new ListsStylesFeature(this, this.settings, this.obsidianUtils), new EnterOutdentIfLineIsEmptyFeature( this, this.settings, this.editorUtils, this.listsUtils ), new EnterShouldCreateNewlineOnChildLevelFeature( this, this.settings, this.listsUtils ), new EnsureCursorInListContentFeature( this, this.settings, this.editorUtils, this.listsUtils ), new MoveCursorToPreviousUnfoldedLineFeature( this, this.settings, this.listsUtils ), new DeleteShouldIgnoreBulletsFeature( this, this.settings, this.editorUtils, this.listsUtils ), new SelectionShouldIgnoreBulletsFeature( this, this.settings, this.listsUtils ), new ZoomFeature(this, this.settings, this.obsidianUtils, this.listsUtils), new FoldFeature(this, this.obsidianUtils, this.listsUtils), new SelectAllFeature(this, this.obsidianUtils, this.listsUtils), new MoveItemsFeature(this, this.obsidianUtils, this.listsUtils), ]; for (const feature of this.features) { await feature.load(); } } async onunload() { console.log(`Unloading obsidian-outliner`); for (const feature of this.features) { await feature.unload(); } } } <file_sep>/src/features/EnsureCursorInListContentFeature.ts import { Plugin_2 } from "obsidian"; import { EditorUtils } from "src/editor_utils"; import { IFeature } from "src/feature"; import { ListUtils } from "src/list_utils"; import { Settings } from "src/settings"; export class EnsureCursorInListContentFeature implements IFeature { constructor( private plugin: Plugin_2, private settings: Settings, private editorUtils: EditorUtils, private listsUtils: ListUtils ) {} async load() { this.plugin.registerCodeMirror((cm) => { cm.on("cursorActivity", this.handleCursorActivity); }); } async unload() { this.plugin.app.workspace.iterateCodeMirrors((cm) => { cm.off("cursorActivity", this.handleCursorActivity); }); } private ensureCursorInListContent(editor: CodeMirror.Editor) { const cursor = editor.getCursor(); const indentSign = this.listsUtils.detectListIndentSign(editor, cursor); if (indentSign === null) { return; } const line = editor.getLine(cursor.line); const linePrefix = this.listsUtils.getListLineInfo(line, indentSign) .prefixLength; if (cursor.ch < linePrefix) { cursor.ch = linePrefix; editor.setCursor(cursor); } } private ensureCursorIsInUnfoldedLine(editor: CodeMirror.Editor) { const cursor = editor.getCursor(); const mark = editor.findMarksAt(cursor).find((m) => (m as any).__isFold); if (!mark) { return; } const firstFoldingLine: CodeMirror.LineHandle = (mark as any).lines[0]; if (!firstFoldingLine) { return; } const lineNo = editor.getLineNumber(firstFoldingLine); if (lineNo !== cursor.line) { editor.setCursor({ line: lineNo, ch: editor.getLine(lineNo).length, }); } } private handleCursorActivity = (cm: CodeMirror.Editor) => { if ( this.settings.stickCursor && this.editorUtils.containsSingleCursor(cm) && this.listsUtils.isCursorInList(cm) ) { this.ensureCursorIsInUnfoldedLine(cm); this.ensureCursorInListContent(cm); } }; } <file_sep>/src/features/ZoomFeature.ts import { Plugin_2 } from "obsidian"; import { ListUtils } from "src/list_utils"; import { ObsidianUtils } from "src/obsidian_utils"; import { Settings } from "src/settings"; import { IFeature } from "../feature"; class ZoomState { constructor(public line: CodeMirror.LineHandle, public header: HTMLElement) {} } export class ZoomFeature implements IFeature { private zoomStates: WeakMap<CodeMirror.Editor, ZoomState> = new WeakMap(); constructor( private plugin: Plugin_2, private settings: Settings, private obsidianUtils: ObsidianUtils, private listsUtils: ListUtils ) { this.zoomStates = new WeakMap(); } async load() { this.plugin.registerCodeMirror((cm) => { cm.on("beforeChange", this.handleBeforeChange); cm.on("change", this.handleChange); cm.on("beforeSelectionChange", this.handleBeforeSelectionChange); }); this.plugin.registerDomEvent(window, "click", this.handleClick); this.plugin.addCommand({ id: "zoom-in", name: "Zoom in to the current list item", callback: this.obsidianUtils.createCommandCallback( this.zoomIn.bind(this) ), hotkeys: [ { modifiers: ["Mod"], key: ".", }, ], }); this.plugin.addCommand({ id: "zoom-out", name: "Zoom out the entire document", callback: this.obsidianUtils.createCommandCallback( this.zoomOut.bind(this) ), hotkeys: [ { modifiers: ["Mod", "Shift"], key: ".", }, ], }); } async unload() { this.plugin.app.workspace.iterateCodeMirrors((cm) => { cm.off("beforeSelectionChange", this.handleBeforeSelectionChange); cm.off("change", this.handleChange); cm.off("beforeChange", this.handleBeforeChange); }); } private handleClick = (e: MouseEvent) => { const target = e.target as HTMLElement | null; if ( !target || !this.settings.zoomOnClick || !target.classList.contains("cm-formatting-list-ul") ) { return; } let wrap = target; while (wrap) { if (wrap.classList.contains("CodeMirror-wrap")) { break; } wrap = wrap.parentElement; } if (!wrap) { return; } let foundEditor: CodeMirror.Editor | null = null; this.plugin.app.workspace.iterateCodeMirrors((cm) => { if (foundEditor) { return; } if (cm.getWrapperElement() === wrap) { foundEditor = cm; } }); if (!foundEditor) { return; } const pos = foundEditor.coordsChar({ left: e.x, top: e.y, }); if (!pos) { return; } e.preventDefault(); e.stopPropagation(); this.zoomIn(foundEditor, pos); foundEditor.setCursor({ line: pos.line, ch: foundEditor.getLine(pos.line).length, }); }; private handleBeforeChange = ( cm: CodeMirror.Editor, changeObj: CodeMirror.EditorChangeCancellable ) => { const zoomState = this.zoomStates.get(cm); if ( !zoomState || changeObj.origin !== "setValue" || changeObj.from.line !== 0 || changeObj.from.ch !== 0 ) { return; } const tillLine = cm.lastLine(); const tillCh = cm.getLine(tillLine).length; if (changeObj.to.line !== tillLine || changeObj.to.ch !== tillCh) { return; } this.zoomOut(cm); }; private handleChange = ( cm: CodeMirror.Editor, changeObj: CodeMirror.EditorChangeCancellable ) => { const zoomState = this.zoomStates.get(cm); if (!zoomState || changeObj.origin !== "setValue") { return; } this.zoomIn(cm, { line: cm.getLineNumber(zoomState.line), ch: 0, }); }; private handleBeforeSelectionChange = ( cm: CodeMirror.Editor, changeObj: CodeMirror.EditorSelectionChange ) => { if (!this.zoomStates.has(cm)) { return; } let visibleFrom: CodeMirror.Position | null = null; let visibleTill: CodeMirror.Position | null = null; for (let i = cm.firstLine(); i <= cm.lastLine(); i++) { const wrapClass = cm.lineInfo(i).wrapClass || ""; const isHidden = wrapClass.includes("outliner-plugin-hidden-row"); if (visibleFrom === null && !isHidden) { visibleFrom = { line: i, ch: 0 }; } if (visibleFrom !== null && visibleTill !== null && isHidden) { break; } if (visibleFrom !== null) { visibleTill = { line: i, ch: cm.getLine(i).length }; } } let changed = false; for (const range of changeObj.ranges) { if (range.anchor.line < visibleFrom.line) { changed = true; range.anchor.line = visibleFrom.line; range.anchor.ch = visibleFrom.ch; } if (range.anchor.line > visibleTill.line) { changed = true; range.anchor.line = visibleTill.line; range.anchor.ch = visibleTill.ch; } if (range.head.line < visibleFrom.line) { changed = true; range.head.line = visibleFrom.line; range.head.ch = visibleFrom.ch; } if (range.head.line > visibleTill.line) { changed = true; range.head.line = visibleTill.line; range.head.ch = visibleTill.ch; } } if (changed) { changeObj.update(changeObj.ranges); } }; private zoomOut(editor: CodeMirror.Editor) { const zoomState = this.zoomStates.get(editor); if (!zoomState) { return false; } for (let i = editor.firstLine(), l = editor.lastLine(); i <= l; i++) { editor.removeLineClass(i, "wrap", "outliner-plugin-hidden-row"); } zoomState.header.parentElement.removeChild(zoomState.header); this.zoomStates.delete(editor); return true; } private zoomIn( editor: CodeMirror.Editor, cursor: CodeMirror.Position = editor.getCursor() ) { const lineNo = cursor.line; const root = this.listsUtils.parseList(editor, cursor); if (!root) { return false; } this.zoomOut(editor); const { indentLevel } = this.listsUtils.getListLineInfo( editor.getLine(lineNo), root.getIndentSign() ); let after = false; for (let i = editor.firstLine(), l = editor.lastLine(); i <= l; i++) { if (i < lineNo) { editor.addLineClass(i, "wrap", "outliner-plugin-hidden-row"); } else if (i > lineNo && !after) { const afterLineInfo = this.listsUtils.getListLineInfo( editor.getLine(i), root.getIndentSign() ); after = !afterLineInfo || afterLineInfo.indentLevel <= indentLevel; } if (after) { editor.addLineClass(i, "wrap", "outliner-plugin-hidden-row"); } } const createSeparator = () => { const span = document.createElement("span"); span.textContent = " > "; return span; }; const createTitle = (content: string, cb: () => void) => { const a = document.createElement("a"); a.className = "outliner-plugin-zoom-title"; if (content) { a.textContent = content; } else { a.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; } a.onclick = (e) => { e.preventDefault(); cb(); }; return a; }; const createHeader = () => { const div = document.createElement("div"); div.className = "outliner-plugin-zoom-header"; let list = root.getListUnderLine(lineNo).getParent(); while (list && list.getParent()) { const lineNo = root.getLineNumberOf(list); div.prepend( createTitle(list.getContent(), () => this.zoomIn(editor, { line: lineNo, ch: 0 }) ) ); div.prepend(createSeparator()); list = list.getParent(); } div.prepend( createTitle(this.obsidianUtils.getActiveLeafDisplayText(), () => this.zoomOut(editor) ) ); return div; }; const zoomHeader = createHeader(); editor.getWrapperElement().prepend(zoomHeader); this.zoomStates.set( editor, new ZoomState(editor.getLineHandle(lineNo), zoomHeader) ); return true; } } <file_sep>/src/features/ListsStylesFeature.ts import { Settings } from "../settings"; import { Plugin_2 } from "obsidian"; import { IFeature } from "../feature"; import { ObsidianUtils } from "../obsidian_utils"; const text = (size: number) => `Outliner styles doesn't work with ${size}-spaces-tabs. Please check your Obsidian settings.`; export class ListsStylesFeature implements IFeature { private statusBarText: HTMLElement; private interval: number; constructor( private plugin: Plugin_2, private settings: Settings, private obsidianUtils: ObsidianUtils ) {} async load() { if (this.settings.styleLists) { this.addListsStyles(); } if (this.settings.zoomOnClick) { this.addZoomStyles(); } this.settings.onChange("styleLists", this.onStyleListsSettingChange); this.settings.onChange("zoomOnClick", this.onZoomOnClickSettingChange); this.addStatusBarText(); this.startStatusBarInterval(); } async unload() { clearInterval(this.interval); if (this.statusBarText.parentElement) { this.statusBarText.parentElement.removeChild(this.statusBarText); } this.settings.removeCallback( "zoomOnClick", this.onZoomOnClickSettingChange ); this.settings.removeCallback("styleLists", this.onStyleListsSettingChange); this.removeListsStyles(); } private startStatusBarInterval() { let visible: number | null = null; this.interval = window.setInterval(() => { const { useTab, tabSize } = this.obsidianUtils.getObsidianTabsSettigns(); const shouldBeVisible = this.settings.styleLists && useTab && tabSize !== 4; if (shouldBeVisible && visible !== tabSize) { this.statusBarText.style.display = "block"; this.statusBarText.setText(text(tabSize)); visible = tabSize; } else if (!shouldBeVisible && visible !== null) { this.statusBarText.style.display = "none"; visible = null; } }, 1000); } private onStyleListsSettingChange = (styleLists: boolean) => { if (styleLists) { this.addListsStyles(); } else { this.removeListsStyles(); } }; private onZoomOnClickSettingChange = (zoomOnClick: boolean) => { if (zoomOnClick) { this.addZoomStyles(); } else { this.removeZoomStyles(); } }; private addStatusBarText() { this.statusBarText = this.plugin.addStatusBarItem(); this.statusBarText.style.color = "red"; this.statusBarText.style.display = "none"; } private addListsStyles() { document.body.classList.add("outliner-plugin-bls"); } private removeListsStyles() { document.body.classList.remove("outliner-plugin-bls"); } private addZoomStyles() { document.body.classList.add("outliner-plugin-bls-zoom"); } private removeZoomStyles() { document.body.classList.remove("outliner-plugin-bls-zoom"); } } <file_sep>/specs/EnterShouldCreateNewlineOnChildLevelFeature.spec.ts /** * @jest-environment ./jest/obsidian-environment */ test("enter should create newline on the same level", async () => { // arrange await applyState(["- one", "\t- two|"]); // act await simulateKeydown("Enter"); // assert await expect(await getCurrentState()).toEqualEditorState([ "- one", "\t- two", "\t- |", ]); }); test("enter should create newline on the child level if child exists", async () => { // arrange await applyState(["- one", "\t- two|", "\t\t- three"]); // act await simulateKeydown("Enter"); // assert await expect(await getCurrentState()).toEqualEditorState([ "- one", "\t- two", "\t\t- |", "\t\t- three", ]); }); <file_sep>/specs/EnterOutdentIfLineIsEmptyFeature.spec.ts /** * @jest-environment ./jest/obsidian-environment */ test("enter should outdent line if line is empty", async () => { // arrange await applyState(["- one", "\t- two", "\t\t- |"]); // act await simulateKeydown("Enter"); // assert await expect(await getCurrentState()).toEqualEditorState([ "- one", "\t- two", "\t- |", ]); }); test("enter should delete list item if it's last item and it's on the top level", async () => { // arrange await applyState(["- one", "- |"]); // act await simulateKeydown("Enter"); // assert await expect(await getCurrentState()).toEqualEditorState(["- one", "", "|"]); }); <file_sep>/specs/DeleteShouldIgnoreBulletsFeature.spec.ts /** * @jest-environment ./jest/obsidian-environment */ test("backspace should work as regular if it's last empty line", async () => { // arrange await applyState(["- |"]); // act await simulateKeydown("Backspace"); // assert await expect(await getCurrentState()).toEqualEditorState(["-|"]); }); test("backspace should work as regular if it's first line without children", async () => { // arrange await applyState(["- |one", "- two"]); // act await simulateKeydown("Backspace"); // assert await expect(await getCurrentState()).toEqualEditorState(["-|one", "- two"]); }); test("backspace should do nothing if it's first line but with children", async () => { // arrange await applyState(["- |one", "\t- two"]); // act await simulateKeydown("Backspace"); // assert await expect(await getCurrentState()).toEqualEditorState([ "- |one", "\t- two", ]); }); test("backspace should remove symbol if it isn't empty line", async () => { // arrange await applyState(["- qwe|"]); // act await simulateKeydown("Backspace"); // assert await expect(await getCurrentState()).toEqualEditorState(["- qw|"]); }); test("backspace should remove list item if it's empty", async () => { // arrange await applyState(["- one", "- |"]); // act await simulateKeydown("Backspace"); // assert await expect(await getCurrentState()).toEqualEditorState(["- one|"]); }); test("cmd+backspace should remove content only", async () => { // arrange await applyState(["- one", "- two|"]); // act await simulateKeydown("Cmd-Backspace"); await simulateKeydown("Cmd-Backspace"); // assert await expect(await getCurrentState()).toEqualEditorState(["- one", "- |"]); }); test("delete should remove next item if cursor is on the end", async () => { // arrange await applyState(["- qwe|", "\t- ee"]); // act await simulateKeydown("Delete"); // assert await expect(await getCurrentState()).toEqualEditorState(["- qwe|ee"]); }); <file_sep>/src/features/EnterShouldCreateNewlineOnChildLevelFeature.ts import { Plugin_2 } from "obsidian"; import { IFeature } from "../feature"; import { ListUtils } from "../list_utils"; import { Settings } from "../settings"; export class EnterShouldCreateNewlineOnChildLevelFeature implements IFeature { constructor( private plugin: Plugin_2, private settings: Settings, private listUtils: ListUtils ) {} async load() { this.plugin.registerCodeMirror((cm) => { cm.on("beforeChange", this.onBeforeChange); }); } async unload() { this.plugin.app.workspace.iterateCodeMirrors((cm) => { cm.off("beforeChange", this.onBeforeChange); }); } private onBeforeChange = ( cm: CodeMirror.Editor, changeObj: CodeMirror.EditorChangeCancellable ) => { if (!this.settings.betterEnter) { return; } const { listUtils } = this; const currentLine = cm.getLine(changeObj.from.line); const nextLine = cm.getLine(changeObj.from.line + 1); if (!currentLine || !nextLine) { return; } const indentSign = listUtils.detectListIndentSign(cm, changeObj.from); if (indentSign === null) { return; } const currentLineInfo = listUtils.getListLineInfo(currentLine, indentSign); const nextLineInfo = listUtils.getListLineInfo(nextLine, indentSign); if (!currentLineInfo || !nextLineInfo) { return; } const changeIsNewline = changeObj.text.length === 2 && changeObj.text[0] === "" && !!listUtils.getListLineInfo(changeObj.text[1], indentSign); const nexlineLevelIsBigger = currentLineInfo.indentLevel + 1 == nextLineInfo.indentLevel; const nextLineIsEmpty = cm.getRange(changeObj.from, { line: changeObj.from.line, ch: changeObj.from.ch + 1, }).length === 0; if (changeIsNewline && nexlineLevelIsBigger && nextLineIsEmpty) { changeObj.text[1] = indentSign + changeObj.text[1]; changeObj.update(changeObj.from, changeObj.to, changeObj.text); } }; } <file_sep>/specs/MoveItemsFeature.spec.ts /** * @jest-environment ./jest/obsidian-environment */ test("obsidian-outliner:outdent-list should outdent line", async () => { // arrange await applyState(["- qwe", "\t- qwe|"]); // act await executeCommandById("obsidian-outliner:outdent-list"); // assert await expect(await getCurrentState()).toEqualEditorState(["- qwe", "- qwe|"]); }); test("obsidian-outliner:outdent-list should outdent children", async () => { // arrange await applyState(["- qwe", "\t- qwe|", "\t\t- qwe"]); // act await executeCommandById("obsidian-outliner:outdent-list"); // assert await expect(await getCurrentState()).toEqualEditorState([ "- qwe", "- qwe|", "\t- qwe", ]); }); test("obsidian-outliner:indent-list should indent line", async () => { // arrange await applyState(["- qwe", "- qwe|"]); // act await executeCommandById("obsidian-outliner:indent-list"); // assert await expect(await getCurrentState()).toEqualEditorState([ "- qwe", "\t- qwe|", ]); }); test("obsidian-outliner:indent-list should indent children", async () => { // arrange await applyState(["- qwe", "- qwe|", "\t- qwe"]); // act await executeCommandById("obsidian-outliner:indent-list"); // assert await expect(await getCurrentState()).toEqualEditorState([ "- qwe", "\t- qwe|", "\t\t- qwe", ]); }); test("obsidian-outliner:indent-list should not indent line if it's no parent", async () => { // arrange await applyState(["- qwe", "\t- qwe|"]); // act await executeCommandById("obsidian-outliner:indent-list"); // assert await expect(await getCurrentState()).toEqualEditorState([ "- qwe", "\t- qwe|", ]); }); test("obsidian-outliner:indent-list should keep cursor at the same text position", async () => { // arrange await applyState(["- qwe", " - qwe", " - q|we"]); // act await executeCommandById("obsidian-outliner:indent-list"); // assert await expect(await getCurrentState()).toEqualEditorState([ "- qwe", " - qwe", " - q|we", ]); }); test("obsidian-outliner:move-list-item-down should move line down", async () => { // arrange await applyState(["- one|", "- two"]); // act await executeCommandById("obsidian-outliner:move-list-item-down"); // assert await expect(await getCurrentState()).toEqualEditorState(["- two", "- one|"]); }); test("obsidian-outliner:move-list-item-down should move children down", async () => { // arrange await applyState(["- one|", "\t- one one", "- two"]); // act await executeCommandById("obsidian-outliner:move-list-item-down"); // assert await expect(await getCurrentState()).toEqualEditorState([ "- two", "- one|", "\t- one one", ]); }); test("obsidian-outliner:move-list-item-up should move line up", async () => { // arrange await applyState(["- one", "- two|"]); // act await executeCommandById("obsidian-outliner:move-list-item-up"); // assert await expect(await getCurrentState()).toEqualEditorState(["- two|", "- one"]); }); test("obsidian-outliner:move-list-item-up should move children up", async () => { // arrange await applyState(["- two", "- one|", "\t- one one"]); // act await executeCommandById("obsidian-outliner:move-list-item-up"); // assert await expect(await getCurrentState()).toEqualEditorState([ "- one|", "\t- one one", "- two", ]); }); <file_sep>/src/logger.ts import { Settings } from "./settings"; export class Logger { constructor(private settings: Settings) {} log(method: string, ...args: any[]) { if (!this.settings.debug) { return; } console.info(method, ...args); } bind(method: string) { return (...args: any[]) => this.log(method, ...args); } } <file_sep>/src/features/EnterOutdentIfLineIsEmptyFeature.ts import { Plugin_2 } from "obsidian"; import { EditorUtils } from "../editor_utils"; import { IFeature } from "../feature"; import { ListUtils } from "../list_utils"; import { Settings } from "../settings"; function isEnter(e: KeyboardEvent) { return ( e.code === "Enter" && e.shiftKey === false && e.metaKey === false && e.altKey === false && e.ctrlKey === false ); } export class EnterOutdentIfLineIsEmptyFeature implements IFeature { constructor( private plugin: Plugin_2, private settings: Settings, private editorUtils: EditorUtils, private listUtils: ListUtils ) {} async load() { this.plugin.registerCodeMirror((cm) => { cm.on("keydown", this.onKeyDown); }); } async unload() { this.plugin.app.workspace.iterateCodeMirrors((cm) => { cm.off("keydown", this.onKeyDown); }); } private outdentIfLineIsEmpty(editor: CodeMirror.Editor) { if (!this.editorUtils.containsSingleCursor(editor)) { return false; } const root = this.listUtils.parseList(editor); if (!root) { return false; } const list = root.getListUnderCursor(); if (list.getContent().length > 0 || list.getLevel() === 1) { return false; } root.moveLeft(); this.listUtils.applyChanges(editor, root); return true; } private onKeyDown = (cm: CodeMirror.Editor, e: KeyboardEvent) => { if (!this.settings.betterEnter || !isEnter(e)) { return; } const worked = this.outdentIfLineIsEmpty(cm); if (worked) { e.preventDefault(); e.stopPropagation(); } }; } <file_sep>/src/features/SelectAllFeature.ts import { Plugin_2 } from "obsidian"; import { ListUtils } from "src/list_utils"; import { ObsidianUtils } from "src/obsidian_utils"; import { IFeature } from "../feature"; export class SelectAllFeature implements IFeature { constructor( private plugin: Plugin_2, private obsidianUtils: ObsidianUtils, private listsUtils: ListUtils ) {} async load() { this.plugin.addCommand({ id: "select-all", name: "Select a list item or the entire list", callback: this.obsidianUtils.createCommandCallback( this.selectAll.bind(this) ), hotkeys: [ { modifiers: ["Mod"], key: "a", }, ], }); } async unload() {} private selectAll(editor: CodeMirror.Editor) { const selections = editor.listSelections(); if (selections.length !== 1) { return false; } const selection = selections[0]; if (selection.anchor.line !== selection.head.line) { return false; } const root = this.listsUtils.parseList(editor, selection.anchor); if (!root) { return false; } const list = root.getListUnderCursor(); const startCh = list.getContentStartCh(); const endCh = list.getContentEndCh(); if (selection.from().ch === startCh && selection.to().ch === endCh) { // select all list editor.setSelection( root.getListStartPosition(), root.getListEndPosition() ); } else { // select all line editor.setSelection( { line: selection.anchor.line, ch: startCh, }, { line: selection.anchor.line, ch: endCh, } ); } return true; } }
7ba685e29e9b9f5556bfe025f9245b03d9c4fccc
[ "TypeScript" ]
24
TypeScript
pret-a-porter/obsidian-outliner
9e74b9cf1b299fc1413ac50e38f81df9d696cf5e
2494f78110469d687a873e45ecc1efc209c13f06
refs/heads/master
<repo_name>Shamimasharmin/Face-detection-and-identification-with-mysql-database-in-real-time<file_sep>/datasetgenerating.py import cv2 import sqlite3 cam = cv2.VideoCapture(0) faceDetect=cv2.CascadeClassifier('haarcascade_frontalface_default.xml'); def insertOrUpdate(Id,Name): conn=sqlite3.connect("FaceBase.db") cmd="SELECT * FROM People" cursor=conn.execute(cmd) isRecordExist=0 for row in cursor: isRecordExist=1 if(isRecordExist==1): cmd="UPDATE People SET Name= "+str(Name)+" WHERE ID = "+str(Id) else: cmd="INSERT INTO PEOPLE(ID,Name) Values("+str(Id)+","+str(Name)+")" conn.execute(cmd) conn.commit() conn.close() id=input('Enter user id : ') name=input('Enter your name : ') insertOrUpdate(id,name) sampleNum=0 while(True): ret, frame = cam.read(); gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces=faceDetect.detectMultiScale(gray,1.3,5); for(x,y,w,h) in faces: sampleNum=sampleNum+1; cv2.imwrite("dataSet/user."+id+'.'+ str(sampleNum) +".jpg",frame[y:y+h,x:x+w]) cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2) cv2.imshow('frame', frame) #imgshow,it is declare as frame that's why it doesn't shows gray color if cv2.waitKey(20) & 0xFF == ord('q'):#to close the frame just press q break # When everything done, release the capture cam.release() cv2.destroyAllWindows() <file_sep>/README.md # Face-detection-and-identification-with-mysql-database-in-real-time Face Detection and identification by using mysql database and implementing opencv, python: Face Detection: Face detection is just pulling out faces in an image or a video. Face Identification: Face identification is identify faces in a video or image including the person's name. This takes a little bit extra training, that we have done in here. The training portion and the identification of faces can be absolutely advanced. Advanced means using deep learning libraries such as tensorflow or PI torch. Opencv has some built-in features to make those things(advanced) easier. To do this project here used: numpy==1.15.4, opencv==3.4.3.18, pillow=5.3.0, virualenv==16.1.0, python=3.6.7, SQLiteStudio. ✔ Step 1: Download SQLiteStudio SQLiteStudio needs to be downloaded that suits your operating system from this link sqlitestudio.pl/index.rvt?act=download and install it. After insatalling open it and create a database named as FaceBase.db in a directory. In this directoery other file for this project will be here. In this db file now create a table which is here named as "People". Now, in this People table add some colum as per ur wish. I created Id, Name, Age, Female, Criminal Records by supposing it is a police record. ✔ Step 2: Copy haarcascade_frontalface_default.xml file Copy this file from cv2 or download it from this repository and keep this file in the project directory. ✔ Step 3: Create two directories dataSet and recognizer Create new two directories in the project directory. I named one as dataSet and other one named as recognizer. In the dataSet directory pictures of the person will be saved automatically and in the recognizer directory a yml file will be saved automatically when the pictures will be trained. ✔ Step 4: Create a new py file for gathering data(file named as datasetgenerating.py) This py file has been created in the same project directory. In this datasetgenerating.py file user id and user name has been asked. So, when running this datasetgenerating.py file enter user id and enter user name. The user name needs to be entered in double quotation. Than the webcamera will open and detect a face and take picture of the face and will save the pictures of faces in dataSet directory. ✔ Step 5: Close the webcam by hit on q button of the keyboard When the webcam will open and take pictures of face automatically than need to close the webcam by hitting q button not the ✖ button. By hitting ✖ button of the webcam, the webcam will not close. Than look at the FaceBase.db file in the people table and refresh it and will see the name and the id which has been given by the user. ✔ Step 6: Create another py file for train those pictures of faces(file named as facetrain.py) This py file will train all the pictures of faces which are in the dataSet directory. After running facetrain.py file trainingData.yml will be automatically saved in recognizer directory. This will help to recognize a person. ✔ Step 7: Create one new another py file(file named as sqldatasetcreator.py) In this file the person id and name has been declared in the if else loop. The same id and name has to be given which has been given as user input while running datasetgenerating.py file. Otherwise result will not be proper. Now, after running sqldatasetcreator.py file will see the name of the person and there also need to do some other works that is: in the FaceBase.db file's people table the other column need to be update. In the people table age, gender and criminal records will be written and save it. Than we can see in the webcam the person's name, age, gender, criminal records. We can also add another column in the people table if we want. <file_sep>/sqldatasetcreator.py import numpy as np import cv2,os from PIL import Image import pickle import sqlite3 recognizer = cv2.face.LBPHFaceRecognizer_create(); #create a recognizer, LBPH is a face recognition algorithm.Local Binary Patterns Histograms recognizer.read("recognizer\\trainingData.yml") faceDetect=cv2.CascadeClassifier('haarcascade_frontalface_default.xml'); path = 'dataSet' def getProfile(id): conn = sqlite3.connect("FaceBase.db") cmd="SELECT * FROM People" cursor=conn.execute(cmd) profile=None for row in cursor: profile=row conn.close() return profile cam = cv2.VideoCapture(0); font = cv2.FONT_HERSHEY_SIMPLEX #5=font size fontscale = 1 fontcolor = (255,255,255) stroke = 2 profiles={} while(True): ret, frame = cam.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces=faceDetect.detectMultiScale(gray,1.3,5); for(x,y,w,h) in faces: id, conf = recognizer.predict(gray[y:y+h,x:x+w]) cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2) if(conf<50): if(id==1): id="Munmun" elif(id==2): id="Mysha" else: id="Unknown" profile=getProfile(id) if(profile!=None): cv2.putText(frame,"Name:" +str(profile[1]), (x,y+h+30), font, fontscale, fontcolor, stroke)#print the number or value of the prediction, str(id) means the text we want to print, (x,y+h) is for the text to be in the face and (x,y) is for the text on the upper of the rectangle cv2.putText(frame,"Age:" +str(profile[2]), (x,y+h+60), font, fontscale, fontcolor, stroke) cv2.putText(frame,"Gender:" +str(profile[3]), (x,y+h+90), font, fontscale, fontcolor, stroke) cv2.putText(frame,"Criminal Records:" +str(profile[4]), (x,y+h+120), font, fontscale, fontcolor, stroke) cv2.putText(frame,"Profession:" +str(profile[5]), (x,y+h+150), font, fontscale, fontcolor, stroke) cv2.imshow("frame",frame); #cv2.waitKey(1); #if(sampleNum>20): # break if cv2.waitKey(20) & 0xFF == ord('q'): break; cam.release() cv2.destroyAllWindows()<file_sep>/facetrain.py import os #it's a python library to import all the images that are saved in the folder named as dataSet import cv2 # library import numpy as np #opencv only works with numpy array from PIL import Image #to capture images, PIL means python image library recognizer = cv2.face.LBPHFaceRecognizer_create(); #create a recognizer, LBPH is a face recognition algorithm.Local Binary Patterns Histograms path='dataSet' #path of the image sample where the images are saved def getImagesWithID(path): # a method to get all the corresponding images with id which means the saved images name imagePaths=[os.path.join(path,f) for f in os.listdir(path)] #create a list for the path for all the images that are available in the folder #print (imagePaths) # this is for running this file to check if tha path of the images has created or not #getImagesWithID(path) faces=[] # create an empty list for face IDs=[] # create empty list for the id for imagePath in imagePaths: #to go through the images # first open the image from directory than convert it to numpy array because opencv only works with numpy array faceImg=Image.open(imagePath).convert("L"); #faceImg is now PIL image, now opening the image from directory faceNp=np.array(faceImg,'uint8') #than converting to numpy array so opencv can work with it,uint8 meaning - Unsigned integer (0 to 255) #now need to get the user id which are name of the saved images in dataSet folder ID=int(os.path.split(imagePath)[-1].split('.')[1]) #to count backward of the saved images name, it is in string format that's why int is used to convert it to integer format faces.append(faceNp) #directly store faces and id print(ID) IDs.append(ID) cv2.imshow("training",faceNp)#images capturing or training cv2.waitKey(10) return np.array(IDs), faces #return the values means faces and ids Ids, faces=getImagesWithID(path) # create faces,ids with path recognizer.train(faces,Ids) # to train the recognizer, need the faces and ids recognizer.save('recognizer/trainingData.yml') #create a recognizer folder in the present directory than got the trainingData.yml cv2.destroyAllWindows()
9f0faf36b27b9c8f161c8a8ea8e0ffa6b309bb48
[ "Markdown", "Python" ]
4
Python
Shamimasharmin/Face-detection-and-identification-with-mysql-database-in-real-time
8ca7a0da1ce8b807b1984c898f0151c7cd276d0d
96566c4ed3d7c1005d4bea2e5afb22e842afec6d
refs/heads/master
<file_sep># -*- coding: utf-8 -*- from typing import List, Optional import os import torch import torch.nn as nn from transformers import BertForTokenClassification,BertTokenizer,BertConfig # CRF Ref: https://pytorch-crf.readthedocs.io/en/stable/index.html # bertCrf Ref: https://github.com/997261095/bert-kbqa/blob/master/BERT_CRF.py class CRF(nn.Module): def __init__(self, num_tags : int = 2, batch_first: bool = True) -> None: if num_tags <= 0: raise ValueError(f'invalid number of tags: {num_tags}') super().__init__() self.num_tags = num_tags self.batch_first = batch_first # score of start-> self.start_transitions = nn.Parameter(torch.empty(num_tags)) # score of ->tag_end self.end_transitions = nn.Parameter(torch.empty(num_tags)) # transitions[i][j]: score of tag_i -> tag_j self.transitions = nn.Parameter(torch.empty(num_tags,num_tags)) self.reset_parameters() def reset_parameters(self): init_range = 0.1 nn.init.uniform_(self.start_transitions, -init_range, init_range) nn.init.uniform_(self.end_transitions, -init_range, init_range) nn.init.uniform_(self.transitions, -init_range, init_range) def __repr__(self): return f'{self.__class__.__name__}(num_tags={self.num_tags})' # Compute the conditional log likelihood of a sequence of tags given emission scores # change to negative log likelihood # p(y|x) = exp(Score(X, y)) / sum(exp(Score(X, y))) # log P = Score(X, y) - log(sum(exp(Score(X, y)))) # loss = - log P = log(sum(exp(Score(X, y)))) - Score(X, y) def forward(self, emissions:torch.Tensor, tags:torch.Tensor = None, mask:Optional[torch.ByteTensor] = None, reduction: str = "mean") -> torch.Tensor: self._validate(emissions, tags = tags ,mask = mask) reduction = reduction.lower() if reduction not in ('none','sum','mean','token_mean'): raise ValueError(f'invalid reduction {reduction}') if mask is None: mask = torch.ones_like(tags,dtype = torch.uint8) if self.batch_first: # emissions.shape (seq_len,batch_size,tag_num) emissions = emissions.transpose(0,1) tags = tags.transpose(0,1) mask = mask.transpose(0,1) # shape: (batch_size,) numerator = self._computer_score(emissions=emissions,tags=tags,mask=mask) # shape: (batch_size,) denominator = self._compute_normalizer(emissions=emissions,mask=mask) # shape: (batch_size,) nllh = denominator - numerator if reduction == 'none': return nllh elif reduction == 'sum': return nllh.sum() elif reduction == 'mean': return nllh.mean() assert reduction == 'token_mean' return nllh.sum() / mask.float().sum() def decode(self,emissions:torch.Tensor, mask : Optional[torch.ByteTensor] = None) ->List[List[int]]: self._validate(emissions=emissions,mask=mask) if mask is None: mask = emissions.new_ones(emissions.shape[:2],dtype=torch.uint8) if self.batch_first: emissions = emissions.transpose(0,1) mask = mask.transpose(0,1) return self._viterbi_decode(emissions,mask) def _validate(self, emissions:torch.Tensor, tags:Optional[torch.LongTensor] = None , mask:Optional[torch.ByteTensor] = None) -> None: if emissions.dim() != 3: raise ValueError(f"emissions must have dimension of 3 , got {emissions.dim()}") if emissions.size(2) != self.num_tags: raise ValueError( f'expected last dimension of emissions is {self.num_tags},' f'got {emissions.size(2)}' ) if tags is not None: if emissions.shape[:2] != mask.shape: raise ValueError( 'the first two dimensions of and mask must match,' f'got {tuple(emissions.shape[:2])} and {tuple(mask.shape)}' ) no_empty_seq = not self.batch_first and mask[0].all() no_empty_seq_bf = self.batch_first and mask[:,0].all() if not no_empty_seq and not no_empty_seq_bf: raise ValueError('mask of the first timestep must all be on') def _computer_score(self, emissions:torch.Tensor, tags:torch.LongTensor, mask:torch.ByteTensor) -> torch.Tensor: # batch second # emissions: (seq_length, batch_size, num_tags) # tags: (seq_length, batch_size) # mask: (seq_length, batch_size) assert emissions.dim() == 3 and tags.dim() == 2 assert emissions.shape[:2] == tags.shape assert emissions.size(2) == self.num_tags assert mask.shape == tags.shape assert mask[0].all() seq_length, batch_size = tags.shape mask = mask.float() # Start transition score and first emission # self.start_transitions: score of start-> # score.shape: (batch_size, ) score = self.start_transitions[tags[0]] score += emissions[0, torch.arange(batch_size), tags[0]] for i in range(1, seq_length): # Transition score to next tag, only added if next timestep is valid (mask == 1) # shape: (batch_size, ) score += self.transitions[tags[i-1], tags[i]] * mask[i] # Emission score for next tag, only added if next timestep is valid (mask == 1) score += emissions[i, torch.arange(batch_size), tags[i]] * mask[i] # End transition score # shape: (batch_size,) seq_ends = mask.long().sum(dim=0) - 1 # final tags of each sample last_tags = tags[seq_ends, torch.arange(batch_size)] # shape: (batch_size,) 每一个样本到最后一个词的得分加上之前的score score += self.end_transitions[last_tags] return score def _compute_normalizer(self, emissions:torch.Tensor , mask: torch.ByteTensor) -> torch.Tensor: # emissions: (seq_length, batch_size, num_tags) # mask: (seq_length, batch_size) assert emissions.dim() == 3 and mask.dim() == 2 assert emissions.shape[:2] == mask.shape assert emissions.size(2) == self.num_tags assert mask[0].all() seq_length = emissions.size(0) # shape : (batch_size,num_tag) # self.start_transitions start 到其他tag(不包含end)的得分 # start_transitions.shape tag_nums emissions[0].shape (batch_size,tag_size) # Start transition score and first emission; score has size of # (batch_size, num_tags) where for each batch, the j-th column stores # the score that the first timestep has tag j # shape: (batch_size, num_tags) score = self.start_transitions + emissions[0] for i in range(1,seq_length): # Broadcast score for every possible next tag # shape: (batch_size, num_tags, 1) broadcast_score = score.unsqueeze(dim=2) # Broadcast emission score for every possible current tag # shape: (batch_size, 1, num_tags) broadcast_emissions = emissions[i].unsqueeze(1) # Compute the score tensor of size (batch_size, num_tags, num_tags) where # for each sample, entry at row i and column j stores the sum of scores of all # possible tag sequences so far that end with transitioning from tag i to tag j # and emitting # shape: (batch_size, num_tags, num_tags) next_score = broadcast_score + self.transitions + broadcast_emissions # Sum over all possible current tags, but we're in score space, so a sum # becomes a log-sum-exp: for each sample, entry i stores the sum of scores of # all possible tag sequences so far, that end in tag i # shape: (batch_size, num_tags) next_score = torch.logsumexp(next_score,dim = 1) # Set score to the next score if this timestep is valid (mask == 1) # shape: (batch_size, num_tags) score = torch.where(mask[i].unsqueeze(1), next_score, score) # End transition score # shape: (batch_size, num_tags) score += self.end_transitions # Sum (log-sum-exp) over all possible tags # shape: (batch_size,) return torch.logsumexp(score,dim=1) def _viterbi_decode(self, emissions: torch.FloatTensor, mask: torch.ByteTensor) -> List[List[int]]: # emissions: (seq_length, batch_size, num_tags) # mask: (seq_length, batch_size) assert emissions.dim() == 3 and mask.dim() == 2 assert emissions.shape[:2] == mask.shape assert emissions.size(2) == self.num_tags assert mask[0].all() seq_length, batch_size = mask.shape # Start transition and first emission # shape: (batch_size, num_tags) score = self.start_transitions + emissions[0] history = [] # score is a tensor of size (batch_size, num_tags) where for every batch, # value at column j stores the score of the best tag sequence so far that ends # with tag j # history saves where the best tags candidate transitioned from; this is used # when we trace back the best tag sequence # Viterbi algorithm recursive case: we compute the score of the best tag sequence # for every possible next tag for i in range(1, seq_length): # Broadcast viterbi score for every possible next tag # shape: (batch_size, num_tags, 1) broadcast_score = score.unsqueeze(2) # Broadcast emission score for every possible current tag # shape: (batch_size, 1, num_tags) broadcast_emission = emissions[i].unsqueeze(1) # Compute the score tensor of size (batch_size, num_tags, num_tags) where # for each sample, entry at row i and column j stores the score of the best # tag sequence so far that ends with transitioning from tag i to tag j and emitting # shape: (batch_size, num_tags, num_tags) next_score = broadcast_score + self.transitions + broadcast_emission # Find the maximum score over all possible current tag # shape: (batch_size, num_tags) next_score, indices = next_score.max(dim=1) # Set score to the next score if this timestep is valid (mask == 1) # and save the index that produces the next score # shape: (batch_size, num_tags) score = torch.where(mask[i].unsqueeze(1), next_score, score) history.append(indices) # End transition score # shape: (batch_size, num_tags) score += self.end_transitions # Now, compute the best path for each sample # shape: (batch_size,) seq_ends = mask.long().sum(dim=0) - 1 best_tags_list = [] for idx in range(batch_size): # Find the tag which maximizes the score at the last timestep; this is our best tag # for the last timestep _, best_last_tag = score[idx].max(dim=0) best_tags = [best_last_tag.item()] # We trace back where the best last tag comes from, append that to our best tag # sequence, and trace it back again, and so on for hist in reversed(history[:seq_ends[idx]]): best_last_tag = hist[idx][best_tags[-1]] best_tags.append(best_last_tag.item()) # Reverse the order because we start from the last timestep best_tags.reverse() best_tags_list.append(best_tags) return best_tags_list class BertCrf(nn.Module): def __init__(self, config_name:str = 'bert-base-chinese', model_name:str = None, num_tags: int = 2, batch_first:bool = True) -> None: # 记录batch_first self.batch_first = batch_first # 加载模型配置文件 if config_name != 'bert-base-chinese': if not os.path.exists(config_name): raise ValueError( "Error! No model config file: '{}'".format(config_name) ) else: self.config_name = config_name else: self.config_name = config_name # 加载预训练模型 if model_name is not None: if model_name == 'bert-base-chinese': self.model_name = model_name elif not os.path.exists(model_name): raise ValueError( "Error! No pretrained model: '{}'".format(model_name) ) else: self.model_name = model_name else: self.model_name = None if num_tags <= 0: raise ValueError(f'invalid number of tags: {num_tags}') super().__init__() self.bert_config = BertConfig.from_pretrained(self.config_name) self.bert_config.num_labels = num_tags # 如果模型不存在 if self.model_name is None: self.model_kwargs = {'config': self.bert_config} self.bertModel = BertForTokenClassification(**self.model_kwargs) elif self.model_name == 'bert-base-chinese': self.model_kwargs = {'config': self.bert_config, "from_tf": True} self.bertModel = BertForTokenClassification.from_pretrained(self.model_name, **self.model_kwargs) self.crf_model = CRF(num_tags=num_tags, batch_first=batch_first) def forward(self,input_ids:torch.Tensor, tags:torch.Tensor = None, attention_mask:Optional[torch.ByteTensor] = None, token_type_ids=torch.Tensor, decode:bool = True, # 是否预测编码 reduction: str = "mean") -> List: out = self.bertModel(input_ids = input_ids, attention_mask = attention_mask, token_type_ids=token_type_ids) emissions = out[0] # 这里在seq_len的维度上去头,是去掉了[CLS],去尾巴有两种情况 # 1、是 <pad> 2、[SEP] new_emissions = emissions[:, 1:-1] # del [CLS], [SEP] new_mask = attention_mask[:,2:].bool() # tags=None -> prediction, no loss if tags == None: loss = None pass else: new_tags = tags[:, 1:-1] loss = self.crf_model(emissions=new_emissions, tags=new_tags, mask=new_mask, reduction=reduction) if decode: tag_list = self.crf_model.decode(emissions=new_emissions, mask=new_mask) return [loss, tag_list] return [loss] <file_sep># # 切分数据集, # 原始的 nlpcc-iccpol-2016.kbqa.testing-data 有 9870 个样本 # 原始的 nlpcc-iccpol-2016.kbqa.training-data 有 14609 个样本 # # 将nlpcc-iccpol-2016.kbqa.testing-data 中的对半分,一半变成验证集(dev.text),一半变成测试集(test.txt) # nlpcc-iccpol-2016.kbqa.training-data 保持不变,复制成为训练集 train.txt # import pandas as pd import os data_dir = 'NLPCC2016KBQA' file_name_list = ['nlpcc-iccpol-2016.kbqa.testing-data','nlpcc-iccpol-2016.kbqa.training-data'] for file_name in file_name_list: file_path_name = os.path.join(data_dir,file_name) file = [] with open(file_path_name,'r',encoding='utf-8') as f: for line in f: line = line.strip() if line == '': continue file.append(line) f.close() if 'training' in file_name: with open(os.path.join(data_dir,'train.txt') , "w", encoding='utf-8') as f: f.write('\n'.join(file)) f.close() elif 'testing' in file_name: assert len(file) % 4 == 0 testing_num = len(file) / 4 # 一个样本是由 4 行构成的 test_num = int(testing_num / 2) # 真正的测试集分一半 test_line_no = int(test_num * 4) with open(os.path.join(data_dir, 'test.txt'), "w", encoding='utf-8') as f: f.write('\n'.join(file[:test_line_no])) # 乘以四得到行号,前一半给 test 数据集 f.close() with open(os.path.join(data_dir, 'dev.txt'), "w", encoding='utf-8') as f: f.write('\n'.join(file[test_line_no:])) # 乘以四得到行号,后一半给 dev 数据集 f.close() print("Done") <file_sep># -*- coding: utf-8 -*- import argparse from collections import Counter import code import os import gc import logging from tqdm import tqdm, trange import random import codecs import torch import torch.nn as nn from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset import bertcrf from transformers import AdamW, get_linear_schedule_with_warmup from transformers import BertConfig, BertForSequenceClassification, BertTokenizer from sklearn.metrics import classification_report import numpy as np import pandas as pd CRF_LABELS = ["O", "B-LOC", "I-LOC"] def calc_real_sentences(label_ids, mask, pred): label_ids = np.array(label_ids) mask = np.array(mask) pred = np.array(pred) #print('label shape: ', label_ids.shape) #print('mask shape: ', mask.shape) #print('pred shape: ', pred.shape) # shape (batch_size, max_len) assert label_ids.shape == mask.shape # batch_size assert label_ids.shape[0] == pred.shape[0] # 第0位是[CLS] 最后一位是<pad> 或者 [SEP] new_ids = label_ids[:, 1:-1] new_mask = mask[:, 2:] # 保持长度和new_ids一致即可 real_ids = [] for i in range(new_ids.shape[0]): # real label的长度等于mask去头/尾/pad的长度 seq_len = new_mask[i].sum() assert seq_len == len(pred[i]) real_ids.append(new_ids[i][:seq_len].tolist()) return real_ids def flatten(inputs): result = [] for i in inputs: result.extend(i) return result def set_seed(seed=4321): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) class NerInputText: def __init__(self, id, question, label=None): self.id = id self.question = question self.label = label class NerInputFeatures: def __init__(self, input_ids, attention_mask, token_type_ids, label=None): self.input_ids = input_ids self.attention_mask = attention_mask self.token_type_ids = token_type_ids self.label = label class preProcessorNer: def get_train_examples(self, data_dir): return self._create_examples( os.path.join(data_dir, "train.txt")) def get_dev_examples(self, data_dir): return self._create_examples( os.path.join(data_dir, "dev.txt")) def get_test_examples(self,data_dir): return self._create_examples( os.path.join(data_dir, "test.txt")) def get_labels(self): return ["O", "B-LOC", "I-LOC"] def _create_examples(self, path): lines = [] max_len = 0 with codecs.open(path, 'r', encoding='utf-8') as f: word_list = [] label_list = [] for line in f: tokens = line.strip().split() if 2 == len(tokens): # "你 O" word = tokens[0] label = tokens[1] word_list.append(word) label_list.append(label) elif not tokens: #end of one sentence if len(label_list) > max_len: max_len = len(label_list) lines.append((word_list,label_list)) word_list = [] label_list = [] examples = [] for i, (sentence, label) in enumerate(lines): examples.append( NerInputText(id=i, question=" ".join(sentence), label=label) ) f.close() return examples def bertEncodeNer(texts, tokenizer, max_seq_length=512, label_list=None): all_tokens = [] all_masks = [] all_segments = [] features = [] for text in texts: tokens = tokenizer.tokenize(text.question) ids = tokenizer.convert_tokens_to_ids(tokens) # cls + ids + sep input_ids = tokenizer.build_inputs_with_special_tokens(ids) masks = [1] * len(input_ids) #token_type_ids = tokenizer.create_token_type_ids_from_sequences(idsA, idsB) token_type_ids = [0] * (len(ids) + 2) # pad seq to max length pad_seq = [0] * (max_seq_length - len(input_ids)) input_ids += pad_seq masks += pad_seq token_type_ids += pad_seq assert len(input_ids) == max_seq_length, "Error with input length {} vs {}".format(len(input_ids), max_seq_length) assert len(masks) == max_seq_length, "Error with input length {} vs {}".format(len(masks), max_seq_length) assert len(token_type_ids) == max_seq_length, "Error with input length {} vs {}".format(len(token_type_ids), max_seq_length) # [CLS]/[SEP]: 'O', pad 0 = 'O', keep same lens with other embeddings labels_ids = [0] + [label_list.index(i) for i in text.label] + [0] + pad_seq assert len(labels_ids) == max_seq_length, "Error with input length {} vs {}".format(len(labels_ids), max_seq_length) features.append( NerInputFeatures(input_ids, masks, token_type_ids, labels_ids) ) return features def load_and_cache_example(args, tokenizer, processor, data_type): doc_list = ['train','dev','test'] if data_type not in doc_list: raise ValueError("data_type must be one of {}".format(" ".join(doc_list))) cached_features_file = "cached_{}_{}".format(data_type, str(args["max_seq_length"])) cached_features_file = os.path.join(args["data_dir"], cached_features_file) # 加载已处理的feature文件 if os.path.exists(cached_features_file): features = torch.load(cached_features_file) else: label_list = processor.get_labels() if doc_list[0] == data_type: examples = processor.get_train_examples(args["data_dir"]) elif doc_list[1] == data_type: examples = processor.get_dev_examples(args["data_dir"]) elif doc_list[2] == data_type: examples = processor.get_test_examples(args["data_dir"]) features = bertEncodeNer(texts=examples, tokenizer=tokenizer, max_seq_length=args["max_seq_length"], label_list=label_list) torch.save(features, cached_features_file) all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long) all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long) all_label = torch.tensor([f.label for f in features], dtype=torch.long) dataset = TensorDataset(all_input_ids, all_attention_mask, all_token_type_ids, all_label) return dataset def evaluate_and_save_model(args, model, val_dataloader, best_f1): if not os.path.exists(args["output_dir"]): os.makedirs(args["output_dir"]) res = evaluate(args, model, val_dataloader) precision_b = res['1']['precision'] recall_b = res['1']['recall'] f1_b = res['1']['f1-score'] support_b = res['1']['support'] precision_i = res['2']['precision'] recall_i = res['2']['recall'] f1_i = res['2']['f1-score'] support_i = res['2']['support'] weight_b = support_b / (support_b + support_i) weight_i = 1 - weight_b avg_precision = precision_b * weight_b + precision_i * weight_i avg_recall = recall_b * weight_b + recall_i * weight_i avg_f1 = f1_b * weight_b + f1_i * weight_i all_avg_precision = res['macro avg']['precision'] all_avg_recall = res['macro avg']['recall'] all_avg_f1 = res['macro avg']['f1-score'] print("[B-LOC] Precision : {:.4f} Recall : {:.4f} F1 : {:.4f} Support : {}" .format(precision_b, recall_b, f1_b, support_b)) print("[I-LOC] Precision : {:.4f} Recall : {:.4f} F1 : {:.4f} Support : {}" .format(precision_i, recall_i, f1_i, support_i)) print("AVG: Precision : {:.4f} Recall : {:.4f} F1 : {:.4f}" .format(avg_precision, avg_recall, avg_f1)) print("all AVG: Precision : {:.4f} Recall : {:.4f} F1 : {:.4f}" .format(all_avg_precision, all_avg_recall, all_avg_f1)) if avg_f1 > best_f1: best_f1 = avg_f1 #model_to_save = model.module if hasattr(model, 'module') else model #model_to_save.save_pretrained(args["output_dir"]) torch.save(model.state_dict(), os.path.join(args["output_dir"], "pytorch_model.bin")) print("save the best model with avg_f1= {:.4f}".format(best_f1)) return best_f1 def evaluate(args, model, val_dataloader): print("--------------- Validation ---------------") print(" Num examples = {}".format(len(val_dataloader))) print(" Batch size = {}".format(args["batch_size"])) all_real_labels = [] all_pred_labels = [] total_loss = [] for batch in val_dataloader: model.eval() batch = tuple(t.to(args["device"]) for t in batch) with torch.no_grad(): inputs = {'input_ids':batch[0], 'attention_mask':batch[1], 'token_type_ids':batch[2], 'tags':batch[3], 'decode':True, 'reduction': 'None' } outputs = model(**inputs) # loss: (batch_size, ) # logits=list[list(int)]: [[00012200],[001222200],..] (batch_size,) loss, logits = outputs[0], outputs[1] total_loss.extend(loss.tolist()) # tensor -> numpy #logits = logits.detach().cpu().numpy() label_ids = batch[3].to('cpu').numpy() masks = batch[1].to('cpu').numpy() all_pred_labels.extend(logits) all_real_labels.extend(calc_real_sentences(label_ids, masks, logits)) total_loss = np.array(total_loss).mean() all_real_labels = np.array([i for j in all_real_labels for i in j]) all_pred_labels = np.array([i for j in all_pred_labels for i in j]) assert all_real_labels.shape == all_pred_labels.shape print(all_real_labels, all_pred_labels) res = classification_report(y_true = all_real_labels, y_pred = all_pred_labels, output_dict=True) return res def train(args, train_dataloader, val_dataloader, model): # optimizer parameter gradient_accumulation_steps = 1 total_lens = len(train_dataloader) // gradient_accumulation_steps * args["epochs"] no_decay = ['bias', 'LayerNorm.weight', 'transitions'] optimizer_grouped_parameters = [ {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': 0.0}, {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} ] optimizer = AdamW(optimizer_grouped_parameters, lr=args["learning_rate"], eps=1e-8) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=total_lens) print("--------------- Training ---------------") print(" Num Batch = {}".format(len(train_dataloader))) print(" Num Epochs = {}".format(args["epochs"])) print(" Gradient Accumulation steps = {}".format(gradient_accumulation_steps)) print(" Total optimization steps = {}".format(total_lens)) model.zero_grad() set_seed() train_acc = 0.0 for i in range(int(args["epochs"])): #epoch_iterator = tqdm(train_dataloader, desc="Iteration") tr_loss = 0.0 for step, batch in enumerate(train_dataloader): model.train() batch = tuple(t.to(args["device"]) for t in batch) inputs = {'input_ids':batch[0], 'attention_mask':batch[1], 'token_type_ids':batch[2], 'tags':batch[3], 'decode': True, } outputs = model(**inputs) loss, logits = outputs[0], outputs[1] # 梯度累积计算,当gpu过小 if gradient_accumulation_steps > 1: loss = loss / gradient_accumulation_steps loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) #logging_loss += loss.item() tr_loss += loss.item() if (step + 1) % gradient_accumulation_steps == 0: optimizer.step() scheduler.step() model.zero_grad() #global_step += 1 #print("EPOCH : [{}/{}] global step : {} loss = {:.4f}".format(i+1, args["epochs"], global_step, logging_loss)) #logging_loss = 0.0 # 每100步,评估一次 #if (global_step % 50 == 0 and global_step <= 100) or (global_step % 100 == 0 and global_step <= 1000) \ # or (global_step % 200 == 0): if (step + 1) % 100 == 0: print("EPOCH : [{}/{}] step : {} cur_loss : {:.4f} ".format(i+1, args["epochs"], step, loss.item())) #train_acc = evaluate_and_save_model(args, model, val_dataloader, i, step, train_acc) train_acc = evaluate_and_save_model(args, model, val_dataloader, train_acc) print(" avg_loss : {:.4f} ".format(tr_loss/len(train_dataloader))) # 最后循环结束 再评估一次 train_acc = evaluate_and_save_model(args, model, val_dataloader, train_acc) def test(): device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') args_test = {"data_dir": '/content/gdrive/My Drive/nlpqa2/input/data/ner_data/', "load_path": '/content/gdrive/My Drive/nlpqa2/output/data2/', #"vocab_file": 'bert-base-chinese-vocab.txt' #"model_config": 'pytorch_model.bin', #"model_path": 'config.json', "max_seq_length": 128, "batch_size": 256, "learning_rate": 6e-6, "epochs": 3, "device": device } processor = preProcessorNer() tokenizer = BertTokenizer.from_pretrained('bert-base-chinese', return_tensors='pt') test_dataset = load_and_cache_example(args_test, tokenizer, processor, 'test') model_kwargs = {'config_name': 'bert-base-chinese', 'num_tags':len(processor.get_labels()), 'batch_first':True } model = bertcrf.BertCrf(**model_kwargs) model.load_state_dict(torch.load(os.path.join(args_test["load_path"], "pytorch_model.bin"))) model = model.to(device) test_dataloader = DataLoader(test_dataset, sampler=SequentialSampler(test_dataset), batch_size=args_test["batch_size"]) del test_dataset gc.collect() all_real_labels = [] all_pred_labels = [] total_loss = [] for batch in test_dataloader: model.eval() batch = tuple(t.to(device) for t in batch) with torch.no_grad(): inputs = {'input_ids':batch[0], 'attention_mask':batch[1], 'token_type_ids':batch[2], 'tags':batch[3], 'decode':True, 'reduction': 'None' } outputs = model(**inputs) loss, logits = outputs[0], outputs[1] total_loss.extend(loss.tolist()) # tensor -> numpy label_ids = batch[3].to('cpu').numpy() masks = batch[1].to('cpu').numpy() all_pred_labels.extend(logits) all_real_labels.extend(calc_real_sentences(label_ids, masks, logits)) total_loss = np.array(total_loss).mean() all_real_labels = np.array([i for j in all_real_labels for i in j]) all_pred_labels = np.array([i for j in all_pred_labels for i in j]) assert all_real_labels.shape == all_pred_labels.shape res = classification_report(y_true = all_real_labels, y_pred = all_pred_labels, output_dict=True) print(res) if __name__ == '__main__': device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print("using device", device) args_train = {"data_dir": '/content/gdrive/My Drive/nlpqa2/input/data/ner_data/', "pre_train_model": 'bert-base-chinese', "output_dir": '/content/gdrive/My Drive/nlpqa2/output/data2/', "max_seq_length": 128, "batch_size": 16, "learning_rate": 6e-6, "epochs": 3, "device": device } assert os.path.exists(args_train["data_dir"]) processor = preProcessorNer() tokenizer = BertTokenizer.from_pretrained(args_train["pre_train_model"], return_tensors='pt') train_dataset = load_and_cache_example(args_train, tokenizer, processor, 'train') val_dataset = load_and_cache_example(args_train, tokenizer, processor, 'dev') model_kwargs = {'config_name': args_train["pre_train_model"], 'model_name':args_train["pre_train_model"], 'num_tags':len(processor.get_labels()), 'batch_first':True } model = bertcrf.BertCrf(**model_kwargs) model = model.to(device) train_dataloader = DataLoader(train_dataset, batch_size=args_train["batch_size"], sampler=RandomSampler(train_dataset)) val_dataloader = DataLoader(val_dataset, sampler=SequentialSampler(val_dataset), batch_size=args_train["batch_size"]) del train_dataset, val_dataset gc.collect() train(args_train, train_dataloader, val_dataloader, model) del train_dataloader, val_dataloader gc.collect() #test()<file_sep># -*- coding: utf-8 -*- import argparse from collections import Counter import code import os import gc import logging from tqdm import tqdm, trange import random import codecs import torch import torch.nn as nn from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from transformers import AdamW, get_linear_schedule_with_warmup from transformers import BertConfig, BertForSequenceClassification, BertTokenizer import numpy as np import pandas as pd def set_seed(seed=4321): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) def calc_acc(real_label, pred_label): real_label = np.array(real_label) pred_label = np.array(pred_label) assert real_label.shape == pred_label.shape assert real_label.shape[0] % 2 == 0 #真实label应该是2的倍数 # 对每个label:预测正确的个数/预测总数(无论真假label) label_acc = float((real_label == pred_label).sum()) / float(pred_label.shape[0]) # real_label = real_label.reshape(-1,2) assert real_label.shape[0] == real_label[:,0].sum() # 转成真实问题数*(2个预测概率) pred_label = pred_label.reshape(-1,2) # 看看对每个问题预测成2个答案的概率 #pred_idx = pred_label.argmax(dim=-1) pred_idx = np.argmax(pred_label, axis=1).flatten() # 对每个问题:预测正确的acc question_acc = float((pred_idx == 0).sum()) / float(pred_idx.shape[0]) return question_acc, label_acc class SimInputText: def __init__(self, id, question, attribute, label=None): self.id = id self.question = question self.attribute = attribute self.label = label class SimInputFeatures: def __init__(self, input_ids, attention_mask, token_type_ids, label=None): self.input_ids = input_ids self.attention_mask = attention_mask self.token_type_ids = token_type_ids self.label = label class preProcessor: def get_train_examples(self, data_dir): return self._create_examples( os.path.join(data_dir, "train.txt")) def get_dev_examples(self, data_dir): return self._create_examples( os.path.join(data_dir, "dev.txt")) def get_test_examples(self,data_dir): return self._create_examples( os.path.join(data_dir, "test.txt")) def get_labels(self): return [0, 1] def _create_examples(self, path): examples = [] with codecs.open(path, 'r', encoding='utf-8') as f: for line in f: tokens = line.strip().split('\t') if 4 == len(tokens): examples.append( SimInputText(id=int(tokens[0]), question=tokens[1], attribute=tokens[2], label=int(tokens[3])) ) f.close() return examples def bertEncode(texts, tokenizer, max_seq_length=512, label_list=None): all_tokens = [] all_masks = [] all_segments = [] features = [] for text in texts: textA = tokenizer.tokenize(text.question) textB = tokenizer.tokenize(text.attribute) idsA = tokenizer.convert_tokens_to_ids(textA) idsB = tokenizer.convert_tokens_to_ids(textB) # cls + idsA + sep + idsB + sep input_ids = tokenizer.build_inputs_with_special_tokens(idsA, idsB) masks = [1] * len(input_ids) #token_type_ids = tokenizer.create_token_type_ids_from_sequences(idsA, idsB) token_type_ids = [0] * (len(idsA) + 2) + [1] * (len(idsB) + 1) # pad seq to max length pad_seq = [0] * (max_seq_length - len(input_ids)) input_ids += pad_seq masks += pad_seq token_type_ids += pad_seq assert len(input_ids) == max_seq_length, "Error with input length {} vs {}".format(len(input_ids), max_seq_length) assert len(masks) == max_seq_length, "Error with input length {} vs {}".format(len(masks), max_seq_length) assert len(token_type_ids) == max_seq_length, "Error with input length {} vs {}".format(len(token_type_ids), max_seq_length) features.append( SimInputFeatures(input_ids, masks, token_type_ids, text.label) ) return features def load_and_cache_example(args, tokenizer, processor, data_type): doc_list = ['train','dev','test'] if data_type not in doc_list: raise ValueError("data_type must be one of {}".format(" ".join(doc_list))) cached_features_file = "cached_{}_{}".format(data_type, str(args["max_seq_length"])) cached_features_file = os.path.join(args["data_dir"], cached_features_file) # 加载feature if os.path.exists(cached_features_file): features = torch.load(cached_features_file) else: label_list = processor.get_labels() if doc_list[0] == data_type: examples = processor.get_train_examples(args["data_dir"]) elif doc_list[1] == data_type: examples = processor.get_dev_examples(args["data_dir"]) elif doc_list[2] == data_type: examples = processor.get_test_examples(args["data_dir"]) features = bertEncode(texts=examples, tokenizer=tokenizer, max_seq_length=args["max_seq_length"], label_list=label_list) torch.save(features, cached_features_file) all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long) all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long) all_label = torch.tensor([f.label for f in features], dtype=torch.long) dataset = TensorDataset(all_input_ids, all_attention_mask, all_token_type_ids, all_label) return dataset def evaluate_and_save_model(args, model, val_dataloader, epoch, best_acc): if not os.path.exists(args["output_dir"]): os.makedirs(args["output_dir"]) val_loss, question_acc, label_acc = evaluate(args, model, val_dataloader) print("EPOCH : [{}/{}] val_loss : {:.4f} question_acc : {:.4f} label_acc : {:.4f}" .format(epoch + 1, args["epochs"], val_loss, question_acc, label_acc)) if question_acc > best_acc: best_acc = question_acc # hasattr判断对象是否有某属性 bool model_to_save = model.module if hasattr(model, 'module') else model model_to_save.save_pretrained(args["output_dir"]) #torch.save(model.state_dict(), os.path.join(args["output_dir"], "pytorch_model.bin")) #print("question_acc : {:.4f}".format(best_acc)) return best_acc def evaluate(args, model, val_dataloader): print("--------------- Validation ---------------") print(" Num examples = {}".format(len(val_dataloader))) print(" Batch size = {}".format(args["batch_size"])) total_loss = 0.0 total_sample = 0 # 样本数 all_real_labels = [] all_pred_labels = [] for batch in val_dataloader: model.eval() batch = tuple(t.to(args["device"]) for t in batch) with torch.no_grad(): inputs = {'input_ids':batch[0], 'attention_mask':batch[1], 'token_type_ids':batch[2], 'labels':batch[3], } outputs = model(**inputs) loss, logits = outputs[0], outputs[1] #total_loss += loss * batch[0].shape[0] # loss * 样本数 total_loss += loss.item() logits = logits.detach().cpu().numpy() label_ids = batch[3].to('cpu').numpy() total_sample += batch[0].shape[0] # 记录样本个数 #pred = logits.argmax(dim=-1).tolist() # 得到预测label (list) pred = np.argmax(logits, axis=1).flatten() all_pred_labels.extend(pred) # 预测label all_real_labels.extend(batch[3].view(-1).tolist()) # 真实label avg_loss = total_loss / total_sample question_acc, label_acc = calc_acc(all_real_labels, all_pred_labels) return avg_loss, question_acc, label_acc def train(args, train_dataloader, val_dataloader, model): # optimizer parameter gradient_accumulation_steps = 1 total_lens = len(train_dataloader) // gradient_accumulation_steps * args["epochs"] no_decay = ['bias', 'LayerNorm.weight','transitions'] optimizer_grouped_parameters = [ {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': 0.0}, {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} ] optimizer = AdamW(optimizer_grouped_parameters, lr=args["learning_rate"], eps=1e-8) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=total_lens) print("--------------- Training ---------------") print(" Num Batch = {}".format(len(train_dataloader))) print(" Num Epochs = {}".format(args["epochs"])) print(" Gradient Accumulation steps = {}".format(gradient_accumulation_steps)) print(" Total optimization steps = {}".format(total_lens)) model.zero_grad() set_seed() train_acc = 0.0 for i in range(int(args["epochs"])): tr_loss = 0.0 for step, batch in enumerate(train_dataloader): model.train() batch = tuple(t.to(args["device"]) for t in batch) inputs = {'input_ids':batch[0], 'attention_mask':batch[1], 'token_type_ids':batch[2], 'labels':batch[3], } outputs = model(**inputs) loss, logits = outputs[0], outputs[1] if gradient_accumulation_steps > 1: loss = loss / gradient_accumulation_steps loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) #logging_loss += loss.item() tr_loss += loss.item() if (step + 1) % gradient_accumulation_steps == 0: optimizer.step() scheduler.step() model.zero_grad() #global_step += 1 #print("EPOCH : [{}/{}] global step : {} loss = {:.4f}".format(i+1, args["epochs"], global_step, logging_loss)) #logging_loss = 0.0 # 每100步,评估一次 #if (global_step % 50 == 0 and global_step <= 100) or (global_step % 100 == 0 and global_step <= 1000) \ # or (global_step % 200 == 0): if (step + 1) % 100 == 0: print("EPOCH : [{}/{}] step : {} cur_loss : {:.4f} ".format(i+1, args["epochs"], step, loss.item())) #train_acc = evaluate_and_save_model(args, model, val_dataloader, i, step, train_acc) train_acc = evaluate_and_save_model(args, model, val_dataloader, i, train_acc) print(" avg_loss : {:.4f} ".format(tr_loss/len(train_dataloader))) # 最后循环结束 再评估一次 train_acc = evaluate_and_save_model(args, model, val_dataloader, i, train_acc) def test(): device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') args_test = {"data_dir": '/content/gdrive/My Drive/nlpqa2/input/data/sim_data/', "load_path": '/content/gdrive/My Drive/nlpqa2/output/data/', #"vocab_file": 'bert-base-chinese-vocab.txt' #"model_config": 'pytorch_model.bin', #"model_path": 'config.json', "max_seq_length": 128, "batch_size": 16, "learning_rate": 6e-6, "epochs": 3, "device": device } tokenizer = BertTokenizer(os.path.join(args_test["data_dir"], 'bert-base-chinese-vocab.txt'), return_tensors='pt') processor = preProcessor() test_dataset = load_and_cache_example(args_test, tokenizer, processor, 'test') bert_config = BertConfig.from_pretrained(os.path.join(args_test["load_path"], 'config.json')) bert_config.num_labels = len(processor.get_labels()) test_dataloader = DataLoader(test_dataset, sampler=SequentialSampler(test_dataset), batch_size=args_test["batch_size"]) model_kwargs = {'config': bert_config, "from_tf": False} model = BertForSequenceClassification.from_pretrained(os.path.join(args_test["load_path"], 'pytorch_model.bin'), **model_kwargs) #model.load_state_dict(torch.load(os.path.join(args["load_path"], "model_path"))) model = model.to(device) del test_dataset gc.collect() total_loss = 0.0 total_sample = 0 # 样本数 all_real_labels = [] all_pred_labels = [] for batch in test_dataloader: model.eval() batch = tuple(t.to(device) for t in batch) with torch.no_grad(): inputs = {'input_ids': batch[0], 'attention_mask': batch[1], 'token_type_ids': batch[2], 'labels': batch[3] } outputs = model(**inputs) loss, logits = outputs[0], outputs[1] total_loss += loss.item() #total_loss += loss * batch[0].shape[0] # loss * 样本数 logits = logits.detach().cpu().numpy() label_ids = batch[3].to('cpu').numpy() total_sample += batch[0].shape[0] # 记录样本个数 #pred = logits.argmax(dim=-1).tolist() # 得到预测的label转为list pred = np.argmax(logits, axis=1).flatten() all_pred_labels.extend(pred) all_real_labels.extend(batch[3].view(-1).tolist()) loss = total_loss / total_sample question_acc, label_acc = calc_acc(all_real_labels, all_pred_labels) print("avg_loss", loss) print("question_acc", question_acc) print("label_acc", label_acc) if __name__ == '__main__': device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print("using device", device) args_train = {"data_dir": '/content/gdrive/My Drive/nlpqa2/input/data/sim_data/', "pre_train_model": 'bert-base-chinese', "output_dir": '/content/gdrive/My Drive/nlpqa2/output/data/', "max_seq_length": 128, "batch_size": 16, "learning_rate": 6e-6, "epochs": 3, "device": device } assert os.path.exists(args_train["data_dir"]) processor = preProcessor() tokenizer = BertTokenizer.from_pretrained(args_train["pre_train_model"], return_tensors='pt') train_dataset = load_and_cache_example(args_train, tokenizer, processor, 'train') val_dataset = load_and_cache_example(args_train, tokenizer, processor, 'dev') bert_config = BertConfig.from_pretrained(args_train["pre_train_model"]) bert_config.num_labels = len(processor.get_labels()) model_kwargs = {'config': bert_config, "from_tf": True} model = BertForSequenceClassification.from_pretrained(args_train["pre_train_model"], **model_kwargs) model = model.to(device) train_dataloader = DataLoader(train_dataset, sampler=RandomSampler(train_dataset), batch_size=args_train["batch_size"]) val_dataloader = DataLoader(val_dataset, sampler=SequentialSampler(val_dataset), batch_size=args_train["batch_size"]) del train_dataset, val_dataset gc.collect() train(args_train, train_dataloader, val_dataloader, model) del train_dataloader, val_dataloader gc.collect() #test()<file_sep># kbqa-bert construct simple kbqa system based on deep learning(BERT) ## 数据 input/data NLPCC2016的中文KBQA数据集 【original data】 http://tcci.ccf.org.cn/conference/2016/pages/page05_evadata.html 【处理过的三元组数据集】 https://github.com/huangxiangzhou/NLPCC2016KBQA ## 数据预处理 - split_dataset.py: 将数据集分为train(14609)/dev(9870)/test(9870)三部分 - ner-dataset2.py: 构造NER数据集,采用BIO标签 - sim-dataset3.py: 构造【问题-属性】数据集,二分类问题:1个问题-正确实体:label=1 / 1个问题-错误实体:label=0 - triple_clean4.py: 构造三元组数据集,存为csv文件,用于mention查询 ## 训练模型1 - ner_main.py: 基于pytorch crf + bert,用于识别输入问题中的mention crf(ref:https://pytorch-crf.readthedocs.io/en/stable/index.html#) bertcrf(ref:https://github.com/997261095/bert-kbqa/blob/master/BERT_CRF.py) ## 训练模型2 - sim_main.py: 基于 pytorch bert,用于计算问题和属性的相似度,判断问题是否包含该属性 ## 综合以上两个模型 - kbqa.py: - 1)对于输入问题,利用NER模型识别问题中的 mention; - 2)简单检索 triple_clean.csv,进行实体链接,找出知识库中所有对应的 entity 及其对应候选 attribute 和 answer; - 3)简单字符串匹配:若候选属性出现在问题中,则问题-属性直接匹配成功,返回对应 answer; - 4)问题-属性匹配:若候选属性没有直接出现在问题中,利用问题-属性相似度模型进行预测,返回对应 answer ## 有待改进 - 1)Candidate Entity Generation:同一 entity 存在不同 mention - 2)Entity Disambiguation: 同一 mention 对应不同 entity <file_sep># coding:utf-8 import sys import os import random import pandas as pd import re ''' 通过 ner_data 中的数据 构建出 用来匹配句子相似度的 样本集合 构造属性关联训练集,分类问题,训练BERT分类模型 1 ''' data_dir = 'ner_data' file_name_list = ['train.csv','dev.csv','test.csv'] new_dir = 'sim_data' pattern = re.compile('^-+') # 以-开头 for file_name in file_name_list: file_path_name = os.path.join(data_dir,file_name) assert os.path.exists(file_path_name) attribute_classify_sample = [] df = pd.read_csv(file_path_name, encoding='utf-8') df['attribute'] = df['t_str'].apply(lambda x: x.split('|||')[1].strip()) #2nd 属性 attribute_list = df['attribute'].tolist() # 转化成列表 attribute_list = list(set(attribute_list)) # 去重 attribute_list = [att.strip().replace(' ','') for att in attribute_list] # 去尾部,去空格 attribute_list = [re.sub(pattern,'',att) for att in attribute_list] # 去掉 以-开头 attribute_list = list(set(attribute_list)) # 再去重 for row in df.index: question, pos_att = df.loc[row][['q_str', 'attribute']] question = question.strip().replace(' ','') # 去尾部,空格 question = re.sub(pattern, '', question) # 去掉 以-开头 pos_att = pos_att.strip().replace(' ','') # 去尾部,空格 pos_att = re.sub(pattern, '', pos_att) # 去掉 以-开头 #每个问题1个正例属性(自身),1个负例属性(随机) neg_att_list = [] while True: neg_att_list = random.sample(attribute_list, 1) if pos_att not in neg_att_list: break attribute_classify_sample.append([question, pos_att, '1']) neg_att_sample = [[question, neg_att, '0'] for neg_att in neg_att_list] attribute_classify_sample.extend(neg_att_sample) seq_result = [str(lineno) + '\t' + '\t'.join(line) for (lineno, line) in enumerate(attribute_classify_sample)] if not os.path.exists(new_dir): os.makedirs(new_dir) file_type = file_name.split('.')[0] print("***** {} ******".format(file_type)) new_file_name = file_type + '.'+'txt' with open(os.path.join(new_dir,new_file_name), "w", encoding='utf-8') as f: f.write("\n".join(seq_result)) f.close() <file_sep># -*- coding: utf-8 -*- import sys import os import gc import torch import torch.nn as nn from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset import bertcrf, ner_main, sim_main from transformers import BertConfig, BertForSequenceClassification, BertTokenizer import numpy as np import pandas as pd #import pymysql from tqdm import tqdm, trange device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") def load_ner_model(config_file, model_name, label_num=3): model = bertcrf.BertCrf(config_name=config_file, num_tags=label_num, batch_first=True) model.load_state_dict(torch.load(model_name)) return model # model_name=os.path.join(args_test["load_path"], 'pytorch_model.bin') def load_sim_model(config_file, model_name, label_num=2): bert_config = BertConfig.from_pretrained(config_file) bert_config.num_labels = label_num model_kwargs = {'config': bert_config, "from_tf": False} model = BertForSequenceClassification.from_pretrained(model_name, **model_kwargs) return model def get_entity(model, tokenizer, sentence, max_seq_length=128): sentence_list = list(sentence.strip().replace(' ','')) text = " ".join(sentence_list) tokens = tokenizer.tokenize(text) ids = tokenizer.convert_tokens_to_ids(tokens) # cls + ids + sep input_ids = tokenizer.build_inputs_with_special_tokens(ids) masks = [1] * len(input_ids) #token_type_ids = tokenizer.create_token_type_ids_from_sequences(idsA, idsB) token_type_ids = [0] * (len(ids) + 2) # pad seq to max length pad_seq = [0] * (max_seq_length - len(input_ids)) input_ids += pad_seq masks += pad_seq token_type_ids += pad_seq assert len(input_ids) == max_seq_length, "Error with input length {} vs {}".format(len(input_ids), max_seq_length) assert len(masks) == max_seq_length, "Error with input length {} vs {}".format(len(masks), max_seq_length) assert len(token_type_ids) == max_seq_length, "Error with input length {} vs {}".format(len(token_type_ids), max_seq_length) input_ids = torch.tensor(input_ids).reshape(1, -1).to(device) masks = torch.tensor(masks).reshape(1, -1).to(device) token_type_ids = torch.tensor(token_type_ids).reshape(1, -1).to(device) model = model.to(device) model.eval() # when label is None, loss won't be computed output = model(input_ids = input_ids, tags = None, attention_mask = masks, token_type_ids = token_type_ids, decode=True) pred_tag = output[1][0] assert len(pred_tag) == len(sentence_list) or len(pred_tag) == max_len - 2 pred_tag_len = len(pred_tag) CRF_LABELS = ['O', 'B-LOC', 'I-LOC'] b_loc_idx = CRF_LABELS.index('B-LOC') i_loc_idx = CRF_LABELS.index('I-LOC') o_idx = CRF_LABELS.index('O') if b_loc_idx not in pred_tag and i_loc_idx not in pred_tag: print("没有在句子[{}]中发现实体".format(sentence)) return '' if b_loc_idx in pred_tag: entity_start_idx = pred_tag.index(b_loc_idx) else: entity_start_idx = pred_tag.index(i_loc_idx) entity_list = [] entity_list.append(sentence_list[entity_start_idx]) for i in range(entity_start_idx+1, pred_tag_len): if pred_tag[i] == i_loc_idx: entity_list.append(sentence_list[i]) else: break return "".join(entity_list) def semantic_match(model, tokenizer, question, attribute_list, answer_list, max_seq_length): assert len(attribute_list) == len(answer_list) all_tokens = [] all_masks = [] all_segments = [] features = [] for attribute in attribute_list: textA = tokenizer.tokenize(question) textB = tokenizer.tokenize(attribute) idsA = tokenizer.convert_tokens_to_ids(textA) idsB = tokenizer.convert_tokens_to_ids(textB) # cls + idsA + sep + idsB + sep input_ids = tokenizer.build_inputs_with_special_tokens(idsA, idsB) masks = [1] * len(input_ids) #token_type_ids = tokenizer.create_token_type_ids_from_sequences(idsA, idsB) token_type_ids = [0] * (len(idsA) + 2) + [1] * (len(idsB) + 1) # pad seq to max length pad_seq = [0] * (max_seq_length - len(input_ids)) input_ids += pad_seq masks += pad_seq token_type_ids += pad_seq assert len(input_ids) == max_seq_length, "Error with input length {} vs {}".format(len(input_ids), max_seq_length) assert len(masks) == max_seq_length, "Error with input length {} vs {}".format(len(masks), max_seq_length) assert len(token_type_ids) == max_seq_length, "Error with input length {} vs {}".format(len(token_type_ids), max_seq_length) features.append( sim_main.SimInputFeatures(input_ids, masks, token_type_ids) ) all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long) all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long) assert all_input_ids.shape == all_attention_mask.shape assert all_attention_mask.shape == all_token_type_ids.shape dataset = TensorDataset(all_input_ids, all_attention_mask, all_token_type_ids) sampler = SequentialSampler(dataset) dataloader = DataLoader(dataset, sampler=sampler, batch_size=128) data_num = all_attention_mask.shape[0] batch_size = 128 all_logits = None for batch in dataloader: model.eval() batch = tuple(t.to(device) for t in batch) with torch.no_grad(): inputs = {'input_ids': batch[0], 'attention_mask': batch[1], 'token_type_ids': batch[2], 'labels': None } outputs = model(**inputs) logits = outputs[0] #logits = logits.sigmoid(dim = -1) #logits = logits.softmax(dim = -1) if all_logits is None: all_logits = logits.clone() else: all_logits = torch.cat([all_logits, logits], dim = 0) prediction = all_logits.argmax(dim = -1) if prediction.sum() == 0: return torch.tensor(-1) else: return prediction.argmax(dim = -1) def select_database(sql): # connect database connect = pymysql.connect(user="root", password="<PASSWORD>", host="127.0.0.1", port=3306, db="kb_qa", charset="utf8") cursor = connect.cursor() # 创建操作游标 try: # 执行SQL语句 cursor.execute(sql) # 获取所有记录列表 results = cursor.fetchall() except Exception as e: print("Error: unable to fecth data: %s ,%s" % (repr(e), sql)) finally: # 关闭数据库连接 cursor.close() connect.close() return results # directly match: check if attribute is in question def text_match(attribute_list, answer_list, sentence): assert len(attribute_list) == len(answer_list) idx = -1 for i, attribute in enumerate(attribute_list): if attribute in sentence: idx = i break if idx != -1: return attribute_list[idx], answer_list[idx] return "","" def main(): with torch.no_grad(): ner_path = '/content/gdrive/My Drive/nlpqa2/output/data2/' sim_path = '/content/gdrive/My Drive/nlpqa2/output/data/' ner_processor = ner_main.preProcessorNer() tokenizer = BertTokenizer.from_pretrained('bert-base-chinese', return_tensors='pt') ner_model = load_ner_model(config_file='bert-base-chinese', model_name=os.path.join(ner_path, 'pytorch_model.bin'), label_num=len(ner_processor.get_labels())) ner_model = ner_model.to(device) ner_model.eval() while True: print("====="*8) raw_text = input("Please input the question(quit: 'q'):\n") raw_text = raw_text.strip() if (raw_text == 'q'): print("Thank U for using KBQA!") return entity = get_entity(model=ner_model, tokenizer=tokenizer, sentence=raw_text, max_seq_length=128) print("Entity: ", entity) if not entity: print("Cannot find entity in question!") continue # search entity via database #sql_str = "select * from nlpccqa where entity = '{}'".format(entity) #triple_list = select_database(sql_str) # search entity from clean_triple file directly df = pd.read_csv('/content/gdrive/My Drive/nlpqa2/input/data/DB_Data/clean_triple.csv') triple_list = [] pick = df.loc[df['entity'] == entity] triple_list = pick.values.tolist() if len(triple_list) == 0: print("There is no related info about entity '{}'".format(entity)) continue print('find triple list:\n', triple_list) triple_list = list(zip(*triple_list)) print('attr list:\n', triple_list[1]) attribute_list = triple_list[1] answer_list = triple_list[2] attribute, answer = text_match(attribute_list, answer_list, raw_text) if attribute and answer: res = "{}的{}是{}".format(entity, attribute, answer) else: sim_processor = sim_main.preProcessor() sim_model = load_sim_model(config_file=os.path.join(sim_path, 'config.json'), model_name=os.path.join(sim_path, 'pytorch_model.bin'), label_num=len(sim_processor.get_labels())) sim_model = sim_model.to(device) sim_model.eval() attribute_idx = semantic_match(sim_model, tokenizer, raw_text, attribute_list, answer_list, 64).item() if attribute_idx == -1: res = '' else: attribute = attribute_list[attribute_idx] answer = answer_list[attribute_idx] res = "{}的{}是{}".format(entity, attribute, answer) if res == '': print("There is no answer about entity '{}'".format(entity)) else: print("Answer:", res) if __name__ == '__main__': main()
c47fc463c34156f5c7a9d57ced5468e63d8a2385
[ "Markdown", "Python" ]
7
Python
Cecilia9999/kbqa-bert
a1501f2e433858e63853f504ce1500391a4513ef
3176c5045c04e87341ddad5daac35468a3a9e8e1
refs/heads/master
<repo_name>bugsnag/gulp-bugsnag<file_sep>/README.md # gulp-bugsnag [![Build status](https://travis-ci.org/bugsnag/gulp-bugsnag.svg?branch=master)](https://travis-ci.org/bugsnag/gulp-bugsnag) [![NPM](https://img.shields.io/npm/v/gulp-bugsnag.svg)](https://npmjs.org/package/gulp-bugsnag) Gulp plugins for common Bugsnag actions. ## Installation ``` npm install --save-dev gulp-bugsnag ``` ## Plugins ```js const { reportBuild } = require('gulp-bugsnag') ``` ### `reportBuild(build, opts): stream` Reports your application's build to Bugsnag. It can auto detect source control from `.git`, `.hg` and `package.json`. This plugin should go at the end of the task where you build your application – however it operates as a passthrough stream, so you can place things downstream of it if you like. Once it has received the last item in the stream, the plugin will report the build to Bugsnag. If something upstream errors the build report will not get sent. - `build` describes the build you are reporting to Bugsnag - `apiKey: string` your Bugsnag API key __[required]__ - `appVersion: string` the version of the application you are building __[required]__ - `releaseStage: string` `'production'`, `'staging'` etc. (leave blank if this build can be released to different `releaseStage`s) - `sourceControl: object` an object describing the source control of the build (if not specified, the module will attempt to detect source control information from `.git`, `.hg` and the nearest `package.json`) - `provider: string` can be one of: `'github'`, `'github-enterprise'`, `'gitlab'`, `'gitlab-onpremise'`, `'bitbucket'`, `'bitbucket-server'` - `repository: string` a URL (`git`/`ssh`/`https`) pointing to the repository, or webpage representing the repository - `revision: string` the unique identifier for the commit (e.g. git SHA) - `builderName: string` the name of the person/machine that created this build (defaults to the result of the `whoami` command) - `autoAssignRelease: boolean` automatically associate this build with any new error events and sessions that are received for the `releaseStage` until a subsequent build notification is received. If this is set to `true` and no `releaseStage` is provided the build will be applied to `'production'`. - `opts` - `logLevel: string` the minimum severity of log to output (`'debug'`, `'info'`, `'warn'`, `'error'`), default `'warn'` - `logger: object` provide a different logger object `{ debug, info, warn, error }` - `path: string` the path to search for source control info, defaults to `process.cwd()` - `endpoint: string` post the build payload to a URL other than the default (`https://build.bugsnag.com`) #### Usage ```js /* gulpfile.js */ const gulp = require('gulp') const concat = require('gulp-concat') const { reportBuild } = require('gulp-bugsnag') gulp.task('build', () => { gulp.src('src/*.js') .pipe(concat('bundle.js')) .pipe(gulp.dest('dist')) .pipe(reportBuild({ apiKey: 'YOUR_API_KEY', appVersion: '1.2.3' })) }) // $ gulp build // runs your build process and then notifies Bugsnag if the task succeeds ``` ## Support - [Search open and closed issues](https://github.com/bugsnag/gulp-bugsnag/issues?q=is%3Aissue) issues for similar problems - [Report a bug or request a feature](https://github.com/bugsnag/gulp-bugsnag/issues/new) - Email [<EMAIL>](mailto:<EMAIL>) ## Contributing All contributors are welcome! See our [contributing guide](CONTRIBUTING.md). ## License This module is free software released under the MIT License. See [LICENSE.txt](LICENSE.txt) for details. <file_sep>/test/fixtures/a/gulpfile.js const gulp = require('gulp') const concat = require('gulp-concat') const reportBuild = require('../../../').reportBuild gulp.task('build', () => { gulp.src('src/*.js') .pipe(concat('bundle.js')) .pipe(gulp.dest('dist')) .pipe(reportBuild({ apiKey: 'YOUR_API_KEY', appVersion: '1.2.3' }, { endpoint: `http://localhost:${process.env.PORT}` })) }) <file_sep>/test/fixtures/a/src/vendor.js /* * Vendor js stuff */ <file_sep>/build-reporter.js const reportBuild = require('bugsnag-build-reporter') const through = require('through2') module.exports = (build, opts) => { const _build = Object.assign({ buildTool: 'gulp-bugsnag' }, build) const _opts = Object.assign({ logLevel: 'warn' }, opts) // Create a passthrough stream that will re-emit every item // it recieves. Once it has received all input, it will report // the build to Bugsnag and close the stream. const stream = through.obj({}, null, (cb) => { reportBuild(_build, _opts) .then(cb) .catch(err => { // this error needs be reported in the next tick // because within the callstack of the promise it // gets re-emited at an unhandled rejection process.nextTick(() => cb(err)) }) }) return stream } <file_sep>/index.js module.exports = { reportBuild: require('./build-reporter') }
558d2da5ea2ff856a89a81c472aacfb7e55bcba7
[ "Markdown", "JavaScript" ]
5
Markdown
bugsnag/gulp-bugsnag
ee60faac266aab8fb3863147597e6f22ef2995ea
eef416cf062f4b512c1305ba9ff24da5645d7402
refs/heads/master
<file_sep>import React from 'react'; import {Jumbotron} from 'react-bootstrap'; import helpers from '../utils/helpers'; class Form extends React.Component { constructor(props) { super(props); this.state = { term: "", location: "", limit: 5, results: [], trenResults: [] }; } handleChange = (event) => { var newState = {}; newState[event.target.id] = event.target.value; this.setState(newState); } handleSubmit = (event) => { event.preventDefault(); console.log("STARTING HELPER"); // search query helpers.runQuery(this.state.term, this.state.location, this.state.limit) .then(data => { this.setState({results: data}); }).then(data => { console.log("SEARCH RESULTS") console.log(this.state.results) }) // trending query helpers.runTrending(this.state.location) .then(data1 => { this.setState({trenResults: data1}); }).then(data1 => { console.log("TRENDING RESULTS") console.log(this.state.trenResults) }) } render(){ return ( <div> <Jumbotron className="form"> <h1 id="logo">Form</h1> <form onSubmit={this.handleSubmit}> <p> What's your name? </p> <input type="text" id="term" className="form-control" value={this.state.term} onChange={this.handleChange} placeholder="foodBomb" required /> {/*} // <br /><br /> // <p> In </p> // <input // type="text" // id="location" // className="form-control" // value={this.state.location} // onChange={this.handleChange} // placeholder="New York, NY" // required // /> // <br /><br /> // <p> Results </p> // <input // type="number" // id="limit" // value={this.state.limit} // className="form-control" // onChange={this.handleChange} // min="1" // max="20" // required // /> // <br /><br /> */} <input type="submit" value="Submit" className="btn btn-lg" /> </form> </Jumbotron> </div> ); } } export default Form <file_sep>import axios from 'axios'; const clientId = "<KEY>"; const clientSecret = "<KEY>"; const helpers = { runQuery: (query, location, limit) => { console.log(query); console.log(location); console.log(limit); const queryURL = `https://api.foursquare.com/v2/venues/search?v=20161016&near=${location}&limit=${limit}&query=${query}&intent=checkin&client_id=${clientId}&client_secret=${clientSecret}` return axios.get(queryURL) .then(function(response) { console.log(response.data.response.venues); return response }) }, runTrending: (location) => { console.log(location); const trendURL = `https://api.foursquare.com/v2/venues/trending?v=20131016&near=${location}&limit=5&radius=2000&client_id=${clientId}&client_secret=${clientSecret}` // console.log(trendURL) return axios.get(trendURL) .then(function(response) { console.log(response.data.response.venues); return response }) }, runExplore: (location) => { console.log(location); const exploreURL = `https://api.foursquare.com/v2/venues/explore?v=20131016&near=${location}&section=food&client_id=${clientId}&client_secret=${clientSecret}` return axios.get(exploreURL) .then(function(response) { console.log("full explore array"); console.log(response); return response; }) }, runVenue: (query, location) => { console.log(query); console.log(location); const venueURL = `https://api.foursquare.com/v2/venues/search?v=20161016&near=${location}&limit=1&query=${query}&intent=checkin&client_id=${clientId}&client_secret=${clientSecret}` return axios.get(venueURL) .then(function(response) { console.log(response.data.response.venues); return response }) }, runID: (id) => { console.log(id); const idURL = `https://api.foursquare.com/v2/venues/${id}?v=20131016&client_id=${clientId}&client_secret=${clientSecret}` return axios.get(idURL) .then(function(response) { console.log("HELPER RESPONSE ID") console.log(response) return response }) }, } export default helpers;
321adf000eda742351a06b920193c9197ccf2bb0
[ "JavaScript" ]
2
JavaScript
eXo5/flashbomb
3d511921283158e47d4fc7898df1c12fe0b1e50a
8eb6e15e8d4619a1bf178f8f2ce221d714346705
refs/heads/master
<file_sep>#!/usr/bin/env python #coding=utf-8 BTC_PRICE = 45000 BTC_PER_HASH = 0.0000339 HASH_RATE = 7.5 round_cycle = 13 hard = 0.93 KW = 1.2 electric = 0.3 fee = KW * 24 * 13 * electric def easy_mode(): daily_earn = BTC_PER_HASH * HASH_RATE * BTC_PRICE daily_cost = KW * 24 * electric print('daily_earn: {}'.format(daily_earn)) print('daily_cost: {}'.format(daily_cost)) print('real_earn: {}'.format(daily_earn - daily_cost)) def range_mode(): earn = 0 cost = 0 for i in range(0, 100): round_mine = BTC_PER_HASH * HASH_RATE * round_cycle * (hard ** i) earn += round_mine cost += fee earn -= fee/float(BTC_PRICE) if round_mine <= fee/float(BTC_PRICE): print('{} month'.format(round(i*13/30.0, 5))) break if i == 99: print('{} month'.format(round(i*13/30.0, 5))) print('round: {}, earn: {}, money: {}, total: {}'.format( i+1, round(earn, 5), round(round_mine*BTC_PRICE, 5), round(earn*BTC_PRICE, 3))) print('earn: {} cost: {}'.format(round(earn, 5), round(cost, 5))) def main(): range_mode() easy_mode() if __name__ == '__main__': main() <file_sep> LTC_PRICE = 780 LTC_PER_HASH = 0.00004781 HASH_RATE = 220 round = 3 hard = 0.97 KW = 2 fee = KW * 24 * 3 * 0.25/float(LTC_PRICE) earn = 0 for i in range(0, 300): round_mine = LTC_PER_HASH * HASH_RATE * round * (hard ** i) earn += round_mine earn -= fee if round_mine <= fee: print str(i*3/30.0) + 'month' break print str(i + 1), str(earn), str(round_mine * LTC_PRICE), str(earn * LTC_PRICE)
7c0eca6d002d9422da183f58a74a865f148b6d9b
[ "Python" ]
2
Python
greatshi/mining_compute
44185102364cea8ce50717722814b57dcc3f9069
abf51cb431da945d347c4be49f4993317d8f526e
refs/heads/master
<repo_name>andigreen/WhatsThatFoodApp<file_sep>/app/src/main/java/com/wtf/whatsthatfoodapp/auth/EmailLoginActivity.java package com.wtf.whatsthatfoodapp.auth; import android.content.Intent; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.wtf.whatsthatfoodapp.BasicActivity; import com.wtf.whatsthatfoodapp.R; import com.wtf.whatsthatfoodapp.memory.CollageActivity; public class EmailLoginActivity extends BasicActivity { private final String TAG = EmailLoginActivity.class.getSimpleName(); private static final int REQ_RECOVERY = 2899; private static final int REQ_REGISTER = 9293; private EditText emailField; private EditText passwordField; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; private FirebaseUser user; Intent displayHomePage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_email_login); Button email_btn = (Button) findViewById(R.id.email_button); emailField = (EditText) findViewById(R.id.emailfield); passwordField = (EditText) findViewById(R.id.passwordfield); Button register_btn = (Button) findViewById(R.id.Register_btn); Button password_recover = (Button) findViewById(R.id.password_recover); email_btn.setOnClickListener(this); register_btn.setOnClickListener(this); password_recover.setOnClickListener(this); displayHomePage = new Intent(this, CollageActivity.class); // [START initialize_auth] mAuth = FirebaseAuth.getInstance(); // [END initialize_auth] user = mAuth.getCurrentUser(); // [START auth_state_listener] if (user != null && (BasicActivity.getProvider().equals("Facebook") || BasicActivity.getProvider().equals("Google"))) { startActivity(displayHomePage); } mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null && user.isEmailVerified()) { // User is signed in startActivity(displayHomePage); } } }; // [END auth_state_listener] } private void EmailSignIn(String email, String password) { if (!validateForm()) { return; } showProgressDialog(); // [START sign_in_with_email] mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { user = mAuth.getCurrentUser(); if (task.isSuccessful()) { if (user.isEmailVerified()) { startActivity(displayHomePage); } else { Toast.makeText(EmailLoginActivity.this, "Please verify your email", Toast.LENGTH_SHORT).show(); // [START_EXCLUDE] hideProgressDialog(); // [END_EXCLUDE] } } // If sign in fails, display a message to the // user. If sign in succeeds // the auth state listener will be notified // and logic to handle the // signed in user can be handled in the // listener. if (!task.isSuccessful()) { Toast.makeText(EmailLoginActivity.this, R.string.auth_failed, Toast.LENGTH_SHORT).show(); // [START_EXCLUDE] hideProgressDialog(); // [END_EXCLUDE] } } }); // [END sign_in_with_email] } private boolean validateForm() { boolean valid = true; String email = this.emailField.getText().toString(); if (TextUtils.isEmpty(email)) { this.emailField.setError("Required."); valid = false; } else { this.emailField.setError(null); } String password = this.passwordField.getText().toString(); if (TextUtils.isEmpty(password)) { this.passwordField.setError("Required."); valid = false; } else if (password.length() < 6) { this.passwordField.setError( "Password should be longer than 6 characters"); } else { this.passwordField.setError(null); } return valid; } // [START on_start_add_listener] @Override public void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); } // [END on_start_add_listener] // [START on_stop_remove_listener] @Override public void onStop() { super.onStop(); if (mAuthListener != null) { mAuth.removeAuthStateListener(mAuthListener); } } // [END on_stop_remove_listener] @Override public void onClick(View v) { int i = v.getId(); if (i == R.id.Register_btn) { Intent toSignupPage = new Intent(EmailLoginActivity.this, CreateAccountActivity.class); startActivityForResult(toSignupPage, REQ_REGISTER); } else if (i == R.id.email_button) { EmailSignIn(emailField.getText().toString(), passwordField.getText().toString()); } else if (i == R.id.password_recover) { Intent toRecoveryPage = new Intent(EmailLoginActivity.this, PasswordRecoveryActivity.class); toRecoveryPage.putExtra(PasswordRecoveryActivity.EMAIL_KEY, emailField.getText().toString()); startActivityForResult(toRecoveryPage, REQ_RECOVERY); } } // [START onactivityresult] @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQ_RECOVERY && resultCode == RESULT_OK) { Snackbar .make(findViewById(android.R.id.content), R.string.reset_password_sent, Snackbar.LENGTH_INDEFINITE) .setAction("DISMISS", new View.OnClickListener() { @Override public void onClick(View v) { // Implicit dimissal } }).show(); }else if(requestCode == REQ_REGISTER && resultCode == RESULT_OK) { Snackbar .make(findViewById(android.R.id.content), R.string.email_verification_sent, Snackbar.LENGTH_INDEFINITE) .setAction("DISMISS", new View.OnClickListener() { @Override public void onClick(View v) { // Implicit dimissal } }).show(); } } } <file_sep>/app/src/main/java/com/wtf/whatsthatfoodapp/memory/CollageActivity.java package com.wtf.whatsthatfoodapp.memory; import android.Manifest; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.content.ContextCompat; import android.support.v4.content.FileProvider; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.getbase.floatingactionbutton.FloatingActionButton; import com.getbase.floatingactionbutton.FloatingActionsMenu; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.UploadTask; import com.wtf.whatsthatfoodapp.App; import com.wtf.whatsthatfoodapp.BasicActivity; import com.wtf.whatsthatfoodapp.PairsMemoryGameActivity; import com.wtf.whatsthatfoodapp.R; import com.wtf.whatsthatfoodapp.auth.AuthUtils; import com.wtf.whatsthatfoodapp.auth.LogoutActivity; import com.wtf.whatsthatfoodapp.auth.MainActivity; import com.wtf.whatsthatfoodapp.auth.SettingsActivity; import com.wtf.whatsthatfoodapp.notification.ViewNotificationsActivity; import com.wtf.whatsthatfoodapp.search.SearchActivity; import com.wtf.whatsthatfoodapp.user.UserSettings; import com.wtf.whatsthatfoodapp.user.UserSettingsDao; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import de.hdodenhof.circleimageview.CircleImageView; public class CollageActivity extends BasicActivity implements NavigationView .OnNavigationItemSelectedListener { public static final String REMINDERS_COUNT = "REMINDERS_COUNT"; public static final int REQUEST_PERMISSIONS = 123; private static final String TAG = CollageActivity.class.getSimpleName(); private static final int REQUEST_IMAGE_GALLERY = 4843; private static final int REQUEST_IMAGE_CAMERA = 9924; private static final int GALLERY = 1; private Uri imageUri; private FloatingActionsMenu createMenu; private MemoryDao dao; private ActionBarDrawerToggle drawerToggle; private CircleImageView photo_button; private Menu menu; private TextView noMemories; private UserSettingsDao userDao; private FirebaseAuth mAuth; private FirebaseUser user; private ListAdapter collageListAdapter; @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_PERMISSIONS: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { } else { Toast.makeText(this,"What's That Food needs permissions to be accepted", Toast.LENGTH_SHORT).show(); } return; } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_collage); // Set up toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp); NavigationView nav_view = (NavigationView) findViewById(R.id.nav_view); View nav_header = nav_view.getHeaderView(0); setSupportActionBar(toolbar); mAuth = FirebaseAuth.getInstance(); user = mAuth.getCurrentUser(); drawerToggle = setupDrawerToggle(); if (BasicActivity.getProvider().equals("Google")) { App app = (App) getApplicationContext(); // Configure Google Sign In GoogleSignInOptions gso = new GoogleSignInOptions.Builder( GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); // [END config_signin] app.setGso(gso); GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, app.getGso()) .build(); app.setClient(mGoogleApiClient); app.getClient().connect(); } photo_button = (CircleImageView) (nav_header.findViewById( R.id.profile_photo)); photo_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), GALLERY); } }); final TextView nav_name = (TextView) nav_view.getHeaderView(0) .findViewById(R.id.profile_name); nav_view.setNavigationItemSelectedListener(this); ValueEventListener nameListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { UserSettings userInfo = dataSnapshot.getValue( UserSettings.class); if (userInfo != null) { nav_name.setText(userInfo.getUsername()); } } @Override public void onCancelled(DatabaseError databaseError) { } }; userDao = new UserSettingsDao(AuthUtils.getUserUid()); userDao.getUserInfoRef().addValueEventListener(nameListener); userDao.getPhotoRef().getDownloadUrl().addOnSuccessListener( new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { Glide.with(CollageActivity.this) .load(uri) .centerCrop() .dontAnimate() // required by CircleImageView .into(photo_button); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Glide.with(CollageActivity.this) .load(user.getPhotoUrl()) .centerCrop() .dontAnimate() // required by CircleImageView .into(photo_button); } }); // Set up list and adapter dao = new MemoryDao(this); collageListAdapter = new MemoryAdapter(this, Memory.class, dao.getMemoriesRef().orderByChild(Memory.TS_KEY_NEWEST), dao); final ListView collageList = (ListView) findViewById(R.id.collage_list); collageList.setAdapter(collageListAdapter); collageList.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Memory memory = (Memory) collageList .getItemAtPosition(position); Intent viewMemory = new Intent(view.getContext(), ViewMemoryActivity.class); viewMemory.putExtra(ViewMemoryActivity.MEMORY_KEY, memory); startActivity(viewMemory); } }); // Set up buttons createMenu = (FloatingActionsMenu) findViewById( R.id.collage_create_menu); FloatingActionButton cameraButton = (FloatingActionButton) findViewById( R.id.collage_create_camera); FloatingActionButton galleryButton = (FloatingActionButton) findViewById(R.id.collage_create_gallery); cameraButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageFromCamera(); } }); galleryButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageFromGallery(); } }); // Set up "no memories" element noMemories = (TextView) findViewById(R.id.collage_no_memories); dao.getMemoriesRef().addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { noMemories.setVisibility(dataSnapshot.hasChildren() ? View.GONE : View.VISIBLE); } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggles drawerToggle.onConfigurationChanged(newConfig); } /** * Opens the native camera UI to get an image. */ private void imageFromCamera() { if (Build.VERSION.SDK_INT >= 23) { int permissionWriteExternalCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); int permissionCameraCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA); if (permissionWriteExternalCheck == PackageManager.PERMISSION_DENIED || permissionCameraCheck == PackageManager.PERMISSION_DENIED){ requestPermissions( new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, REQUEST_PERMISSIONS); return; } } Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (intent.resolveActivity(getPackageManager()) == null) return; @SuppressLint("SimpleDateFormat") String ts = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); File imageFile; try { imageFile = File.createTempFile("WTF_" + ts, ".jpg", storageDir); } catch (IOException e) { Log.e(TAG, "Could not create image file."); return; } imageUri = FileProvider.getUriForFile(this, "com.wtf.whatsthatfoodapp.fileprovider", imageFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, REQUEST_IMAGE_CAMERA); } /** * Opens the native image gallery to get an image. */ private void imageFromGallery() { if (Build.VERSION.SDK_INT >= 23) { int permissionWriteExternalCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); int permissionCameraCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA); if (permissionWriteExternalCheck == PackageManager.PERMISSION_DENIED || permissionCameraCheck == PackageManager.PERMISSION_DENIED){ requestPermissions( new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, REQUEST_PERMISSIONS); return; } } Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, null), REQUEST_IMAGE_GALLERY); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Send image URI from camera to CreateMemoryActivity if (requestCode == REQUEST_IMAGE_CAMERA && resultCode == RESULT_OK) { Intent createMemory = new Intent(this, CreateMemoryActivity.class); createMemory.putExtra(CreateMemoryActivity.IMAGE_URI_KEY, imageUri); startActivity(createMemory); } // Send image URI from gallery to CreateMemoryActivity if (requestCode == REQUEST_IMAGE_GALLERY && resultCode == RESULT_OK) { Intent createMemory = new Intent(this, CreateMemoryActivity.class); createMemory.putExtra(CreateMemoryActivity.IMAGE_URI_KEY, data.getData()); startActivity(createMemory); } // require photo from GALLERY if (requestCode == GALLERY && resultCode != 0) { Uri photoUri = data.getData(); Glide.with(this).load(photoUri).dontAnimate().into(photo_button); UploadTask uploadTask = userDao.getPhotoRef().putFile(photoUri); uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast error = Toast.makeText(getApplicationContext(), "Photo upload failed. We'll try again later.", Toast.LENGTH_SHORT); error.show(); } }); } super.onActivityResult(requestCode, resultCode, data); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); this.menu = menu; inflater.inflate(R.menu.main_menu, menu); new Handler().post(new Runnable() { @Override public void run() { final View v = findViewById(R.id.collage_search); if (v != null) { v.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { Intent gameIntent = new Intent( getApplicationContext(), PairsMemoryGameActivity.class); startActivity(gameIntent); return true; } }); } } }); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection int item_id = item.getItemId(); if (item_id == R.id.collage_search) { Intent searchIntent = new Intent(this, SearchActivity.class); startActivity(searchIntent); return true; } else if (drawerToggle.onOptionsItemSelected(item)) { return true; } else if (item_id == R.id.nav_notifications) { Intent notificationsIntent = new Intent(this, ViewNotificationsActivity.class); startActivity(notificationsIntent); return true; } //default return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); createMenu.collapseImmediately(); } // [START on_stop_remove_listener] @Override public void onStop() { super.onStop(); } // [END on_stop_remove_listener] private void viewSettings() { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show(); } private ActionBarDrawerToggle setupDrawerToggle() { // NOTE: Make sure you pass in a valid toolbar reference. // ActionBarDrawToggle() does not require it // and will not render the hamburger icon without it. return new ActionBarDrawerToggle(this, (DrawerLayout) findViewById(R.id.activity_collage), (Toolbar) findViewById(R.id.toolbar), R.string.drawer_open, R.string.drawer_close); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.nav_name: changeNameDialog(); break; case R.id.nav_notifications: Intent notificationsIntent = new Intent(this, ViewNotificationsActivity.class); startActivity(notificationsIntent); return true; case R.id.nav_logout: Intent intent = new Intent(this, LogoutActivity.class); startActivity(intent); return true; case R.id.nav_settings: viewSettings(); } return false; } /** * Displays a dialog allowing the user to change their profile name. */ private void changeNameDialog() { View v = getLayoutInflater().inflate(R.layout.dialog_change_name, null); final EditText nameEdit = (EditText) v.findViewById( R.id.change_name_text); DatabaseReference userRef = userDao.getUserInfoRef(); userRef.child("username").addListenerForSingleValueEvent( new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { nameEdit.setText(dataSnapshot.getValue().toString()); nameEdit.setSelection(nameEdit.length()); } @Override public void onCancelled(DatabaseError databaseError) { } }); new AlertDialog.Builder(this) .setTitle("Change name to") .setView(v) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { userDao.getUserInfoRef().child("username").setValue( nameEdit.getText().toString()); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } private void exitApp() { Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(MainActivity.EXIT_KEY, true); startActivity(intent); } @Override public void onBackPressed() { new AlertDialog.Builder(this) .setMessage("Are you sure you want to exit?") .setPositiveButton("Exit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int w) { exitApp(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int w) { d.dismiss(); } }) .show(); } } <file_sep>/app/src/main/java/com/wtf/whatsthatfoodapp/memory/ViewMemoryActivity.java package com.wtf.whatsthatfoodapp.memory; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.PendingIntent; import android.app.TimePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.format.DateFormat; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.wtf.whatsthatfoodapp.R; import com.wtf.whatsthatfoodapp.notification.AlarmReceiver; import com.wtf.whatsthatfoodapp.TextUtil; import com.wtf.whatsthatfoodapp.share.ShareActivity; import net.opacapp.multilinecollapsingtoolbar.CollapsingToolbarLayout; import org.w3c.dom.Text; import java.text.SimpleDateFormat; import java.util.Calendar; import static com.wtf.whatsthatfoodapp.memory.CreateMemoryActivity.PREFS; public class ViewMemoryActivity extends AppCompatActivity { public static final String MEMORY_KEY = "memory"; private static final String TAG = ViewMemoryActivity.class.getSimpleName(); private static final int REQ_EDIT = 3936; private static final int REQ_SHARE = 3937; private MemoryDao dao; private Memory memory; private ImageView image; private CollapsingToolbarLayout title; private Toolbar toolbar; private TextView loc; private TextView desc; private RatingBar rating; private RatingBar price; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_memory); dao = new MemoryDao(this); memory = getIntent().getExtras().getParcelable(MEMORY_KEY); image = (ImageView) findViewById(R.id.view_memory_image); dao.loadImage(memory).centerCrop().into(image); image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ViewMemoryActivity.this, FullImageActivity.class); intent.putExtra(FullImageActivity.MEMORY_KEY, memory); startActivity(intent); } }); // Set up collapsing toolbar toolbar = (Toolbar) findViewById(R.id.view_memory_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); title = (CollapsingToolbarLayout) findViewById( R.id.view_memory_collapsing_toolbar); // Set up share FAB findViewById(R.id.view_memory_edit).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent shareIntent = new Intent(ViewMemoryActivity.this, ShareActivity.class); shareIntent.putExtra(ShareActivity.MEMORY_KEY, memory); startActivityForResult(shareIntent, REQ_SHARE); } }); loc = (TextView) findViewById(R.id.view_memory_loc); desc = (TextView) findViewById(R.id.view_memory_desc); rating = (RatingBar) findViewById(R.id.view_memory_rating); price = (RatingBar) findViewById(R.id.view_memory_price); populateFields(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQ_EDIT && resultCode == RESULT_OK) { memory = data.getParcelableExtra(EditMemoryActivity.MEMORY_KEY); populateFields(); } if (requestCode == REQ_SHARE && resultCode == ShareActivity .RESULT_FAILED) { Snackbar.make(findViewById(android.R.id.content), R.string .share_loading_failed, Snackbar.LENGTH_LONG).show(); } super.onActivityResult(requestCode, resultCode, data); } private void populateFields() { title.setTitle(memory.getTitle()); loc.setText(memory.getLoc()); String memoryDesc = memory.getDescription(); setDescVisible(!(memoryDesc == null || memoryDesc.isEmpty())); desc.setText(memoryDesc); TextUtil.linkifyTags(desc); int ratingVal = memory.getRate(); int priceVal = memory.getPrice(); setRatingsVisible(ratingVal != 0, priceVal != 0); rating.setRating(ratingVal); price.setRating(priceVal); setAlarmVisible(memory.getSavedForNextTime()); } private void setAlarmVisible(boolean visible){ if (visible){ SharedPreferences sf = getSharedPreferences(PREFS, Context.MODE_PRIVATE); TextView tv = (TextView) findViewById(R.id.time_tv); tv.setText(tv.getText() + " " + sf.getString(String.valueOf(memory.getTsCreatedNeg()), "")); tv.setVisibility(View.VISIBLE); } } private void setDescVisible(boolean visible) { int vis = visible ? View.VISIBLE : View.GONE; findViewById(R.id.view_memory_desc_div).setVisibility(vis); findViewById(R.id.view_memory_desc).setVisibility(vis); } private void setRatingsVisible(boolean rating, boolean price) { findViewById(R.id.view_memory_rating).setVisibility( rating ? View.VISIBLE : View.GONE); findViewById(R.id.view_memory_price).setVisibility( price ? View.VISIBLE : View.GONE); findViewById(R.id.view_memory_rating_div).setVisibility( (rating && price) ? View.VISIBLE : View.GONE); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Load Alternative Menu (with alarm buttons) if (memory.getSavedForNextTime()) { getMenuInflater().inflate(R.menu.menu_view_memory_sfnt, menu); } else { getMenuInflater().inflate(R.menu.menu_view_memory, menu); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; case R.id.remove_alarm: removeAlarm(); finish(); break; case R.id.edit_alarm: editAlarm(); break; case R.id.view_memory_edit: Intent editIntent = new Intent(this, EditMemoryActivity.class); editIntent.putExtra(EditMemoryActivity.MEMORY_KEY, memory); startActivityForResult(editIntent, REQ_EDIT); break; case R.id.view_memory_delete: AlertDialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.dialog_delete_memory_title); builder.setMessage(R.string.dialog_delete_memory_message); builder.setPositiveButton(R.string.dialog_delete_pos, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (memory.getSavedForNextTime()){ removeAlarm(); } dao.deleteMemory(memory); finish(); } }); builder.setNegativeButton(R.string.dialog_delete_neg, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); dialog = builder.create(); dialog.show(); } return super.onOptionsItemSelected(item); } public void removeAlarm() { memory.setSavedForNextTime(false); dao.writeMemory(memory); SharedPreferences sp = getSharedPreferences(PREFS, Context.MODE_PRIVATE); int requestCode = sp.getInt((String.valueOf(memory.getTsCreated())), 0); if (requestCode == 0) { return; } SharedPreferences.Editor editor = getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit(); editor.putInt(CollageActivity.REMINDERS_COUNT, sp.getInt(CollageActivity.REMINDERS_COUNT, 1) - 1); editor.apply(); AlarmManager alarmManager = (AlarmManager) getSystemService( Context.ALARM_SERVICE); Intent intentAlarm = new Intent(this, AlarmReceiver.class); Bundle bundle = new Bundle(); bundle.putParcelable(EditMemoryActivity.MEMORY_KEY, memory); intentAlarm.putExtra("bundle", bundle); alarmManager.cancel( PendingIntent.getBroadcast(this, requestCode, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT)); } public void editAlarm() { Calendar calendar = Calendar.getInstance(); new TimePickerDialog( this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.MINUTE, minute); SimpleDateFormat sdf = new SimpleDateFormat("H:mm"); SharedPreferences sp = getSharedPreferences(PREFS, Context.MODE_PRIVATE); int requestCode = sp.getInt( (String.valueOf(memory.getTsCreated())), 0); if (requestCode == 0) { return; } AlarmManager alarmManager = (AlarmManager) getSystemService( Context.ALARM_SERVICE); Intent intentAlarm = new Intent(getApplicationContext(), AlarmReceiver.class); Bundle bundle = new Bundle(); bundle.putParcelable(EditMemoryActivity.MEMORY_KEY, memory); intentAlarm.putExtra("bundle", bundle); PendingIntent pendingIntent = PendingIntent.getBroadcast( getApplicationContext(), requestCode, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); // Save the alarm request code so it can be accessed and // cancelled after SharedPreferences.Editor editor = getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit(); editor.putInt(String.valueOf(memory.getTsCreated()), requestCode); editor.putString(String.valueOf(memory.getTsCreatedNeg()), sdf.format(calendar.getTime())); editor.apply(); finish(); } }, calendar.get(Calendar.HOUR_OF_DAY) + 2, calendar.get(Calendar.MINUTE), DateFormat.is24HourFormat(this)).show(); } public void showInMap(View v) { Uri uri = Uri.parse("geo:0,0?q=" + Uri.encode(memory.getLoc())); Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri); mapIntent.setPackage("com.google.android.apps.maps"); startActivity(mapIntent); } private float[] convertLocToCoordinates(String loc) { float[] coordinates = new float[2]; String[] sCoordinates = loc.split(" "); String degrees = "°"; String minutes = "'"; String[] sDegrees = sCoordinates[0].split(degrees); float longitude = Float.valueOf(sDegrees[0]); longitude += Float.valueOf(sDegrees[1].split(minutes)[0]) / 60; String[] s2Degrees = sCoordinates[1].split(degrees); float latitude = Float.valueOf(s2Degrees[0]); latitude += Float.valueOf(s2Degrees[1].split(minutes)[0]) / 60; coordinates[0] = longitude; coordinates[1] = latitude; return coordinates; } } <file_sep>/app/src/main/java/com/wtf/whatsthatfoodapp/memory/EditMemoryActivity.java package com.wtf.whatsthatfoodapp.memory; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import android.widget.Toast; import com.wtf.whatsthatfoodapp.BasicActivity; import com.wtf.whatsthatfoodapp.R; import com.wtf.whatsthatfoodapp.notification.AlarmReceiver; public class EditMemoryActivity extends BasicActivity { public static final String MEMORY_KEY = "memory"; public static final String NOTIFICATION = "notification"; private static final String TAG = EditMemoryActivity.class.getSimpleName(); private MemoryDao dao; private Memory memory; private MemoryFormFragment form; private boolean fromNotification; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_memory); dao = new MemoryDao(this); memory = getIntent().getParcelableExtra(MEMORY_KEY); fromNotification = getIntent().getBooleanExtra(NOTIFICATION,false); // Set up toolbar Toolbar toolbar = (Toolbar) findViewById( R.id.edit_memory_toolbar); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); } // Set up form fragment form = MemoryFormFragment.newInstance(memory, new MemoryFormFragment.ImageListener() { @Override public void onImageReady(ImageView view) { // Load photo view dao.loadImage(memory) .centerCrop() .into(view); } }); getFragmentManager().beginTransaction().replace(R.id.edit_memory_form, form).commit(); } private boolean saveMemory() { if (form.validateAndSaveInto(memory)) { memory.setSavedForNextTime(false); dao.writeMemory(memory); return true; } return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_edit_memory, menu); return true; } @Override public void onBackPressed() { form.confirmDiscard(new MemoryFormFragment.ConfirmDiscardListener() { @Override public void onPositive() { setResult(RESULT_CANCELED); EditMemoryActivity.super.onBackPressed(); } @Override public void onNegative() { } }); } private MemoryFormFragment.ConfirmDiscardListener confirmDiscardListener = new MemoryFormFragment.ConfirmDiscardListener() { @Override public void onPositive() { setResult(RESULT_CANCELED); finish(); } @Override public void onNegative() { } }; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Back to collage case android.R.id.home: form.confirmDiscard(confirmDiscardListener); return true; // Start location picker case R.id.edit_memory_getloc: form.createPlacePicker(); return true; // Save new memory case R.id.edit_memory_save: if (fromNotification){ dao.memoryExists(memory, new MemoryDao.MemoryExistsListener() { @Override public void onResult(boolean exists) { if (!exists) { Toast.makeText(getApplicationContext(),"Memory does not exist", Toast.LENGTH_SHORT).show(); finish(); return; } // Do whatever if the memory exists memory.setSavedForNextTime(false); if (saveMemory()) { Intent result = new Intent(); result.putExtra(MEMORY_KEY, memory); setResult(RESULT_OK, result); finish(); } } }); } else { memory.setSavedForNextTime(false); if (saveMemory()) { Intent result = new Intent(); result.putExtra(MEMORY_KEY, memory); setResult(RESULT_OK, result); finish(); } } return true; } // Other options not handled return super.onOptionsItemSelected(item); } } <file_sep>/app/src/main/java/com/wtf/whatsthatfoodapp/memory/MemoryFormFragment.java package com.wtf.whatsthatfoodapp.memory; import android.app.AlertDialog; import android.app.Fragment; import android.content.DialogInterface; import android.content.Intent; import android.media.Image; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.RatingBar; import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.ui.PlacePicker; import com.wtf.whatsthatfoodapp.R; import static android.app.Activity.RESULT_OK; public class MemoryFormFragment extends Fragment { public static final String ARG_MEMORY = "memory"; private static final String TAG = MemoryFormFragment.class.getSimpleName(); private static final int PLACE_PICKER_REQUEST = 200; private ImageListener imageListener; private boolean changesMade = false; private ImageView image; private EditText titleText; private EditText locText; private EditText descText; private RatingBar ratingRating; private RatingBar priceRating; private TextInputLayout titleWrapper; private TextInputLayout locWrapper; public MemoryFormFragment() { } public static MemoryFormFragment newInstance(Memory memory) { MemoryFormFragment fragment = new MemoryFormFragment(); Bundle args = new Bundle(); args.putParcelable(ARG_MEMORY, memory); fragment.setArguments(args); return fragment; } public static MemoryFormFragment newInstance(Memory memory, ImageListener imageListener) { MemoryFormFragment fragment = newInstance(memory); fragment.imageListener = imageListener; return fragment; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); AppCompatActivity a = (AppCompatActivity) getActivity(); super.onCreate(savedInstanceState); Memory memory; if (getArguments() != null) { memory = getArguments().getParcelable(ARG_MEMORY); } else { return; } titleText = (EditText) a.findViewById(R.id.memory_form_title); locText = (EditText) a.findViewById(R.id.memory_form_loc); descText = (EditText) a.findViewById(R.id.memory_form_desc); ratingRating = (RatingBar) a.findViewById(R.id.memory_form_rating); priceRating = (RatingBar) a.findViewById(R.id.memory_form_price); titleText.setText(memory.getTitle()); locText.setText(memory.getLoc()); descText.setText(memory.getDescription()); ratingRating.setRating(memory.getRate()); priceRating.setRating(memory.getPrice()); // Set appropriate focus if (titleText.getText().length() != 0) { descText.requestFocus(); descText.setSelection(descText.getText().length()); } // Clear errors whenever text changes titleWrapper = (TextInputLayout) a.findViewById( R.id.memory_form_title_wrapper); locWrapper = (TextInputLayout) a.findViewById( R.id.memory_form_loc_wrapper); titleWrapper.setErrorEnabled(false); locWrapper.setErrorEnabled(false); titleText.addTextChangedListener( new ErrorClearTextWatcher(titleWrapper)); locText.addTextChangedListener(new ErrorClearTextWatcher(locWrapper)); // Track whenever changes are made AnyChangeListener changeListener = new AnyChangeListener(); titleText.addTextChangedListener(changeListener); locText.addTextChangedListener(changeListener); descText.addTextChangedListener(changeListener); ratingRating.setOnRatingBarChangeListener(changeListener); priceRating.setOnRatingBarChangeListener(changeListener); } public boolean validateAndSaveInto(Memory memory) { if (!validateForm()) return false; // Write memory fields memory.setTitle(titleText.getText().toString()); memory.setLoc(locText.getText().toString()); memory.setDescription(descText.getText().toString()); memory.setTag(descText.getText().toString()); memory.setRate((int) ratingRating.getRating()); memory.setPrice((int) priceRating.getRating()); return true; } /** * Callback interface for the "Discard changes?" dialog (see * confirmDiscard). */ public interface ConfirmDiscardListener { void onPositive(); void onNegative(); } /** * If changes were made to the form fields, shows the user a dialog to * confirm whether they would like to discard those changes. Calls the * corresponding callbacks of the given {@link ConfirmDiscardListener}. * their input. If no changes were made, calls onPositive(). */ public void confirmDiscard(final ConfirmDiscardListener listener) { if (!changesMade) { listener.onPositive(); return; } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(R.string.memory_form_discard); builder.setPositiveButton(R.string.memory_form_discard_pos, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { listener.onPositive(); } }); builder.setNegativeButton(R.string.memory_form_discard_neg, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { listener.onNegative(); } }); builder.create().show(); } public interface ImageListener { void onImageReady(ImageView view); } /** * A simple listener which sets changesMade to true anytime a form * element's value is modified. */ private class AnyChangeListener implements TextWatcher, RatingBar.OnRatingBarChangeListener { @Override public void afterTextChanged(Editable s) { changesMade = true; } @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { changesMade = true; } // Unused methods @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } } private class ErrorClearTextWatcher implements TextWatcher { private TextInputLayout layout; ErrorClearTextWatcher(TextInputLayout layout) { this.layout = layout; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { layout.setErrorEnabled(false); } } /** * Returns true if all of the form contents are valid, and also updates * the error status of form contents. * <p> * Currently, the form only requires that title and loc are both nonempty. */ private boolean validateForm() { String title = titleText.getText().toString(); String loc = locText.getText().toString(); boolean valid = true; if (title.isEmpty()) { titleWrapper.setError("Please enter a title."); valid = false; } else titleWrapper.setErrorEnabled(false); if (loc.isEmpty()) { locWrapper.setError("Please enter a location."); valid = false; } else locWrapper.setErrorEnabled(false); return valid; } public void createPlacePicker() { PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder(); try { startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST); } catch (GooglePlayServicesRepairableException e) { e.printStackTrace(); } catch (GooglePlayServicesNotAvailableException e) { e.printStackTrace(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK) { Place place = PlacePicker.getPlace(getActivity(), data); locText.setText(place.getName()); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_memory_form, container, false); image = (ImageView) view.findViewById(R.id.memory_form_image); if (imageListener != null) { imageListener.onImageReady(image); } return view; } public void setLocation(CharSequence location) { locText.setText(location); } } <file_sep>/app/src/main/java/com/wtf/whatsthatfoodapp/search/SearchUtils.java package com.wtf.whatsthatfoodapp.search; class SearchUtils { /** * Returns a collection of query tokens, none of which contain spaces, * from the given query. */ static String[] getTokens(String query) { return raisePound(query).split("\\s+"); } /** * Returns a string where the every # with word chars following, is * replaced by the symbol ⋕ (a Unicode approximation with codepoint > * 128, so that it is included in tokens by the SQLite FTS "simple" * tokenizer). */ static String raisePound(String str) { return str.replaceAll("#(?=[^\\s]+)", "\u22d5"); } } <file_sep>/app/src/main/java/com/wtf/whatsthatfoodapp/auth/PasswordRecoveryActivity.java package com.wtf.whatsthatfoodapp.auth; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import android.view.View; import android.widget.EditText; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.wtf.whatsthatfoodapp.BasicActivity; import com.wtf.whatsthatfoodapp.R; public class PasswordRecoveryActivity extends BasicActivity { public static final String EMAIL_KEY = "email"; private static final String TAG = PasswordRecoveryActivity.class .getSimpleName(); private FirebaseAuth mAuth; private EditText emailField; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_password_recovery); // [START initialize_auth] mAuth = FirebaseAuth.getInstance(); // [END initialize_auth] findViewById(R.id.recover_btn).setOnClickListener(this); emailField = (EditText) findViewById(R.id.emailfield); emailField.setText(""); String email = getIntent().getStringExtra(EMAIL_KEY); if (email != null) emailField.append(email); } @Override public void onClick(View v) { String email = ((EditText) findViewById(R.id.emailfield)).getText() .toString(); if (email.isEmpty()) return; mAuth.sendPasswordResetEmail(email) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { setResult(RESULT_OK); finish(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Don't show the user anything. This may indicate // that the email doesn't exist, which is exploitable // knowledge. } }); } @Override public void onBackPressed() { setResult(RESULT_CANCELED); super.onBackPressed(); } } <file_sep>/app/src/main/java/com/wtf/whatsthatfoodapp/BasicActivity.java package com.wtf.whatsthatfoodapp; import android.app.ProgressDialog; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.UserInfo; import com.wtf.whatsthatfoodapp.R; public class BasicActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener { public final String TAG = BasicActivity.class.getSimpleName(); @VisibleForTesting public ProgressDialog mProgressDialog; public void showProgressDialog() { if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage(getString(R.string.loading)); mProgressDialog.setIndeterminate(true); } mProgressDialog.show(); } public void hideProgressDialog() { if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } } public static String getProvider() { for (UserInfo user : FirebaseAuth.getInstance().getCurrentUser().getProviderData()) { if (user.getProviderId().equals("facebook.com")) { System.out.println("User is signed in with Facebook"); return "Facebook"; } if (user.getProviderId().equals("google.com")) { System.out.println("User is signed in with Google"); return "Google"; } } return "Firebase"; } // [START on_start_add_listener] @Override public void onStart() { super.onStart(); } // [END on_start_add_listener] // [START on_stop_remove_listener] @Override public void onStop() { super.onStop(); hideProgressDialog(); } // [END on_stop_remove_listener] @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onClick(View v) { } } <file_sep>/app/src/main/java/com/wtf/whatsthatfoodapp/PairsMemoryGameActivity.java package com.wtf.whatsthatfoodapp; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.LinearLayout; import android.widget.RelativeLayout; import java.lang.ref.WeakReference; public class PairsMemoryGameActivity extends Activity { private PairsMemoryGameView gameView; private Handler handler; private AlertDialog alertDialog; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); handler = new MyHandler(this); play(); } private void play(){ RelativeLayout rl = (RelativeLayout) findViewById(R.id.game_top_rl); gameView = new PairsMemoryGameView(this,handler); gameView.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); rl.addView(gameView); } private void displayWinDialog(){ DialogInterface.OnClickListener positiveBtn = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }; AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this).setTitle("Well Done !!!") .setPositiveButton("Menu",positiveBtn).setCancelable(false).setMessage("Credits:\nFood icons made by Madebyoliver and <NAME> from www.flaticon.com"); alertDialog = alertDialogBuilder.create(); alertDialog.show(); } @Override public void onBackPressed(){ // Override to do nothing } private static class MyHandler extends Handler { private final WeakReference<PairsMemoryGameActivity> weakReference; public MyHandler (PairsMemoryGameActivity gameActivity){ weakReference = new WeakReference<>(gameActivity); } @Override public void handleMessage(Message msg){ PairsMemoryGameActivity gameActivity = weakReference.get(); String function = msg.getData().getString("function"); if (function.equals("stop")){ gameActivity.displayWinDialog(); } } } } <file_sep>/README.md # WhatsThatFoodApp To install this app, download `whatsthatfood.apk` from [the releases page](https://github.com/peiranli/WhatsThatFoodApp/releases) and install on your Android device. You may need to check "Unknown sources" in Settings > Security in order to install this app, since it is not obtained from the Google Play Store. <file_sep>/app/src/main/java/com/wtf/whatsthatfoodapp/user/UserSettings.java package com.wtf.whatsthatfoodapp.user; /** * Created by peiranli on 2/20/17. */ public class UserSettings { private String email; private String username; private boolean toAlbum; private String Uid; private String key; public UserSettings() { // Default constructor required for calls to DataSnapshot.getValue(User.class) } public UserSettings(String email,String username, String Uid) { this.email = email; this.username = username; this.toAlbum = true; this.Uid = Uid; this.key = this.Uid; } public String getUid(){ return this.Uid; } public void setUid(String uid){ this.Uid = uid; this.key = this.Uid; } public String getKey(){ return this.key; } public String getEmail(){ return this.email; } public String getUsername() { return this.username; } public void setEmail(String email){ this.email = email; } public void setUsername(String username){ this.username = username; } public boolean isToAlbum() { return this.toAlbum; } public void setToAlbum(boolean toAlbum) { this.toAlbum = toAlbum; } } <file_sep>/app/src/main/java/com/wtf/whatsthatfoodapp/search/FilterDialog.java package com.wtf.whatsthatfoodapp.search; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ArrayAdapter; import android.widget.RatingBar; import android.widget.Spinner; import com.wtf.whatsthatfoodapp.R; import com.wtf.whatsthatfoodapp.search.SearchActivity.FilterMode; import com.wtf.whatsthatfoodapp.search.SearchActivity.SortMode; public class FilterDialog extends DialogFragment { private static final String SORT_MODE = "sortMode"; private static final String RATING_MODE = "ratingMode"; private static final String RATING_VAL = "ratingVal"; private static final String PRICE_MODE = "priceMode"; private static final String PRICE_VAL = "priceVal"; private Spinner sortSpinner; private Spinner ratingSpinner; private RatingBar ratingRating; private Spinner priceSpinner; private RatingBar priceRating; FilterDialogListener listener; static FilterDialog newInstance(SortMode sortMode, FilterMode ratingMode, int ratingVal, FilterMode priceMode, int priceVal) { FilterDialog f = new FilterDialog(); Bundle args = new Bundle(); args.putSerializable(SORT_MODE, sortMode); args.putSerializable(RATING_MODE, ratingMode); args.putInt(RATING_VAL, ratingVal); args.putSerializable(PRICE_MODE, priceMode); args.putInt(PRICE_VAL, priceVal); f.setArguments(args); return f; } interface FilterDialogListener { void onApply(SortMode sortMode, FilterMode ratingMode, int ratingVal, FilterMode priceMode, int priceVal); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Inflate view and get references to view elements LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.activity_filter, null); ratingSpinner = (Spinner) view.findViewById(R.id.filter_rating_spinner); ArrayAdapter<FilterMode> ratingAdapter = new ArrayAdapter<>( getActivity(), R.layout.filter_spinner, FilterMode.values()); ratingSpinner.setAdapter(ratingAdapter); priceSpinner = (Spinner) view.findViewById(R.id.filter_price_spinner); ArrayAdapter<FilterMode> priceAdapter = new ArrayAdapter<>( getActivity(), R.layout.filter_spinner, FilterMode.values()); priceSpinner.setAdapter(priceAdapter); Spinner time_spinner = (Spinner) view.findViewById( R.id.filter_created_spinner); time_spinner.setAdapter(ArrayAdapter.createFromResource(getActivity(), R.array.filter_time, R.layout.filter_spinner)); sortSpinner = (Spinner) view.findViewById(R.id.filter_sort_spinner); ArrayAdapter<SortMode> sortAdapter = new ArrayAdapter<>(getActivity(), R.layout.filter_spinner, SortMode.values()); sortSpinner.setAdapter(sortAdapter); ratingRating = (RatingBar) view.findViewById(R.id.filter_rating_rating); priceRating = (RatingBar) view.findViewById(R.id.filter_price_rating); // Initialize values SortMode sortMode = (SortMode) getArguments().getSerializable( SORT_MODE); FilterMode ratingMode = (FilterMode) getArguments().getSerializable( RATING_MODE); int ratingVal = getArguments().getInt(RATING_VAL); FilterMode priceMode = (FilterMode) getArguments().getSerializable( PRICE_MODE); int priceVal = getArguments().getInt(PRICE_VAL); sortSpinner.setSelection(sortAdapter.getPosition(sortMode)); ratingSpinner.setSelection(ratingAdapter.getPosition(ratingMode)); ratingRating.setRating(ratingVal); priceSpinner.setSelection(priceAdapter.getPosition(priceMode)); priceRating.setRating(priceVal); // Build dialog AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.Dialog); builder.setView(view) .setTitle("Search filters") .setPositiveButton("Apply", applyClickListener) .setNegativeButton("Cancel", cancelClickListener); return builder.create(); } private DialogInterface.OnClickListener applyClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SortMode sortMode = (SortMode) sortSpinner .getSelectedItem(); FilterMode ratingMode = (FilterMode) ratingSpinner .getSelectedItem(); int ratingVal = (int) ratingRating.getRating(); FilterMode priceMode = (FilterMode) priceSpinner .getSelectedItem(); int priceVal = (int) priceRating.getRating(); listener.onApply(sortMode, ratingMode, ratingVal, priceMode, priceVal); } }; private DialogInterface.OnClickListener cancelClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { FilterDialog.this.getDialog().cancel(); } }; @Override public void onAttach(Context context) { super.onAttach(context); try { listener = (FilterDialogListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString() + " must implement " + FilterDialogListener.class.getSimpleName()); } } } <file_sep>/app/src/main/java/com/wtf/whatsthatfoodapp/memory/MemoryAdapter.java package com.wtf.whatsthatfoodapp.memory; import android.app.Activity; import android.util.Log; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.firebase.ui.database.FirebaseListAdapter; import com.firebase.ui.storage.images.FirebaseImageLoader; import com.google.firebase.database.Query; import com.google.firebase.storage.StorageReference; import com.wtf.whatsthatfoodapp.R; import com.wtf.whatsthatfoodapp.notification.ViewNotificationsActivity; public class MemoryAdapter extends FirebaseListAdapter<Memory> { private MemoryDao dao; private Activity activity; public MemoryAdapter(Activity activity, Class<Memory> modelClass, Query query, MemoryDao dao) { super(activity, modelClass, R.layout.memory_list_item, query); this.dao = dao; this.activity = activity; } @Override protected void populateView(View v, Memory model, int position) { TextView viewTitle = (TextView) v.findViewById(R.id .memory_list_item_title); TextView viewLoc = (TextView) v.findViewById(R.id .memory_list_item_loc); ImageView viewImage = (ImageView) v.findViewById(R.id .memory_list_item_image); final ProgressBar progress = (ProgressBar) v.findViewById(R.id .memory_list_item_progress); viewTitle.setText(model.getTitle()); viewLoc.setText(model.getLoc()); // Load photo into view dao.loadImage(model) // Hide progress bar when image is loaded, or error occurs .listener(new RequestListener<StorageReference, GlideDrawable>() { @Override public boolean onException(Exception e, StorageReference model, Target<GlideDrawable> target, boolean isFirstResource) { progress.setVisibility(View.GONE); return false; } @Override public boolean onResourceReady(GlideDrawable resource, StorageReference model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { progress.setVisibility(View.GONE); return false; } }) .centerCrop() .into(viewImage); } }
9fc429950a37a27c970719278d3d7dfd2eb4f943
[ "Markdown", "Java" ]
13
Java
andigreen/WhatsThatFoodApp
b0ab734ba3d43460b012b9c8f9f01265ab763380
0a016de712220ad8964c8226e40336c922d9ce1e
refs/heads/master
<repo_name>KunalBurangi/React-Seed<file_sep>/src/Components/home/redusers/reduser.js import * as types from "../../../utilActions/actionTypes"; const initialState = { UserName: "" }; export default function HomeReducer(state = initialState, action) { debugger; switch (action.type) { case types.USER_NAME: return { UserName: action.payload }; default: return initialState; } }
c24154aca29d49a606b0eb1f253f8395d7edb818
[ "JavaScript" ]
1
JavaScript
KunalBurangi/React-Seed
55f52dfb20ee5149c30f5583bffb1ec8eed2a82a
a011306afab86dd6a2a584201318ee260c66ebc9
refs/heads/master
<repo_name>85020121/Fangxincai<file_sep>/fangxincai/FXCDefine.h // // FXCDefine.h // fangxincai // // Created by <NAME> on 5/11/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #define FXC_SERVER_HEAD @"http://bowen.gao.perso.sfr.fr" #define FXC_PRODUCTS_REQUEST @"http://bowen.gao.perso.sfr.fr/protected/iOS/ios_tools.php?iosRequest=iosGetProducts" #define FXC_PRODUCTS_BY_IDS @"http://bowen.gao.perso.sfr.fr/protected/iOS/ios_tools.php?iosRequest=iosGetProductsByIDs" #define FXC_PRODUCTS_BY_INTERVAL @"http://bowen.gao.perso.sfr.fr/protected/iOS/ios_tools.php?iosRequest=iosGetProductsByInterval" #define REQUEST_PRODUCTS_INTERVAL 15 <file_sep>/README.md Fangxincai ========== <file_sep>/Podfile platform :ios, '6.0' pod 'JSONKit', '~> 1.4' pod 'ECSlidingViewController', '~> 0.10.0' pod 'MBProgressHUD', '~> 0.6' pod 'AFNetworking', '~> 1.2'
b9ce34320863d1de783886bbc9bba8cda6c5fd2a
[ "Markdown", "C", "Ruby" ]
3
C
85020121/Fangxincai
20cea139e45b37c2a61630998ecd11805565678b
0258b0ce662347e71d2a04f9984840ae8f0f10ef
refs/heads/master
<file_sep><?php /* SAML Authentication Plugin Custom Hook This file acts as a hook for the SAML Authentication plugin. The plugin will call the functions defined in this file in certain points in the plugin lifecycle. Use this sample file as a template. You should copy it and not modify it in place since you may lost your changes in future updates. To use this hook you have to go to the config form in the admin interface of Moodle and set the full path to this file. Please note that the default value for such a field is this custom_hook.php file itself. You should not change the name of the funcions since that's the API the plugin expect to exist and to use. Read the comments of each function to discover when they are called and what are they for. */ /* name: saml_hook_attribute_filter arguments: - $saml_attributes: array of SAML attributes return value: - nothing purpose: this function allows you to modify the array of SAML attributes. You can change the values of them (e.g. removing the non desired urn parts) or you can even remove or add attributes on the fly. */ function saml_hook_attribute_filter(&$saml_attributes) { // Nos quedamos sólamente con el DNI dentro del schacPersonalUniqueID if(isset($saml_attributes['schacPersonalUniqueID'])) { foreach($saml_attributes['schacPersonalUniqueID'] as $key => $value) { $data = array(); if(preg_match('/urn:mace:terena.org:schac:personalUniqueID:es:(.*):(.*)/', $value, $data)) { $saml_attributes['schacPersonalUniqueID'][$key] = $data[2]; //DNI sin letra //$saml_attributes['schacPersonalUniqueID'][$key] = substr($value[2], 0, 8); } else { unset($saml_attributes['schacPersonalUniqueID'][$key]); } } } // Pasamos el irisMailMainAddress como mail si no existe if(!isset($saml_attributes['mail'])) { if(!isset($saml_attributes['irisMailMainAddress'])) { $saml_attributes['mail'] = $saml_attributes['irisMailMainAddress']; } } // Pasamos el uid como eduPersonPrincipalName o como eduPersonTargetedID if(!isset($saml_attributes['eduPersonPrincipalName'])) { if(!isset($saml_attributes['uid'])) { $saml_attributes['eduPersonPrincipalName'] = $saml_attributes['uid']; } else if (isset($saml_attributes['eduPersonTargetedID'])) { $saml_attributes['eduPersonPrincipalName'] = $saml_attributes['eduPersonTargetedID']; } else if (isset($saml_attributes['mail'])) { $saml_attributes['eduPersonPrincipalName'] = $saml_attributes['mail']; } } // Pasamos el uid como eduPersonPrincipalName if(!isset($saml_attributes['eduPersonPrincipalName'])) { if(!isset($saml_attributes['uid'])) { $saml_attributes['eduPersonPrincipalName'] = $saml_attributes['uid']; } else if (isset($saml_attributes['mail'])) { $saml_attributes['eduPersonPrincipalName'] = $saml_attributes['mail']; } } } /* name: saml_hook_user_exists arguments: - $username: candidate name of the current user - $saml_attributes: array of SAML attributes - $user_exists: true if the $username exists in Moodle database return value: - true if you consider that this username should exist, false otherwise. purpose: this function let you change the logic by which the plugin thinks the user exists in Moodle. You can even change the username if the user exists but you want to recreate with another name. */ function saml_hook_user_exists(&$username, $saml_attributes, $user_exists) { return true; } /* name: saml_hook_authorize_user arguments: - $username: name of the current user - $saml_attributes: array of SAML attributes - $authorize_user: true if the plugin thinks this user should be allowed return value: - true if the user should be authorized or an error string explaining why the user access should be denied. purpose: use this function to deny the access to the current user based on the value of its attributes or any other reason you want. It is very important that this function return either true or an error message. */ function saml_hook_authorize_user($username, $saml_attributes, $authorize_user) { /* Set the saml attributes to a session variable so we can access them on user creation */ if ($authorize_user) $_SESSION['saml_attributes'] = $saml_attributes; return true; } /* name: saml_hook_post_user_created arguments: - $user: object containing the Moodle user return value: - nothing purpose: use this function if you want to make changes to the user object or update any external system for statistics or something similar. */ function saml_hook_post_user_created($user) { /* Assign the correct role if the email is within the allowed emails list */ $saml_roles = $_SESSION['saml_attributes']['roles']; global $DB; $role_mapping = array(); /* See if any of the saml roles for this user map to any moodle role short names */ for ($i = 0; $i < count($saml_roles); $i++) { if ( $mdl_role = $DB->get_record('role', array('shortname'=>$saml_roles[$i])) ) { array_push($role_mapping, $mdl_role); } } /* Map roles if we found any */ for ($i = 0; $i < count($role_mapping); $i++) { // Find the context level of this role $context = $DB->get_record( 'role_context_levels', array('roleid'=>$role_mapping[$i]->id) ); role_assign($role_mapping[$i]->id, $user->id, $context->contextlevel); } } <file_sep>emailroleassign =============== Lightweight drupal module that allows administrators to set up automated role assignment depending on the user's email domain name. For Drupal 7.x, place the emailroleassign folder in `[drupalinstallation]/sites/all/modules/` and enable the module from the Drupal administrator module configuration page. The configuration page can then be found at `[drupalurl]/admin/config/emailroleassign`. custom_hook.php =============== Custom hook for the simplesaml authentication module for Moodle. Allows the synchronization of drupal roles that have the same Moodle role short name. Upon account creation, the saml roles are checked to see if any equivalent short names exist as a moodle role, if so they are assigned to the new user. The permissions of this role have to be set in Moodle's configuration, as the custom hook is only responsible for assigning the role, not for any role permissions. This file replaces the custom_hook.php file in `[moodle_installation]/auth/saml/custom_hook.php`.
f33b1fa80805940fb7aaf8c9050f1052a87ef062
[ "Markdown", "PHP" ]
2
PHP
craigknott/emailroleassign
ab966a34b785fd128b00c1b925ced0ad2ed3e21a
bd402881dec2f52c57c368832a0769ab22abe8ef
refs/heads/master
<repo_name>TailoMC/KnowNixSystem<file_sep>/src/me/Tailo/KnowNixSystem/Permission/PlayerRecivePermissionEvent_Listener.java package me.Tailo.KnowNixSystem.Permission; import me.Tailo.KnowNixSystem.Permission.Permission_methoden.Group; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerLoginEvent; public class PlayerRecivePermissionEvent_Listener implements Listener { private main plugin; public static boolean recived; public PlayerRecivePermissionEvent_Listener(main main) { this.plugin = main; plugin.getServer().getPluginManager().registerEvents(this, main); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPlayerLogin(PlayerLoginEvent e) { Player p = e.getPlayer(); Group group = Permission_methoden.getGroup(p); Permission_methoden.loadPermissions(p, group); } } <file_sep>/src/me/Tailo/KnowNixSystem/Permission/COMMAND_perm.java package me.Tailo.KnowNixSystem.Permission; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import me.Tailo.KnowNixSystem.Permission.UUIDFetcher; import me.Tailo.KnowNixSystem.Permission.Permission_methoden.Group; import me.Tailo.KnowNixSystem.System.main; public class COMMAND_perm implements CommandExecutor { @SuppressWarnings("unused") private main plugin; public COMMAND_perm(main main) { this.plugin = main; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(sender instanceof ConsoleCommandSender) { if(args.length == 3) { if(args[1].equalsIgnoreCase("setgroup")) { String uuid = UUIDFetcher.getUUID(args[0]).toString(); Group group = Permission_methoden.getGroup(args[2]); Permission_methoden.setGroup(uuid, group); } } } return true; } } <file_sep>/src/me/Tailo/KnowNixSystem/Methoden/Vanish_methoden.java package me.Tailo.KnowNixSystem.Methoden; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import me.Tailo.KnowNixSystem.MySQL.MySQL; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Team; public class Vanish_methoden { private static main plugin; @SuppressWarnings("static-access") public Vanish_methoden(main main) { this.plugin = main; } private static HashMap<Scoreboard, HashMap<Player, Team>> team = new HashMap<>(); public static HashMap<Player, BukkitRunnable> run = new HashMap<>(); private static HashMap<Player, List<Player>> van = new HashMap<>(); public static void vanish(final Player p) { List<Player> vanplayers = new ArrayList<Player>(); for(Player players : Bukkit.getOnlinePlayers()) { if(players.spigot().getHiddenPlayers().contains(p)) { vanplayers.add(players); } if(!players.hasPermission("sup") && !players.hasPermission("content")) { players.hidePlayer(p); } else { Scoreboard board = players.getScoreboard(); Team t = board.getTeam(p.getUniqueId().toString().substring(0, 16)); if(t == null) { t = board.registerNewTeam(p.getUniqueId().toString().substring(0, 16)); t.setSuffix(" §7[Vanish]"); Team oldteam = p.getScoreboard().getEntryTeam(p.getName()); if(oldteam != null) { t.setPrefix(oldteam.getPrefix()); HashMap<Player, Team> map = team.get(players); if(map == null) { map = new HashMap<>(); } map.put(p, oldteam); team.put(board, map); } } t.addEntry(p.getName()); } } run.put(p, new BukkitRunnable() { @Override public void run() { for(Player players : Bukkit.getOnlinePlayers()) { if(players.canSee(p) && !players.hasPermission("sup") && !players.hasPermission("content")) { players.hidePlayer(p); if(van.get(p).contains(players)) { van.get(p).remove(players); } } Scoreboard board = players.getScoreboard(); if(!board.getTeam(p.getUniqueId().toString().substring(0, 16)).getName().equals(board.getEntryTeam(p.getName()).getName())) { HashMap<Player, Team> map = team.get(board); if(map == null) { map = new HashMap<>(); } map.put(p, board.getEntryTeam(p.getName())); team.put(board, map); board.getTeam(p.getUniqueId().toString().substring(0, 16)).setPrefix(board.getEntryTeam(p.getName()).getPrefix()); board.getTeam(p.getUniqueId().toString().substring(0, 16)).addEntry(p.getName()); } } } }); run.get(p).runTaskTimer(plugin, 0, 20); van.put(p, vanplayers); p.sendMessage(plugin.prefix + "§4§lDu bist jetzt unsichtbar!"); } public static void unvanish(Player p) { run.get(p).cancel(); run.remove(p); List<Scoreboard> list = new ArrayList<>(); for(Player players : Bukkit.getOnlinePlayers()) { if(!van.get(p).contains(players)) { players.showPlayer(p); } if(players.hasPermission("sup") || players.hasPermission("content")) { Scoreboard board = players.getScoreboard(); if(!list.contains(board)) { list.add(board); } } } for(Scoreboard boards : list) { Team t = boards.getTeam(p.getUniqueId().toString().substring(0, 16)); if(t != null) { t.removeEntry(p.getName()); t.unregister(); } Team newteam = team.get(boards).get(p); if(newteam != null) { newteam.addEntry(p.getName()); } team.get(boards).remove(p); } p.sendMessage(plugin.prefix + "§4§lDu bist jetzt sichtbar!"); } public static boolean hasVanishEnabled(Player p) { ResultSet rs = MySQL.getResult("SELECT playername FROM vanish WHERE UUID = '" + p.getUniqueId().toString() + "'"); try { return rs.next(); } catch (SQLException e) { e.printStackTrace(); } return false; } public static void setVanish(Player p) { MySQL.update("INSERT INTO vanish (UUID, playername) VALUES ('" + p.getUniqueId().toString() + "', '" + p.getName() + "')"); } public static void unsetVanish(Player p) { MySQL.update("DELETE FROM vanish WHERE UUID = '" + p.getUniqueId() + "'"); } } <file_sep>/src/me/Tailo/KnowNixSystem/Commands/COMMAND_op.java package me.Tailo.KnowNixSystem.Commands; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class COMMAND_op implements CommandExecutor { private main plugin; public COMMAND_op(main main) { this.plugin = main; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(sender.hasPermission("srdev")) { if(args.length == 0) { if(sender.isOp()) { sender.setOp(false); sender.sendMessage(plugin.prefix + "§9Du wurdest gedeopped!"); } else { sender.setOp(true); sender.sendMessage(plugin.prefix + "§9Du wurdest geopped!"); } } else { if(args.length == 1) { @SuppressWarnings("deprecation") OfflinePlayer target = Bukkit.getOfflinePlayer(args[0]); if(target.isOp()) { target.setOp(false); sender.sendMessage(plugin.prefix + "§6" + target.getName() + " §9wurde gedeopped!"); if(target.isOnline()) { ((Player) target).sendMessage(plugin.prefix + "§9Du wurdest gedeopped!"); } } else { target.setOp(true); sender.sendMessage(plugin.prefix + "§6" + target.getName() + " §9wurde geopped!"); if(target.isOnline()) { ((Player) target).sendMessage(plugin.prefix + "§9Du wurdest geopped!"); } } } } } return true; } } <file_sep>/src/me/Tailo/KnowNixSystem/Listener/AsyncPlayerChatEvent_Listener.java package me.Tailo.KnowNixSystem.Listener; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; public class AsyncPlayerChatEvent_Listener implements Listener { private main plugin; public AsyncPlayerChatEvent_Listener(main main) { this.plugin = main; plugin.getServer().getPluginManager().registerEvents(this, main); } @EventHandler(priority = EventPriority.HIGHEST) public void onAsyncPlayerChat(AsyncPlayerChatEvent e) { if(plugin.globalmute) { if(!e.getPlayer().hasPermission("sup") && !e.getPlayer().hasPermission("content") && !e.getPlayer().hasPermission("builder")) { e.setCancelled(true); e.getPlayer().sendMessage(plugin.prefix + "§cGlobalmute ist aktiv!"); } } if(e.getMessage().contains("@")) { for(Player players : Bukkit.getOnlinePlayers()) { String newmsg = e.getMessage().replace("@" + players.getName(), "§b@" + players.getName() + "§r"); e.setMessage(newmsg); } } } } <file_sep>/src/me/Tailo/KnowNixSystem/Listener/PlayerLoginEvent_Listener.java package me.Tailo.KnowNixSystem.Listener; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerLoginEvent; public class PlayerLoginEvent_Listener implements Listener { private main plugin; public PlayerLoginEvent_Listener(main main) { this.plugin = main; plugin.getServer().getPluginManager().registerEvents(this, main); } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerLogin(PlayerLoginEvent e) { String ip = e.getHostname().toString().split(":")[0]; if(!ip.toLowerCase().endsWith("knownix.de")) { e.disallow(null, "§9§lKnowNix\n\n§cBitte joine über '§a§l§nknownix.de§c'!\n\n§7(Port 25565)"); return; } String name = e.getPlayer().getName().toLowerCase(); if(plugin.banned.contains(name)) { e.disallow(null, "§cDu wurdest für diesen Server gesperrt!"); } } } <file_sep>/src/me/Tailo/KnowNixSystem/MySQL/MySQL.java package me.Tailo.KnowNixSystem.MySQL; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import com.mysql.jdbc.exceptions.jdbc4.CommunicationsException; public class MySQL { public static Connection con; public static String host; public static String port; public static String database; public static String username; public static String password; public static void connect() { if(!isConnected()) { loadConfig(); try { con = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?autoReconnect=true", username, password); System.out.println("[System] Verbindung mit MySQL erfolgreich hergestellt!"); } catch (SQLException e) { e.printStackTrace(); System.err.println("[System] Verbindung mit MySQL konnte nicht hergestellt werden!"); } } } public static void disconnect() { if(isConnected()) { try { con.close(); System.out.println("[System] Verbindung mit MySQL erfolgreich geschlossen!"); } catch (SQLException e) { e.printStackTrace(); } } } public static boolean isConnected() { if(con != null) { return true; } return false; } public static void update(String qry) { PreparedStatement ps; try { ps = con.prepareStatement(qry); ps.executeUpdate(); } catch (SQLException e) { if(e instanceof CommunicationsException) { System.out.println("[System] Verbindung mit MySQL verloren! Versuche erneut..."); update(qry); } e.printStackTrace(); } } public static ResultSet getResult(String qry) { PreparedStatement ps; try { ps = con.prepareStatement(qry); return ps.executeQuery(); } catch (SQLException e) { if(e instanceof CommunicationsException) { System.out.println("[System] Verbindung mit MySQL verloren! Versuche erneut..."); return getResult(qry); } e.printStackTrace(); } return null; } private static void loadConfig() { File file = new File("plugins/KnowNixSystem", "mysql.yml"); FileConfiguration cfg = YamlConfiguration.loadConfiguration(file); cfg.addDefault("host", "localhost"); cfg.addDefault("port", "3306"); cfg.addDefault("database", "system"); cfg.addDefault("username", "system"); cfg.addDefault("password", "<PASSWORD>"); cfg.options().copyDefaults(true); try { cfg.save(file); } catch (IOException e) { e.printStackTrace(); } host = cfg.getString("host"); port = cfg.getString("port"); database = cfg.getString("database"); username = cfg.getString("username"); password = cfg.getString("<PASSWORD>"); } } <file_sep>/src/me/Tailo/KnowNixSystem/Commands/COMMAND_teleport.java package me.Tailo.KnowNixSystem.Commands; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Listener; public class COMMAND_teleport implements CommandExecutor, Listener { private main plugin; public COMMAND_teleport(main main) { this.plugin = main; plugin.getServer().getPluginManager().registerEvents(this, main); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(sender instanceof Player) { Player p = (Player) sender; if(p.hasPermission("mod")) { if(args.length == 1) { if(p.hasPermission("srmod") && args[0].equalsIgnoreCase("all")) { for(Player players : Bukkit.getOnlinePlayers()) { players.teleport(p); } p.sendMessage(plugin.prefix + "§3Alle Spieler wurden zu dir teleportiert!"); } else { Player target = Bukkit.getPlayer(args[0]); if(target != null) { p.teleport(target); p.sendMessage(plugin.prefix + "§3Du hast dich zu §6" + target.getDisplayName() + " §3teleportiert!"); } else { p.sendMessage(plugin.prefix + "§3Der Spieler §6" + args[0] + " §3ist nicht online!"); } } } else if(args.length == 2) { if(p.hasPermission("mod")) { if(args[0].equalsIgnoreCase("here")) { Player target = Bukkit.getPlayer(args[1]); if(target != null) { target.teleport(p); p.sendMessage(plugin.prefix + "§6" + target.getDisplayName() + " §3wurde zu dir teleportiert!"); } else { p.sendMessage(plugin.prefix + "§3Der Spieler §6" + args[1] + "§3 ist nicht online!"); } } else { Player p1 = Bukkit.getPlayer(args[0]); if(p1 != null) { Player p2 = Bukkit.getPlayer(args[1]); if(p2 != null) { p1.teleport(p2); p.sendMessage(plugin.prefix + "§6" + p1.getDisplayName() + " §3wurde zu " + p2.getDisplayName() + " §3teleportiert!"); } else { p.sendMessage(plugin.prefix + "§3Der Spieler §6" + args[1] + "§3 ist nicht online!"); } } else { p.sendMessage(plugin.prefix + "§3Der Spieler §6" + args[1] + "§3 ist nicht online!"); } } } } else if(args.length == 3) { if(p.hasPermission("srmod")) { try { Location loc = new Location(p.getWorld(), Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2])); p.teleport(loc); } catch(Exception e) { p.sendMessage(plugin.prefix + "§cDu hast keine Zahlen angegeben!"); } } } else if(args.length == 4) { if(p.hasPermission("srmod")) { try { World world = Bukkit.getWorld(args[3]); if(world != null) { Location loc = new Location(world, Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2])); p.teleport(loc); } else { p.sendMessage(plugin.prefix + "§cDiese Welt existiert nicht!"); p.sendMessage(plugin.prefix + "§3Existierende Welten:"); for(World worlds : Bukkit.getWorlds()) { p.sendMessage("§7- §6" + worlds.getName()); } } } catch(Exception e) { p.sendMessage(plugin.prefix + "§cDu hast keine Zahlen angegeben!"); } } } else { p.sendMessage("§3/tp <Spielername> §r- §6Teleportiere dich zu einem Spieler!"); if(p.hasPermission("moderator")) { p.sendMessage("§3/tp here <Spielername> §r- §6Teleportiere einen Spieler zu dir!"); } if(p.hasPermission("admin")) { p.sendMessage("§3/tp <X> <Y> <Z> [Welt] §r- §6Teleportiere dich zu einer Koordinate!"); p.sendMessage("§3/tp all §r- §6Teleportiere alle Spieler zu dir!"); } } } } else { sender.sendMessage("Du kannst den teleport Befehl nicht benutzen. Diese Funktion können nur Spieler Ingame nutzen!"); } return true; } } <file_sep>/src/me/Tailo/KnowNixSystem/Permission/UUIDFetcher.java package me.Tailo.KnowNixSystem.Permission; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.mojang.util.UUIDTypeAdapter; public class UUIDFetcher { public static final long FEBRUARY_2015 = 1422748800000L; private static Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create(); private static final String UUID_URL = "https://api.mojang.com/users/profiles/minecraft/%s?at=%d"; private static final String NAME_URL = "https://api.mojang.com/user/profiles/%s/names"; public static Map<String, UUID> uuidCache = new HashMap<String, UUID>(); public static Map<UUID, String> nameCache = new HashMap<UUID, String>(); private static ExecutorService pool = Executors.newCachedThreadPool(); private String name; private UUID id; public static void getUUID(final String name, Consumer<UUID> action) { pool.execute(new Acceptor<UUID>(action) { @Override public UUID getValue() { return getUUID(name); } }); } public static UUID getUUID(String name) { return getUUIDAt(name, System.currentTimeMillis()); } public static UUID getUUIDAt(String name, long timestamp) { name = name.toLowerCase(); if (uuidCache.containsKey(name)) { return uuidCache.get(name); } try { HttpURLConnection connection = (HttpURLConnection) new URL(String.format(UUID_URL, name, timestamp/1000)).openConnection(); connection.setReadTimeout(5000); UUIDFetcher data = gson.fromJson(new BufferedReader(new InputStreamReader(connection.getInputStream())), UUIDFetcher.class); uuidCache.put(name, data.id); nameCache.put(data.id, data.name); return data.id; } catch (Exception e) { e.printStackTrace(); } return null; } public static void getName(final UUID uuid, Consumer<String> action) { pool.execute(new Acceptor<String>(action) { @Override public String getValue() { return getName(uuid); } }); } public static String getName(UUID uuid) { if (nameCache.containsKey(uuid)) { return nameCache.get(uuid); } try { HttpURLConnection connection = (HttpURLConnection) new URL(String.format(NAME_URL, UUIDTypeAdapter.fromUUID(uuid))).openConnection(); connection.setReadTimeout(5000); UUIDFetcher[] nameHistory = gson.fromJson(new BufferedReader(new InputStreamReader(connection.getInputStream())), UUIDFetcher[].class); UUIDFetcher currentNameData = nameHistory[nameHistory.length - 1]; uuidCache.put(currentNameData.name.toLowerCase(), uuid); nameCache.put(uuid, currentNameData.name); return currentNameData.name; } catch (Exception e) { e.printStackTrace(); } return null; } public static interface Consumer<T> { void accept(T t); } public static abstract class Acceptor<T> implements Runnable { private Consumer<T> consumer; public Acceptor(Consumer<T> consumer) { this.consumer = consumer; } public abstract T getValue(); @Override public void run() { consumer.accept(getValue()); } } }<file_sep>/src/me/Tailo/KnowNixSystem/Listener/ServerListPingEvent_Listener.java package me.Tailo.KnowNixSystem.Listener; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.server.ServerListPingEvent; public class ServerListPingEvent_Listener implements Listener { private main plugin; public ServerListPingEvent_Listener(main main) { this.plugin = main; plugin.getServer().getPluginManager().registerEvents(this, main); } @EventHandler(priority = EventPriority.HIGHEST) public void onServerListPing(ServerListPingEvent e) { String ip = e.getAddress().getHostName(); if(!ip.equalsIgnoreCase("nevadamc.de")) { e.setMotd("§9§lNevadaMC\n§cBitte joine über '§a§l§nnevadamc.de§c'! §7(Port 25565)"); e.setMaxPlayers(0); } } } <file_sep>/src/me/Tailo/KnowNixSystem/Commands/COMMAND_kck.java package me.Tailo.KnowNixSystem.Commands; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class COMMAND_kck implements CommandExecutor { private main plugin; public COMMAND_kck(main main) { this.plugin = main; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(sender.hasPermission("mod")) { if(args.length == 1) { if(!(args[0].equalsIgnoreCase("all") && sender.hasPermission("srmod"))) { Player target = Bukkit.getPlayer(args[0]); if(target != null) { target.kickPlayer(plugin.prefix + "§6Du wurdest gekickt!"); sender.sendMessage(plugin.prefix + "§6" + target.getName() + " §3wurde gekickt!"); } else { sender.sendMessage(plugin.prefix + "§cDieser Spieler ist nicht online"); } } else { for(Player players : Bukkit.getOnlinePlayers()) { if(!players.hasPermission("testmod")) { players.kickPlayer(plugin.prefix + "§6Du wurdest gekickt!"); } } sender.sendMessage(plugin.prefix + "§3Alle Spieler wurden gekickt!"); } } else if(args.length > 1) { String reason = ""; for(int i = 1; i < args.length; i++) { reason = reason + args[i] + " "; } if(!(args[0].equalsIgnoreCase("all") && sender.hasPermission("srmod"))) { Player target = Bukkit.getPlayer(args[0]); if(target != null) { target.kickPlayer(plugin.prefix + "§6Du wurdest gekickt! §4Grund: §c" + reason); sender.sendMessage(plugin.prefix + "§6" + target.getName() + " §3wurde gekickt! §4Grund: §c" + reason); } else { sender.sendMessage(plugin.prefix + "§cDieser Spieler ist nicht online"); } } else { for(Player players : Bukkit.getOnlinePlayers()) { if(!players.hasPermission("testmod")) { players.kickPlayer(plugin.prefix + "§6Du wurdest gekickt! §4Grund: §c" + reason); } } sender.sendMessage(plugin.prefix + "§3Alle Spieler wurden gekickt! §4Grund: §c" + reason); } } else { sender.sendMessage(plugin.prefix + "§c/kck <Spielername>"); } } return true; } } <file_sep>/src/me/Tailo/KnowNixSystem/Listener/PlayerJoinEvent_Listener.java package me.Tailo.KnowNixSystem.Listener; import me.Tailo.KnowNixSystem.Methoden.Vanish_methoden; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; public class PlayerJoinEvent_Listener implements Listener { private main plugin; public PlayerJoinEvent_Listener(main main) { this.plugin = main; plugin.getServer().getPluginManager().registerEvents(this, main); } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerJoin(PlayerJoinEvent e) { Player p = e.getPlayer(); if(p.hasPermission("sup") || p.hasPermission("content")) { if(Vanish_methoden.hasVanishEnabled(p)) { Vanish_methoden.vanish(p); e.setJoinMessage(""); } if(Vanish_methoden.run.size() != 0) { for(Player players : Vanish_methoden.run.keySet()) { if(!p.hasPermission("testmod")) { p.hidePlayer(players); } } } } } } <file_sep>/src/me/Tailo/KnowNixSystem/Commands/COMMAND_vanish.java package me.Tailo.KnowNixSystem.Commands; import me.Tailo.KnowNixSystem.Methoden.Vanish_methoden; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class COMMAND_vanish implements CommandExecutor { @SuppressWarnings("unused") private main plugin; public COMMAND_vanish(main main) { this.plugin = main; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(sender instanceof Player) { Player p = (Player) sender; if(p.hasPermission("sup") || p.hasPermission("content")) { if(!Vanish_methoden.hasVanishEnabled(p)) { Vanish_methoden.vanish(p); Vanish_methoden.setVanish(p); } else { Vanish_methoden.unvanish(p); Vanish_methoden.unsetVanish(p); } } } else { sender.sendMessage("Dieser Befehl kann nur als Spieler ausgeführt werden!"); } return true; } } <file_sep>/src/me/Tailo/KnowNixSystem/Commands/COMMAND_fly.java package me.Tailo.KnowNixSystem.Commands; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class COMMAND_fly implements CommandExecutor { private main plugin; public COMMAND_fly(main main) { this.plugin = main; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(sender instanceof Player) { Player p = (Player) sender; if(p.hasPermission("srmod")) { if(args.length == 0) { if(!p.getAllowFlight()) { p.setAllowFlight(true); p.sendMessage(plugin.prefix + "§3Der Flugmodus wurde §aaktiviert§3!"); } else { p.setAllowFlight(false); p.sendMessage(plugin.prefix + "§3Der Flugmodus wurde §cdeaktiviert§3!"); } } else if(args.length == 1) { if(p.hasPermission("srdev")) { Player target = Bukkit.getPlayer(args[0]); if(target != null) { if(!target.getAllowFlight()) { target.setAllowFlight(true); target.sendMessage(plugin.prefix + "§3Der Flugmodus wurde für dich §aaktiviert§3!"); p.sendMessage(plugin.prefix + "§3Der Flugmodus wurde für §6" + target.getName() + " §aaktiviert§3!"); } else { target.setAllowFlight(false); target.sendMessage(plugin.prefix + "§3Der Flugmodus wurde für dich §cdeaktiviert§3!"); p.sendMessage(plugin.prefix + "§3Der Flugmodus wurde für §6" + target.getName() + " §cdeaktiviert§3!"); } } else { p.sendMessage(plugin.prefix + "§3Dieser Spieler ist nicht §6online§3!"); } } } else { p.sendMessage(plugin.prefix + "§cDu verwendest zu viele Argumente!"); } } } else { sender.sendMessage("Dieser Befehl kann nur als Spieler ausgeführt werden!"); } return true; } } <file_sep>/src/me/Tailo/KnowNixSystem/Commands/COMMAND_god.java package me.Tailo.KnowNixSystem.Commands; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Listener; public class COMMAND_god implements CommandExecutor, Listener { private main plugin; public COMMAND_god(main main) { this.plugin = main; plugin.getServer().getPluginManager().registerEvents(this, main); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(sender instanceof Player) { Player p = (Player) sender; if(p.hasPermission("srmod")) { if(args.length == 0) { if(!plugin.god.contains(p.getName())) { plugin.god.add(p.getName()); p.sendMessage(plugin.prefix + "§3Die Unsterblichkeit wurde §aaktiviert§3!"); } else { plugin.god.remove(p.getName()); p.sendMessage(plugin.prefix + "§3Die Unsterblichkeit wurde §cdeaktiviert§3!"); } } else if(args.length == 1) { if(p.hasPermission("srdev")) { Player target = Bukkit.getPlayer(args[0]); if(target != null) { if(!plugin.god.contains(target.getName())) { plugin.god.add(target.getName()); target.sendMessage(plugin.prefix + "§3Die Unsterblichkeit wurde für dich §aaktiviert§3!"); p.sendMessage(plugin.prefix + "§3Die Unsterblichkeit wurde für §6" + target.getName() + " §aaktiviert§3!"); } else { plugin.god.remove(target.getName()); target.sendMessage(plugin.prefix + "§3Die Unsterblichkeit wurde für dich §cdeaktiviert§3!"); p.sendMessage(plugin.prefix + "§3Die Unsterblichkeit wurde für §6" + target.getName() + " §cdeaktiviert§3!"); } } else { p.sendMessage(plugin.prefix + "§3Dieser Spieler ist nicht §6online§3!"); } } } else { p.sendMessage(plugin.prefix + "§cDu verwendest zu viele Argumente!"); } } } else { sender.sendMessage("Dieser Befehl kann nur als Spieler ausgeführt werden!"); } return true; } } <file_sep>/src/me/Tailo/KnowNixSystem/Listener/PlayerTeleportEvent_Listener.java package me.Tailo.KnowNixSystem.Listener; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import me.Tailo.KnowNixSystem.System.main; public class PlayerTeleportEvent_Listener implements Listener { private main plugin; public PlayerTeleportEvent_Listener(main main) { this.plugin = main; plugin.getServer().getPluginManager().registerEvents(this, main); } @EventHandler public void onPlayerTeleport(PlayerTeleportEvent e) { if(e.getPlayer().hasPermission("mod")) { plugin.back.put(e.getPlayer().getUniqueId(), e.getFrom()); } if(plugin.freeze.contains(e.getPlayer().getName())) { System.out.println(e.getCause()); if(e.getCause() != TeleportCause.UNKNOWN) { e.setCancelled(true); } } } } <file_sep>/src/me/Tailo/KnowNixSystem/Commands/COMMAND_fix.java package me.Tailo.KnowNixSystem.Commands; import java.util.ArrayList; import java.util.List; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class COMMAND_fix implements CommandExecutor { private main plugin; public COMMAND_fix(main main) { this.plugin = main; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(sender instanceof Player) { Player p = (Player) sender; List<Player> list = new ArrayList<>(); for(Player players : Bukkit.getOnlinePlayers()) { if(p.canSee(players)) { list.add(players); p.hidePlayer(players); } } for(Player players : list) { p.showPlayer(players); } p.sendMessage(plugin.prefix + "§3Alle Spieler sollten jetzt sichtbar sein!"); } else { sender.sendMessage("Dieser Befehl kann nur als Spieler ausgeführt werden!"); } return true; } } <file_sep>/src/me/Tailo/KnowNixSystem/Permission/Permission_methoden.java package me.Tailo.KnowNixSystem.Permission; import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionAttachment; import me.Tailo.KnowNixSystem.MySQL.MySQL; import me.Tailo.KnowNixSystem.System.main; public class Permission_methoden { private static main plugin; @SuppressWarnings("static-access") public Permission_methoden(main main) { this.plugin = main; } public static void loadPermissions(Player p, Group group) { loadExtraPermissions(p, group); } public static void setGroup(String uuid, Group group) { if(group != Group.SPIELER) { if(isUserExists(uuid)) { MySQL.update("UPDATE permissions SET UUID = '" + uuid + "',playername = '" + UUIDFetcher.getName(UUID.fromString(uuid)) + "',rank = '" + getGroupName(group) + "' WHERE UUID = '" + uuid + "'"); } else { MySQL.update("INSERT INTO permissions (UUID, playername, rank) VALUES ('" + uuid + "', '" + UUIDFetcher.getName(UUID.fromString(uuid)) + "', '" + getGroupName(group) + "')"); } } else { if(isUserExists(uuid)) { MySQL.update("DELETE FROM permissions WHERE UUID = '" + uuid + "'"); } } } public static Group getGroup(Player p) { ResultSet rs = MySQL.getResult("SELECT rank FROM permissions WHERE UUID = '" + p.getUniqueId().toString() + "'"); try { while(rs.next()) { String groupname = rs.getString("rank"); Group group = Permission_methoden.getGroup(groupname); return group; } } catch (SQLException e) { e.printStackTrace(); } return Group.SPIELER; } public static String getGroupName(Group group) { if(group == Group.ADMIN) return "Admin"; if(group == Group.SRDEV) return "SrDev"; if(group == Group.DEV) return "Dev"; if(group == Group.SRMOD) return "SrMod"; if(group == Group.MOD) return "Mod"; if(group == Group.SUP) return "Sup"; if(group == Group.CONTENT) return "Content"; if(group == Group.BUILDER) return "Builder"; if(group == Group.VIP) return "VIP"; if(group == Group.PREMIUMPLUS) return "PremiumPlus"; if(group == Group.PREMIUM) return "Premium"; if(group == Group.SPIELER) return "Spieler"; return "NULL"; } public static Group getGroup(String string) { if (string.equalsIgnoreCase("premium")) { return Group.PREMIUM; } else if (string.equalsIgnoreCase("premiumplus")) { return Group.PREMIUMPLUS; } else if (string.equalsIgnoreCase("vip")) { return Group.VIP; } else if (string.equalsIgnoreCase("builder")) { return Group.BUILDER; } else if (string.equalsIgnoreCase("content")) { return Group.CONTENT; } else if (string.equalsIgnoreCase("sup")) { return Group.SUP; } else if (string.equalsIgnoreCase("mod")) { return Group.MOD; } else if (string.equalsIgnoreCase("srmod")) { return Group.SRMOD; } else if (string.equalsIgnoreCase("dev")) { return Group.DEV; } else if (string.equalsIgnoreCase("srdev")) { return Group.SRDEV; } else if (string.equalsIgnoreCase("admin")) { return Group.ADMIN; } return Group.SPIELER; } public static void loadExtraPermissions(Player p, Group group) { if(group == Group.ADMIN) { PermissionAttachment attachment = p.addAttachment(plugin); attachment.setPermission("vip", true); attachment.setPermission("premium", true); attachment.setPermission("premiumplus", true); attachment.setPermission("sup", true); attachment.setPermission("mod", true); attachment.setPermission("srmod", true); attachment.setPermission("dev", true); attachment.setPermission("srdev", true); attachment.setPermission("admin", true); attachment.setPermission("spartan.bypass", true); // attachment.setPermission("reflex.bypass", true); attachment.setPermission("spartan.reconnect", true); } if(group == Group.SRDEV) { PermissionAttachment attachment = p.addAttachment(plugin); attachment.setPermission("vip", true); attachment.setPermission("premium", true); attachment.setPermission("premiumplus", true); attachment.setPermission("sup", true); attachment.setPermission("mod", true); attachment.setPermission("srmod", true); attachment.setPermission("dev", true); attachment.setPermission("srdev", true); attachment.setPermission("spartan.bypass", true); // attachment.setPermission("reflex.bypass", true); attachment.setPermission("spartan.reconnect", true); } if(group == Group.DEV) { PermissionAttachment attachment = p.addAttachment(plugin); attachment.setPermission("vip", true); attachment.setPermission("premium", true); attachment.setPermission("premiumplus", true); attachment.setPermission("sup", true); attachment.setPermission("mod", true); attachment.setPermission("srmod", true); attachment.setPermission("dev", true); attachment.setPermission("spartan.bypass", true); // attachment.setPermission("reflex.bypass", true); attachment.setPermission("spartan.reconnect", true); } if(group == Group.SRMOD) { PermissionAttachment attachment = p.addAttachment(plugin); attachment.setPermission("vip", true); attachment.setPermission("premium", true); attachment.setPermission("premiumplus", true); attachment.setPermission("sup", true); attachment.setPermission("mod", true); attachment.setPermission("srmod", true); attachment.setPermission("spartan.bypass", true); // attachment.setPermission("reflex.bypass", true); attachment.setPermission("spartan.reconnect", true); } if(group == Group.MOD) { PermissionAttachment attachment = p.addAttachment(plugin); attachment.setPermission("vip", true); attachment.setPermission("premium", true); attachment.setPermission("premiumplus", true); attachment.setPermission("sup", true); attachment.setPermission("mod", true); attachment.setPermission("spartan.bypass", true); // attachment.setPermission("reflex.bypass", true); attachment.setPermission("spartan.reconnect", true); } if(group == Group.SUP) { PermissionAttachment attachment = p.addAttachment(plugin); attachment.setPermission("vip", true); attachment.setPermission("premium", true); attachment.setPermission("premiumplus", true); attachment.setPermission("sup", true); attachment.setPermission("spartan.bypass", true); // attachment.setPermission("reflex.bypass", true); attachment.setPermission("spartan.reconnect", true); } if(group == Group.CONTENT) { PermissionAttachment attachment = p.addAttachment(plugin); attachment.setPermission("vip", true); attachment.setPermission("premium", true); attachment.setPermission("premiumplus", true); attachment.setPermission("content", true); attachment.setPermission("spartan.bypass", true); // attachment.setPermission("reflex.bypass", true); attachment.setPermission("spartan.reconnect", true); attachment.setPermission("BungeeSigns.use", true); } if(group == Group.BUILDER) { PermissionAttachment attachment = p.addAttachment(plugin); attachment.setPermission("vip", true); attachment.setPermission("premium", true); attachment.setPermission("premiumplus", true); attachment.setPermission("builder", true); attachment.setPermission("spartan.bypass", true); // attachment.setPermission("reflex.bypass", true); attachment.setPermission("spartan.reconnect", true); attachment.setPermission("BungeeSigns.use", true); } if(group == Group.VIP) { PermissionAttachment attachment = p.addAttachment(plugin); attachment.setPermission("vip", true); attachment.setPermission("premium", true); attachment.setPermission("premiumplus", true); attachment.setPermission("spartan.bypass", true); // attachment.setPermission("reflex.bypass", true); attachment.setPermission("spartan.reconnect", true); attachment.setPermission("BungeeSigns.use", true); } if(group == Group.PREMIUMPLUS) { PermissionAttachment attachment = p.addAttachment(plugin); attachment.setPermission("premium", true); attachment.setPermission("premiumplus", true); attachment.setPermission("BungeeSigns.use", true); } if(group == Group.PREMIUM) { PermissionAttachment attachment = p.addAttachment(plugin); attachment.setPermission("premium", true); attachment.setPermission("BungeeSigns.use", true); } if(group == Group.SPIELER) { PermissionAttachment attachment = p.addAttachment(plugin); attachment.setPermission("BungeeSigns.use", true); } } public enum Group { SPIELER, PREMIUM, PREMIUMPLUS, VIP, BUILDER, CONTENT, SUP, MOD, SRMOD, DEV, SRDEV, ADMIN } private static boolean isUserExists(String uuid) { try { ResultSet rs = MySQL.getResult("SELECT rank FROM permissions WHERE UUID = '" + uuid + "'"); return rs.next(); } catch (SQLException e) { e.printStackTrace(); } return false; } } <file_sep>/src/me/Tailo/KnowNixSystem/Commands/COMMAND_freeze.java package me.Tailo.KnowNixSystem.Commands; import me.Tailo.KnowNixSystem.System.main; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; public class COMMAND_freeze implements CommandExecutor { private main plugin; public COMMAND_freeze(main main) { this.plugin = main; } @SuppressWarnings("deprecation") @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(sender.hasPermission("mod")) { if(args.length == 1) { Player target = Bukkit.getPlayer(args[0]); if(target != null) { if(plugin.freeze.contains(target.getName())) { plugin.freeze.remove(target.getName()); target.sendMessage(plugin.prefix + "§9Du bist jetzt nicht mehr eingefroren!"); sender.sendMessage(plugin.prefix + "§e" + target.getName() + " §9ist jetzt nicht mehr eingefroren!"); } else { target.sendMessage(plugin.prefix + "§9Du wurdest eingefroren!"); target.sendMessage(plugin.prefix + "§4Wenn du den Server verlässt kann das als §eBan §4enden!"); sender.sendMessage(plugin.prefix + "§e" + target.getName() + " §9wurde eingefroren!"); Vector v = new Vector(0, -1, 0); BukkitRunnable run = new BukkitRunnable() { @Override public void run() { if(!target.isOnGround()) { target.setVelocity(v); } else { cancel(); plugin.freeze.add(target.getName()); } } }; run.runTaskTimer(plugin, 0, 1); } } else { sender.sendMessage(plugin.prefix + "§e" + args[0] + " §cist nicht online!"); } } else { sender.sendMessage(plugin.prefix + "§c/freeze [Spielername]"); } } return true; } }
5f4f030d6870edae3970c3b218fb3dc91b0ebc1a
[ "Java" ]
19
Java
TailoMC/KnowNixSystem
39f15edefde74cf194c3769938a83513bf88c613
6f24509e0418a7b9817a33a696b27787c47a44d8
refs/heads/master
<file_sep>#coding:utf-8 from sqlalchemy import create_engine, ForeignKey, Column, Integer, String from sqlalchemy.orm import sessionmaker, relationship, backref from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() DB_CONNECT_STRING = 'oracle://jl:jl@172.16.58.3:15001/orcl?charset=utf8' sess=None engine = create_engine(DB_CONNECT_STRING) DBSession = sessionmaker(bind=engine) session = DBSession() print type(session) #样品检验信息表YPJYXX class JL(Base): # 表的名字: __tablename__ = 'yqjyxx' # 表的结构: id = Column(Integer, primary_key=True) SLRQ=Column(String) SJDW=Column(String) LXR=Column(String) LXDH=Column(String) YQMC=Column(String) GGXH=Column(String) CCBH=Column(String) JL=Column(String) <file_sep>#coding=utf8 from django.shortcuts import render,render_to_response from django.http import HttpResponse,HttpResponseRedirect from django.template import RequestContext from django.contrib.auth.decorators import login_required from views import * #import cx_Oracle #import MySQLdb #from django.core.paginator import Paginator,InvalidPage,EmptyPage,PageNotAnInteger #from paginator import * #import json #from django import forms #前台首页 def index(req): context = {} context['hello'] = 'Hello World!' return render(req, 'index.html', context) #后台首页 @login_required(login_url = '/login/') def totalView(req): res={} #try: # user = req.GET.get('user') # print user.username #except Exception: # traceback.print_exc() res['chanpin']=38071 res['jl']=47687 res['xianwei']=12864 res['chanpinBad']=2067 res['jlBad']=1150 res['xianweiBad']=2393 return render_to_response('total_view.html',res,context_instance=RequestContext(req))<file_sep>#coding=utf8 from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings from views import * urlpatterns = patterns('', #质量基础--产品检测院 url(r'^chanpin/$',chanpin,name = 'chanpin'), url(r'^chanpinIndex/$',chanpinIndex,name = 'chanpinIndex'), url(r'^getChanpinData/$',getChanpinData), url(r'^getCPSCList/$',getCPSCList), url(r'^addSCCP/$',addSCCP), url(r'^changeBar/$',changeBar), #质量基础--计量 url(r'^jlIndex/$',jlIndex,name = 'jlIndex'), url(r'^jl/$',jl,name = 'jl'), url(r'^getJLData/$',getJLData), url(r'^getJLSCList/$',getJLSCList), url(r'^addSCJL/$',addSCJL), #质量基础--铜铅锌 url(r'^tqx/$',tqx,name = 'tqx'), url(r'^gongshang/$',gongshang,name = 'gongshang'), url(r'^huanbao/$',huanbao,name = 'huanbao'), #质量基础--纤维 url(r'^xianweiIndex/$',xianweiIndex,name = 'xianweiIndex'), url(r'^xianwei/$',xianwei,name = 'xianwei'), url(r'^getXianweiData/$',getXianweiData), url(r'^getXWSCList/$',getXWSCList), url(r'^addSCXW/$',addSCXW), url(r'^changeXianweiBar/$',changeXianweiBar), #质量基础--国家监督抽查 url(r'^gjccIndex/$',gjccIndex,name = 'gjccIndex'), url(r'^changeGCBar/$',changeGCBar), url(r'^changeGCRadar/$',changeGCRadar), #质量状况--进出口 url(r'^entranceIndex/$',entranceIndex,name='entranceIndex'), #质量状况--产品抽查 url(r'^inspectionIndex/$',inspectionIndex,name='inspectionIndex'), #质量状况--网络交易 url(r'^onlinetradingIndex/$',onlinetradingIndex,name='onlinetradingIndex'), #应用分析--电梯 url(r'^diantiIndex/$', dtIndex,name='dtIndex'), url(r'^dttj/$', dttj,name='dttj'), url(r'^dtwb/$', dtwb,name='dtwb'), url(r'^getDTZTData/$',getDTZTData), #应用分析--电缆 url(r'^dianlanIndex/$', dianlanIndex,name='dianlanIndex'), url(r'^dianlan/$', dianlan,name='dianlan'), url(r'^getDLData/$', getDLData), url(r'^addSCDL/$', addSCDL), url(r'^getDLSCList/$', getDLSCList), url(r'^industry/$',industry,name = 'industry'), url(r'^product/$',product,name = 'product'), url(r'^region/$',region,name = 'region'), url(r'^brand/$',brand,name = 'brand'), url(r'^enterprise/$',enterprise,name = 'enterprise'), #风险分析 #url(r'^riskAnalysis/$',riskAnalysis,name = 'riskAnalysis'), #风险预警 url(r'^riskWarning/$',riskWarning,name = 'riskWarning'), url(r'^wordCloud/$',wordCloud,name = 'wordCloud'), #WebGIS url(r'^mapChina/$',mapChina,name = 'mapChina'), url(r'^mapAnhui/$',mapAnhui,name = 'mapAnhui'), #宏观经济 url(r'^economic/$',economic,name = 'economic'), ) <file_sep>#coding=utf8 from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings from views import * #testchocolat urlpatterns = patterns('', url(r'^$', totalView,name='index'), url(r'^admin/', include(admin.site.urls)), url(r'^login/', include('login.urls')), url(r'^test/$',test,name = 'test'), #后台首页 url(r'^totalView/$', totalView,name='totalView'), #质量基础--产品检测院 url(r'^chanpin/$',chanpin,name = 'chanpin'), url(r'^chanpinIndex/$',chanpinIndex,name = 'chanpinIndex'), url(r'^getChanpinData/$',getChanpinData), url(r'^getCPSCList/$',getCPSCList), url(r'^addSCCP/$',addSCCP), url(r'^changeBar/$',changeBar), url(r'^addChanpin/$',addChanpin), #质量基础--计量 url(r'^jlIndex/$',jlIndex,name = 'jlIndex'), url(r'^jl/$',jl,name = 'jl'), url(r'^getJLData/$',getJLData), url(r'^getJLSCList/$',getJLSCList), url(r'^addSCJL/$',addSCJL), #质量基础--铜铅锌 url(r'^tqx/$',tqx,name = 'tqx'), url(r'^gongshang/$',gongshang,name = 'gongshang'), url(r'^huanbao/$',huanbao,name = 'huanbao'), #质量基础--纤维 url(r'^xianweiIndex/$',xianweiIndex,name = 'xianweiIndex'), url(r'^xianwei/$',xianwei,name = 'xianwei'), url(r'^getXianweiData/$',getXianweiData), url(r'^getXWSCList/$',getXWSCList), url(r'^addSCXW/$',addSCXW), #质量基础--国家监督抽查 url(r'^gjccIndex/$',gjccIndex,name = 'gjccIndex'), url(r'^changeGCBar/$',changeGCBar), url(r'^changeGCRadar/$',changeGCRadar), ## url(r'^xianwei/$',xianwei,name = 'xianwei'), ## url(r'^getXianweiData/$',getXianweiData), ## url(r'^getXWSCList/$',getXWSCList), ## url(r'^addSCXW/$',addSCXW), #应用分析--电梯 url(r'^diantiIndex/$', dtIndex,name='dtIndex'), url(r'^dttj/$', dttj,name='dttj'), url(r'^dtwb/$', dtwb,name='dtwb'), url(r'^getDTZTData/$',getDTZTData), #应用分析--电缆 url(r'^dianlanIndex/$', dianlanIndex,name='dianlanIndex'), url(r'^dianlan/$', dianlan,name='dianlan'), url(r'^getDLData/$', getDLData), url(r'^addSCDL/$', addSCDL), url(r'^getDLSCList/$', getDLSCList), url(r'^industry/$',industry,name = 'industry'), url(r'^product/$',product,name = 'product'), url(r'^region/$',region,name = 'region'), url(r'^brand/$',brand,name = 'brand'), url(r'^enterprise/$',enterprise,name = 'enterprise'), #风险分析 #url(r'^riskAnalysis/$',riskAnalysis,name = 'riskAnalysis'), #风险预警 url(r'^riskWarning/$',riskWarning,name = 'riskWarning'), url(r'^wordCloud/$',wordCloud,name = 'wordCloud'), #WebGIS url(r'^mapChina/$',mapChina,name = 'mapChina'), url(r'^mapAnhui/$',mapAnhui,name = 'mapAnhui'), #宏观经济 url(r'^economic/$',economic,name = 'economic'), url(r'^userManage/$',userManage,name = 'userManage'), url(r'^roleManage/$',roleManage,name = 'roleManage'), url(r'^logManage/$',logManage,name = 'logManage'), #静态文件路径 (r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_URL}), #前台页面 url(r'^index/$',index,name = 'index'), url(r'^consumer/$',consumer,name = 'consumer'), url(r'^consumer1/$',consumer1,name = 'consumer1'), url(r'^consumer2/$',consumer2,name = 'consumer2'), url(r'^consumer3/$',consumer3,name = 'consumer3'), url(r'^consumer4/$',consumer4,name = 'consumer4'), url(r'^totalindex/$',totalindex,name = 'totalindex') , url(r'^gover/$',gover,name = 'gover') , url(r'^gover1/$',gover1,name = 'gover1') , url(r'^gover2/$',gover2,name = 'gover2') , url(r'^gover3/$',gover3,name = 'gover3') , url(r'^gover4/$',gover4,name = 'gover4') , url(r'^friendlink/$',friendlink,name = 'friendlink') , url(r'^industries/$',industries,name = 'industries') , url(r'^industry1/$',industry1,name = 'industry1') , url(r'^industry2/$',industry2,name = 'industry2') , url(r'^industry3/$',industry3,name = 'industry3') , url(r'^industry4/$',industry4,name = 'industry4') , url(r'^others/$',others,name = 'others') , url(r'^publicservice/$',publicservice,name = 'publicservice') , url(r'^publicservice1/$',publicservice1,name = 'publicservice1') , url(r'^publicservicelink/$',publicservicelink,name = 'publicservicelink') , url(r'^new1/$',new1,name = 'new1'), ) <file_sep>#coding:utf8 from django.conf.urls import patterns, url from login import views urlpatterns = patterns('', url(r'^$', views.login, name='login'), #url(r'^login/changepwd/$', views.changepwd,name='changepwd'), url(r'login/$',views.login,name = 'login'), url(r'regist/$',views.regist,name = 'regist'), url(r'logout/$',views.logout,name = 'logout'), url(r'forgetpwd/$', views.forgetpwd), ) <file_sep>#coding=utf8 from django.shortcuts import render,render_to_response from django.http import HttpResponse,HttpResponseRedirect from django.template import RequestContext from django import forms from django.contrib.auth.decorators import login_required def credit_eval(req): return render_to_response('credit/credit_eval.html',{},context_instance=RequestContext(req)) def credit_info(req): return render_to_response('credit/credit_info.html',{},context_instance=RequestContext(req)) <file_sep>#coding:utf8 from django.conf.urls import url,patterns from credit import views urlpatterns = patterns('', url(r'credit_eval/$',views.credit_eval), url(r'credit_info/$', views.credit_info), ) <file_sep>#coding=utf8 from django.shortcuts import render,render_to_response from django.http import HttpResponse,HttpResponseRedirect from django.template import RequestContext from django import forms from django.contrib.auth.decorators import login_required #import cx_Oracle #import MySQLdb #from django.core.paginator import Paginator,InvalidPage,EmptyPage,PageNotAnInteger from paginator import * #import json def consumer(req): context = {} context['hello'] = 'Hello World!' return render(req, 'consumer.html', context) def consumer1(req): context = {} context['hello'] = 'Hello World!' return render(req, 'consumer1.html', context) def consumer2(req): context = {} context['hello'] = 'Hello World!' return render(req, 'consumer2.html', context) def consumer3(req): context = {} context['hello'] = 'Hello World!' return render(req, 'consumer3.html', context) def consumer4(req): context = {} context['hello'] = 'Hello World!' return render(req, 'consumer4.html', context) def totalindex(req): context = {} context['hello'] = 'Hello World!' return render(req, 'totalindex.html', context) def gover(req): context = {} context['hello'] = 'Hello World!' return render(req, 'gover.html', context) def gover1(req): context = {} context['hello'] = 'Hello World!' return render(req, 'gover1.html', context) def gover2(req): context = {} context['hello'] = 'Hello World!' return render(req, 'gover2.html', context) def gover3(req): context = {} context['hello'] = 'Hello World!' return render(req, 'gover3.html', context) def gover4(req): context = {} context['hello'] = 'Hello World!' return render(req, 'gover4.html', context) def friendlink(req): context = {} context['hello'] = 'Hello World!' return render(req, 'friendlink.html', context) def industries(req): context = {} context['hello'] = 'Hello World!' return render(req, 'industries.html', context) def industry1(req): context = {} context['hello'] = 'Hello World!' return render(req, 'industry1.html', context) def industry2(req): context = {} context['hello'] = 'Hello World!' return render(req, 'industry2.html', context) def industry3(req): context = {} context['hello'] = 'Hello World!' return render(req, 'industry3.html', context) def industry4(req): context = {} context['hello'] = 'Hello World!' return render(req, 'industry4.html', context) def others(req): context = {} context['hello'] = 'Hello World!' return render(req, 'others.html', context) def publicservice(req): context = {} context['hello'] = 'Hello World!' return render(req, 'publicservice.html', context) def publicservice1(req): context = {} context['hello'] = 'Hello World!' return render(req, 'publicservice1.html', context) def publicservicelink(req): context = {} context['hello'] = 'Hello World!' return render(req, 'publicservicelink.html', context) def new1(req): context = {} context['hello'] = 'Hello World!' return render(req, 'new1.html', context) <file_sep>#coding=utf8 from django.shortcuts import render,render_to_response from django.http import HttpResponse,HttpResponseRedirect from django.template import RequestContext from django import forms from django.contrib.auth.decorators import login_required #import cx_Oracle import MySQLdb #from django.core.paginator import Paginator,InvalidPage,EmptyPage,PageNotAnInteger from paginator import * import json import datetime from models import * #数据库参数 DB_HOST='192.168.127.12' DB_PORT=16001 DB_NAME='anhuiend' DB_USER='root' DB_PASSWD='<PASSWORD>' DB_CHARSET='utf8' #通用函数 ''' 获得每月的天数 ''' def monthList(year): if (year%4 == 0 and (year%100 != 0 or year%400 == 0) ) : return [31,29,31,30,31,30,31,31,30,31,30,31] else : return [31,28,31,30,31,30,31,31,30,31,30,31] ''' 将格式为2015-01-01的字符串日期转化为datetime.date形式 ''' def str2date(str_date): year ,month ,day = str_date.split('-') return datetime.date(int(year) ,int(month) ,int(day)) #质量基础 #产品检测院 ''' 质检院首页 ''' @login_required(login_url = '/login/') def chanpinIndex(req): data={} try: data['total'] = Ahzj.objects.all().count() data['bad'] = Ahzj.objects.all().filter(jyjl__contains='不').count() data['sc'] = ScYpjyxx.objects.all().count() except Exception , e: print e data['total']=data['bad']= data['sc']=0 ## data['totalData']={'1':2.0, '2':4.9,'3': 7.0, '4':23.2, 5525.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3] ## data['badData']=[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3] try: data['totalData'] , data['badData']=getChanpinBar(2015) except Exception , e: print e return render_to_response('qualityBase/chanpinIndex.html',data,context_instance=RequestContext(req)) #产品检测院首页柱形图数据 返回分别包含12个月的全数据量和不合格数据量的list def getChanpinBar(year): #2015年12个月的总数量 total=[] for month in range(12): count = Ahzj.objects.all().filter(shrq__contains=year,shrq__month=month).count() total.append(count) #2015年12个月的不合格数量 bad=[] for month in range(12): count = Ahzj.objects.all().filter(shrq__contains=year,shrq__month=month,jyjl__contains='不').count() bad.append(count) print total,bad return total,bad #更新柱形图数据 def changeBar(req): year=req.GET.get('year','2015') year=int(year) res={} try: bar=getChanpinBar(year) res['totalData']=bar[0] res['badData']=bar[1] except Exception,e: print e return HttpResponse(json.dumps(res), content_type='application/json') @login_required(login_url = '/login/') def addSCCP(req): #请求所传过来的是unicode格式 ypmc=req.GET.get('ypmc','') jyyj=req.GET.get('jyyj','') jyjl=req.GET.get('jyjl','') sjdw=req.GET.get('sjdw','') try: ypmc=ypmc.encode('utf-8') jyyj=jyyj.encode('utf-8') jyjl=jyjl.encode('utf-8') sjdw=sjdw.encode('utf-8') except Exception,e: print e sc_ypjyxx = ScYpjyxx(ypmc=ypmc,jyyj=jyyj,jyjl=jyjl,sjdw=sjdw) sc_ypjyxx.save() res={} return HttpResponse(json.dumps(res), content_type='application/json') #获取产品检测院收藏数据 @login_required(login_url = '/login/') def getCPSCList(req): scList = ScYpjyxx.objects.all() data=[] for sc in scList: each={} each['ypmc']=sc.ypmc#.decode('gbk','ignore').encode('utf8') each['jyyj']=sc.jyyj#.decode('gbk','ignore').encode('utf8') each['jyjl']=sc.jyjl#.decode('gbk','ignore').encode('utf8') each['sjdw']=sc.sjdw#.decode('gbk','ignore').encode('utf8') data.append(each) res={} res['data'] = data return HttpResponse(json.dumps(res), content_type='application/json') @login_required(login_url = '/login/') def chanpin(req): mode=req.GET.get('mode','all') page=req.GET.get('page','1') term=req.GET.get('term',None) before=req.GET.get('before','2015-01-01') after=req.GET.get('after','2015-12-31') print before,after print "chanpinQuery:",mode,page,term if mode=='all': bad=False else: bad=True #分页 try: totalNum = getChanpinListNumByIndex(bad=bad,term=term,before=before,after=after) print totalNum except Exception,e: print e paginator =Paginator(totalNum,10) #每页10条 #获取总页数 try: page=int(req.GET.get('page','1')) if page < 1: page=1 except ValueError: page=1 ## print "page:",page #页面数据 try: dataList = getChanpinListByIndex(paginator.getIndex(page),bad=bad,term=term,before=before,after=after) except : dataList = getChanpinListByIndex(paginator.getIndex(1),bad=bad,term=term,before=before,after=after) data=[] print len(dataList) for i in dataList: each={} each['ypmc']=i.ypmc#.decode('gbk').encode('utf8') each['jyyj']=i.jyyj#.decode('gbk').encode('utf8') each['jyjl']=i.jyjl#.decode('gbk').encode('utf8') each['sjdw']=i.sjdw#.decode('gbk').encode('utf8') each['scdw']=i.scdw#.decode('gbk').encode('utf8') data.append(each) #翻页栏 after_range_num = 6 before_range_num = 7 res={} res['data'] = data res['has_previous'] = paginator.has_previous(page) res['has_next'] = paginator.has_next(page) res['page_range'] = paginator.page_range(page,before_range_num,after_range_num) res['number'] = page res['previous_page_number'] = paginator.previous_page_number(page) res['next_page_number'] = paginator.next_page_number(page) res['bad']=bad res['after']=after res['before']=before return render_to_response('qualityBase/chanpin.html',res,context_instance=RequestContext(req)) #获取产品检测院数据 #分页:pageIndex #不合格:bad def getChanpinListNumByIndex(bad=False,term=None,before='2015-01-01',after='2015-12-31'): try: before=before.encode('utf8') after=after.encode('utf8') except Exception ,e: print e start_time = str2date(before) end_time = str2date(after) # 产品名称 if term: term = term.encode('utf8') else: term = "" #不合格 if bad: bad_term = '不' else: bad_term = "" #查询语句 try: res = Ahzj.objects.filter(jyjl__contains=bad_term,shrq__range=(start_time,end_time),ypmc__contains=term).count() except Exception,e: print e print bad,term,before,after,res return res #获取产品检测院数据 #分页:pageIndex #不合格:bad def getChanpinListByIndex(pageIndex,bad=False,term=None,before='2015-01-01',after='2015-12-31'): try: before=before.encode('utf8') after=after.encode('utf8') except Exception ,e: print e #起始时间 start_time = str2date(before) end_time = str2date(after) #产品名称 if term: term = term.encode('utf8') else: term = "" #不合格 if bad: bad_term = '不' else: bad_term = "" #查询语句 a = pageIndex[0] - 1 b = pageIndex[1] - 1 print a,b,term,bad_term try: dataList=Ahzj.objects.filter(jyjl__contains=bad_term,shrq__range=(start_time,end_time),ypmc__contains=term)[a:b] except Exception,e: print e return dataList def getChanpinData(req): mode=req.GET.get('mode','all') page=req.GET.get('page','1') term=req.GET.get('term',None) before=req.GET.get('before','2015-01-01') after=req.GET.get('after','2015-12-31') print before,after if mode=='all': bad=False else: bad=True #分页 totalNum=getChanpinListNumByIndex(bad=bad,term=term,before=before,after=after) print "total:",totalNum paginator =Paginator(totalNum,10) #每页10条 try: page=int(page) if page < 1: page=1 except ValueError: page=1 print "page:",page #页面数据 try: dataList = getChanpinListByIndex(paginator.getIndex(page),bad=bad,term=term,before=before,after=after) except Exception, e: print e dataList = getChanpinListByIndex(paginator.getIndex(1),bad=bad,term=term,before=before,after=after) data=[] for i in dataList: each={} each['ypmc']=i.ypmc#.decode('gbk').encode('utf8') each['jyyj']=i.jyyj#.decode('gbk').encode('utf8') each['jyjl']=i.jyjl#.decode('gbk').encode('utf8') each['sjdw']=i.sjdw#.decode('gbk').encode('utf8') each['scdw']=i.scdw#.decode('gbk').encode('utf8') data.append(each) #翻页栏 after_range_num = 4 before_range_num = 5 res={} res['data'] = data res['has_previous'] = paginator.has_previous(page) res['has_next'] = paginator.has_next(page) res['page_range'] = paginator.page_range(page,before_range_num,after_range_num) res['number'] = page res['previous_page_number'] = paginator.previous_page_number(page) res['next_page_number'] = paginator.next_page_number(page) return HttpResponse(json.dumps(res), content_type='application/json') #纤维 #首页 @login_required(login_url='login') def xianweiIndex(req): data={} try: data['total'] = Ahxj.objects.all().count() data['bad'] = Ahxj.objects.all().filter(jyjl__contains='不').count() data['sc'] = ScXw.objects.all().count() except Exception , e: print e data['total']=data['bad']= data['sc']=0 ## data['totalData']={'1':2.0, '2':4.9,'3': 7.0, '4':23.2, 5525.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3] ## data['badData']=[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3] try: data['totalData'] , data['badData']=getXianweiBar(2015) except Exception , e: print e return render_to_response('qualityBase/xianweiIndex.html',data,context_instance=RequestContext(req)) #产品检测院首页柱形图数据 返回分别包含12个月的全数据量和不合格数据量的list def getXianweiBar(year): #2015年12个月的数量 total=[] for month in range(12): data = Ahxj.objects.filter(wcrq__month=month,wcrq__year=year).count() total.append(data) #2015年12个月的不合格数量 bad=[] for month in range(12): data=Ahxj.objects.filter(wcrq__month=month,wcrq__year=year,jyjl__contains='不').count() bad.append(data) print total,bad return total,bad #更新柱形图数据 def changeXianweiBar(req): year=req.GET.get('year','2015') year=int(year) res={} try: bar=getXianweiBar(year) res['totalData']=bar[0] res['badData']=bar[1] except Exception,e: print e return HttpResponse(json.dumps(res), content_type='application/json') def addSCXW(req): ypmc=req.GET.get('ypmc','') jyyj=req.GET.get('jyyj','') jl=req.GET.get('jl','') sjdw=req.GET.get('sjdw','') sc = ScXw(ypmc=ypmc,jyyj=jyyj,jl=jl,sjdw=sjdw) sc.save() res={} return HttpResponse(json.dumps(res), content_type='application/json') #获取纤维检验局收藏数据 def getXWSCList(req): dataList = ScXw.objects.all() data=[] for i in dataList: each={} each['ypmc']=i.ypmc#.decode('gbk','ignore').encode('utf8') each['jyyj']=i.jyyj#.decode('gbk','ignore').encode('utf8') each['jyjl']=i.jyjl#.decode('gbk','ignore').encode('utf8') each['sjdw']=i.sjdw#.decode('gbk','ignore').encode('utf8') data.append(each) res={} res['data'] = data return HttpResponse(json.dumps(res), content_type='application/json') #获取纤维检验局数据数量 #分页:pageIndex #不合格:bad def getXianweiListNumByIndex(bad=False,term=None,before='2015-01-01',after='2015-12-31'): try: before=before.encode('utf8') after=after.encode('utf8') except Exception ,e: print e start_time = str2date(before) end_time = str2date(after) if term: term = term.encode('utf8') else: term = "" if bad: bad_term = "不" else: bad_term = "" #查询语句 try: res =Ahxj.objects.filter(wcrq__range=(start_time,end_time),ypmc__contains=term,jyjl__contains=bad_term).count() except Exception,e: print e return res #获取纤维检验局数据 #分页:pageIndex #不合格:bad def getXianweiListByIndex(pageIndex,bad=False,term=None,before='2000-01-01',after='2015-12-31'): a = pageIndex[0]-1 b = pageIndex[1]-1 try: before=before.encode('utf8') after=after.encode('utf8') except Exception ,e: print e start_time = datetime.date(before) end_time = datetime.date(after) if term: term = term.encode('utf8') else: term = "" if bad: bad_term = '不' else: bad_term = "" print "here",term,bad_term #查询语句 try: dataList = Ahxj.objects.filter(wcrq__range=(start_time,end_time),ypmc__contains=term,jyjl__contains=bad_term)[a:b] except Exception,e: print e return dataList @login_required(login_url='login') def xianwei(req): mode=req.GET.get('mode','all') page=req.GET.get('page','1') term=req.GET.get('term',None) before=req.GET.get('before','2015-01-01') after=req.GET.get('after','2015-12-31') print before,after print "xianweiQuery:",mode,page,term if mode=='all': bad=False else: bad=True #分页 try: totalNum=getXianweiListNumByIndex(bad=bad,term=term,before=before,after=after) except Exception,e: print e print totalNum paginator =Paginator(totalNum,10) #每页10条 #获取总页数 try: page=int(req.GET.get('page','1')) if page < 1: page=1 except ValueError: page=1 ## print "page:",page #页面数据 try: dataList = getXianweiListByIndex(paginator.getIndex(page),bad=bad,term=term,before=before,after=after) except : dataList = getXianweiListByIndex(paginator.getIndex(1),bad=bad,term=term,before=before,after=after) data=[] for i in dataList: each={} each['ypmc']=i.ypmc#.decode('gbk').encode('utf8') each['jyyj']=i.jyyj#.decode('gbk').encode('utf8') each['jyxm']=i.jyxm#.decode('gbk').encode('utf8') each['jl']=i.jyjl#.decode('gbk').encode('utf8') each['scdw']=i.scdw#.decode('gbk').encode('utf8') data.append(each) #翻页栏 after_range_num = 6 before_range_num = 7 res={} res['data'] = data res['has_previous'] = paginator.has_previous(page) res['has_next'] = paginator.has_next(page) res['page_range'] = paginator.page_range(page,before_range_num,after_range_num) res['number'] = page res['previous_page_number'] = paginator.previous_page_number(page) res['next_page_number'] = paginator.next_page_number(page) res['bad']=bad res['after']=after res['before']=before return render_to_response('qualityBase/xianwei.html',res,context_instance=RequestContext(req)) def getXianweiData(req): mode=req.GET.get('mode','all') page=req.GET.get('page','1') term=req.GET.get('term',None) before=req.GET.get('before','2015-01-01') after=req.GET.get('after','2015-12-31') print before,after if mode=='all': bad=False else: bad=True #分页 totalNum=getXianweiListNumByIndex(bad=bad,term=term,before=before,after=after) print "total:",totalNum paginator =Paginator(totalNum,10) #每页10条 try: page=int(page) if page < 1: page=1 except ValueError: page=1 print "page:",page #页面数据 try: dataList = getXianweiListByIndex(paginator.getIndex(page),bad=bad,term=term,before=before,after=after) except Exception, e: print e dataList = getXianweiListByIndex(paginator.getIndex(1),bad=bad,term=term,before=before,after=after) data=[] for i in dataList: each={} each['ypmc']=i.ypmc each['jyyj']=i.jyyj each['jyxm']=i.jyxm each['jl']=i.jyjl each['scdw']=i.scdw data.append(each) #翻页栏 after_range_num = 6 before_range_num = 7 res={} res['data'] = data res['has_previous'] = paginator.has_previous(page) res['has_next'] = paginator.has_next(page) res['page_range'] = paginator.page_range(page,before_range_num,after_range_num) res['number'] = page res['previous_page_number'] = paginator.previous_page_number(page) res['next_page_number'] = paginator.next_page_number(page) return HttpResponse(json.dumps(res), content_type='application/json') #计量 #计量科研院整体概览数据 @login_required(login_url='login') def jlIndex(req): data={} try: data['total'] = Ahim.objects.all().count() data['bad'] = Ahim.objects.filter(jl__contains='不').count() data['sc'] = ScYqjyxx.objects.all().count() except Exception , e: print e data['total']=data['new']=data['bad']= data['sc']=0 ## data['totalData']={'1':2.0, '2':4.9,'3': 7.0, '4':23.2, 5525.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3] ## data['badData']=[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3] try: data['totalData'] , data['badData']=getJLBar(2015) except Exception , e: print e print data return render_to_response('qualityBase/jlIndex.html',data,context_instance=RequestContext(req)) #计量科研院首页柱形图数据 返回分别包含12个月的全数据量和不合格数据量的list def getJLBar(year): #2015年12个月的总数量 total=[] for month in range(12): data = Ahim.objects.filter(slrq__month=month,slrq__year=year).count() total.append(data) #2015年12个月的不合格数量 bad=[] for i in range(12): data = Ahim.objects.filter(slrq__month=month,slrq__year=year,jl__contains='不').count() bad.append(data) print total,bad return total,bad #计量数据总页 @login_required(login_url='login') def jl(req): mode=req.GET.get('mode','all') page=req.GET.get('page','1') term=req.GET.get('term',None) before=req.GET.get('before','2015-01-01') after=req.GET.get('after','2015-12-31') print before,after print "jlQuery:",mode,page,term if mode=='all': bad=False else: bad=True #分页 totalNum=getJLListNumByIndex(bad=bad,term=term,before=before,after=after) print totalNum paginator =Paginator(totalNum,10) #每页10条 #获取总页数 try: page=int(req.GET.get('page','1')) if page < 1: page=1 except ValueError: page=1 ## print "page:",page #页面数据 try: dataList = getJLListByIndex(paginator.getIndex(page),bad=bad,term=term,before=before,after=after) except : dataList = getJLListByIndex(paginator.getIndex(1),bad=bad,term=term,before=before,after=after) data=[] for i in dataList: each={} each['sjdw']=i.sjdw each['yqmc']=i.yqmc#.decode('gbk','ignore').encode('utf8') each['ggxh']=i.ggxh#.decode('gbk','ignore').encode('utf8') each['ccbh']=i.ccbh#.decode('gbk','ignore').encode('utf8') each['jl']=i.jl#.decode('gbk','ignore').encode('utf8') data.append(each) #翻页栏 after_range_num = 6 before_range_num = 7 res={} res['data'] = data res['has_previous'] = paginator.has_previous(page) res['has_next'] = paginator.has_next(page) res['page_range'] = paginator.page_range(page,before_range_num,after_range_num) res['number'] = page res['previous_page_number'] = paginator.previous_page_number(page) res['next_page_number'] = paginator.next_page_number(page) res['bad']=bad res['after']=after res['before']=before return render_to_response('qualityBase/jl.html',res,context_instance=RequestContext(req)) #return render_to_response('chanpin.html',locals(),req) def addSCJL(req): yqmc=req.GET.get('yqmc') ggxh=req.GET.get('ggxh') jl=req.GET.get('jl') sjdw=req.GET.get('sjdw') try: yqmc=yqmc.encode('utf-8') ggxh=ggxh.encode('utf-8') jl=jl.encode('utf-8') sjdw=sjdw.encode('utf-8') except Exception,e: print e sc = ScYqjyxx(yqmc=yqmc,ggxh=ggxh,jl=jl,sjdw=sjdw) sc.save() res={} return HttpResponse(json.dumps(res), content_type='application/json') #获取计量科学院收藏数据 def getJLSCList(req): dataList = ScYqjyxx.objecs.all() data=[] for i in dataList: each={} each['yqmc']=i.yqmc#.decode('gbk','ignore').encode('utf8') each['ggxh']=i.ggxh#.decode('gbk','ignore').encode('utf8') each['jl']=i.jl#.decode('gbk','ignore').encode('utf8') each['sjdw']=i.sjdw#.decode('gbk','ignore').encode('utf8') data.append(each) res={} res['data'] = data return HttpResponse(json.dumps(res), content_type='application/json') #获取计量科学院数据 #分页:pageIndex #不合格:bad def getJLListNumByIndex(bad=False,term=None,before='2015-01-01',after='2015-12-31'): try: before=before.encode('utf8') after=after.encode('utf8') except Exception ,e: print e start_time = str2date(before) end_time = str2date(after) if term: term = term.encode('utf8') else: term = '' if bad: bad_term = '不' else: bad_term = '' #查询语句 res = Ahim.objects.filter(slrq__range=(start_time,end_time),yqmc__contains=term,jl__contains=bad_term).count() print bad,term,before,after,res return res # 获取计量科研院数据 # 分页:pageIndex # 不合格:bad def getJLListByIndex(pageIndex,bad=False,term=None,before='2015-01-01',after='2015-12-31'): a = pageIndex[0]-1 b = pageIndex[1]-1 try: before=before.encode('utf8') after=after.encode('utf8') except Exception ,e: print e start_time = str2date(before) end_time = str2date(after) if term: term = term.encode('utf8') else: term = '' if bad: bad_term = '不' else: bad_term = '' # 查询语句 dataList = Ahim.objects.filter(slrq__range=(start_time,end_time),yqmc__contains=term,jl__contains=bad_term)[a:b] return dataList # 获得数据 def getJLData(req): mode=req.GET.get('mode','all') page=req.GET.get('page','1') term=req.GET.get('term',None) before=req.GET.get('before','2015-01-01') after=req.GET.get('after','2015-12-31') print before,after if mode=='all': bad=False else: bad=True # 分页 totalNum=getJLListNumByIndex(bad=bad,term=term,before=before,after=after) print "total:",totalNum paginator =Paginator(totalNum,10) # 每页10条 try: page=int(page) if page < 1: page=1 except ValueError: page=1 print "page:",page # 页面数据 try: dataList = getJLListByIndex(paginator.getIndex(page),bad=bad,term=term,before=before,after=after) except Exception, e: print e dataList = getJLListByIndex(paginator.getIndex(1),bad=bad,term=term,before=before,after=after) data=[] for i in dataList: each={} each['sjdw']=i.sjdw #.decode('gbk').encode('utf8') each['yqmc']=i.yqmc #.decode('gbk').encode('utf8') each['ggxh']=i.ggxh #.decode('gbk').encode('utf8') each['ccbh']=i.ccbh #.decode('gbk').encode('utf8') each['jl']=i.jl #.decode('gbk').encode('utf8') data.append(each) # 翻页栏 after_range_num = 6 before_range_num = 7 res={} res['data'] = data res['has_previous'] = paginator.has_previous(page) res['has_next'] = paginator.has_next(page) res['page_range'] = paginator.page_range(page,before_range_num,after_range_num) res['number'] = page res['previous_page_number'] = paginator.previous_page_number(page) res['next_page_number'] = paginator.next_page_number(page) return HttpResponse(json.dumps(res), content_type='application/json') #铜铅锌 def tqx(req): return render_to_response('tqx.html',{},context_instance=RequestContext(req)) #常用字典 # PROVINCE={'北京市':'1','天津市':'2','上海市':'3','重庆市':'4','河北省':'5','河南省':'6','江苏省':'7',\ # '广东省':'8','山东省':'9','山西省':'10','陕西省':'11','浙江省':'12','黑龙江省':'13','辽宁省':'14',\ # '吉林省':'15','四川省':'16','湖北省':'17','湖南省':'18','江西省':'19','广西省':'20','安徽省':'21',\ # '福建省':'22','云南省':'23','甘肃省':'24'} PROVINCE={'1':'北京市','2':'天津市','3':'上海市','4':'重庆市','5':'河北省','6':'河南省','7':'江苏省',\ '8':'广东省','9':'山东省','10':'山西省','11':'陕西省','12':'浙江省','13':'黑龙江省','14':'辽宁省',\ '15':'吉林省','16':'四川省','17':'湖北省','18':'湖南省','19':'江西省','20':'广西省','21':'安徽省',\ '22':'福建省','23':'云南省','24':'甘肃省'} #国抽产品字典 GC_PRODUCT={'1':'安全帽','2':'储水式电热水器','3':'电冰箱','4':'电力变压器','5':'家用太阳能热水器','6':'汽车制动液','7':'杀虫气雾剂','8':'植物保护机械'} # 国家抽查 @login_required(login_url='login') def gjccIndex(req): data={} try: data['total'] = Nsi.objects.all().count() data['bad'] = Nsi.objects.filter(jl__contains='不').count() data['product'] = len(GC_PRODUCT) except Exception , e: print e data['total'],data['bad'],data['product']=0 ## data['totalData']={'1':2.0, '2':4.9,'3': 7.0, '4':23.2, 5525.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3] ## data['badData']=[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3] try: data['anhuiData'],data['chinaData']=getGCLine('1') data['anhuiRadar'],data['pkRadar']=getGCRadar('7') print "succes" except Exception , e: print e data['productname']=GC_PRODUCT['1'] data['pkcity']=PROVINCE['7'] print data return render_to_response('qualityBase/gjccIndex.html',data,context_instance=RequestContext(req)) def getGCQRate(province='0',product='1',year=2013): if province=='0': bad = Nsi.objects.filter(jl__contains='不',year__contains=year,cplb__contains=GC_PRODUCT[product]).count() total = Nsi.objects.filter(year__contains=year,cplb__contains=GC_PRODUCT[product]).count() else: bad = Nsi.objects.filter(jl__contains='不',year__contains=year,cplb__contains=GC_PRODUCT[product],region__contains=PROVINCE[province]).count() total = Nsi.objects.filter(year__contains=year,cplb__contains=GC_PRODUCT[product],region__contains=PROVINCE[province]).count() if total>0: res=(total-bad)/float(total) res=round(res*100,2) else: res=0 return res #国家监督抽查首页柱形图数据 返回分别包含三年的的全部省份该产品的合格率折线数据 def getGCLine(product): #三年各省的合格率的总数量 anhuiData=[] for j in range(2013,2016): anhuiData.append(getGCQRate(year=str(j),product=product,province='21')) chinaData=[] for j in range(2013,2016): chinaData.append(getGCQRate(year=str(j),product=product,province='0')) print anhuiData,chinaData return anhuiData,chinaData def changeGCBar(req): product=req.GET.get('product','1') product=str(product) res={} try: res['anhuiData'],res['chinaData']=getGCLine(product) except Exception,e: print e res['productname']=GC_PRODUCT[product] return HttpResponse(json.dumps(res), content_type='application/json') #国家监督抽查首页柱形图数据 返回分别包含安徽和另个省的雷达数据 def getGCRadar(province='7'): #三年各省的合格率的总数量 anhuiData=[] #productList=['1','2','3','4','5','6'] for i in range(1,7): count=0 total=0 for year in range(2013,2016): item=getGCQRate(year=str(year),product=str(i),province='21') if item>0: count+=1 total+=item total=round(total/count,2) anhuiData.append(total) pkData=[] for i in range(1,7): count=0 total=0 for year in range(2013,2016): item=getGCQRate(year=str(year),product=str(i),province=province) if item>0: count+=1 total+=item total=round(total/count,2) pkData.append(total) print anhuiData,pkData return anhuiData,pkData def changeGCRadar(req): province=req.GET.get('province','7') province=str(province) res={} try: res['anhuiRadar'], res['pkRadar']=getGCRadar(province) except Exception,e: print e res['pkcity']=PROVINCE[province] return HttpResponse(json.dumps(res), content_type='application/json') ############# ###外部数据### ############ #工商数据 def gongshang(req): return render_to_response('tqx.html',{},context_instance=RequestContext(req)) #环保数据 def huanbao(req): return render_to_response('huanbao.html',{},context_instance=RequestContext(req)) ############# ###质量状况### ############ #行业 def industry(req): return render_to_response('industry.html',{},context_instance=RequestContext(req)) #产品 def product(req): return render_to_response('product.html',{},context_instance=RequestContext(req)) #区域 def region(req): return render_to_response('region.html',{},context_instance=RequestContext(req)) #品牌 def brand(req): return render_to_response('brand.html',{},context_instance=RequestContext(req)) #企业 def enterprise(req): return render_to_response('enterprise.html',{},context_instance=RequestContext(req)) ############# ###质量舆情### ############ #宏观政策 def hgzc(req): return render_to_response('news1.html',{},context_instance=RequestContext(req)) #质检要闻 def zjyw(req): return render_to_response('news2.html',{},context_instance=RequestContext(req)) #行业报道 def hybd(req): return render_to_response('news3.html',{},context_instance=RequestContext(req)) #企业动态 def qydt(req): return render_to_response('news4.html',{},context_instance=RequestContext(req)) ############ ##应用分析## ############ #电梯 @login_required(login_url='login') def dtIndex(req): data,total=getDTNum() res={} res['data']=data res['total']=total return render_to_response('riskAnalysis/diantiIndex.html',res,context_instance=RequestContext(req)) def getDTNum(): #取得前六电梯数目的城市 try: dataList = ElevatorNum.objects.order_by('count')[0:5] except Exception,e: print e data = [] for i in range(len(dataList)): each={} each['index']=i+1 each['city']=dataList[i].region.encode('utf8')#.decode('gbk').encode('utf8') each['count']=dataList[i].count data.append(each) print data #取得全部电梯数 dataList = ElevatorNum.objects.all() total=0 for i in dataList: total += i.count return data,total def dttj(req): mode=req.GET.get('mode','zhi') city=req.GET.get('city','合肥市') try: city=city.encode('utf8') except Exception,e: print e city='合肥市' data=getDTZT(city) res={} res['city']=city res['origin']=data return render_to_response('riskAnalysis/diantitongji.html',res,context_instance=RequestContext(req)) def dtwb(req): mode=req.GET.get('mode','zhi') return render_to_response('riskAnalysis/diantiweibao.html',{},context_instance=RequestContext(req)) ''' 安徽各地市 ''' AC={'合肥市':'1','滁州市':'2','宣城市':'3','黄山市':'4','蚌埠市':'5','池州市':'6','安庆市':'7','马鞍山市':'8','宿州市':'9','淮北市':'10','铜陵市':'11','亳州市':'12','六安市':'13','芜湖市':'14','淮南市':'15','阜阳市':'16',} '''省份表 ''' def getDTZT(city): conn = MySQLdb.connect(host=DB_HOST,port=DB_PORT,user=DB_USER,passwd=<PASSWORD>,db=DB_NAME,charset=DB_CHARSET) cursor=conn.cursor() data=[] for i in range(12): a=i+1 cityNum=AC[city] queryString="select JYXM , C"+cityNum+" from elevator where JYXMBH="+str(a) try: cursor.execute(queryString) r=cursor.fetchall()[0] print r[0],r[1] each={} each['index']=a each['name']=r[0] each['count']=int(float(r[1])*100) data.append(each) except Exception,e: print e cursor.close() conn.close() return data def getDTZTData(req): city=req.GET.get('city') city=city.encode('utf8') res={} res['city']=city res['data']=getDTZT(city) try: result=json.dumps(res) except Exception,e: print e return HttpResponse(result, content_type='application/json') #电缆 @login_required(login_url='login') def dianlanIndex(req): data={} data['total'] = Cable.objects.all().count() data['bad'] = Cable.objects.filter(jl__contains='不').count() data['sc'] = ScDianlan.objects.all().count() ## data['totalData']={'1':2.0, '2':4.9,'3': 7.0, '4':23.2, 5525.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3] ## data['badData']=[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3] try: data['totalData'] , data['badData']=getDLBar(2015) except Exception , e: print e return render_to_response('riskAnalysis/dianlanIndex.html',data,context_instance=RequestContext(req)) def getDLBar(year): #2015年12个月的总数量 total=[] c=['合肥','阜阳','滁州','安庆','淮北','淮南','六安','马鞍山','铜陵','芜湖','宿州','宣城'] for i in c: count=Cable.objects.filter(city__contains=i).count() total.append(count) #2015年12个月的不合格数量 bad=[] for i in c: count=Cable.objects.filter(city__contains=i,jl__contains='不').count() bad.append(count) print total,bad return total,bad def addSCDL(req): ypmc=req.GET.get('ypmc').encode('utf-8') ggxh=req.GET.get('ggxh').encode('utf-8') jl=req.GET.get('jl').encode('utf-8') sjdw=req.GET.get('sjdw').encode('utf-8') ScDianlan(ypmc=ypmc,ggxh=ggxh,jl=jl,sjdw=sjdw).save() res={} return HttpResponse(json.dumps(res), content_type='application/json') #获取电缆收藏数据 def getDLSCList(req): dataList=ScDianlan.objects.all() data=[] for i in dataList: each={} try: each['qymc']=i.qymc#.decode('gbk').encode('utf8') except Exception,e: each['qymc']="" print e try: each['cpmc']=i.cpmc#.decode('gbk').encode('utf8') except Exception,e: each['cpmc']="" print e try: each['ggxh']=i.ggxh#.decode('gbk').encode('utf8') except Exception,e: each['ggxh']="" print e try: each['jl']=i.jl#.decode('gbk').encode('utf8') except Exception,e: each['jl']="" print e data.append(each) print data res={} res['data'] = data return HttpResponse(json.dumps(res), content_type='application/json') #电缆抽查数据总页 def dianlan(req): mode=req.GET.get('mode','all') page=req.GET.get('page','1') term=req.GET.get('term',None) before=req.GET.get('before','2015-01-01') after=req.GET.get('after','2015-12-31') city=req.GET.get('city',None) print before,after print "here:",mode,page,term,city if mode=='all': bad=False else: bad=True #分页 totalNum=getDLListNumByIndex(bad=bad,term=term,before=before,after=after,city=city) print totalNum paginator =Paginator(totalNum,10) #每页10条 #获取总页数 try: page=int(req.GET.get('page','1')) if page < 1: page=1 except ValueError: page=1 ## print "page:",page #页面数据 try: dataList = getDLListByIndex(paginator.getIndex(page),bad=bad,term=term,before=before,after=after,city=city) except : dataList = getDLListByIndex(paginator.getIndex(1),bad=bad,term=term,before=before,after=after,city=city) data=[] for i in dataList: each={} each['qymc'] = i.qymc each['cpmc'] = i.cpmc each['ggxh'] = i.ggxh each['jl'] = i.jl each['city'] = i.city data.append(each) #翻页栏 after_range_num = 3 before_range_num = 3 res={} res['data'] = data res['has_previous'] = paginator.has_previous(page) res['has_next'] = paginator.has_next(page) res['page_range'] = paginator.page_range(page,before_range_num,after_range_num) res['number'] = page res['previous_page_number'] = paginator.previous_page_number(page) res['next_page_number'] = paginator.next_page_number(page) res['bad']=bad res['after']=after res['before']=before return render_to_response('riskAnalysis/dianlan.html',res,context_instance=RequestContext(req)) #return render_to_response('chanpin.html',locals(),req) #获取电缆抽查数据 #分页:pageIndex #不合格:bad def getDLListNumByIndex(bad=False,term=None,before='2015-01-01',after='2015-12-31',city=None): try: before=before.encode('utf8') after=after.encode('utf8') except Exception ,e: print e start_time = str2date(before) end_time = str2date(after) if city: city = city.encode('utf8') else: city = "" if term: term = term.encode('utf8') else: term = "" if bad: bad_term = '不' else: bad_term='' #查询语句 try: res = Cable.objects.filter(jl__contains=bad_term,city__contains=city,cpmc__contains=term,scrq__range=(start_time,end_time)).count() except Exception,e: print e print bad,term,before,after,res return res def getDLListByIndex(pageIndex,bad=False,term=None,before='2015-01-01',after='2015-12-31',city=None): try: before=before.encode('utf8') after=after.encode('utf8') except Exception ,e: print e start_time = str2date(before) end_time = str2date(after) if city: city = city.encode('utf8') else: city = "" if term: term = term.encode('utf8') else: term = "" if bad: bad_term = '不' else: bad_term='' b = pageIndex[1]-1 a = pageIndex[0]-1 #查询语句 try: dataList = Cable.objects.filter(jl__contains=bad_term,city__contains=city,cpmc__contains=term,scrq__range=(start_time,end_time))[a:b] except Exception,e: print e return dataList #获得数据 def getDLData(req): mode=req.GET.get('mode','all') page=req.GET.get('page','1') term=req.GET.get('term',None) before=req.GET.get('before','2015-01-01') after=req.GET.get('after','2015-12-31') print before,after if mode=='all': bad=False else: bad=True #分页 totalNum=getDLListNumByIndex(bad=bad,term=term,before=before,after=after) print "total:",totalNum paginator =Paginator(totalNum,10) #每页10条 try: page=int(page) if page < 1: page=1 except ValueError: page=1 print "page:",page #页面数据 try: dataList = getDLListByIndex(paginator.getIndex(page),bad=bad,term=term,before=before,after=after) except Exception, e: print e dataList = getDLListByIndex(paginator.getIndex(1),bad=bad,term=term,before=before,after=after) data=[] for i in dataList: each={} each['qymc']=i.qymc each['cpmc']=i.cpmc each['ggxh']=i.ggxh each['jl']=i.jl each['city']=i.city each['jl']=i.jl data.append(each) #翻页栏 after_range_num = 6 before_range_num = 7 res={} res['data'] = data res['has_previous'] = paginator.has_previous(page) res['has_next'] = paginator.has_next(page) res['page_range'] = paginator.page_range(page,before_range_num,after_range_num) res['number'] = page res['previous_page_number'] = paginator.previous_page_number(page) res['next_page_number'] = paginator.next_page_number(page) return HttpResponse(json.dumps(res), content_type='application/json') #质量状况 #进口不合格产品 @login_required(login_url='login') def entranceIndex(req): return render_to_response('qualityBase/entranceIndex.html',{},context_instance=RequestContext(req)) #产品抽查 @login_required(login_url='login') def inspectionIndex(req): return render_to_response('qualityBase/inspectionIndex.html',{},context_instance=RequestContext(req)) #网络交易 @login_required(login_url='login') def onlinetradingIndex(req): return render_to_response('qualityBase/onlinetradingIndex.html',{},context_instance=RequestContext(req)) #质量舆情 def riskWarning(req): return render_to_response('riskWarning/index.html',{},context_instance=RequestContext(req)) #词云模块 def wordCloud(req): return render_to_response('riskWarning/wordCloud.html',{},context_instance=RequestContext(req)) #WebGIS #全国地图 def mapChina(req): return render_to_response('webGis/map_china.html',{},context_instance=RequestContext(req)) #安徽地图 def mapAnhui(req): return render_to_response('webGis/map_anhui.html',{},context_instance=RequestContext(req)) #经济数据 def economic(req): return render_to_response('qualityBase/economic.html',{},context_instance=RequestContext(req)) #国抽数据 def gc(req): return render_to_response() <file_sep>#coding:utf8 from django.shortcuts import render_to_response,render,get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.models import User from django.contrib import auth from django.contrib import messages from django.template.context import RequestContext from django.forms.formsets import formset_factory from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.contrib.auth.decorators import login_required from .forms import LoginForm import logging logger = logging.getLogger('anhui.login.views') from log.ip_config import getIP def login(req): ip = getIP(req) if req.method == 'GET': form = LoginForm() return render_to_response('login/login.html', RequestContext(req, {'form': form,})) else: form = LoginForm(req.POST) if form.is_valid(): username = req.POST.get('username', '') #返回的username是unicode password = req.POST.get('password', '') url = req.get_full_path() redirect_url = "" try: redirect_url = url.split('?next=')[1] print redirect_url except Exception,e: print e pass user = auth.authenticate(username=username, password=<PASSWORD>) if user is not None and user.is_active: auth.login(req, user) log_string = "[IP:" + ip + "][登陆成功][用户名:" + str(username) + "]" logger.info(log_string) req.session.set_expiry(600) if redirect_url!="": return HttpResponseRedirect(redirect_url) return HttpResponseRedirect('/totalView/') else: log_string = "[IP:" + ip + "][登陆失败][用户名或密码有误]" logger.info(log_string) return render_to_response('login/login.html', RequestContext(req, {'form': form,'password_is_wrong':True})) else: return render_to_response('login/login.html', RequestContext(req, {'form': form})) #注销 @login_required(login_url='/login/') def logout(req): auth.logout(req) return HttpResponseRedirect("/login/") #修改密码 #@login_required def changepwd(req): print 'change password!' if req.method == 'GET': try: form = ChangepwdForm() except Exception: traceback.print_exc() print 'form get init' return render_to_response('changepwd.html',RequestContext(req,{'form':form})) else: form = ChangepwdForm(req.POST) if form.is_valid(): username = req.user.username oldpassword = req.POST.get('oldpassword','') user = auth.authenticate(username=username,password=old<PASSWORD>) if user is not None and user.is_active: newpassword1 = req.POST.get('newpassword1','') #newpass word2 = req.POST.get('newpassword2') user.set_password(<PASSWORD>) user.save() return render_to_response('total_view.html',RequestContext(req,{'changepwd_success':True})) else: return render_to_response('changepwd.html',RequestContext(req,{'form':form,'oldpassword_is_wrong':True})) else: return render_to_response('changepwd.html',RequestContext(req,{'form':form})) #注册 def regist(req): print "regist" return HttpResponse("请联系管理员!进行后台注册!") #丢失密码 def forgetpwd(req): return HttpResponse("请联系管理员!找回丢失密码!") <file_sep>#coding=utf8 from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings from views import * #testchocolat urlpatterns = patterns('', url(r'^$', totalView,name='index'), url(r'^admin/', include(admin.site.urls)), url(r'^login/', include('login.urls')), url(r'^base/', include('base.urls')), url(r'^show/', include('show.urls')), url(r'^credit/',include('credit.urls')), #后台首页 url(r'^totalView/$', totalView,name='totalView'), url(r'^index/$',index,name = 'index'), #静态文件路径 (r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_URL}), ) <file_sep>#coding:utf8 """ Django settings for anhui project. Generated by 'django-admin startproject' using Django 1.8.3. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<KEY>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False TEMPLATE_DEBUG = False ALLOWED_HOSTS = '*' # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ) ROOT_URLCONF = 'anhui.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR+"/templates",], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'anhui.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'anhuiend', 'USER': 'root', 'PASSWORD': '<PASSWORD>', 'HOST': '172.16.58.3', 'PORT': '16001',} } ## 'db1': { ## 'ENGINE': 'django.db.backends.oracle', ## 'NAME': 'orcl', ## 'USER': 'xianwei', ## 'PASSWORD': '<PASSWORD>', ## 'HOST': '172.16.58.3', ## 'PORT': '15001',}, ## 'db2': { ## 'ENGINE': 'django.db.backends.oracle', ## 'NAME': 'orcl', ## 'USER': 'gc', ## 'PASSWORD': 'gc', ## 'HOST': '172.16.58.3', ## 'PORT': '15001',} # use multi-database in django # add by WeizhongTu ##DATABASE_ROUTERS = ['anhui.database_router.DatabaseAppsRouter'] ##DATABASE_APPS_MAPPING = { ## # example: ## #'app_name':'database_name', ## 'model': 'default', ## 'xianwei': 'db1', ##} # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = './static/' #Session settings SESSION_EXPIRE_AT_BROWSER_CLOSE = True #Logging import logging import django.utils.log import logging.handlers #Refer TO #http://davidbj.blog.51cto.com/4159484/1433741 #http://python.usyiyi.cn/django/topics/logging.html #日志记录操作:登陆注册等放在一起 LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters':{ 'standard': { 'format': '%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(module)s:%(funcName)s] [%(levelname)s]- %(message)s'} }, 'handlers':{ 'file':{ 'level':'INFO', 'class':'logging.handlers.RotatingFileHandler', 'filename':'log/file.log', 'formatter':'standard', }, }, 'loggers':{ 'anhui.login.views':{ 'handlers':['file'], 'level':'INFO', 'propagate':True, }, }, } <file_sep>#coding:utf8 from django.http import HttpRequest def getIP(request): ''' 正常状况REMOTE_ADDR代表用户的ip 若使用nginx做代理或者做了负载均衡,REMOTE_ADDR得到的则是127.0.0.1 此时HTTP_X_FORWARDED_FOR才是用户的实际ip ''' if request.META.has_key('HTTP_X_FORWARDED_FOR'): ip = request.META['HTTP_X_FORWARDED_FOR'] else: ip = request.META['REMOTE_ADDR'] return ip <file_sep>#coding=utf8 from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings from views import * #前台页面 urlpatterns = patterns('', #后台门户 url(r'^totalindex/$',totalindex,name = 'totalindex') , url(r'^consumer/$',consumer,name = 'consumer'), url(r'^consumer1/$',consumer1,name = 'consumer1'), url(r'^consumer2/$',consumer2,name = 'consumer2'), url(r'^consumer3/$',consumer3,name = 'consumer3'), url(r'^consumer4/$',consumer4,name = 'consumer4'), url(r'^gover/$',gover,name = 'gover') , url(r'^gover1/$',gover1,name = 'gover1') , url(r'^gover2/$',gover2,name = 'gover2') , url(r'^gover3/$',gover3,name = 'gover3') , url(r'^gover4/$',gover4,name = 'gover4') , url(r'^friendlink/$',friendlink,name = 'friendlink') , url(r'^industries/$',industries,name = 'industries') , url(r'^industry1/$',industry1,name = 'industry1') , url(r'^industry2/$',industry2,name = 'industry2') , url(r'^industry3/$',industry3,name = 'industry3') , url(r'^industry4/$',industry4,name = 'industry4') , url(r'^others/$',others,name = 'others') , url(r'^publicservice/$',publicservice,name = 'publicservice') , url(r'^publicservice1/$',publicservice1,name = 'publicservice1') , url(r'^publicservicelink/$',publicservicelink,name = 'publicservicelink') , url(r'^new1/$',new1,name = 'new1'), )
1a0946c606241d650d5c7ef399cc919f6ce15e7e
[ "Python" ]
14
Python
Darcyfork/anhui9017
9616f602327092776d00650c59fc4103f0c4071f
aca1bb6bd9a88ce6ca1c052802f12a10229894ce
refs/heads/master
<file_sep> library(xlsx) library(dplyr) library(ggplot2) library(reshape2) library(data.table) library(ggmap) library(rjson) library(rlist) # # install.packages("rlist") library(RJDBC) # ??RJDBC #RJDBCcon <-odbcConnect("test2",uid="root",pwd="<PASSWORD>") # ?dbListTables # channel <- odbcDriverConnect("test1") dev<-JDBC("com.mysql.jdbc.Driver", "C:\\jar\\mysql-connector-java-5.1.38\\mysql-connector-java-5.1.38-bin.jar" ) conn<-dbConnect(dev, "jdbc:mysql://localhost:3306/etag", "root", "ceciits" ) dbListTables(conn) dblist<-c("tce01_20160102","tce01_20160103" ,"tce01_20160104", "tce01_20160105", "tce01_20160106", "tce01_20160107", "tce01_20160108" ,"tce01_20160109" ,"tce01_20160110", "tce01_20160111" ,"tce01_20160112") total<-length(dblist) # dblist[1] # # x.dates<-c("17.03.2001", "16.03.2001", "15.03.2001") # x.times<-c("23:39:15", "23:50:00", "22:23:43") # x.datetime <- paste(x.dates,x.times) # str(strptime(x.datetime, "%d.%m.%Y %H:%M:%S")) # revise to %d.%m.%Y # Sys.setlocale("LC_TIME", lct) # # lct <- Sys.getlocale("LC_TIME") # Sys.setlocale("LC_TIME", "C") # str(z) # # date<-"2013-11-14" # date<-as.Date(date) # # ss<- weekdays(date) # # ?as.ITime # (as.ITime("10:45")) # # aa<-as.POSIXct(186480,origin="1970-1-1") # aa single_veicle_tr_info_finall<-list() for(dd in 1:total){ sqlQuerytb<-paste("select * from",dblist[dd], sep=" " ) test_data<-dbGetQuery(conn,sqlQuerytb) test_data<-mutate(test_data,full_time=as.POSIXct(strptime(paste(date,time),"%Y-%m-%d %H:%M:%S"))) date_start_time<-as.POSIXct(test_data$date[1]) date_start_time<-as.numeric(date_start_time) date<-as.Date(test_data$date[1]) week<-weekdays(date) pathnum<-nrow(od_patt) weekdays=c("星期一","星期二","星期三","星期四","星期五") holidays=c("星期六","星期日") for(numm in 1:pathnum){ o_point<-as.character(od_patt$o_station[numm]) d_point<-as.character(od_patt$d_station[numm]) # tt_epc_trt<-list() # o_point<-"etag-04" # d_point<-"etag-05" for(ts in 1:48){ #30mins一個time range timestep_start<-ts*30*60/3600 od_set<-filter(test_data,as.numeric(test_data$full_time) < date_start_time+30*60*ts & as.numeric(test_data$full_time)>=date_start_time+30*60*(ts-1)) od_set_o<-filter(od_set,od_set$station==o_point) #時間範圍內過o點的所有epc if(nrow(od_set_o)==0){ next; } else{ epc_list<-data.frame(od_set_o$epc,od_set_o$full_time) colnames(epc_list)<-c("epc","ps_o_time") for(i in 1:nrow(epc_list)){ o_epc<-as.character(epc_list$epc[i]) ps_o_time<-as.numeric(epc_list$ps_o_time[i]) #目標epc過o點時間 od_set_o<-filter(test_data,epc==o_epc & station==d_point & as.numeric(full_time)>ps_o_time) if(nrow(od_set_o)==0){ next; } else{ ps_d_time<-as.numeric(sort(od_set_o$full_time)[1])#目標epc過d點時間 epc_od_trt<-ps_d_time-ps_o_time vc_type<-substr(o_epc,start=6,stop=6) # single_epc_trt<-c(o_epc,epc_od_trt) # # tt_epc_trt<-c(tt_epc_trt,list(single_epc_trt)) sg_v_data<-list(vc_type=vc_type,o_epc=o_epc,epc_od_trt=epc_od_trt) time_info<-list(week=week,date=date,time=timestep_start) roadpth_info<-list(o_point=o_point,d_point=d_point) single_veicle_tr_info<-list(roadpth_info=roadpth_info,time_info=time_info,sg_v_data=sg_v_data) single_veicle_tr_info_finall<-c(single_veicle_tr_info_finall,list(single_veicle_tr_info)) } } } } } } single_veicle_tr_info_finall head(single_veicle_tr_info_finall) single_veicle_tr_info_finall[[27201]] ltt<-List(single_veicle_tr_info_finall) ltt lttt<-List(ltt,single_veicle_tr_info_finall) str(ltt) a<-c(1,2,3) b<-c(1) aa<-c(1,2,3,4,5) is.element(b, aa) (is.element(aa, b)) pathnum<-nrow(od_patt) s_car_total_data<-ltt$filter(sg_v_data$vc_type==3) #小車 l_car_total_data<-ltt$filter(sg_v_data$vc_type==4) #大車 sum_od_data_finall<-c() for( tsp in 1:48){ # ts=tsp/2 # for(numm in 1:pathnum){ # tsp=2 # numm=1 s_o_point<-as.character(od_patt$o_station[numm]) s_d_point<-as.character(od_patt$d_station[numm]) s_car_sum_trt_w<-s_car_total_data$filter(is.element(time_info$week,weekdays) & time_info$time== ts & roadpth_info$o_point==s_o_point & roadpth_info$d_point==s_d_point ) l_car_sum_trt_w<-l_car_total_data$filter(is.element(time_info$week,weekdays)& time_info$time== ts & roadpth_info$o_point==s_o_point & roadpth_info$d_point==s_d_point ) W_s_car_sum_trt_num=length(s_car_sum_trt_w$map(sg_v_data$epc_od_trt)[]) W_l_car_sum_trt_num=length(l_car_sum_trt_w$map(sg_v_data$epc_od_trt)[]) if(W_s_car_sum_trt_num!=0){ datalist<-as.numeric(s_car_sum_trt_w$map(sg_v_data$epc_od_trt)[]) W_s_car_sum_trt_median=median(datalist) } else{ W_s_car_sum_trt_median=NULL } if(W_l_car_sum_trt_num!=0){ datalist<-as.numeric(l_car_sum_trt_w$map(sg_v_data$epc_od_trt)[]) W_l_car_sum_trt_median=median(datalist) } else{ W_l_car_sum_trt_median=NULL } s_car_sum_trt_h<-s_car_total_data$filter(is.element(time_info$week,holidays) & time_info$time== ts & roadpth_info$o_point==s_o_point & roadpth_info$d_point==s_d_point ) l_car_sum_trt_h<-l_car_total_data$filter(is.element(time_info$week,holidays) & time_info$time== ts & roadpth_info$o_point==s_o_point & roadpth_info$d_point==s_d_point ) H_s_car_sum_trt_num=length(s_car_sum_trt_h$map(sg_v_data$epc_od_trt)[]) H_l_car_sum_trt_num=length(l_car_sum_trt_h$map(sg_v_data$epc_od_trt)[]) if(H_s_car_sum_trt_num!=0){ datalist<-as.numeric(s_car_sum_trt_h$map(sg_v_data$epc_od_trt)[]) H_s_car_sum_trt_median=median(datalist) } else{ H_s_car_sum_trt_median=NULL } if(H_l_car_sum_trt_num!=0){ datalist<-as.numeric(l_car_sum_trt_h$map(sg_v_data$epc_od_trt)[]) H_l_car_sum_trt_median=median(datalist) } else{ H_l_car_sum_trt_median=NULL } sum_od_data<-c(W_s_car_sum_trt_num,W_l_car_sum_trt_num,W_s_car_sum_trt_median,W_l_car_sum_trt_median, H_s_car_sum_trt_num,H_l_car_sum_trt_num,H_s_car_sum_trt_median,H_l_car_sum_trt_median) sum_od_data_finall<-cbind(sum_od_data_finall,sum_od_data) } } # tt_epc_trt # ddf<-as.data.frame(tt_epc_trt) # # f1<-c(1,2) # f2<-c(1,3) # f3<-list(f1=c(1,4)) # # f_list1<-list(f1=f1,f2=f2) # # f_list1<-f_list1.app # f_list1 # f_list2<-append(f_list1,f3) # # f_list2<-c(f_list1,f3) # f_list2 # f_list1<-f_list1 # # str(f_list2) # f_list2[[i]][2] # f_list2$ # # dff<-as.data.frame(f_list3) # str(dff) # name1<-f_list2[[1]] # str(f_list2) # f_list2.name1 # epc_ip=c() # trt_t=c() # dff<-list(epc_ip=c(),trt_t=c()) # str(dff) # add_ip=1 # # add_trt=23 # # epc_ip=c(epc_ip,add_ip) # trt_t=c(trt_t,add_trt) # # dff<-list(epc_ip=epc_ip,trt_t=trt_t) # # dff # # (dff$trt_t==23) # } # kkk$time<-as.POSIXct(kkk$time) str(kk_m) dbWriteTable(conn,"test11",kkk) dbDisconnect(conn) <file_sep>library(xlsx) library(dplyr) library(ggplot2) library(reshape2) library(data.table) library(ggmap) library(rjson) # install.packages("bitops") decodeLine <- function(encoded){ require(bitops) vlen <- nchar(encoded) vindex <- 0 varray <- NULL vlat <- 0 vlng <- 0 while(vindex < vlen){ vb <- NULL vshift <- 0 vresult <- 0 repeat{ if(vindex + 1 <= vlen){ vindex <- vindex + 1 vb <- as.integer(charToRaw(substr(encoded, vindex, vindex))) - 63 } vresult <- bitOr(vresult, bitShiftL(bitAnd(vb, 31), vshift)) vshift <- vshift + 5 if(vb < 32) break } dlat <- ifelse( bitAnd(vresult, 1) , -(bitShiftR(vresult, 1)+1) , bitShiftR(vresult, 1) ) vlat <- vlat + dlat vshift <- 0 vresult <- 0 repeat{ if(vindex + 1 <= vlen) { vindex <- vindex+1 vb <- as.integer(charToRaw(substr(encoded, vindex, vindex))) - 63 } vresult <- bitOr(vresult, bitShiftL(bitAnd(vb, 31), vshift)) vshift <- vshift + 5 if(vb < 32) break } dlng <- ifelse( bitAnd(vresult, 1) , -(bitShiftR(vresult, 1)+1) , bitShiftR(vresult, 1) ) vlng <- vlng + dlng varray <- rbind(varray, c(vlat * 1e-5, vlng * 1e-5)) } coords <- data.frame(varray) names(coords) <- c("lat", "lon") coords } file1 ="C:/Users/62552/Desktop/台中交控案/台中五權路etag點位資料.csv" gate_xy_tc<-read.table(file1, header=T,sep = ",",encoding ="big5") gate_xy_tc$site<- iconv(gate_xy_tc$site, "big5", "utf8") library(gdata) #?combn() gate_xy_tc$station<-as.character(gate_xy_tc$station) west_station<-c("etag-01","etag-02","etag-03","etag-04","etag-05") east_station<-c("etag-06","etag-07","etag-08") west_od <- combn(west_station, 2) east_od <- combn(east_station, 2) west_od_t<-t(west_od) east_od_t<-t(east_od) dir_w<-c("出城") dir_e<-c("入城") west_od_t<-cbind(west_od_t,dir_w) east_od_t<-cbind(east_od_t,dir_e) west_od_t<-as.data.frame(west_od_t) east_od_t<-as.data.frame(east_od_t) colnames(west_od_t)<-c('o_station','d_station','dir') colnames(east_od_t)<-c('o_station','d_station','dir') od_patt<-rbind(west_od_t,east_od_t) #for 五權西路 roadpath_info<-c( "segment", "link", "link", "link", "segment", "link", "link", "segment", "link", "segment", "segment", "link", "segment" ) od_patt<-cbind(od_patt,roadpath_info) num=nrow(od_patt) dur_time_finall<-c() dur_time_finall_total_w<-c() for(i in 1:num){ point_od<-od_patt[i,] o_point=as.character(point_od$o_station) d_point=as.character(point_od$d_station) o_lon<-(filter(gate_xy_tc,station==o_point))$lon o_lat<-(filter(gate_xy_tc,station==o_point))$lat d_lon<-(filter(gate_xy_tc,station==d_point))$lon d_lat<-(filter(gate_xy_tc,station==d_point))$lat from<-paste(as.character(o_lon),as.character(o_lat),sep=", ") from<-as.character(from) to<-paste(as.character(d_lon),as.character(d_lat),sep=", ") to<-as.character(to) origin<-from destination<-to travelMode <- "driving" for(j in 1:47){ tttt<-as.POSIXct("2016-01-19 00:00:00") tttt<-as.POSIXct((as.numeric(tttt)+1800*(j-1)),origin="1970-01-01") tttt # departureTime <- Sys.time() #I want to leave now! departureTime <- tttt key="<KEY>" baseUrl <- "https://maps.googleapis.com/maps/api/directions/json?" finalUr1 <- paste(baseUrl , "origin=", origin , "&destination=", destination , "&sensor=false" , "&mode=", travelMode , "&departure_time=", as.integer(departureTime) , "&key=",key , sep = "" ) # finalUr1 <- paste(baseUrl # , "origin=", origin # , "&destination=", destination # , "&sensor=false" # , "&mode=", travelMode # , "&departure_time=", as.integer(departureTime) # , sep = "" # ) # finalUr1 url_string <- URLencode(finalUr1) trip <- fromJSON(paste(readLines(url_string), collapse = "")) tripPathEncoded <- trip$routes[[1]]$overview_polyline$points k=length(trip$routes[[1]]$legs[[1]]$steps[]) dur_time<-trip$routes[[1]]$legs[[1]]$duration_in_traffic$value # dur_dist<-trip$routes[[1]]$legs[[1]]$distance$value # duration_in_traffic dur_time_finall<-c(dur_time_finall,dur_time) # dur_dist Sys.sleep(0.1) } dur_time_finall_total_w<-cbind(dur_time_finall_total_w,dur_time_finall) dur_time_finall<-c() } ggapi_dur_time_mtx_w<-as.data.frame(dur_time_finall_total_w) ggapi_dur_time_mtx<-as.data.frame(dur_time_finall_total) ff=c(1,2,3,4) fff<-ff fff<-cbind(fff,ff) ffff<-cbind(fff,ff) ffff gmap_trip_trt=0 gmap_trip_dis=0 for(i in 1:k){ tripdurationsteptime<- trip$routes[[1]]$legs[[1]]$steps[[i]]$duration$value gmap_trip_trt<-gmap_trip_trt+tripdurationsteptime tripdurationstepdis <- trip$routes[[1]]$legs[[1]]$steps[[i]]$distance$value gmap_trip_dis<-gmap_trip_dis+tripdurationstepdis } tripPathCoords <- decodeLine(tripPathEncoded) centerpoint="24.139858, 120.649200" map <- get_map(centerpoint, zoom = 14 ) ggmap(map) + geom_path(aes(lon, lat), data=tripPathCoords, lwd = 2) } str(m[,1]) plot(1:3) grid(NA, 5, lwd = 2) # grid only in y-direction combn(c(1,1,1,1,2,2,2,3,3,4), 3, tabulate, nbins = 4) as.c
5391eb5991ba6390691bc0570f83554665155df7
[ "R" ]
2
R
musasi65/tccityetg
ea2c5d1aca124d0f767b8ebdc9d24d43bd2ade30
7510280612522a93dc658ebc70480f3750a64184
refs/heads/master
<file_sep> <html> <head> <!-- Chama as dependências da página --> <?php $this->loadFrontDependences($viewName); ?> <title>Página Inicial</title> </head> <body> Voce está na index </body> </html> <file_sep><?php /* * Fupma - Mini Framework * * Determina se o ambiente de execução se é de desenvolvimento ou não. * TRUE = Desenvolvimento * FALSE = Produção * */ define ('ENVIRONMENT', TRUE);
a59c82709d7ad29846ef1f1af08802cb4bf06e0b
[ "PHP" ]
2
PHP
TheEevoS/Makroup
bdc38e22929dfab56302c963974c56a2b5907f1b
dd6a9df9e491a86a81dc59263d446d59df6c47b1
refs/heads/master
<repo_name>rsl140/javalearn<file_sep>/javaProDemo/src/com/homework/Object2/Testzuoye12.java package com.homework.Object2; public class Testzuoye12 { public static void main(String[] args) { Jiaoyuan jy = new Jiaoyuan(); zuoye12 zy = new zuoye12(); } } <file_sep>/javaProDemo/src/com/homework/zonghe/TriangleZuoYe16.java package com.homework.zonghe; public class TriangleZuoYe16 extends ZuoYe16{ public TriangleZuoYe16(int length, int heigth) { super(length, heigth); } @Override public void area() { System.out.println("三角形面积:"+(this.length*this.heigth)/2); } } <file_sep>/javaProDemo/src/com/homework/duanwu/string/zuoye10.java package com.homework.duanwu.string; import java.util.Scanner; /** * @author rsl * @功能 字符串10 * @时间 2017.5.30 * */ public class zuoye10 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("输入一个字符串:"); String str = input.next(); //String str = "rotor"; StringBuffer str1 = new StringBuffer(str); if(str1.reverse().toString().equals(str)){ System.out.println("是回文字符"); } else{ System.out.println("不是回文字符"); } } } <file_sep>/javaProDemo/src/com/homework/Object2/MyDate.java package com.homework.Object2; /** * @author rsl * @功能 基础11 * @时间 2017.5.27 * */ public class MyDate { private String y; private String m; private String d; public MyDate() { super(); } public MyDate(String y, String m, String d) { super(); this.y = y; this.m = m; this.d = d; } public String getY() { return y; } public void setY(String y) { this.y = y; } public String getM() { return m; } public void setM(String m) { this.m = m; } public String getD() { return d; } public void setD(String d) { this.d = d; } } <file_sep>/javaProDemo/src/com/homework/classes/ClassRoom.java package com.homework.classes; /** * @作者:饶思羚 * @功能:面向对象一-课后作业4 * @地址:机房 * @时间:2017.5.17 * */ public class ClassRoom { String className;//班级归属 String type;//教室类型 int classSize;//教室大小(容纳多少人) //显示教室信息 public void show(){ System.out.println("当前班级:" + className + ",教室类型:" + type + ",容纳人数:" + classSize); } } <file_sep>/javaProDemo/src/com/homework/onlyString/SortFriut.java package com.homework.onlyString; import java.util.Arrays; import java.util.Scanner; /** * @功能 课后3 * @作者 饶思羚 * @时间 2017.5.23 * @地址 家 * * */ public class SortFriut { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("输入五种水果以英文逗号隔开:"); String friut = input.next(); String[] arry = friut.split(","); Arrays.sort(arry); for(String str:arry){ System.out.print(str + " "); } } } <file_sep>/javaProDemo/src/com/homework/classString/TestAccount.java package com.homework.classString; public class TestAccount { public static void main(String[] args) { Account money = new Account(); money.Mnue(); } } <file_sep>/javaProDemo/src/com/homework/classString/TestTriangle.java package com.homework.classString; import java.util.Scanner; public class TestTriangle { public static void main(String[] args) { System.out.println("请输入3条边的值:a,b,c"); Scanner input = new Scanner(System.in); String bian = input.next(); String[] s = bian.split(","); Triangle t = new Triangle(); int a = Integer.parseInt(s[0]); int b = Integer.parseInt(s[1]); int c = Integer.parseInt(s[2]); boolean istriangle = t.isTriangle(a, b, c); if(istriangle){ System.out.println(t.shape(a, b, c)); } } } <file_sep>/javaProDemo/src/com/homework/onlyString/ChinaName.java package com.homework.onlyString; import java.util.Scanner; /** * @功能 课后4 * @作者 饶思羚 * @时间 2017.5.23 * @地址 家 * * */ public class ChinaName { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("输入姓名:"); String name = input.next(); String x = name.substring(0,1); String m = name.substring(1); System.out.println("姓:"+ x +",名:"+ m ); } } <file_sep>/javaProDemo/src/com/homework/duotai/Text.java package com.homework.duotai; public class Text { public static void main(String[] args) { //上机1 Master a = new Master(); Pet dog = new Dog(); Pet penguin = new Penguin(); Pet cat = new Cat(); a.feed(dog); a.feed(penguin); a.feed(cat); //上机二 a.play(dog); a.play(penguin); } } <file_sep>/javaProDemo/src/com/homework/Interface/Cat.java package com.homework.Interface; /** * @author rsl * @功能 课后一 * @时间 2017.6.1 * */ public class Cat implements Pet{ public void eat(){ System.out.println("猫猫正在吃东西"); } public void shout(){ System.out.println("猫猫正在叫"); } } <file_sep>/javaProDemo/src/com/demo/chapter12/TestFileReader.java package com.demo.chapter12; import java.io.File; import java.io.FileReader; import java.io.Reader; public class TestFileReader { public static void main(String[] args) throws Exception{ //第一步:关联文件 String path =File.separator+"Users"+File.separator+"rsl"+File.separator+"Desktop"+File.separator+"hello.txt"; File file = new File(path); if(!file.exists()){//如果不存在 穿件文件 file.createNewFile(); } Reader reader = new FileReader(file); char data[] = new char[1024]; int len = reader.read(data); System.out.println("读到的内容"); System.out.println(new String(data,0,len)); reader.close(); } } <file_sep>/javaProDemo/src/pro/Member.java package pro; import java.text.SimpleDateFormat; import java.util.Date; //CRM 客户关系管理系统 /** * 会员模型 * */ public class Member implements Comparable{ private String id; //会员编号,唯一 private String name; //会员名字 private int point; //积分 private String gender; //性别 private Date birthDay; //生日 private String phoneNumber; //电话号码 private String address; //地址 private String job; //职业 public Member(){} public Member(String id,String name){ this.id=id; this.name=name; this.point=0; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPoint() { return point; } public void setPoint(int point) { this.point = point; } public String getGender() { if(null==gender||"".equals(gender)){ return "保密"; } return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthDay() { return birthDay; } public String getDateStr(){ String dateStr=null; if(null!=this.birthDay){ SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd"); dateStr=sdf.format(birthDay); }else{ return "保密"; } return dateStr; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } public String getPhoneNumber() { if(null==phoneNumber||"".equals(phoneNumber)){ return "保密"; } return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getAddress() { if(null==address||"".equals(address)){ return "保密"; } return address; } public void setAddress(String address) { this.address = address; } public String getJob() { if(null==job||"".equals(job)){ return "保密"; } return job; } public void setJob(String job) { this.job = job; } @Override //排序 public int compareTo(Object o) { if(this.id.compareTo(((Member)o).getId())>0){ return 1; }else if(this.id.compareTo(((Member)o).getId())<0){ return -1; }else{ return this.name.compareTo(((Member)o).getName()); } } } <file_sep>/javaProDemo/ReadMe.md # 文件目录 + src + com + homework 作业存放 + classes 面向对象 + classNoString 无参 + classString 有参 + homework 刚接触java + onlyString 字符串 + object1 面向对象1 + demo 课堂演示 + chapter1_9 1-9章 + chapter10 10章 + Demo 课堂演示 + pro 个人项目<file_sep>/javaProDemo/src/com/homework/homework/arrayshomework2.java package com.homework.homework; import java.util.Scanner; public class arrayshomework2 { /* * @功能:统计每个整数和非法数字的个数 * @作者:饶思羚 * @时间:2017.5.8 * @地点:家 */ public static void main(String[] args) { System.out.println("请输入10个数:"); Scanner input = new Scanner(System.in); int[] number = new int[10];//循环输入10个数字 for(int i = 0;i<number.length;i++){ number[i] = input.nextInt(); } //System.out.println(number.length); int one = 0,two = 0,three = 0,def = 0;//计算数字个数 for(int j = 0;j<number.length;j++){ switch(number[j]){//判断数字是否为非法并计数 case 1: one++; break; case 2: two++; break; case 3: three++; break; default: def++; break; } } System.out.println("数字1的个数:"+one); System.out.println("数字2的个数:"+two); System.out.println("数字3的个数:"+three); System.out.println("非法数字的个数:"+def); } } <file_sep>/javaProDemo/src/com/demo/chapter1_9/ScoreCalc.java package com.demo.chapter1_9; public class ScoreCalc { int java;//java成绩 int db;//数据库成绩 int cSharp;//C#成绩 public int sum(){ return java+db+cSharp; } public double avg(){ return sum()/3; } } <file_sep>/javaProDemo/src/com/homework/onlyString/kehou1.java package com.homework.onlyString; /** * @功能 课后1,2 * @作者 饶思羚 * @时间 2017.5.23 * @地址 家 * * */ public class kehou1 { // 1、 下列有关字符串的叙述错误的是(C,D )(选择两项) // A. 字符串是对象 // B. String对象存储字符串的效率比StringBuffer高。 // C. 可以使用StringBuffer strBuffer = “这是字符串”;声明并初始化StringBuffer对象 // D. String类提供了许多用来操作字符串的方法:连接、提取、查询等。 // 2. // ==在基本数据类型时,判断的是他们的值,不是基本数据类型时,判断是否是同一个对象的引用 // equals只是用来比较引用类型的 } <file_sep>/javaProDemo/src/com/demo/chapter11/HashMapTest.java package com.demo.chapter11; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Map.Entry; public class HashMapTest { public static void main(String[] args) { Map<Integer, String> countryMap = new HashMap<Integer, String>(); countryMap.put(1, "China"); countryMap.put(2, "USA"); countryMap.put(3, "England"); countryMap.put(4, "Korea"); countryMap.put(4, "Korea"); //可为空 但是不能重复,如果有重复的 后面的会覆盖前面的 countryMap.put(null, "12å"); System.out.println("map的长度为:"+countryMap.size()); Set<Integer> keys = countryMap.keySet(); System.out.println("遍历key:"); //遍历key并取值 System.out.println("序号\t国家"); for (Integer integer : keys) { System.out.println(integer+"\t"+countryMap.get(integer)); } System.out.println("返回值的集合:========"); Collection<String> values = countryMap.values(); for (String string : values) { System.out.println(string); } System.out.println("是否包含key为5的:"+countryMap.containsKey(5)); System.out.println("是否包含value为cn的:"+countryMap.containsValue("China")); //System.out.println("key2的值是:"+countryMap.get(2)); //移除 //countryMap.remove(2); System.out.println("取entrySet:------------"); Set<Entry<Integer, String>> entryies = countryMap.entrySet(); for (Entry<Integer, String> entry : entryies) { System.out.println(entry); } } } <file_sep>/javaProDemo/src/com/homework/zonghe/xnZuoYe27.java package com.homework.zonghe; public class xnZuoYe27 { public void sum(int num,int count){ int number = 1; for(int i = 0;i<count;i++){ number*=num; } System.out.println(number); } public static void main(String[] args) { xnZuoYe27 test = new xnZuoYe27(); test.sum(10, 3); } } <file_sep>/javaProDemo/src/com/homework/classes/ChangePassword.java package com.homework.classes; import java.util.Scanner; /** * @作者:饶思羚 * @功能:面向对象一-上机练习三 * @地址:机房 * @时间:2017.5.17 * */ public class ChangePassword { /** * 更改管理员密码 * */ public static void main(String[] args) { String nameInput;//保存用户输入的用户名 String pwd;//保存用户输入的密码 String pwdConfirm;//保存用户再次输入的密码 Scanner input = new Scanner(System.in); Administrator admin = new Administrator(); admin.name = "admin1";//给name属性赋值 admin.password = "<PASSWORD>";//给password属性赋值 //输入旧的用户名和密码 System.out.println("请输入用户名:"); nameInput =input.next(); System.out.println("请输入密码:"); pwd =input.next(); //判断用户输入的是否正确 if(admin.name.equals(nameInput) && admin.password.equals(pwd)){ System.out.println("\n请输入新密码:"); pwd =input.next(); System.out.println("请再次输入新密码:"); pwdConfirm =input.next(); while(!pwd.equals(pwdConfirm)){ System.out.println("两次输入不一致,请重新输入"); System.out.println("\n请输入新密码:"); pwd =input.next(); System.out.println("请再次输入新密码:"); pwdConfirm =input.next(); } System.out.println("修改密码成功,您的新密码为:" + pwd); }else{ System.out.println("用户名和密码不匹配!您没有权限更新管理员信息。"); } } } <file_sep>/javaProDemo/src/com/homework/Object2/Mobilephone.java package com.homework.Object2; /** * @author rsl * @功能 基础4 * @时间 2017.5.27 * */ public class Mobilephone extends Phone { private String type;//品牌 public Mobilephone() { super(); // TODO Auto-generated constructor stub } public Mobilephone(int phoneNumber,String type) { super(phoneNumber); this.type = type; } public String getType() { return type; } public void setType(String type) { this.type = type; } } <file_sep>/javaProDemo/src/com/homework/duotai/Cat.java package com.homework.duotai; public class Cat extends Pet{ //上机一 public void eat(){ this.Health+=2; System.out.println("小猫正在进食!"); System.out.println("小猫生命值为:"+this.Health); } } <file_sep>/javaProDemo/src/com/homework/classString/IsSuShu.java package com.homework.classString; /** * @功能 课后练习5(素数) * @作者 饶思羚 * @时间 2017.5.23 * @地址 机房 * */ public class IsSuShu { public boolean isPrime(int value){ // 素数只能被1和本身整除 boolean flag = true; int count = 0;//技术有多少个能被整除 for(int i = 1;i <= value;i++){ if(value % i == 0){ count++; } } if(count>2){ flag = false; } return flag; } } <file_sep>/javaProDemo/src/com/homework/zonghe/RectZuoYe16.java package com.homework.zonghe; public class RectZuoYe16 extends ZuoYe16{ public RectZuoYe16(int length, int heigth) { super(length, heigth); } @Override public void area() { System.out.println("长方形面积:"+this.length*this.heigth); } } <file_sep>/javaProDemo/src/com/homework/zonghe/AnimalZuoYe10.java package com.homework.zonghe; public class AnimalZuoYe10 { String type; public void sound(){ System.out.println("叫"); } } <file_sep>/javaProDemo/src/com/homework/zonghe/ZuoYe15.java package com.homework.zonghe; import java.util.Scanner; public class ZuoYe15 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("输入第1个数:"); int num1 = input.nextInt(); System.out.println("输入第2个数:"); int num2 = input.nextInt(); System.out.println("输入第3个数:"); int num3 = input.nextInt(); int num4 = num1>num2?num1:num2; int maxnum = num4>num3?num4:num3; System.out.println("最大值为:"+maxnum); } } <file_sep>/javaProDemo/src/com/homework/Interface/BizAgent.java package com.homework.Interface; /** * @author rsl * @功能 上机二 * @时间 2017.6.1 * */ public interface BizAgent extends Person { public void giveBizAgent(); } <file_sep>/javaProDemo/src/com/homework/classes/CustomerTest.java package com.homework.classes; /** * @作者:饶思羚 * @功能:对象一-上机练习5 * @地址:机房 * @时间:2017.5.17 * */ public class CustomerTest { public static void main(String[] args) { customer cusromer1 = new customer();//创建实例 //赋值 cusromer1.number = 3050; cusromer1.type = "金卡"; cusromer1.show(); //判断是否回馈积分 if(cusromer1.type.equals("金卡") && cusromer1.number > 1000){ System.out.println("回馈积分500分!"); } else if(cusromer1.type.equals("普卡") && cusromer1.number > 5000){ System.out.println("回馈积分500分!"); } else{ System.out.println("无回馈积!"); } } } <file_sep>/javaProDemo/src/com/homework/classString/TestCustManager.java package com.homework.classString; public class TestCustManager { public static void main(String[] args) { CustManager cus = new CustManager(); cus.Mnue(); } } <file_sep>/javaProDemo/src/com/homework/duanwu/string/zuoye12.java package com.homework.duanwu.string; import java.util.Scanner; /** * @author rsl * @功能 字符串12 * @时间 2017.5.30 * */ public class zuoye12 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("输入一个字符串:"); String str = input.next(); String[] str1 = str.split(""); int count = 0; for(int i = 0;i<str1.length;i++){ if(str1[i].equals("e")){ count++; } } System.out.println("e出现的次数为:" + count); } } <file_sep>/javaProDemo/src/com/homework/zonghe/GongRenZuoYe18.java package com.homework.zonghe; public class GongRenZuoYe18 implements ZuoYe18 { @Override public void eat() { System.out.println("工人喂食"); } @Override public void play() { System.out.println("工人陪玩"); } } <file_sep>/javaProDemo/src/com/homework/classNoString/Menu.java package com.homework.classNoString; import java.util.Scanner; /** * @功能 类的无参 上机练习2 * @作者 饶思羚 * @时间 2017.5.18 * @地址 机房 * */ public class Menu { /*登陆*/ public void showLoginMenu(){ System.out.println("\n\t欢迎使用我型我素购物管理系统\n"); System.out.println("\t\t 1.登 陆 系 统\n"); System.out.println("\t\t 2.退 出\n"); System.out.println("**********************************"); System.out.println("请选择,输入数字:"); Scanner input = new Scanner(System.in); boolean con; StartSMS login = new StartSMS(); do{ con = false; int no = input.nextInt(); switch(no){ case 1: login.Login(); break; case 2: System.exit(0); break; default: System.out.println("输入有误,请重新输入。"); con = true; } }while(con); } /*显示主菜单*/ public void showMainMenu(){ System.out.println("\n\t我型我素购物管理系统主菜单\n"); System.out.println("**********************************"); System.out.println("\t\t 1.客 户 信 息 管 理\n"); System.out.println("\t\t 2.真 情 回 馈\n"); System.out.println("**********************************"); System.out.println("请选择,输入数或按0返回上一级菜单:"); boolean con; do{ con = false; Scanner input = new Scanner(System.in); int no = input.nextInt(); switch(no){ case 1 : showCustMenu(); break; case 2 : showSendGMenu(); break; case 0 : showLoginMenu(); break; default : System.out.println("输入有误,请重新输入数字:"); con = true; } }while(con); } /*显示客户信息管理菜单*/ public void showCustMenu(){ System.out.println("\n\t客户信息管理\n"); System.out.println("**********************************"); System.out.println("\t\t 1.查询客户信息\n"); System.out.println("\t\t 2.修改客户信息\n"); System.out.println("\t\t 3.添加客户信息\n"); System.out.println("\t\t 4.显示所有客户信息\n"); System.out.println("**********************************"); System.out.println("请选择,输入数或按0返回上一级菜单:"); boolean con; do{ con = false; Scanner input = new Scanner(System.in); int no = input.nextInt(); switch(no){ case 1 : System.out.println("查询客户信息"); break; case 2 : System.out.println("查询客户信息"); break; case 3 : System.out.println("查询客户信息"); break; case 4 : System.out.println("查询客户信息"); break; case 0 : showMainMenu(); break; default : System.out.println("输入有误,请重新输入数字:"); con = true; } }while(con); showMainMenu(); } /*显示真情回馈管理菜单*/ public void showSendGMenu(){ System.out.println("\n\t真情回馈\n"); System.out.println("**********************************"); System.out.println("\t\t 1.幸运大放送\n"); System.out.println("\t\t 2.幸运抽奖\n"); System.out.println("\t\t 3.生日问候\n"); System.out.println("**********************************"); System.out.println("请选择,输入数或按0返回上一级菜单:"); boolean con; do{ con = false; Scanner input = new Scanner(System.in); int no = input.nextInt(); switch(no){ case 1 : System.out.println("幸运大放送"); break; case 2 : System.out.println("幸运抽奖"); break; case 3 : System.out.println("生日问候"); break; case 0 : showMainMenu(); break; default : System.out.println("输入有误,请重新输入数字:"); con = true; } }while(con); showMainMenu(); } } <file_sep>/javaProDemo/src/com/homework/Interface/Pig.java package com.homework.Interface; /** * @author rsl * @功能 课后一 * @时间 2017.6.1 * */ public class Pig implements Pet{ public void eat(){ System.out.println("猪猪正在吃东西"); } public void shout(){ System.out.println("猪猪正在嚎叫"); } } <file_sep>/javaProDemo/src/com/homework/Object2/TestBank.java package com.homework.Object2; import java.util.Scanner; public class TestBank { public static void main(String[] args) { Bank bank = new Bank(); Scanner input = new Scanner(System.in); //double money = input.nextDouble(); boolean flag; do{ flag = true; System.out.println("1.存款\t2.取款\t3.查询\t4任意键退出.\n请输入:"); int num = input.nextInt(); double amount = 0; switch(num){ case 1: System.out.println("输入存款金额:"); amount = input.nextDouble(); bank.putIn(amount); break; case 2: System.out.println("输入取款金额:"); amount = input.nextDouble(); if(!bank.getOut(amount)){ } break; case 3: bank.search(); break; default: System.exit(0); } bank.search(); }while(flag); } } <file_sep>/javaProDemo/src/com/homework/homework/arrayshomework1.java package com.homework.homework; import java.util.Arrays; /* * @功能:找出最低积分 * @作者:饶思羚 * @时间:2017.5.8 * @地点:家 */ public class arrayshomework1 { public static void main(String[] args) { int[] nums = new int[] {18,25,7,36,13,2,89,63}; int temp = 0;//定义一个存储最小值的变量 int index = 0;//定义一个存储下标的变量 int[] temparray = nums.clone();//克隆原数组并保存在一个变量中 Arrays.sort(temparray);//对变量进行升序排序 for(int i = 0;i<nums.length;i++){ if(nums[i]==temparray[0]){//循环原数组与排序后的数组中第一个数对比得出原数组最小值 temp = nums[i]; index = i; } } System.out.println("最低积分是:"+temp); System.out.println("下标为:"+index); } } <file_sep>/javaProDemo/src/com/homework/Interface/Eatable.java package com.homework.Interface; /** * @author rsl * @功能 课后二 * @时间 2017.6.1 * */ public interface Eatable{ public void eat(); } <file_sep>/javaProDemo/src/com/homework/duanwu/string/zuoye11.java package com.homework.duanwu.string; import java.util.Scanner; /** * @author rsl * @功能 字符串11 * @时间 2017.5.30 * */ public class zuoye11 { public static void main(String[] args) { String str = "ABCDEFHIJKLM"; StringBuffer str1 = new StringBuffer(str); System.out.println(str1.reverse().toString()); } } <file_sep>/javaProDemo/src/com/demo/chapter10/ListDemo.java package com.demo.chapter10; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class ListDemo { public static void main(String[] args) { // Dog dog0 = new Dog("小黄",4); // Dog dog1 = new Dog("小2",5); // Dog dog2 = new Dog("小3",7); // Dog dog3 = new Dog("小4",10); List<Dog> dogs = new ArrayList<Dog>(); dogs.add(new Dog("小黄",4)); dogs.add(new Dog("小2",5)); dogs.add(new Dog("小3",7)); dogs.add(new Dog("小4",10)); System.out.println("总共有小狗"+dogs.size()+"只"); System.out.println("-------------分割线------------"); show(dogs); System.out.println("-------------移除第三条狗------------"); dogs.remove(2); show(dogs); LinkedList<Penguin> pen = new LinkedList<Penguin>(); pen.add(new Penguin("2",3,"男")); pen.add(new Penguin("3",5,"男")); pen.add(new Penguin("4",9,"女")); pen.addFirst(new Penguin("1",8,"女")); showPen(pen); } public static void show(List<Dog> dogs){ for (int i = 0; i < dogs.size(); i++) { System.out.println("狗名:"+dogs.get(i).name); } } public static void showPen(List<Penguin> pen){ for (int i = 0; i < pen.size(); i++) { System.out.println("企鹅名:"+pen.get(i).getName()); } } } <file_sep>/javaProDemo/src/com/homework/Interface/Store.java package com.homework.Interface; /** * @author rsl * @功能 课后一 * @时间 2017.6.1 * */ public class Store { public Pet getPet(String pet){ Pet a; if("dog".equals(pet)){ a=new Dog(); }else if("pig".equals(pet)){ a= new Pig(); }else{ a= new Cat(); } return a; } } <file_sep>/javaProDemo/src/com/homework/classes/Calculator.java package com.homework.classes; /** * @作者:饶思羚 * @功能:对象1-课后作业1 * @地址:机房 * @时间:2017.5.17 * */ public class Calculator { int number1;//定义数1 int number2;//定义数2 //加法 public void Add(){ int add = number1 + number2; System.out.println(add); } //减法 public void Subtraction(){ int add = number1 - number2; System.out.println(add); } //乘法 public void Multiplication(){ int add = number1 * number2; System.out.println(add); } //除法 public void DivisionMethod(){ int add = number1 / number2; System.out.println(add); } } <file_sep>/javaProDemo/src/com/homework/duotai/Bus.java package com.homework.duotai; public class Bus extends MotoVehicle{ public Bus(String no, String brand) { super(no, brand); } public double calRent(int days){ double num =0; switch(this.brand){ case "金龙": num=1000*days; break; } return num; } } <file_sep>/javaProDemo/src/com/demo/chapter10/A.java package com.demo.chapter10; public class A { public String show(A a) { return "A and A"; } public String show(D d) { return "A and D"; } } <file_sep>/javaProDemo/src/com/homework/classString/TextInsertArrayIn.java package com.homework.classString; import java.util.Scanner; public class TextInsertArrayIn { /** * @功能 类的有参 课后练习6 * @作者 饶思羚 * @时间 2017.5.21 * @地址 机房 * */ public static void main(String[] args) { InsertArrayIn inser = new InsertArrayIn(); int[] array = new int[]{0,1,2,3,4,5,6}; Scanner input = new Scanner(System.in); //插入前显示 inser.getArray(array); //输入不正确时循环输入 boolean flag = false; int index; do{ System.out.println("请输入插入位置:"); index = input.nextInt();//插入位置 if(index <= 0){ System.out.println("请输入有效位置"); flag = true; } }while(flag); System.out.println("请输入插入内容:"); int value = input.nextInt();//插入位置 //获取插入后数组 int[] arrays = inser.insertArray(array, index, value); inser.getArray(arrays); } } <file_sep>/javaProDemo/src/com/homework/zonghe/MZuoYe17.java package com.homework.zonghe; public abstract class MZuoYe17 { int a=9,b=4,c=5; public abstract void max(); public abstract void min(); } <file_sep>/javaProDemo/src/com/demo/chapter10/Printer.java package com.demo.chapter10; public abstract class Printer { abstract void print(String str); } <file_sep>/javaProDemo/src/com/homework/zonghe/CircleZuoYe2.java package com.homework.zonghe; public class CircleZuoYe2 extends PointZuoYe2{ double rad = 5;//半径 //计算圆面积 public double area(){ return (3.14*rad*rad); } public void show(){ System.out.println("圆面积为:" + area()); } } <file_sep>/javaProDemo/src/com/homework/homework/classwork1.java package com.homework.homework; import java.util.Scanner; public class classwork1 { /* * @功能:插入到合适位置 * @作者:饶思羚 * @时间:2017.5.9 * @地点: */ public static void main(String[] args) { String[] books = new String[]{"computer","Hibernate","java","struts"};//旧数组 String inputbooks=""; String[] newbooks = new String[books.length+1]; for(int i=0;i<books.length;i++){ newbooks[i] = books[i]; } System.out.println("请输入新书名:"); Scanner input = new Scanner(System.in); inputbooks = input.next(); int index = -1; for(int i=0;i<newbooks.length;i++){ if(newbooks[i].compareToIgnoreCase(inputbooks)>0){ index=i; break; } } //移位 从后往前赋值 for(int i = newbooks.length-1;i>index;i--){ newbooks[i]=newbooks[i-1]; } newbooks[index]=inputbooks; System.out.println("---------"); for(String str:newbooks){ System.out.println(str+" "); } } } <file_sep>/javaProDemo/src/com/homework/zonghe/FingSumZuoYe6.java package com.homework.zonghe; import java.util.Arrays; public class FingSumZuoYe6 { public void find(int[] num){ Arrays.sort(num); int sum = 0; for(int i=0;i<num.length;i++){ sum+=num[i]; } System.out.println("最大值:"+num[num.length-1]); System.out.println("最小值:"+num[0]); System.out.println("平均值:"+sum/num.length); } public static void main(String[] args) { FingSumZuoYe6 test = new FingSumZuoYe6(); int [] num = {2,3,1,5,2,9}; test.find(num); } } <file_sep>/javaProDemo/src/com/homework/zonghe/GanBuZuoYe18.java package com.homework.zonghe; public class GanBuZuoYe18 implements ZuoYe18 { @Override public void eat() { System.out.println("干部喂食"); } @Override public void play() { System.out.println("干部陪玩"); } } <file_sep>/javaProDemo/src/com/demo/chapter1_9/AutoLion.java package com.demo.chapter1_9; /* * @功能:狮子 * @作者:饶思羚 * @时间:2017.5.8 * @地点:家 */ public class AutoLion { String color = "黄色"; public void run(){ System.out.println("每秒0.1米的速度前进"); } public String bark(){ String sound = "大声的吼叫"; return sound; } //获得颜色 public String getColor(){ return color; } /*显示狮子特性*/ public String showLion(){ return "这是一个" + getColor() + "的玩具狮子。"; } } <file_sep>/javaProDemo/src/com/demo/chapter10/TryCatch1.java package com.demo.chapter10; import java.util.Scanner; public class TryCatch1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入课程代号(1~3)之间的数字"); try { int num = input.nextInt(); switch(num){ case 1: System.out.println("C"); break; case 2: System.out.println("C++"); break; case 3: System.out.println("C#"); break; default: System.out.println("请输入1-3之间的数字"); } } catch (Exception e) { e.printStackTrace(); //System.out.println(e.getMessage()); //System.out.println("你输入的有问题哦!"); }finally { System.out.println("欢迎提出建议:"); } } } <file_sep>/javaProDemo/src/com/demo/chapter1_9/demo2.java package com.demo.chapter1_9; /* * @功能:基本数据类型 * @作者:饶思羚 * @时间:2017.5.8 * @地点:家 */ public class demo2 { public static void main(String[] args) { int heightZhang = 170; int heightLi = heightZhang; System.out.println("张浩的身高:"+heightZhang); System.out.println("李明的身高:"+heightLi); System.out.println(); heightLi = 180; System.out.println("张浩的身高:"+heightZhang); System.out.println("李明的身高:"+heightLi); System.out.println(); /* * 引用数据类型 */ int[] zhang = new int[] {170,70}; int[] li = zhang; System.out.println("张浩的身高:"+zhang[0]); System.out.println("张浩的体重:"+zhang[1]); System.out.println("李明的身高:"+li[0]); System.out.println("李明的体重:"+li[1]); System.out.println(); li[0] = 180; li[1] = 80; System.out.println("张浩的身高:"+zhang[0]); System.out.println("张浩的体重:"+zhang[1]); System.out.println("李明的身高:"+li[0]); System.out.println("李明的体重:"+li[1]); } } <file_sep>/javaProDemo/src/com/homework/Exception/ZY4.java package com.homework.Exception; public class ZY4 { public static void main(String[] args) { try { System.out.println("这是一个异常处理的案列:"); System.out.println(4/0); } catch (ArithmeticException e) { System.out.println(e.getMessage()); } } } <file_sep>/javaProDemo/src/com/homework/Exception/ZY6.java package com.homework.Exception; import java.util.InputMismatchException; import java.util.Scanner; public class ZY6 { public static void main(String[] args) { Scanner input = new Scanner(System.in); try{ System.out.println("输入一个除数"); int a = input.nextInt(); System.out.println("输入一个被除数"); int b = input.nextInt(); System.out.println(a/b); }catch (InputMismatchException|ArithmeticException e) { if(e instanceof InputMismatchException){ System.out.println("非法输入,只能输入数字"); }else if(e instanceof ArithmeticException){ System.out.println("除数不能为0"); } } } } <file_sep>/javaProDemo/src/com/homework/zonghe/GunZuoYe58.java package com.homework.zonghe; public class GunZuoYe58 { String name; private int num;//子弹数量 private int id;//枪手编号 static int count=0; public void fire(){ System.out.println("开枪"); } public GunZuoYe58(String name, int num, int id) { super(); this.name = name; this.num = num; this.id = id; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public int getId() { return id; } public void setId(int id) { this.id = id; } } <file_sep>/javaProDemo/src/com/homework/zonghe/FootballZuoYe13.java package com.homework.zonghe; public class FootballZuoYe13 extends SportsZuoYe13{ } <file_sep>/javaProDemo/src/com/homework/Exception/MyExceptionZY10.java package com.homework.Exception; public class MyExceptionZY10 extends Exception{ public MyExceptionZY10(String message) { super(message); } } <file_sep>/javaProDemo/src/com/demo/chapter10/ColorPrinter.java package com.demo.chapter10; public class ColorPrinter extends Printer { @Override void print(String str) { System.out.println("打印彩色图片"+str); } } <file_sep>/javaProDemo/src/com/homework/onlyString/FindChar.java package com.homework.onlyString; import java.util.Scanner; /** * @功能 上机练习3 * @作者 饶思羚 * @时间 2017.5.23 * @地址 机房 * */ public class FindChar { public static int counter(String inputs, String word){ int counter = 0; //计数器,初值为0 String[] chars = inputs.split(""); for(int i = 0;i < chars.length;i++){ if(chars[i].equals(word)){ counter++; } } return counter; } public static void main(String[] args) { FindChar findch = new FindChar(); Scanner input = new Scanner(System.in); System.out.println("输入一个字符串:"); String inputs = input.next(); System.out.println("输入要查找的字符:"); String word = input.next(); int count = findch.counter(inputs, word); System.out.println("其中包含:" + count +"个" + word); } } <file_sep>/javaProDemo/src/com/demo/chapter11/FindNum.java package com.demo.chapter11; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class FindNum { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入一串字符串:"); String str = input.next(); String[] strs = str.split(""); Set<String> set=new HashSet<String>(); Map<Integer, String> countryMap = new HashMap<Integer, String>(); //赋值 for (int i = 0; i < strs.length; i++) { countryMap.put(i+1, strs[i]); set.add(strs[i]); } //查找 for (int i = 0; i < set.toArray().length; i++) { int count = 0; for(int j = 1;j<=countryMap.size();j++){ if(countryMap.get(j).equals(set.toArray()[i])){ count++; } } System.out.println(set.toArray()[i]+"的次数:"+count); } } } <file_sep>/javaProDemo/src/com/demo/chapter10/BlackPrinter.java package com.demo.chapter10; public class BlackPrinter extends Printer { @Override void print(String str) { System.out.println("打印黑白图片"+str); } } <file_sep>/javaProDemo/src/com/homework/zonghe/TriangleZuoYe1.java package com.homework.zonghe; import java.util.Scanner; public class TriangleZuoYe1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入三角形的三个边以“,”号间隔"); String str = input.next(); String [] str1 = str.split(","); TriangleZuoYe1 triangle = new TriangleZuoYe1(); boolean flag = triangle.isTriangle(Integer.parseInt(str1[0]),Integer.parseInt(str1[1]),Integer.parseInt(str1[2])); if(flag){ triangle.shape(Integer.parseInt(str1[0]),Integer.parseInt(str1[1]),Integer.parseInt(str1[2])); System.out.println("面积为:" + (Integer.parseInt(str1[0])+Integer.parseInt(str1[1])+Integer.parseInt(str1[2]))/2); } } /*判断是否为三角形*/ public boolean isTriangle(int a, int b, int c){ if(a + b > c){ System.out.println("是三角形!"); return true; }else{ System.out.println("不是三角形!"); return false; } } /*判断是什么三角形*/ public void shape(int a, int b, int c){ if(a * a + b * b == c * c){ System.out.println("直角三角形"); }else if(a * a + b * b < c * c){ System.out.println("钝角三角形"); }else{ System.out.println("锐角三角形"); } } } <file_sep>/javaProDemo/src/com/homework/Interface/Paper.java package com.homework.Interface; /** * @author rsl * @功能 上机三 * @时间 2017.6.1 * */ public interface Paper { public String getSize(); } <file_sep>/javaProDemo/src/com/homework/Object2/Student1.java package com.homework.Object2; /** * @author rsl * @功能 基础作业2 * @时间 2017.5.25 * */ public class Student1 { private int classNo; private String name; private int score; public int getClassNo() { return classNo; } public void setClassNo(int classNo) { this.classNo = classNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } } <file_sep>/javaProDemo/src/com/demo/chapter10/TrstDog.java package com.demo.chapter10; public class TrstDog { public static void main(String[] args) { Dog dog = new Dog(); System.out.println("我的名字是:" + dog.name); System.out.println("我的年龄是:" + dog.age); //Dog dog1 = new Dog("八公"); // System.out.println("我的名字是:" + dog1.name +" " + dog1.age); // Dog[] dog2 = new Dog[4]; } } <file_sep>/javaProDemo/src/com/homework/duotai/Dog.java package com.homework.duotai; public class Dog extends Pet{ //上机一 public void eat(){ this.Health+=3; System.out.println("狗狗正在进食!"); System.out.println("狗狗生命值为:"+this.Health); } //上机二 public void catchingFlyDisc(){ this.Health-=10; System.out.println("狗狗和主人玩飞盘游戏"); System.out.println("狗狗生命值为:"+this.Health); } } <file_sep>/javaProDemo/src/com/homework/duotai/Truck.java package com.homework.duotai; public class Truck extends MotoVehicle{ public Truck(String no, String brand) { super(no, brand); // TODO Auto-generated constructor stub } @Override public double calRent(int days) { double num =0; switch(this.brand){ case "解放": num=50*days; break; } return num; } } <file_sep>/javaProDemo/src/com/demo/chapter1_9/demo4.java package com.demo.chapter1_9; /* * @功能:数组的修改 * @作者:饶思羚 * @时间:2017.5.8 * @地点: */ public class demo4 { public static void main(String[] args) { String[] musics = new String[]{"island","Ocean","Pretty","Sun"};//旧数组 for(int i= 0;i<musics.length;i++){ if(musics[i].equals("Ocean")){ musics[i]="read"; break; } } for(String str :musics){ System.out.print(str+" "); } } } <file_sep>/javaProDemo/src/com/homework/duanwu/string/zuoye9.java package com.homework.duanwu.string; import java.util.Scanner; /** * @author rsl * @功能 字符串9 * @时间 2017.5.30 * */ public class zuoye9 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("输入第一个整数:"); int a = input.nextInt(); System.out.println("输入第二个整数:"); int b = input.nextInt(); System.out.println("两个数和为:"+(a+b)); } } <file_sep>/javaProDemo/src/com/homework/duotai/Customer.java package com.homework.duotai; public class Customer { public double calcToteRent(MotoVehicle[] motos, int day){ double num = 0; for (int i = 0; i < motos.length; i++) { num+=motos[i].calRent(day); } return num; } } <file_sep>/javaProDemo/src/com/demo/chapter1_9/demo3.java package com.demo.chapter1_9; import java.util.Scanner; /* * @功能:数组的增加 * @作者:饶思羚 * @时间:2017.5.8 * @地点: */ public class demo3 { public static void main(String[] args) { String[] musics = new String[]{"island","Ocean","Pretty","Sun"};//旧数组 String[] newMusic = new String[musics.length+1]; String inputMusic = ""; for(int i=0;i<musics.length;i++){ newMusic[i]=musics[i];//赋值 } System.out.println("请输入歌名:"); Scanner input =new Scanner(System.in); inputMusic = input.next(); int index=-1;//找不到 //找到存放位置 for(int i = 0;i<newMusic.length-1;i++){ if(newMusic[i].compareToIgnoreCase(inputMusic)>0){ index = i; break; } } System.out.println("插入位置为:"+index); //判断是否为有效位置 if(index!=-1){ //移位 for(int i = newMusic.length-1;i>index;i--){ newMusic[i]=newMusic[i-1]; } //赋值到指定地址 newMusic[index] = inputMusic; }else{ newMusic[newMusic.length-1] = inputMusic; } //输出新数组 for(String str :newMusic){ System.out.print(str+" "); } } } <file_sep>/javaProDemo/src/com/demo/chapter12/TestFileWriter.java package com.demo.chapter12; import java.io.File; import java.io.FileWriter; import java.io.Writer; public class TestFileWriter { public static void main(String[] args) throws Exception{ //第一步:关联文件 String path =File.separator+"Users"+File.separator+"rsl"+File.separator+"Desktop"+File.separator+"hello.txt"; File file = new File(path); if(!file.exists()){//如果不存在 穿件文件 file.createNewFile(); } Writer writer = new FileWriter(file); String str = "中华人民共和国中华人民共和国"; writer.write(str); writer.close(); System.out.println("ok!"); } } <file_sep>/javaProDemo/src/com/homework/zonghe/PZuoYe17.java package com.homework.zonghe; public class PZuoYe17 extends MZuoYe17{ @Override public void max() { int num4 = a>b?a:b; int maxnum = num4>c?num4:c; System.out.println("最大:"+maxnum); } @Override public void min() { int num4 = a>b?b:a; int minnum = num4>c?c:num4; System.out.println("最小:"+minnum); } public static void main(String[] args) { MZuoYe17 test = new PZuoYe17(); test.max(); test.min(); } } <file_sep>/javaProDemo/src/com/homework/duanwu/string/zuoye8.java package com.homework.duanwu.string; import java.util.Scanner; /** * @author rsl * @功能 字符串8 * @时间 2017.5.30 * */ public class zuoye8 { public static void main(String[] args) { String str = "FEDCBA"; String[] str1 = str.split(""); for(int i = 0;i < str1.length;i++){ System.out.println(str1[i]); } } } <file_sep>/javaProDemo/src/com/project/exploit1/GameAngin.java package com.project.exploit1; public class GameAngin { } <file_sep>/README.md # 学习java ## 存储java的练习demo等<file_sep>/javaProDemo/src/com/demo/chapter1_9/Phone.java package com.demo.chapter1_9; public class Phone { String name; //Cell cell; } <file_sep>/javaProDemo/src/com/homework/Object2/Employee.java package com.homework.Object2; /** * @author rsl * @功能 基础11 * @时间 2017.5.27 * */ public class Employee extends MyDate { private String name; private String moneyOfYear;//年薪 public Employee() { super(); } public Employee(String y, String m, String d,String name,String moneyOfYear) { super(y, m, d); this.name = name; this.moneyOfYear = moneyOfYear; } public void show(){ String msg = "姓名:"+name+",年薪:"+moneyOfYear+",日期:"+super.getY()+super.getM()+super.getD(); System.out.println(msg); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMoneyOfYear() { return moneyOfYear; } public void setMoneyOfYear(String moneyOfYear) { this.moneyOfYear = moneyOfYear; } } <file_sep>/javaProDemo/src/com/homework/Exception/ZY2.java package com.homework.Exception; public class ZY2 { public static void main(String[] args) { try { System.out.println("抛出异常前"); int a = 1/0; //出异常,不执行try里面的下一行代码,跳到catch里。 System.out.println("继续执行"); }catch (Exception e) { System.out.println("捕获异常"); }finally {//最终会执行的语句 System.out.println("不管有没有异常,最后都要执行这里"); } } } <file_sep>/javaProDemo/src/TextPorject/Text.java package TextPorject; import com.project.exploit1.Meun; public class Text { public static void main(String[] args) { Meun ck=new Meun(); ck.hasRole(); } } <file_sep>/javaProDemo/src/com/homework/classNoString/Season.java package com.homework.classNoString; import java.util.Scanner; /** * @功能 类的无参 课后作业1 * @作者 饶思羚 * @时间 2017.5.18 * @地址 机房 * */ public class Season { //判断季节 public void isFourSeason(){ Scanner input = new Scanner(System.in); System.out.println("请输入月份:"); int num = input.nextInt(); if(num >= 1 && num <= 3){ System.out.println("该季节是春季"); } else if(num >= 4 && num <= 6){ System.out.println("该季节是夏季"); } else if(num >= 7 && num <= 9){ System.out.println("该季节是秋季"); } else if(num >= 10 && num <= 12){ System.out.println("该季节是冬季"); }else{ System.out.println("输入错误!"); } } //调用季节 public static void main(String[] arry){ Season s = new Season(); s.isFourSeason(); } } <file_sep>/javaProDemo/src/com/homework/Object2/Moveable.java package com.homework.Object2; /** * @author rsl * @功能 基础4 * @时间 2017.5.27 * */ public interface Moveable { public void Moveable(); }<file_sep>/javaProDemo/src/com/homework/Object2/zuoye17.java package com.homework.Object2; /** * @author rsl * @功能 基础17 * @时间 2017.5.26 * */ public class zuoye17 { private int x; private int y; public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public static void main(String[] args) { zuoye17 text = new zuoye17(); //赋值 text.setX(9); text.setY(1); //获取 System.out.println("x:"+text.getX()); System.out.println("y:"+text.getY()); } } <file_sep>/javaProDemo/src/com/homework/duanwu/string/zuoye5.java package com.homework.duanwu.string; import java.util.Scanner; /** * @author rsl * @功能 字符串5 * @时间 2017.5.30 * */ public class zuoye5 { public static void main(String[] args) { String str = "22030219851022024"; if(str.startsWith("220302")){ System.out.println("是以指定220302为前缀"); }else{ System.out.println("不是以指定220302为前缀"); } if(str.endsWith("220302")){ System.out.println("是以指定220302为后缀"); }else{ System.out.println("不是以指定220302为后缀"); } } } <file_sep>/javaProDemo/src/com/demo/chapter10/TestPrint.java package com.demo.chapter10; public class TestPrint { public static void main(String[] args) { Printer a = new ColorPrinter(); a.print("1"); Printer b = new BlackPrinter(); b.print("2"); } } <file_sep>/javaProDemo/src/com/homework/duotai/MotoVehicle.java package com.homework.duotai; public abstract class MotoVehicle { String no;//车牌 String brand;//品牌 int days;//租借天数 public MotoVehicle(String no,String brand) { this.no = no; this.brand = brand; } public abstract double calRent(int days); } <file_sep>/javaProDemo/src/com/homework/zonghe/AppletZuoYe54.java package com.homework.zonghe; public class AppletZuoYe54 implements AZuoYe54{ @Override public int method1(int x) { int num =1; for(int i=0;i<x;i++){ num*=5; } return num; } @Override public int method2(int x, int y) { int num = x > y ? x:y; return num; } public void paint(){ System.out.println(this.method1(2)); System.out.println(this.method2(2,8)); } public static void main(String[] args) { AppletZuoYe54 test = new AppletZuoYe54(); test.paint(); } } <file_sep>/javaProDemo/src/com/homework/duanwu/string/zuoye7.java package com.homework.duanwu.string; import java.util.Scanner; /** * @author rsl * @功能 字符串7 * @时间 2017.5.30 * */ public class zuoye7 { public static void main(String[] args) { String str1 = "100"; String str2 = "123.678"; System.out.println(Integer.parseInt(str1)); System.out.println(Float.parseFloat(str2)); } } <file_sep>/javaProDemo/src/com/homework/Interface/FlyingDiscCatchable.java package com.homework.Interface; /** * @author rsl * @功能 课后二 * @时间 2017.6.1 * */ public interface FlyingDiscCatchable { //玩飞盘 public void catchingFlyDisc(); } <file_sep>/javaProDemo/src/com/homework/Object2/TestPhone.java package com.homework.Object2; public class TestPhone { public static void main(String[] args) { Phone[] test = new Phone[5]; test[0] = new Phone(111111); test[1] = new Phone(222222); test[2] = new Mobilephone(33333,"iphone"); test[3] = new Fixedphone(44444,"座机在客厅"); test[4] = new Cordlessphone(55555,"在卧室","子母机"); System.out.println(test[0].getPhoneNumber()); System.out.println(test[1].getPhoneNumber()); System.out.println(test[2].getPhoneNumber()); System.out.println(test[3].getPhoneNumber()); System.out.println(test[4].getPhoneNumber()); } } <file_sep>/javaProDemo/src/com/homework/duotai/TestPrient.java package com.homework.duotai; /** * 作业2 * * */ public class TestPrient { public static void main(String[] args) { Printer test1 = new DotMatrixPrinter(); Printer test2 = new InkpetPrinter(); Printer test3 = new LaserPrinter(); test1.print(); test2.print(); test3.print(); } } <file_sep>/javaProDemo/src/com/demo/chapter1_9/demo5.java package com.demo.chapter1_9; /* * @功能:数组的删除 * @作者:饶思羚 * @时间:2017.5.8 * @地点: */ public class demo5 { public static void main(String[] args) { String[] musics = new String[]{"island","Ocean","Pretty","Sun"};//旧数组 int index = -1; //查找需要删除的数组下标 for(int i= 0;i<musics.length;i++){ if(musics[i].equals("Ocean")){ index = i; break; } } //移位 for(int i = index;i<musics.length-1;i++){ musics[i]=musics[i+1]; } //删除最后一个数值 musics[musics.length-1]=null; for(String str :musics){ System.out.print(str+" "); } } } <file_sep>/javaProDemo/src/com/homework/zonghe/PersonZuoYe7.java package com.homework.zonghe; public class PersonZuoYe7 { String ear; String eye; String nose; String mouth; String hand; String leg; public void hear(){ System.out.println("可以听见"); } public void smell(){ System.out.println("可以闻见"); } public void bite(){ System.out.println("可以咬"); } public void take(){ System.out.println("可以拿东西"); } public void go(){ System.out.println("可以走路"); } } <file_sep>/javaProDemo/src/com/homework/classes/Degree.java package com.homework.classes; /** * @作者:饶思羚 * @功能:面向对象一-课后作业4 * @地址:机房 * @时间:2017.5.17 * */ public class Degree { String DegreeName;//学位人姓名 String type;//学位 //显示学位信息 public void show(){ System.out.println("姓名:" + DegreeName + ",学位:" + type); } } <file_sep>/javaProDemo/src/com/homework/classNoString/TestScoreCalc.java package com.homework.classNoString; public class TestScoreCalc { public static void main(String[] args) { ScoreCalc score = new ScoreCalc(); score.java = 80; score.cSharp = 70; score.db = 82; score.showAvg(); score.showTotleScore(); } } <file_sep>/javaProDemo/src/com/homework/Object1/Penguin.java package com.homework.Object1; import com.demo.chapter10.StaticTest; /** * @功能:上机练习4 * @作者:饶思羚 * @地点:机房 * @时间:2017.5.24 * */ public class Penguin { static String SEX_MALE = "Q仔"; static String SEX_FEMALE = "Q妹"; String name; String age; public static void main(String[] args) { //静态方法只能调用静态方法或者属性 Penguin a = new Penguin("123","90"); Penguin b = new Penguin("456","9"); Penguin c = new Penguin("789","7"); System.out.println(a.SEX_FEMALE); Penguin.SEX_MALE="雄"; Penguin.SEX_FEMALE="雌"; System.out.println(a.SEX_FEMALE); } public Penguin(String name,String age){ this.name=name; this.age=age; } } <file_sep>/javaProDemo/src/com/homework/Exception/StudentZY10.java package com.homework.Exception; import java.util.Scanner; public class StudentZY10 { public void speak(int m) throws MyExceptionZY10{ if(m<1000){ throw new MyExceptionZY10("要大于1000"); } } public static void main(String[] args) { StudentZY10 test = new StudentZY10(); Scanner input = new Scanner(System.in); System.out.println("输入一个数:"); try{ int a = input.nextInt(); test.speak(a); }catch (MyExceptionZY10 e) { // e.printStackTrace(); System.out.println(e.getMessage()); } } } <file_sep>/javaProDemo/src/com/homework/Interface/Programmer.java package com.homework.Interface; /** * @author rsl * @功能 上机二 * @时间 2017.6.1 * */ public interface Programmer extends Person{ public void giveProgrammer(); } <file_sep>/javaProDemo/src/com/homework/duotai/TestRent.java package com.homework.duotai; //上机3、4 public class TestRent { public static void main(String[] args) { Customer test = new Customer(); MotoVehicle[] motos = new MotoVehicle[5]; motos[0] = new Car("京NY28588","宝马"); motos[1] = new Car("京NNN3284","宝马"); motos[2] = new Car("京NT43765","别克"); motos[3] = new Bus("京5643765","金龙"); motos[4] = new Truck("京GD78124","解放"); System.out.println("租5天得价格为:" + test.calcToteRent(motos, 5));; } } <file_sep>/javaProDemo/src/com/homework/Interface/Pet.java package com.homework.Interface; /** * @author rsl * @功能 课后一 * @时间 2017.6.1 * */ public interface Pet { void eat(); void shout(); } <file_sep>/javaProDemo/src/com/homework/zonghe/StudentZuoYe12.java package com.homework.zonghe; public class StudentZuoYe12 extends PersonZuoYe12{ } <file_sep>/javaProDemo/src/com/homework/classString/Triangle.java package com.homework.classString; /** * @功能 类的有参 课后练习3 * @作者 饶思羚 * @时间 2017.5.23 * @地址 机房 * */ public class Triangle { /*判断是否为三角形*/ public boolean isTriangle(int a, int b, int c){ if(a + b > c){ System.out.println("是三角形!"); return true; }else{ System.out.println("不是三角形!"); return false; } } /*判断是什么三角形*/ public String shape(int a, int b, int c){ String lx; if(a * a + b * b == c * c){ lx = "直角三角形"; }else if(a * a + b * b < c * c){ lx = "钝角三角形"; }else{ lx = "锐角三角形"; } return lx; } } <file_sep>/javaProDemo/src/com/homework/zonghe/PersonZuoYe12.java package com.homework.zonghe; public class PersonZuoYe12 { public String name; public String sex; public int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public String getSex() { return sex; } } <file_sep>/javaProDemo/src/com/homework/classString/TestCustomerBiz.java package com.homework.classString; import java.util.Scanner; /** * @功能 类的有参 上机练习1 * @作者 饶思羚 * @时间 2017.5.19 * @地址 机房 * */ public class TestCustomerBiz { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean flag;//判断是否循环 CustomerBiz cus = new CustomerBiz(); do{ flag = false; System.out.print("请输入客户的姓名:"); String inputName = input.next(); cus.addName(inputName); System.out.println("继续输入吗?(y/n)"); String inputYesOrNo = input.next(); if(inputYesOrNo.equals("y")){ flag = true; } }while(flag); System.out.println("***************************"); System.out.println("\t客户姓名列表\t"); System.out.println("***************************"); cus.showNames();//显示列表 System.out.println(); System.out.println(); System.out.println("请输入要查找的客户姓名:"); //查找是否存在 String search = input.next(); boolean isFind =cus.search(search); System.out.println("*****查找结果****"); if(isFind){ System.out.println("找到了!"); }else{ System.out.println("你确定你输入正确了吗?"); } } } <file_sep>/javaProDemo/src/com/homework/Object1/Student2.java package com.homework.Object1; public class Student2 { String name; int age; String sex; String zy; public Student2(String name,int age){ this.sex = "男"; this.zy = "计算机"; this.name = name; this.age = age; } public Student2(String name,int age,String sex,String zy){ this.sex = sex; this.zy = zy; this.name = name; this.age = age; } public void show(){ System.out.println("姓名:"+ name +",年龄:"+ age +",性别:"+ sex +",专业:"+ zy); } } <file_sep>/javaProDemo/src/com/homework/Interface/TestPrinter.java package com.homework.Interface; /** * @author rsl * @功能 上机三 * @时间 2017.6.1 * */ public class TestPrinter { public static void main(String[] args) { Printer printer=new Printer(); printer.setName("HP"); printer.setInkBox(new BlackInkBox()); printer.setPaper(new B5Paper()); printer.print("Hello World"); } } <file_sep>/javaProDemo/src/pro/manage.java package pro; import java.util.Scanner; import java.util.Arrays; public class manage { /** * 会员管理系统 * 日期:2017.5.10 * 作者:饶思羚 * 会员名,会员年龄,电话 * */ public static Scanner input = new Scanner(System.in); public static void main(String[] args) { Boolean flag = false;//定义是否继续循环 String[] vipName = new String[10]; String[] vipAge = new String[10]; String[] vipPhone = new String[10]; //初始化数据内容 vipName[0] = "张三"; vipAge[0] = "20"; vipPhone[0] = "11111111111"; vipName[1] = "李四"; vipAge[1] = "28"; vipPhone[1] = "22222222222"; vipName[2] = "赵五"; vipAge[2] = "18"; vipPhone[2] = "33333333333"; do{ Mnue(); String choose = input.next(); switch(choose){ case "1": selects(vipName,vipAge,vipPhone); flag = returns(); break; case "2": change(vipName,vipAge,vipPhone); flag = returns(); break; case "3": delect(vipName,vipAge,vipPhone); flag = returns(); break; case "4": add(vipName,vipAge,vipPhone); flag = returns(); break; case "5": list(vipName,vipAge,vipPhone); flag = returns(); break; default: System.exit(0); break; } }while(flag); } //首页 private static void Mnue(){ System.out.println("***********************"); System.out.println("\n\t1.查找"); System.out.println("\t2.修改"); System.out.println("\t3.删除"); System.out.println("\t4.新增"); System.out.println("\t5.列表"); System.out.println("\t6.任意键退出\n"); System.out.println("***********************"); System.out.println("请选择:"); } //是否返回上级菜单 private static Boolean returns(){ System.out.println("返回上级菜单请按:0"); int returnChoose = input.nextInt(); if(returnChoose==0){ return true; }else{ return false; } } //查找 public static void selects(String[] vipName,String[] vipAge,String[] vipPhone){ System.out.println("输入姓名查找:"); String name = input.next(); int index = forEarchArrayReturnIndex(vipName,name);//是否能查找到 if(index != -1){ System.out.println("会员名:"+vipName[index]); System.out.println("年龄:"+vipAge[index]); System.out.println("电话:"+vipPhone[index]); }else{ System.out.println("查无此人!"); } System.out.println(); } //修改 public static void change(String[] vipName,String[] vipAge,String[] vipPhone){ Boolean changeflag = false; do{ System.out.println("***********************"); System.out.println("\n\t1.姓名"); System.out.println("\t2.年龄"); System.out.println("\t3.电话\n"); System.out.println("***********************"); int changepro = input.nextInt(); switch(changepro){ case 1: changeContent(vipName); changeflag=false; break; case 2: changeContent(vipAge); changeflag=false; break; case 3: changeContent(vipPhone); changeflag=false; break; default: System.out.println("输入有效数字"); changeflag=true; break; } }while(changeflag); } //删除 public static void delect(String[] vipName,String[] vipAge,String[] vipPhone){ System.out.println("输入需要删除的人名"); String name = input.next(); int index = forEarchArrayReturnIndex(vipName,name); if(index != -1){ vipName[index] = null; vipAge[index] = null; vipPhone[index] = null; }else{ System.out.println("查无此人!"); } } //增加 public static void add(String[] vipName,String[] vipAge,String[] vipPhone){ System.out.println("输入需要新增的人名"); String name = input.next(); System.out.println("输入需要新增的年龄"); String age = input.next(); System.out.println("输入需要新增的电话"); String phone = input.next(); boolean inputflag = false; for(int i = 0;i<vipName.length;i++){ if(vipName[i]==null){ vipName[i] = name; vipAge[i] = age; vipPhone[i] = phone; inputflag = true; break; } } if(inputflag){ System.out.println("添加成功"); } else{ System.out.println("达到存储上限"); } } //返回列表 public static void list(String[] vipName,String[] vipAge,String[] vipPhone){ System.out.print("姓名\t年龄\t电话\n"); for(int i = 0;i < vipName.length;i++){ if(vipName[i] != null){ System.out.print(vipName[i] + "\t" + vipAge[i] + "\t" + vipPhone[i] + "\n"); } } } //根据修改不同的数组更改数组内容 public static void changeContent(String[] array){ System.out.println("请输入要修改的内容"); String vale = input.next(); int index = forEarchArrayReturnIndex(array,vale); if(index != -1){ System.out.println("请输入需要修改为的内容"); String changevale = input.next(); array[index] = changevale; }else{ System.out.println("找不到需要修改的内容"); } } //根据输入的内容在数组中查找相同的值返回下标 public static int forEarchArrayReturnIndex(String[] array,String vale){ int index = -1; for(int i = 0;i<array.length-1;i++){ if(array[i] != null && array[i].equals(vale)){ index = i; break; } } return index; } } <file_sep>/javaProDemo/src/com/homework/zonghe/TestZuoYe16.java package com.homework.zonghe; public class TestZuoYe16 { public static void main(String[] args) { ZuoYe16 test1 = new RectZuoYe16(13, 2); ZuoYe16 test2 = new TriangleZuoYe16(13, 2); test1.area(); test2.area(); } } <file_sep>/javaProDemo/src/com/homework/duanwu/string/zuoye15.java package com.homework.duanwu.string; public class zuoye15 { /** * @author rsl * @功能 字符串14 * @时间 2017.5.27 * */ public static void main(String[] args) { String a="yekmaakkccekymbvb"; int longth=a.length(); for(int i=0;i<longth;i++){ if(!"".equals(a)){ String d=a.substring(0,1); //重复的变为空 String b=a.replace(d, ""); //原先长度减去去重长度等于去掉得个数==有几个相同的 System.out.println(d+":"+(a.length()-b.length())); a=b; } else{ break; } } } }
e470d6c37a0e33524d9144b15a055084c7eb3b69
[ "Markdown", "Java" ]
109
Java
rsl140/javalearn
e246b4689707d04bdf2868d7ae05e612a2bcc98f
bc81ccad188a6fa7c199abb7d1a4836e45535dd1
refs/heads/master
<repo_name>Bingnan/Lentoid_HEVC_Decoder_Demo<file_sep>/andhevdecoderNew/app/build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 19 buildToolsVersion "24.0.3" defaultConfig { applicationId "pku.shengbin.hevdecoder" minSdkVersion 9 targetSdkVersion 17 } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } sourceSets { main { jni.srcDirs = [] jniLibs.srcDirs = ['src/main/libs'] } } } <file_sep>/andhevdecoderNew/app/src/main/java/pku/shengbin/utils/HttpAccessor.java package pku.shengbin.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpAccessor { /** * 根据URL下载文件,前提是这个文件中的内容是文本,函数的返回值就是文件的内容 1.创建一个URL对象 * 2.通过URL对象,创建一个HttpURLConnection对象 3.得到InputStream 4.从InputStream中读取数据 */ public String getContentFromUrl(String strUrl) { StringBuffer buffer = new StringBuffer(); String line = null; BufferedReader reader = null; try { // 创建一个URL对象 URL url = new URL(strUrl); // 创建一个Http连接 HttpURLConnection urlConn = (HttpURLConnection) url .openConnection(); reader = new BufferedReader(new InputStreamReader( urlConn.getInputStream())); // 使用IO流读取数据 while ((line = reader.readLine()) != null) { buffer.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return buffer.toString(); } } <file_sep>/andhevdecoder/jni/jniplayer/yuv2rgb565.cpp // Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // contributor <NAME> <<EMAIL>> // This file is modified based on: // http://dxr.mozilla.org/mozilla-central/source/gfx/ycbcr/yuv_convert_arm.cpp #include "yuv2rgb565.h" #if ARCH_ARM && HAVE_NEON /*************************************** * convert in neon: */ void __attribute((noinline,optimize("-fomit-frame-pointer"))) yuv42x_to_rgb565_row_neon(uint16_t *dst, const uint8_t *y, const uint8_t *u, const uint8_t *v, int n, int oddflag) { static __attribute__((aligned(16))) uint16_t acc_r[8] = { 22840, 22840, 22840, 22840, 22840, 22840, 22840, 22840, }; static __attribute__((aligned(16))) uint16_t acc_g[8] = { 17312, 17312, 17312, 17312, 17312, 17312, 17312, 17312, }; static __attribute__((aligned(16))) uint16_t acc_b[8] = { 28832, 28832, 28832, 28832, 28832, 28832, 28832, 28832, }; /* * Registers: * q0, q1 : d0, d1, d2, d3 - are used for initial loading of YUV data * q2 : d4, d5 - are used for storing converted RGB data * q3 : d6, d7 - are used for temporary storage * * q4-q7 - reserved * * q8, q9 : d16, d17, d18, d19 - are used for expanded Y data * q10 : d20, d21 * q11 : d22, d23 * q12 : d24, d25 * q13 : d26, d27 * q13, q14, q15 - various constants (#16, #149, #204, #50, #104, #154) */ asm volatile ( ".fpu neon\n" /* Allow to build on targets not supporting neon, and force the object file * target to avoid bumping the final binary target */ ".arch armv7-a\n" ".object_arch armv4t\n" ".macro convert_macroblock size\n" /* load up to 16 source pixels */ ".if \\size == 16\n" "pld [%[y], #64]\n" "pld [%[u], #64]\n" "pld [%[v], #64]\n" "vld1.8 {d1}, [%[y]]!\n" "vld1.8 {d3}, [%[y]]!\n" "vld1.8 {d0}, [%[u]]!\n" "vld1.8 {d2}, [%[v]]!\n" ".elseif \\size == 8\n" "vld1.8 {d1}, [%[y]]!\n" "vld1.8 {d0[0]}, [%[u]]!\n" "vld1.8 {d0[1]}, [%[u]]!\n" "vld1.8 {d0[2]}, [%[u]]!\n" "vld1.8 {d0[3]}, [%[u]]!\n" "vld1.8 {d2[0]}, [%[v]]!\n" "vld1.8 {d2[1]}, [%[v]]!\n" "vld1.8 {d2[2]}, [%[v]]!\n" "vld1.8 {d2[3]}, [%[v]]!\n" ".elseif \\size == 4\n" "vld1.8 {d1[0]}, [%[y]]!\n" "vld1.8 {d1[1]}, [%[y]]!\n" "vld1.8 {d1[2]}, [%[y]]!\n" "vld1.8 {d1[3]}, [%[y]]!\n" "vld1.8 {d0[0]}, [%[u]]!\n" "vld1.8 {d0[1]}, [%[u]]!\n" "vld1.8 {d2[0]}, [%[v]]!\n" "vld1.8 {d2[1]}, [%[v]]!\n" ".elseif \\size == 2\n" "vld1.8 {d1[0]}, [%[y]]!\n" "vld1.8 {d1[1]}, [%[y]]!\n" "vld1.8 {d0[0]}, [%[u]]!\n" "vld1.8 {d2[0]}, [%[v]]!\n" ".elseif \\size == 1\n" "vld1.8 {d1[0]}, [%[y]]!\n" "vld1.8 {d0[0]}, [%[u]]!\n" "vld1.8 {d2[0]}, [%[v]]!\n" ".else\n" ".error \"unsupported macroblock size\"\n" ".endif\n" /* d1 - Y data (first 8 bytes) */ /* d3 - Y data (next 8 bytes) */ /* d0 - U data, d2 - V data */ /* split even and odd Y color components */ "vuzp.8 d1, d3\n" /* d1 - evenY, d3 - oddY */ /* clip upper and lower boundaries */ "vqadd.u8 q0, q0, q4\n" "vqadd.u8 q1, q1, q4\n" "vqsub.u8 q0, q0, q5\n" "vqsub.u8 q1, q1, q5\n" "vshr.u8 d4, d2, #1\n" /* d4 = V >> 1 */ "vmull.u8 q8, d1, d27\n" /* q8 = evenY * 149 */ "vmull.u8 q9, d3, d27\n" /* q9 = oddY * 149 */ "vld1.16 {d20, d21}, [%[acc_r], :128]\n" /* q10 - initialize accumulator for red */ "vsubw.u8 q10, q10, d4\n" /* red acc -= (V >> 1) */ "vmlsl.u8 q10, d2, d28\n" /* red acc -= V * 204 */ "vld1.16 {d22, d23}, [%[acc_g], :128]\n" /* q11 - initialize accumulator for green */ "vmlsl.u8 q11, d2, d30\n" /* green acc -= V * 104 */ "vmlsl.u8 q11, d0, d29\n" /* green acc -= U * 50 */ "vld1.16 {d24, d25}, [%[acc_b], :128]\n" /* q12 - initialize accumulator for blue */ "vmlsl.u8 q12, d0, d30\n" /* blue acc -= U * 104 */ "vmlsl.u8 q12, d0, d31\n" /* blue acc -= U * 154 */ "vhsub.s16 q3, q8, q10\n" /* calculate even red components */ "vhsub.s16 q10, q9, q10\n" /* calculate odd red components */ "vqshrun.s16 d0, q3, #6\n" /* right shift, narrow and saturate even red components */ "vqshrun.s16 d3, q10, #6\n" /* right shift, narrow and saturate odd red components */ "vhadd.s16 q3, q8, q11\n" /* calculate even green components */ "vhadd.s16 q11, q9, q11\n" /* calculate odd green components */ "vqshrun.s16 d1, q3, #6\n" /* right shift, narrow and saturate even green components */ "vqshrun.s16 d4, q11, #6\n" /* right shift, narrow and saturate odd green components */ "vhsub.s16 q3, q8, q12\n" /* calculate even blue components */ "vhsub.s16 q12, q9, q12\n" /* calculate odd blue components */ "vqshrun.s16 d2, q3, #6\n" /* right shift, narrow and saturate even blue components */ "vqshrun.s16 d5, q12, #6\n" /* right shift, narrow and saturate odd blue components */ "vzip.8 d0, d3\n" /* join even and odd red components */ "vzip.8 d1, d4\n" /* join even and odd green components */ "vzip.8 d2, d5\n" /* join even and odd blue components */ "vshll.u8 q3, d0, #8\n\t" "vshll.u8 q8, d1, #8\n\t" "vshll.u8 q9, d2, #8\n\t" "vsri.u16 q3, q8, #5\t\n" "vsri.u16 q3, q9, #11\t\n" /* store pixel data to memory */ ".if \\size == 16\n" " vst1.16 {d6, d7}, [%[dst]]!\n" " vshll.u8 q3, d3, #8\n\t" " vshll.u8 q8, d4, #8\n\t" " vshll.u8 q9, d5, #8\n\t" " vsri.u16 q3, q8, #5\t\n" " vsri.u16 q3, q9, #11\t\n" " vst1.16 {d6, d7}, [%[dst]]!\n" ".elseif \\size == 8\n" " vst1.16 {d6, d7}, [%[dst]]!\n" ".elseif \\size == 4\n" " vst1.16 {d6}, [%[dst]]!\n" ".elseif \\size == 2\n" " vst1.16 {d6[0]}, [%[dst]]!\n" " vst1.16 {d6[1]}, [%[dst]]!\n" ".elseif \\size == 1\n" " vst1.16 {d6[0]}, [%[dst]]!\n" ".endif\n" ".endm\n" "vmov.u8 d8, #15\n" /* add this to U/V to saturate upper boundary */ "vmov.u8 d9, #20\n" /* add this to Y to saturate upper boundary */ "vmov.u8 d10, #31\n" /* sub this from U/V to saturate lower boundary */ "vmov.u8 d11, #36\n" /* sub this from Y to saturate lower boundary */ "vmov.u8 d26, #16\n" "vmov.u8 d27, #149\n" "vmov.u8 d28, #204\n" "vmov.u8 d29, #50\n" "vmov.u8 d30, #104\n" "vmov.u8 d31, #154\n" "cmp %[oddflag], #0\n" "beq 1f\n" "convert_macroblock 1\n" "sub %[n], %[n], #1\n" "1:\n" "subs %[n], %[n], #16\n" "blt 2f\n" "1:\n" "convert_macroblock 16\n" "subs %[n], %[n], #16\n" "bge 1b\n" "2:\n" "tst %[n], #8\n" "beq 3f\n" "convert_macroblock 8\n" "3:\n" "tst %[n], #4\n" "beq 4f\n" "convert_macroblock 4\n" "4:\n" "tst %[n], #2\n" "beq 5f\n" "convert_macroblock 2\n" "5:\n" "tst %[n], #1\n" "beq 6f\n" "convert_macroblock 1\n" "6:\n" ".purgem convert_macroblock\n" : [y] "+&r" (y), [u] "+&r" (u), [v] "+&r" (v), [dst] "+&r" (dst), [n] "+&r" (n) : [acc_r] "r" (&acc_r[0]), [acc_g] "r" (&acc_g[0]), [acc_b] "r" (&acc_b[0]), [oddflag] "r" (oddflag) : "cc", "memory", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "d11", /* "d12", "d13", "d14", "d15", */ "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23", "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31" ); } void ConvertYCbCrToRGB565_neon( const uint8_t* y_buf, const uint8_t* u_buf, const uint8_t* v_buf, uint8_t* rgb_buf, int pic_width, int pic_height, int y_stride, int uv_stride, int rgb_stride, int yuv_type) { int x_shift; int y_shift; x_shift = (yuv_type != 444); //YUV 4:4:4 y_shift = (yuv_type == 420); //YUV 4:2:0 /* From Wiki: The Y'V12 format is essentially the same as Y'UV420p, but it has the U and V data reversed: the Y' values are followed by the V values, with the U values last. */ for (int i = 0; i < pic_height; i++) { int yoffs; int uvoffs; yoffs = y_stride * i; uvoffs = uv_stride * (i>>y_shift); yuv42x_to_rgb565_row_neon((uint16_t*)(rgb_buf + rgb_stride * i), y_buf + yoffs, u_buf + uvoffs, v_buf + uvoffs, pic_width, 0); } } #endif //ARCH_ARM && HAVE_NEON /************************************* * convert in c: */ /* * Use NS_CLAMP to force a value (such as a preference) into a range. */ #define NS_CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x))) /*Convert a single pixel from Y'CbCr to RGB565. This uses the exact same formulas as the asm, even though we could make the constants a lot more accurate with 32-bit wide registers.*/ static uint16_t yu2rgb565(int y, int u, int v, int dither) { /*This combines the constant offset that needs to be added during the Y'CbCr conversion with a rounding offset that depends on the dither parameter.*/ static const int DITHER_BIAS[4][3] = { {-14240, 8704, -17696}, {-14240+128,8704+64, -17696+128}, {-14240+256,8704+128,-17696+256}, {-14240+384,8704+192,-17696+384} }; int r; int g; int b; r = NS_CLAMP((74*y+102*v+DITHER_BIAS[dither][0])>>9, 0, 31); g = NS_CLAMP((74*y-25*u-52*v+DITHER_BIAS[dither][1])>>8, 0, 63); b = NS_CLAMP((74*y+129*u+DITHER_BIAS[dither][2])>>9, 0, 31); return (uint16_t)(r<<11 | g<<5 | b); } void yuv_to_rgb565_row_c(uint16_t *dst, const uint8_t *y, const uint8_t *u, const uint8_t *v, int x_shift, int pic_width) { int x; for (x = 0; x < pic_width; x++) { dst[x] = yu2rgb565(y[x], u[x>>x_shift], v[x>>x_shift], 2); // Disable dithering for now. } } void ConvertYCbCrToRGB565_c( const uint8_t* y_buf, const uint8_t* u_buf, const uint8_t* v_buf, uint8_t* rgb_buf, int pic_width, int pic_height, int y_stride, int uv_stride, int rgb_stride, int yuv_type) { int x_shift; int y_shift; x_shift = (yuv_type != 444); //YUV 4:4:4 y_shift = (yuv_type == 420); //YUV 4:2:0 /* From Wiki: The Y'V12 format is essentially the same as Y'UV420p, but it has the U and V data reversed: the Y' values are followed by the V values, with the U values last. */ for (int i = 0; i < pic_height; i++) { int yoffs; int uvoffs; yoffs = y_stride * i; uvoffs = uv_stride * (i>>y_shift); yuv_to_rgb565_row_c((uint16_t*)(rgb_buf + rgb_stride * i), y_buf + yoffs, u_buf + uvoffs, v_buf + uvoffs, x_shift, pic_width); } } void ConvertYCbCrToRGB565( const uint8_t* y_buf, const uint8_t* u_buf, const uint8_t* v_buf, uint8_t* rgb_buf, int pic_width, int pic_height, int y_stride, int uv_stride, int rgb_stride, int yuv_type) { #if HAVE_NEON ConvertYCbCrToRGB565_neon(y_buf, u_buf, v_buf, rgb_buf, pic_width, pic_height, y_stride, uv_stride, rgb_stride, yuv_type); #else ConvertYCbCrToRGB565_c(y_buf, u_buf, v_buf, rgb_buf, pic_width, pic_height, y_stride, uv_stride, rgb_stride, yuv_type); #endif } <file_sep>/andhevdecoder/jni/jniplayer/jniplayer.cpp // jniplayer.cpp : decode H.265/HEVC video data in separate native thread // // Copyright (c) 2013 Strongene Ltd. All Right Reserved. // http://www.strongene.com // // Contributors: // <NAME> <<EMAIL>> // <NAME> <<EMAIL>> // // You are free to re-use this as the basis for your own application // in source and binary forms, with or without modification, provided // that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice and this list of conditions. // * Redistributions in binary form must reproduce the above // copyright notice and this list of conditions in the documentation // and/or other materials provided with the distribution. #include <android/log.h> #include <android/bitmap.h> #include <stdio.h> #include <time.h> #include <pthread.h> #include <unistd.h> #include "jniplayer.h" #include "jni_utils.h" #include "yuv2rgb565.h" #include "gl_renderer.h" #ifdef __cplusplus #define __STDC_CONSTANT_MACROS #define __STDC_LIMIT_MACROS #ifdef _STDINT_H #undef _STDINT_H #endif #include <stdint.h> #define __STDC_FORMAT_MACROS #endif extern "C" { #include "lenthevcdec.h" } #define LOG_TAG "jniplayer" #define ENABLE_LOGD 0 #if ENABLE_LOGD #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #else #define LOGD(...) #endif #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) #ifndef _countof #define _countof(a) (sizeof(a) / sizeof((a)[0])) #endif #define LOOP_PLAY 1 #if ARCH_ARM #define USE_SWSCALE 0 #else #define USE_SWSCALE 0 #endif struct fields_t { jmethodID drawFrame; jmethodID postEvent; }; struct MediaInfo { int width; int height; char data_src[1024]; int raw_bs; }; VideoFrame gVF = {0, 0, 0, 0, 0, {NULL, NULL, NULL}}; pthread_mutex_t gVFMutex = PTHREAD_MUTEX_INITIALIZER; static fields_t fields; static JNIEnv *gEnv = NULL; static JNIEnv *gEnvLocal = NULL; static jclass gClass = NULL; static MediaInfo media; static pthread_t decode_thread; static struct SwsContext *p_sws_ctx; static const char* const kClassPathName = "pku/shengbin/hevdecoder/NativeMediaPlayer"; // for lenthevcdec static const uint32_t AU_COUNT_MAX = 1024 * 1024; static const uint32_t AU_BUF_SIZE_MAX = 1024 * 1024 * 50; static uint32_t au_pos[AU_COUNT_MAX]; // too big array, use static to save stack space static uint32_t au_count, au_buf_size; static uint8_t *au_buf = NULL; static lenthevcdec_ctx lent_ctx = NULL; static volatile int exit_decode_thread = 0; static volatile int is_playing = 0; static int frames_sum = 0; static double tstart = 0; static int frames = 0; static double tlast = 0; static float renderFPS = 0; static uint64_t renderInterval = 0; static struct timeval timeStart; uint32_t getms() { struct timeval t; gettimeofday(&t, NULL); return (t.tv_sec * 1000) + (t.tv_usec / 1000); } void postEvent(int msg, int ext1, int ext2) { JNIEnv *env = getJNIEnv(); env->CallStaticVoidMethod(gClass, fields.postEvent, msg, ext1, ext2, 0); } int drawFrame(VideoFrame * vf) { LOGD("enter drawFrame:%u (%f)", getms(), vf->pts); // copy decode frame to global buffer pthread_mutex_lock(&gVFMutex); if ( gVF.linesize_y != vf->linesize_y || gVF.linesize_uv != vf->linesize_uv || gVF.height != vf->height ) { if ( NULL != gVF.yuv_data[0] ) free(gVF.yuv_data[0]); gVF.yuv_data[0] = gVF.yuv_data[1] = gVF.yuv_data[2] = NULL; gVF.yuv_data[0] = (uint8_t*)malloc(vf->linesize_y * vf->height + vf->linesize_uv * vf->height ); if ( NULL == gVF.yuv_data[0] ) { LOGE("malloc failed!\n"); return -1; } gVF.yuv_data[1] = gVF.yuv_data[0] + vf->linesize_y*vf->height; gVF.yuv_data[2] = gVF.yuv_data[1] + vf->linesize_uv*vf->height/2; } gVF.width = vf->width; gVF.height = vf->height; gVF.linesize_y = vf->linesize_y; gVF.linesize_uv = vf->linesize_uv; gVF.pts = vf->pts; memcpy(gVF.yuv_data[0], vf->yuv_data[0], vf->linesize_y*vf->height); memcpy(gVF.yuv_data[1], vf->yuv_data[1], vf->linesize_uv*vf->height/2); memcpy(gVF.yuv_data[2], vf->yuv_data[2], vf->linesize_uv*vf->height/2); pthread_mutex_unlock(&gVFMutex); // wait for display struct timeval timeNow; gettimeofday(&timeNow, NULL); int64_t timePassed = ((int64_t)(timeNow.tv_sec - timeStart.tv_sec))*1000000 + (timeNow.tv_usec - timeStart.tv_usec); int64_t delay = vf->pts - timePassed; if (delay > 0) { usleep(delay); } // update information gettimeofday(&timeNow, NULL); double tnow = timeNow.tv_sec + (timeNow.tv_usec / 1000000.0); if (tlast == 0) tlast = tnow; if (tstart == 0) tstart = tnow; if (tnow > tlast + 1) { double avg_fps; LOGI("Video Display FPS:%i", (int)frames); frames_sum += frames; avg_fps = frames_sum / (tnow - tstart); LOGI("Video AVG FPS:%.2lf", avg_fps); postEvent(900, int(frames), int(avg_fps * 4096)); tlast = tlast + 1; frames = 0; } frames++; // request display if (gEnvLocal == NULL) gEnvLocal = getJNIEnv(); LOGD("before request draw:%u (%f)", getms(), vf->pts); return gEnvLocal->CallStaticIntMethod(gClass, fields.drawFrame, vf->width, vf->height); } int lent_hevc_get_sps(uint8_t* buf, int size, uint8_t** sps_ptr) { int i, nal_type, sps_pos; sps_pos = -1; for ( i = 0; i < (size - 4); i++ ) { if ( 0 == buf[i] && 0 == buf[i+1] && 1 == buf[i+2] ) { nal_type = (buf[i+3] & 0x7E) >> 1; if ( 33 != nal_type && sps_pos >= 0 ) { break; } if ( 33 == nal_type ) { // sps sps_pos = i; } i += 2; } } if ( sps_pos < 0 ) return 0; if ( i == (size - 4) ) i = size; *sps_ptr = buf + sps_pos; return i - sps_pos; } int lent_hevc_get_frame(uint8_t* buf, int size, int *is_idr) { static int seq_hdr = 0; int i, nal_type, idr = 0; for ( i = 0; i < (size - 6); i++ ) { if ( 0 == buf[i] && 0 == buf[i+1] && 1 == buf[i+2] ) { nal_type = (buf[i+3] & 0x7E) >> 1; if ( nal_type <= 21 ) { if ( buf[i+5] & 0x80 ) { /* first slice in pic */ if ( !seq_hdr ) break; else seq_hdr = 0; } } if ( nal_type >= 32 && nal_type <= 34 ) { if ( !seq_hdr ) { seq_hdr = 1; idr = 1; break; } seq_hdr = 1; } i += 2; } } if ( i == (size - 6) ) i = size; if ( NULL != is_idr ) *is_idr = idr; return i; } void* rawbs_runDecoder(void *p) { int32_t got_frame, width, height, stride[3]; uint8_t* pixels[3]; int64_t pts, got_pts; int frame_count, ret, i; if ( NULL == lent_ctx || NULL == au_buf ) return NULL; decode: // decode all AUs frame_count = 0; for ( i = 0; i < au_count && !exit_decode_thread; i++ ) { pts = i * 40; got_frame = 0; uint32_t start_time = getms(); LOGD("before decode: %u", start_time); ret = lenthevcdec_decode_frame(lent_ctx, au_buf + au_pos[i], au_pos[i + 1] - au_pos[i], pts, &got_frame, &width, &height, stride, (void**)pixels, &got_pts); if ( ret < 0 ) { LOGE("call lenthevcdec_decode_frame failed! ret = %d\n", ret); goto exit; } uint32_t end_time = getms(); LOGD("after decode: %u", end_time); uint32_t dec_time = end_time - start_time; if ( got_frame > 0 ) { LOGD("decoding time: %u - %u = %u\n", end_time, start_time, dec_time); LOGD("decode frame: pts = %" PRId64 ", linesize = {%d,%d,%d}\n", got_pts, stride[0], stride[1], stride[2]); if ( media.width != width || media.height != height ) { LOGD("Video dimensions change! %dx%d -> %dx%d\n", media.width, media.height, width, height); media.width = width; media.height = height; } // draw frame to screen VideoFrame vf; vf.width = width; vf.height = height; vf.linesize_y = stride[0]; vf.linesize_uv = stride[1]; vf.pts = renderInterval * frame_count; vf.yuv_data[0] = pixels[0]; vf.yuv_data[1] = pixels[1]; vf.yuv_data[2] = pixels[2]; if (frame_count == 0) { gettimeofday(&timeStart, NULL); } drawFrame(&vf); frame_count++; } } #if LOOP_PLAY if (!exit_decode_thread) { LOGI("automatically play again\n"); goto decode; } #endif // flush decoder while ( !exit_decode_thread ) { got_frame = 0; ret = lenthevcdec_decode_frame(lent_ctx, NULL, 0, pts, &got_frame, &width, &height, stride, (void**)pixels, &got_pts); if ( ret < 0 || got_frame <= 0) break; if ( got_frame > 0 ) { if ( media.width != width || media.height != height ) { LOGD("Video dimensions change! %dx%d -> %dx%d\n", media.width, media.height, width, height); media.width = width; media.height = height; } // draw frame to screen VideoFrame vf; vf.width = width; vf.height = height; vf.linesize_y = stride[0]; vf.linesize_uv = stride[1]; vf.pts = renderInterval * frame_count; vf.yuv_data[0] = pixels[0]; vf.yuv_data[1] = pixels[1]; vf.yuv_data[2] = pixels[2]; drawFrame(&vf); frame_count++; } } exit: if ( NULL != au_buf ) free(au_buf); au_buf = 0; if ( NULL != lent_ctx ) lenthevcdec_destroy(lent_ctx); lent_ctx = NULL; postEvent(909, int(frame_count), 0); // end of file detachJVM(); is_playing = 0; LOGI("decode thread exit\n"); exit_decode_thread = 0; return NULL; } static int MediaPlayer_setDataSource(JNIEnv *env, jobject thiz, jstring path) { const char *pathStr = env->GetStringUTFChars(path, NULL); memset(&media, 0, sizeof(media)); strcpy(media.data_src, pathStr); // Make sure that local ref is released before a potential exception env->ReleaseStringUTFChars(path, pathStr); // is raw HEVC bitstream file ? static const char * hevc_raw_bs_ext[] = {".hevc", ".hm91", ".hm10", ".bit", ".hvc", ".h265", ".265"}; char * ext = strrchr(media.data_src, '.'); if ( NULL != ext ) { int i; for ( i = 0; i < _countof(hevc_raw_bs_ext); i++ ) { if ( strcasecmp(hevc_raw_bs_ext[i], ext) == 0 ) break; } if ( i < _countof(hevc_raw_bs_ext) ) media.raw_bs = 1; } return 0; } static int rawbs_prepare(int threads) { FILE *in_file; int32_t got_frame, width, height, stride[3]; uint8_t* pixels[3]; int64_t pts, got_pts; uint8_t *sps; lenthevcdec_ctx one_thread_ctx; int compatibility, frame_count, sps_len, ret, i; in_file = NULL; au_buf = NULL; lent_ctx = NULL; one_thread_ctx = NULL; // get compatibility version compatibility = 0x7fffffff; if ( strncasecmp(".hm91", media.data_src + (strlen(media.data_src) - 5), 5) == 0 ) compatibility = 91; else if ( strncasecmp(".hm10", media.data_src + (strlen(media.data_src) - 5), 5) == 0 ) compatibility = 100; // read file in_file = fopen(media.data_src, "rb"); if ( NULL == in_file ) { LOGE("Can not open input file '%s'\n", media.data_src); goto error_exit; } fseek(in_file, 0, SEEK_END); au_buf_size = ftell(in_file); fseek(in_file, 0, SEEK_SET); LOGD("file size is %d bytes\n", au_buf_size); if ( au_buf_size > AU_BUF_SIZE_MAX ) au_buf_size = AU_BUF_SIZE_MAX; au_buf = (uint8_t*)malloc(au_buf_size); if ( NULL == au_buf ) { LOGE("call malloc failed! size is %d\n", au_buf_size); goto error_exit; } if ( fread(au_buf, 1, au_buf_size, in_file) != au_buf_size ) { LOGE("call fread failed!\n"); goto error_exit; } fclose(in_file); in_file = NULL; LOGD("%d bytes read to address %p\n", au_buf_size, au_buf); // find all AU au_count = 0; for ( i = 0; i < au_buf_size && au_count < (AU_COUNT_MAX - 1); i+=3 ) { i += lent_hevc_get_frame(au_buf + i, au_buf_size - i, NULL); if (i < au_buf_size) { au_pos[au_count++] = i; } LOGD("AU[%d] = %d\n", au_count - 1, au_pos[au_count - 1]); } au_pos[au_count] = au_buf_size; // include last AU LOGD("found %d AUs\n", au_count); // open lentoid HEVC decoder LOGI("create lentoid decoder: compatibility = %d, threads = %d\n", compatibility, threads); lent_ctx = lenthevcdec_create(threads, compatibility, NULL); if ( NULL == lent_ctx ) { LOGE("call lenthevcdec_create failed!\n"); goto error_exit; } LOGD("get decoder %p\n", lent_ctx); // find sps, decode it and get video resolution sps_len = lent_hevc_get_sps(au_buf, au_buf_size, &sps); if ( sps_len > 0 ) { // get a one-thread decoder to decode SPS one_thread_ctx = lenthevcdec_create(1, compatibility, NULL); if ( NULL == lent_ctx ) goto error_exit; width = 0; height = 0; ret = lenthevcdec_decode_frame(one_thread_ctx, sps, sps_len, 0, &got_frame, &width, &height, stride, (void**)pixels, &pts); if ( 0 != width && 0 != height ) { media.width = width; media.height = height; LOGD("Video dimensions is %dx%d\n", width, height); } lenthevcdec_destroy(one_thread_ctx); one_thread_ctx = NULL; } return 0; error_exit: if ( NULL != in_file ) fclose(in_file); in_file = NULL; if ( NULL != au_buf ) free(au_buf); au_buf = NULL; if ( NULL != lent_ctx ) lenthevcdec_destroy(lent_ctx); lent_ctx = NULL; if ( NULL != one_thread_ctx ) lenthevcdec_destroy(one_thread_ctx); one_thread_ctx = NULL; return -1; } static int MediaPlayer_prepare(JNIEnv *env, jobject thiz, jint threadNumber, jfloat fps) { LOGD("MediaPlayer_prepare: %d threads, fps %f\n", threadNumber, fps); renderFPS = fps; if (fps == 0) renderInterval = 1; else { renderInterval = 1.0 / fps * 1000000; // us } return rawbs_prepare(threadNumber); } static int MediaPlayer_start(JNIEnv *env, jobject thiz) { LOGI("start decoding thread"); pthread_create(&decode_thread, NULL, rawbs_runDecoder, NULL); return 0; } static int MediaPlayer_pause(JNIEnv *env, jobject thiz) { return 0; } static int MediaPlayer_go(JNIEnv *env, jobject thiz) { return 0; } static int MediaPlayer_stop(JNIEnv *env, jobject thiz) { void* result; exit_decode_thread = 1; pthread_join(decode_thread, &result); exit_decode_thread = 0; if (p_sws_ctx != NULL) { // sws_freeContext(p_sws_ctx); p_sws_ctx = NULL; } if ( NULL != gVF.yuv_data[0] ) free(gVF.yuv_data[0]); memset(&gVF, 0, sizeof(gVF)); LOGI("media player stopped\n"); return 0; } static bool MediaPlayer_isPlaying(JNIEnv *env, jobject thiz) { return is_playing; } static int MediaPlayer_seekTo(JNIEnv *env, jobject thiz, jint msec) { return 0; } static int MediaPlayer_getVideoWidth(JNIEnv *env, jobject thiz) { int w = media.width; return w; } static int MediaPlayer_getVideoHeight(JNIEnv *env, jobject thiz) { int h = media.height; return h; } static int MediaPlayer_getCurrentPosition(JNIEnv *env, jobject thiz) { int msec = 0; return msec; } static int MediaPlayer_getDuration(JNIEnv *env, jobject thiz) { int msec = 0; return msec; } // ---------------------------------------------------------------------------- static void MediaPlayer_native_init(JNIEnv *env) { jclass clazz; clazz = env->FindClass("pku/shengbin/hevdecoder/NativeMediaPlayer"); if (clazz == NULL) { jniThrowException(env, "java/lang/RuntimeException", "Can't find MediaPlayer"); return; } fields.postEvent = env->GetStaticMethodID(clazz, "postEventFromNative", "(III)V"); if (fields.postEvent == NULL) { jniThrowException(env, "java/lang/RuntimeException", "Can't find MediaPlayer.postEventFromNative"); return; } fields.drawFrame = env->GetStaticMethodID(clazz, "drawFrame","(II)I"); if (fields.drawFrame == NULL) { jniThrowException(env, "java/lang/RuntimeException", "Can't find MediaPlayer.drawFrame"); return; } gClass = NULL; gEnv = NULL; gEnvLocal = NULL; p_sws_ctx = NULL; frames_sum = 0; tstart = 0; frames = 0; tlast = 0; renderFPS = 0; renderInterval = 0; } static void MediaPlayer_native_setup(JNIEnv *env, jobject thiz, jobject weak_this) { // Hold onto the MediaPlayer class for use in calling the static method // that posts events to the application thread. jclass clazz = env->GetObjectClass(thiz); if (clazz == NULL) { jniThrowException(env, "java/lang/Exception", kClassPathName); return; } gClass = (jclass)env->NewGlobalRef(clazz); gEnv = env; } static void MediaPlayer_renderBitmap(JNIEnv *env, jobject obj, jobject bitmap) { void* pixels; int ret; if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) { LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret); } // Convert the image from its native format to RGB565 uint32_t start_time = getms(); LOGD("before scale: %d", getms()); #if USE_SWSCALE // use swscale, which may be optimized with SSE for x86 arch if (p_sws_ctx == NULL) { p_sws_ctx = sws_getContext( gVF.width, gVF.height, PIX_FMT_YUV420P, gVF.width, gVF.height, PIX_FMT_RGB565, SWS_BICUBIC|SWS_CPU_CAPS_MMX|SWS_CPU_CAPS_MMX2|SWS_CPU_CAPS_SSE2, NULL, NULL, NULL); } if (p_sws_ctx != NULL) { unsigned char *src[4]; int src_stride[4]; unsigned char *dst[4]; int dst_stride[4]; src_stride[0] = gVF.linesize_y; src_stride[1] = src_stride[2] = gVF.linesize_uv; dst[0] = (unsigned char*)pixels; dst_stride[0] = gVF.width * 2; sws_scale(p_sws_ctx, (const uint8_t * const *)gVF.yuv_data, src_stride, 0, gVF.height, dst, dst_stride); } #else ConvertYCbCrToRGB565( gVF.yuv_data[0], gVF.yuv_data[1], gVF.yuv_data[2], (uint8_t*)pixels, gVF.width, gVF.height, gVF.linesize_y, gVF.linesize_uv, gVF.width * 2, 420 ); #endif uint32_t end_time = getms(); LOGD("after scale: %d", getms()); LOGD("scale time: %dms", end_time - start_time); AndroidBitmap_unlockPixels(env, bitmap); } // ---------------------------------------------------------------------------- static JNINativeMethod gMethods[] = { { "setDataSource", "(Ljava/lang/String;)I", (void *) MediaPlayer_setDataSource }, { "native_prepare", "(IF)I", (void *) MediaPlayer_prepare }, { "native_start", "()I", (void *) MediaPlayer_start }, { "native_stop", "()I", (void *) MediaPlayer_stop }, { "getVideoWidth", "()I", (void *) MediaPlayer_getVideoWidth }, { "getVideoHeight", "()I", (void *) MediaPlayer_getVideoHeight }, { "native_seekTo", "(I)I", (void *) MediaPlayer_seekTo }, { "native_pause", "()I", (void *) MediaPlayer_pause }, { "native_go", "()I", (void *) MediaPlayer_go }, { "isPlaying", "()Z", (void *) MediaPlayer_isPlaying }, { "getCurrentPosition", "()I", (void *) MediaPlayer_getCurrentPosition }, { "getDuration", "()I", (void *) MediaPlayer_getDuration }, { "native_init", "()V", (void *) MediaPlayer_native_init }, { "native_setup", "(Ljava/lang/Object;)V", (void *) MediaPlayer_native_setup }, { "renderBitmap", "(Landroid/graphics/Bitmap;)V", (void *) MediaPlayer_renderBitmap }, }; int register_player(JNIEnv *env) { return jniRegisterNativeMethods(env, kClassPathName, gMethods, sizeof(gMethods) / sizeof(gMethods[0])); } <file_sep>/andhevdecoderNew/app/build/intermediates/incremental/mergeDebugAndroidTestResources/compile-file-map.properties #Thu Feb 16 18:19:47 CST 2017 <file_sep>/andhevdecoder/jni/jniplayer/gl_renderer.cpp // gl_renderer.cpp : render YUV data directly using GPU with OpenGL ES 2.0 // // Copyright (c) 2013 Strongene Ltd. All Right Reserved. // http://www.strongene.com // // Contributors: // <NAME> <<EMAIL>> // <NAME> <<EMAIL>> // // You are free to re-use this as the basis for your own application // in source and binary forms, with or without modification, provided // that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice and this list of conditions. // * Redistributions in binary form must reproduce the above // copyright notice and this list of conditions in the documentation // and/or other materials provided with the distribution. #include <jni.h> #include <android/log.h> #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <pthread.h> #include "jniplayer.h" #include "gl_renderer.h" #include "jni_utils.h" extern VideoFrame gVF; extern pthread_mutex_t gVFMutex; #define LOG_TAG "gl_renderer" #define ENABLE_LOGD 0 #if ENABLE_LOGD #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #else #define LOGD(...) #endif #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) static GLuint gProgram; static GLuint gTexIds[3]; static GLuint gAttribPosition; static GLuint gAttribTexCoord; static GLuint gUniformTexY; static GLuint gUniformTexU; static GLuint gUniformTexV; static int backingWidth, backingHeight; static int needSetup = 0; static const char gVertexShader[] = "attribute vec4 a_position;\n" "attribute vec2 a_texCoord;\n" "varying vec2 v_tc;\n" "void main()\n" "{\n" " gl_Position = a_position;\n" " v_tc = a_texCoord;\n" "}\n"; static const char gFragmentShader[] = "varying lowp vec2 v_tc;\n" "uniform sampler2D u_texY;\n" "uniform sampler2D u_texU;\n" "uniform sampler2D u_texV;\n" "void main(void)\n" "{\n" "mediump vec3 yuv;\n" "lowp vec3 rgb;\n" "yuv.x = texture2D(u_texY, v_tc).r;\n" "yuv.y = texture2D(u_texU, v_tc).r - 0.5;\n" "yuv.z = texture2D(u_texV, v_tc).r - 0.5;\n" "rgb = mat3( 1, 1, 1,\n" "0, -0.39465, 2.03211,\n" "1.13983, -0.58060, 0) * yuv;\n" "gl_FragColor = vec4(rgb, 1);\n" "}\n"; static void printGLString(const char *name, GLenum s) { const char *v = (const char *) glGetString(s); LOGI("GL %s = %s\n", name, v); } static GLuint loadShader(GLenum shaderType, const char* pSource) { GLuint shader = glCreateShader(shaderType); if (shader) { glShaderSource(shader, 1, &pSource, NULL); glCompileShader(shader); GLint compiled = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLint infoLen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen) { char* buf = (char*) malloc(infoLen); if (buf) { glGetShaderInfoLog(shader, infoLen, NULL, buf); LOGE("Could not compile shader %d:\n%s\n", shaderType, buf); free(buf); } glDeleteShader(shader); shader = 0; } } } return shader; } static GLuint createProgram(const char* pVertexSource, const char* pFragmentSource) { GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource); if (!vertexShader) { return 0; } GLuint fragmentShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource); if (!fragmentShader) { return 0; } GLuint program = glCreateProgram(); if (program) { glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); glLinkProgram(program); GLint linkStatus = GL_FALSE; glGetProgramiv(program, GL_LINK_STATUS, &linkStatus); if (linkStatus != GL_TRUE) { GLint bufLength = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength); if (bufLength) { char* buf = (char*) malloc(bufLength); if (buf) { glGetProgramInfoLog(program, bufLength, NULL, buf); LOGE("Could not link program:\n%s\n", buf); free(buf); } } glDeleteProgram(program); program = 0; } } return program; } static GLfloat vertexPositions[] = { -1.0, -1.0, 0.0, 1.0, -1.0, 0.0, -1.0, 1.0, 0.0, 1.0, 1.0, 0.0 }; static GLfloat textureCoords[] = { 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0 }; static int init() { printGLString("Version", GL_VERSION); printGLString("Vendor", GL_VENDOR); printGLString("Renderer", GL_RENDERER); printGLString("Extensions", GL_EXTENSIONS); // create and use our program gProgram = createProgram(gVertexShader, gFragmentShader); if (!gProgram) { LOGE("Could not create program."); return -1; } glUseProgram(gProgram); // get the location of attributes in our shader gAttribPosition = glGetAttribLocation(gProgram, "a_position"); gAttribTexCoord = glGetAttribLocation(gProgram, "a_texCoord"); // get the location of uniforms in our shader gUniformTexY = glGetUniformLocation(gProgram, "u_texY"); gUniformTexU = glGetUniformLocation(gProgram, "u_texU"); gUniformTexV = glGetUniformLocation(gProgram, "u_texV"); // can enable only once glEnableVertexAttribArray(gAttribPosition); glEnableVertexAttribArray(gAttribTexCoord); // set the value of uniforms (uniforms all have constant value) glUniform1i(gUniformTexY, 0); glUniform1i(gUniformTexU, 1); glUniform1i(gUniformTexV, 2); // generate and set parameters for the textures glEnable (GL_TEXTURE_2D); glGenTextures(3, gTexIds); for (int i = 0; i < 3; i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, gTexIds[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } return 0; } static int setupGraphics(int w, int h) { LOGI("setupGraphics(%d, %d)", w, h); backingWidth = w; backingHeight = h; needSetup = 1; return 0; } void glDrawFrame() { pthread_mutex_lock(&gVFMutex); if (gVF.yuv_data[0] == NULL) { LOGI("gVF.yuv_data[0] == NULL"); pthread_mutex_unlock(&gVFMutex); return; } double pts = gVF.pts; if (needSetup) { LOGI("Will setup ... \n"); GLuint width = gVF.width; GLuint height = gVF.height; float aspect = (float) width / (float) height; if (aspect >= (float) backingWidth / (float) backingHeight) { // fill screen in width, and leave space in Y float scale = (float) backingWidth / (float) width; float maxY = ((float) height * scale) / (float) backingHeight; vertexPositions[1] = vertexPositions[4] = -maxY; vertexPositions[7] = vertexPositions[10] = maxY; } else { // fill screen in height, and leave space in X float scale = (float) backingHeight / (float) height; float maxX = ((float) width * scale) / (float) backingWidth; vertexPositions[0] = vertexPositions[6] = -maxX; vertexPositions[3] = vertexPositions[9] = maxX; } // modify the texture coordinates float texCoord = ((float) width) / gVF.linesize_y; textureCoords[2] = textureCoords[6] = texCoord; // set the value of attributes glVertexAttribPointer(gAttribPosition, 3, GL_FLOAT, 0, 0, vertexPositions); glVertexAttribPointer(gAttribTexCoord, 2, GL_FLOAT, 0, 0, textureCoords); glViewport(0, 0, backingWidth, backingHeight); LOGI("setup finished\n"); needSetup = 0; } glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear (GL_COLOR_BUFFER_BIT); LOGD("before upload: %u (%f)", getms(), pts); // upload textures glActiveTexture(GL_TEXTURE0 + 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, gVF.linesize_y, gVF.height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, gVF.yuv_data[0]); glActiveTexture(GL_TEXTURE0 + 1); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, gVF.linesize_uv, gVF.height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, gVF.yuv_data[1]); glActiveTexture(GL_TEXTURE0 + 2); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, gVF.linesize_uv, gVF.height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, gVF.yuv_data[2]); pthread_mutex_unlock(&gVFMutex); LOGD("after upload: %u (%f)", getms(), pts); LOGD("before glDrawArrays: %u (%f)", getms(), pts); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); LOGD("after glDrawArrays: %u (%f)", getms(), pts); } jint nativeInit(JNIEnv * env, jobject obj) { int ret = init(); if (ret < 0) { LOGE("initialize failed!"); } return ret; } jint nativeSetup(JNIEnv * env, jobject obj, jint width, jint height) { int ret = setupGraphics(width, height); if (ret < 0) { LOGE("setup failed!"); } return ret; } void nativeDrawFrame(JNIEnv * env, jobject obj) { glDrawFrame(); } static JNINativeMethod methods[] = { { "nativeInit", "()I", (void *) nativeInit }, { "nativeSetup", "(II)I", (void *) nativeSetup }, { "nativeDrawFrame", "()V", (void *) nativeDrawFrame }, }; int register_renderer(JNIEnv *env) { return jniRegisterNativeMethods(env, "pku/shengbin/hevdecoder/GLRenderer", methods, sizeof(methods) / sizeof(methods[0])); } <file_sep>/andhevdecoder/jni/jniplayer/Android.mk LOCAL_PATH := $(call my-dir) # # jniplayer.so # include $(CLEAR_VARS) ifeq ($(TARGET_ARCH_ABI), armeabi-v7a) LENT_CFLAGS := -DARCH_ARM=1 -DHAVE_NEON=1 endif ifeq ($(TARGET_ARCH_ABI), x86) LENT_CFLAGS := -DARCH_X86_32=1 endif LOCAL_C_INCLUDES += $(LOCAL_PATH)/../lenthevcdec/ $(LOCAL_PATH)/../../../../../../ LOCAL_SRC_FILES := jniplayer.cpp jni_utils.cpp yuv2rgb565.cpp gl_renderer.cpp LOCAL_LDLIBS := -llog -lz -ljnigraphics -lGLESv2 LOCAL_CFLAGS += $(LENT_CFLAGS) LOCAL_SHARED_LIBRARIES := lenthevcdec LOCAL_MODULE := jniplayer include $(BUILD_SHARED_LIBRARY) <file_sep>/andhevdecoder/jni/jniplayer/jni_utils.cpp #include <stdlib.h> #include <android/log.h> #include "jni_utils.h" #define LOG_TAG "jni_utils" static JavaVM *gVM; extern int register_player(JNIEnv *env); extern int register_renderer(JNIEnv *env); /* * Throw an exception with the specified class and an optional message. */ int jniThrowException(JNIEnv* env, const char* className, const char* msg) { jclass exceptionClass = env->FindClass(className); if (exceptionClass == NULL) { LOGE("Unable to find exception class %s", className); return -1; } if (env->ThrowNew(exceptionClass, msg) != JNI_OK) { LOGE("Failed throwing '%s' '%s'", className, msg); } return 0; } JNIEnv* getJNIEnv() { JNIEnv* env = NULL; int ret = gVM->GetEnv((void**) &env, JNI_VERSION_1_4); if (ret == JNI_OK) { return env; } else if (ret == JNI_EDETACHED) { jint attachSuccess = gVM->AttachCurrentThread(&env, NULL); if (attachSuccess != 0) { LOGE("attach current thread failed \n"); return NULL; } } else { LOGE("obtain JNIEnv failed, return: %d \n", ret); } return env; } void detachJVM() { int ret; ret = gVM->DetachCurrentThread(); if (ret == JNI_OK) { LOGI("detach return OK: %d", ret); } else { LOGE("detach return NOT OK: %d", ret); } } /* * Register native JNI-callable methods. * * "className" looks like "java/lang/String". */ int jniRegisterNativeMethods(JNIEnv* env, const char* className, const JNINativeMethod* gMethods, int numMethods) { jclass clazz; LOGI("Registering %s natives\n", className); clazz = env->FindClass(className); if (clazz == NULL) { LOGE("Native registration unable to find class '%s'\n", className); return -1; } if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) { LOGE("RegisterNatives failed for '%s'\n", className); return -1; } return 0; } jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv* env = NULL; jint result = JNI_ERR; gVM = vm; if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) { LOGE("GetEnv failed!"); return JNI_ERR; } LOGI("loading . . ."); if (register_player(env) != JNI_OK) { LOGE("can't register player"); return JNI_ERR; } if (register_renderer(env) != JNI_OK) { LOGE("can't register renderer"); return JNI_ERR; } LOGI("loaded"); return JNI_VERSION_1_4; } <file_sep>/andhevdecoderNew/app/src/main/java/pku/shengbin/hevdecoder/NativeMediaPlayer.java package pku.shengbin.hevdecoder; import android.app.Activity; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Bitmap.Config; import android.opengl.GLSurfaceView; import android.preference.PreferenceManager; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.Surface.OutOfResourcesException; import android.widget.TextView; import java.io.File; import java.io.FileFilter; import java.lang.ref.WeakReference; import java.util.regex.Pattern; public class NativeMediaPlayer { public static final int MEDIA_INFO_FRAMERATE_VIDEO = 900; public static final int MEDIA_INFO_END_OF_FILE = 909; private int mNativeContext; // accessed by native methods private static Activity mOwnerActivity; private static Surface mSurface; private static GLSurfaceView mGLSurfaceView; private static TextView mInfoTextView; private static Bitmap mFrameBitmap = null; private static int mDisplayWidth = 0; private static int mDisplayHeight = 0; private static int mDisplayFPS = -1; private static int mDisplayAvgFPS = -1; private static int mDecodeFPS = -1; private static int mBitrateVideo = -1; private static int mBitrateAudio = -1; private static boolean mShowInfo = true; private static boolean mShowInfoGL = true; private static String mInfo = ""; private native final void native_init(); private native final void native_setup(Object mediaplayer_this); private native int native_prepare(int threadNum, float renderFPS); private native int native_start(); private native int native_stop(); private native int native_pause(); private native int native_go(); private native int native_seekTo(int msec); public NativeMediaPlayer(Activity activity) { native_init(); /* * Native setup requires a weak reference to our object. It's easier to * create it here than in C++. */ native_setup(new WeakReference<NativeMediaPlayer>(this)); mOwnerActivity = activity; } private native static int hasNeon(); static { System.loadLibrary("lenthevcdec"); System.loadLibrary("jniplayer"); } public void setDisplay(SurfaceHolder sh) { if (sh != null) { mSurface = sh.getSurface(); } else mSurface = null; } public void setGLDisplay(GLSurfaceView glView, TextView tv) { mGLSurfaceView = glView; mInfoTextView = tv; } public void setDisplaySize(int w, int h) { mDisplayHeight = h; mDisplayWidth = w; } public native int setDataSource(String path); public native int getVideoWidth(); public native int getVideoHeight(); public native boolean isPlaying(); public native int getCurrentPosition(); public native int getDuration(); /** * Gets the number of cores available in this device, across all processors. * Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu" * * @return The number of cores, or 1 if failed to get result */ private int getNumCores() { // Private Class to display only CPU devices in the directory listing class CpuFilter implements FileFilter { @Override public boolean accept(File pathname) { // Check if filename is "cpu", followed by a single digit number if (Pattern.matches("cpu[0-9]+", pathname.getName())) { return true; } return false; } } try { // Get directory containing CPU info File dir = new File("/sys/devices/system/cpu/"); // Filter to only list the devices we care about File[] files = dir.listFiles(new CpuFilter()); // Return the number of cores (virtual CPU devices) return files.length; } catch (Exception e) { // Default to return 1 core return 1; } } public int prepare() { // android maintains the preferences for us, so use directly SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(mOwnerActivity); int num = Integer.parseInt(settings.getString("multi_thread", "0")); if (0 == num) { int cores = getNumCores();// Runtime.getRuntime().availableProcessors(); if (cores <= 1) num = 1; else num = (cores < 5) ? ((cores * 3 + 1) / 2) : 8; Log.d("NativeMediaPlayer", cores + " cores detected! use " + num + " threads.\n"); } float fps = Float.parseFloat(settings.getString("render_fps", "0")); return native_prepare(num, fps); } public int start() { int w = getVideoWidth(), h = getVideoHeight(); if (w > 0 && h > 0) mFrameBitmap = Bitmap.createBitmap(w, h, Config.RGB_565); return native_start(); } public void stop() { native_stop(); } public void pause() { native_pause(); } public void go() { native_go(); } public void seekTo(int msec) { } public void setShowInfo(boolean show) { mShowInfo = show; if (mShowInfo == false && mInfoTextView != null) { mInfoTextView.setText(""); } } private native static void renderBitmap(Bitmap bitmap); public static int drawFrame(int width, int height) { SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(mOwnerActivity); boolean useGL = settings.getBoolean("opengl_switch", true); if (useGL) { mGLSurfaceView.requestRender(); if (mShowInfoGL) { mInfo = ""; Paint paint = new Paint(); paint.setColor(Color.WHITE); paint.setTextSize(40); if (width > 0) { mInfo += ("Video Size:" + width + "x" + height); } if (mDisplayFPS > 0) { mInfo += (" Display FPS:" + mDisplayFPS); } if (mDisplayAvgFPS > 0) { mInfo += String.format(" Average FPS:%.2f", mDisplayAvgFPS / 4096.0); } mOwnerActivity.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub mInfoTextView.setText(mInfo); } }); mShowInfoGL = false; } return 0; } // draw without OpenGL Canvas canvas = null; try { canvas = mSurface.lockCanvas(null); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OutOfResourcesException e) { // TODO Auto-generated catch block e.printStackTrace(); } canvas.drawColor(Color.BLACK); if (null == mFrameBitmap || mFrameBitmap.getWidth() != width) { // video size has changed, we need to create a new frame bitmap // correspondingly mFrameBitmap = Bitmap.createBitmap(width, height, Config.RGB_565); } renderBitmap(mFrameBitmap); if (mDisplayWidth != mFrameBitmap.getWidth()) { Matrix matrix = new Matrix(); float scaleWidth = ((float) mDisplayWidth) / width; float scaleHeight = ((float) mDisplayHeight) / height; matrix.postScale(scaleWidth, scaleHeight); matrix.postTranslate((canvas.getWidth() - mDisplayWidth) / 2, (canvas.getHeight() - mDisplayHeight) / 2); if (mFrameBitmap.getWidth() < 640) { // small bitmap, able to use filter Paint paint = new Paint(); paint.setFilterBitmap(true); canvas.drawBitmap(mFrameBitmap, matrix, paint); } else { canvas.drawBitmap(mFrameBitmap, matrix, null); } } else { canvas.drawBitmap(mFrameBitmap, (canvas.getWidth() - mDisplayWidth) / 2, (canvas.getHeight() - mDisplayHeight) / 2, null); } if (mShowInfo) { Paint paint = new Paint(); paint.setColor(Color.WHITE); paint.setTextSize(40); String info = ""; if (width > 0) { info += ("Video Size:" + width + "x" + height); } if (mDisplayFPS > 0) { info += (" Display FPS:" + mDisplayFPS); } if (mDisplayAvgFPS > 0) { info += String.format(" Average FPS:%.2f", mDisplayAvgFPS / 4096.0); } if (mDecodeFPS > 0) { info += (" Decode FPS:" + mDecodeFPS); } canvas.drawText(info, 20, 60, paint); info = ""; if (mBitrateVideo > 0) { info += "Bitrate: video " + Integer.toString(mBitrateVideo); } if (mBitrateAudio > 0) { info += ", audio " + Integer.toString(mBitrateAudio); } if (mBitrateVideo > 0 || mBitrateAudio > 0) { info += ", total " + Integer.toString(mBitrateVideo + mBitrateAudio) + " kbit/s"; } canvas.drawText(info, 20, 100, paint); } mSurface.unlockCanvasAndPost(canvas); return 0; } /** * Called from native code when an interesting event happens. This method * just uses the EventHandler system to post the event back to the main app * thread. We use a weak reference to the original MediaPlayer object so * that the native code is safe from the object disappearing from underneath * it. (This is the cookie passed to native_setup().) */ public static void postEventFromNative(int what, int arg1, int arg2) { switch (what) { case MEDIA_INFO_FRAMERATE_VIDEO: mDisplayFPS = arg1; mDisplayAvgFPS = arg2; if (mShowInfo) { mShowInfoGL = true; } break; case MEDIA_INFO_END_OF_FILE: mOwnerActivity.finish(); break; } } } <file_sep>/andhevdecoder/jni/jniplayer/jniplayer.h #ifndef __JNIPLAYER_H__ #define __JNIPLAYER_H__ struct VideoFrame { int width; int height; int linesize_y; int linesize_uv; double pts; uint8_t *yuv_data[3]; }; uint32_t getms(); #endif /* __JNIPLAYER_H__ */ <file_sep>/andhevdecoderNew/.gradle/2.14.1/taskArtifacts/cache.properties #Thu Feb 16 18:18:49 CST 2017 <file_sep>/andhevdecoder/jni/jniplayer/yuv2rgb565.h #include <sys/types.h> void ConvertYCbCrToRGB565_neon( const uint8_t* y_buf, const uint8_t* u_buf, const uint8_t* v_buf, uint8_t* rgb_buf, int pic_width, int pic_height, int y_stride, int uv_stride, int rgb_stride, int yuv_type); void ConvertYCbCrToRGB565_c( const uint8_t* y_buf, const uint8_t* u_buf, const uint8_t* v_buf, uint8_t* rgb_buf, int pic_width, int pic_height, int y_stride, int uv_stride, int rgb_stride, int yuv_type); void ConvertYCbCrToRGB565( const uint8_t* y_buf, const uint8_t* u_buf, const uint8_t* v_buf, uint8_t* rgb_buf, int pic_width, int pic_height, int y_stride, int uv_stride, int rgb_stride, int yuv_type); <file_sep>/README.md 视骏HEVC decoder demo(20150615版本) - 本工程下载自视骏官网: http://www.xhevc.com/resource/Strongene_Lentoid_HEVC_Decoder_Android_2015_06_15.zip - 其中andhevdecoder目录是视骏之前基于Eclipse的工程 - andhevdecoderNew是我转换成基于gradle的工程 <file_sep>/andhevdecoder/jni/jniplayer/jni_utils.h #ifndef __JNI_UTILS_H__ #define __JNI_UTILS_H__ #include <stdlib.h> #include <jni.h> #include <android/log.h> #ifdef __cplusplus #define __STDC_CONSTANT_MACROS #define __STDC_LIMIT_MACROS #ifdef _STDINT_H #undef _STDINT_H #endif #include <stdint.h> #define __STDC_FORMAT_MACROS #endif #define ENABLE_LOGD 0 #if ENABLE_LOGD #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #else #define LOGD(...) #endif #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) int jniThrowException(JNIEnv* env, const char* className, const char* msg); int jniRegisterNativeMethods(JNIEnv* env, const char* className, const JNINativeMethod* gMethods, int numMethods); JNIEnv* getJNIEnv(); void detachJVM(); #endif /* __JNI_UTILS_H__ */
b893549d2303d9c444d6e8bfae45d493d9f49fad
[ "Markdown", "Makefile", "INI", "Gradle", "Java", "C", "C++" ]
14
Gradle
Bingnan/Lentoid_HEVC_Decoder_Demo
847037718f7ed539b073b21a2a07cdc93d6b7e96
07d1f756d17f011fad917268faac67f09482128f
refs/heads/master
<repo_name>RecencyBias/Total_work_till_date<file_sep>/scrapers/twitterscraper-master/requirements.txt coala-utils~=0.5.0 bs4 lxml fake_useragent requests<file_sep>/diff_tweets_single_person_daily_analysis/new1.py import re str = open('modi50.txt', 'r').read() #exampleString = "Jessica is 15 years old, and Daniel is 27 years old.Edward is 97 years old, and his grandfather, Oscar, is 102." #replies = re.findall(r'\d{1,6} replies',str) #str1 = ''.join(replies) #replies1 = re.findall(r'\d{1,6}',str1) retweets = re.findall(r"retweet_count=\d{1,6}|'retweet_count': \d{1,6}",str) str2 = ''.join(retweets) retweets2 = re.findall(r'\d{1,6}',str2) days = re.findall(r"'created_at':\s'[A-Z][a-z][a-z]\s[A-z][a-z][a-z]\s\d{1,2}",str) #2016', 'favourites_count dates = re.findall(r"\d{1,4}', 'favourites_count",str) strdates = ''.join(dates) year = re.findall(r'\d{1,4}',strdates) #print year for x in year: year.remove('2009') print len(retweets2) #print len(dates) print len(year) print year strday = ''.join(days) #print strday date = re.findall(r"[A-Z][a-z][a-z]\s[A-z][a-z][a-z]\s\d{1,2}",strday) strdate = ''.join(date) finaldate = re.findall('[A-z][a-z][a-z]\s\d{1,2}',strdate) strdates = ''.join(finaldate) #mat=re.match(r'(\d{4})[,]\s(\d{2})[,]\s(\d{2})[,]\s(\d{2})[,]\s(\d{2})[,]\s(\d{2})',str) #print finaldate augdays = re.findall(r'Aug\s\d{1,2}',strdates) juldays = re.findall(r'Jul\s\d{1,2}',strdates) jundays = re.findall(r'Jun\s\d{1,2}',strdates) maydays = re.findall(r'May\s\d{1,2}',strdates) aprdays = re.findall(r'Apr\s\d{1,2}',strdates) jandays = re.findall(r'Jan\s\d{1,2}',strdates) febdays = re.findall(r'Feb\s\d{1,2}',strdates) mardays = re.findall(r'Mar\s\d{1,2}',strdates) sepdays = re.findall(r'Sep\s\d{1,2}',strdates) octdays = re.findall(r'Oct\s\d{1,2}',strdates) novdays = re.findall(r'Nov\s\d{1,2}',strdates) decdays = re.findall(r'Dec\s\d{1,2}',strdates) #print aprdays augdays = ''.join(augdays) juldays = ''.join(juldays) jundays = ''.join(jundays) maydays = ''.join(maydays) aprdays = ''.join(aprdays) jandays = ''.join(jandays) febdays = ''.join(febdays) mardays = ''.join(mardays) sepdays = ''.join(sepdays) octdays = ''.join(octdays) novdays = ''.join(novdays) decdays = ''.join(decdays) #print augdays augdays1 = re.findall(r'\d{1,2}',augdays) juldays1 = re.findall(r'\d{1,2}',juldays) jundays1 = re.findall(r'\d{1,2}',jundays) maydays1 = re.findall(r'\d{1,2}',maydays) aprdays1 = re.findall(r'\d{1,2}',aprdays) jandays1 = re.findall(r'\d{1,2}',jandays) febdays1 = re.findall(r'\d{1,2}',febdays) mardays1 = re.findall(r'\d{1,2}',mardays) sepdays1 = re.findall(r'\d{1,2}',sepdays) octdays1 = re.findall(r'\d{1,2}',octdays) novdays1 = re.findall(r'\d{1,2}',novdays) decdays1 = re.findall(r'\d{1,2}',decdays) augdates = [int(numeric_string) for numeric_string in augdays1] juldates = [int(numeric_string) for numeric_string in juldays1] jundates = [int(numeric_string) for numeric_string in jundays1] maydates = [int(numeric_string) for numeric_string in maydays1] aprdates = [int(numeric_string) for numeric_string in aprdays1] jandates = [int(numeric_string) for numeric_string in jandays1] febdates = [int(numeric_string) for numeric_string in febdays1] mardates = [int(numeric_string) for numeric_string in mardays1] #sepdates = [int(numeric_string) for numeric_string in sepdays1] #octdates = [int(numeric_string) for numeric_string in octdays1] #novdates = [int(numeric_string) for numeric_string in novdays1] #decdates = [int(numeric_string) for numeric_string in decdays1] print augdates finaldate1 = [] for i in augdates: finaldate.append(16-i) for i in juldates: if(13-i > 0): finaldate1.append(30+13-i) elif(13-i < 0): finaldate1.append(30 - abs(13-i)) for i in jundates: if(13-i > 0): finaldate1.append(30*2+13-i) elif(13-i < 0): finaldate1.append(30*2 -abs(13-i)) for i in maydates: if(13-i > 0): finaldate1.append(30*3+13-i) elif(13-i < 0): finaldate1.append(30*3-abs(13-i)) for i in aprdates: if(13-i > 0): finaldate1.append(30*4+13-i) elif(13-i < 0): finaldate1.append(30*4-abs(13-i)) finaldate1.append(30 - abs(13-i)) for i in mardates: if(13-i > 0): finaldate1.append(30*5+13-i) elif(13-i < 0): finaldate1.append(30*5 -abs(13-i)) for i in febdates: if(13-i > 0): finaldate1.append(30*6+13-i) elif(13-i < 0): finaldate1.append(30*6-abs(13-i)) for i in jandates: if(13-i > 0): finaldate1.append(30*7+13-i) elif(13-i < 0): finaldate1.append(30*7-abs(13-i)) print finaldate1 #print year #print dmo #days1 = re.findall(r'\d{1,2}',strday) #intdays = [int(numeric_string) for numeric_string in days1] likes = re.findall(r"favorite_count=\d{1,6}|'favorite_count': \d{1,6}",str) str3 = ''.join(likes) likes2 = re.findall(r'\d{1,6}',str3) #time = re.findall(r'\d{1,2} hours ago',str) #str4 = ''.join(time) #time2 = re.findall(r'\d{1,2}',str4) #print days #print days1 #print intdays #print retweets #print days #print likes #print retweets2 #print likes2 intretweets = [int(numeric_string) for numeric_string in retweets2] intlikes = [int(numeric_string) for numeric_string in likes2] #print intretweets #print intlikes ''' intnewdays = [abs(11-i)*24 for i in intdays] for i in intdays: if((11-i) > 0): j = (11-i)*24 intnewdays.append(j) else: j = abs(11-31)*24+(31-i)*24 intnewdays.append(j) #print intnewdays intnewdays = intnewdays[0:5] #print intnewdays #time = re.findall(r'[A-Z][a-z]*\s\d{1,2}',str) #retweets = re.findall(r'[A-Z][a-z]*',exampleString) intreplies = [int(numeric_string) for numeric_string in replies1] inttime = [int(numeric_string) for numeric_string in time2] inttime=inttime+intnewdays print inttime print(intreplies) print(intretweets) print(intlikes) print(inttime) intreplies1 = intreplies[0:7] intretweets2=intretweets[0:7] intlikes2=intlikes[0:7] inttime1=inttime[0:7] print(len(intreplies1)) print(len(intretweets2)) print(len(intlikes2)) print(len(inttime1)) print(intreplies1) print(intretweets2) print(intlikes2) print(inttime1) import matplotlib.pyplot as plt x=inttime1 #labels=['','feb','mar','apr'] y=intlikes2 plt.bar(x,y, align='center',color='green',label="No of likes") #plt.xticks(x, labels) plt.xlabel('Number of hours ago tweet was posted') plt.ylabel('Features(Likes, Retweets, Replies') plt.title('Histogram depicting the relationship between popularity of media features and time') plt.bar(x,intretweets2,color='yellow',label = "No of retweets") plt.bar(x,intreplies1,color='blue',label = "No of replies") plt.show() import numpy #a = numpy.array([[1,2],[3,4],[5,6]]) numpy.savetxt("pc.csv",zip(inttime,intreplies,intlikes,intretweets), delimiter=',', header="Time,Replies,Likes,Retweets", comments="") ''' <file_sep>/diff_tweets_single_person_daily_analysis/mg.py import re str = open('melindagates.txt', 'r').read() #exampleString = "Jessica is 15 years old, and Daniel is 27 years old.Edward is 97 years old, and his grandfather, Oscar, is 102." replies = re.findall(r'\d{1,6} replies',str) str1 = ''.join(replies) replies1 = re.findall(r'\d{1,6}',str1) retweets = re.findall(r'\d{1,6} retweets',str) str2 = ''.join(retweets) retweets2 = re.findall(r'\d{1,6}',str2) augdays = re.findall(r'Aug\s\d{1,2}',str) juldays = re.findall(r'Jul\s\d{1,2}',str) print augdays augdays = ''.join(augdays) juldays = ''.join(juldays) #jundays = ''.join(jundays) augdays1 = re.findall(r'\d{1,2}',augdays) juldays1 = re.findall(r'\d{1,2}',juldays) #jundays1 = re.findall(r'\d{1,2}',jundays) augdates = [int(numeric_string) for numeric_string in augdays1] juldates = [int(numeric_string) for numeric_string in juldays1] #jundates = [int(numeric_string) for numeric_string in jundays1] print augdates print juldates #print jundates finaldate = [] for i in augdates: finaldate.append(13-i) for i in juldates: if(13-i > 0): finaldate.append(30+13-i) elif(13-i < 0): finaldate.append(30 - abs(13-i)) print finaldate '''strday = ''.join(days)0 days1 = re.findall(r'\d{1,2}',strday) intdays = [int(numeric_string) for numeric_string in days1] print intdays''' likes = re.findall(r'\d{1,6} likes',str) str3 = ''.join(likes) likes2 = re.findall(r'\d{1,6}',str3) '''time = re.findall(r'\d{1,2} hours ago',str) str4 = ''.join(time) time2 = re.findall(r'\d{1,2}',str4) #print days #print days1 #print intdays intnewdays = [] for i in for i in intdays: if((13-i) > 0): j = 13-i intnewdays.append(j) else: j = abs(13-31)+13-i intnewdays.append(j) print intnewdays #intnewdays = intnewdays[0:5] #print intnewdays #time = re.findall(r'[A-Z][a-z]*\s\d{1,2}',str) ''' #retweets = re.findall(r'[A-Z][a-z]*',exampleString) intreplies = [int(numeric_string) for numeric_string in replies1] intretweets = [int(numeric_string) for numeric_string in retweets2] intlikes = [int(numeric_string) for numeric_string in likes2] #inttime = [int(numeric_string) for numeric_string in time2] #inttime=inttime+intnewdays #print inttime print(intreplies) print(intretweets) print(intlikes) print(finaldate) intreplies1 = intreplies[0:20] intretweets2=intretweets[0:20] intlikes2=intlikes[0:20] #inttime1=intnewdays[0:10] ''' print(len(intreplies1)) print(len(intretweets2)) print(len(intlikes2)) print(len(inttime1)) print(intreplies1) print(intretweets2) print(intlikes2) print(inttime1) ''' import matplotlib.pyplot as plt x=finaldate #labels=['','feb','mar','apr'] y=intlikes2 plt.bar(x,y, align='center',color='green',label="No of likes") #plt.xticks(x, labels) plt.xlabel('Number of days ago tweet was posted') plt.ylabel('Features(Likes = green, Retweets=yellow, Replies=blue)') plt.title('Histogram depicting the relationship between popularity of media features and time') plt.bar(x,intretweets2,color='yellow',label = "No of retweets") plt.bar(x,intreplies1,color='blue',label = "No of replies") plt.show() import numpy #a = numpy.array([[1,2],[3,4],[5,6]]) numpy.savetxt("pc.csv",zip(inttime,intreplies,intlikes,intretweets), delimiter=',', header="Time,Replies,Likes,Retweets", comments="") <file_sep>/hourly_analysis_single_tweets/finaltry.py import urllib2 from bs4 import BeautifulSoup as soup quote_page = "https://twitter.com/" # query the website and return the html to the variable 'page' page = urllib2.urlopen(quote_page) page_soup = soup(page, "html.parser") #tweets=page_soup.findAll("p",{"class":"TweetTextSize TweetTextSize--normal js-tweet-text tweet-text"}) # no of tweets 20 stored in tweets... """ tweets[0].text tweets[1].text we get tweets using it""" """for tweet in tweets: print("--> "+ (tweet.text)) comment=""" prat=page_soup.findAll("div", {"class":"content"}) # prac=prat[0] """filename = "tweetslist.csv" f = open(filename, "w") #open file in write mode headers = "tweet, tweet_details, reply2, reweet, like\n" f.write(headers)""" for prac in prat: tweets = prac.p.text print("------->"+ tweets) # print tweet tweet_details = prac.div.text.strip() print(tweet_details) # print tweet details reply = prac.findAll("span", {"class": "ProfileTweet-actionCount"}) reply2=reply[0].text print(reply2) # print no of reply on tweet retweet =reply[1].text print(retweet) # print no of reweets likes =reply[2].text print(likes) #print no of likes # f.write(tweets + "," + tweet_details + "," + reply2 + "," + retweet + "," + likes + "\n") #f.close() <file_sep>/scrapers/twitterscraper-master/sel.py import time from selenium import webdriver from selenium.webdriver.common.keys import Keys #This may not work if you do not have chromedriver. #Get it from here: #https://sites.google.com/a/chromium.org/chromedriver/home #Copy the executable file into the PATH folder. browser = webdriver.Chrome() #opens an automated browser window url = 'https://twitter.com/narendramodi' browser.get(url) #opens the url in the browser body = browser.find_element_by_tag_name('body') for i in range(5): body.send_keys(Keys.PAGE_DOWN) time.sleep(0.2) #moves the page down by 5 page down scrolls tweets = browser.find_element_by_class_name('tweet-text') #finds elements by class name of the tweets for tweet in tweets: print(tweet) browser.close() #closes the browser window <file_sep>/scrapers/twitterscraper-master/twitterscraper/main.py """ This is a command line application that allows you to scrape twitter! """ import collections import json from argparse import ArgumentParser from datetime import datetime from os.path import isfile from json import dump import logging from twitterscraper import query_tweets from twitterscraper.query import query_all_tweets class JSONEncoder(json.JSONEncoder): def default(self, obj): if hasattr(obj, '__json__'): return obj.__json__() elif isinstance(obj, collections.Iterable): return list(obj) elif isinstance(obj, datetime): return obj.isoformat() elif hasattr(obj, '__getitem__') and hasattr(obj, 'keys'): return dict(obj) elif hasattr(obj, '__dict__'): return {member: getattr(obj, member) for member in dir(obj) if not member.startswith('_') and not hasattr(getattr(obj, member), '__call__')} return json.JSONEncoder.default(self, obj) def main(): logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO) try: parser = ArgumentParser( description=__doc__ ) parser.add_argument("query", type=str, help="Advanced twitter query") parser.add_argument("-o", "--output", type=str, default="tweets.json", help="Path to a JSON file to store the gathered " "tweets to.") parser.add_argument("-l", "--limit", type=int, default=None, help="Number of minimum tweets to gather.") parser.add_argument("-a", "--all", action='store_true', help="Set this flag if you want to get all tweets " "in the history of twitter. This may take a " "while but also activates parallel tweet " "gathering. The number of tweets however, " "will be capped at around 100000 per 10 " "days.") args = parser.parse_args() if isfile(args.output): logging.error("Output file already exists! Aborting.") exit(-1) if args.all: tweets = query_all_tweets(args.query) else: tweets = query_tweets(args.query, args.limit) with open(args.output, "w") as output: dump(tweets, output, cls=JSONEncoder) except KeyboardInterrupt: logging.info("Program interrupted by user. Quitting...") <file_sep>/timeline_plotting/ranks5.py import matplotlib.pyplot as plt import numpy as np time = [46,7,29,18,8,27,35,29,24,6,16,3,47,21,16,24,50,31,35,40,31,18,39,13,29,25,46,41] replies = [1,4,0,123,60,0,123,60,0,120,25,71,0,0,0,12,0,17,32,0,63,59,0,1,77,5,10,6,79,63] retweets = [7,9,62,1,309,6,7,347,20,219,0,3,1,32,3,28,135,9,202,96,9,15,127,16,109,13,219,253] likes = [10,46,4,0,1100,70,5,1500,58,841,0,7,2,224,10,134,458,13,854,303,16,28,162,44,143,73,697,1200] ranks = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28] plt.bar(ranks,time, align='center',color='green',label="No of likes") print len(time) print len(retweets) print len(likes) print len(ranks) plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() #plt.xticks(x, labels) plt.bar(ranks,replies,align = 'center',color='red') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() plt.bar(ranks,retweets,align = 'center',color = 'yellow') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() plt.bar(ranks,likes,align ='center',color = 'cyan') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() <file_sep>/scrapers/crawl-beautifulsoup2.py # -*- coding: utf-8 -*- # python 2 # from urllib import urlopen import os import shutil import urllib import urllib2 import urlparse import time import pprint import sys import lxml.html from bs4 import BeautifulSoup # get html links def processOneUrl(url): """fetch URL content and update resultUrl.""" try: # in case of 404 error html_page = urllib2.urlopen(url) soup = BeautifulSoup.BeautifulSoup(html_page) for link in soup.findAll('A'): fullurl = urlparse.urljoin(url, link.get('HREF')) if fullurl.startswith(inputURL): if (fullurl not in resultUrl): resultUrl[fullurl] = False resultUrl[url] = True # set as crawled except: resultUrl[url] = True # set as crawled def moreToCrawl(): """returns True or False""" for url, crawled in iter(resultUrl.iteritems()): print url print crawled if not crawled: print "moreToCrawl found {}".format(url) return url return False # craw a website, list all url under a specific given path if len(sys.argv) < 3: print "usage: python crawl-healthcare.py <folderName> <url>" exit() inputURL = sys.argv[2] resultUrl = {inputURL:False} print resultUrl # key is a url we want. value is True or False. True means already crawled docType = sys.argv[1] if os.path.isdir(os.getcwd()+"/"+docType): shutil.rmtree(docType) os.mkdir(docType) curDir=os.getcwd() os.chdir(curDir+"/"+docType) while True: toCrawl = moreToCrawl() if not toCrawl: print "not to crawl" break aStr= str(toCrawl) arr = aStr.split("/") document = str(arr[len(arr)-1]) f = open(document,'w') proxyhandler = urllib2.ProxyHandler({'http': 'http://10.10.78.61:3128'}) opener = urllib2.build_opener(proxyhandler) try: opener.open(toCrawl) except urllib2.URLError, e: print e.code print e.read() urllib2.install_opener(opener) req = urllib2.Request(toCrawl) response = urllib2.urlopen(req) html = response.read() response.read() response.close() tree = lxml.html.fromstring(html) for e in tree.iter(): if e.tag=="p" or e.tag=="h1": f.write(e.text_content().encode('utf8')) f.write('\n') f.close() processOneUrl(toCrawl) time.sleep(2) #pprint.pprint(resultUrl) <file_sep>/scrapers/twitterscraper-master/HISTORY.rst # twitterscraper changelog ## 0.x.x TBD ## 0.3.0 ( 2017-08-01 ) ### Added - Tweet class now also includes 'replies', 'retweets' and 'likes' ## 0.2.7 ( 2017-01-10 ) ----------- ### Improved - PR #26: use ``requests`` library for HTTP requests. Makes the use of urllib2 / urllib redundant. ### Added: - changelog.txt for GitHub - HISTORY.rst for PyPi - README.rst for PyPi ## 0.2.6 ( 2017-01-02 ) ----------- ### Improved - PR #25: convert date retrieved from timestamp to day precision <file_sep>/scrapers/trac2.py import tweepy import csv #Twitter API credentials consumer_key = "IWSVC6OEOK41wPBtwJPNXQAT4" consumer_secret = "<KEY>" access_key = "<KEY>" access_secret = "<KEY>" def get_all_tweets(screen_name): #Twitter only allows access to a users most recent 3240 tweets with this method #authorize twitter, initialize tweepy auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) #initialize a list to hold all the tweepy Tweets alltweets = [] #make initial request for most recent tweets (200 is the maximum allowed count) new_tweets = api.user_timeline(screen_name = screen_name,count=200) #save most recent tweets alltweets.extend(new_tweets) #save the id of the oldest tweet less one oldest = alltweets[-1].id - 1 #keep grabbing tweets until there are no tweets left to grab while len(new_tweets) > 0: print( "getting tweets before %s" % (oldest)) #all subsiquent requests use the max_id param to prevent duplicates new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest) #save most recent tweets alltweets.extend(new_tweets) #update the id of the oldest tweet less one oldest = alltweets[-1].id - 1 print ("...%s tweets downloaded so far" % (len(alltweets))) #print( tweet ) # u can use tweet.text if u want to print only tweet not other features # i print latest 500 tweets a person whose i used as a screen_name or username u can print total tweets #or no of tweets according to your choice change range in given list barray = alltweets[0:500] for tweet in barray: print(tweet) if __name__ == '__main__': get_all_tweets("MichelleObama") #pass in the username of the account you want to download I used "narendramodi". <file_sep>/hourly_analysis_single_tweets/bar.py #Numbers of features x hours after the tweet was posted import matplotlib.pyplot as plt hours = [1,2,3,4,5,6] SainaNehwal_replies = [11,1,3,2,1,0] SainaNehwal_retweets = [13,2,1,1,1,0] SainaNehwal_likes = [159,20,33,28,24,22] plt.bar(SainaNehwal_likes,SainaNehwal_retweets, align='center',color='green',label="likesvsretweets") import numpy #a = numpy.array([[1,2],[3,4],[5,6]]) numpy.savetxt("dtaa.csv",zip(SainaNehwal_replies,SainaNehwal_likes,SainaNehwal_retweets), delimiter=',', header="Replies,Likes,Retweets", comments="") #plt.xticks(x, labels) '''plt.xlabel('Number of hours ago tweet was posted') plt.ylabel('No of retweets') plt.show() #plt.title('Histogram depicting the relationship between popularity of media features and time') #plt.bar(x,intretweets2,color='yellow',label = "No of retweets") #plt.bar(x,intreplies1,color='blue',label = "No of replies") ''' plt.show() BSF_replies = [2,1,0,0,0,0] BSF_retweets = [24,2,2,3,3,3] BSF_likes = [57,8,10,12,10,11] plt.bar(BSF_likes,BSF_retweets, align='center',color='green',label="No of retweets") numpy.savetxt("dtaa1.csv",zip(BSF_replies,BSF_likes,BSF_retweets), delimiter=',', header="Replies,Likes,Retweets", comments="") #plt.xticks(x, labels) plt.xlabel('BSF likes') plt.ylabel('No of retweets') plt.show() '''plt.bar(hours,BSF_likes, align='center',color='green',label="No of likes") #plt.xticks(x, labels) plt.xlabel('BSF Number of hours ago tweet was posted') plt.ylabel('No of likes') plt.show() plt.bar(hours,BSF_replies, align='center',color='green',label="No of replies") #plt.xticks(x, labels) plt.xlabel('BSF Number of hours ago tweet was posted') plt.ylabel('No of replies') plt.show() ''' IITMadras_replies = [0,0,0,0,0,0] IITMadras_retweets = [2,1,0,2,0,1] IITMadras_likes = [20,1,0,7,1,6] numpy.savetxt("dtaa2.csv",zip(IITMadras_replies,IITMadras_likes,IITMadras_retweets), delimiter=',', header="Replies,Likes,Retweets", comments="") plt.bar(IITMadras_likes,IITMadras_retweets, align='center',color='green',label="No of retweets") #plt.xticks(x, labels) plt.xlabel('IITM likes') plt.ylabel('No of retweets') plt.show() '''ITMadras_replies = [0,0,0,0,0,0] IITMadras_retweets = [2,1,0,2,0,1] IITMadras_likes = [20,1,0,7,1,6] plt.bar(hours,IITMadras_replies, align='center',color='green',label="No of replies") #plt.xticks(x, labels) plt.xlabel('IITM Number of hours ago tweet was posted') plt.ylabel('No of replies') plt.show() ITMadras_replies = [0,0,0,0,0,0] IITMadras_retweets = [2,1,0,2,0,1] IITMadras_likes = [20,1,0,7,1,6] plt.bar(hours,IITMadras_likes, align='center',color='green',label="No of likes") #plt.xticks(x, labels) plt.xlabel('IITM Number of hours ago tweet was posted') plt.ylabel('No of likes') plt.show() Paytm_replies = [3,0,0,0,0,0] Paytm_retweets = [3,0,0,0,0,0] Paytm_likes = [13,1,0,0,1,4] plt.bar(hours,Paytm_retweets, align='center',color='green',label="No of retweets") #plt.xticks(x, labels) plt.xlabel('Paytm Number of hours ago tweet was posted') plt.ylabel('No of retweets') plt.show() plt.bar(hours,Paytm_likes, align='center',color='green',label="No of likes") #plt.xticks(x, labels) plt.xlabel('Paytm Number of hours ago tweet was posted') plt.ylabel('No of likes') plt.show() plt.bar(hours,Paytm_replies, align='center',color='green',label="No of replies") #plt.xticks(x, labels) plt.xlabel('Paytm Number of hours ago tweet was posted') plt.ylabel('No of replies') plt.show()''' OnePlus_replies = [10,0,2,1,0,4] OnePlus_retweets = [16,2,2,2,1,0] OnePlus_likes = [204,37,32,35,12,19] numpy.savetxt("dtaa3.csv",zip(OnePlus_replies,OnePlus_likes,OnePlus_retweets), delimiter=',', header="Replies,Likes,Retweets", comments="") plt.bar(OnePlus_likes,OnePlus_retweets, align='center',color='green',label="No of retweets") #plt.xticks(x, labels) plt.xlabel('Oneplus likes') plt.ylabel('No of retweets') plt.show() '''plt.bar(hours,OnePlus_replies, align='center',color='green',label="No of replies") #plt.xticks(x, labels) plt.xlabel('Oneplus Number of hours ago tweet was posted') plt.ylabel('No of replies') plt.show() plt.bar(hours,OnePlus_likes, align='center',color='green',label="No of likes") #plt.xticks(x, labels) plt.xlabel('Oneplus Number of hours ago tweet was posted') plt.ylabel('No of likes') plt.show() ''' TEDTalks_replies = [12,0,5,0,0,0] TEDTalks_retweets = [58,5,9,9,6,4] TEDTalks_likes = [115,8,23,15,9,9] plt.bar(TEDTalks_likes,TEDTalks_retweets, align='center',color='green',label="No of retweets") numpy.savetxt("dtaa3.csv",zip(TEDTalks_replies,TEDTalks_likes,TEDTalks_retweets), delimiter=',', header="Replies,Likes,Retweets", comments="") #plt.xticks(x, labels) plt.xlabel('Ted Number of likes') plt.ylabel('No of retweets') plt.show() '''plt.bar(hours,TEDTalks_replies, align='center',color='green',label="No of replies") #plt.xticks(x, labels) plt.xlabel('Ted Number of hours ago tweet was posted') plt.ylabel('No of replies') plt.show() plt.bar(hours,TEDTalks_likes, align='center',color='green',label="No of likes") #plt.xticks(x, labels) plt.xlabel('Ted Number of hours ago tweet was posted') plt.ylabel('No of likes') plt.show() SuhelSeth_replies = [2,0,0,0,1,0] SuhelSeth_retweets = [6,0,0,0,0,0] SuhelSeth_likes = [27,1,1,2,1,1] plt.bar(hours,SuhelSeth_retweets, align='center',color='green',label="No of retweets") #plt.xticks(x, labels) plt.xlabel('SS Number of hours ago tweet was posted') plt.ylabel('No of retweets') plt.show() plt.bar(hours,SuhelSeth_likes, align='center',color='green',label="No of likes") #plt.xticks(x, labels) plt.xlabel('SS Number of hours ago tweet was posted') plt.ylabel('No of likes') plt.show() plt.bar(hours,SuhelSeth_replies, align='center',color='green',label="No of replies") #plt.xticks(x, labels) plt.xlabel('SS Number of hours ago tweet was posted') plt.ylabel('No of replies') plt.show()''' KiranBedi_replies = [45,6,8,4,1,9] KiranBedi_retweets = [55,13,14,7,5,6] KiranBedi_likes = [336,69,88,60,57,46] plt.bar(KiranBedi_likes,KiranBedi_retweets, align='center',color='green',label="No of retweets") #plt.xticks(x, labels) plt.xlabel('KB likes') plt.ylabel('No of retweets') plt.show() '''plt.bar(hours,KiranBedi_replies, align='center',color='green',label="No of replies") #plt.xticks(x, labels) plt.xlabel('KB Number of hours ago tweet was posted') plt.ylabel('No of replies') plt.show() plt.bar(hours,KiranBedi_likes, align='center',color='green',label="No of likes") #plt.xticks(x, labels) plt.xlabel('KB Number of hours ago tweet was posted') plt.ylabel('No of likes') plt.show() ''' ROFLGandhi_replies = [34,2,5,7,3,0] ROFLGandhi_retweets = [244,37,57,80,43,56] ROFLGandhi_likes = [451,75,126,135,96,111] plt.bar(ROFLGandhi_likes,ROFLGandhi_retweets, align='center',color='green',label="No of retweets") #plt.xticks(x, labels) plt.xlabel('RG Number of likes') plt.ylabel('No of retweets') plt.show() '''plt.bar(hours,ROFLGandhi_replies, align='center',color='green',label="No of replies") #plt.xticks(x, labels) plt.xlabel('RG Number of hours ago tweet was posted') plt.ylabel('No of replies') plt.show() plt.bar(hours,ROFLGandhi_likes, align='center',color='green',label="No of likes") #plt.xticks(x, labels) plt.xlabel('RG Number of hours ago tweet was posted') plt.ylabel('No of likes') plt.show() ''' <file_sep>/scrapers/parser1.py import urllib2 import re from bs4 import BeautifulSoup from nltk.corpus import wordnet from nltk import word_tokenize import nltk from nltk.corpus import stopwords from nltk.stem import PorterStemmer from nltk.stem import WordNetLemmatizer from collections import Counter def parse(url): headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request(url, None, headers) data = urllib2.urlopen(req).read() data = BeautifulSoup(data) body = data.body all_texts = body.find_all("p") #print(all_texts[1]) #all_texts = all_texts[0] #print(all_texts) #print(len(all_texts)) text1 = "" for i in range(len(all_texts)): #print(all_texts[i]) all_links = all_texts[i].find_all("a") for links in all_links: cleanr = re.compile('<.*?>') all_texts[i] = re.sub(cleanr, '', str(all_texts[i])) cleanr = re.compile('<script>.*?</script>') all_texts[i] = re.sub(cleanr, '', str(all_texts[i])) #print(all_texts[i]) text1 = text1 + str(all_texts[i]) cleanr = re.compile('<.*?>') text1 = re.sub(cleanr, '', str(text1)) #print #print(text) #print(data) #print(data.title.string) #print(data.h1.string) h = '\d{1,4}' hs = re.findall(h,str(data.string)) #print(hs) #print(data.h2.string) #print(data.p.string) #print(data.body) data = data.body.get_text data = re.sub('<.*?>', '', str(data)) data = re.sub('(\\t*\\n*)*', ' ', str(data)) data = re.sub('(\\n*\\t*)*', '', str(data)) data = str(data).replace("\t","") data = data.replace("\n","") f = open("parser1.txt","w") f.write(data) f.close() #print(data) words = word_tokenize(data) #print(words) fin_list1 = [] for word in words: if wordnet.synsets(word): fin_list1.append(word) #print(fin_list1) lemmatizer = WordNetLemmatizer() fin_lits1 = [lemmatizer.lemmatize(token) for token in fin_list1] stop_words = set(stopwords.words('english')) fin_list = [] for word in fin_list1: if word not in stop_words: fin_list.append(word) text = " ".join(fin_list) return text1 ''' tf = [] tf = Counter(fin_list) total = 0 print(tf) for key,value in tf.iteritems(): total = total + value print(total) for key,value in tf.iteritems(): tf[key] = value/float(total) print(tf) total = 0 text = " ".join(fin_list) texts=Counter(text.split()) vocab_inv = {x[0] for x in texts.most_common()} vocab = {x: i for i,x in enumerate(vocab_inv)} #print(vocab) for key,value in vocab.iteritems(): total = total + value print(total) datas = nltk.pos_tag(fin_list) datas = nltk.ne_chunk(datas, binary=True) #print(datas) '''<file_sep>/scrapers/views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import datetime from django.shortcuts import render,render_to_response from django.template import loader,Context,RequestContext from django.contrib.auth.models import User from pymongo import MongoClient import requests import urllib2 import time,json import re import threading from bs4 import BeautifulSoup from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponseRedirect from django.contrib.auth import logout from crawler.models import RegistrationForm from elasticsearch import Elasticsearch from parser1 import parse import sys reload(sys) sys.setdefaultencoding('utf-8') url_pool = [("http://www.michigan.gov",3),("https://www.nrcan.gc.ca/",3),("http://dnr.maryland.gov/",3),("https://resourcegovernance.org/",3),("https://naturalresources.virginia.gov/",3),("https://naturalresources.wales/?lang=en",3)] client = MongoClient() es = Elasticsearch([{'host': 'localhost', 'port': 9200}]) db = client.test collection = db.docs class AllThreads(threading.Thread): print('crawl') def __init__(self,url,period): period = period threading.Thread.__init__(self) self.url = url def crawl(self,url_pool,period): if(urllib2.urlopen(self.url)): page = urllib2.urlopen(self.url) soup = BeautifulSoup(page) all_links = soup.find_all("a") for link in all_links: new_link = link.get("href") if new_link not in zip(*url_pool)[0]: if(re.findall('^/',str(new_link))): try: url_pool.append((self.url + str(new_link),1)) id = self.url print id #id = datetime.now() ok=True try: data = parse(self.url + str(new_link)) print "Success" #sleep(1000) except: print "Error" data = parse(self.url + str(new_link)) data = "Nothing Found" ok=False #db.docs.insert_one({"id": id,"data":data,"link":self.url + str(new_link)}) dict1 = {"link":self.url + str(new_link),"data":data} data = json.dumps(dict1, ensure_ascii=False) if ok: print "Inserting" es.index(index='sw', doc_type='people', id=id,body=json.loads(data)) #with open("doc.json", "w") as f: #json.dump(list(collection.find()), f) except urllib2.HTTPError as e: error_message = e.read() #print "error part1",error_message else: try: url_pool.append((new_link,1)) id = datetime.now() ok=True try: data = parse(str(new_link)) print "Success 2" #sleep(1000) except: print "Error2s" data = "Nothing Found" ok=False dict1 = {"link":str(new_link),"data":data} data = json.dumps(dict1, ensure_ascii=False) if ok: print "Inserting" es.index(index='sw', doc_type='people', id=id,body=json.loads(data)) except urllib2.HTTPError as e: error_message = e.read() #print "error part2",error_message time.sleep(period) self.crawl(url_pool,period) def get_the_links(url_pool): k = 0 for i in url_pool: if i[0] is not None: background = AllThreads(i[0],i[1]) background.start() background.crawl(url_pool,i[1]) background.join() k = k + 1 else: break return url_pool def crawldata(): global url_pool print "Crawling" url_pool = get_the_links(url_pool) @csrf_exempt def crawl_page(request): global url_pool #for index in es.indices.get('*'): # print index url_pool = get_the_links(url_pool) return HttpResponse("Exhausted links.") def start(request): return render( request, 'crawler/startindex.html', { 'title':'Demo Content', 'year': datetime.now().year, } ) def signup(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user(username=form.cleaned_data['username'],password=form.cleaned_data['<PASSWORD>'],email=form.cleaned_data['email']) return HttpResponseRedirect('/login') else: variables = RequestContext(request, { 'form': form, 'title':'Demo Content', 'year': datetime.now().year, }) return render_to_response('crawler/signup.html',variables) form = RegistrationForm() variables = RequestContext(request, { 'form': form, 'title':'Demo Content', 'year': datetime.now().year, }) return render_to_response('crawler/signup.html',variables) def login(request): return render( request, 'crawler/login.html', { 'title':'Demo Content', 'year': datetime.now().year, } ) def home(request): if not request.GET.get('query'): template = loader.get_template('crawler/home.html') variables = Context({ 'user': request.user , 'title':'Demo Content', 'year': datetime.now().year, }) output = template.render(variables) else : result = es.search(index="sw", body={"query": {"match": {'data': request.GET.get('query')}}}) #print result['hits']['hits'][0]["_source"] res=[] for rows in result['hits']['hits']: f_res={} f_res["link"]=rows["_source"]["link"] if len(rows["_source"]["data"]) >= 500: f_res["data"]=rows["_source"]["data"][:500]+"..." else: f_res["data"]=rows["_source"]["data"] res.append(f_res) if len(res)==0: f_res={} f_res["link"]="" f_res["data"]="No results were found for "+request.GET.get('query')+"" res.append(f_res) template = loader.get_template('crawler/search.html') variables = Context({ 'user': request.user , 'title':'Demo Content', 'year': datetime.now().year, 'results' : res }) output = template.render(variables) return HttpResponse(output) def logout_page(request): logout(request) return HttpResponseRedirect('/login')<file_sep>/modi.py~ import re str = open('modi.txt', 'r').read() #exampleString = "Jessica is 15 years old, and Daniel is 27 years old.Edward is 97 years old, and his grandfather, Oscar, is 102." replies = re.findall(r'\d{1,6} replies',str) str1 = ''.join(replies) replies1 = re.findall(r'\d{1,6}',str1) retweets = re.findall(r'\d{1,6} retweets',str) str2 = ''.join(retweets) retweets2 = re.findall(r'\d{1,6}',str2) days = re.findall(r'Aug\s\d{1,2}|Jul\s\d{1,2}',str) strday = ''.join(days) days1 = re.findall(r'\d{1,2}',strday) intdays = [int(numeric_string) for numeric_string in days1] likes = re.findall(r'\d{1,6} likes',str) str3 = ''.join(likes) likes2 = re.findall(r'\d{1,6}',str3) time = re.findall(r'\d{1,2} hours ago',str) str4 = ''.join(time) time2 = re.findall(r'\d{1,2}',str4) #print days #print days1 #print intdays intnewdays = [abs(11-i)*24 for i in intdays] for i in intdays: if((11-i) > 0): j = (11-i)*24 intnewdays.append(j) else: j = abs(11-31)*24+(31-i)*24 intnewdays.append(j) #print intnewdays intnewdays = intnewdays[0:5] #print intnewdays #time = re.findall(r'[A-Z][a-z]*\s\d{1,2}',str) #retweets = re.findall(r'[A-Z][a-z]*',exampleString) intreplies = [int(numeric_string) for numeric_string in replies1] intretweets = [int(numeric_string) for numeric_string in retweets2] intlikes = [int(numeric_string) for numeric_string in likes2] inttime = [int(numeric_string) for numeric_string in time2] inttime=inttime+intnewdays print inttime '''print(intreplies) print(intretweets) print(intlikes) print(inttime) ''' intreplies1 = intreplies[0:7] intretweets2=intretweets[0:7] intlikes2=intlikes[0:7] inttime1=inttime[0:7] print(len(intreplies1)) print(len(intretweets2)) print(len(intlikes2)) print(len(inttime1)) print(intreplies1) print(intretweets2) print(intlikes2) print(inttime1) import matplotlib.pyplot as plt x=inttime1 #labels=['','feb','mar','apr'] y=intlikes2 plt.bar(x,y, align='center',color='green',label="No of likes") #plt.xticks(x, labels) plt.xlabel('Number of hours ago tweet was posted') plt.ylabel('Features(Likes, Retweets, Replies') plt.title('Histogram depicting the relationship between popularity of media features and time') plt.bar(x,intretweets2,color='yellow',label = "No of retweets") plt.bar(x,intreplies1,color='blue',label = "No of replies") plt.show() import numpy #a = numpy.array([[1,2],[3,4],[5,6]]) numpy.savetxt("pc.csv",zip(inttime,intreplies,intlikes,intretweets), delimiter=',', header="Time,Replies,Likes,Retweets", comments="") <file_sep>/scrapers/twitterscraper-master/README.md # Synopsis A simple script to scrape for Tweets using the Python package requests to retrieve the content and Beautifullsoup4 to parse the retrieved content. # Motivation Twitter has provided [REST API's](https://dev.twitter.com/rest/public) which can be used by developers to access and read Twitter data. They have also provided a [Streaming API](https://dev.twitter.com/streaming/overview) which can be used to access Twitter Data in real-time. Most of the software written to access Twitter data provide a library which functions as a wrapper around Twitters Search and Streaming API's and therefore are limited by the limitations of the API's. With Twitter's Search API you can only sent 180 Requests every 15 minutes. With a maximum number of 100 tweets per Request this means you can mine for 4 x 180 x 100 = 72.000 tweets per hour. By using TwitterScraper you are not limited by this number but by your internet speed/bandwith and the number of instances of TwitterScraper you are willing to start. One of the bigger disadvantages of the Search API is that you can only access Tweets written in the **past 7 days**. This is a major bottleneck for anyone looking for older past data to make a model from. With TwitterScraper there is no such limitation. Per Tweet it scrapes the following information: + Username and Full Name + Tweet-id + Tweet text + Tweet timestamp + No. of likes + No. of replies + No. of retweets # Installation To install **twitterscraper**: ```python (sudo) pip install twitterscraper ``` or you can clone the repository and in the folder containing setup.py ```python python setup.py install ``` # The CLI You can use the command line application to get your tweets stored to JSON right away: `twitterscraper Trump --limit 100 --output=tweets.json` `twitterscraper Trump -l 100 -o tweets.json` Omit the limit to retrieve all tweets. You can at any time abort the scraping by pressing Ctrl+C, the scraped tweets will be stored safely in your JSON file. # The output file All of the retrieved Tweets are stored in the indicated output file. The contents of the output file will look like: ``` [{"fullname": "<NAME>", "id": "892397793071050752", "likes": "1", "replies": "0", "retweets": "0", "text": "Latest: Trump now at lowest Approval and highest Disapproval ratings yet. Oh, we're winning bigly here ...\n\nhttps://projects.fivethirtyeight.com/trump-approval-ratings/?ex_cid=rrpromo\u00a0\u2026", "timestamp": "2017-08-01T14:53:08", "user": "Rupert_Meehl"}, {"fullname": "<NAME>", "id": "892397794375327744", "likes": "0", "replies": "0", "retweets": "0", "text": "A former GOP Rep quoted this line, which pretty much sums up Donald Trump. https://twitter.com/davidfrum/status/863017301595107329\u00a0\u2026", "timestamp": "2017-08-01T14:53:08", "user": "barryshap"}, (...) ] ``` # Advanced Search You can use any advanced query twitter supports. Simply compile your query at <https://twitter.com/search-advanced>. After you compose your advanced search, copy the part of the URL between q= and the first subsequent &. For example, from the URL `https://twitter.com/search?l=&q=Trump%20near%3A%22Seattle%2C%20WA%22%20within%3A15mi%20since%3A2017-05-02%20until%3A2017-05-05&src=typd&lang=en` you need to copy the following part: `Trump%20near%3A%22Seattle%2C%20WA%22%20within%3A15mi%20since%3A2017-05-02%20until%3A2017-05-05` You can use the CLI with the advanced query, the same way as a simple query: + based on a daterange: ```twitterscraper Trump%20since%3A2017-01-03%20until%3A2017-01-04 -o tweets.json``` + based on a daterange and location: ```twitterscraper Trump%20near%3A"Seattle%2C%20WA"%20within%3A15mi%20since%3A2017-05-02%20until%3A2017-05-05 -o tweets.json``` + based on a specific author: ```twitterscraper Trump%20from%3AAlWest13 -o tweets.json``` # Code Example You can easily use TwitterScraper from within python: ```python from twitterscraper import query_tweets # All tweets matching either Trump or Clinton will be returned. You will get at # least 10 results within the minimal possible time/number of requests for tweet in query_tweets("Trump OR Clinton", 10)[:10]: print(tweet.user.encode('utf-8')) ``` You should get an output like this: ```text Tweet(user='@WiseFreeman', id='797020313569689601', timestamp='02:17 - 11. Nov. 2016', fullname='<NAME>', text="Chinese Internet Companies Are In Danger After Trump's Victory http://fb.me/5NfxcdTn9\xa0") Tweet(user='@TheRoseBushes', id='797020313099927552', timestamp='02:17 - 11. Nov. 2016', fullname='The Rose Bushes', text='Democrats Wonder If Bernie Sanders Could Have Beaten Trump http://ift.tt/2fHyWDL\xa0') Tweet(user='@TvPrefeito', id='797020312869240833', timestamp='02:17 - 11. Nov. 2016', fullname='TvPrefeito', text='Na Casa Branca, Trump diz que vai pedir conselhos a Obama http://tinyurl.com/z97ll3c\xa0pic.twitter.com/aJeAjrldnM') Tweet(user='@portlandor_agen', id='797020312655241217', timestamp='02:17 - 11. Nov. 2016', fullname='Portland Agent', text='Portland Police Say Anti-Trump Protest Is &#039;Riot&#039; #donald https://dragplus.com/post/id/38524480\xa0…') Tweet(user='@rpsmybb', id='797020312084905984', timestamp='02:17 - 11. Nov. 2016', fullname='<NAME>', text='Electoral College Electors: Electoral College Make Hillary Clinton President on December 19 - Подпишите петицию! http://fb.me/Rlv2qfWH\xa0') Tweet(user='@Shane_Conneely', id='797020312038703104', timestamp='02:17 - 11. Nov. 2016', fullname='<NAME>', text="#Trump's public works scheme has odd historical symmetries, ironically tea-party fear of big gov spending may be the only restraint on him") Tweet(user='@LavakyMohammed', id='797020311220785152', timestamp='02:17 - 11. Nov. 2016', fullname='<NAME>', text='Usa-Un extrémiste Sioniste , milicien de Soros et anti Trump ! pic.twitter.com/PTDag2eQbO') Tweet(user='@Isethoriginal', id='797020310641983489', timestamp='02:17 - 11. Nov. 2016', fullname='<NAME>', text='Just curious: If SJW are convinced Trump is a dictator, will they still be eager to repeal the 2nd amendment? Or will they buy mass ammo?') Tweet(user='@italianfood_age', id='797020310134525952', timestamp='02:17 - 11. Nov. 2016', fullname='Italian Food agent', text='Portland Police Say Anti-Trump Protest Is &#039;Riot&#039; #donald https://dragplus.com/post/id/38524480\xa0…') Tweet(user='@laurac2605', id='797020310113570817', timestamp='02:17 - 11. Nov. 2016', fullname='<NAME>', text='Why Clinton’s identity politics backfired http://www.spiked-online.com/newsite/article/why-clintons-identity-politics-backfired-trump-election/18960#.WCWah68m09A.twitter\xa0… very interesting article') ``` # TO DO - Add caching potentially? Would be nice to be able to resume scraping if something goes wrong and have half of the data of a request cached or so. - Add an example of using a thread pool/asynchio for gathering more tweets in parallel. <file_sep>/scrapers/twitterscraper-master/twitterscraper/query.py import json import logging import random import sys from datetime import timedelta, date from multiprocessing.pool import Pool import requests from fake_useragent import UserAgent from twitterscraper.tweet import Tweet ua = UserAgent() HEADERS_LIST = [ua.chrome, ua.google, ua['google chrome'], ua.firefox, ua.ff] INIT_URL = "https://twitter.com/search?f=tweets&vertical=default&q={q}" RELOAD_URL = "https://twitter.com/i/search/timeline?f=tweets&vertical=" \ "default&include_available_features=1&include_entities=1&" \ "reset_error_state=false&src=typd&max_position={pos}&q={q}" def query_single_page(url, html_response=True, retry=3): """ Returns tweets from the given URL. :param url: The URL to get the tweets from :param html_response: False, if the HTML is embedded in a JSON :param retry: Number of retries if something goes wrong. :return: The list of tweets, the pos argument for getting the next page. """ headers = {'User-Agent': random.choice(HEADERS_LIST)} try: response = requests.get(url, headers=headers) if html_response: html = response.text else: json_resp = response.json() html = json_resp['items_html'] tweets = list(Tweet.from_html(html)) if not tweets: return [], None if not html_response: return tweets, json_resp['min_position'] return tweets, "TWEET-{}-{}".format(tweets[-1].id, tweets[0].id) except requests.exceptions.HTTPError as e: logging.exception('HTTPError {} while requesting "{}"'.format( e, url)) except requests.exceptions.ConnectionError as e: logging.exception('ConnectionError {} while requesting "{}"'.format( e, url)) except requests.exceptions.Timeout as e: logging.exception('TimeOut {} while requesting "{}"'.format( e, url)) if retry > 0: logging.info("Retrying...") return query_single_page(url, html_response, retry-1) logging.error("Giving up.") return [], None def query_tweets_once(query, limit=None, num_tweets=0): """ Queries twitter for all the tweets you want! It will load all pages it gets from twitter. However, twitter might out of a sudden stop serving new pages, in that case, use the `query_tweets` method. Note that this function catches the KeyboardInterrupt so it can return tweets on incomplete queries if the user decides to abort. :param query: Any advanced query you want to do! Compile it at https://twitter.com/search-advanced and just copy the query! :param limit: Scraping will be stopped when at least ``limit`` number of items are fetched. :param num_tweets: Number of tweets fetched outside this function. :return: A list of twitterscraper.Tweet objects. You will get at least ``limit`` number of items. """ logging.info("Querying {}".format(query)) query = query.replace(' ', '%20').replace("#", "%23").replace(":", "%3A") pos = None tweets = [] try: while True: new_tweets, pos = query_single_page( INIT_URL.format(q=query) if pos is None else RELOAD_URL.format(q=query, pos=pos), pos is None ) if len(new_tweets) == 0: logging.info("Got {} tweets for {}.".format( len(tweets), query)) return tweets logging.info("Got {} tweets ({} new).".format( len(tweets) + num_tweets, len(new_tweets))) tweets += new_tweets if limit is not None and len(tweets) + num_tweets >= limit: return tweets except KeyboardInterrupt: logging.info("Program interrupted by user. Returning tweets gathered " "so far...") except BaseException: logging.exception("An unknown error occurred! Returning tweets " "gathered so far.") return tweets def eliminate_duplicates(iterable): """ Yields all unique elements of an iterable sorted. Elements are considered non unique if the equality comparison to another element is true. (In those cases, the set conversion isn't sufficient as it uses identity comparison.) """ class NoElement: pass prev_elem = NoElement for elem in sorted(iterable): if prev_elem is NoElement: prev_elem = elem yield elem continue if prev_elem != elem: prev_elem = elem yield elem def query_tweets(query, limit=None): tweets = [] iteration = 1 while limit is None or len(tweets) < limit: logging.info("Running iteration no {}, query is {}".format( iteration, repr(query))) new_tweets = query_tweets_once(query, limit, len(tweets)) tweets.extend(new_tweets) if not new_tweets: break mindate = min(map(lambda tweet: tweet.timestamp, new_tweets)).date() maxdate = max(map(lambda tweet: tweet.timestamp, new_tweets)).date() logging.info("Got tweets ranging from {} to {}".format( mindate.isoformat(), maxdate.isoformat())) # Add a day, twitter only searches until excluding that day and we dont # have complete results for that one yet. However, we cannot limit the # search to less than one day: if all results are from the same day, we # want to continue searching further into the past: either there are no # further results or twitter stopped serving them and there's nothing # we can do. if mindate != maxdate: mindate += timedelta(days=1) # Twitter will always choose the more restrictive until: query += ' until:' + mindate.isoformat() iteration += 1 # Eliminate duplicates return list(eliminate_duplicates(tweets)) def query_all_tweets(query): """ Queries *all* tweets in the history of twitter for the given query. This will run in parallel for each ~10 days. :param query: A twitter advanced search query. :return: A list of tweets. """ year = 2006 month = 3 limits = [] while date(year=year, month=month, day=1) < date.today(): nextmonth = month + 1 if month < 12 else 1 nextyear = year + 1 if nextmonth == 1 else year limits.append( (date(year=year, month=month, day=1), date(year=year, month=month, day=10)) ) limits.append( (date(year=year, month=month, day=10), date(year=year, month=month, day=20)) ) limits.append( (date(year=year, month=month, day=20), date(year=nextyear, month=nextmonth, day=1)) ) year, month = nextyear, nextmonth queries = ['{} since:{} until:{}'.format(query, since, until) for since, until in reversed(limits)] pool = Pool(20) all_tweets = [] try: for new_tweets in pool.imap_unordered(query_tweets_once, queries): all_tweets.extend(new_tweets) logging.info("Got {} tweets ({} new).".format( len(all_tweets), len(new_tweets))) except KeyboardInterrupt: logging.info("Program interrupted by user. Returning all tweets " "gathered so far.") return sorted(all_tweets) <file_sep>/scrapers/twitterscraper-master/README.rst Synopsis ======== A simple script to scrape for Tweets using the Python package requests to retrieve the content and Beautifullsoup4 to parse the retrieved content. Motivation ========== Twitter has provided `REST API's <https://dev.twitter.com/rest/public>`__ which can be used by developers to access and read Twitter data. They have also provided a `Streaming API <https://dev.twitter.com/streaming/overview>`__ which can be used to access Twitter Data in real-time. Most of the software written to access Twitter data provide a library which functions as a wrapper around Twitters Search and Streaming API's and therefore are limited by the limitations of the API's. With Twitter's Search API you can only sent 180 Requests every 15 minutes. With a maximum number of 100 tweets per Request this means you can mine for 4 x 180 x 100 = 72.000 tweets per hour. By using TwitterScraper you are not limited by this number but by your internet speed/bandwith and the number of instances of TwitterScraper you are willing to start. One of the bigger disadvantages of the Search API is that you can only access Tweets written in the **past 7 days**. This is a major bottleneck for anyone looking for older past data to make a model from. With TwitterScraper there is no such limitation. Installation ============ To install **twitterscraper**: .. code:: python (sudo) pip install twitterscraper or you can clone the repository and in the folder containing setup.py .. code:: python python setup.py install The CLI ======= You can use the command line application to get your tweets stored to JSON right away: ``twitterscraper "Trump OR Clinton" --limit 100 --output=tweets.json`` Omit the limit to retrieve all tweets. You can at any time abort the scraping by pressing Ctrl+C, the scraped tweets will be stored safely in your JSON file. Code Example ============ You can easily use TwitterScraper from within python: .. code:: python from twitterscraper import query_tweets # All tweets matching either Trump or Clinton will be returned. You will get at # least 10 results within the minimal possible time/number of requests for tweet in query_tweets("Trump OR Clinton", 10)[:10]: print(tweet.user.encode('utf-8')) You can use any advanced query twitter supports. Simply compile your query at https://twitter.com/search-advanced. You should get an output like this: .. code:: text Tweet(user='@WiseFreeman', id='797020313569689601', timestamp='02:17 - 11. Nov. 2016', fullname='Solomon Freeman', text="Chinese Internet Companies Are In Danger After Trump's Victory http://fb.me/5NfxcdTn9\xa0") Tweet(user='@TheRoseBushes', id='797020313099927552', timestamp='02:17 - 11. Nov. 2016', fullname='The Rose Bushes', text='Democrats Wonder If Bernie Sanders Could Have Beaten Trump http://ift.tt/2fHyWDL\xa0') Tweet(user='@TvPrefeito', id='797020312869240833', timestamp='02:17 - 11. Nov. 2016', fullname='TvPrefeito', text='Na Casa Branca, Trump diz que vai pedir conselhos a Obama http://tinyurl.com/z97ll3c\xa0pic.twitter.com/aJeAjrldnM') Tweet(user='@portlandor_agen', id='797020312655241217', timestamp='02:17 - 11. Nov. 2016', fullname='Portland Agent', text='Portland Police Say Anti-Trump Protest Is &#039;Riot&#039; #donald https://dragplus.com/post/id/38524480\xa0…') Tweet(user='@rpsmybb', id='797020312084905984', timestamp='02:17 - 11. Nov. 2016', fullname='<NAME>', text='Electoral College Electors: Electoral College Make Hillary Clinton President on December 19 - Подпишите петицию! http://fb.me/Rlv2qfWH\xa0') Tweet(user='@Shane_Conneely', id='797020312038703104', timestamp='02:17 - 11. Nov. 2016', fullname='<NAME>', text="#Trump's public works scheme has odd historical symmetries, ironically tea-party fear of big gov spending may be the only restraint on him") Tweet(user='@LavakyMohammed', id='797020311220785152', timestamp='02:17 - 11. Nov. 2016', fullname='<NAME>', text='Usa-Un extrémiste Sioniste , milicien de Soros et anti Trump ! pic.twitter.com/PTDag2eQbO') Tweet(user='@Isethoriginal', id='797020310641983489', timestamp='02:17 - 11. Nov. 2016', fullname='<NAME>', text='Just curious: If SJW are convinced Trump is a dictator, will they still be eager to repeal the 2nd amendment? Or will they buy mass ammo?') Tweet(user='@italianfood_age', id='797020310134525952', timestamp='02:17 - 11. Nov. 2016', fullname='Italian Food agent', text='Portland Police Say Anti-Trump Protest Is &#039;Riot&#039; #donald https://dragplus.com/post/id/38524480\xa0…') Tweet(user='@laurac2605', id='797020310113570817', timestamp='02:17 - 11. Nov. 2016', fullname='<NAME>', text='Why Clinton’s identity politics backfired http://www.spiked-online.com/newsite/article/why-clintons-identity-politics-backfired-trump-election/18960#.WCWah68m09A.twitter\xa0… very interesting article') TO DO ===== - Add caching potentially? Would be nice to be able to resume scraping if something goes wrong and have half of the data of a request cached or so. - Add an example of using a thread pool/asynchio for gathering more tweets in parallel. <file_sep>/scrapers/flipkart-scrapping-master/flipkart_spidetr.py import scrapy import urllib2 import urllib from scrapy.spiders import BaseSpider from scrapy.selector import Selector from scrapy.http.request import Request from scrapy.http.response import Response from scrapy import signals from scrapy.xlib.pydispatch import dispatcher import re import csv #start_urls = search_url #start_urls=['http://www.flipkart.com/rosra-c1-analog-watch-couple-men-women-boys-girls/p/itmef43d6hdnmv2q'] #hxs = Selector(response) #hxs.select(".//a[@class='fk-display-block']/text()").extract() class Flipkart(scrapy.Spider): search_q = raw_input("Enter what you want to search with quotation:") search_q= search_q.replace(" ", "+") search_url="http://www.flipkart.com/search?q="+search_q #print search_url name = "flipkart" allowed_domains = ['flipkart.com'] start_urls = [search_url] #def __init__(self): #super(Flipkart, self) #def spider_closed(self, spider): #pass fo=open("reviews_flipkart12.csv","w+") fo.write("Rating,date,Review\n") fo.close() def parse(self, response): #hxs = Selector(response) hxs=Selector(response) links = hxs.xpath(".//div[@class='pu-visual-section']/a/@href").extract() link="http://flipkart.com"+links[0] #print "\n The link to go is:\n\n" #print link #print "\n\n\n ^^^The link to go" request = scrapy.Request(link,callback=self.parse_review) #request.meta['item'] = item yield request def parse_review(self, response): hxs = Selector(response) #item = response.meta['item']Lmfkmvkfd ".//div[@class='subLine']/p[@class='subText']/a/@href" newlinks= hxs.xpath(".//div[@class='subLine']/p[@class='subText']/a/@href").extract() newlink="http://flipkart.com"+newlinks[0] #print newlink #print "\n\n\n\n" request = scrapy.Request(newlink,callback=self.parse_review2) yield request def parse_review2(self, response): hxs = Selector(response) review_elements=hxs.xpath(".//span[@class='review-text']").extract() review_rating=hxs.xpath(".//div[@class='line']/div[@class='fk-stars']/@title").extract() #date of posting can be found from next line review_date=hxs.xpath(".//div[@class='unit size1of5 section1']/div[@class='date line fk-font-small']/text()").extract() tmp1=0 for review_element in review_elements: review_element=review_element.replace("<br>", "") review_element=review_element.replace('<span class="review-text">', "") review_element=review_element.replace("</span>", "") review_element=review_element.replace("\n", "") review_element=review_element.replace(',', '","') #review_date=review_datex.replace("\n", "") #review_element=review_element.replace("\u2019", "") #review_element=unicode(review_element, errors='ignore') #print review_date #print tmp1 review_element=review_element.encode('utf-8') #type() #print review_element #print review_date[tmp1] #print "----------------------------------------------------" #with open('C:\Users\HP\Desktop\Skybits\\a\\flipkart\\flipkart\Extracted_Reviews\\reviews.csv', 'w') as f: # c = csv.writer(f) #writerow=review_rating[tmp1]+","+review_element+"\n" fo=open("reviews_flipkart12.csv","a") fo.write(review_rating[tmp1]+",") fo.write(review_date[tmp1].replace("\n", "")+",") fo.write(review_element) fo.write("\n") fo.close() #print review_element +","+ review_rating[tmp1]+"\n" tmp1=tmp1+1 next_page_link = hxs.xpath(".//a[@class='nav_bar_next_prev']/@href").extract() #next_page_link=next_prev_page[1] k=len(next_page_link)-1 #print "THE LINK TO NEXT PAGE IS:" next_page_go_link= "http://flipkart.com"+next_page_link[k] if next_page_go_link: # check if there is a next page at all yield Request(next_page_go_link, callback=self.parse_review2) #Flipkart()<file_sep>/scrapers/web.py # import libraries import urllib2 from bs4 import BeautifulSoup # specify the url print("Above modi"); quote_page = 'https://twitter.com/narendramodi' print("Below modi") # query the website and return the html to the variable 'page' page = urllib2.urlopen(quote_page) print("Below url") # parse the html using beautiful soap and store in variable `soup` soup = BeautifulSoup(page, 'html.parser') #soup.prettify() print("under") # Take out the <div> of name and get its value name_box = soup.findAll('div', attrs={'class': 'content'}) #name = name_box.text.strip() # strip() is used to remove starting and trailing for i in name_box: tweets = i.p.text print("------->"+ tweets) # print tweet tweet_details = i.div.text.strip() print(tweet_details) # print tweet details reply = i.findAll("span", {"class": "ProfileTweet-actionCount"}) reply2=reply[0].text print(reply2) # print no of reply on tweet retweet =reply[1].text print(retweet) # print no of reweets likes =reply[2].text <file_sep>/diff_tweets_single_person_daily_analysis/pand5.py import re str = open('pc5.txt', 'r').read() #exampleString = "Jessica is 15 years old, and Daniel is 27 years old.Edward is 97 years old, and his grandfather, Oscar, is 102." replies = re.findall(r'\d{1,6} replies',str) str1 = ''.join(replies) replies1 = re.findall(r'\d{1,6}',str1) retweets = re.findall(r'\d{1,6} retweets',str) str2 = ''.join(retweets) retweets2 = re.findall(r'\d{1,6}',str2) likes = re.findall(r'\d{1,6} likes',str) str3 = ''.join(likes) likes2 = re.findall(r'\d{1,6}',str3) time = re.findall(r'\d{1,2} hours ago',str) str4 = ''.join(time) time2 = re.findall(r'\d{1,2}',str4) #time = re.findall(r'[A-Z][a-z]*\s\d{1,2}',str) #retweets = re.findall(r'[A-Z][a-z]*',exampleString) intreplies = [int(numeric_string) for numeric_string in replies1] intretweets = [int(numeric_string) for numeric_string in retweets2] intlikes = [int(numeric_string) for numeric_string in likes2] inttime = [int(numeric_string) for numeric_string in time2] '''print(intreplies) print(intretweets) print(intlikes) ''' print(inttime) intreplies1 = intreplies[0:5] intretweets2=intretweets[0:5] intlikes2=intlikes[0:5] print(intreplies1) print(intretweets2) print(intlikes2) #print(red) '''/*list2 = [] for i in range(len(replies)): x = re.findall(r'\d{1,6}',replies[i]) t = int(x) list2.append(t) print list2 ''' ''' import matplotlib.pyplot as plt #plt.plot(inttime,intreplies1) plt.bar(inttime,intreplies,label="Example one") plt.show() ''' import matplotlib.pyplot as plt x=inttime #labels=['','feb','mar','apr'] y=intlikes2 plt.bar(x,y, align='center',color='green',label="No of likes") #plt.xticks(x, labels) plt.xlabel('Number of hours ago tweet was posted') plt.ylabel('Features(Likes, Retweets, Replies') plt.title('Histogram depicting the relationship between popularity of media features and time') plt.bar(x,intretweets2,color='yellow',label = "No of retweets") plt.bar(x,intreplies1,color='blue',label = "No of replies") plt.show() import pandas as pd import matplotlib.pyplot as plt import numpy as np ''' y = np.random.rand(10,4) y[:,0]= np.arange(10) df = pd.DataFrame(y, columns=["X", "A", "B", "C"]) ax = df.plot(x="X", y="A", kind="bar") df.plot(x="X", y="B", kind="bar", ax=ax, color="C2") df.plot(x="X", y="C", kind="bar", ax=ax, color="C3") plt.show() list = ['1' , '2', '3'] list2 = [] for i in range(len(list)): t = int(list[i]) list2.append(t) print list2 ''' <file_sep>/timeline_plotting/ranks3.py import matplotlib.pyplot as plt import numpy as np time = [60,52,16,60,12,5,60,24,24] replies = [0,357,0,0,0,7,20,1,69] retweets = [16,625,4,110,0,34,2000,14,62] likes = [15,1100,2,8,2,72,3100,16,59] ranks = [1,2,3,4,5,6,7,8,9] plt.bar(ranks,time, align='center',color='green',label="No of likes") plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() #plt.xticks(x, labels) plt.bar(ranks,replies,align = 'center',color='red') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() plt.bar(ranks,retweets,align = 'center',color = 'yellow') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() plt.bar(ranks,likes,align ='center',color = 'cyan') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() <file_sep>/scrapers/amazon-scrapping-master/amazoncomspider.py import scrapy import urllib2 import urllib from scrapy.spiders import BaseSpider from scrapy.selector import Selector from scrapy.http.request import Request from scrapy.http.response import Response from scrapy import signals from scrapy.xlib.pydispatch import dispatcher import re import csv #start_urls = search_url #start_urls=['http://www.flipkart.com/rosra-c1-analog-watch-couple-men-women-boys-girls/p/itmef43d6hdnmv2q'] #hxs = Selector(response) #hxs.select(".//a[@class='fk-display-block']/text()").extract() class amazoncom(scrapy.Spider): search_q = raw_input("Enter what you want to search with quotations:") search_q= search_q.replace(" ", "+") search_url="http://www.amazon.com/s/?field-keywords="+search_q print search_url name = "amazoncom" allowed_domains = ['amazon.com'] start_urls = [search_url] #def __init__(self): #super(Flipkart, self) #def spider_closed(self, spider): #pass fo=open("reviews_amazoncom.csv","w+") fo.write("Rating,Date,Review\n") fo.close() def parse(self, response): #hxs = Selector(response) hxs=Selector(response) links = hxs.xpath(".//a[@class='a-link-normal s-access-detail-page a-text-normal']/@href").extract() link=links[0] print "\n The link to go is:\n\n" print link print "\n\n\n ^^^The link to go" request = scrapy.Request(link,callback=self.parse_review) #-------------------------request.meta['item'] = item yield request def parse_review(self, response): hxs = Selector(response) #item = response.meta['item'] newlinks= hxs.xpath(".//div[@class='a-fixed-left-grid-col a-col-left']/a[@class='a-link-emphasis a-nowrap']/@href").extract() newlink=newlinks[0] print newlink request = scrapy.Request(newlink,callback=self.parse_review2) yield request def parse_review2(self, response): hxs = Selector(response) review_elements=hxs.xpath(".//span[@class='a-size-base review-text']").extract() review_rating=hxs.xpath(".//div[@class='a-section review']/div[@class='a-row']/a[@class='a-link-normal']/i/span/text()").extract() #--date of posting can be found from next line review_date=hxs.xpath(".//div[@class='a-section review']/div[@class='a-row']/span[@class='a-size-base a-color-secondary review-date']/text()").extract() #--review_date=hxs.xpath(".//div[@class='line']/div[@class='date']/text()").extract() tmp1=0 for review_element in review_elements: review_element=review_element.replace("<br>", "") review_element=review_element.replace('<span class="a-size-base review-text">', "") review_element=review_element.replace("</span>", "") review_element=review_element.replace("\n", "") #review_element=review_element.replace("\u2019", "") #review_element=unicode(review_element, errors='ignore') review_element=review_element.encode('utf-8') #type() #print tmp1 #print review_element #print review_rating[tmp1] #print "----------------------------------------------------" #with open('C:\Users\HP\Desktop\Skybits\\a\\flipkart\\flipkart\Extracted_Reviews\\reviews_amazoncom.csv', 'w') as f: # c = csv.writer(f) #writerow=review_rating[tmp1]+","+review_element+"\n" fo=open("reviews_amazoncom.csv","a") fo.write(review_rating[tmp1].replace("out of 5 stars", "")+",") fo.write((review_date[tmp1].replace("on", "")).replace("\n", "")+",") fo.write(review_element) fo.write("\n") tmp1=tmp1+1 next_page_link = hxs.xpath(".//ul[@class='a-pagination']/li[@class='a-last']/a/@href").extract() #next_page_link=next_prev_page[1] k=len(next_page_link)-1 #print "THE LINK TO NEXT PAGE IS:" next_page_go_link= "http://amazon.com"+next_page_link[k] if next_page_go_link: # check if there is a next page at all yield Request(next_page_go_link, callback=self.parse_review2) #Flipkart()<file_sep>/timeline_plotting/ranks.py import matplotlib.pyplot as plt import numpy as np time = [1,5,2,2,5,5,2,6,7,7,0.5,7] replies = [109,37,483,79,121,23000,672,409,416,405,42,32] retweets = [244,57,3200,155,254,15000,1800,810,71,8300,124,106] likes = [575,203,18000,328,1100,56000,1600,5600,460,28000,194,1100] ranks = [1,2,3,4,5,6,7,8,9,10,11,12] plt.bar(ranks,time, align='center',color='green',label="No of likes") plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() #plt.xticks(x, labels) plt.bar(ranks,replies,align = 'center',color='red') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() plt.bar(ranks,retweets,align = 'center',color = 'yellow') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() plt.bar(ranks,likes,align ='center',color = 'cyan') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() <file_sep>/timeline_plotting/ranks4.py import matplotlib.pyplot as plt import numpy as np time = [8,10,7,7,5,9,0,73,6,6,7,5,10,7,8,5,9,2,9,6,10] replies = [0,16,9,0,3,6,306,199,36,2,107,72,1,63,27,27,8,56,26,30,12] retweets = [0,43,2,0,75,306,391,158,95,18,125,207,83,1100,64,175,252,176,138,592,400] print len(time) print len(replies) print len(retweets) likes = [0,432,420,0,302,695,1200,1700,819,116,1100,1700,94,2000,798,599,765,780,577,1200,300] print len(likes) ranks = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21] plt.bar(ranks,time, align='center',color='green',label="No of likes") plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() #plt.xticks(x, labels) plt.bar(ranks,replies,align = 'center',color='red') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() plt.bar(ranks,retweets,align = 'center',color = 'yellow') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() plt.bar(ranks,likes,align ='center',color = 'cyan') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = Hours, Red = Replies, cyan = likes ,yellow = retweets') plt.show() <file_sep>/scrapers/twitterscraper-master/twitterscraper/tweet.py from datetime import datetime from bs4 import BeautifulSoup from coala_utils.decorators import generate_ordering @generate_ordering('timestamp', 'id', 'text', 'user', 'replies', 'retweets', 'likes') class Tweet: def __init__(self, user, id, timestamp, fullname, text, replies, retweets, likes): self.user = user self.id = id self.timestamp = timestamp self.fullname = fullname self.text = text self.replies = replies self.retweets = retweets self.likes = likes @classmethod def from_soup(cls, tweet): return cls( user=tweet.find('span', 'username').text[1:], id=tweet['data-item-id'], timestamp=datetime.utcfromtimestamp( int(tweet.find('span', '_timestamp')['data-time'])), fullname=tweet.find('strong', 'fullname').text, text=tweet.find('p', 'tweet-text').text or "", replies = tweet.find('div', 'ProfileTweet-action--reply').find('span', 'ProfileTweet-actionCountForPresentation').text or '0', retweets = tweet.find('div', 'ProfileTweet-action--retweet').find('span', 'ProfileTweet-actionCountForPresentation').text or '0', likes = tweet.find('div', 'ProfileTweet-action--favorite').find('span', 'ProfileTweet-actionCountForPresentation').text or '0' ) @classmethod def from_html(cls, html): soup = BeautifulSoup(html, "lxml") tweets = soup.find_all('li', 'js-stream-item') if tweets: for tweet in tweets: try: yield cls.from_soup(tweet) except AttributeError: pass # Incomplete info? Discard! <file_sep>/scrapers/wikiscrape.py # import libraries import urllib2 from bs4 import BeautifulSoup import re quote_page = 'https://en.wikipedia.org/wiki/Deep_Blue_%28chess_computer%29' page = urllib2.urlopen(quote_page).read() soup = BeautifulSoup(page) body = soup.body all_texts = body.find_all("p") for i in range(len(all_texts)): #print(all_texts[i]) #all_links = all_texts[i].find_all("th") for text in all_texts: cleanr = re.compile('<.*?>') all_texts[i] = re.sub(cleanr, '', str(all_texts[i])) cleanr = re.compile('<script>.*?</script>') all_texts[i] = re.sub(cleanr, '', str(all_texts[i])) print(all_texts[i]) <file_sep>/timeline_plotting/ranks2.py import matplotlib.pyplot as plt import numpy as np time = [2,6,11,11,5,7,100,12,10,120] replies = [2,12,25,43,3,16,123,44,1,19] retweets = [10,30,275,51,40,33,807,23,6,133] likes = [31,29,423,29,97,191,3400,18,31,481] ranks = [1,2,3,4,5,6,7,8,9,10] plt.bar(ranks,time, align='center',color='green',label="No of likes") plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = minutes, Red = Replies, cyan = likes ,yellow = retweets') plt.show() #plt.xticks(x, labels) plt.bar(ranks,replies,align = 'center',color='red') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = minutes, Red = Replies, cyan = likes ,yellow = retweets') plt.show() plt.bar(ranks,retweets,align = 'center',color = 'yellow') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = minutes, Red = Replies, cyan = likes ,yellow = retweets') plt.show() plt.bar(ranks,likes,align ='center',color = 'cyan') plt.xlabel('The number at which it appeared on timeline') plt.ylabel('Green = minutes, Red = Replies, cyan = likes ,yellow = retweets') plt.show()
17babbd98efea7605477e49c3c3673178381ec14
[ "Markdown", "Python", "Text", "reStructuredText" ]
27
Text
RecencyBias/Total_work_till_date
cb90fef04def2ae10c2e623c7e67a9fd62e0b679
f0dc822a016201e5ca3ce905fc252f23cbc1bf44
refs/heads/master
<repo_name>Wouterdek/pluckertree<file_sep>/tests/Benchmarks.cpp #include <gtest/gtest.h> #include <gmock/gmock.h> #include <iostream> #include <Pluckertree.h> #include <random> #include <fstream> #include <string> #include <thread> #include <mutex> #include "DataSetGenerator.h" using namespace testing; using namespace pluckertree; using namespace Eigen; const std::string output_path("/home/wouter/Documents/pluckertree_benchmarks/"); //auto lines = LoadFromFile("/home/wouter/Documents/sphere_lines.txt"); template<typename size_type> void parallel_for(size_type arr_size, std::function<void(size_type)> f) { auto threadCount = std::thread::hardware_concurrency(); size_type batchSize, batchRemainder; size_type batchRemainderBegin; if(arr_size < threadCount) { batchSize = 1; batchRemainder = 0; batchRemainderBegin = arr_size; threadCount = arr_size; } else { batchSize = arr_size / threadCount; batchRemainder = arr_size % threadCount; batchRemainderBegin = arr_size - batchRemainder; } std::vector<std::thread> threads {}; for(size_type i = 0; i < threadCount; ++i) { threads.emplace_back([&f](size_type begin, size_type end){ for(auto cur = begin; cur < end; ++cur) { f(cur); } }, i*batchSize, (i+1)*batchSize); } for(auto cur = batchRemainderBegin; cur < arr_size; ++cur) { f(cur); } for(auto& thread : threads) { thread.join(); } } TEST(Benchmarks, DISABLED_NearestNeighbour_Lines_Random) { std::random_device dev{}; bool isLogPlot = true; bool isSqrtPlot = false; std::string filename; std::vector<unsigned int> bench_line_counts; if(isLogPlot) { filename = output_path+"NearestNeighbour_Lines_Random_log.txt"; bench_line_counts = {100, 1000, 10000, 100000, 1000000}; } else if(isSqrtPlot) { filename = output_path+"NearestNeighbour_Lines_Random_sqrt.txt"; bench_line_counts = {40000, 90000, 160000, 250000, 360000}; } else { filename = output_path+"NearestNeighbour_Lines_Random.txt"; bench_line_counts = {100, 250000, 500000, 750000, 1000000}; } std::fstream out(filename, std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } for(int bench_type_i = 0; bench_type_i < bench_line_counts.size(); ++bench_type_i) { std::cout << "Testing bench type " << (bench_type_i+1) << " of " << bench_line_counts.size() << std::endl; out << "BENCH INFO" << std::endl; unsigned int line_count = bench_line_counts[bench_type_i]; unsigned int query_count = 100; float max_dist = 100; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "START BENCH" << std::endl; std::mutex mutex; parallel_for(query_count, std::function([&out, &mutex, &dev, max_dist, query_count, line_count](unsigned int query_i){ unsigned int query_seed, line_seed; { const std::lock_guard<std::mutex> l(mutex); query_seed = dev(); line_seed = dev(); } //Generate line, tree and query std::vector<LineWrapper> lines = GenerateRandomLines(line_seed, line_count, max_dist); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); auto query_point = GenerateRandomPoints(query_seed, 1, max_dist)[0]; //Perform query std::array<const LineWrapper *, 1> result{nullptr}; float result_dist = 1E99; auto nbResultsFound = tree.FindNeighbours(query_point, result.begin(), result.end(), result_dist); { const std::lock_guard<std::mutex> l(mutex); out << Diag::visited << ";" << Diag::minimizations << std::endl; } })); out.flush(); out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestHit_Lines_Random) { std::random_device dev{}; std::fstream out(output_path+"NearestHit_Lines_Random.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } //std::vector<unsigned int> bench_line_counts = {100, 250000, 500000, 750000, 1000000}; std::vector<unsigned int> bench_line_counts = {100, 1000, 10000, 100000, 1000000}; for(int bench_type_i = 0; bench_type_i < bench_line_counts.size(); ++bench_type_i) { std::cout << "Testing bench type " << (bench_type_i+1) << " of " << bench_line_counts.size() << std::endl; out << "BENCH INFO" << std::endl; unsigned int line_count = bench_line_counts[bench_type_i]; unsigned int query_count = 100; float max_dist = 100; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "START BENCH" << std::endl; std::mutex mutex; parallel_for(query_count, std::function([&out, &mutex, &dev, max_dist, query_count, line_count](unsigned int query_i){ unsigned int query_seed, line_seed; { const std::lock_guard<std::mutex> l(mutex); query_seed = dev(); line_seed = dev(); } //Generate line, tree, query std::vector<LineWrapper> lines = GenerateRandomLines(line_seed, line_count, max_dist); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); auto query_point = GenerateRandomPoints(query_seed, 1, max_dist)[0]; auto query_normal = GenerateRandomNormals(query_seed+1, 1)[0]; //Perform query std::array<const LineWrapper *, 1> result{nullptr}; float result_dist = 1E99; auto nbResultsFound = tree.FindNearestHits(query_point, query_normal, result.begin(), result.end(), result_dist); { const std::lock_guard<std::mutex> l(mutex); out << Diag::visited << ";" << Diag::minimizations << std::endl; } })); out.flush(); out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestNeighbour_LineSegments_Random) { std::random_device dev{}; std::fstream out(output_path+"NearestNeighbour_LineSegments_Random.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } //std::vector<unsigned int> bench_line_counts = {100, 250000, 500000, 750000, 1000000}; std::vector<unsigned int> bench_line_counts = {100, 1000, 10000, 100000, 1000000}; for(int bench_type_i = 0; bench_type_i < bench_line_counts.size(); ++bench_type_i) { std::cout << "Testing bench type " << (bench_type_i+1) << " of " << bench_line_counts.size() << std::endl; out << "BENCH INFO" << std::endl; unsigned int line_count = bench_line_counts[bench_type_i]; unsigned int query_count = 100; float max_dist = 100; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "START BENCH" << std::endl; std::mutex mutex; parallel_for(query_count, std::function([&out, &mutex, &dev, max_dist, query_count, line_count](unsigned int query_i){ unsigned int query_seed, line_seed; { const std::lock_guard<std::mutex> l(mutex); query_seed = dev(); line_seed = dev(); } //Generate line, tree, query auto lines = GenerateRandomLineSegments(line_seed, line_count, max_dist, -100, 100); auto tree = segments::TreeBuilder<LineSegmentWrapper, &LineSegmentWrapper::l>::Build(lines.begin(), lines.end()); auto query_point = GenerateRandomPoints(query_seed, 1, max_dist)[0]; //Perform query std::array<const LineSegmentWrapper *, 1> result{nullptr}; float result_dist = 1E99; auto nbResultsFound = tree.FindNeighbours(query_point, result.begin(), result.end(), result_dist); { const std::lock_guard<std::mutex> l(mutex); out << Diag::visited << ";" << Diag::minimizations << std::endl; } })); out.flush(); out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestHit_LineSegments_Random) { std::random_device dev{}; std::fstream out(output_path+"NearestHit_LineSegments_Random.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } //std::vector<unsigned int> bench_line_counts = {100, 250000, 500000, 750000, 1000000}; std::vector<unsigned int> bench_line_counts = {100, 1000, 10000, 100000, 1000000}; for(int bench_type_i = 0; bench_type_i < bench_line_counts.size(); ++bench_type_i) { std::cout << "Testing bench type " << (bench_type_i+1) << " of " << bench_line_counts.size() << std::endl; out << "BENCH INFO" << std::endl; unsigned int line_count = bench_line_counts[bench_type_i]; unsigned int query_count = 100; float max_dist = 100; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "START BENCH" << std::endl; std::mutex mutex; parallel_for(query_count, std::function([&out, &mutex, &dev, max_dist, query_count, line_count](unsigned int query_i){ unsigned int query_seed, line_seed; { const std::lock_guard<std::mutex> l(mutex); query_seed = dev(); line_seed = dev(); } //Generate line, tree, query auto lines = GenerateRandomLineSegments(line_seed, line_count, max_dist, -100, 100); auto tree = segments::TreeBuilder<LineSegmentWrapper, &LineSegmentWrapper::l>::Build(lines.begin(), lines.end()); auto query_point = GenerateRandomPoints(query_seed, 1, max_dist)[0]; auto query_normal = GenerateRandomNormals(query_seed+1, 1)[0]; //Perform query std::array<const LineSegmentWrapper *, 1> result{nullptr}; float result_dist = 1E99; auto nbResultsFound = tree.FindNearestHits(query_point, query_normal, result.begin(), result.end(), result_dist); { const std::lock_guard<std::mutex> l(mutex); out << Diag::visited << ";" << Diag::minimizations << std::endl; } })); out.flush(); out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestNeighbour_Short_LineSegments_Random) { std::random_device dev{}; std::fstream out(output_path+"NearestNeighbour_Short_LineSegments_Random.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } //std::vector<unsigned int> bench_line_counts = {100, 250000, 500000, 750000, 1000000}; //std::vector<unsigned int> bench_line_counts = {100, 1000, 10000, 100000, 1000000}; std::vector<unsigned int> bench_line_counts = {128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288}; for(int bench_type_i = 0; bench_type_i < bench_line_counts.size(); ++bench_type_i) { std::cout << "Testing bench type " << (bench_type_i+1) << " of " << bench_line_counts.size() << std::endl; out << "BENCH INFO" << std::endl; unsigned int line_count = bench_line_counts[bench_type_i]; unsigned int query_count = 100; float max_dist = 100; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "START BENCH" << std::endl; std::mutex mutex; parallel_for(query_count, std::function([&out, &mutex, &dev, max_dist, query_count, line_count](unsigned int query_i){ unsigned int query_seed, line_seed; { const std::lock_guard<std::mutex> l(mutex); query_seed = dev(); line_seed = dev(); } //Generate line, tree, query auto lines = GenerateRandomLineSegments(line_seed, line_count, max_dist, -100, 100); ModifyLineSegmentLength(lines, 0.1); auto tree = segments::TreeBuilder<LineSegmentWrapper, &LineSegmentWrapper::l>::Build(lines.begin(), lines.end()); auto query_point = GenerateRandomPoints(query_seed, 1, max_dist)[0]; //Perform query std::array<const LineSegmentWrapper *, 1> result{nullptr}; float result_dist = 1E99; auto nbResultsFound = tree.FindNeighbours(query_point, result.begin(), result.end(), result_dist); { const std::lock_guard<std::mutex> l(mutex); out << Diag::visited << ";" << Diag::minimizations << std::endl; } })); out.flush(); out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestNeighbour_Lines_SceneFile) { std::random_device dev{}; //"/media/wouter/Data2/Thesis/misc/sphere_lines.txt" std::string scene_filename = "/media/wouter/Data2/Thesis/misc/underwater_lines.txt"; std::string scene_name = "sphere"; //sphere, underwater std::string filename; filename = output_path+"NearestNeighbour_Lines_Scene_"+scene_name+".txt"; std::vector<unsigned int> bench_line_counts = {100, 1000, 10000, 100000, 1000000}; std::fstream out(filename, std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } std::vector<LineWrapper> all_lines = LoadFromFile(scene_filename); for(int bench_type_i = 0; bench_type_i < bench_line_counts.size(); ++bench_type_i) { std::cout << "Testing bench type " << (bench_type_i+1) << " of " << bench_line_counts.size() << std::endl; out << "BENCH INFO" << std::endl; unsigned int line_count = bench_line_counts[bench_type_i]; unsigned int query_count = 100; float max_dist = 5; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "START BENCH" << std::endl; std::mutex mutex; parallel_for(query_count, std::function([&out, &mutex, &dev, max_dist, query_count, &all_lines, line_count](unsigned int query_i){ unsigned int query_seed, line_seed; { const std::lock_guard<std::mutex> l(mutex); query_seed = dev(); line_seed = dev(); } //Generate line, tree and query std::vector<LineWrapper> lines = SampleRandomLines(all_lines, line_seed, line_count); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); auto query_point = GenerateRandomPoints(query_seed, 1, max_dist)[0]; //Perform query std::array<const LineWrapper *, 1> result{nullptr}; float result_dist = 1E99; auto nbResultsFound = tree.FindNeighbours(query_point, result.begin(), result.end(), result_dist); { const std::lock_guard<std::mutex> l(mutex); out << Diag::visited << ";" << Diag::minimizations << std::endl; } })); out.flush(); out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestNeighbour_Lines_Parallel) { std::random_device dev{}; std::fstream out(output_path+"NearestNeighbour_Lines_Parallel.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } //std::vector<unsigned int> bench_line_counts = {100, 250000, 500000, 750000, 1000000}; std::vector<unsigned int> bench_line_counts = {100, 1000, 10000, 100000, 1000000}; for(int bench_type_i = 0; bench_type_i < bench_line_counts.size(); ++bench_type_i) { std::cout << "Testing bench type " << (bench_type_i+1) << " of " << bench_line_counts.size() << std::endl; out << "BENCH INFO" << std::endl; unsigned int line_count = bench_line_counts[bench_type_i]; unsigned int query_count = 100; float max_dist = 100; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "START BENCH" << std::endl; std::mutex mutex; parallel_for(query_count, std::function([&out, &mutex, &dev, max_dist, query_count, line_count](unsigned int query_i){ unsigned int query_seed, line_seed; { const std::lock_guard<std::mutex> l(mutex); query_seed = dev(); line_seed = dev(); } //Generate line, tree, query std::default_random_engine rng{line_seed+1}; std::uniform_real_distribution<float> dist(0, 1); Vector3f direction(dist(rng), dist(rng), dist(rng)); direction.normalize(); std::vector<LineWrapper> lines = GenerateParallelLines(line_seed, line_count, max_dist, direction); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); auto query_point = GenerateRandomPoints(query_seed, 1, max_dist)[0]; //Perform query std::array<const LineWrapper *, 1> result{nullptr}; float result_dist = 1E99; auto nbResultsFound = tree.FindNeighbours(query_point, result.begin(), result.end(), result_dist); { const std::lock_guard<std::mutex> l(mutex); out << Diag::visited << ";" << Diag::minimizations << std::endl; } })); out.flush(); out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestNeighbour_Lines_EquiDistant) { std::random_device dev{}; std::fstream out(output_path+"NearestNeighbour_Lines_EquiDistant.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } //std::vector<unsigned int> bench_line_counts = {100, 250000, 500000, 750000, 1000000}; std::vector<unsigned int> bench_line_counts = {100, 1000, 10000, 100000, 1000000}; for(int bench_type_i = 0; bench_type_i < bench_line_counts.size(); ++bench_type_i) { std::cout << "Testing bench type " << (bench_type_i+1) << " of " << bench_line_counts.size() << std::endl; out << "BENCH INFO" << std::endl; unsigned int line_count = bench_line_counts[bench_type_i]; unsigned int query_count = 100; float max_dist = 100; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "START BENCH" << std::endl; std::mutex mutex; parallel_for(query_count, std::function([&out, &mutex, &dev, max_dist, query_count, line_count](unsigned int query_i){ unsigned int query_seed, line_seed; { const std::lock_guard<std::mutex> l(mutex); query_seed = dev(); line_seed = dev(); } //Generate lines and tree std::vector<LineWrapper> lines = GenerateEquiDistantLines(line_seed, line_count, max_dist); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); auto query_point = GenerateRandomPoints(query_seed, 1, max_dist)[0]; //Perform query std::array<const LineWrapper *, 1> result{nullptr}; float result_dist = 1E99; auto nbResultsFound = tree.FindNeighbours(query_point, result.begin(), result.end(), result_dist); { const std::lock_guard<std::mutex> l(mutex); out << Diag::visited << ";" << Diag::minimizations << std::endl; } })); out.flush(); out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestNeighbour_Lines_EqualMoment) { std::random_device dev{}; std::fstream out(output_path+"NearestNeighbour_Lines_EqualMoment.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } //std::vector<unsigned int> bench_line_counts = {100, 250000, 500000, 750000, 1000000}; std::vector<unsigned int> bench_line_counts = {100, 1000, 10000, 100000, 1000000}; for(int bench_type_i = 0; bench_type_i < bench_line_counts.size(); ++bench_type_i) { std::cout << "Testing bench type " << (bench_type_i+1) << " of " << bench_line_counts.size() << std::endl; out << "BENCH INFO" << std::endl; unsigned int line_count = bench_line_counts[bench_type_i]; unsigned int query_count = 100; float max_dist = 100; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "START BENCH" << std::endl; std::mutex mutex; parallel_for(query_count, std::function([&out, &mutex, &dev, max_dist, query_count, line_count](unsigned int query_i){ unsigned int query_seed, line_seed; { const std::lock_guard<std::mutex> l(mutex); query_seed = dev(); line_seed = dev(); } //Generate lines and tree std::default_random_engine rng{line_seed+1}; std::uniform_real_distribution<float> dist(0, 1); Vector3f moment(dist(rng), dist(rng), dist(rng)); moment.normalize(); moment *= dist(rng) * max_dist; std::vector<LineWrapper> lines = GenerateEqualMomentLines(line_seed, line_count, moment); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); auto query_point = GenerateRandomPoints(query_seed, 1, max_dist)[0]; //Perform query std::array<const LineWrapper *, 1> result{nullptr}; float result_dist = 1E99; auto nbResultsFound = tree.FindNeighbours(query_point, result.begin(), result.end(), result_dist); { const std::lock_guard<std::mutex> l(mutex); out << Diag::visited << ";" << Diag::minimizations << std::endl; } })); out.flush(); out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestNeighbour_LineSegments_VaryingLengths) { std::fstream out(output_path+"NearestNeighbour_LineSegments_VaryingLengths.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } unsigned int line_count = 100000; unsigned int query_seed, line_seed; { std::random_device dev{}; query_seed = dev(); line_seed = dev(); } // Generate lines float max_dist = 100; auto lines = GenerateRandomLineSegments(line_seed, line_count, max_dist, -100, 100); //Generate query points unsigned int query_count = 100; auto query_points = GenerateRandomPoints(query_seed, query_count, max_dist); std::vector<float> bench_lineseg_t_min = {-100, -75, -50, -25, -1}; std::vector<float> bench_lineseg_t_max = { 100, 75, 50, 25, 1}; for(int bench_type_i = 0; bench_type_i < bench_lineseg_t_min.size(); ++bench_type_i) { std::cout << "Testing bench type " << (bench_type_i+1) << " of " << bench_lineseg_t_min.size() << std::endl; out << "BENCH INFO" << std::endl; float t_min = bench_lineseg_t_min[bench_type_i]; float t_max = bench_lineseg_t_max[bench_type_i]; out << "Query generation seed: " << query_seed << std::endl; out << "Line generation seed: " << line_seed << std::endl; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "T min: " << t_min << std::endl; out << "T max: " << t_max << std::endl; out << "START BENCH" << std::endl; //Modifying segment lengths /*for(auto& s : lines) { s.l.t1 = t_min; s.l.t2 = t_max; }*/ ModifyLineSegmentLength(lines, t_max-t_min); //Generate lines and tree std::cout << "Generating tree\r"; auto tree = segments::TreeBuilder<LineSegmentWrapper, &LineSegmentWrapper::l>::Build(lines.begin(), lines.end()); //Perform queries out << "START DATA" << std::endl; std::cout << "Running queries \r"; std::mutex mutex; parallel_for(query_points.size(), std::function([&query_points, &tree, &out, &mutex](std::vector<Vector3f>::size_type query_i){ const auto& query = query_points[query_i]; std::array<const LineSegmentWrapper *, 1> result{nullptr}; float result_dist = 1E99; auto nbResultsFound = tree.FindNeighbours(query, result.begin(), result.end(), result_dist); { const std::lock_guard<std::mutex> l(mutex); out << Diag::visited << ";" << Diag::minimizations << std::endl; } })); std::cout << " \r"; out << "END DATA" << std::endl; out.flush(); out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestNeighbour_Lines_RequestSize) { std::fstream out(output_path+"NearestNeighbour_Lines_RequestSize.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } unsigned int line_count = 100000; unsigned int query_count = 100; unsigned int query_seed, line_seed; { std::random_device dev{}; query_seed = dev(); line_seed = dev(); } // Generate lines float max_dist = 100; auto lines = GenerateRandomLines(line_seed, line_count, max_dist); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); //Generate query points auto query_points = GenerateRandomPoints(query_seed, query_count, max_dist); std::vector<unsigned int> bench_request_sizes = {1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50}; for(int bench_type_i = 0; bench_type_i < bench_request_sizes.size(); ++bench_type_i) { std::cout << "Testing bench type " << (bench_type_i+1) << " of " << bench_request_sizes.size() << std::endl; out << "BENCH INFO" << std::endl; unsigned int request_size = bench_request_sizes[bench_type_i]; float max_dist = 100; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "Request size: " << request_size << std::endl; out << "START BENCH" << std::endl; out << "Query generation seed: " << query_seed << std::endl; out << "Line generation seed: " << line_seed << std::endl; //Perform queries out << "START DATA" << std::endl; std::cout << "Running queries \r"; std::mutex mutex; parallel_for(query_points.size(), std::function([request_size, &query_points, &tree, &out, &mutex](std::vector<Vector3f>::size_type query_i){ const auto& query = query_points[query_i]; std::vector<const LineWrapper *> result(request_size); float result_dist = 1E99; auto nbResultsFound = tree.FindNeighbours(query, result.begin(), result.end(), result_dist); { const std::lock_guard<std::mutex> l(mutex); out << Diag::visited << ";" << Diag::minimizations << std::endl; } })); std::cout << " \r"; out << "END DATA" << std::endl; out.flush(); out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, NearestNeighbour_Lines_Origin) { std::fstream out(output_path+"NearestNeighbour_Lines_Origin.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } unsigned int line_count = 100000; unsigned int iterations = 10; unsigned int query_count = 100; unsigned int query_seed, line_seed; { std::random_device dev{}; query_seed = dev(); line_seed = dev(); } // Generate lines float max_line_dist = 10; std::vector<std::vector<LineWrapper>> lineSets(iterations); for(unsigned int i = 0; i < iterations; ++i) { lineSets[i] = GenerateRandomLines(line_seed+i, line_count, max_line_dist); } std::vector<std::vector<LineWrapper>> translatedLinesSets = lineSets; //Generate query points float max_query_dist = 100; auto query_points = GenerateRandomPoints(query_seed, query_count, max_query_dist); std::vector<Vector3f> translatedQueryPoints = query_points; //Generate translation vectors std::vector<Vector3f> bench_translation_vectors { Vector3f(0, 0, 0), Vector3f(20, 0, 0), Vector3f(40, 0, 0), Vector3f(60, 0, 0), Vector3f(0, 0, 20), Vector3f(0, 0, 40), Vector3f(0, 0, 60), Vector3f(0, 60, 0), Vector3f(std::sqrt(20), std::sqrt(20), 0), }; for(int bench_type_i = 0; bench_type_i < bench_translation_vectors.size(); ++bench_type_i) { std::cout << "Testing bench type " << (bench_type_i+1) << " of " << bench_translation_vectors.size() << std::endl; out << "BENCH INFO" << std::endl; auto translation_vect = bench_translation_vectors[bench_type_i]; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum line distance: " << max_line_dist << std::endl; out << "Maximum query distance: " << max_query_dist << std::endl; out << "Translation vector: " << translation_vect.transpose() << std::endl; for(unsigned int it = 0; it < iterations; ++it) { for(unsigned int i = 0; i < line_count; ++i) { Vector3f curP = lineSets[it][i].l.d.cross(lineSets[it][i].l.m); Vector3f p1 = curP + translation_vect; Vector3f p2 = (curP + lineSets[it][i].l.d) + translation_vect; translatedLinesSets[it][i] = LineWrapper(Line::FromTwoPoints(p1, p2)); } } for(unsigned int i = 0; i < query_count; ++i) { translatedQueryPoints[i] = query_points[i] + translation_vect; } /*out << "START TREEDEPTH DATA" << std::endl; std::function<void(const TreeNode<LineWrapper, &LineWrapper::l>*, unsigned int)> visitor; visitor = [&out, &visitor](const TreeNode<LineWrapper, &LineWrapper::l>* curNode, unsigned int curDepth){ if(curNode == nullptr) { return; } out << curDepth << std::endl; visitor(curNode->children[0].get(), curDepth+1); visitor(curNode->children[1].get(), curDepth+1); }; for(const auto& sector : tree.sectors) { visitor(sector.rootNode.get(), 1); } out << "END TREEDEPTH DATA" << std::endl;*/ out << "START BENCH" << std::endl; out << "Query generation seed: " << query_seed << std::endl; out << "Line generation seed: " << line_seed << std::endl; //Perform queries out << "START DATA" << std::endl; std::cout << "Running queries \r"; for(unsigned int it = 0; it < iterations; ++it) { auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(translatedLinesSets[it].begin(), translatedLinesSets[it].end()); std::mutex mutex; parallel_for(translatedQueryPoints.size(), std::function([&translatedQueryPoints, &tree, &out, &mutex](std::vector<Vector3f>::size_type query_i){ const auto& query = translatedQueryPoints[query_i]; std::array<const LineWrapper *, 1> result {nullptr}; float result_dist = 1E99; auto nbResultsFound = tree.FindNeighbours(query, result.begin(), result.end(), result_dist); { const std::lock_guard<std::mutex> l(mutex); out << Diag::visited << ";" << Diag::minimizations << std::endl; } })); } std::cout << " \r"; out << "END DATA" << std::endl; out.flush(); out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestNeighbour_Lines_Dist_Histogram) { std::fstream out(output_path+"NearestNeighbour_Lines_Dist_Histogram.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } unsigned int line_count = 100000; unsigned int query_count = 100; float max_dist = 100; unsigned int query_seed, line_seed; { std::random_device dev{}; query_seed = dev(); line_seed = dev(); } auto lines = GenerateRandomLines(line_seed, line_count, max_dist); auto query_points = GenerateRandomPoints(query_seed, query_count, max_dist); std::vector<float> dists(lines.size()); for(const auto& q : query_points) { out << "BENCH INFO" << std::endl; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "Query generation seed: " << query_seed << std::endl; out << "Line generation seed: " << line_seed << std::endl; out << "START BENCH" << std::endl; parallel_for(lines.size(), std::function([&lines, q, &dists](std::vector<Vector3f>::size_type line_i){ const auto& l = lines[line_i].l; dists[line_i] = (q.cross(l.d) - l.m).norm(); })); for(float dist : dists) { out << dist << std::endl; } out << "END DATA" << std::endl; out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestNeighbour_Lines_Dist_Progress) { std::fstream out(output_path+"NearestNeighbour_Lines_Dist_Progress.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } unsigned int line_count = 100000; unsigned int query_count = 100; float max_dist = 100; unsigned int query_seed, line_seed; { std::random_device dev{}; query_seed = dev(); line_seed = dev(); } auto lines = GenerateRandomLines(line_seed, line_count, max_dist); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); auto query_points = GenerateRandomPoints(query_seed, query_count, max_dist); unsigned int query_i = 0; unsigned int time_i = 0; Diag::on_node_visited = std::function([&out, &query_i, &time_i](float best_so_far_dist, float cur_line_dist, float cur_node_mindist, int cur_depth) { out << query_i << ";" << time_i << ";" << best_so_far_dist << ';' << cur_line_dist << ";" << cur_node_mindist << ';' << cur_depth << std::endl; time_i++; }); out << "BENCH INFO" << std::endl; out << "Line count: " << line_count << std::endl; out << "Query count: " << query_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "Query generation seed: " << query_seed << std::endl; out << "Line generation seed: " << line_seed << std::endl; out << "START BENCH" << std::endl; //for(const auto& q : query_points) for(query_i = 0; query_i < query_points.size(); query_i++) { const auto& q = query_points[query_i]; std::cout << query_i << "/" << query_points.size() << std::endl; std::array<const LineWrapper *, 1> result{nullptr}; float result_dist = 1E99; tree.FindNeighbours(q, result.begin(), result.end(), result_dist); time_i = 0; } out << "END BENCH" << std::endl << std::endl; out.flush(); out.close(); Diag::reset(); } TEST(Benchmarks, DISABLED_NearestNeighbour_Lines_Dist_Tightness) { std::fstream out(output_path+"NearestNeighbour_Lines_Dist_Tightness.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } unsigned int line_count = 10000; unsigned int iterations = 1; float max_dist = 100; Diag::force_visit_all = true; unsigned int iter_i = 0; std::vector<float> min_bin_dist {}; Diag::on_node_enter = std::function([&min_bin_dist](float best_so_far_dist, float cur_node_mindist, int cur_depth) { min_bin_dist.push_back(cur_node_mindist); }); Diag::on_node_leave = std::function([&min_bin_dist](float best_so_far_dist, float cur_line_dist, float cur_node_mindist, int cur_depth) { min_bin_dist.pop_back(); }); Diag::on_node_visited = std::function([&out, &iter_i, &min_bin_dist](float best_so_far_dist, float cur_line_dist, float cur_node_mindist, int cur_depth) { for(int i = 0; i < min_bin_dist.size(); i++) { out << iter_i << ';' << cur_line_dist-min_bin_dist[i] << ';' << i << std::endl; } }); out << "BENCH INFO" << std::endl; out << "Line count: " << line_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "START BENCH" << std::endl; std::random_device dev{}; for(iter_i = 0; iter_i < iterations; ++iter_i) { unsigned int query_seed, line_seed; { query_seed = dev(); line_seed = dev(); } out << "Query generation seed: " << query_seed << std::endl; out << "Line generation seed: " << line_seed << std::endl; auto lines = GenerateRandomLines(line_seed, line_count, max_dist); //auto lines = LoadFromFile("/home/wouter/Documents/sphere_lines.txt"); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); auto query_point = GenerateRandomPoints(query_seed, 1, max_dist)[0]; out << "START DATA" << std::endl; std::array<const LineWrapper *, 1> result{nullptr}; float result_dist = 1E99; tree.FindNeighbours(query_point, result.begin(), result.end(), result_dist); out << "END DATA" << std::endl; } out << "END BENCH" << std::endl << std::endl; out.flush(); out.close(); Diag::reset(); } TEST(Benchmarks, DISABLED_NearestNeighbour_Lines_Random_SplitTypes) { std::fstream out(output_path+"NearestNeighbour_Lines_Random_SplitTypes.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } unsigned int line_count = 100000; { out << "BENCH INFO" << std::endl; unsigned int iteration_count = 10; float max_dist = 100; out << "Line count: " << line_count << std::endl; out << "Iteration count: " << iteration_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "START BENCH" << std::endl; for(int i = 0; i < iteration_count; ++i) { std::cout << "Iteration " << (i+1) << " of " << iteration_count << std::endl; unsigned int line_seed; { std::random_device dev{}; line_seed = dev(); } out << "Line generation seed: " << line_seed << std::endl; //Generate lines and tree std::cout << "Generating lines & tree\r"; std::vector<LineWrapper> lines = GenerateRandomLines(line_seed, line_count, max_dist); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); //Perform queries out << "START DATA" << std::endl; std::cout << "Running queries \r"; std::array<unsigned int, 3> moment_splits {0, 0, 0}; unsigned int directional_splits = 0; std::function<void(const TreeNode<LineWrapper, &LineWrapper::l>*)> visitor; visitor = std::function([&visitor, &moment_splits, &directional_splits](const TreeNode<LineWrapper, &LineWrapper::l>* node){ if(node == nullptr || (node->children[0] == nullptr || node->children[1] == nullptr)) { return; } if(node->type == NodeType::moment) { moment_splits[node->bound_component_idx]++; }else if(node->type == NodeType::direction) { directional_splits++; } visitor(node->children[0].get()); visitor(node->children[1].get()); }); for(const auto& sector : tree.sectors) { visitor(sector.rootNode.get()); } unsigned int total = moment_splits[0] + moment_splits[1] + moment_splits[2] + directional_splits; out << (float)moment_splits[0]/(float)total << ";" << (float)moment_splits[1]/(float)total << ";" << (float)moment_splits[2]/(float)total << ";" << (float)directional_splits/(float)total << std::endl; std::cout << " \r"; out << "END DATA" << std::endl; out.flush(); } out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestNeighbour_Lines_Random_SplitTypes_By_Level) { std::fstream out(output_path+"NearestNeighbour_Lines_Random_SplitTypes_By_Level.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } unsigned int line_count = 100000; { out << "BENCH INFO" << std::endl; unsigned int iteration_count = 1; float max_dist = 100; out << "Line count: " << line_count << std::endl; out << "Iteration count: " << iteration_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "START BENCH" << std::endl; for(int i = 0; i < iteration_count; ++i) { std::cout << "Iteration " << (i+1) << " of " << iteration_count << std::endl; unsigned int line_seed; { std::random_device dev{}; line_seed = dev(); } out << "Line generation seed: " << line_seed << std::endl; //Generate lines and tree std::cout << "Generating lines & tree\r"; //auto lines = LoadFromFile("/home/wouter/Documents/sphere_lines.txt"); std::vector<LineWrapper> lines = GenerateRandomLines(line_seed, line_count, max_dist); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); //Perform queries out << "START DATA" << std::endl; std::cout << "Running queries \r"; Eigen::Matrix<int, 4, 100> split_counts = Eigen::Matrix<int, 4, 100>::Zero(); // Rows are {phi, theta, radius, directional}, columns are levels std::function<void(const TreeNode<LineWrapper, &LineWrapper::l>*, int)> visitor; visitor = std::function([&visitor, &split_counts](const TreeNode<LineWrapper, &LineWrapper::l>* node, int level){ if(node == nullptr || (node->children[0] == nullptr || node->children[1] == nullptr)) { return; } if(node->type == NodeType::moment) { split_counts(node->bound_component_idx, level)++; }else if(node->type == NodeType::direction) { split_counts(3, level)++; } visitor(node->children[0].get(), level+1); visitor(node->children[1].get(), level+1); }); for(const auto& sector : tree.sectors) { visitor(sector.rootNode.get(), 0); } Eigen::Matrix<float, 4, 100> split_freqs; for(int level = 0; level < 100; ++level) { unsigned int total = split_counts.col(level).sum(); split_freqs.col(level) = split_counts.col(level).cast<float>() / (float)total; } for(int level = 0; level < 100; ++level) { for(int dim_i = 0; dim_i < 4; ++dim_i) { auto curVal = split_freqs(dim_i, level); curVal = std::isnan(curVal) ? 0 : curVal; out << curVal; if(dim_i < 3) { out << ";"; }else{ out << std::endl; } } } std::cout << " \r"; out << "END DATA" << std::endl; out.flush(); } out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } TEST(Benchmarks, DISABLED_NearestNeighbour_Lines_Random_Build_Variances) { std::fstream out(output_path+"NearestNeighbour_Lines_Random_Build_Variances.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } unsigned int line_count = 100000; { out << "BENCH INFO" << std::endl; unsigned int iteration_count = 1; float max_dist = 100; out << "Line count: " << line_count << std::endl; out << "Iteration count: " << iteration_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; Diag::on_build_variance_calculated = [&out](float m_phi_var, float m_gamma_var, float m_radius_var, float d_var){ out << m_phi_var << ";" << m_gamma_var << ";" << m_radius_var << ";" << d_var << std::endl; }; out << "START BENCH" << std::endl; for(int i = 0; i < iteration_count; ++i) { std::cout << "Iteration " << (i+1) << " of " << iteration_count << std::endl; unsigned int line_seed; { std::random_device dev{}; line_seed = dev(); } out << "Line generation seed: " << line_seed << std::endl; //Generate lines and tree std::cout << "Generating lines & tree\r"; std::vector<LineWrapper> lines = GenerateRandomLines(line_seed, line_count, max_dist); out << "START DATA" << std::endl; auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); out << "END DATA" << std::endl; out.flush(); } out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); Diag::reset(); } TEST(Benchmarks, DISABLED_NearestNeighbour_Lines_Random_Spreads) { std::fstream out(output_path+"NearestNeighbour_Lines_Random_Spreads.txt", std::fstream::out | std::fstream::app); if(out.fail()) { std::cerr << "Failed to open file" << std::endl; return; } unsigned int line_count = 1000000; { out << "BENCH INFO" << std::endl; unsigned int iteration_count = 10; float max_dist = 100; out << "Line count: " << line_count << std::endl; out << "Iteration count: " << iteration_count << std::endl; out << "Maximum distance: " << max_dist << std::endl; out << "START BENCH" << std::endl; unsigned int line_seed; { std::random_device dev{}; line_seed = dev(); } out << "Line generation seed: " << line_seed << std::endl; auto lines = LoadFromFile("/home/wouter/Documents/sphere_lines.txt"); for(auto& l : lines) { l.l.m.z() *= 2.0; } //std::vector<LineWrapper> lines = GenerateRandomLines(line_seed, line_count, max_dist); out << "START DATA" << std::endl; for(const auto& line : lines) { auto m = cart2spherical(line.l.m); out << m.x() << ";" << m.y() << ";" << m.z() << std::endl; } out << "END DATA" << std::endl; out << "END BENCH" << std::endl << std::endl; } out.flush(); out.close(); } <file_sep>/tests/Tree.cpp #include <gtest/gtest.h> #include <gmock/gmock.h> #include <iostream> #include <Pluckertree.h> #include <random> #include "DataSetGenerator.h" using namespace testing; using namespace pluckertree; using namespace Eigen; /* TEST(Tree, TestBuildTree_OneInEachSector) { std::vector<Line> lines { Line::FromPointAndDirection(Vector3f(), Vector3f()), Line::FromPointAndDirection(Vector3f(), Vector3f()), }; auto tree = pluckertree::TreeBuilder::Build(lines.begin(), lines.end()); } TEST(Tree, TestBuildTree_TopSector) { std::vector<Line> lines { Line::FromPointAndDirection(Vector3f(), Vector3f()), Line::FromPointAndDirection(Vector3f(), Vector3f()), }; auto tree = pluckertree::TreeBuilder::Build(lines.begin(), lines.end()); } TEST(Tree, TestBuildTree_XYSector) { std::vector<Line> lines { Line::FromPointAndDirection(Vector3f(), Vector3f()), Line::FromPointAndDirection(Vector3f(), Vector3f()), }; auto tree = pluckertree::TreeBuilder::Build(lines.begin(), lines.end()); } TEST(Tree, TestBuildTree_SubNodesInParent) { std::vector<Line> lines { Line::FromPointAndDirection(Vector3f(), Vector3f()), Line::FromPointAndDirection(Vector3f(), Vector3f()), }; auto tree = pluckertree::TreeBuilder::Build(lines.begin(), lines.end()); }*/ #include <chrono> TEST(Tree, DISABLED_TestFindNeighbours_1_Random) { for(int pass = 0; pass < 1; ++pass) { unsigned int line_count = 100000; unsigned int query_count = 100; std::random_device dev{}; unsigned int line_seed = dev(); std::cout << "Line generation seed: " << line_seed << std::endl; std::vector<LineWrapper> lines = GenerateRandomLines(line_seed, line_count, 100); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); unsigned int query_seed = dev(); std::cout << "Query generation seed: " << query_seed << std::endl; auto query_points = GenerateRandomPoints(query_seed, query_count, 100); std::array<const LineWrapper *, 1> result{nullptr}; int i = 0; for (const auto &query : query_points) { /*if (i < 8) { i++; continue; }*/ //if(i % 10 == 0) { std::cout << i << std::endl; } //auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); //std::cout << "i: " << i << ", " << std::ctime(&t) << std::endl; float result_dist = 1E99; auto nbResultsFound = tree.FindNeighbours(query, result.begin(), result.end(), result_dist); std::cout << "visited nodes: " << Diag::visited << std::endl; EXPECT_EQ(nbResultsFound, 1); auto smallestLineIt = std::min_element(lines.begin(), lines.end(), [query](const LineWrapper &l1, const LineWrapper &l2) { auto l1Norm = (query.cross(l1.l.d) - l1.l.m).squaredNorm(); auto l2Norm = (query.cross(l2.l.d) - l2.l.m).squaredNorm(); return l1Norm < l2Norm; }); Line &SmallestLine = smallestLineIt->l; Vector3f m_spher = cart2spherical(SmallestLine.m); std::vector<int> idx; int sectI = 0; //std::cout << Diag::minimizations << std::endl; /*for (const auto &sector: tree.sectors) { if (Eigen::AlignedBox<float, 3>(sector.bounds.m_start, sector.bounds.m_end).contains( cart2spherical(SmallestLine.m)) && sector.bounds.d_bound_1.dot(SmallestLine.d) >= 0 //greater or equal, or just greater? && sector.bounds.d_bound_2.dot(SmallestLine.d) >= 0) { idx.push_back(sectI); const auto *node = sector.rootNode.get(); Bounds b1 = sector.bounds; while (node != nullptr) { //Bounds b2 = sector.bounds; if(node->type == NodeType::moment) { b1.m_end[node->bound_component_idx] = node->m_component; //b2.m_start[sector.rootNode->bound_component_idx] = sector.rootNode->m_component; } else { b1.d_bound_1 = node->d_bound; //b1.d_bound_2 = bounds.d_bound_2; } if (Eigen::AlignedBox<float, 3>(b1.m_start, b1.m_end).contains(cart2spherical(SmallestLine.m)) && b1.d_bound_1.dot(SmallestLine.d) >= 0 //greater or equal, or just greater? && b1.d_bound_2.dot(SmallestLine.d) >= 0) { idx.push_back(0); node = node->children[0].get(); } else { idx.push_back(1); node = node->children[1].get(); } } break; } sectI++; }*/ if (SmallestLine != result[0]->l) { std::cout << std::endl; std::cout << "sect: "; for (int curI : idx) { std::cout << curI << " "; } std::cout << std::endl; std::cout << "Querypoint index: " << i << std::endl; std::cout << "Distance found: " << result_dist << std::endl; std::cout << "Actual smallest distance: " << (query.cross(SmallestLine.d) - SmallestLine.m).norm() << std::endl; EXPECT_EQ(SmallestLine, result[0]->l); } i++; } } } TEST(Tree, DISABLED_ShowMeTheGrid) { //dlb, dub, m_start, m_end Eigen::Vector3f q(1,0,0); Eigen::Vector3f dlb = Eigen::Vector3f(-1,0,0); Eigen::Vector3f dub = Eigen::Vector3f(0,-1,0); //top Eigen::Vector3f mlb(-M_PI, 0, 0); Eigen::Vector3f mub(M_PI, 0.785398185, 1); //left //Eigen::Vector3f mlb(M_PI/4, 0.785398185, 0); //Eigen::Vector3f mub(3*M_PI/4, 2.356194487, 1); //all //Eigen::Vector3f mlb(-M_PI, 0, 0); //Eigen::Vector3f mub(M_PI, M_PI, 1); //hemisphere //Eigen::Vector3f mlb(-M_PI, M_PI/2, 0); //Eigen::Vector3f mub(M_PI, M_PI, 1); std::string file = "/home/wouter/Desktop/pluckerdata/0"; pluckertree::show_me_the_grid(file, dlb, dub, mlb, mub, q); } TEST(Tree, DISABLED_TestFindNearestHit_Random) { for(int pass = 0; pass < 1; ++pass) { unsigned int line_count = 100; unsigned int query_count = 100; std::random_device dev{}; unsigned int line_seed = dev(); std::cout << "Line generation seed: " << line_seed << std::endl; std::vector<LineWrapper> lines = GenerateRandomLines(line_seed, line_count, 100); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); unsigned int query_seed = dev(); std::cout << "Query generation seed: " << query_seed << std::endl; auto query_points = GenerateRandomPoints(query_seed, query_count, 100); auto query_point_normals = GenerateRandomNormals(query_seed, query_count); std::array<const LineWrapper*, 1> result { nullptr }; int i = 0; for(unsigned int query_i = 0; query_i < query_points.size(); ++query_i) { const auto& query = query_points[query_i]; const auto& query_normal = query_point_normals[query_i]; //auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); //std::cout << "i: " << i << ", " << std::ctime(&t) << std::endl; float result_dist = 1E99; auto nbResultsFound = tree.FindNearestHits(query, query_normal, result.begin(), result.end(), result_dist); EXPECT_EQ(nbResultsFound, 1); auto smallestLineIt = std::min_element(lines.begin(), lines.end(), [query, query_normal](const LineWrapper& l1, const LineWrapper& l2){ auto distF = [](const Eigen::Vector3f& p, const Eigen::Vector3f& n, const Line& l){ Eigen::Vector3f l0 = (l.d.cross(l.m)); Eigen::Vector3f intersection = l0 + (l.d * (p - l0).dot(n)/(l.d.dot(n))); Eigen::Vector3f vect = intersection - p; return vect; }; auto l1Norm = distF(query, query_normal, l1.l).squaredNorm(); auto l2Norm = distF(query, query_normal, l2.l).squaredNorm(); return l1Norm < l2Norm; }); Line& SmallestLine = smallestLineIt->l; Vector3f m_spher = cart2spherical(SmallestLine.m); std::vector<int> idx; int sectI = 0; /*for (const auto &sector: tree.sectors) { if (Eigen::AlignedBox<float, 3>(sector.bounds.m_start, sector.bounds.m_end).contains( cart2spherical(SmallestLine.m)) && sector.bounds.d_bound_1.dot(SmallestLine.d) >= 0 //greater or equal, or just greater? && sector.bounds.d_bound_2.dot(SmallestLine.d) >= 0) { idx.push_back(sectI); const auto *node = sector.rootNode.get(); Bounds b1 = sector.bounds; while (node != nullptr) { //Bounds b2 = sector.bounds; if(node->type == NodeType::moment) { b1.m_end[node->bound_component_idx] = node->m_component; //b2.m_start[sector.rootNode->bound_component_idx] = sector.rootNode->m_component; } else { b1.d_bound_1 = node->d_bound; //b1.d_bound_2 = bounds.d_bound_2; } if (Eigen::AlignedBox<float, 3>(b1.m_start, b1.m_end).contains(cart2spherical(SmallestLine.m)) && b1.d_bound_1.dot(SmallestLine.d) >= 0 //greater or equal, or just greater? && b1.d_bound_2.dot(SmallestLine.d) >= 0) { idx.push_back(0); node = node->children[0].get(); } else { idx.push_back(1); node = node->children[1].get(); } } break; } sectI++; }*/ if(SmallestLine != result[0]->l) { std::cout << "actual smallest: " ; float smallest = 1E99; /*for(float curVal : TreeNode::results) { smallest = std::min(smallest, curVal); //std::cout << curVal << " "; }*/ std::cout << smallest << " "; //std::cout << "returned smallest: " << TreeNode::results.back() << std::endl; std::cout << std::endl; std::cout << "sect: " ; for(int curI : idx) { std::cout << curI << " "; } std::cout << std::endl; std::cout << "Querypoint index: " << i << std::endl; std::cout << "Distance found: " << result_dist << std::endl; std::cout << "Actual smallest distance: " << (query.cross(SmallestLine.d) - SmallestLine.m).norm() << std::endl; EXPECT_EQ(SmallestLine, result[0]->l); } i++; } } } unsigned int CountNodes(const std::unique_ptr<TreeNode<LineWrapper, &LineWrapper::l>>& n) { if(n == nullptr) { return 0; } auto c1 = CountNodes(n->children[0]); auto c2 = CountNodes(n->children[1]); return 1 + c1 + c2; }; TEST(Tree, DISABLED_TreeSize_Random) { for(int pass = 0; pass < 100; ++pass) { unsigned int line_count = 100000; std::random_device dev{}; unsigned int line_seed = dev(); std::vector<LineWrapper> lines = GenerateRandomLines(line_seed, line_count, 100); auto tree = TreeBuilder<LineWrapper, &LineWrapper::l>::Build(lines.begin(), lines.end()); unsigned int nodes = 0; for(const auto& sector : tree.sectors) { nodes += CountNodes(sector.rootNode); } if(tree.size() != line_count || tree.size() != nodes) { std::cout << "Line generation seed: " << line_seed << std::endl; } EXPECT_EQ(tree.size(), line_count); EXPECT_EQ(tree.size(), nodes); } } <file_sep>/tests/DataSetGenerator.h #pragma once #include <Pluckertree.h> #include <PluckertreeSegments.h> #include <Eigen/Dense> #include <random> using Line = pluckertree::Line; using LineSegment = pluckertree::segments::LineSegment; using Eigen::Vector3f; struct LineWrapper { Line l; explicit LineWrapper(Line line) : l(std::move(line)) {} }; struct LineSegmentWrapper { LineSegment l; explicit LineSegmentWrapper(LineSegment line) : l(std::move(line)) {} }; std::vector<LineWrapper> LoadFromFile(const std::string& filename); std::vector<LineWrapper> GenerateRandomLines(unsigned int seed, unsigned int lineCount, float maxDist); std::vector<LineWrapper> SampleRandomLines(const std::vector<LineWrapper>& all_lines, unsigned int seed, unsigned int lineCount); std::vector<LineWrapper> GenerateParallelLines(unsigned int seed, unsigned int lineCount, float maxDist, const Vector3f& direction); std::vector<LineWrapper> GenerateEquiDistantLines(unsigned int seed, unsigned int lineCount, float maxDist); //Equidistant from center std::vector<LineWrapper> GenerateEqualMomentLines(unsigned int seed, unsigned int lineCount, const Vector3f& moment); std::vector<LineSegmentWrapper> GenerateRandomLineSegments(unsigned int seed, unsigned int lineCount, float maxDist, float minT, float maxT); void ModifyLineSegmentLength(std::vector<LineSegmentWrapper>& l, float length); std::vector<Vector3f> GenerateRandomPoints(unsigned int seed, unsigned int pointCount, float maxDist); std::vector<Vector3f> GenerateRandomNormals(unsigned int seed, unsigned int normalCount);<file_sep>/src/CMakeLists.txt # Installation instructions #install(TARGETS my_library DESTINATION "${main_lib_dest}") #install(FILES ${header} DESTINATION "${include_dest}") file(GLOB_RECURSE PLUCKERTREE_SRC "*.h" "*.cpp" ) add_library(pluckertree ${PLUCKERTREE_SRC}) target_include_directories(pluckertree PRIVATE ${PLUCKERTREE_SOURCE_DIR}/src) target_include_directories(pluckertree PRIVATE ${PLUCKERTREE_SOURCE_DIR}/include) target_include_directories(pluckertree PRIVATE ${PLUCKERTREE_SOURCE_DIR}/dependencies/LBFGSpp/include) find_package(Eigen3 REQUIRED NO_MODULE) target_link_libraries(pluckertree PRIVATE Eigen3::Eigen nlopt)<file_sep>/tests/CMakeLists.txt enable_testing() file(GLOB_RECURSE tests_SRC "*.h" "*.cpp" ) ### GOOGLE TEST if(NOT EXISTS "${PLUCKERTREE_SOURCE_DIR}/dependencies/googletest/CMakeLists.txt") message(FATAL_ERROR "The submodules were not downloaded! GIT_SUBMODULE was turned off or failed. Please update submodules and try again.") endif() set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) add_subdirectory("${PLUCKERTREE_SOURCE_DIR}/dependencies/googletest/" "dependencies/googletest/") # Keeps the cache cleaner mark_as_advanced( BUILD_GMOCK BUILD_GTEST BUILD_SHARED_LIBS gmock_build_tests gtest_build_samples gtest_build_tests gtest_disable_pthreads gtest_force_shared_crt gtest_hide_internal_symbols ) set_target_properties(gtest PROPERTIES FOLDER dependencies) set_target_properties(gtest_main PROPERTIES FOLDER dependencies) set_target_properties(gmock PROPERTIES FOLDER dependencies) set_target_properties(gmock_main PROPERTIES FOLDER dependencies) ### find_package(Eigen3 REQUIRED NO_MODULE) #find_package(Boost 1.69 REQUIRED COMPONENTS fiber) #find_package(TBB CONFIG REQUIRED) add_executable(tests ${tests_SRC}) target_include_directories(tests PRIVATE ${PLUCKERTREE_SOURCE_DIR}/include) target_include_directories(tests PRIVATE ${PLUCKERTREE_SOURCE_DIR}/src) target_link_libraries (tests PRIVATE gmock gtest gtest_main pluckertree Eigen3::Eigen) #find_package(GTest MODULE REQUIRED) #gtest_add_tests(TARGET tests tests_SRC) #gtest_discover_tests(tests) <file_sep>/tests/LineSegments.cpp #include <gtest/gtest.h> #include <gmock/gmock.h> #include <PluckertreeSegments.h> #include <iostream> #include <random> #include "DataSetGenerator.h" using namespace testing; using namespace Eigen; std::vector<int> FindSegment(const pluckertree::segments::TreeNode<LineSegmentWrapper, &LineSegmentWrapper::l>* node, const pluckertree::segments::Bounds& parentBounds, const LineSegment& smallestLine) { if (node == nullptr) { return {}; }else if(node->content.l == smallestLine) { return {0xFACE0FF}; } std::vector<int> idx {}; std::array<pluckertree::segments::Bounds, 2> childBounds {}; for(int i = 0; i < 2; ++i) { childBounds[i] = parentBounds; if (node->type == pluckertree::segments::NodeType::moment) { if (i == 0) { childBounds[0].m_end[node->bound_component_idx] = node->m_component; } else { childBounds[1].m_start[node->bound_component_idx] = node->m_component; } } else if (node->type == pluckertree::segments::NodeType::direction) { if (i == 0) { childBounds[i].d_bound_1 = node->d_bound; //childBounds[i].d_bound_2 = curBounds.d_bound_2; } else { //childBounds[i].d_bound_1 = curBounds.d_bound_1; childBounds[i].d_bound_2 = -node->d_bound; } } else if (node->type == pluckertree::segments::NodeType::t) { if (i == 0) { childBounds[i].t1Min = node->c1t1; childBounds[i].t2Max = node->c1t2; } else { childBounds[i].t1Min = node->c2t1; childBounds[i].t2Max = node->c2t2; } } } std::vector<int> subIdx; if (node->type == pluckertree::segments::NodeType::t) { auto c1Idx = FindSegment(node->children[0].get(), childBounds[0], smallestLine); if(c1Idx.size() > 0 && c1Idx[c1Idx.size()-1] == 0xFACE0FF) { idx.push_back(0); subIdx = c1Idx; }else{ auto c2Idx = FindSegment(node->children[1].get(), childBounds[1], smallestLine); if(c2Idx.size() > 0 && c2Idx[c2Idx.size()-1] == 0xFACE0FF) { idx.push_back(1); subIdx = c2Idx; } } } else { if (Eigen::AlignedBox<float, 3>(childBounds[0].m_start, childBounds[0].m_end).contains( cart2spherical(smallestLine.l.m)) && childBounds[0].d_bound_1.dot(smallestLine.l.d) >= 0 //greater or equal, or just greater? && childBounds[0].d_bound_2.dot(smallestLine.l.d) >= 0) { idx.push_back(0); subIdx = FindSegment(node->children[0].get(), childBounds[0], smallestLine); } else { idx.push_back(1); subIdx = FindSegment(node->children[1].get(), childBounds[1], smallestLine); } } for (int curIdx : subIdx) { idx.push_back(curIdx); } return idx; } std::vector<int> FindSegment(const pluckertree::segments::Tree<LineSegmentWrapper, &LineSegmentWrapper::l>& tree, const LineSegment& smallestLine) { std::vector<int> idx; int sectI = 0; for (const auto &sector: tree.sectors) { if (Eigen::AlignedBox<float, 3>(sector.bounds.m_start, sector.bounds.m_end).contains( cart2spherical(smallestLine.l.m)) && sector.bounds.d_bound_1.dot(smallestLine.l.d) >= 0 //greater or equal, or just greater? && sector.bounds.d_bound_2.dot(smallestLine.l.d) >= 0) { idx.push_back(sectI); const auto *node = sector.rootNode.get(); pluckertree::segments::Bounds curBounds = sector.bounds; auto result = FindSegment(node, curBounds, smallestLine); for(int curIdx : result) { idx.push_back(curIdx); } break; } sectI++; } return idx; } TEST(Tree, DISABLED_TestLineSegmentsInBounds) { for(int pass = 0; pass < 100; ++pass) { unsigned int line_count = 100; std::random_device dev{}; unsigned int line_seed = dev(); std::cout << "Line segment generation seed: " << line_seed << std::endl; auto lines = GenerateRandomLineSegments(line_seed, line_count, 100, -100, 100); auto tree = pluckertree::segments::TreeBuilder<LineSegmentWrapper, &LineSegmentWrapper::l>::Build(lines.begin(), lines.end()); std::array<const LineSegmentWrapper *, 1> result{nullptr}; std::vector<std::tuple<const pluckertree::segments::TreeNode<LineSegmentWrapper, &LineSegmentWrapper::l>*, float, float>> todo; for(const auto& sector : tree.sectors) { if(sector.rootNode != nullptr) { todo.emplace_back(sector.rootNode.get(), sector.bounds.t1Min, sector.bounds.t2Max); } } while(!todo.empty()) { const auto [curNode, t1, t2] = todo.back(); todo.pop_back(); EXPECT_GE(curNode->content.l.t1, t1); EXPECT_LE(curNode->content.l.t2, t2); bool isTSplitNode = curNode->type == pluckertree::segments::NodeType::t; if(curNode->children[0] != nullptr) { todo.emplace_back(curNode->children[0].get(), isTSplitNode ? curNode->c1t1 : t1, isTSplitNode ? curNode->c1t2 : t2); } if(curNode->children[1] != nullptr) { todo.emplace_back(curNode->children[1].get(), isTSplitNode ? curNode->c2t1 : t1, isTSplitNode ? curNode->c2t2 : t2); } } } } TEST(Tree, TestFindNeighbouringLineSegments_Random) { for(int pass = 0; pass < 100; ++pass) { unsigned int line_count = 100; unsigned int query_count = 100; std::random_device dev{}; unsigned int line_seed = dev(); std::cout << "Line segment generation seed: " << line_seed << std::endl; auto lines = GenerateRandomLineSegments(line_seed, line_count, 100, -100, 100); auto tree = pluckertree::segments::TreeBuilder<LineSegmentWrapper, &LineSegmentWrapper::l>::Build(lines.begin(), lines.end()); unsigned int query_seed = dev(); std::cout << "Query generation seed: " << query_seed << std::endl; auto query_points = GenerateRandomPoints(query_seed, query_count, 100); std::array<const LineSegmentWrapper *, 1> result{nullptr}; int i = 0; for (const auto &query : query_points) { if(i % 50 == 0) { std::cout << i << std::endl; } //auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); //std::cout << "i: " << i << ", " << std::ctime(&t) << std::endl; float result_dist = 1E99; auto nbResultsFound = tree.FindNeighbours(query, result.begin(), result.end(), result_dist); //std::cout << "visited nodes: " << TreeNode::visited << std::endl; EXPECT_EQ(nbResultsFound, 1); auto distF = [](const LineSegment& s, const Eigen::Vector3f& q) { Eigen::Vector3f p = s.l.d.cross(s.l.m); float t = s.l.d.dot(q); t = std::min(std::max(t, s.t1), s.t2); Eigen::Vector3f v = (p + t*s.l.d) - q; return v; }; auto smallestLineIt = std::min_element(lines.begin(), lines.end(), [query, distF](const LineSegmentWrapper &l1, const LineSegmentWrapper &l2) { auto l1Norm = distF(l1.l, query).squaredNorm(); auto l2Norm = distF(l2.l, query).squaredNorm(); return l1Norm < l2Norm; }); LineSegment &SmallestLine = smallestLineIt->l; Vector3f m_spher = cart2spherical(SmallestLine.l.m); auto idx = FindSegment(tree, SmallestLine); if (SmallestLine != result[0]->l) { std::cout << std::endl; std::cout << "sect: "; for (int curI : idx) { std::cout << curI << " "; } std::cout << std::endl; std::cout << "Querypoint index: " << i << std::endl; std::cout << "Distance found: " << result_dist << std::endl; std::cout << "Actual smallest distance: " << distF(SmallestLine, query).norm() << std::endl; EXPECT_EQ(SmallestLine, result[0]->l); } i++; } } } TEST(Tree, DISABLED_TestFindNearestHitLineSegments_Random) { for(int pass = 0; pass < 100; ++pass) { unsigned int line_count = 100; unsigned int query_count = 100; std::random_device dev{}; unsigned int line_seed = dev(); std::cout << "Line segment generation seed: " << line_seed << std::endl; auto lines = GenerateRandomLineSegments(line_seed, line_count, 100, -100, 100); auto tree = pluckertree::segments::TreeBuilder<LineSegmentWrapper, &LineSegmentWrapper::l>::Build(lines.begin(), lines.end()); unsigned int query_seed = dev(); std::cout << "Query generation seed: " << query_seed << std::endl; auto query_points = GenerateRandomPoints(query_seed, query_count, 100); auto query_point_normals = GenerateRandomNormals(query_seed, query_count); std::array<const LineSegmentWrapper *, 1> result{nullptr}; for(unsigned int query_i = 0; query_i < query_points.size(); ++query_i) { if(query_i % 10 == 0) { std::cout << query_i << std::endl; } const auto& query = query_points[query_i]; const auto& query_normal = query_point_normals[query_i]; //auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); //std::cout << "i: " << i << ", " << std::ctime(&t) << std::endl; float result_dist = 1E99; auto nbResultsFound = tree.FindNearestHits(query, query_normal, result.begin(), result.end(), result_dist); //std::cout << "visited nodes: " << TreeNode::visited << std::endl; auto distF = [&query_normal](const LineSegment& s, const Eigen::Vector3f& q) { Eigen::Vector3f l0 = (s.l.d.cross(s.l.m)); auto t = (q - l0).dot(query_normal)/(s.l.d.dot(query_normal)); if(t < s.t1 || t > s.t2) { return 1E99f; } Eigen::Vector3f intersection = l0 + (s.l.d * t); Eigen::Vector3f vect = intersection - q; return vect.norm(); }; auto smallestLineIt = std::min_element(lines.begin(), lines.end(), [query, distF](const LineSegmentWrapper &l1, const LineSegmentWrapper &l2) { auto l1Norm = distF(l1.l, query); auto l2Norm = distF(l2.l, query); return l1Norm < l2Norm; }); LineSegment &SmallestLine = smallestLineIt->l; Vector3f m_spher = cart2spherical(SmallestLine.l.m); auto actual_smallest_dist = distF(SmallestLine, query); if(actual_smallest_dist == INFINITY) { EXPECT_EQ(nbResultsFound, 0); } else{ EXPECT_EQ(nbResultsFound, 1); if (SmallestLine != result[0]->l && result_dist != actual_smallest_dist) { std::cout << "Querypoint index: " << query_i << std::endl; std::cout << "Distance found: " << result_dist << std::endl; std::cout << "Actual smallest distance: " << actual_smallest_dist << std::endl; EXPECT_EQ(SmallestLine, result[0]->l); } } } } }<file_sep>/include/Pluckertree.h #pragma once #include <limits> #include <cstdint> #include <numeric> #include <memory> #include <Eigen/Dense> #include "MathUtil.h" #include <random> #include <iostream> namespace pluckertree { /** * Find the moment vector that produces the line with the smallest distance to the querypoint. * phi = polar angle, theta = azimuth, r = radius. * @param point the querypoint * @param dirLowerBound lower bound of the directional vector, in spherical coordinates [phi; theta] * @param dirUpperBound upper bound of the directional vector, in spherical coordinates [phi; theta] * @param momentLowerBound lower bound of the moment vector, in spherical coordinates [phi; theta; r] * @param momentUpperBound upper bound of the moment vector, in spherical coordinates [phi; theta; r] * @param min output parameter, will receive the moment vector * @return the distance from the line to the querypoint */ double FindMinDist( const Eigen::Vector3f& point, const Eigen::Vector3f& dirLowerBound, const Eigen::Vector3f& dirUpperBound, const Eigen::Vector3f& momentLowerBound, const Eigen::Vector3f& momentUpperBound, Eigen::Vector3f& min ); double FindMinHitDist( const Eigen::Vector3f& point, const Eigen::Vector3f& point_normal, const Eigen::Vector3f& dirLowerBound, const Eigen::Vector3f& dirUpperBound, const Eigen::Vector3f& momentLowerBound, const Eigen::Vector3f& momentUpperBound, Eigen::Vector3f& min ); double FindMinDist( const Eigen::Vector3f& point, const Eigen::Vector3f& dirLowerBound, const Eigen::Vector3f& dirUpperBound, const Eigen::Vector3f& moment ); void show_me_the_grid(std::string& file, const Eigen::Vector3f& dlb, const Eigen::Vector3f& dub, const Eigen::Vector3f& mlb, const Eigen::Vector3f& mub, const Eigen::Vector3f& q); class Line { public: Line(Eigen::Vector3f d, Eigen::Vector3f m) : d(std::move(d)), m(std::move(m)) {}; static Line FromPointAndDirection(const Eigen::Vector3f& point, const Eigen::Vector3f& direction) { auto p = point - point.dot(direction)*direction; auto m = p.cross(direction); return Line(direction, m); //Alternatively: auto dot = point.dot(direction); auto pointSqrNorm = point.squaredNorm(); auto scale = std::sqrt(pointSqrNorm) / std::sqrt(dot*dot + pointSqrNorm); return Line(direction, point.cross(direction) * scale); } static Line FromTwoPoints(const Eigen::Vector3f& point_a, const Eigen::Vector3f& point_b) { return FromPointAndDirection(point_a, (point_b-point_a).normalized()); } Eigen::Vector3f d; // Carthesian Eigen::Vector3f m; // Carthesian bool operator==(const Line& rhs) const { return (d == rhs.d) && (m == rhs.m); } bool operator!=(const Line& rhs) const { return !operator==(rhs); } }; template<class Content, Line Content::*line_member> class TreeNode; struct Bounds { Eigen::Vector3f d_bound_1; // Carthesian Eigen::Vector3f d_bound_2; // Carthesian Eigen::Vector3f m_start; // Spherical Eigen::Vector3f m_end; // Spherical Bounds(Eigen::Vector3f d_bound_1, Eigen::Vector3f d_bound_2, Eigen::Vector3f m_start, Eigen::Vector3f m_end) : d_bound_1(std::move(d_bound_1)), d_bound_2(std::move(d_bound_2)), m_start(std::move(m_start)), m_end(std::move(m_end)) {} Bounds() = default; void Clip(Eigen::Vector3f& moment) const { // Technically, we should account for -PI = PI in azimuth, but due to choice of sectors this method is fine. moment.x() = std::max(m_start.x(), std::min(m_end.x(), moment.x())); moment.y() = std::max(m_start.y(), std::min(m_end.y(), moment.y())); moment.z() = std::max(m_start.z(), std::min(m_end.z(), moment.z())); } bool ContainsMoment(const Eigen::Vector3f& moment /*spher coords*/) const { return Eigen::AlignedBox<float, 3>(m_start, m_end).contains(moment); } }; template<class Content, Line Content::*line_member> class TreeSector { public: Bounds bounds; std::unique_ptr<TreeNode<Content, line_member>> rootNode; TreeSector(Eigen::Vector3f d_bound_1, Eigen::Vector3f d_bound_2, Eigen::Vector3f m_start, Eigen::Vector3f m_end) : bounds(std::move(d_bound_1), std::move(d_bound_2), std::move(m_start), std::move(m_end)) {} }; enum class NodeType : uint8_t { moment, direction }; /** * @brief Inserts given value into the iterator range before specified position. * @param __position The position. * @param __x Data to be inserted. * * This function will insert a copy of the given value before the specified location. * All values will shift towards the end, with the last element being discarded. * position must be smaller than end. */ template<typename Iterator, typename Value, typename = typename std::enable_if<std::is_same<Value, typename std::iterator_traits<Iterator>::value_type>::value>::type> void iter_insert(Iterator position, Iterator end, const Value& val) { assert(position < end); for(Iterator it = end-2; it >= position; --it) { *(it+1) = *it; } *position = val; } constexpr float margin = 0; struct Diag { static thread_local unsigned int visited; static thread_local unsigned int minimizations; static std::optional<std::function<void(float best_so_far_dist, float cur_line_dist, float cur_node_mindist, int cur_depth)>> on_node_visited; static std::optional<std::function<void(float best_so_far_dist, float cur_node_mindist, int cur_depth)>> on_node_enter; static std::optional<std::function<void(float best_so_far_dist, float cur_line_dist, float cur_node_mindist, int cur_depth)>> on_node_leave; static std::optional<std::function<void(float m_phi_var, float m_gamma_var, float m_radius_var, float d_var)>> on_build_variance_calculated; static bool force_visit_all; static void reset() { visited = 0; minimizations = 0; on_node_visited = std::nullopt; on_node_enter = std::nullopt; on_node_leave = std::nullopt; on_build_variance_calculated = std::nullopt; force_visit_all = false; } }; template<class Content, class DistF, class OutputIt, typename = typename std::enable_if<std::is_same<const Content*, typename std::iterator_traits<OutputIt>::value_type>::value>::type> static float insert(const Content* elem, OutputIt out_first, OutputIt out_end, const Eigen::Vector3f& query_point, const DistF& distF) { auto it = std::lower_bound(out_first, out_end, elem, [&query_point, distF](const Content* c1, const Content* c2){ auto dist1 = c1 == nullptr ? std::numeric_limits<float>::infinity() : distF(c1, query_point).squaredNorm(); auto dist2 = c2 == nullptr ? std::numeric_limits<float>::infinity() : distF(c2, query_point).squaredNorm(); return dist1 < dist2; }); if(it != out_end) { iter_insert(it, out_end, elem); } auto lastElemPtr = *(out_end - 1); if(lastElemPtr == nullptr) { return std::numeric_limits<float>::infinity(); } return distF(lastElemPtr, query_point).norm(); } template<class Content, Line Content::*line_member> class TreeNode { public: std::array<std::unique_ptr<TreeNode<Content, line_member>>, 2> children; Content content; Eigen::Vector3f d_bound; //carthesian float m_component; //spherical NodeType type : 1; //uint8_t bound_idx : 1; uint8_t bound_component_idx : 2; //uint8_t pad1 : 6; //uint8_t pad2[7]; TreeNode(uint8_t bound_component_idx, float m_component, Content content) : type(NodeType::moment), bound_component_idx(bound_component_idx), m_component(m_component), content(std::move(content)), children() {} TreeNode(Eigen::Vector3f d_bound, Content content) : type(NodeType::direction), d_bound(std::move(d_bound)), content(std::move(content)), children() {} template<class OutputIt, typename = typename std::enable_if<std::is_same<const Content*, typename std::iterator_traits<OutputIt>::value_type>::value>::type> typename std::iterator_traits<OutputIt>::difference_type FindNeighbours( const Eigen::Vector3f& query_point, OutputIt out_first, OutputIt out_last, float& max_dist, const Bounds& bounds, const Eigen::Vector3f& moment_min_hint, int depth, float moment_min_hint_dist ) const { if(Diag::on_node_enter.has_value()) { (*Diag::on_node_enter)(max_dist, moment_min_hint_dist, depth); } Diag::visited++; std::array<float, 2> minimumDistances {}; std::array<Bounds, 2> childBounds {}; std::array<Eigen::Vector3f, 2> childMomentMinima {}; for(int i = 0; i < 2; ++i) { const auto& c = children[i]; if(c == nullptr) { minimumDistances[i] = std::numeric_limits<float>::infinity(); } else { childBounds[i] = bounds; if(this->type == NodeType::moment) { if(i == 0) { childBounds[0].m_end[this->bound_component_idx] = m_component; }else { childBounds[1].m_start[this->bound_component_idx] = m_component; } if(childBounds[i].ContainsMoment(moment_min_hint)) //TODO: test { childMomentMinima[i] = moment_min_hint; minimumDistances[i] = moment_min_hint_dist; continue; } } else { if(i == 0) { childBounds[i].d_bound_1 = this->d_bound; childBounds[i].d_bound_2 = bounds.d_bound_2; }else { childBounds[i].d_bound_1 = bounds.d_bound_1; childBounds[i].d_bound_2 = -this->d_bound; } } childMomentMinima[i] = moment_min_hint; childBounds[i].Clip(childMomentMinima[i]); minimumDistances[i] = FindMinDist(query_point, childBounds[i].d_bound_1, childBounds[i].d_bound_2, childBounds[i].m_start, childBounds[i].m_end, childMomentMinima[i]); } } // permutation = indices of children, from smallest to largest min dist std::array<uint8_t, 2> permutation = {0, 1}; if(minimumDistances[0] > minimumDistances[1]) { std::swap(permutation[0], permutation[1]); } unsigned int nbResultsFound = 0; auto resultsListLength = std::distance(out_first, out_last); for(uint8_t idx : permutation) { if((minimumDistances[idx] > max_dist+margin && !Diag::force_visit_all) || children[idx] == nullptr) //max_dist_check { break; } auto nbResultsInNode = children[idx]->FindNeighbours(query_point, out_first, out_last, max_dist, childBounds[idx], childMomentMinima[idx], depth+1, minimumDistances[idx]); nbResultsFound = std::min(nbResultsFound + nbResultsInNode, resultsListLength); } auto distF = [](const Content* c, const Eigen::Vector3f& p) { const auto& l = c->*line_member; Eigen::Vector3f v = p.cross(l.d) - l.m; return v; }; auto dist = distF(&content, query_point).norm(); if(Diag::on_node_visited.has_value()) { (*Diag::on_node_visited)(max_dist, dist, moment_min_hint_dist, depth); } if(dist < max_dist+margin) //max_dist_check { max_dist = insert(&content, out_first, out_last, query_point, distF); nbResultsFound++; } if(Diag::on_node_leave.has_value()) { (*Diag::on_node_leave)(max_dist, dist, moment_min_hint_dist, depth); } return nbResultsFound; } template<class OutputIt, typename = typename std::enable_if<std::is_same<const Content*, typename std::iterator_traits<OutputIt>::value_type>::value>::type> typename std::iterator_traits<OutputIt>::difference_type FindNearestHits( const Eigen::Vector3f& query_point, const Eigen::Vector3f& query_normal, OutputIt out_first, OutputIt out_last, float& max_dist, const Bounds& bounds, const Eigen::Vector3f& moment_min_hint, int depth, float moment_min_hint_dist ) const { Diag::visited++; std::array<float, 2> minimumDistances {}; std::array<Bounds, 2> childBounds {}; std::array<Eigen::Vector3f, 2> childMomentMinima {}; for(int i = 0; i < 2; ++i) { const auto& c = children[i]; if(c == nullptr) { minimumDistances[i] = std::numeric_limits<float>::infinity(); } else { childBounds[i] = bounds; if(this->type == NodeType::moment) { if(i == 0) { childBounds[0].m_end[this->bound_component_idx] = m_component; }else { childBounds[1].m_start[this->bound_component_idx] = m_component; } if(childBounds[i].ContainsMoment(moment_min_hint)) //TODO: test { childMomentMinima[i] = moment_min_hint; minimumDistances[i] = moment_min_hint_dist; continue; } } else { if(i == 0) { childBounds[i].d_bound_1 = this->d_bound; childBounds[i].d_bound_2 = bounds.d_bound_2; }else { childBounds[i].d_bound_1 = bounds.d_bound_1; childBounds[i].d_bound_2 = -this->d_bound; } } childMomentMinima[i] = moment_min_hint; childBounds[i].Clip(childMomentMinima[i]); minimumDistances[i] = FindMinHitDist(query_point, query_normal, childBounds[i].d_bound_1, childBounds[i].d_bound_2, childBounds[i].m_start, childBounds[i].m_end, childMomentMinima[i]); } } // permutation = indices of children, from smallest to largest min dist std::array<uint8_t, 2> permutation = {0, 1}; if(minimumDistances[0] > minimumDistances[1]) { std::swap(permutation[0], permutation[1]); } unsigned int nbResultsFound = 0; auto resultsListLength = std::distance(out_first, out_last); for(uint8_t idx : permutation) { if((minimumDistances[idx] > max_dist+margin && !Diag::force_visit_all) || children[idx] == nullptr) //max_dist_check { break; } auto nbResultsInNode = children[idx]->FindNearestHits(query_point, query_normal, out_first, out_last, max_dist, childBounds[idx], childMomentMinima[idx], depth+1, minimumDistances[idx]); nbResultsFound = std::min(nbResultsFound + nbResultsInNode, resultsListLength); } //auto dist = (query_point.cross(line.d) - line.m).norm(); auto distF = [&query_normal](const Content* c, const Eigen::Vector3f& p){ const auto& l = c->*line_member; Eigen::Vector3f l0 = (l.d.cross(l.m)); Eigen::Vector3f intersection = l0 + (l.d * (p - l0).dot(query_normal)/(l.d.dot(query_normal))); Eigen::Vector3f vect = intersection - p; return vect; }; auto dist = distF(&content, query_point).norm(); if(Diag::on_node_visited.has_value()) { (*Diag::on_node_visited)(max_dist, dist, moment_min_hint_dist, depth); } if(dist < max_dist+margin) //max_dist_check { max_dist = insert(&content, out_first, out_last, query_point, distF); nbResultsFound++; } return nbResultsFound; } }; template<typename Content, Line Content::*line_member> class Tree { private: size_t _size; public: std::array<TreeSector<Content, line_member>, 32> sectors; explicit Tree(size_t size, std::array<TreeSector<Content, line_member>, 32> sectors) : _size(size), sectors(std::move(sectors)) {} size_t size() const { return _size; }; //void Add(const Line& line); //bool Remove(const Line* line); template<class OutputIt, typename = typename std::enable_if<std::is_same<const Content*, typename std::iterator_traits<OutputIt>::value_type>::value>::type> typename std::iterator_traits<OutputIt>::difference_type FindNeighbours( const Eigen::Vector3f& query_point, OutputIt out_first, OutputIt out_last, float& max_dist ) const { Diag::visited = 0; Diag::minimizations = 0; std::array<float, 32> minimumDistances {}; std::array<Eigen::Vector3f, 32> moment_min_hints {}; for(int i = 0; i < minimumDistances.size(); ++i) { const auto& sector = sectors[i]; if(sector.rootNode == nullptr) { minimumDistances[i] = std::numeric_limits<float>::infinity(); } else { moment_min_hints[i] = sector.bounds.m_start + (sector.bounds.m_end - sector.bounds.m_start)/2; minimumDistances[i] = FindMinDist(query_point, sector.bounds.d_bound_1, sector.bounds.d_bound_2, sector.bounds.m_start, sector.bounds.m_end, moment_min_hints[i]); } } std::array<uint8_t, 32> permutation {}; std::iota(permutation.begin(), permutation.end(), 0); std::sort(permutation.begin(), permutation.end(), [it = minimumDistances.begin()](uint8_t a, uint8_t b) { return *(it + a) < *(it + b); }); //Search through sectors[idx].rootNode, ignoring sectors/bins with a mindist larger than searchRadius //Insert each line found into the output list, keeping the list sorted by distance. // Discard the last element, or don't insert if the new element is larger than all current results. //Set searchradius to the largest distance in the results list unsigned int nbResultsFound = 0; auto resultsListLength = std::distance(out_first, out_last); for(uint8_t idx : permutation) { if((minimumDistances[idx] > max_dist+margin && !Diag::force_visit_all) || sectors[idx].rootNode == nullptr) //max_dist_check { break; } const auto& curBounds = sectors[idx].bounds; auto nbResultsInNode = sectors[idx].rootNode->FindNeighbours( query_point, out_first, out_last, max_dist, curBounds, moment_min_hints[idx], 0, minimumDistances[idx]); nbResultsFound = std::min(nbResultsFound + nbResultsInNode, resultsListLength); } //std::cout << "visited " << Diag::visited << "/" << size() << std::endl; return nbResultsFound; } template<class OutputIt, typename = typename std::enable_if<std::is_same<const Content*, typename std::iterator_traits<OutputIt>::value_type>::value>::type> typename std::iterator_traits<OutputIt>::difference_type FindNearestHits( const Eigen::Vector3f& query_point, const Eigen::Vector3f& query_normal, OutputIt out_first, OutputIt out_last, float& max_dist ) const { Diag::visited = 0; Diag::minimizations = 0; std::array<float, 32> minimumDistances {}; std::array<Eigen::Vector3f, 32> moment_min_hints {}; for(int i = 0; i < minimumDistances.size(); ++i) { const auto& sector = sectors[i]; if(sector.rootNode == nullptr) { minimumDistances[i] = std::numeric_limits<float>::infinity(); } else { moment_min_hints[i] = sector.bounds.m_start + (sector.bounds.m_end - sector.bounds.m_start)/2; minimumDistances[i] = FindMinHitDist(query_point, query_normal, sector.bounds.d_bound_1, sector.bounds.d_bound_2, sector.bounds.m_start, sector.bounds.m_end, moment_min_hints[i]); } } std::array<uint8_t, 32> permutation {}; std::iota(permutation.begin(), permutation.end(), 0); std::sort(permutation.begin(), permutation.end(), [it = minimumDistances.begin()](uint8_t a, uint8_t b) { return *(it + a) < *(it + b); }); //Search through sectors[idx].rootNode, ignoring sectors/bins with a mindist larger than searchRadius //Insert each line found into the output list, keeping the list sorted by distance. // Discard the last element, or don't insert if the new element is larger than all current results. //Set searchradius to the largest distance in the results list unsigned int nbResultsFound = 0; auto resultsListLength = std::distance(out_first, out_last); for(uint8_t idx : permutation) { if((minimumDistances[idx] > max_dist+margin && !Diag::force_visit_all) || sectors[idx].rootNode == nullptr) //max_dist_check { break; } const auto& curBounds = sectors[idx].bounds; auto nbResultsInNode = sectors[idx].rootNode->FindNearestHits( query_point, query_normal, out_first, out_last, max_dist, curBounds, moment_min_hints[idx], 0, minimumDistances[idx]); nbResultsFound = std::min(nbResultsFound + nbResultsInNode, resultsListLength); } //std::cout << "visited " << Diag::visited << "/" << size() << std::endl; return nbResultsFound; } }; struct MyRand{ static std::random_device rand_dev; }; template<class Content, Line Content::*line_member> class TreeBuilder { using Node = TreeNode<Content, line_member>; using Sector = TreeSector<Content, line_member>; private: template<class LineIt, typename = typename std::enable_if<std::is_same<Content, typename std::iterator_traits<LineIt>::value_type>::value>::type> static std::unique_ptr<Node> BuildNode(LineIt lines_begin, LineIt lines_end, const Bounds& bounds, int level) { auto lineCount = std::distance(lines_begin, lines_end); if(lineCount == 0) { return nullptr; } // Find axis with largest variance and split in 2 there std::unique_ptr<Node> node; //NodeType type; uint8_t splitComponent = 0; Bounds subBounds1 = bounds; Bounds subBounds2 = bounds; LineIt pivot; std::uniform_real_distribution<float> unit{0.0f, 1.0f}; float v = unit(MyRand::rand_dev); /////////////////////////////// // Calculate directional variance // project direction vectors to bound domain, calculate variance of sine of angle to bound, and use this to decide NodeType const Eigen::Vector3f& cur_bound = bounds.d_bound_1; Eigen::Vector3f bound_domain_normal = bounds.d_bound_1.cross(bounds.d_bound_2).normalized(); if(bound_domain_normal.dot(bounds.m_start) < 0) { bound_domain_normal *= -1; } auto calc_sine = [](const Eigen::Vector3f& d, const Eigen::Vector3f& bound_domain_normal, const Eigen::Vector3f& cur_bound){ Eigen::Vector3f cross1 = (d - bound_domain_normal * bound_domain_normal.dot(d)).normalized().cross(cur_bound); auto sin = cross1.norm(); if(cross1.dot(bound_domain_normal) < 0) { sin *= -1; } return sin; }; /*auto dVariance = calc_pop_variance(lines_begin, lines_end, [&bound_domain_normal, &cur_bound, calc_sine](const Content& c){ const auto& line = c.*line_member; return std::asin(calc_sine(line.d, bound_domain_normal, cur_bound)); }); auto dMaxSin = bounds.d_bound_1.cross(bounds.d_bound_2).norm(); //auto dMaxPossibleVariance = (dMaxSin * dMaxSin)/4; //Assumes angle between bounds >= 90° //auto dVarianceNormalized = dVariance / dMaxPossibleVariance; auto dVarianceNormFactor = std::asin(dMaxSin); dVarianceNormFactor = dVarianceNormFactor * dVarianceNormFactor; auto dVarianceNormalized = dVariance; */ /////////////////////////////// bool splitOnDir = false; /////////////////////////////// // Calculate max moment variance #define M_LEVEL_ALTERNATING #if defined(M_MAX_VAR) || defined(M_MIN_VAR) #undef M_MAX_VAR Eigen::Array3f mVarianceVect = calc_vec3_pop_variance(lines_begin, lines_end, [](const Content& c){return cart2spherical((c.*line_member).m); }); Eigen::Array3f mVarianceNormFact = (bounds.m_end - bounds.m_start).array(); mVarianceNormFact = mVarianceNormFact * mVarianceNormFact; mVarianceVect = mVarianceVect.cwiseQuotient(mVarianceNormFact); #if defined(M_MAX_VAR) auto mVariance = mVarianceVect.maxCoeff(&splitComponent); #elif defined(M_MIN_VAR) auto mVariance = mVarianceVect.minCoeff(&splitComponent); #endif //splitOnDir = dVarianceNormalized > mVariance; /*if(level < 5 && level % 2 == 0) { splitComponent = 2; }*/ splitOnDir = v < 0.25; unsigned int pivot_i = lineCount/2; #elif defined(M_MAX_MAD) || defined(M_MIN_MAD) #undef M_MAX_MAD float phi_mad = calc_MAD(lines_begin, lines_end, [](const Content& c){return cart2spherical((c.*line_member).m)[0]; }); float theta_mad = calc_MAD(lines_begin, lines_end, [](const Content& c){return cart2spherical((c.*line_member).m)[1]; }); float radius_mad = calc_MAD(lines_begin, lines_end, [](const Content& c){return cart2spherical((c.*line_member).m)[2]; }); Eigen::Array3f mMADVect {phi_mad, theta_mad, radius_mad}; Eigen::Array3f mMADNormFact = (bounds.m_end - bounds.m_start).array(); //mMADNormFact[2] = mMADNormFact[2] / 3.0f; //std::cout << mMADVect.transpose() << " | " << (mMADVect/mMADNormFact).transpose() << std::endl; mMADVect = mMADVect.cwiseQuotient(mMADNormFact); #if defined(M_MAX_MAD) auto mMAD = mMADVect.maxCoeff(&splitComponent); #elif defined(M_MIN_MAD) auto mMAD = mMADVect.minCoeff(&splitComponent); #endif /*if(level == 0) { splitComponent = 2; }else if(level == 1) { splitComponent = 0; }*/ //splitOnDir = dVarianceNormalized > mVariance; splitOnDir = v < 0.25; unsigned int pivot_i = lineCount/2; #elif defined(M_RANDOM) if(v < 0.37) { splitComponent = 0; }else if(v < 0.65) { splitComponent = 1; }else{ splitComponent = 2; } splitOnDir = v < 0.25; unsigned int pivot_i = lineCount/2; #elif defined(M_LEVEL_ALTERNATING) splitComponent = level % 4; splitOnDir = (level % 4) == 3; unsigned int pivot_i = lineCount/2; #elif defined(M_VOLUME_HEURISTIC) unsigned int cur_best_dim_i = 0; unsigned int cur_best_i = 0; float cur_best_h = 1E99; for(int dim_i = 0; dim_i < 3; ++dim_i) { std::sort(lines_begin, lines_end, [splitComponent](const Content& c1, const Content& c2){ const auto& l1 = c1.*line_member; const auto& l2 = c2.*line_member; return cart2spherical(l1.m)[splitComponent] < cart2spherical(l2.m)[splitComponent]; }); for(unsigned int i = 1; i < lineCount-1; ++i) { const Line& l1 = (*(lines_begin+i-1)).*line_member; const Line& l2 = (*(lines_begin+i+1)).*line_member; subBounds1.m_end[dim_i] = cart2spherical(l1.m)[dim_i]; subBounds2.m_start[dim_i] = cart2spherical(l2.m)[dim_i]; float vol1; { float r1 = subBounds1.m_start.z(); float r2 = subBounds1.m_end.z(); vol1 = (((r2*r2*r2) - (r1*r1*r1))/2.0f) * (-std::cos(subBounds1.m_end.y()) + std::cos(subBounds1.m_start.y())) * (subBounds1.m_end.x() - subBounds1.m_start.x()); } float vol2; { float r1 = subBounds2.m_start.z(); float r2 = subBounds2.m_end.z(); vol2 = (((r2*r2*r2) - (r1*r1*r1))/2.0f) * (-std::cos(subBounds2.m_end.y()) + std::cos(subBounds2.m_start.y())) * (subBounds2.m_end.x() - subBounds2.m_start.x()); } auto node1ElemCount = i; auto node2ElemCount = (lineCount - i - 1); //float heuristic = (vol1 * node1ElemCount) + (vol2 * node2ElemCount); //float heuristic = (vol1) + (vol2); //float heuristic = (vol1/node1ElemCount) + (vol2/node2ElemCount); float heuristic = (vol1*node1ElemCount) + (vol2*node2ElemCount); if(heuristic < cur_best_h) { cur_best_h = heuristic; cur_best_dim_i = dim_i; cur_best_i = i; } } subBounds1.m_end[dim_i] = bounds.m_end[dim_i]; subBounds2.m_start[dim_i] = bounds.m_start[dim_i]; } splitComponent = cur_best_dim_i; unsigned int pivot_i = cur_best_i; splitOnDir = v < 0.25; #elif defined(M_LONGEST_DIST) unsigned int cur_best_dim_i = 0; unsigned int cur_best_i = 0; float cur_best_h = 0; for(int dim_i = 0; dim_i < 3; ++dim_i) { std::sort(lines_begin, lines_end, [splitComponent](const Content& c1, const Content& c2){ const auto& l1 = c1.*line_member; const auto& l2 = c2.*line_member; return cart2spherical(l1.m)[splitComponent] < cart2spherical(l2.m)[splitComponent]; }); for(unsigned int i = 1; i < lineCount-1; ++i) { const Line& l1 = (*(lines_begin+i-1)).*line_member; const Line& l2 = (*(lines_begin+i+1)).*line_member; float heuristic = ((cart2spherical(l2.m)[dim_i]) - (cart2spherical(l1.m)[dim_i]))/(bounds.m_end[dim_i] - bounds.m_start[dim_i]); if(heuristic > cur_best_h) { cur_best_h = heuristic; cur_best_dim_i = dim_i; cur_best_i = i; } } } splitComponent = cur_best_dim_i; unsigned int pivot_i = cur_best_i; splitOnDir = v < 0.25; #elif defined(M_PACK_AND_CUT) bool isPackNode = level % 4 == 0; unsigned int cur_best_dim_i = 0; unsigned int cur_best_i = 0; float cur_best_h = 0; std::array<float,3> cur_best_hs {0,0,0}; for(int dim_i = 0; dim_i < 3; ++dim_i) { std::sort(lines_begin, lines_end, [splitComponent](const Content& c1, const Content& c2){ const auto& l1 = c1.*line_member; const auto& l2 = c2.*line_member; return cart2spherical(l1.m)[splitComponent] < cart2spherical(l2.m)[splitComponent]; }); for(unsigned int i = 1; i < lineCount-1; ++i) { const Line& l1 = (*(lines_begin+i-1)).*line_member; const Line& l2 = (*(lines_begin+i+1)).*line_member; subBounds1.m_end[dim_i] = cart2spherical(l1.m)[dim_i]; subBounds2.m_start[dim_i] = cart2spherical(l2.m)[dim_i]; float vol1; { float r1 = subBounds1.m_start.z(); float r2 = subBounds1.m_end.z(); vol1 = (((r2*r2*r2) - (r1*r1*r1))/2.0f) * (-std::cos(subBounds1.m_end.y()) + std::cos(subBounds1.m_start.y())) * (subBounds1.m_end.x() - subBounds1.m_start.x()); } float vol2; { float r1 = subBounds2.m_start.z(); float r2 = subBounds2.m_end.z(); vol2 = (((r2*r2*r2) - (r1*r1*r1))/2.0f) * (-std::cos(subBounds2.m_end.y()) + std::cos(subBounds2.m_start.y())) * (subBounds2.m_end.x() - subBounds2.m_start.x()); } auto node1ElemCount = i; auto node2ElemCount = (lineCount - i - 1); /*float heuristic1 = 0.5*(vol1/node1ElemCount) + (node2ElemCount/vol2); //cut, pack float heuristic2 = (node1ElemCount/vol1) + 0.5*(vol2/node2ElemCount); //pack, cut float heuristic = std::max(heuristic1, heuristic2);*/ float heuristic; if(isPackNode) { heuristic = std::max(vol1/node1ElemCount, vol2/node2ElemCount); }else{ heuristic = std::max(node1ElemCount/vol1, node2ElemCount/vol2); } if(heuristic > cur_best_hs[dim_i]) { cur_best_hs[dim_i] = heuristic; } if(heuristic > cur_best_h) { cur_best_h = heuristic; cur_best_dim_i = dim_i; cur_best_i = i; } } subBounds1.m_end[dim_i] = bounds.m_end[dim_i]; subBounds2.m_start[dim_i] = bounds.m_start[dim_i]; } splitComponent = cur_best_dim_i; unsigned int pivot_i = cur_best_i; splitOnDir = v < 0.25; #endif /////////////////////////////// if(Diag::on_build_variance_calculated.has_value()) { //Diag::on_build_variance_calculated.value()(mVarianceVect.x(), mVarianceVect.y(), mVarianceVect.z(), 0/*dVarianceNormalized*/); //Diag::on_build_variance_calculated.value()(cur_best_hs[0], cur_best_hs[1], cur_best_hs[2], 0/*dVarianceNormalized*/); } if(splitOnDir) { // calculate new bound vector: calc cross product of dir vectors with cur bound vector to obtain sin, // sort by sin, take median, new bound vector is cross product of bound_domain_normal with median dir vect // Given bounds b1 and b2 in parent, and new bound vector nb, the childrens bounds are as follows: // child 1: {nb, b2}, child 2: {b1, -nb} std::sort(lines_begin, lines_end, [&cur_bound, &bound_domain_normal, calc_sine](const Content& c1, const Content& c2){ const auto& l1 = c1.*line_member; const auto& l2 = c2.*line_member; auto sin1 = calc_sine(l1.d, bound_domain_normal, cur_bound); auto sin2 = calc_sine(l2.d, bound_domain_normal, cur_bound); return sin1 < sin2; }); pivot = lines_begin + (lines_end - lines_begin)/2; const auto& pivotLine = (*pivot).*line_member; Eigen::Vector3f dir_bound = bound_domain_normal.cross(pivotLine.d).normalized(); subBounds1.d_bound_1 = dir_bound; subBounds1.d_bound_2 = bounds.d_bound_2; subBounds2.d_bound_1 = bounds.d_bound_1; subBounds2.d_bound_2 = -dir_bound; node = std::make_unique<Node>(dir_bound, *pivot); } else { std::sort(lines_begin, lines_end, [splitComponent](const Content& c1, const Content& c2){ const auto& l1 = c1.*line_member; const auto& l2 = c2.*line_member; return cart2spherical(l1.m)[splitComponent] < cart2spherical(l2.m)[splitComponent]; }); pivot = lines_begin + pivot_i; const auto& pivotLine = (*pivot).*line_member; auto splitCompVal = cart2spherical(pivotLine.m)[splitComponent]; subBounds1.m_end[splitComponent] = splitCompVal; subBounds2.m_start[splitComponent] = splitCompVal; node = std::make_unique<Node>(splitComponent, splitCompVal, *pivot); } // Store iterators and bounds and then recurse node->children[0] = BuildNode(lines_begin, pivot, subBounds1, level + 1); node->children[1] = BuildNode(pivot+1, lines_end, subBounds2, level + 1); return std::move(node); } public: template<class LineIt, typename = typename std::enable_if<std::is_same<Content, typename std::iterator_traits<LineIt>::value_type>::value>::type> static Tree<Content, line_member> Build(LineIt lines_first, LineIt lines_last) { // Create sectors using Eigen::Vector3f; constexpr float max_dist = 150; //TODO constexpr float min_dist = 1e-3; std::array<Sector, 32> sectors { // Top sector Sector(Vector3f(1, 0, 0), Vector3f(0, 1, 0), Vector3f(-M_PI, 0, min_dist), Vector3f(0, M_PI/4, max_dist)), Sector(Vector3f(0, 1, 0), Vector3f(-1, 0, 0), Vector3f(-M_PI, 0, min_dist), Vector3f(0, M_PI/4, max_dist)), Sector(Vector3f(-1, 0, 0), Vector3f(0, -1, 0), Vector3f(-M_PI, 0, min_dist), Vector3f(0, M_PI/4, max_dist)), Sector(Vector3f(0, -1, 0), Vector3f(1, 0, 0), Vector3f(-M_PI, 0, min_dist), Vector3f(0, M_PI/4, max_dist)), Sector(Vector3f(1, 0, 0), Vector3f(0, 1, 0), Vector3f(0, 0, min_dist), Vector3f(M_PI, M_PI/4, max_dist)), Sector(Vector3f(0, 1, 0), Vector3f(-1, 0, 0), Vector3f(0, 0, min_dist), Vector3f(M_PI, M_PI/4, max_dist)), Sector(Vector3f(-1, 0, 0), Vector3f(0, -1, 0), Vector3f(0, 0, min_dist), Vector3f(M_PI, M_PI/4, max_dist)), Sector(Vector3f(0, -1, 0), Vector3f(1, 0, 0), Vector3f(0, 0, min_dist), Vector3f(M_PI, M_PI/4, max_dist)), // Bottom sector Sector(Vector3f(1, 0, 0), Vector3f(0, 1, 0), Vector3f(-M_PI, 3*M_PI/4, min_dist), Vector3f(0, M_PI, max_dist)), Sector(Vector3f(0, 1, 0), Vector3f(-1, 0, 0), Vector3f(-M_PI, 3*M_PI/4, min_dist), Vector3f(0, M_PI, max_dist)), Sector(Vector3f(-1, 0, 0), Vector3f(0, -1, 0), Vector3f(-M_PI, 3*M_PI/4, min_dist), Vector3f(0, M_PI, max_dist)), Sector(Vector3f(0, -1, 0), Vector3f(1, 0, 0), Vector3f(-M_PI, 3*M_PI/4, min_dist), Vector3f(0, M_PI, max_dist)), Sector(Vector3f(1, 0, 0), Vector3f(0, 1, 0), Vector3f(0, 3*M_PI/4, min_dist), Vector3f(M_PI, M_PI, max_dist)), Sector(Vector3f(0, 1, 0), Vector3f(-1, 0, 0), Vector3f(0, 3*M_PI/4, min_dist), Vector3f(M_PI, M_PI, max_dist)), Sector(Vector3f(-1, 0, 0), Vector3f(0, -1, 0), Vector3f(0, 3*M_PI/4, min_dist), Vector3f(M_PI, M_PI, max_dist)), Sector(Vector3f(0, -1, 0), Vector3f(1, 0, 0), Vector3f(0, 3*M_PI/4, min_dist), Vector3f(M_PI, M_PI, max_dist)), // -X -Y sector Sector(Vector3f(0, 0, 1), Vector3f(1, -1, 0).normalized(), Vector3f(-M_PI, M_PI/4, min_dist), Vector3f(-M_PI/2, 3*M_PI/4, max_dist)), Sector(Vector3f(1, -1, 0).normalized(), Vector3f(0, 0, -1), Vector3f(-M_PI, M_PI/4, min_dist), Vector3f(-M_PI/2, 3*M_PI/4, max_dist)), Sector(Vector3f(0, 0, -1), Vector3f(-1, 1, 0).normalized(), Vector3f(-M_PI, M_PI/4, min_dist), Vector3f(-M_PI/2, 3*M_PI/4, max_dist)), Sector(Vector3f(-1, 1, 0).normalized(), Vector3f(0, 0, 1), Vector3f(-M_PI, M_PI/4, min_dist), Vector3f(-M_PI/2, 3*M_PI/4, max_dist)), // +X -Y sector Sector(Vector3f(0, 0, 1), Vector3f(-1, -1, 0).normalized(), Vector3f(-M_PI/2, M_PI/4, min_dist), Vector3f(0, 3*M_PI/4, max_dist)), Sector(Vector3f(-1, -1, 0).normalized(), Vector3f(0, 0, -1), Vector3f(-M_PI/2, M_PI/4, min_dist), Vector3f(0, 3*M_PI/4, max_dist)), Sector(Vector3f(0, 0, -1), Vector3f(1, 1, 0).normalized(), Vector3f(-M_PI/2, M_PI/4, min_dist), Vector3f(0, 3*M_PI/4, max_dist)), Sector(Vector3f(1, 1, 0).normalized(), Vector3f(0, 0, 1), Vector3f(-M_PI/2, M_PI/4, min_dist), Vector3f(0, 3*M_PI/4, max_dist)), // +X +Y sector Sector(Vector3f(0, 0, 1), Vector3f(1, -1, 0).normalized(), Vector3f(0, M_PI/4, min_dist), Vector3f(M_PI/2, 3*M_PI/4, max_dist)), Sector(Vector3f(1, -1, 0).normalized(), Vector3f(0, 0, -1), Vector3f(0, M_PI/4, min_dist), Vector3f(M_PI/2, 3*M_PI/4, max_dist)), Sector(Vector3f(0, 0, -1), Vector3f(-1, 1, 0).normalized(), Vector3f(0, M_PI/4, min_dist), Vector3f(M_PI/2, 3*M_PI/4, max_dist)), Sector(Vector3f(-1, 1, 0).normalized(), Vector3f(0, 0, 1), Vector3f(0, M_PI/4, min_dist), Vector3f(M_PI/2, 3*M_PI/4, max_dist)), // -X +Y sector Sector(Vector3f(0, 0, 1), Vector3f(-1, -1, 0).normalized(), Vector3f(M_PI/2, M_PI/4, min_dist), Vector3f(M_PI, 3*M_PI/4, max_dist)), Sector(Vector3f(-1, -1, 0).normalized(), Vector3f(0, 0, -1), Vector3f(M_PI/2, M_PI/4, min_dist), Vector3f(M_PI, 3*M_PI/4, max_dist)), Sector(Vector3f(0, 0, -1), Vector3f(1, 1, 0).normalized(), Vector3f(M_PI/2, M_PI/4, min_dist), Vector3f(M_PI, 3*M_PI/4, max_dist)), Sector(Vector3f(1, 1, 0).normalized(), Vector3f(0, 0, 1), Vector3f(M_PI/2, M_PI/4, min_dist), Vector3f(M_PI, 3*M_PI/4, max_dist)) }; auto nbLines = std::distance(lines_first, lines_last); // Sort lines into sectors std::array<LineIt, 32> line_sector_ends; { LineIt it_begin = lines_first; int idx = 0; for(Sector& sector : sectors) { for(LineIt it = it_begin; it < lines_last; ++it) { const auto& line = (*it).*line_member; if(sector.bounds.ContainsMoment(cart2spherical(line.m)) && sector.bounds.d_bound_1.dot(line.d) >= 0 //greater or equal, or just greater? && sector.bounds.d_bound_2.dot(line.d) >= 0) { std::iter_swap(it_begin, it); it_begin++; } } line_sector_ends[idx] = it_begin; idx++; } } // Subdivide sectors into bins { LineIt it_begin = lines_first; int idx = 0; for(Sector& sector : sectors) { LineIt it_end = line_sector_ends[idx]; auto count = std::distance(it_begin, it_end); sector.rootNode = BuildNode(it_begin, it_end, sector.bounds, 0); it_begin = it_end; idx++; } } return Tree<Content, line_member>(nbLines, std::move(sectors)); } }; } <file_sep>/README.md # Plückertree - Fast nearest neighbouring line lookup This is the code written for my master thesis with the dutch title "Plückerbomen: efficiënt zoeken van k dichtstbijzijnde rechten rond punt in 3D, met toepassing in photonmapping". (in english: "Plückertrees: efficient search of k nearest lines around point in 3D, with application in photonmapping") Main takeaway of this paper: using a tree based on plückercoordinates, it is possible to find the lines with the shortest distance to an arbitrary 3D point in about O(n^0.608) time while taking up only O(n) space. The paper shows comparable performance for similar problems such as rays instead of lines, or using distance to line-plane intersection instead of line-point. This is research code, so definitely not production ready. You can find the PDF of my thesis [here](Thesis.pdf).<file_sep>/tests/FixedMomentRegionDistanceMinimizer.cpp #include <gtest/gtest.h> #include <gmock/gmock.h> #include <Pluckertree.h> #include <MathUtil.h> #include <iostream> using namespace testing; using namespace Eigen; using namespace pluckertree; Vector3f AnyDirBound(const Vector3f& q, const Vector3f& moment) { return moment.cross(q); } float FindMinDist(const Vector3f& q, const Vector3f& cartMoment) { Vector3f b = AnyDirBound(q, cartMoment); return FindMinDist(q, b, b, cart2spherical(cartMoment)); } TEST(RegionDistanceMinimizer, TestFixedMomentUnrestrictedDirQAtOneX) { //for each k, calc dlb and dub by making sure dot product with both da and db is > 0. // (dlb = dub = (da + db)/2 ?) Vector3f q(1, 0, 0); float epsilon = 1e-6; EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 1.0, 0.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.7, 0.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 1.5, 0.0)), 0.5, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 1.0, 0.0, 0.0)), std::sqrt(2), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 2.0, 0.0, 0.0)), std::sqrt(5), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.0, 1.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.0, 0.7)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.0, 1.5)), 0.5, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.5, 0.5)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 3.0, 4.0)), 4, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(-1.0, 0.0, 0.0)), std::sqrt(2), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(-2.0, 0.0, 0.0)), std::sqrt(5), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, -1.0, 0.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, -0.7, 0.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, -1.5, 0.0)), 0.5, epsilon); } TEST(RegionDistanceMinimizer, TestFixedMomentUnrestrictedDirQAtTwoX) { Vector3f q(2, 0, 0); float epsilon = 1e-6; EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 1.0, 0.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 3.0, 0.0)), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 1.0, 0.0, 0.0)), std::sqrt(5), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 2.0, 0.0, 0.0)), std::sqrt(8), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(-1.0, 0.0, 0.0)), std::sqrt(5), epsilon); } TEST(RegionDistanceMinimizer, TestFixedMomentUnrestrictedDirQAtNegativeTwoX) { Vector3f q(-2, 0, 0); float epsilon = 1e-6; EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 1.0, 0.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 3.0, 0.0)), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 1.0, 0.0, 0.0)), std::sqrt(5), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 2.0, 0.0, 0.0)), std::sqrt(8), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.0, 1.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.5, 0.5)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 3.0, 4.0)), 3, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(-1.0, 0.0, 0.0)), std::sqrt(5), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(-2.0, 0.0, 0.0)), std::sqrt(8), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, -1.0, 0.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, -2.0, 0.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, -3.0, 0.0)), 1, epsilon); } TEST(RegionDistanceMinimizer, TestFixedMomentUnrestrictedDirQAtY) { Vector3f q(0, 1, 0); float epsilon = 1e-6; EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 1.0, 0.0)), std::sqrt(2), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 1.0, 0.0, 0.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 2.0, 0.0, 0.0)), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.0, 1.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.0, 0.7)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.0, 1.5)), 0.5, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.5, 0.5)), 1/std::sqrt(2), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 3.0, 3.0)), std::sqrt(std::pow(1/std::sqrt(2), 2) + std::pow(std::sqrt(18)-(1/std::sqrt(2)), 2)), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(-1.0, 0.0, 0.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(-2.0, 0.0, 0.0)), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, -1.0, 0.0)), std::sqrt(2), epsilon); } TEST(RegionDistanceMinimizer, TestFixedMomentUnrestrictedDirQMixed) { Vector3f q(1, 1, 0); float epsilon = 1e-6; EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 1.0, 0.0)), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.7, 0.0)), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 1.5, 0.0)), std::sqrt(0.5*0.5 + 1), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 1.0, 0.0, 0.0)), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 2.0, 0.0, 0.0)), std::sqrt(2), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.0, 1.0)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.0, 0.7)), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f( 0.0, 0.0, 1.5)), 1.5-std::sqrt(2), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(-1.0, 0.0, 0.0)), 1, epsilon); } TEST(RegionDistanceMinimizer, TestFixedMomentRestrictedDirQAtOneX) { Vector3f q(1, 0, 0); float epsilon = 1e-6; EXPECT_NEAR(FindMinDist(q, Vector3f(0, 0, -1), Vector3f(0, 0, -1), cart2spherical(Vector3f(0.0, 1.0, 0.0))), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(0, 0, 1), Vector3f(0, 0, 1), cart2spherical(Vector3f(0.0, 1.0, 0.0))), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(1, 0, 1e-3).normalized(), Vector3f(-1, 0, 1e-3).normalized(), cart2spherical(Vector3f(0.0, 1.0, 0.0))), 2, epsilon); //Narrow bound here, but distance can technically be a bit lower than 2 EXPECT_NEAR(FindMinDist(q, Vector3f(0.998455, 0, .055560).normalized(), Vector3f(-0.994729, 0, .102535).normalized(), cart2spherical(Vector3f(0.0, -1.0, 0.0))), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(0, 0, -1), Vector3f(0, 0, -1), cart2spherical(Vector3f(0.0, -1.0, 0.0))), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(1, 0, -1e-3).normalized(), Vector3f(-1, 0, -1e-3).normalized(), cart2spherical(Vector3f(0.0, -1.0, 0.0))), 2, epsilon); //Same here as above EXPECT_NEAR(FindMinDist(q, Vector3f(0, 1, 0), Vector3f(-1, 0, 0), cart2spherical(Vector3f(0.0, 0.0, 1.0))), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(0, -1, 0), Vector3f(0, -1, 0), cart2spherical(Vector3f(0.0, 0.0, 1.0))), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(0, -1, 0), Vector3f(-1, 0, 0), cart2spherical(Vector3f(0.0, 0.0, 1.0))), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(0, -1, 0), Vector3f(-1, 0, 0), cart2spherical(Vector3f(0.0, 0.0, -1.0))), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(0, 1, 0), Vector3f(0, 1, 0), cart2spherical(Vector3f(0.0, 0.0, -1.0))), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(0, -1, 0), Vector3f(0, -1, 0), cart2spherical(Vector3f(0.0, 0.0, -1.0))), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(1, .0001, 0).normalized(), Vector3f(-1, .0001, 0).normalized(), cart2spherical(Vector3f(0.0, 0.0, -1.0))), 2, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(0, 0, 1), Vector3f(0, 1, 0), cart2spherical(Vector3f(1.0, 0.0, 0.0))), std::sqrt(2), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(0, 0, -1), Vector3f(0, 1, 0), cart2spherical(Vector3f(1.0, 0.0, 0.0))), std::sqrt(2), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(0, 0, 1), Vector3f(0, -1, 0), cart2spherical(Vector3f(1.0, 0.0, 0.0))), std::sqrt(2), epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(0, 0, -1), Vector3f(0, -1, 0), cart2spherical(Vector3f(1.0, 0.0, 0.0))), std::sqrt(2), epsilon); } TEST(RegionDistanceMinimizer, TestFixedMomentRestrictedDirQAtTwoX) { Vector3f q(2, 0, 0); float epsilon = 1e-6; EXPECT_NEAR(FindMinDist(q, Vector3f(1, 0, 0), Vector3f(0, 1, 0), cart2spherical(Vector3f(0.0, 0.0, 1.0))), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(-1, 0, 0), Vector3f(0, 1, 0), cart2spherical(Vector3f(0.0, 0.0, 1.0))), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(0, -1, 0), Vector3f(0, -1, 0), cart2spherical(Vector3f(0.0, 0.0, 1.0))), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(.5001, -.86603, 0).normalized(), Vector3f(-.5, .86603, 0).normalized(), cart2spherical(Vector3f(0.0, 0.0, 1.0))), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(1, 0, 0), Vector3f(0, -1, 0), cart2spherical(Vector3f(0.0, 0.0, 1.0))), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(-1, 0, 0), Vector3f(0, -1, 0), cart2spherical(Vector3f(0.0, 0.0, 1.0))), 1, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(1, 0, 0), Vector3f(1, 0, 0), cart2spherical(Vector3f(0.0, 0.0, 1.0))), 0, epsilon); EXPECT_NEAR(FindMinDist(q, Vector3f(-1, 0, 0), Vector3f(-1, 0, 0), cart2spherical(Vector3f(0.0, 0.0, 1.0))), 0, epsilon); }<file_sep>/tests/TestUtilities.h #pragma once #define EXPECT_VEC3_NEAR(vect1, vect2, epsilon) \ EXPECT_NEAR(vect1[0], vect2[0], epsilon); \ EXPECT_NEAR(vect1[1], vect2[1], epsilon); \ EXPECT_NEAR(vect1[2], vect2[2], epsilon) <file_sep>/tests/Line.cpp #include <gtest/gtest.h> #include <gmock/gmock.h> #include <Pluckertree.h> #include "TestUtilities.h" using namespace testing; using namespace pluckertree; using namespace Eigen; TEST(Line, TestFromPointAndDirection1) { auto epsilon = 1e-6; auto l = Line::FromPointAndDirection(Vector3f(0, 0, 1), Vector3f(1, 0, 0)); EXPECT_VEC3_NEAR(l.d, Vector3f(1, 0, 0), epsilon); EXPECT_VEC3_NEAR(l.m, Vector3f(0, 1, 0), epsilon); } TEST(Line, TestFromPointAndDirection2) { auto epsilon = 1e-6; auto l = Line::FromPointAndDirection(Vector3f(2, 0, 0), Vector3f(0, 1, 0)); EXPECT_VEC3_NEAR(l.d, Vector3f(0, 1, 0), epsilon); EXPECT_VEC3_NEAR(l.m, Vector3f(0, 0, 2), epsilon); } TEST(Line, TestFromPointAndDirection3) { auto epsilon = 1e-6; auto l = Line::FromPointAndDirection(Vector3f(1, 0, 1), Vector3f(1, 0, 0)); EXPECT_VEC3_NEAR(l.d, Vector3f(1, 0, 0), epsilon); EXPECT_VEC3_NEAR(l.m, Vector3f(0, 1, 0), epsilon); } TEST(Line, TestFromPointAndDirection4) { auto epsilon = 1e-6; auto l = Line::FromPointAndDirection(Vector3f(-1, 0, 0), Vector3f(0, 0, 1)); EXPECT_VEC3_NEAR(l.d, Vector3f(0, 0, 1), epsilon); EXPECT_VEC3_NEAR(l.m, Vector3f(0, 1, 0), epsilon); } TEST(Line, TestFromPointAndDirection5) { auto epsilon = 1e-6; Vector3f d = Vector3f(-1/std::sqrt(2.0f), -1/std::sqrt(2.0f), 1).normalized(); auto l = Line::FromPointAndDirection(Vector3f(1, -1, 0).normalized(), d); EXPECT_VEC3_NEAR(l.d, d, epsilon); EXPECT_VEC3_NEAR(l.m, Vector3f(-0.5, -0.5, -std::sqrt(2)/2), epsilon); } TEST(Line, TestFromTwoPoints1) { auto epsilon = 1e-6; auto l = Line::FromTwoPoints(Vector3f(0, 0, 1), Vector3f(1, 0, 1)); EXPECT_VEC3_NEAR(l.d, Vector3f(1, 0, 0), epsilon); EXPECT_VEC3_NEAR(l.m, Vector3f(0, 1, 0), epsilon); } TEST(Line, TestFromTwoPoints2) { auto epsilon = 1e-6; auto l = Line::FromTwoPoints(Vector3f(2, 0, 0), Vector3f(2, 2, 0)); EXPECT_VEC3_NEAR(l.d, Vector3f(0, 1, 0), epsilon); EXPECT_VEC3_NEAR(l.m, Vector3f(0, 0, 2), epsilon); } TEST(Line, TestFromTwoPoints3) { auto epsilon = 1e-6; auto l = Line::FromTwoPoints(Vector3f(1, 0, 1), Vector3f(2, 0, 1)); EXPECT_VEC3_NEAR(l.d, Vector3f(1, 0, 0), epsilon); EXPECT_VEC3_NEAR(l.m, Vector3f(0, 1, 0), epsilon); }<file_sep>/include/MathUtil.h #pragma once #include <Eigen/Dense> template<typename number_t> auto spherical2cart(number_t phi, number_t theta, number_t r) { auto x = r * std::sin(theta) * std::cos(phi); auto y = r * std::sin(theta) * std::sin(phi); auto z = r * std::cos(theta); return Eigen::Matrix<number_t, 3, 1>(x, y, z); } template<typename Vector3_t> auto cart2spherical(const Vector3_t& p) { auto XsqPlusYsq = p[0]*p[0] + p[1]*p[1]; auto r = p.norm(); auto elev = std::atan2(std::sqrt(XsqPlusYsq), p[2]); auto az = std::atan2(p[1],p[0]); return Vector3_t(az, elev, r); } template<typename Iter, typename Accessor> float calc_MAD(Iter begin, Iter end, Accessor f) { std::sort(begin, end, [&f](const auto& v1, const auto& v2){ return f(v1) < f(v2); }); auto median = f(*(begin + ((end - begin)/2))); std::sort(begin, end, [&f, median](const auto& v1, const auto& v2){ return std::abs(f(v1) - median) < std::abs(f(v2) - median); }); auto mad = std::abs(f(*(begin + ((end - begin)/2))) - median); return mad; } template<typename Iter, typename Accessor> float calc_pop_variance(Iter begin, Iter end, Accessor f) { float total = 0; for(auto it = begin; it < end; ++it) { total += f(*it); } auto elemCount = std::distance(begin, end); float avg = total / elemCount; float variance = 0; for(auto it = begin; it < end; ++it) { float cur = f(*it) - avg; variance += cur * cur; } variance /= elemCount; return variance; } template<typename Iter, typename Accessor> Eigen::Array3f calc_vec3_pop_variance(Iter begin, Iter end, Accessor f) { Eigen::Array3f total(0, 0, 0); for(auto it = begin; it < end; ++it) { total += f(*it).array(); } auto elemCount = std::distance(begin, end); Eigen::Array3f avg = total / elemCount; Eigen::Array3f variance(0, 0, 0); for(auto it = begin; it < end; ++it) { Eigen::Array3f cur = f(*it).array() - avg; variance += cur * cur; } variance /= elemCount; return variance; } <file_sep>/CMakeLists.txt cmake_minimum_required (VERSION 3.10) project(PLUCKERTREE) set(CMAKE_CXX_STANDARD 17) #set(CMAKE_VERBOSE_MAKEFILE ON) add_subdirectory (src) if(DEFINED PLUCKERTREE_ENABLE_TESTS) add_subdirectory (tests) endif() <file_sep>/include/PluckertreeSegments.h #pragma once #include <Pluckertree.h> namespace pluckertree::segments { /** * Find the moment vector that produces the line with the smallest distance to the querypoint. * phi = polar angle, theta = azimuth, r = radius. * @param point the querypoint * @param dirLowerBound lower bound of the directional vector, in spherical coordinates [phi; theta] * @param dirUpperBound upper bound of the directional vector, in spherical coordinates [phi; theta] * @param momentLowerBound lower bound of the moment vector, in spherical coordinates [phi; theta; r] * @param momentUpperBound upper bound of the moment vector, in spherical coordinates [phi; theta; r] * @param t1Min minium t value for the start of the line segment * @param t2Max maximum t value for the end of the line segment * @param min output parameter, will receive the moment vector * @return the distance from the line to the querypoint */ double FindMinDist( const Eigen::Vector3f& point, const Eigen::Vector3f& dirLowerBound, const Eigen::Vector3f& dirUpperBound, const Eigen::Vector3f& momentLowerBound, const Eigen::Vector3f& momentUpperBound, float t1Min, float t2Max, Eigen::Vector3f& min ); class LineSegment { public: LineSegment(Line line, float t1, float t2) : l(std::move(line)), t1(t1), t2(t2) {}; Line l; float t1, t2; bool operator==(const LineSegment& rhs) const { return (l == rhs.l) && (t1 == rhs.t1) && (t2 == rhs.t2); } bool operator!=(const LineSegment& rhs) const { return !operator==(rhs); } }; template<class Content, LineSegment Content::*line_member> class TreeNode; struct Bounds { Eigen::Vector3f d_bound_1; // Carthesian Eigen::Vector3f d_bound_2; // Carthesian Eigen::Vector3f m_start; // Spherical Eigen::Vector3f m_end; // Spherical float t1Min, t2Max; Bounds(Eigen::Vector3f d_bound_1, Eigen::Vector3f d_bound_2, Eigen::Vector3f m_start, Eigen::Vector3f m_end, float t1Min, float t2Max) : d_bound_1(std::move(d_bound_1)), d_bound_2(std::move(d_bound_2)), m_start(std::move(m_start)), m_end(std::move(m_end)), t1Min(t1Min), t2Max(t2Max) {} Bounds() = default; void Clip(Eigen::Vector3f& moment) const { // Technically, we should account for -PI = PI in azimuth, but due to choice of sectors this method is fine. moment.x() = std::max(m_start.x(), std::min(m_end.x(), moment.x())); moment.y() = std::max(m_start.y(), std::min(m_end.y(), moment.y())); moment.z() = std::max(m_start.z(), std::min(m_end.z(), moment.z())); } bool ContainsMoment(const Eigen::Vector3f& moment /*spher coords*/) const { return Eigen::AlignedBox<float, 3>(m_start, m_end).contains(moment); } }; template<class Content, LineSegment Content::*line_member> class TreeSector { public: Bounds bounds; std::unique_ptr<TreeNode<Content, line_member>> rootNode; TreeSector(Eigen::Vector3f d_bound_1, Eigen::Vector3f d_bound_2, Eigen::Vector3f m_start, Eigen::Vector3f m_end, float t1Min, float t2Max) : bounds(std::move(d_bound_1), std::move(d_bound_2), std::move(m_start), std::move(m_end), t1Min, t2Max) {} }; enum class NodeType : uint8_t { moment, direction, t }; constexpr float margin = 0; template<class Content, class DistF, class OutputIt, typename = typename std::enable_if<std::is_same<const Content*, typename std::iterator_traits<OutputIt>::value_type>::value>::type> static float insert(const Content* elem, OutputIt out_first, OutputIt out_end, const Eigen::Vector3f& query_point, const DistF& distF) { auto it = std::lower_bound(out_first, out_end, elem, [&query_point, distF](const Content* c1, const Content* c2){ auto dist1 = c1 == nullptr ? std::numeric_limits<float>::infinity() : distF(c1, query_point); auto dist2 = c2 == nullptr ? std::numeric_limits<float>::infinity() : distF(c2, query_point); return dist1 < dist2; }); if(it != out_end) { iter_insert(it, out_end, elem); } auto lastElemPtr = *(out_end - 1); if(lastElemPtr == nullptr) { return std::numeric_limits<float>::infinity(); } return distF(lastElemPtr, query_point); } template<class Content, LineSegment Content::*line_member> class TreeNode { public: std::array<std::unique_ptr<TreeNode<Content, line_member>>, 2> children; Content content; union { Eigen::Vector3f d_bound; //carthesian struct { float m_component; //spherical uint8_t bound_component_idx; }; struct { float c1t1, c1t2; float c2t1, c2t2; }; }; NodeType type : 2; //uint8_t pad1 : 6; //uint8_t pad2[7]; TreeNode(uint8_t bound_component_idx, float m_component, Content content) : type(NodeType::moment), bound_component_idx(bound_component_idx), m_component(m_component), content(std::move(content)), children() {} TreeNode(Eigen::Vector3f d_bound, Content content) : type(NodeType::direction), d_bound(std::move(d_bound)), content(std::move(content)), children() {} TreeNode(float c1t1, float c1t2, float c2t1, float c2t2, Content content) : type(NodeType::t), c1t1(c1t1), c1t2(c1t2), c2t1(c2t1), c2t2(c2t2), content(std::move(content)), children() {} template<class OutputIt, typename = typename std::enable_if<std::is_same<const Content*, typename std::iterator_traits<OutputIt>::value_type>::value>::type> typename std::iterator_traits<OutputIt>::difference_type FindNeighbours( const Eigen::Vector3f& query_point, OutputIt out_first, OutputIt out_last, float& max_dist, const Bounds& bounds, const Eigen::Vector3f& moment_min_hint, float moment_min_hint_dist ) const { Diag::visited++; std::array<float, 2> minimumDistances {}; std::array<Bounds, 2> childBounds {}; std::array<Eigen::Vector3f, 2> childMomentMinima {}; for(int i = 0; i < 2; ++i) { const auto& c = children[i]; if(c == nullptr) { minimumDistances[i] = std::numeric_limits<float>::infinity(); } else { childBounds[i] = bounds; if(this->type == NodeType::moment) { if(i == 0) { childBounds[0].m_end[this->bound_component_idx] = m_component; }else { childBounds[1].m_start[this->bound_component_idx] = m_component; } if(childBounds[i].ContainsMoment(moment_min_hint)) { childMomentMinima[i] = moment_min_hint; minimumDistances[i] = moment_min_hint_dist; continue; } } else if(this->type == NodeType::direction) { if(i == 0) { childBounds[i].d_bound_1 = this->d_bound; childBounds[i].d_bound_2 = bounds.d_bound_2; }else { childBounds[i].d_bound_1 = bounds.d_bound_1; childBounds[i].d_bound_2 = -this->d_bound; } } else if(this->type == NodeType::t) { if(i == 0) { childBounds[i].t1Min = c1t1; childBounds[i].t2Max = c1t2; }else { childBounds[i].t1Min = c2t1; childBounds[i].t2Max = c2t2; } } childMomentMinima[i] = moment_min_hint; childBounds[i].Clip(childMomentMinima[i]); minimumDistances[i] = FindMinDist(query_point, childBounds[i].d_bound_1, childBounds[i].d_bound_2, childBounds[i].m_start, childBounds[i].m_end, childBounds[i].t1Min, childBounds[i].t2Max, childMomentMinima[i]); } } // permutation = indices of children, from smallest to largest min dist std::array<uint8_t, 2> permutation = {0, 1}; if(minimumDistances[0] > minimumDistances[1]) { std::swap(permutation[0], permutation[1]); } unsigned int nbResultsFound = 0; auto resultsListLength = std::distance(out_first, out_last); for(uint8_t idx : permutation) { if(minimumDistances[idx] > max_dist+margin || children[idx] == nullptr) //max_dist_check { break; } auto nbResultsInNode = children[idx]->FindNeighbours(query_point, out_first, out_last, max_dist, childBounds[idx], childMomentMinima[idx], minimumDistances[idx]); nbResultsFound = std::min(nbResultsFound + nbResultsInNode, resultsListLength); } auto distF = [](const Content* c, const Eigen::Vector3f& q) { const auto& s = c->*line_member; Eigen::Vector3f p = s.l.d.cross(s.l.m); float t = s.l.d.dot(q); t = std::min(std::max(t, s.t1), s.t2); Eigen::Vector3f v = (p + t*s.l.d) - q; return v.norm(); }; auto dist = distF(&content, query_point); if(dist < max_dist+margin) //max_dist_check { max_dist = insert(&content, out_first, out_last, query_point, distF); nbResultsFound++; } return nbResultsFound; } template<class OutputIt, typename = typename std::enable_if<std::is_same<const Content*, typename std::iterator_traits<OutputIt>::value_type>::value>::type> typename std::iterator_traits<OutputIt>::difference_type FindNearestHits( const Eigen::Vector3f& query_point, const Eigen::Vector3f& query_normal, OutputIt out_first, OutputIt out_last, float& max_dist, const Bounds& bounds, const Eigen::Vector3f& moment_min_hint, float moment_min_hint_dist ) const { Diag::visited++; std::array<float, 2> minimumDistances {}; std::array<Bounds, 2> childBounds {}; std::array<Eigen::Vector3f, 2> childMomentMinima {}; for(int i = 0; i < 2; ++i) { const auto& c = children[i]; if(c == nullptr) { minimumDistances[i] = std::numeric_limits<float>::infinity(); } else { childBounds[i] = bounds; if(this->type == NodeType::moment) { if(i == 0) { childBounds[0].m_end[this->bound_component_idx] = m_component; }else { childBounds[1].m_start[this->bound_component_idx] = m_component; } if(childBounds[i].ContainsMoment(moment_min_hint)) { childMomentMinima[i] = moment_min_hint; minimumDistances[i] = moment_min_hint_dist; continue; } } else if(this->type == NodeType::direction) { if(i == 0) { childBounds[i].d_bound_1 = this->d_bound; childBounds[i].d_bound_2 = bounds.d_bound_2; }else { childBounds[i].d_bound_1 = bounds.d_bound_1; childBounds[i].d_bound_2 = -this->d_bound; } } else if(this->type == NodeType::t) { if(i == 0) { childBounds[i].t1Min = c1t1; childBounds[i].t2Max = c1t2; }else { childBounds[i].t1Min = c2t1; childBounds[i].t2Max = c2t2; } } childMomentMinima[i] = moment_min_hint; childBounds[i].Clip(childMomentMinima[i]); minimumDistances[i] = FindMinDist(query_point, childBounds[i].d_bound_1, childBounds[i].d_bound_2, childBounds[i].m_start, childBounds[i].m_end, childBounds[i].t1Min, childBounds[i].t2Max, childMomentMinima[i]); } } // permutation = indices of children, from smallest to largest min dist std::array<uint8_t, 2> permutation = {0, 1}; if(minimumDistances[0] > minimumDistances[1]) { std::swap(permutation[0], permutation[1]); } unsigned int nbResultsFound = 0; auto resultsListLength = std::distance(out_first, out_last); for(uint8_t idx : permutation) { if(minimumDistances[idx] > max_dist+margin || children[idx] == nullptr) //max_dist_check { break; } auto nbResultsInNode = children[idx]->FindNearestHits(query_point, query_normal, out_first, out_last, max_dist, childBounds[idx], childMomentMinima[idx], minimumDistances[idx]); nbResultsFound = std::min(nbResultsFound + nbResultsInNode, resultsListLength); } auto distF = [&query_normal](const Content* c, const Eigen::Vector3f& q) { const auto& s = c->*line_member; Eigen::Vector3f l0 = (s.l.d.cross(s.l.m)); auto t = (q - l0).dot(query_normal)/(s.l.d.dot(query_normal)); if(t < s.t1 || t > s.t2) { return 1E99f; } Eigen::Vector3f intersection = l0 + (s.l.d * t); Eigen::Vector3f vect = intersection - q; return vect.norm(); }; auto dist = distF(&content, query_point); if(dist < max_dist+margin) //max_dist_check { max_dist = insert(&content, out_first, out_last, query_point, distF); nbResultsFound++; } return nbResultsFound; } }; template<typename Content, LineSegment Content::*line_member> class Tree { private: size_t _size; public: std::array<TreeSector<Content, line_member>, 32> sectors; explicit Tree(size_t size, std::array<TreeSector<Content, line_member>, 32> sectors) : _size(size), sectors(std::move(sectors)) {} size_t size() const { return _size; }; //void Add(const Line& line); //bool Remove(const Line* line); template<class OutputIt, typename = typename std::enable_if<std::is_same<const Content*, typename std::iterator_traits<OutputIt>::value_type>::value>::type> typename std::iterator_traits<OutputIt>::difference_type FindNeighbours( const Eigen::Vector3f& query_point, OutputIt out_first, OutputIt out_last, float& max_dist ) const { Diag::visited = 0; Diag::minimizations = 0; std::array<float, 32> minimumDistances {}; std::array<Eigen::Vector3f, 32> moment_min_hints {}; for(int i = 0; i < minimumDistances.size(); ++i) { const auto& sector = sectors[i]; if(sector.rootNode == nullptr) { minimumDistances[i] = std::numeric_limits<float>::infinity(); } else { moment_min_hints[i] = sector.bounds.m_start + (sector.bounds.m_end - sector.bounds.m_start)/2; minimumDistances[i] = FindMinDist(query_point, sector.bounds.d_bound_1, sector.bounds.d_bound_2, sector.bounds.m_start, sector.bounds.m_end, sector.bounds.t1Min, sector.bounds.t2Max, moment_min_hints[i]); } } std::array<uint8_t, 32> permutation {}; std::iota(permutation.begin(), permutation.end(), 0); std::sort(permutation.begin(), permutation.end(), [it = minimumDistances.begin()](uint8_t a, uint8_t b) { return *(it + a) < *(it + b); }); //Search through sectors[idx].rootNode, ignoring sectors/bins with a mindist larger than searchRadius //Insert each line found into the output list, keeping the list sorted by distance. // Discard the last element, or don't insert if the new element is larger than all current results. //Set searchradius to the largest distance in the results list unsigned int nbResultsFound = 0; auto resultsListLength = std::distance(out_first, out_last); for(uint8_t idx : permutation) { if(minimumDistances[idx] > max_dist+margin || sectors[idx].rootNode == nullptr) //max_dist_check { break; } const auto& curBounds = sectors[idx].bounds; auto nbResultsInNode = sectors[idx].rootNode->FindNeighbours( query_point, out_first, out_last, max_dist, curBounds, moment_min_hints[idx], minimumDistances[idx]); nbResultsFound = std::min(nbResultsFound + nbResultsInNode, resultsListLength); } //std::cout << "visited " << Diag::visited << "/" << size() << std::endl; return nbResultsFound; } template<class OutputIt, typename = typename std::enable_if<std::is_same<const Content*, typename std::iterator_traits<OutputIt>::value_type>::value>::type> typename std::iterator_traits<OutputIt>::difference_type FindNearestHits( const Eigen::Vector3f& query_point, const Eigen::Vector3f& query_normal, OutputIt out_first, OutputIt out_last, float& max_dist ) const { Diag::visited = 0; Diag::minimizations = 0; std::array<float, 32> minimumDistances {}; std::array<Eigen::Vector3f, 32> moment_min_hints {}; for(int i = 0; i < minimumDistances.size(); ++i) { const auto& sector = sectors[i]; if(sector.rootNode == nullptr) { minimumDistances[i] = std::numeric_limits<float>::infinity(); } else { moment_min_hints[i] = sector.bounds.m_start + (sector.bounds.m_end - sector.bounds.m_start)/2; //FindMinDist because no FindMinHitDist has been defined for line segments and FindMinDist will always return a lower value so no invalid results will be returned. minimumDistances[i] = FindMinDist(query_point, sector.bounds.d_bound_1, sector.bounds.d_bound_2, sector.bounds.m_start, sector.bounds.m_end, sector.bounds.t1Min, sector.bounds.t2Max, moment_min_hints[i]); } } std::array<uint8_t, 32> permutation {}; std::iota(permutation.begin(), permutation.end(), 0); std::sort(permutation.begin(), permutation.end(), [it = minimumDistances.begin()](uint8_t a, uint8_t b) { return *(it + a) < *(it + b); }); //Search through sectors[idx].rootNode, ignoring sectors/bins with a mindist larger than searchRadius //Insert each line found into the output list, keeping the list sorted by distance. // Discard the last element, or don't insert if the new element is larger than all current results. //Set searchradius to the largest distance in the results list unsigned int nbResultsFound = 0; auto resultsListLength = std::distance(out_first, out_last); for(uint8_t idx : permutation) { if(minimumDistances[idx] > max_dist+margin || sectors[idx].rootNode == nullptr) //max_dist_check { break; } const auto& curBounds = sectors[idx].bounds; auto nbResultsInNode = sectors[idx].rootNode->FindNearestHits( query_point, query_normal, out_first, out_last, max_dist, curBounds, moment_min_hints[idx], minimumDistances[idx]); nbResultsFound = std::min(nbResultsFound + nbResultsInNode, resultsListLength); } //std::cout << "visited " << Diag::visited << "/" << size() << std::endl; return nbResultsFound; } }; template<class Content, LineSegment Content::*line_member> class TreeBuilder { using Node = TreeNode<Content, line_member>; using Sector = TreeSector<Content, line_member>; private: template<class LineIt, typename = typename std::enable_if<std::is_same<Content, typename std::iterator_traits<LineIt>::value_type>::value>::type> static std::unique_ptr<Node> BuildNode(LineIt lines_begin, LineIt lines_end, const Bounds& bounds, int level) { auto lineCount = std::distance(lines_begin, lines_end); if(lineCount == 0) { return nullptr; }else if(lineCount == 1) { std::unique_ptr<Node> node = std::make_unique<Node>(0, ((*lines_begin).*line_member).l.m[0], *lines_begin); node->children[0] = nullptr; node->children[1] = nullptr; return node; } // Find axis with largest variance and split in 2 there std::unique_ptr<Node> node = nullptr; //NodeType type; uint8_t splitComponent = 0; Bounds subBounds1 = bounds; Bounds subBounds2 = bounds; LineIt pivot; /////////////////////////////// // Calculate directional variance // project direction vectors to bound domain, calculate variance of sine of angle to bound, and use this to decide NodeType const Eigen::Vector3f& cur_bound = bounds.d_bound_1; Eigen::Vector3f bound_domain_normal = bounds.d_bound_1.cross(bounds.d_bound_2).normalized(); if(bound_domain_normal.dot(bounds.m_start) < 0) { bound_domain_normal *= -1; } auto calc_sine = [](const Eigen::Vector3f& d, const Eigen::Vector3f& bound_domain_normal, const Eigen::Vector3f& cur_bound){ Eigen::Vector3f cross1 = (d - bound_domain_normal * bound_domain_normal.dot(d)).normalized().cross(cur_bound); auto sin = cross1.norm(); if(cross1.dot(bound_domain_normal) < 0) { sin *= -1; } return sin; }; /*auto dVariance = calc_pop_variance(lines_begin, lines_end, [&bound_domain_normal, &cur_bound, calc_sine](const Content& c){ const auto& line = (c.*line_member).l; return calc_sine(line.d, bound_domain_normal, cur_bound); }); auto dMaxSin = bounds.d_bound_1.cross(bounds.d_bound_2).norm(); auto dMaxPossibleVariance = (dMaxSin * dMaxSin)/4; //Assumes angle between bounds >= 90° auto dVarianceNormalized = dVariance / dMaxPossibleVariance;*/ /////////////////////////////// bool splitOnDir = false; bool splitOnT = false; /////////////////////////////// // Calculate max moment variance #define M_LEVEL_ALTERNATING #if defined(M_MAX_VAR) Eigen::Array3f mVarianceVect = calc_vec3_pop_variance(lines_begin, lines_end, [](const Content& c){return cart2spherical((c.*line_member).l.m); }); Eigen::Array3f mVarianceNormFact = (bounds.m_end - bounds.m_start).array(); mVarianceNormFact = mVarianceNormFact * mVarianceNormFact; mVarianceNormFact /= 4; mVarianceVect = mVarianceVect.cwiseQuotient(mVarianceNormFact); auto mVariance = mVarianceVect.maxCoeff(&splitComponent); // Calculate t variance auto t1Var = calc_pop_variance(lines_begin, lines_end, [](const Content& c){ return (c.*line_member).t1; }); auto t2Var = calc_pop_variance(lines_begin, lines_end, [](const Content& c){ return (c.*line_member).t2; }); auto tBoundDist = bounds.t2Max - bounds.t1Min; auto tVarNormalized = (t1Var+t2Var)*2 / (tBoundDist * tBoundDist); // ((t1Var+t2Var)/2)/(tBoundDist * tBoundDist)/4; splitOnT = tVarNormalized > dVarianceNormalized && tVarNormalized > mVariance; if(!splitOnT){ //splitOnDir = dVarianceNormalized > mVariance; splitOnDir = v < 0.25; } unsigned int pivot_i = lineCount/2; #elif defined(M_LEVEL_ALTERNATING) splitComponent = level % 5; splitOnDir = (level % 5) == 3; splitOnT = (level % 5) == 4; unsigned int pivot_i = lineCount/2; #endif if(splitOnT) { TSplitInfo<LineIt> splitInfo = SplitOnT(lines_begin, lines_end, bounds.t1Min, bounds.t2Max); pivot = splitInfo.pivot; //std::cout << "t split" << std::endl; subBounds1.t1Min = splitInfo.c1t1; subBounds1.t2Max = splitInfo.c1t2; subBounds2.t1Min = splitInfo.c2t1; subBounds2.t2Max = splitInfo.c2t2; node = std::make_unique<Node>(splitInfo.c1t1, splitInfo.c1t2, splitInfo.c2t1, splitInfo.c2t2, *pivot); node->children[0] = BuildNode(splitInfo.c1Begin, splitInfo.c2Begin, subBounds1, level + 1); node->children[1] = BuildNode(splitInfo.c2Begin, lines_end, subBounds2, level + 1); } else { if(splitOnDir) { // calculate new bound vector: calc cross product of dir vectors with cur bound vector to obtain sin, // sort by sin, take median, new bound vector is cross product of bound_domain_normal with median dir vect // Given bounds b1 and b2 in parent, and new bound vector nb, the childrens bounds are as follows: // child 1: {nb, b2}, child 2: {b1, -nb} std::sort(lines_begin, lines_end, [&cur_bound, &bound_domain_normal, calc_sine](const Content& c1, const Content& c2){ const auto& l1 = (c1.*line_member).l; const auto& l2 = (c2.*line_member).l; auto sin1 = calc_sine(l1.d, bound_domain_normal, cur_bound); auto sin2 = calc_sine(l2.d, bound_domain_normal, cur_bound); return sin1 < sin2; }); pivot = lines_begin + (lines_end - lines_begin)/2; const auto& pivotLine = ((*pivot).*line_member).l; Eigen::Vector3f dir_bound = bound_domain_normal.cross(pivotLine.d).normalized(); subBounds1.d_bound_1 = dir_bound; subBounds1.d_bound_2 = bounds.d_bound_2; subBounds2.d_bound_1 = bounds.d_bound_1; subBounds2.d_bound_2 = -dir_bound; node = std::make_unique<Node>(dir_bound, *pivot); } else { std::sort(lines_begin, lines_end, [splitComponent](const Content& c1, const Content& c2){ const auto& l1 = (c1.*line_member).l; const auto& l2 = (c2.*line_member).l; return cart2spherical(l1.m)[splitComponent] < cart2spherical(l2.m)[splitComponent]; }); pivot = lines_begin + pivot_i; const auto& pivotLine = ((*pivot).*line_member).l; auto splitCompVal = cart2spherical(pivotLine.m)[splitComponent]; subBounds1.m_end[splitComponent] = splitCompVal; subBounds2.m_start[splitComponent] = splitCompVal; node = std::make_unique<Node>(splitComponent, splitCompVal, *pivot); } // Store iterators and bounds and then recurse node->children[0] = BuildNode(lines_begin, pivot, subBounds1, level + 1); node->children[1] = BuildNode(pivot+1, lines_end, subBounds2, level + 1); } return std::move(node); } template<class LineIt> struct TSplitInfo { float c1t1, c1t2, c2t1, c2t2; LineIt pivot; LineIt c1Begin; LineIt c2Begin; TSplitInfo(float c1T1, float c1T2, float c2T1, float c2T2, LineIt pivot, LineIt c1Begin, LineIt c2Begin) : c1t1(c1T1), c1t2(c1T2), c2t1(c2T1), c2t2(c2T2), pivot(pivot), c1Begin(c1Begin), c2Begin(c2Begin) {} }; template<class LineIt, typename = typename std::enable_if<std::is_same<Content, typename std::iterator_traits<LineIt>::value_type>::value>::type> static TSplitInfo<LineIt> SplitOnT(LineIt lines_begin, LineIt lines_end, float t1Min, float t2Max) { LineIt pivot = std::min_element(lines_begin, lines_end, [domain=Eigen::Vector2f(t1Min, t2Max)](const Content& e1, const Content& e2){ const LineSegment& s1 = (e1.*line_member); const LineSegment& s2 = (e2.*line_member); Eigen::Vector2f s1T(s1.t1, s1.t2); Eigen::Vector2f s2T(s2.t1, s2.t2); return (s1T - domain).squaredNorm() < (s2T - domain).squaredNorm(); }); std::iter_swap(pivot, lines_begin); pivot = lines_begin; auto child_lines_begin = lines_begin+1; std::sort(child_lines_begin, lines_end, [](const Content& e1, const Content& e2){ const LineSegment& s1 = (e1.*line_member); const LineSegment& s2 = (e2.*line_member); return s1.t1 < s2.t1; }); float c1t1 = ((*child_lines_begin).*line_member).t1; float c1t2 = ((*child_lines_begin).*line_member).t2; float c2t1 = ((*lines_end).*line_member).t1; float c2t2 = ((*lines_end).*line_member).t2; auto lineCount = std::distance(child_lines_begin, lines_end); for(unsigned int i = 0; i < lineCount/2; ++i) { const LineSegment& curLeft = ((*(child_lines_begin+i)).*line_member); const LineSegment& curRight = ((*(lines_end-i-1)).*line_member); c1t2 = std::max(c1t2, curLeft.t2); c2t1 = std::min(c2t1, curRight.t1); c2t2 = std::max(c2t2, curRight.t2); } if(lineCount % 2 == 1) { auto idx = lineCount/2; const LineSegment& middle = ((*(child_lines_begin+idx)).*line_member); c2t1 = std::min(c2t1, middle.t1); c2t2 = std::max(c2t2, middle.t2); } LineIt c1Begin = child_lines_begin; LineIt c2Begin = c1Begin + (lineCount/2); return TSplitInfo(c1t1, c1t2, c2t1, c2t2, pivot, c1Begin, c2Begin); } public: template<class LineIt, typename = typename std::enable_if<std::is_same<Content, typename std::iterator_traits<LineIt>::value_type>::value>::type> static Tree<Content, line_member> Build(LineIt lines_first, LineIt lines_last) { // Create sectors using Eigen::Vector3f; constexpr float max_dist = 150; //TODO constexpr float min_dist = 1e-3; constexpr float min_t = -150; constexpr float max_t = 150; std::array<Sector, 32> sectors { // Top sector Sector(Vector3f(1, 0, 0), Vector3f(0, 1, 0), Vector3f(-M_PI, 0, min_dist), Vector3f(0, M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(0, 1, 0), Vector3f(-1, 0, 0), Vector3f(-M_PI, 0, min_dist), Vector3f(0, M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(-1, 0, 0), Vector3f(0, -1, 0), Vector3f(-M_PI, 0, min_dist), Vector3f(0, M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(0, -1, 0), Vector3f(1, 0, 0), Vector3f(-M_PI, 0, min_dist), Vector3f(0, M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(1, 0, 0), Vector3f(0, 1, 0), Vector3f(0, 0, min_dist), Vector3f(M_PI, M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(0, 1, 0), Vector3f(-1, 0, 0), Vector3f(0, 0, min_dist), Vector3f(M_PI, M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(-1, 0, 0), Vector3f(0, -1, 0), Vector3f(0, 0, min_dist), Vector3f(M_PI, M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(0, -1, 0), Vector3f(1, 0, 0), Vector3f(0, 0, min_dist), Vector3f(M_PI, M_PI/4, max_dist), min_t, max_t), // Bottom sector Sector(Vector3f(1, 0, 0), Vector3f(0, 1, 0), Vector3f(-M_PI, 3*M_PI/4, min_dist), Vector3f(0, M_PI, max_dist), min_t, max_t), Sector(Vector3f(0, 1, 0), Vector3f(-1, 0, 0), Vector3f(-M_PI, 3*M_PI/4, min_dist), Vector3f(0, M_PI, max_dist), min_t, max_t), Sector(Vector3f(-1, 0, 0), Vector3f(0, -1, 0), Vector3f(-M_PI, 3*M_PI/4, min_dist), Vector3f(0, M_PI, max_dist), min_t, max_t), Sector(Vector3f(0, -1, 0), Vector3f(1, 0, 0), Vector3f(-M_PI, 3*M_PI/4, min_dist), Vector3f(0, M_PI, max_dist), min_t, max_t), Sector(Vector3f(1, 0, 0), Vector3f(0, 1, 0), Vector3f(0, 3*M_PI/4, min_dist), Vector3f(M_PI, M_PI, max_dist), min_t, max_t), Sector(Vector3f(0, 1, 0), Vector3f(-1, 0, 0), Vector3f(0, 3*M_PI/4, min_dist), Vector3f(M_PI, M_PI, max_dist), min_t, max_t), Sector(Vector3f(-1, 0, 0), Vector3f(0, -1, 0), Vector3f(0, 3*M_PI/4, min_dist), Vector3f(M_PI, M_PI, max_dist), min_t, max_t), Sector(Vector3f(0, -1, 0), Vector3f(1, 0, 0), Vector3f(0, 3*M_PI/4, min_dist), Vector3f(M_PI, M_PI, max_dist), min_t, max_t), // -X -Y sector Sector(Vector3f(0, 0, 1), Vector3f(1, -1, 0).normalized(), Vector3f(-M_PI, M_PI/4, min_dist), Vector3f(-M_PI/2, 3*M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(1, -1, 0).normalized(), Vector3f(0, 0, -1), Vector3f(-M_PI, M_PI/4, min_dist), Vector3f(-M_PI/2, 3*M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(0, 0, -1), Vector3f(-1, 1, 0).normalized(), Vector3f(-M_PI, M_PI/4, min_dist), Vector3f(-M_PI/2, 3*M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(-1, 1, 0).normalized(), Vector3f(0, 0, 1), Vector3f(-M_PI, M_PI/4, min_dist), Vector3f(-M_PI/2, 3*M_PI/4, max_dist), min_t, max_t), // +X -Y sector Sector(Vector3f(0, 0, 1), Vector3f(-1, -1, 0).normalized(), Vector3f(-M_PI/2, M_PI/4, min_dist), Vector3f(0, 3*M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(-1, -1, 0).normalized(), Vector3f(0, 0, -1), Vector3f(-M_PI/2, M_PI/4, min_dist), Vector3f(0, 3*M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(0, 0, -1), Vector3f(1, 1, 0).normalized(), Vector3f(-M_PI/2, M_PI/4, min_dist), Vector3f(0, 3*M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(1, 1, 0).normalized(), Vector3f(0, 0, 1), Vector3f(-M_PI/2, M_PI/4, min_dist), Vector3f(0, 3*M_PI/4, max_dist), min_t, max_t), // +X +Y sector Sector(Vector3f(0, 0, 1), Vector3f(1, -1, 0).normalized(), Vector3f(0, M_PI/4, min_dist), Vector3f(M_PI/2, 3*M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(1, -1, 0).normalized(), Vector3f(0, 0, -1), Vector3f(0, M_PI/4, min_dist), Vector3f(M_PI/2, 3*M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(0, 0, -1), Vector3f(-1, 1, 0).normalized(), Vector3f(0, M_PI/4, min_dist), Vector3f(M_PI/2, 3*M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(-1, 1, 0).normalized(), Vector3f(0, 0, 1), Vector3f(0, M_PI/4, min_dist), Vector3f(M_PI/2, 3*M_PI/4, max_dist), min_t, max_t), // -X +Y sector Sector(Vector3f(0, 0, 1), Vector3f(-1, -1, 0).normalized(), Vector3f(M_PI/2, M_PI/4, min_dist), Vector3f(M_PI, 3*M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(-1, -1, 0).normalized(), Vector3f(0, 0, -1), Vector3f(M_PI/2, M_PI/4, min_dist), Vector3f(M_PI, 3*M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(0, 0, -1), Vector3f(1, 1, 0).normalized(), Vector3f(M_PI/2, M_PI/4, min_dist), Vector3f(M_PI, 3*M_PI/4, max_dist), min_t, max_t), Sector(Vector3f(1, 1, 0).normalized(), Vector3f(0, 0, 1), Vector3f(M_PI/2, M_PI/4, min_dist), Vector3f(M_PI, 3*M_PI/4, max_dist), min_t, max_t) }; auto nbLines = std::distance(lines_first, lines_last); // Sort lines into sectors std::array<LineIt, 32> line_sector_ends; { LineIt it_begin = lines_first; int idx = 0; for(Sector& sector : sectors) { for(LineIt it = it_begin; it < lines_last; ++it) { const auto& line = (*it).*line_member; if(sector.bounds.ContainsMoment(cart2spherical(line.l.m)) && sector.bounds.d_bound_1.dot(line.l.d) >= 0 //greater or equal, or just greater? && sector.bounds.d_bound_2.dot(line.l.d) >= 0) { std::iter_swap(it_begin, it); it_begin++; } } line_sector_ends[idx] = it_begin; idx++; } } // Subdivide sectors into bins { LineIt it_begin = lines_first; int idx = 0; for(Sector& sector : sectors) { LineIt it_end = line_sector_ends[idx]; auto count = std::distance(it_begin, it_end); sector.rootNode = BuildNode(it_begin, it_end, sector.bounds, 0); it_begin = it_end; idx++; } } return Tree<Content, line_member>(nbLines, std::move(sectors)); } }; } <file_sep>/tests/DataSetGenerator.cpp #include "DataSetGenerator.h" #include <fstream> #include <Eigen/Dense> std::vector<LineWrapper> LoadFromFile(const std::string& filename) { std::vector<LineWrapper> result; std::ifstream in(filename); std::string line; while (std::getline(in, line)) { std::istringstream iss(line); char sep; Eigen::Vector3f m, d; if (!(iss >> m.x() >> sep >> m.y()>> sep >> m.z() >> sep >> d.x() >> sep >> d.y() >> sep >> d.z())) { break; } // error result.emplace_back(Line(d, m)); } return result; } std::vector<LineWrapper> GenerateRandomLines(unsigned int seed, unsigned int lineCount, float maxDist) { std::vector<LineWrapper> lines{}; lines.reserve(lineCount); std::default_random_engine rng{seed}; std::uniform_real_distribution<float> dist(-maxDist, maxDist); for (int i = 0; i < lineCount; ++i) { Line l(Vector3f::Zero(), Vector3f::Zero()); do { l = Line::FromTwoPoints( Vector3f(dist(rng), dist(rng), dist(rng)), Vector3f(dist(rng), dist(rng), dist(rng)) ); }while(l.m.norm() >= 150); lines.emplace_back(l); } return lines; } std::vector<LineWrapper> SampleRandomLines(const std::vector<LineWrapper>& all_lines, unsigned int seed, unsigned int lineCount) { if(lineCount > all_lines.size()) { throw std::runtime_error("Not enough lines in dataset"); } std::vector<LineWrapper> lines = all_lines; auto lines_new_end = lines.end(); std::default_random_engine rng{seed}; auto nbLinesToRemove = all_lines.size() - lineCount; for (std::vector<LineWrapper>::size_type i = 0; i < nbLinesToRemove; ++i) { std::uniform_int_distribution<std::vector<LineWrapper>::size_type> rand_i(0, std::distance(lines.begin(), lines_new_end)-1); std::iter_swap(lines.begin() + rand_i(rng), lines_new_end-1); lines_new_end--; } lines.erase(lines_new_end, lines.end()); return lines; } std::vector<LineWrapper> GenerateParallelLines(unsigned int seed, unsigned int lineCount, float maxDist, const Vector3f& direction) { std::vector<LineWrapper> lines{}; lines.reserve(lineCount); std::default_random_engine rng{seed}; std::uniform_real_distribution<float> dist(0, maxDist); for (int i = 0; i < lineCount; ++i) { Line l(Vector3f::Zero(), Vector3f::Zero()); do { l = Line::FromPointAndDirection( Vector3f(dist(rng), dist(rng), dist(rng)), direction ); }while(l.m.norm() >= 150); lines.emplace_back(l); } return lines; } std::vector<LineWrapper> GenerateEquiDistantLines(unsigned int seed, unsigned int lineCount, float distance) { std::vector<LineWrapper> lines{}; lines.reserve(lineCount); std::default_random_engine rng{seed}; std::uniform_real_distribution<float> dist(0, 1.0); for (int i = 0; i < lineCount; ++i) { // Generate point p which line runs through Vector3f p_hat = Vector3f(dist(rng), dist(rng), dist(rng)); p_hat.normalize(); // Generate random directional vector, orthogonal to p Vector3f d = Vector3f(dist(rng), dist(rng), dist(rng)); d -= p_hat * p_hat.dot(d); d.normalize(); Vector3f m = p_hat.cross(d) * distance; lines.emplace_back(Line(d, m)); } return lines; } std::vector<LineWrapper> GenerateEqualMomentLines(unsigned int seed, unsigned int lineCount, const Vector3f& moment) { std::vector<LineWrapper> lines{}; lines.reserve(lineCount); std::default_random_engine rng{seed}; std::uniform_real_distribution<float> unitDist(0, 1.0f); Vector3f moment_d = moment.normalized(); Vector3f baseU = Vector3f(unitDist(rng), unitDist(rng), unitDist(rng)); baseU -= moment_d * moment_d.dot(baseU); baseU.normalize(); Vector3f baseV = baseU.cross(moment_d); for (int i = 0; i < lineCount; ++i) { float angle = unitDist(rng) * 2.0f * M_PI; Vector3f d = std::sin(angle) * baseU + std::cos(angle) * baseV; lines.emplace_back(Line(d, moment)); } return lines; } std::vector<LineSegmentWrapper> GenerateRandomLineSegments(unsigned int seed, unsigned int lineCount, float maxDist, float minT, float maxT) { std::vector<LineSegmentWrapper> lines{}; lines.reserve(lineCount); std::default_random_engine rng{seed}; std::uniform_real_distribution<float> dist(0, maxDist); std::uniform_real_distribution<float> distT(minT, maxT); for (int i = 0; i < lineCount; ++i) { LineSegment l(Line(Vector3f::Zero(), Vector3f::Zero()), 0, 0); do { float t1 = distT(rng); float t2 = distT(rng); if(t1 > t2) { std::swap(t1, t2); } l = LineSegment(Line::FromTwoPoints( Vector3f(dist(rng), dist(rng), dist(rng)), Vector3f(dist(rng), dist(rng), dist(rng)) ), t1, t2); }while(l.l.m.norm() >= 150); lines.emplace_back(l); } return lines; } void ModifyLineSegmentLength(std::vector<LineSegmentWrapper>& l, float length) { float half_length = length/2.0f; for(auto& s : l) { float mid = (s.l.t2 - s.l.t1)/2.0f; s.l.t1 = mid - half_length; s.l.t2 = mid + half_length; } } std::vector<Vector3f> GenerateRandomPoints(unsigned int seed, unsigned int pointCount, float maxDist) { std::vector<Vector3f> queryPoints{}; queryPoints.reserve(pointCount); std::default_random_engine rng{seed}; std::uniform_real_distribution<float> dist(0, maxDist); for (int query_i = 0; query_i < pointCount; ++query_i) { queryPoints.emplace_back(dist(rng), dist(rng), dist(rng)); } return queryPoints; } std::vector<Vector3f> GenerateRandomNormals(unsigned int seed, unsigned int normalCount) { std::vector<Vector3f> query_point_normals {}; query_point_normals.reserve(normalCount); std::default_random_engine rng {seed+1}; std::uniform_real_distribution<float> dist(0, 1); for(int i = 0; i < normalCount; ++i) { query_point_normals.emplace_back(dist(rng), dist(rng), dist(rng)); query_point_normals.back().normalize(); } return query_point_normals; }<file_sep>/src/pluckertree/RegionDistanceMinimizer.cpp #include <LBFGSB.h> #include <vector> #include <iostream> #include <Eigen/Dense> #include <MathUtil.h> #include <fstream> #include <iomanip> #include <nlopt.hpp> #include <Pluckertree.h> #include <PluckertreeSegments.h> using namespace LBFGSpp; using Vector = Eigen::VectorXd; class FixedMomentMinDist { private: using number_t = double; using Vector3_t = Eigen::Vector3d; using Vector2_t = Eigen::Vector2d; using Matrix3_t = Eigen::Matrix3d; Vector3_t q; Vector3_t h1; Vector3_t h2; public: FixedMomentMinDist(Vector3_t q, Vector3_t dirLowerBound, Vector3_t dirUpperBound) : q(std::move(q)), h1(std::move(dirLowerBound)), h2(std::move(dirUpperBound)) {} double operator()(const Vector& x, Vector& grad) { // Careful, don't disturb the big pile of math! number_t phi_k = x[0]; number_t theta_k = x[1]; number_t r_k = x[2]; // f(k) Vector3_t k = spherical2cart(phi_k, theta_k, r_k); Vector3_t kd = k / r_k; Vector3_t qp = q - kd*(q.dot(kd)); Vector3_t qpd = qp.normalized(); auto u = (qp - q).norm(); auto sin_gamma = std::min(r_k/qp.norm(), (number_t)1.0f); auto cos_gamma = std::sqrt(1 - sin_gamma * sin_gamma); Vector3_t da = qpd * cos_gamma + kd.cross(qpd) * sin_gamma; Vector3_t d_alpha; auto da_dot_h1 = da.dot(h1); auto da_dot_h2 = da.dot(h2); if(da_dot_h1 >= 0 && da_dot_h2 >= 0) { d_alpha = da; }else if(da_dot_h1 <= da_dot_h2) { Vector h1_cross_k = h1.cross(k); d_alpha = std::copysign(1.0f, h2.dot(h1_cross_k)) * h1_cross_k.normalized(); }else { Vector h2_cross_k = h2.cross(k); d_alpha = std::copysign(1.0f, h1.dot(h2_cross_k)) * h2_cross_k.normalized(); } Vector3_t db = - qpd * cos_gamma + kd.cross(qpd) * sin_gamma; Vector3_t d_beta; auto db_dot_h1 = db.dot(h1); auto db_dot_h2 = db.dot(h2); if(db_dot_h1 >= 0 && db_dot_h2 >= 0) { d_beta = db; }else if(db_dot_h1 < db_dot_h2) { Vector h1_cross_k = h1.cross(k); d_beta = std::copysign(1.0f, h2.dot(h1_cross_k)) * h1_cross_k.normalized(); }else { Vector h2_cross_k = h2.cross(k); d_beta = std::copysign(1.0f, h1.dot(h2_cross_k)) * h2_cross_k.normalized(); } auto va = (qp.cross(d_alpha) - k).norm(); auto vb = (qp.cross(d_beta) - k).norm(); auto v = std::min(va, vb); auto f = std::sqrt(u*u + v*v); // partial /*auto sin_theta_k = std::sin(theta_k); auto pow2_sin_theta_k = sin_theta_k * sin_theta_k; auto sin_2theta_k = std::sin(2*theta_k); auto cos_theta_k = std::cos(theta_k); auto cos_2theta_k = std::cos(2*theta_k); auto pow2_cos_theta_k = cos_theta_k * cos_theta_k; auto sin_phi_k = std::sin(phi_k); auto pow2_sin_phi_k = sin_phi_k * sin_phi_k; auto sin_2phi_k = std::sin(2*phi_k); auto cos_phi_k = std::cos(phi_k); auto cos_2phi_k = std::cos(2*phi_k); auto pow2_cos_phi_k = cos_phi_k * cos_phi_k; /// auto partial_k_phi_k = r_k * Vector3_t(sin_theta_k * (-sin_phi_k), sin_theta_k * cos_phi_k, cos_theta_k); auto partial_k_theta_k = r_k * Vector3_t(cos_theta_k * cos_phi_k, cos_theta_k * sin_phi_k, (-sin_theta_k)); auto partial_k_r_k = Vector3_t(sin_theta_k * cos_phi_k, sin_theta_k * sin_phi_k, cos_theta_k); Matrix3_t partial_k; partial_k.row(0) = partial_k_phi_k; partial_k.row(1) = partial_k_theta_k; partial_k.row(2) = partial_k_r_k; /// auto k_norm = k.norm(); Matrix3_t partial_kd; for(int i = 0; i < 3; ++i) { partial_kd.row(i) = (partial_k.row(i)/k_norm) - k.transpose() * ((-1/(std::pow(k_norm, 3))) * (k.x() * partial_k.row(i).x() + k.y() * partial_k.row(i).y() + k.z() * partial_k.row(i).z())); } /// Matrix3_t partial_qp; for(int i = 0; i < 3; ++i) { partial_qp.row(i).x() = q.x() * 2 * kd.x() * partial_kd.row(i).x(); partial_qp.row(i).x() += q.y() * (partial_kd.row(i).x() * kd.y() + kd.x() * partial_kd.row(i).y()); partial_qp.row(i).x() += q.z() * (partial_kd.row(i).x() * kd.z() + kd.x() * partial_kd.row(i).z()); partial_qp.row(i).y() = q.x() * (partial_kd.row(i).y() * kd.x() + kd.y() * partial_kd.row(i).x()); partial_qp.row(i).y() += q.y() * 2 * kd.y() * partial_kd.row(i).y(); partial_qp.row(i).y() += q.z() * (partial_kd.row(i).y() * kd.z() + kd.y() * partial_kd.row(i).z()); partial_qp.row(i).z() = q.x() * (partial_kd.row(i).z() * kd.x() + kd.z() * partial_kd.row(i).x()); partial_qp.row(i).z() += q.y() * (partial_kd.row(i).z() * kd.y() + kd.z() * partial_kd.row(i).y()); partial_qp.row(i).z() += q.z() * 2 * kd.z() * partial_kd.row(i).z(); partial_qp.row(i) *= -1; } /// //auto partial_pow2_u_phi_k = 2*(qp.x() - q.x()) * partial_qp_phi_k.x() + 2*(qp.y() - q.y()) * partial_qp_phi_k.y() + 2*(qp.z() - q.z()) * partial_qp_phi_k.z(); auto partial_pow2_u = 2 * (partial_qp * (qp - q)); auto da_xy_norm = Eigen::Vector2f(da.x(), da.y()).norm(); auto qp_norm = qp.norm(); //double partial_delta_phi_k = (1/qp_norm) * (qp.x() * partial_qp_phi_k.x() + qp.y() * partial_qp_phi_k.y() + qp.z() * partial_qp_phi_k.z()); Vector3_t partial_delta; for(int i = 0; i < 3; i++) { partial_delta[i] = (1/qp_norm) * (qp.x() * partial_qp.row(i).x() + qp.y() * partial_qp.row(i).y() + qp.z() * partial_qp.row(i).z()); } Matrix3_t partial_qpd; for(int i = 0; i < 3; i++) { partial_qpd.row(i) = (partial_qp.row(i)/qp_norm) + qp.transpose() * (-1/qp.squaredNorm()) * partial_delta[i]; } Vector3_t partial_sin_gamma(0, 0, 0); //double partial_sin_gamma_phi_k = 1; if(r_k/qp_norm > 1) { for(int i = 0; i < 3; i++) { partial_sin_gamma[i] = -(r_k/qp.squaredNorm()) * partial_delta[i]; //TODO: is this wrong for i=2? //partial_sin_gamma_phi_k = -(r_k/qp.squaredNorm()) * partial_delta_phi_k; } } Vector3_t partial_cos_gamma; for(int i = 0; i < 3; i++) { //TODO partial_cos_gamma[i] = (1/std::sqrt(1-sin_gamma*sin_gamma)) * (-sin_gamma * partial_sin_gamma[i]); } Matrix3_t partial_da = Matrix3_t::Zero(); float sign = 1.0f; if(va >= vb) { sign = -1.0f; //partial_db } for(int i = 0; i < 3; i++) { partial_da.row(i).x() += sign * partial_qpd.row(i).x() * cos_gamma + qpd.x() * partial_cos_gamma[i]; partial_da.row(i).y() += sign * partial_qpd.row(i).y() * cos_gamma + qpd.x() * partial_cos_gamma[i]; partial_da.row(i).z() += sign * partial_qpd.row(i).z() * cos_gamma + qpd.z() * partial_cos_gamma[i]; partial_da.row(i).x() += partial_kd.row(i).y() * qpd.z() * sin_gamma + kd.y() * partial_qpd.row(i).z() * sin_gamma + kd.y() * qpd.z() * partial_sin_gamma[i]; partial_da.row(i).y() += partial_kd.row(i).x() * qpd.z() * sin_gamma + kd.x() * partial_qpd.row(i).z() * sin_gamma + kd.x() * qpd.z() * partial_sin_gamma[i]; partial_da.row(i).z() += partial_kd.row(i).x() * qpd.y() * sin_gamma + kd.x() * partial_qpd.row(i).y() * sin_gamma + kd.x() * qpd.y() * partial_sin_gamma[i]; partial_da.row(i).x() += partial_kd.row(i).z() * qpd.y() * sin_gamma + kd.z() * partial_qpd.row(i).y() * sin_gamma + kd.z() * qpd.y() * partial_sin_gamma[i]; partial_da.row(i).y() += partial_kd.row(i).z() * qpd.x() * sin_gamma + kd.z() * partial_qpd.row(i).x() * sin_gamma + kd.z() * qpd.x() * partial_sin_gamma[i]; partial_da.row(i).z() += partial_kd.row(i).y() * qpd.x() * sin_gamma + kd.y() * partial_qpd.row(i).x() * sin_gamma + kd.y() * qpd.x() * partial_sin_gamma[i]; } Matrix3_t partial_d_alpha; //also partial_d_beta, depending on va >= vb if(da_dot_h1 >= 0 && da_dot_h2 >= 0) { partial_d_alpha = partial_da; }else if(da_dot_h1 < da_dot_h2 || (da_dot_h1 == da_dot_h2 && va < vb)) { for(int i = 0; i < 3; i++) { auto h1_cross_k_sqr_norm = h1.cross(k).squaredNorm(); auto h1_cross_k_norm = std::sqrt(h1_cross_k_sqr_norm); auto partial_h1_cross_k_norm = (h1.y()*k.z() - h1.z()*k.y())*(h1.y()*partial_k.row(i).z() - h1.z()*partial_k.row(i).y()); partial_h1_cross_k_norm += (h1.x()*k.z() - h1.z()*k.x())*(h1.x()*partial_k.row(i).z() - h1.z()*partial_k.row(i).x()); partial_h1_cross_k_norm += (h1.x()*k.y() - h1.y()*k.x())*(h1.x()*partial_k.row(i).y() - h1.y()*partial_k.row(i).x()); partial_h1_cross_k_norm *= (1.0/h1_cross_k_norm); auto fact = std::copysign(1.0, k.dot(h2.cross(h1))) / h1_cross_k_sqr_norm; partial_d_alpha.row(i).x() = h1_cross_k_norm * (h1.y() * partial_k.row(i).z() - h1.z() * partial_k.row(i).y()); partial_d_alpha.row(i).x() -= partial_h1_cross_k_norm * (h1.y() * k.z() - h1.z() * k.y()); partial_d_alpha.row(i).y() = h1_cross_k_norm * (h1.x() * partial_k.row(i).z() - h1.z() * partial_k.row(i).x()); partial_d_alpha.row(i).y() -= partial_h1_cross_k_norm * (h1.x() * k.z() - h1.z() * k.x()); partial_d_alpha.row(i).z() = h1_cross_k_norm * (h1.x() * partial_k.row(i).y() - h1.y() * partial_k.row(i).x()); partial_d_alpha.row(i).z() -= partial_h1_cross_k_norm * (h1.x() * k.y() - h1.y() * k.x()); partial_d_alpha.row(i) *= fact; } }else { for(int i = 0; i < 3; i++) { auto h2_cross_k_sqr_norm = h2.cross(k).squaredNorm(); auto h2_cross_k_norm = std::sqrt(h2_cross_k_sqr_norm); auto partial_h2_cross_k_norm = (h1.y()*k.z() - h2.z()*k.y())*(h2.y()*partial_k.row(i).z() - h2.z()*partial_k.row(i).y()); partial_h2_cross_k_norm += (h2.x()*k.z() - h2.z()*k.x())*(h2.x()*partial_k.row(i).z() - h2.z()*partial_k.row(i).x()); partial_h2_cross_k_norm += (h2.x()*k.y() - h2.y()*k.x())*(h2.x()*partial_k.row(i).y() - h2.y()*partial_k.row(i).x()); partial_h2_cross_k_norm *= (1.0/h2_cross_k_norm); auto fact = std::copysign(1.0, k.dot(h2.cross(h1))) / h2_cross_k_sqr_norm; partial_d_alpha.row(i).x() = h2_cross_k_norm * (h2.y() * partial_k.row(i).z() - h2.z() * partial_k.row(i).y()); partial_d_alpha.row(i).x() -= partial_h2_cross_k_norm * (h2.y() * k.z() - h2.z() * k.y()); partial_d_alpha.row(i).y() = h2_cross_k_norm * (h2.x() * partial_k.row(i).z() - h2.z() * partial_k.row(i).x()); partial_d_alpha.row(i).y() -= partial_h2_cross_k_norm * (h2.x() * k.z() - h2.z() * k.x()); partial_d_alpha.row(i).z() = h2_cross_k_norm * (h2.x() * partial_k.row(i).y() - h2.y() * partial_k.row(i).x()); partial_d_alpha.row(i).z() -= partial_h2_cross_k_norm * (h2.x() * k.y() - h2.y() * k.x()); partial_d_alpha.row(i) *= fact; } } //// auto c_alpha = qp.cross(da); Matrix3_t partial_c_alpha; for(int i = 0; i < 3; i++) { partial_c_alpha.row(i) = Vector3_t( (partial_qp.row(i).y()*d_alpha.z() + qp.y() * partial_d_alpha.row(i).z()) - (partial_qp.row(i).z()*d_alpha.y() + qp.z()*partial_d_alpha.row(i).y()), (partial_qp.row(i).x()*d_alpha.z() + qp.x() * partial_d_alpha.row(i).z()) - (partial_qp.row(i).z()*d_alpha.x() + qp.z()*partial_d_alpha.row(i).x()), (partial_qp.row(i).x()*d_alpha.y() + qp.x() * partial_d_alpha.row(i).y()) - (partial_qp.row(i).y()*d_alpha.x() + qp.y()*partial_d_alpha.row(i).x()) ); } Vector3_t partial_v; for(int i = 0; i < 3; i++) { partial_v[i] = (1.0/va) * ( (c_alpha.x() - k.x()) * (partial_c_alpha.row(i).x() - partial_k.row(i).x()) + (c_alpha.y() - k.y()) * (partial_c_alpha.row(i).y() - partial_k.row(i).y()) + (c_alpha.z() - k.z()) * (partial_c_alpha.row(i).z() - partial_k.row(i).z()) ); } Vector3_t partial_pow2_v = 2*va*partial_v; grad = (1.0/(2.0*std::sqrt(u*u + v*v))) * (partial_pow2_u + partial_pow2_v); /*assert(!grad.hasNaN()); assert(!std::isinf(grad[0])); assert(!std::isinf(grad[1])); assert(!std::isinf(grad[2]));*/ return f; } }; class FixedMomentMinHitDist { private: using number_t = double; using Vector3_t = Eigen::Vector3d; using Vector2_t = Eigen::Vector2d; using Matrix3_t = Eigen::Matrix3d; Vector3_t q; Vector3_t q_n; Vector3_t h1; Vector3_t h2; public: FixedMomentMinHitDist(Vector3_t q, Vector3_t q_n, Vector3_t dirLowerBound, Vector3_t dirUpperBound) : q(std::move(q)), q_n(std::move(q_n)), h1(std::move(dirLowerBound)), h2(std::move(dirUpperBound)) {} double operator()(const Vector& x, Vector& grad) { // Careful, don't disturb the big pile of math! number_t phi_k = x[0]; number_t theta_k = x[1]; number_t r_k = x[2]; // f(k) Vector3_t k = spherical2cart(phi_k, theta_k, r_k); Vector3_t kd = k.normalized(); //Find intersection line of directionvector plane with query plane Vector3_t kd_cross_qn = kd.cross(q_n); auto kd_cross_qn_norm = kd_cross_qn.norm(); if(kd_cross_qn_norm < 1e-6) // All lines are parallel to the query plane, assume all miss. { return std::numeric_limits<double>::infinity(); } Vector3_t isect_d = kd_cross_qn / kd_cross_qn_norm; Vector3_t isect_k = kd * (q_n.dot(q)/kd_cross_qn_norm); Vector3_t isect_p = isect_d.cross(isect_k); Vector3_t qpl = isect_p + isect_d * isect_d.dot(q - isect_p); Vector3_t qpld = qpl.normalized(); auto sin_gamma = std::min(r_k/qpl.norm(), (number_t)1.0f); auto cos_gamma = std::sqrt(1 - sin_gamma * sin_gamma); Vector3_t da = qpld * cos_gamma + kd.cross(qpld) * sin_gamma; Vector3_t d_alpha; auto da_dot_h1 = da.dot(h1); auto da_dot_h2 = da.dot(h2); if(da_dot_h1 >= 0 && da_dot_h2 >= 0) { d_alpha = da; }else if(da_dot_h1 <= da_dot_h2) { Vector h1_cross_k = h1.cross(k); d_alpha = std::copysign(1.0f, h2.dot(h1_cross_k)) * h1_cross_k.normalized(); }else { Vector h2_cross_k = h2.cross(k); d_alpha = std::copysign(1.0f, h1.dot(h2_cross_k)) * h2_cross_k.normalized(); } Vector3_t db = - qpld * cos_gamma + kd.cross(qpld) * sin_gamma; Vector3_t d_beta; auto db_dot_h1 = db.dot(h1); auto db_dot_h2 = db.dot(h2); if(db_dot_h1 >= 0 && db_dot_h2 >= 0) { d_beta = db; }else if(db_dot_h1 < db_dot_h2) { Vector h1_cross_k = h1.cross(k); d_beta = std::copysign(1.0f, h2.dot(h1_cross_k)) * h1_cross_k.normalized(); }else { Vector h2_cross_k = h2.cross(k); d_beta = std::copysign(1.0f, h1.dot(h2_cross_k)) * h2_cross_k.normalized(); } //Calculate intersection point of isect line with (d;k) number_t va = std::numeric_limits<double>::infinity(); if(1 - std::abs(d_alpha.dot(isect_d)) > 1e-3) { Vector3_t isect_d_cross_d_alpha = isect_d.cross(d_alpha); Vector3_t vp_a = (1.0/isect_d.cross(d_alpha).squaredNorm()) * (isect_d * (k.dot(isect_d_cross_d_alpha)) - d_alpha * (isect_k.dot(isect_d_cross_d_alpha))); va = (q - vp_a).norm(); } number_t vb = std::numeric_limits<double>::infinity(); if(1 - std::abs(d_beta.dot(isect_d)) > 1e-3) { Vector3_t isect_d_cross_d_beta = isect_d.cross(d_beta); Vector3_t vp_b = (1.0/isect_d.cross(d_beta).squaredNorm()) * (isect_d * (k.dot(isect_d_cross_d_beta)) - d_beta * (isect_k.dot(isect_d_cross_d_beta))); vb = (q - vp_b).norm(); } auto v = std::min(va, vb); if(std::isinf(v)) { return std::numeric_limits<double>::infinity(); } return v; } }; class FixedMomentMinSegmentDist { private: using number_t = double; using Vector3_t = Eigen::Vector3d; using Vector2_t = Eigen::Vector2d; using Matrix3_t = Eigen::Matrix3d; Vector3_t q; Vector3_t h1; Vector3_t h2; float t1; float t2; public: FixedMomentMinSegmentDist(Vector3_t q, Vector3_t dirLowerBound, Vector3_t dirUpperBound, float t1, float t2) : q(std::move(q)), h1(std::move(dirLowerBound)), h2(std::move(dirUpperBound)), t1(t1), t2(t2) {} double operator()(const Vector& x, Vector& grad) { number_t phi_k = x[0]; number_t theta_k = x[1]; number_t r_k = x[2]; // f(k) Vector3_t k = spherical2cart(phi_k, theta_k, r_k); Vector3_t kd = k / r_k; Vector3_t qp = q - kd*(q.dot(kd)); auto qp_norm = qp.norm(); Vector3_t qpd = qp / qp_norm; auto u = (qp - q).norm(); auto calc_dist_for_gamma = [](const Vector3_t& qp, const Vector3_t& qpd, const Vector3_t& k, const Vector3_t& kd, const Vector3_t& h1, const Vector3_t& h2, number_t orientation, number_t sin_gamma, number_t t1, number_t t2) { auto cos_gamma = std::sqrt(1 - sin_gamma * sin_gamma); Vector3_t da = orientation * qpd * cos_gamma + kd.cross(qpd) * sin_gamma; Vector3_t d_alpha; auto da_dot_h1 = da.dot(h1); auto da_dot_h2 = da.dot(h2); if(da_dot_h1 >= 0 && da_dot_h2 >= 0) { d_alpha = da; }else if(da_dot_h1 <= da_dot_h2) { Vector h1_cross_k = h1.cross(k); d_alpha = std::copysign(1.0f, h2.dot(h1_cross_k)) * h1_cross_k.normalized(); }else { Vector h2_cross_k = h2.cross(k); d_alpha = std::copysign(1.0f, h1.dot(h2_cross_k)) * h2_cross_k.normalized(); } //auto v = (qp.cross(d_alpha) - k).norm(); Vector3_t p = d_alpha.cross(k); auto t = std::min(std::max(d_alpha.dot(qp), t1), t2); auto v = ((p + t*d_alpha) - qp).norm(); return v; }; auto t1_k_hypo_sqr = t1*t1 + r_k*r_k; auto t2_k_hypo_sqr = t2*t2 + r_k*r_k; number_t v; if(t1 >= 0 && t2 >= 0) { number_t sin_gamma; if(qp_norm > t2_k_hypo_sqr) { sin_gamma = std::min(r_k/std::sqrt(t2_k_hypo_sqr), (number_t)1.0f); } else if(qp_norm < t1_k_hypo_sqr) { sin_gamma = std::min(r_k/std::sqrt(t1_k_hypo_sqr), (number_t)1.0f); } else { sin_gamma = std::min(r_k/qp_norm, (number_t)1.0f); } v = calc_dist_for_gamma(qp, qpd, k, kd, h1, h2, 1, sin_gamma, t1, t2); } else if(t1 <= 0 && t2 <= 0) { number_t sin_gamma; if(qp_norm > t1_k_hypo_sqr) { sin_gamma = std::min(r_k/std::sqrt(t1_k_hypo_sqr), (number_t)1.0f); } else if(qp_norm < t2_k_hypo_sqr) { sin_gamma = std::min(r_k/std::sqrt(t2_k_hypo_sqr), (number_t)1.0f); } else { sin_gamma = std::min(r_k/qp_norm, (number_t)1.0f); } v = calc_dist_for_gamma(qp, qpd, k, kd, h1, h2, -1, sin_gamma, t1, t2); } else { number_t sin_gamma_a; if(qp_norm > t2_k_hypo_sqr) { sin_gamma_a = std::min(r_k/std::sqrt(t2_k_hypo_sqr), (number_t)1.0f); } else { sin_gamma_a = std::min(r_k/qp_norm, (number_t)1.0f); } number_t va = calc_dist_for_gamma(qp, qpd, k, kd, h1, h2, 1, sin_gamma_a, t1, t2); number_t sin_gamma_b; if(qp_norm > t1_k_hypo_sqr) { sin_gamma_b = std::min(r_k/std::sqrt(t1_k_hypo_sqr), (number_t)1.0f); } else { sin_gamma_b = std::min(r_k/qp_norm, (number_t)1.0f); } number_t vb = calc_dist_for_gamma(qp, qpd, k, kd, h1, h2, -1, sin_gamma_b, t1, t2); v = std::min(va, vb); } auto f = std::sqrt(u*u + v*v); return f; } }; namespace pluckertree { double FindMinDist( const Eigen::Vector3f& point, const Eigen::Vector3f& dirLowerBound, const Eigen::Vector3f& dirUpperBound, const Eigen::Vector3f& momentLowerBound, const Eigen::Vector3f& momentUpperBound, Eigen::Vector3f& minimum ) { auto minimize = [point,dirLowerBound,dirUpperBound,momentLowerBound,momentUpperBound](Eigen::Vector3f& minimum){ //nlopt::opt opt(nlopt::LN_COBYLA, 3);//LN_NELDERMEAD, LN_SBPLX nlopt::opt opt(nlopt::LN_SBPLX, 3);//LN_NELDERMEAD, LN_SBPLX std::vector<double> lb(momentLowerBound.data(), momentLowerBound.data() + momentLowerBound.rows() * momentLowerBound.cols()); opt.set_lower_bounds(lb); std::vector<double> hb(momentUpperBound.data(), momentUpperBound.data() + momentUpperBound.rows() * momentUpperBound.cols()); opt.set_upper_bounds(hb); FixedMomentMinDist fun(point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>()); auto obj_func = [](const std::vector<double> &x, std::vector<double> &grad, void* f_data) -> double { FixedMomentMinDist* fun = reinterpret_cast<FixedMomentMinDist*>(f_data); Vector x_vect = Eigen::Vector3d {x[0], x[1], x[2]}; Vector grad_vect = Eigen::Vector3d {0, 0, 0}; auto result = (*fun)(x_vect, grad_vect); return result; }; opt.set_min_objective(obj_func, &fun); opt.set_xtol_rel(1e-3); opt.set_stopval(1e-3); opt.set_maxtime(1); opt.set_maxeval(1000); //Vector vec = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f).cast<double>(); Vector vec = minimum.cast<double>(); std::vector<double> x(vec.data(), vec.data() + vec.rows() * vec.cols()); try { double minf; nlopt::result result = opt.optimize(x, minf); minimum = {x[0], x[1], x[2]}; return minf; } catch(std::exception &e) { std::cout << "nlopt failed: " << e.what() << std::endl; throw; } }; Eigen::Vector3f minHint; //minHint = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f); double minVal = 1E99; minHint = momentLowerBound; minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } //TODO: this can be higher if the parent node has a higher min dist value minHint = momentUpperBound; minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentLowerBound.x(), momentLowerBound.y(), momentUpperBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentLowerBound.x(), momentUpperBound.y(), momentLowerBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentUpperBound.x(), momentLowerBound.y(), momentLowerBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentLowerBound.x(), momentUpperBound.y(), momentUpperBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentUpperBound.x(), momentUpperBound.y(), momentLowerBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentUpperBound.x(), momentLowerBound.y(), momentUpperBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; return minVal; /*// Set up parameters LBFGSBParam<double> param; param.epsilon = 1e-6; param.max_iterations = 100; // Create solver and function object LBFGSBSolver<double> solver(param); // New solver class FixedMomentMinDist fun(point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>()); // Initial guess Vector x = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f).cast<double>(); // x will be overwritten to be the best point found double dist; int nbIter = solver.minimize(fun, x, dist, momentLowerBound.cast<double>(), momentUpperBound.cast<double>()); minimum = x.cast<float>(); std::cout << nbIter << " iterations" << std::endl; std::cout << "x = \n" << x.transpose() << std::endl; std::cout << "f(x) = " << dist << std::endl; return dist;*/ } double FindMinHitDist( const Eigen::Vector3f& point, const Eigen::Vector3f& point_normal, const Eigen::Vector3f& dirLowerBound, const Eigen::Vector3f& dirUpperBound, const Eigen::Vector3f& momentLowerBound, const Eigen::Vector3f& momentUpperBound, Eigen::Vector3f& minimum ) { auto minimize = [point,point_normal,dirLowerBound,dirUpperBound,momentLowerBound,momentUpperBound](Eigen::Vector3f& minimum){ //nlopt::opt opt(nlopt::LN_COBYLA, 3);//LN_NELDERMEAD, LN_SBPLX nlopt::opt opt(nlopt::LN_SBPLX, 3);//LN_NELDERMEAD, LN_SBPLX std::vector<double> lb(momentLowerBound.data(), momentLowerBound.data() + momentLowerBound.rows() * momentLowerBound.cols()); opt.set_lower_bounds(lb); std::vector<double> hb(momentUpperBound.data(), momentUpperBound.data() + momentUpperBound.rows() * momentUpperBound.cols()); opt.set_upper_bounds(hb); FixedMomentMinHitDist fun(point.cast<double>(), point_normal.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>()); auto obj_func = [](const std::vector<double> &x, std::vector<double> &grad, void* f_data) -> double { FixedMomentMinHitDist* fun = reinterpret_cast<FixedMomentMinHitDist*>(f_data); Vector x_vect = Eigen::Vector3d {x[0], x[1], x[2]}; Vector grad_vect = Eigen::Vector3d {0, 0, 0}; auto result = (*fun)(x_vect, grad_vect); return result; }; opt.set_min_objective(obj_func, &fun); opt.set_xtol_rel(1e-3); opt.set_stopval(1e-3); opt.set_maxtime(1); opt.set_maxeval(1000); //Vector vec = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f).cast<double>(); Vector vec = minimum.cast<double>(); std::vector<double> x(vec.data(), vec.data() + vec.rows() * vec.cols()); try { double minf; nlopt::result result = opt.optimize(x, minf); minimum = {x[0], x[1], x[2]}; return minf; } catch(std::exception &e) { std::cout << "nlopt failed: " << e.what() << std::endl; throw; } }; Eigen::Vector3f minHint; //minHint = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f); double minVal = 1E99; minHint = momentLowerBound; minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } //TODO: this can be higher if the parent node has a higher min dist value minHint = momentUpperBound; minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentLowerBound.x(), momentLowerBound.y(), momentUpperBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentLowerBound.x(), momentUpperBound.y(), momentLowerBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentUpperBound.x(), momentLowerBound.y(), momentLowerBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentLowerBound.x(), momentUpperBound.y(), momentUpperBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentUpperBound.x(), momentUpperBound.y(), momentLowerBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentUpperBound.x(), momentLowerBound.y(), momentUpperBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; return minVal; } // Segments double segments::FindMinDist( const Eigen::Vector3f& point, const Eigen::Vector3f& dirLowerBound, const Eigen::Vector3f& dirUpperBound, const Eigen::Vector3f& momentLowerBound, const Eigen::Vector3f& momentUpperBound, float t1Min, float t2Max, Eigen::Vector3f& min ) { auto minimize = [point,dirLowerBound,dirUpperBound,momentLowerBound,momentUpperBound, t1Min, t2Max](Eigen::Vector3f& minimum){ nlopt::opt opt(nlopt::LN_COBYLA, 3);//LN_NELDERMEAD, LN_SBPLX std::vector<double> lb(momentLowerBound.data(), momentLowerBound.data() + momentLowerBound.rows() * momentLowerBound.cols()); opt.set_lower_bounds(lb); std::vector<double> hb(momentUpperBound.data(), momentUpperBound.data() + momentUpperBound.rows() * momentUpperBound.cols()); opt.set_upper_bounds(hb); FixedMomentMinSegmentDist fun(point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>(), t1Min, t2Max); auto obj_func = [](const std::vector<double> &x, std::vector<double> &grad, void* f_data) -> double { FixedMomentMinSegmentDist* fun = reinterpret_cast<FixedMomentMinSegmentDist*>(f_data); Vector x_vect = Eigen::Vector3d {x[0], x[1], x[2]}; Vector grad_vect = Eigen::Vector3d {0, 0, 0}; auto result = (*fun)(x_vect, grad_vect); return result; }; opt.set_min_objective(obj_func, &fun); opt.set_xtol_rel(1e-3); opt.set_stopval(1e-3); opt.set_maxtime(1); opt.set_maxeval(1000); //Vector vec = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f).cast<double>(); Vector vec = minimum.cast<double>(); std::vector<double> x(vec.data(), vec.data() + vec.rows() * vec.cols()); try { double minf; nlopt::result result = opt.optimize(x, minf); minimum = {x[0], x[1], x[2]}; return minf; } catch(std::exception &e) { std::cout << "nlopt failed: " << e.what() << std::endl; throw; } }; Eigen::Vector3f minHint; //minHint = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f); double minVal = 1E99; minHint = momentLowerBound; minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } //TODO: this can be higher if the parent node has a higher min dist value minHint = momentUpperBound; minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentLowerBound.x(), momentLowerBound.y(), momentUpperBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentLowerBound.x(), momentUpperBound.y(), momentLowerBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentUpperBound.x(), momentLowerBound.y(), momentLowerBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentLowerBound.x(), momentUpperBound.y(), momentUpperBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentUpperBound.x(), momentUpperBound.y(), momentLowerBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; if(minVal < 1e-3){ return minVal; } minHint = Eigen::Vector3f(momentUpperBound.x(), momentLowerBound.y(), momentUpperBound.z()); minVal = std::min(minVal, minimize(minHint)); Diag::minimizations++; return minVal; } double FindMinDist( const Eigen::Vector3f& point, const Eigen::Vector3f& dirLowerBound, const Eigen::Vector3f& dirUpperBound, const Eigen::Vector3f& moment ) { FixedMomentMinDist f(point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>()); Vector vect = moment.cast<double>(); Vector grad; auto dist = f(vect, grad); return dist; } ///// POINTCLOUD EXPORT thread_local unsigned int pluckertree::Diag::visited = 0; thread_local unsigned int pluckertree::Diag::minimizations = 0; std::optional<std::function<void(float, float, float, int)>> pluckertree::Diag::on_node_visited; std::optional<std::function<void(float, float, int)>> pluckertree::Diag::on_node_enter; std::optional<std::function<void(float, float, float, int)>> pluckertree::Diag::on_node_leave; std::optional<std::function<void(float, float, float, float)>> pluckertree::Diag::on_build_variance_calculated; bool pluckertree::Diag::force_visit_all = false; std::random_device pluckertree::MyRand::rand_dev; struct GridPoint { Eigen::Vector3f pos; Eigen::Vector3f grad; float dist; }; /*std::vector<GridPoint> CalculateGrid( const Eigen::Vector3f& point, const Eigen::Vector3f& query_point, const Eigen::Vector3f& dirLowerBound, const Eigen::Vector3f& dirUpperBound, float x_start, float x_end, float y_start, float y_end, float z_start, float z_end, float resolution ) { FixedMomentMinHitDist f(point.cast<double>(), query_point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>()); auto x_steps = int((x_end - x_start) / resolution); auto y_steps = int((y_end - y_start) / resolution); auto z_steps = int((z_end - z_start) / resolution); std::vector<GridPoint> points(x_steps * y_steps * z_steps); for(int x_i = 0; x_i < x_steps; x_i++) { std::cout << ((float)x_i/(float)x_steps)*100.0f << "%\r"; std::cout.flush(); auto x = x_start + resolution*x_i; for(int y_i = 0; y_i < y_steps; y_i++) { auto y = y_start + resolution*y_i; for(int z_i = 0; z_i < z_steps; z_i++) { auto z = z_start + resolution*z_i; Vector vect = cart2spherical(Eigen::Vector3d(x, y, z)); Vector grad; auto dist = f(vect, grad); auto& curPoint = points[(x_i * y_steps * z_steps) + (y_i * z_steps) + z_i]; curPoint.pos = Eigen::Vector3f(x, y, z); curPoint.dist = dist; //curPoint.grad = grad.cast<float>(); } } } std::cout << std::endl; return points; }*/ std::vector<GridPoint> CalculateBallSlice( const Eigen::Vector3f& point, const Eigen::Vector3f& dirLowerBound, const Eigen::Vector3f& dirUpperBound, const Eigen::Vector3f& mlb, const Eigen::Vector3f& mub, float resolution ) { FixedMomentMinDist f(point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>()); Eigen::Vector3f stepSize = (mub - mlb) / resolution; std::vector<GridPoint> points(resolution * resolution * resolution); for(int x_i = 0; x_i < resolution; x_i++) { std::cout << ((float)x_i/(float)resolution)*100.0f << "%\r"; std::cout.flush(); auto x = mlb.x() + stepSize.x()*x_i; for(int y_i = 0; y_i < resolution; y_i++) { auto y = mlb.y() + stepSize.y()*y_i; for(int z_i = 0; z_i < resolution; z_i++) { auto z = mlb.z() + stepSize.z()*z_i; Vector vect = Eigen::Vector3d(x, y, z); Vector grad; auto dist = f(vect, grad); auto& curPoint = points[(x_i * resolution * resolution) + (y_i * resolution) + z_i]; curPoint.pos = spherical2cart(x, y, z); curPoint.dist = dist; //curPoint.grad = grad.cast<float>(); } } } std::cout << std::endl; return points; } std::vector<GridPoint> CalculateBallSlice( const Eigen::Vector3f& point, const Eigen::Vector3f& query_point, const Eigen::Vector3f& dirLowerBound, const Eigen::Vector3f& dirUpperBound, const Eigen::Vector3f& mlb, const Eigen::Vector3f& mub, float resolution ) { FixedMomentMinHitDist f(point.cast<double>(), query_point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>()); Eigen::Vector3f stepSize = (mub - mlb) / resolution; std::vector<GridPoint> points(resolution * resolution * resolution); for(int x_i = 0; x_i < resolution; x_i++) { std::cout << ((float)x_i/(float)resolution)*100.0f << "%\r"; std::cout.flush(); auto x = mlb.x() + stepSize.x()*x_i; for(int y_i = 0; y_i < resolution; y_i++) { auto y = mlb.y() + stepSize.y()*y_i; for(int z_i = 0; z_i < resolution; z_i++) { auto z = mlb.z() + stepSize.z()*z_i; Vector vect = Eigen::Vector3d(x, y, z); Vector grad; auto dist = f(vect, grad); auto& curPoint = points[(x_i * resolution * resolution) + (y_i * resolution) + z_i]; curPoint.pos = spherical2cart(x, y, z); curPoint.dist = dist; //curPoint.grad = grad.cast<float>(); } } } std::cout << std::endl; return points; } void show_me_the_grid(std::string& file, const Eigen::Vector3f& dlb, const Eigen::Vector3f& dub, const Eigen::Vector3f& mlb, const Eigen::Vector3f& mub, const Eigen::Vector3f& q) { /*Eigen::Vector3f dlb = Eigen::Vector3f(0,0,-1); Eigen::Vector3f dub = Eigen::Vector3f(-std::sqrt(2)/2.0, std::sqrt(2)/2, 0); Eigen::Vector3f mlb(-M_PI, 0.785398185, 1); Eigen::Vector3f mub(-M_PI/2, 2.3561945, 80); Eigen::Vector3f q(25.216011, 86.2393799, 64.2581253); Eigen::Vector3f q_normal(0.742901862, 0.662636876, 0.0949169919);*/ float resolution = 300; //auto data = CalculateBallSlice(q, q_normal, dlb, dub, mlb, mub, resolution); auto data = CalculateBallSlice(q, dlb, dub, mlb, mub, resolution); std::fstream myfile; myfile = std::fstream(file, std::ios::out | std::ios::binary); unsigned int size = data.size(); myfile.write(reinterpret_cast<char*>(&size), sizeof(unsigned int)); for(const auto& entry : data) { myfile.write(reinterpret_cast<const char*>(&entry.pos.x()), sizeof(float)); myfile.write(reinterpret_cast<const char*>(&entry.pos.y()), sizeof(float)); myfile.write(reinterpret_cast<const char*>(&entry.pos.z()), sizeof(float)); myfile.write(reinterpret_cast<const char*>(&entry.grad.x()), sizeof(float)); myfile.write(reinterpret_cast<const char*>(&entry.grad.y()), sizeof(float)); myfile.write(reinterpret_cast<const char*>(&entry.grad.z()), sizeof(float)); myfile.write(reinterpret_cast<const char*>(&entry.dist), sizeof(float)); } myfile.close(); } ///// }<file_sep>/tests/RegionDistanceMinimizer.cpp #include <gtest/gtest.h> #include <gmock/gmock.h> #include <Pluckertree.h> #include <MathUtil.h> #include <iostream> using namespace testing; using namespace Eigen; using namespace pluckertree; TEST(RegionDistanceMinimizer, TestTopSector1) { Eigen::Vector3f dlb = Eigen::Vector3f(0, 1, 0); Eigen::Vector3f dub = Eigen::Vector3f(0, 1, 0); Eigen::Vector3f mlb(-M_PI, 0, 1E-3); Eigen::Vector3f mub(M_PI, M_PI/4.0, 5); Eigen::Vector3f q(1, 0, 0); Eigen::Vector3f min = mlb + (mub - mlb)/2; auto minDist = FindMinDist(q, dlb, dub, mlb, mub, min); float epsilon = 1e-3; EXPECT_NEAR(minDist, 0, epsilon); } TEST(RegionDistanceMinimizer, TestTopSector2) { Eigen::Vector3f dlb = Eigen::Vector3f(0, -1, 0); Eigen::Vector3f dub = Eigen::Vector3f(0, -1, 0); Eigen::Vector3f mlb(-M_PI, 0, 1); Eigen::Vector3f mub(M_PI, M_PI/4.0, 5); Eigen::Vector3f q(1, 0, 0); Eigen::Vector3f min = mlb + (mub - mlb)/2; auto minDist = FindMinDist(q, dlb, dub, mlb, mub, min); float epsilon = 1e-3; EXPECT_NEAR(minDist, 0.806143, epsilon); } TEST(RegionDistanceMinimizer, TestSideSector1) { Eigen::Vector3f dlb = Eigen::Vector3f(0, 0, 1); Eigen::Vector3f dub = Eigen::Vector3f(0, 0, 1); Eigen::Vector3f mlb(-3*M_PI/4.0, 1*M_PI/4.0, 1); Eigen::Vector3f mub(-1*M_PI/4.0, 3*M_PI/4.0, 5); Eigen::Vector3f q(1, 0, 0); Eigen::Vector3f min = mlb + (mub - mlb)/2; auto minDist = FindMinDist(q, dlb, dub, mlb, mub, min); float epsilon = 1e-3; EXPECT_NEAR(minDist, 0, epsilon); } TEST(RegionDistanceMinimizer, TestSideSector2) { Eigen::Vector3f dlb = Eigen::Vector3f(0, 0, 1); Eigen::Vector3f dub = Eigen::Vector3f(0, 0, 1); Eigen::Vector3f mlb(-3*M_PI/4.0, 1*M_PI/4.0, .1); Eigen::Vector3f mub(-1*M_PI/4.0, 3*M_PI/4.0, .5); Eigen::Vector3f q(1, 0, 0); Eigen::Vector3f min = mlb + (mub - mlb)/2; auto minDist = FindMinDist(q, dlb, dub, mlb, mub, min); float epsilon = 1e-3; EXPECT_NEAR(minDist, 0, epsilon); } TEST(RegionDistanceMinimizer, Test3) { Eigen::Vector3f dlb = Eigen::Vector3f(0.707106769, 0.707106769, 0); Eigen::Vector3f dub = Eigen::Vector3f(0, 0, 1); Eigen::Vector3f mlb(1.57079637, 0.785398185, 0); Eigen::Vector3f mub(3.14159274, 2.3561945, 150); Eigen::Vector3f q(46.7477722, 45.1327858, 26.5332966); Eigen::Vector3f min = mlb + (mub - mlb)/2; auto minDist = FindMinDist(q, dlb, dub, mlb, mub, min); std::cout << "min: " << min.transpose() << std::endl; EXPECT_LT(minDist, 10); } TEST(RegionDistanceMinimizer, Test5) { Eigen::Vector3f dlb = Eigen::Vector3f(0,0,-1); Eigen::Vector3f dub = Eigen::Vector3f(-std::sqrt(2)/2.0, std::sqrt(2)/2, 0); Eigen::Vector3f mlb(-1.670233346304141, 1.3752921333858823, 32.70795644289806); Eigen::Vector3f mub(-1.670233346304141, 1.3752921333858823, 32.70795644289806); Eigen::Vector3f q(20.1563377, 1.75047028, 48.4263535); Eigen::Vector3f q_normal(0.403123677, 0.569172323, 0.716612995); Eigen::Vector3f min = mlb + (mub - mlb)/2; auto minDist = FindMinHitDist(q, q_normal, dlb, dub, mlb, mub, min); std::cout << "min: " << min.transpose() << std::endl; EXPECT_LT(minDist, 6.45); } TEST(RegionDistanceMinimizer, Test6) { Eigen::Vector3f dlb = Eigen::Vector3f(0,0,-1); Eigen::Vector3f dub = Eigen::Vector3f(-std::sqrt(2)/2.0, std::sqrt(2)/2, 0); Eigen::Vector3f mlb(-2.9656632640907143, 0.9729883518356381, 60.05482929947763); Eigen::Vector3f mub(-2.9656632640907143, 0.9729883518356381, 60.05482929947763); Eigen::Vector3f q(25.216011, 86.2393799, 64.2581253); Eigen::Vector3f q_normal(0.742901862, 0.662636876, 0.0949169919); Eigen::Vector3f min = mlb + (mub - mlb)/2; auto minDist = FindMinHitDist(q, q_normal, dlb, dub, mlb, mub, min); std::cout << "min: " << min.transpose() << std::endl; EXPECT_LT(minDist, 4.5); }
febc464db9f2e806d0e6c0aa930085d7dcce4397
[ "Markdown", "C", "CMake", "C++" ]
17
C++
Wouterdek/pluckertree
f55d1ed617f0b158e0904ba8c2320a88358e5ada
34ee2b492b54a50cafe3102446b9f34fc8c18f92
refs/heads/master
<file_sep>/************************************************************************* > File Name: frame.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年04月22日 星期六 15时53分42秒 ************************************************************************/ #include <stdio.h> int add(int x, int y) { return x + y; } int foo(int n) { int val = add(n, n); return val; } int main() { int key = 5; return foo(key); } <file_sep>/************************************************************************* > File Name: implicit_tls.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年05月06日 星期六 11时26分11秒 ************************************************************************/ #include <stdio.h> #include <pthread.h> #define LOOP 10000000 __thread int count = 0; //int count = 0; void * thread_routine(void* arg) { for (int i = 0; i < LOOP; i++) { count++; } printf("thread[%lu], count[%d], end\n", pthread_self(), count); } int main() { pthread_t thread[2]; int ret, i; for (i = 0; i < 2; i++) { ret = pthread_create(&thread[i], NULL, thread_routine, NULL); if (ret != 0) { printf("pthread_create fail, index[%d], ret[%d]", i, ret); thread[i] = 0; } } for (i = 0; i < 2; i++) { if (thread[i] != 0) pthread_join(thread[i], NULL); } printf("main end\n"); return 0; } <file_sep>/************************************************************************* > File Name: jump.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年05月06日 星期六 10时26分15秒 ************************************************************************/ #include <stdio.h> #include <setjmp.h> jmp_buf b; void f() { longjmp(b, 1); } int main() { if (setjmp(b)) { printf("world!"); } else { printf("hello"); f(); } return 0; } <file_sep>#include <stdio.h> int global_init_val = 84; int global_uninit_val; __attribute__((section("foo"))) int global = 42; void func1(int i) { printf("%d\n", i); } int main(void) { static int static_init_val = 30; static int static_uninit_val; int a = 1; int b; func1(static_init_val + static_uninit_val + a + b); return a; } <file_sep>/************************************************************************* > File Name: my_malloc_test.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年05月07日 星期日 16时18分57秒 ************************************************************************/ #include <stdio.h> #include "my_malloc.h" int my_heap_init(); void* my_malloc(unsigned size); void my_free(void* ptr); void my_heap_show(); int main() { int ret = my_heap_init(); if (ret != 1) { printf("my_heap_init fail\n"); return -1; } /* int size; while (scanf("%d", &size)) { void* addr = my_malloc(size); if (addr == NULL) { printf("my_malloc error\n"); continue; } printf("my_malloc succ, addr[%p], size[%d]\n", addr, size); }*/ int i; void* addr[5]; for (i = 0; i < 5; i++) { addr[i] = (char*) my_malloc(100); if (addr[i] == 0) { printf("my_malloc fail, index[%d]\n", i); continue; } printf("my_malloc succ, index[%d], ptr[%p]\n", i, addr[i]); } my_heap_show(); printf("all malloc\n\n"); for (i = 0; i < 5; i++) { printf("free, index[%d], ptr[%p]", i, addr[i]); my_free(addr[i]); my_heap_show(); } printf("all free\n\n"); my_heap_show(); return 0; } <file_sep>#include <stdlib.h> #include <unistd.h> int main(int argc, char* argv[]) { char stackBuff[1024*1024]; char *heapBuff = (char*) malloc(1024*1024); while(1) { sleep(1000); } return 0; } <file_sep>/************************************************************************* > File Name: sin.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年04月08日 星期六 21时14分22秒 ************************************************************************/ #include <stdio.h> #include <math.h> int main() { printf("result[%f]\n", sin(3.14/2)); return 0; } <file_sep>/************************************************************************* > File Name: func_ret_val.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年04月23日 星期日 15时55分51秒 ************************************************************************/ typedef struct big_thing { char buff[128]; }big_thing; big_thing return_test() { big_thing b; b.buff[0] = 0; } int main() { big_thing n = return_test(); return 0; } <file_sep>/************************************************************************* > File Name: global_constructor.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年05月07日 星期日 09时56分22秒 ************************************************************************/ #include <stdio.h> void my_init(void) { printf("hello "); } typedef void (*ctor_t) (void); ctor_t __attribute__((section (".ctors"))) my_init_init_p = &my_init; int main() { printf("world\n"); return 0; } <file_sep>/************************************************************************* > File Name: manul_name_nagling.cpp > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年03月11日 星期六 16时45分51秒 ************************************************************************/ #include <stdio.h> namespace myname { int var = 42; } extern "C" double _ZN6myname3varE; //extern double _ZN6myname3varE; int main() { printf("%d\n", _ZN6myname3varE); return 0; } <file_sep>/************************************************************************* > File Name: my_malloc.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年05月07日 星期日 15时10分08秒 ************************************************************************/ #include <unistd.h> #include <stdio.h> //32 M #define BLOCK_SIZE (32*1024*1024) typedef struct _head_header { enum{ HEAP_BLOCK_FREE = 0xABABABAB, HEAP_BLOCK_USED = 0xCDCDCDCD, }type; unsigned size; struct _head_header* next; struct _head_header* prev; }heap_header; #define ADDR_ADD(a, o) ((char*)(a) + (o)) #define HEADER_SIZE (sizeof(heap_header)) static heap_header* list_head = NULL; int my_heap_init() { void* base = NULL; void* end = NULL; heap_header* header = NULL; int ret; base = (void*) sbrk(0); end = (void*) ADDR_ADD(base, BLOCK_SIZE); ret = brk(end); if (ret != 0) return -1; header = (heap_header*) base; header->size = BLOCK_SIZE; header->type = HEAP_BLOCK_FREE; header->next = NULL; header->prev = NULL; list_head = header; return 1; } void* my_malloc(unsigned size) { heap_header* header; if (size == 0) { return NULL; } header = list_head; while (header != NULL) { if (header->type == HEAP_BLOCK_USED) { header = header->next; continue; } if (header->size >= size + HEADER_SIZE && header->size <= size + HEADER_SIZE*2 ) { header->type = HEAP_BLOCK_USED; return ADDR_ADD(header, HEADER_SIZE); } if (header->size > size + HEADER_SIZE*2) { //split heap_header* next = (heap_header*) ADDR_ADD(header, size + HEADER_SIZE); next->prev = header; next->next = header->next; next->type = HEAP_BLOCK_FREE; next->size = header->size - (size + HEADER_SIZE); header->next = next; header->size = size + HEADER_SIZE; header->type = HEAP_BLOCK_USED; return ADDR_ADD(header, HEADER_SIZE); } header = header->next; } } void my_free(void* ptr) { if (ptr == NULL) return; heap_header* header = (heap_header*) ADDR_ADD(ptr, -HEADER_SIZE); if (header->type != HEAP_BLOCK_USED) { return ; } // ---|used|---- header->type = HEAP_BLOCK_FREE; if (header->prev != NULL && header->prev->type == HEAP_BLOCK_FREE) { // merge with front block header->prev->next = header->next; if (header->next != NULL) header->next->prev = header->prev; header->prev->size += header->size; header = header->prev; } if (header->next != NULL && header->next->type == HEAP_BLOCK_FREE) { // merge wtih back block header->size += header->next->size; header->next = header->next->next; if (header->next != NULL) { header->next->prev = header; } } } void my_heap_show() { heap_header* header = list_head; //dump int count = 0; printf("my_heap_show, baseAddr[%p], headerSize[%d]\n", header, HEADER_SIZE); while ( header != NULL) { if (header->type == HEAP_BLOCK_USED) { printf("blockIndex[%d], type[used], size[%d]\n", count, header->size); } else { printf("blockIndex[%d], type[free], size[%d]\n", count, header->size); } count++; header = header->next; } } <file_sep>/************************************************************************* > File Name: a.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年03月19日 星期日 22时03分42秒 ************************************************************************/ extern int shared; int main() { int a = 100; swap(&a, &shared); return 0; } <file_sep>/************************************************************************* > File Name: hello.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年03月09日 星期四 21时18分51秒 ************************************************************************/ #include <stdio.h> int main() { printf("hello world\n"); return 0; } <file_sep>/************************************************************************* > File Name: class_ret.cpp > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年04月23日 星期日 16时39分38秒 ************************************************************************/ #include <iostream> using namespace std; struct cpp_obj { cpp_obj() { cout << "ctor\n" << endl; } cpp_obj(const cpp_obj& c) { cout << "copy ctor\n" << endl; } cpp_obj& operator=(const cpp_obj& rhs) { cout << "operator=\n" << endl; return *this; } ~cpp_obj() { cout << "dtor\n" << endl; } }; cpp_obj return_test() { cpp_obj b; cout << "before return" << endl; return b; } int main() { cpp_obj n; n = return_test(); return 0; } <file_sep>/************************************************************************* > File Name: sleep.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年05月07日 星期日 11时52分02秒 ************************************************************************/ #include <stdio.h> #include <unistd.h> int main() { while (1) { sleep(5); } return 0; } <file_sep>/************************************************************************* > File Name: variable_param_sum.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年05月06日 星期六 09时56分44秒 ************************************************************************/ #include <stdio.h> #define LOG_DEBUT(args...) fprintf(stdout, ##args) int sum(int num, ...) { int *ptr = &num + 1; int i, sum; sum = 0; for (i = 0; i < num; i++) { sum += ptr[i]; } return sum; } int main() { printf("sum[1,2,3] = %d\n", sum(3, 1, 2, 3)); LOG_DEBUT("LOG_DEBUT, var[%d], msg[%s]\n", 1, "hello"); return 0; } <file_sep>/************************************************************************* > File Name: weak_ref.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年03月11日 星期六 21时26分35秒 ************************************************************************/ #include <stdio.h> #include <pthread.h> void foo() __attribute__ ((weak)); //void foo(); int main() { if (foo) { printf("foo is define\n"); } else { printf("foo is not define\n"); } return 0; } <file_sep>/************************************************************************* > File Name: memeory.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年05月07日 星期日 15时14分58秒 ************************************************************************/ #include <stdio.h> #include <stdlib.h> int main() { int size = 1024; char* ptr = (char*)malloc(size); if (ptr == NULL) { printf("malloc fail\n"); return -1; } printf("malloc succ, ptr[%p]\n", ptr); return 0; } <file_sep>/************************************************************************* > File Name: pthread.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年03月11日 星期六 21时40分21秒 ************************************************************************/ #include <stdio.h> #include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg) __attribute__ ((weak)); int main() { if (pthread_create) { printf("multi-thread version\n"); } else { printf("single-thread version\n"); } return 0; } <file_sep>/************************************************************************* > File Name: run_so_simple.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年04月08日 星期六 21时05分10秒 ************************************************************************/ #include <stdio.h> #include <dlfcn.h> int main(int argc, char* argv[]) { void* handle; double (*func) (double); char* error; handle = dlopen(argv[1], RTLD_NOW); if (handle == NULL) { printf("dlopen error\n"); return -1; } func = dlsym(handle, "sin"); if ((error = dlerror()) != NULL) { printf("dlerror\n"); return -1; } printf("result:[%f]\n", func(3.1415926/2)); dlclose(handle); return 0; } <file_sep>/************************************************************************* > File Name: my_malloc.h > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年05月07日 星期日 16时07分19秒 ************************************************************************/ int my_heap_init(); void* my_malloc(unsigned size); void my_free(void* ptr); void my_heap_show(); <file_sep>extern int global; int foo() { global = 1; } <file_sep>/************************************************************************* > File Name: target.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年03月29日 星期三 22时18分12秒 ************************************************************************/ #include <stdio.h> #include <bfd.h> int main() { const char** t = bfd_target_list(); while(*t) { printf("%s\n", *t); t++; } return 0; } <file_sep>/************************************************************************* > File Name: test.c > Author: goldbeef > Mail: <EMAIL> > Created Time: 2017年05月06日 星期六 08时49分06秒 ************************************************************************/ #include <stdio.h> int main(int argc, char* argv[]) { int a, b, c; a = b = 1; c = a + b; int d = 0x01020304; return 0; }
063e5552a4a9be85513012db021bf7ba0039a345
[ "C", "C++" ]
24
C
goldbeef/tool
6ce968b2f31a903029d463f8a10349594df65e77
5203d3f4ab179a27cc4e8b13e08b7c6145e84509
refs/heads/master
<repo_name>jenz/niu-news-child<file_sep>/README.md # niu-news-child Gridbox New Child Theme <file_sep>/functions.php <?php /** * Set Parent/Child Styles * */ add_action( 'wp_enqueue_scripts', 'niu_child_theme_enqueue_styles' ); function niu_child_theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css?v'.time(), array('gridbox-stylesheet' ), wp_get_theme()->get('Version')); } /** * Add in the Favicon * */ add_action( 'wp_head', 'niu_child_theme_favicon' ); function niu_child_theme_favicon() { echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('wpurl').'/favicon.ico" />'; } /** * Set the footer text to always have the correct year * */ add_filter( 'gridbox_footer_text', 'niu_child_theme_copyright_update' ); function niu_child_theme_copyright_update() { echo 'Copyright &copy; '.date('Y').' Board of Trustees of Northern Illinois University. All rights reserved.'; } /** * Display featured post thumbnails in WordPress feeds * @param $content (string) */ add_filter( 'the_excerpt_rss', 'niu_child_theme_custom_feed_with_image' ); add_filter( 'the_content_feed', 'niu_child_theme_custom_feed_with_image' ); function niu_child_theme_custom_feed_with_image( $content ) { global $post; if( has_post_thumbnail( $post->ID ) ) { $content = '<p class="post-thumbnail">' . get_the_post_thumbnail( $post->ID, 'thumbnail' ) . '</p>' . $content; } return $content; } /** * Remove the "Category:" from the archive title * */ add_filter('get_the_archive_title_prefix','__return_false');
1a27c3ed89c8e1646e306b0cf2061bbe0bf6dcac
[ "Markdown", "PHP" ]
2
Markdown
jenz/niu-news-child
98e7013e76279235939866012b22a4f52f89c418
35bef409b5b07106e056595939d03ff1dfee51ea
refs/heads/main
<file_sep>// randomly pick choice function computerPlay() { let no = Math.random(); if (no < 1 / 3) { return "rock"; } else if (no > 2 / 3) { return "scissors"; } else { return "paper"; } } function checkWin(result, scores) { let winner; if (result[0] === result[1]) { scores.draw++; // if choices are same it is draw winner = "draw"; } else if (result[0] === "rock") { if (result[1] === "scissors") { scores.human++; // human rock comp scissors human win winner = "human"; } else { scores.comp++; // human rock comp paper comp win winner = "comp"; } } else if (result[0] === "paper") { if (result[1] === "scissors") { scores.comp++; // human paper comp scissors comp win winner = "comp"; } else { scores.human++; // human paper comp rock human win winner = "human"; } } else { if (result[1] === "rock") { scores.comp++; // human scissors comp rock comp win winner = "comp"; } else { scores.human++; // human scissors comp paper human win winner = "human"; } } return scores; } function game(humanPlay, scores) { compPlay = computerPlay(); showChoices(humanPlay, compPlay); let result = [humanPlay, compPlay]; // array 0: player choice , 1: random choice scores = checkWin(result, scores); // check who wins updateScores(scores); // update scores on page if (scores.human === 5 || scores.comp === 5) { const game = document.querySelector("#game"); game.classList.add("hidden"); const end = document.querySelector("#winner"); end.classList.remove("hidden"); end.classList.add("winner"); if (scores.human === 5) { const humanWin = document.querySelector("#humanWin"); humanWin.classList.remove("hidden"); const compWin = document.querySelector("#compWin"); compWin.classList.add("hidden"); } else { const humanWin = document.querySelector("#humanWin"); humanWin.classList.add("hidden"); const compWin = document.querySelector("#compWin"); compWin.classList.remove("hidden"); } } } function showChoices(human, comp) { // reset choices const buttons = document.querySelectorAll(".choiceHum"); buttons.forEach((button) => { button.classList.remove("chosen"); }); const compButtons = document.querySelectorAll(".choiceComp"); compButtons.forEach((button) => { button.classList.add("hidden"); }); // add chosen class to each of selected if (human === "rock") { const hchosen = document.querySelector("#humanRock"); hchosen.classList.add("chosen"); } else if (human === "paper") { const hchosen = document.querySelector("#humanPaper"); hchosen.classList.add("chosen"); } else { const hchosen = document.querySelector("#humanScissors"); hchosen.classList.add("chosen"); } if (comp === "rock") { const cchosen = document.querySelector("#computerRock"); cchosen.classList.remove("hidden"); } else if (comp === "paper") { const cchosen = document.querySelector("#computerPaper"); cchosen.classList.remove("hidden"); } else { const cchosen = document.querySelector("#computerScissors"); cchosen.classList.remove("hidden"); } } function updateScores(scores) { const humanScore = document.querySelector("#humanScore"); // find human score on webpage humanScore.textContent = scores.human; // update score by changing content const compScore = document.querySelector("#compScore"); compScore.textContent = scores.comp; const draws = document.querySelector("#draws"); draws.textContent = scores.draw; } function reset() { let scores = { human: 0, comp: 0, draw: 0 }; const game = document.querySelector("#game"); game.classList.remove("hidden"); const win = document.querySelector("#winner"); win.classList.add("hidden"); win.classList.remove("winner"); const buttons = document.querySelectorAll(".choiceHum"); const compButtons = document.querySelectorAll(".choiceComp"); compButtons.forEach((button) => button.classList.add("hidden")); buttons.forEach((button) => button.classList.remove("chosen")); updateScores(scores); return scores; } scores = reset(); const buttons = document.querySelectorAll("button"); // create button node list buttons.forEach((button) => { // iterate through each button button.addEventListener("click", () => { // wait for click if (button.id === "humanRock") { // if button id is this it is rock human choice game("rock", scores); // play the game } else if (button.id === "humanPaper") { game("paper", scores); } else if (button.id === "humanScissors") { game("scissors", scores); } else if (button.id === "play") { scores = reset(); } }); });
24ae7a5c2eca80500092b97ffab9bdfbb4db6cbe
[ "JavaScript" ]
1
JavaScript
chabetto/RockPaperScissors
abccaf13350dda77beb4b0442b724beab146ab24
a637002cf323899c203139bae92e6a5b31d6ac90
refs/heads/master
<file_sep>#!/bin/bash source ~/.virtualenv/appdocs/bin/activate cd /home/brian/webapps/appdocs git pull origin master make html
f7f3ac4a9e2cbacbc504993aafcd451ec4fa31fc
[ "Shell" ]
1
Shell
brosner/django-reusable-app-docs
4379b49d42aa9b503d2cf634b385c9c69e7f1fff
f35684c11ac2c16470de23aa3be4d1c044bd2060
refs/heads/master
<file_sep>void wirechamber_kinematics() { //Open files TCanvas *canvas = new TCanvas("canvas", "canvas", 1200, 1500); TFile *f = new TFile("beam.root", "read"); TTree *wc_1 = (TTree*)f->Get("VirtualDetector/wire_chamber_1_detector"); TTree *wc_2 = (TTree*)f->Get("VirtualDetector/wire_chamber_2_detector"); TTree *wc_3 = (TTree*)f->Get("VirtualDetector/wire_chamber_3_detector"); TTree *wc_4 = (TTree*)f->Get("VirtualDetector/wire_chamber_4_detector"); //creating histograms TH1F *h1 = new TH1F("h1", "x in wirechamber 3", 100, -100, 10); TH3* h2 = new TH3D("h2", "wirechamber 1;x(cm);y(cm);z(cm)", 100, -460, -330, 100, -60, 70, 100, 1700, 1740); TH3* h3 = new TH3D("h3", "wirechamber 1&2;x(cm);y(cm);z(cm)", 100, -800, -330, 100, -65, 70, 100, 1700, 3200); TH2* h4 = new TH2F("h4", "x difference, wirechamber 2&3; x(cm); y(cm)", 100, -1100 , -650, 100, -65, 65); TH3* h5 = new TH3D("h5", "wirechamber 2&3;x(cm);y(cm);z(cm)", 100, -1100, -650, 100, -65, 70, 100, 3100, 5200); //declare variables Float_t x_wc1, y_wc1, z_wc1, xwc1[553], ywc1[553], zwc1[553]; Float_t x_wc2, y_wc2, z_wc2, xwc2[553], ywc2[553], zwc2[553]; Float_t x_wc3, y_wc3, z_wc3, xwc3[553], ywc3[553], zwc3[553]; Float_t x_wc4, y_wc4, z_wc4, xwc4[553], ywc4[553], zwc4[553]; wc_1->SetBranchAddress("x", &x_wc1); wc_1->SetBranchAddress("y", &y_wc1); wc_1->SetBranchAddress("z", &z_wc1); wc_2->SetBranchAddress("x", &x_wc2); wc_2->SetBranchAddress("y", &y_wc2); wc_2->SetBranchAddress("z", &z_wc2); wc_3->SetBranchAddress("x", &x_wc3); wc_3->SetBranchAddress("y", &y_wc3); wc_3->SetBranchAddress("z", &z_wc3); wc_4->SetBranchAddress("x", &x_wc4); wc_4->SetBranchAddress("y", &y_wc4); wc_4->SetBranchAddress("z", &z_wc4); //Getting entries int k = 0; for (Int_t i = 0; i<553; i++) { wc_1->GetEntry(i); xwc1[i] = x_wc1; ywc1[i] = y_wc1; zwc1[i] = z_wc1; h2->Fill(x_wc1, y_wc1, z_wc1); h3->Fill(x_wc1, y_wc1, z_wc1); } for (Int_t i = 0; i<256; i++) { wc_2->GetEntry(i); xwc2[i] = x_wc2; ywc2[i] = y_wc2; zwc2[i] = z_wc2; h3->Fill(x_wc2, y_wc2, z_wc2); h4->Fill(x_wc2, y_wc2); h5->Fill(x_wc2, y_wc2, z_wc2); cout << x_wc2 << " " << y_wc2 << " " << z_wc2 << endl; //cout << xwc2[i] << " " << ywc2[i] << endl; } for (Int_t i = 0; i<2; i++) { wc_3->GetEntry(i); xwc3[i] = x_wc3; ywc3[i] = y_wc3; zwc3[i] = z_wc3; h3->Fill(x_wc3, y_wc3, z_wc3); h5->Fill(x_wc3, y_wc3, z_wc3); //cout << xwc3[i] << endl; } int n = 1106; h5->SetMarkerColor(kRed); h5->SetMarkerStyle(5); h5->SetFillColor(kRed); h5->Draw(); h5->GetXaxis()->SetTitleOffset(2); h5->GetYaxis()->SetTitleOffset(2); h5->GetZaxis()->SetTitleOffset(1.5); //h4->GetXaxis()->SetTitle("x (cm)"); //h4->GetXaxis()->SetTitleOffset(2); //h4->GetYaxis()->SetTitle("y (cm)"); //h4->GetYaxis()->SetTitleOffset(2); //h4->Draw(); canvas->Print("Wirechamber23_3D.pdf"); canvas->Close(); } <file_sep>void Tof_kinematics() { //Open files TCanvas *canvas = new TCanvas("canvas"); TFile *f = new TFile("beam.root", "read"); TTree *tof_upstream = (TTree*)f->Get("VirtualDetector/tof_upstream"); TTree *tof_downstream = (TTree*)f->Get("VirtualDetector/tof_downstream"); //declare variables, create histograms Float_t Px_us, Py_us, Pz_us, Px_tofus[1108],Py_tofus[1108], Pz_tofus[1108] ; TH1F *h1 = new TH1F("h1","Px for upstream TOF",100, -800, 10); tof_upstream->SetBranchAddress("Px", &Px_us); tof_upstream->SetBranchAddress("Py", &Py_us); tof_upstream->SetBranchAddress("Pz", &Pz_us); for (Int_t i = 0; i<1108; i++) { tof_upstream->GetEntry(i); Px_tofus[i] = Px_us; Py_tofus[i] = Py_us; Pz_tofus[i] = Pz_us; //cout << Px_tofus[i] << endl; } Float_t Px_ds, Py_ds, Pz_ds, Px_tofds[1108],Py_tofds[1108], Pz_tofds[1108] ; //TH1F *h2 = new TH1F("h1","Px for downstream TOF",100, -800, 10); tof_downstream->SetBranchAddress("Px", &Px_ds); tof_downstream->SetBranchAddress("Py", &Py_ds); tof_downstream->SetBranchAddress("Pz", &Pz_ds); for (Int_t i = 0; i<1108; i++) { tof_downstream->GetEntry(i); Px_tofds[i] = Px_ds; Py_tofds[i] = Py_ds; Pz_tofds[i] = Pz_ds; cout << Px_tofds[i] << endl; } } <file_sep>void TrackID() { TCanvas *canvas = new TCanvas("canvas"); TChain *chain = new TChain("EventTree_Spill1"); //double TrackID_values[8]; TH1* hist = new TH1D("ParticleID histogram", "ParticleID histogram", 100, -30, 30); chain->Add("merge_tree.root"); double PDGidnova; chain->SetBranchAddress("PDGidnova", &PDGidnova); auto entries = chain->GetEntries(); for (int i=0; i<entries; i++){ chain->GetEntry(i); //cout << TPDGidnova << endl; int P_ID = TMath::Sqrt(PDGidnova*PDGidnova); cout << P_ID << endl; //TrackID_values[i] = TrackID; hist->Fill(PDGidnova); } //TH1D *hist = new TH1D("TrackID histogram", "TrackID histogram", 990, 1900); //hist->Fill(TrackID_values); hist->Draw(); canvas->Print("PDGid_30limits.png"); canvas->Close(); }
f5666dc0047e643a99d46359ff94ee57bb79df2a
[ "C" ]
3
C
veeramik/G4simulations_laptop
205cebc3685694c4fb8dae50c11120221c48f2cd
e242c05ec641c991e79084b0d8393d5d232331f8
refs/heads/master
<repo_name>Fratakaci/clabs<file_sep>/Lab2/t2new.c #include<stdio.h> int bitamount(unsigned x); int main(void) { char x[7]; int y; int z=0; for(y=0;y!=EOF;y++) { x[y]=getchar(); if (x[y]=='\n') break; z=(z*10)+(x[y]-'0'); } printf("the number of 1 is:%d\n",bitamount(z)); return 0; } int bitamount(unsigned x) { int b; for(b=0;x!=0;x>>=1) { if(x&1) b++; } return b; } <file_sep>/Lab1/t2.c #include <stdio.h> int bitcount(unsigned x); int main() { int n=0; printf("give a positive number:"); scanf("%d",&n); printf("the number of 1 is:%d\n",bitcount(n)); return 0; } int bitcount(unsigned x) { int b; for(b=0;x!=1;x>>=1) if(x&1) b++; return b; } <file_sep>/Lab6/exper.c #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> char getop(char s[]); double pop(void); void push(double); int n; int m = 0; double val[100]; int main(int argc, char *argv[]) { double op2; int n; for (n = 1; --argc > 0; n++) { switch (getop(argv[n])) { case '0': push(atof(argv[n])); break; case '+': push(pop() + pop()); break; case '*': push(pop() * pop()); break; case '-': op2 = pop(); push(pop() - op2); break; case '/': op2 = pop(); if (op2 != 0.0) { push(pop() / op2); } else { printf("error\n"); } break; default: printf("error%s\n", argv[n]); argc = 1; break; } } printf("\t%.8g\n", pop()); return 0; } char getop(char s[]) { if ((s[0] == '-' && isdigit(s[1])) || (isdigit(s[0]))) { return '0'; } else if (s[0] == '-' || s[0] == '+' || s[0] == '/' || s[0] == '*') { return s[0]; } else { return 0; } } double pop(void) { if (m > 0) { return val[--m]; } else { printf("error\n"); return 0.0; } } void push(double f) { if (m < 100) { val[m++] = f; } else { printf("error%g\n", f); } }<file_sep>/Lab5/52.c #include <stdio.h> #include <ctype.h> char arrary[100]; int number = 0; int getch(void); void ungetch(int c); char getfloat(double *pn); int main(void) { int y = 0; double x[100]; double z = 0; for (y = 0; y < 100 ; y++) { if(getfloat(&x[y]) == '\n') { z = z + x[y]; break; } z = z + x[y]; } printf("%f\n", z); return 0; } int getch(void) { return (number > 0) ? arrary[--number] : getchar(); } void ungetch(int c) { if (number >= 100) { printf("too many characters\n"); } else { arrary[number++] = c; } } char getfloat(double *pn) { char c; int a; int b = 1; while (isspace(c = getch())) { ; } if (!isdigit(c) && c != EOF && c != '+' && c != '-' && c != '.') { ungetch(c); return 0; } a = (c == '-') ? -1 : 1; if (c == '+' || c == '-') { c = getch(); } for (*pn = 0; isdigit(c); c = getch()) { *pn = 10 * *pn + (c - '0'); } if (c == '.') { c = getchar(); if (!isdigit(c)) { ungetch(c); } for (; isdigit(c); c = getchar()) { b *= 10; *pn = 10 * *pn + (c - '0'); } } *pn = *pn / b * a; if (c != EOF) { ungetch(c); } return c; } <file_sep>/Lab6/time.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int a = 0, b = 0, c = 0; int len = 0; int d = 0, e = 0; int f; int day_of_year(int year, int month, int date); void getop(char s[]); int seconddate(void); int year(int f, int a); static char daytab[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; int day_of_year(int year, int month, int date) { int i, leap; leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); for (i = 0; i < month; i++) { date+= daytab[leap][i]; } return date; } int main(int argc, char *argv[]) { len = strlen(argv[1]); getop(argv[1]); d = day_of_year(a, b, c); f = a; seconddate(); len = strlen(argv[2]); getop(argv[2]); e = day_of_year(a, b, c); printf("%d\n", e - d + year(f, a)); } void getop(char s[]) { int process = 0; if (process < len) { while (isdigit(s[process])) { a = a * 10 + s[process] - '0'; process++; } if (s[process] == '/') { ++process; } while (isdigit(s[process])) { b = b * 10 + s[process] - '0'; process++; } if (s[process] == '/') { ++process; } while (isdigit(s[process])) { c = c * 10 + s[process] - '0'; process++; } if (s[process] == '/') { ++process; } } } int seconddate(void) { a = b = c = 0; return 0; } int year(int f, int a) { int g = 0; int h = 0; h = f; while(h < a) { if(h / 4 == 0) { g += 366; } else { g += 365; } ++h; } return g; }<file_sep>/Lab4/4344.C #include <stdio.h> #include <stdlib.h> #include <ctype.h> #define NUMBER '0' #define BUFSIZE 100 int ince = 0; char buf[BUFSIZE]; int getch(void) { return (ince > 0) ? buf[--ince] : getchar(); } void ungetch(int c) { if (ince >= BUFSIZE) { printf("too much\n"); } else { buf[ince++] = c; } } int getch(void); int THETOP = 0; char stack[BUFSIZE]; void ungetch(int); int getop(char s[]) { int i, c; while ((s[0] = c = getch()) == ' ' || c == '\t') ; s[1] = '\0'; if (!isdigit(c) && c != '.' && c != '-') return c; i = 0; if (isdigit(s[i])) while (isdigit(s[++i] = c = getch())) ; if (c == '.') while (isdigit(s[++i] = c = getch())) ; s[i] = '\0'; if (c != EOF) { ungetch(c); } return NUMBER; if (c == '-') { if (isdigit(s[++i] = c= getch())) { s[i] = c; } else { if (c != EOF) { ungetch(c); } return '-'; } } } void push(int a) { if (THETOP <= 98) { stack[THETOP++] = a; } else { printf("It is full\n"); } } int pop(void) { if (THETOP >= 0) { return stack[--THETOP]; } else { printf("It is empty \n"); return 0; } } int top(void) { if (THETOP > 0) { return stack[THETOP]; } else { printf("there is no number"); printf("/n"); } } void print(void) { printf("%d\n", stack[THETOP - 1]); } int main() { printf("there are some tips:\n"); printf("a is copy the top result\n"); printf("b is print the top result\n"); printf("c is exchange two result\n"); printf("d is delete the blank\n"); char s[BUFSIZE]; int op2; int type; while ((type = getop(s)) != EOF) { switch (type) { case NUMBER: push(atoi(s)); break; case '+': push(pop() + pop()); break; case '-': op2 = pop(); push(pop() - op2); break; case '*': push(pop() * pop()); break; case '/': op2 = pop(); if (op2 != 0) { push(pop() / op2); } else { printf("the errror"); break; } case '\n': printf("%d\n", pop()); break; case '%': op2 = pop(); if (op2 != 0) push(pop() % op2); else { printf("error"); } case 'a': push(stack[THETOP - 1]); push(stack[THETOP - 1]); break; case 'b': print(); break; case 'c': op2 = stack[THETOP - 1]; stack[THETOP - 1] = stack[THETOP - 2]; stack[THETOP - 2] = op2; break; case 'd': THETOP = 0; break; } } }<file_sep>/Lab1/CTF.c #include <stdio.h> main() { printf("celsius to fahrenheit\n"); int celsius, fahrenheit; int lower, upper, step; lower=0; upper=100; step=5; celsius=lower; while(celsius<=upper){ fahrenheit=celsius*9/5+32; printf("%d\t%d\n",celsius,fahrenheit); celsius=celsius+step; } } <file_sep>/Lab3/t1.c #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAXLINE 1000 int get_line(char *s, int lim); int strindex(char *s, char *t); char pattern[MAXLINE]; int main() { char line[MAXLINE]; int found; while (1) { get_line(line, MAXLINE); get_line(pattern, MAXLINE); found = strindex(line, pattern); if (found != -1) { printf("%d\n",found) ; } else printf("-1 does not contain t!\n"); } return 0; } int get_line(char *s, int lim) { int c, i; i=0; while (--lim>0&&(c=getchar())!=EOF&&c!='\n') s[i++]=c; if (c=='\n') s[i++]='\0'; return i; } int strindex(char *s, char *t) { int i, j, k, cc=-1, jud=0; for (i=0; s[i]!='\0'; i++) { for (j=i, k=0; t[k]!='\0'&&s[j]==t[k]; j++, k++) { jud++; } if (k>0&&t[k]=='\0') if(i>cc) { cc=i; } } if (jud!=0) return cc; else return -1; }
4b4485cba7126067791339bdfb6cf06211c6206e
[ "C" ]
8
C
Fratakaci/clabs
a175329533331ac185b29241ef8ae1d740dfcf56
1f07eb2dcf3f69aea35616e7d6749550c08b5d1b
refs/heads/master
<file_sep>/* * Copyright 2018, 2019 <NAME>. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY HONG XU ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL HONG XU OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of Hong Xu. * * * * * * Author: <NAME> * * * OpenCV Lane Detection Simple Demo - * Notes: If Linker errors occur on Visual Studio, use "Release" option instead of "Deubg". * Don't forget to the add include path: <drive>:\opencv\build\include */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <conio.h> #include "opencv2\opencv.hpp" #include "opencv2\highgui.hpp" #include "opencv2\video\background_segm.hpp" #include "opencv2\highgui\highgui.hpp" #include "opencv2\core\core.hpp" #include "opencv2\video.hpp" #include "opencv2\videoio.hpp" #include "opencv2\imgcodecs.hpp" #include "opencv2\imgproc.hpp" #include <iostream> //Linking libraries #pragma comment(lib, "opencv_world343.lib") #pragma comment(lib, "opencv_world343d.lib") using namespace cv; using namespace std; int main() { //create an image to store the video screen grab Mat frame; Mat grayFrame; Mat HSVframe; Mat CannyEdge; Mat cloneFrame; Mat linesFrame; Mat dilFrame; size_t i = 0; Mat threshold_frame; Mat str_el = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); std::vector<Vec4i> lines; // will hold the results of the detection VideoCapture cap; cap.open("CarDashCameraFootage.mp4"); while (1) { cap >> frame; //Convert frame to HSV cvtColor(frame, HSVframe, CV_RGB2HSV); //imshow("HSV frame", HSVframe); inRange(HSVframe, Scalar(0, 0, 155), Scalar(179, 255, 255), threshold_frame); dilate(threshold_frame, dilFrame, Mat(), Point(-1, -1), 4, BORDER_CONSTANT, 1); // //Apply opening on the grey frame morphologyEx(dilFrame, dilFrame, cv::MORPH_OPEN, str_el); morphologyEx(dilFrame, dilFrame, cv::MORPH_CLOSE, str_el); //imshow("Dilated frame", dilFrame); morphologyEx(threshold_frame, threshold_frame, cv::MORPH_OPEN, str_el); morphologyEx(threshold_frame, threshold_frame, cv::MORPH_CLOSE, str_el); //Canny edge detection Canny(threshold_frame, CannyEdge, 10, 100, 3); cvtColor(CannyEdge, linesFrame, CV_GRAY2BGR); HoughLinesP(CannyEdge, lines, 1, CV_PI/180, 35, 5, 2); for(i = 0; i < lines.size(); i++) { Vec4i l = lines[i]; line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(255, 0, 0), 3, CV_AA); } imshow("Hough lines", frame); //create a 33ms delay waitKey(20); } return 0; } <file_sep># Lane Detection Demo using OpenCV This is a simple lane detection demo in C++ using OpenCV library. <img width="898" alt="lane detecttion" src="https://user-images.githubusercontent.com/8460504/46281768-72c7ee80-c524-11e8-894c-529f0a824321.png"> Edit: added a second example with more controls on the different parameters, check "lane_detection_example_2.cpp" for the details. This is a screenshot of example 2: <img width="900" alt="lane detection_example_2" src="https://user-images.githubusercontent.com/8460504/55767680-cc0e5e80-5a2e-11e9-8061-d82e4e6bc286.png"> Disclaimer: The code is experimental and has some performance issues. Use it on at your own risk. I have posted it for the sake of knowledge sharing and educational purposes. <file_sep>/* * Copyright 2018, 2019 <NAME>. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY HONG XU ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL HONG XU OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of Hong Xu. * * * * * * Author: <NAME> * * * OpenCV Lane Detection Simple Demo - Example 2 * Notes: If Linker errors occur on Visual Studio, use "Release" option instead of "Deubg". * Don't forget to the add include path: <drive>:\opencv\build\include */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <conio.h> #include "opencv2\opencv.hpp" #include "opencv2\highgui.hpp" #include "opencv2\video\background_segm.hpp" #include "opencv2\highgui\highgui.hpp" #include "opencv2\core\core.hpp" #include "opencv2\video.hpp" #include "opencv2\videoio.hpp" #include "opencv2\imgcodecs.hpp" #include "opencv2\imgproc.hpp" #include <iostream> #pragma comment(lib, "C:\\opencv\\build\\x64\\vc15\\lib\\opencv_world343.lib") #pragma comment(lib, "C:\\opencv\\build\\x64\\vc15\\lib\\opencv_world343d.lib") using namespace cv; using namespace std; //create an image to store the video screen grab Mat frame; //current frame Mat grayFrame; Mat HSVframe; Mat contourOutput; Mat CannyEdge; Mat cloneFrame; Mat linesFrame; Mat fgMaskMOG2; //fg mask generated by MOG2 method Mat dilFrame; Mat openingFrame; Mat croppedFrame; Mat OutputFrame; Mat testFrame; Mat filteredHSV; Mat GuassianBlurFrame; Rect roi(475, 0, 350, 500); std::vector<std::vector<cv::Point> > contours; std::vector<std::vector<cv::Point> > contours_poly(contours.size()); //std::vector<Rect> boundRect(contours.size()); std::vector<Point2f>center(contours.size()); std::vector<float>radius(contours.size()); std::vector<Vec4i> hierarchy; Ptr<BackgroundSubtractor> pMOG2; //MOG2 Background subtractor size_t i = 0; Scalar minRGB(0, 0, 200); Scalar maxRGB(0, 0, 255); int H_min = 98, H_max = 179, S_min = 62, S_max = 255, V_min = 155, V_max = 255; int IDRmin = 1; int IDRmax = 2; int IDGmin = 3; int IDGmax = 4; int IDBmin = 5; int IDBmax = 6; int cannyLow = 30; int cannyHigh = 60; int dilIterate = 1; int Houghthreshold = 8; int minLen = 3; int maxGap = 4; double alpha = 0.5; double beta = 1 - alpha; double frameWidth = 0.0; double frameHeight = 0.0; int thrshValue = 244; int maxVal = 500; int MedianBlurKernel = 3; Scalar min(175, 175, 250); //white min for RGB Scalar max(255, 255, 255); //white max for RGB Mat threshold_frame; Mat str_el = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); std::vector<Vec4i> lines; // will hold the results of the detection int MAX_KERNEL_LENGTH = 31; int main() { //setup the video capture method using the default camera VideoCapture cap; cap.open("CarDashCameraFootage.mp4"); namedWindow("VideoCaptureTutorial", WINDOW_AUTOSIZE); namedWindow("Control", WINDOW_AUTOSIZE); createTrackbar("Hue Min", "Control", &H_min, 179); createTrackbar("Sat Min", "Control", &S_min, 255); createTrackbar("Value Min", "Control", &V_min, 255); createTrackbar("Hue Max", "Control", &H_max, 179); createTrackbar("Sat Max", "Control", &S_max, 255); createTrackbar("Value Max", "Control", &V_max, 255); createTrackbar("Threshold Value", "Control", &thrshValue, 500); createTrackbar("Max. Value", "Control", &maxVal, 500); createTrackbar("Dil Iterations", "Control", &dilIterate, 10); createTrackbar("Low threshold", "Control", &cannyLow, 255); createTrackbar("High threshold", "Control", &cannyHigh, 255); createTrackbar("Line Threshold", "Control", &Houghthreshold, 255); createTrackbar("Min Length", "Control", &minLen, 100); createTrackbar("Max Gap", "Control", &maxGap, 100); //createTrackbar("Median Blur", "Control", &MedianBlurKernel, 100); resizeWindow("Control", 400, 300); pMOG2 = createBackgroundSubtractorMOG2(); while (1) { //grad a frame from the video camers cap >> frame; //Convert RGB frame to gray scale cvtColor(frame, grayFrame, CV_RGB2GRAY); //Convert frame to HSV cvtColor(frame, HSVframe, CV_RGB2HSV);//CV_BGR2YUV); //Dilate inRange(HSVframe, Scalar(H_min, S_min, V_min), Scalar(H_max, S_max, V_max), filteredHSV); threshold(grayFrame, threshold_frame, double(thrshValue), double(maxVal), THRESH_BINARY); addWeighted(threshold_frame, alpha, filteredHSV, beta, 2.0, testFrame); medianBlur(testFrame, testFrame, MedianBlurKernel); dilate(testFrame, dilFrame, Mat(), Point(-1, -1), dilIterate, BORDER_CONSTANT, 1); // //Apply opening on the grey frame morphologyEx(dilFrame, dilFrame, cv::MORPH_OPEN, str_el); morphologyEx(dilFrame, dilFrame, cv::MORPH_CLOSE, str_el); //Canny edge detection Canny(dilFrame, CannyEdge, double(cannyLow), double (cannyHigh), 3); cvtColor(CannyEdge, linesFrame, CV_GRAY2BGR); //imshow("Canny-Grey", CannyEdge); HoughLinesP(CannyEdge, lines, 1, CV_PI / 180, Houghthreshold, minLen, maxGap); for(i = 0; i < lines.size(); i++) { Vec4i l = lines[i]; line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(255, 0, 0), 3, CV_AA); } imshow("Hough lines", frame);//linesFrame); printf("Current config: %d %d %d %d %d %d itr: %d thrld:%d Min len:%d Ma gap: %d L:%d H:%d\n", H_min, S_min, V_min, H_max, S_max, V_max, dilIterate, Houghthreshold, minLen, maxGap,cannyLow, cannyHigh); //create a 50ms delay waitKey(50); } return 0; }
3198990f875dcaf93ead643841766a4f3d001e91
[ "Markdown", "C++" ]
3
C++
kelray/Lane-Detection-Demo-OpenCV
566000f9d3e62b346a6c0d1924c5039e69460fb3
430dbc4bcf6f1c1ff7747e2e93aafb461f0af51b
refs/heads/main
<file_sep>const {Router} = require('express'); const homeControler = require('./controlers/homeControler'); const produtControler = require('./controlers/productControler'); const router = Router(); router.use('/', homeControler); router.use('/products', produtControler); // router. module.exports = router;<file_sep>module.exports = validateProduct = function(req, res, next){ let isValid = true; let data = req.body; if (data.name.trim().length < 2) { isValid = false; }else if(data.description.length < 5){ isValid = false; }else if(!data.imageUrl){ isValid = false; } if (isValid) { next(); } }<file_sep>// handle db GET/ CREATE/ GET BY ID const fs = require('fs/promises'); const path = require('path'); const db = require('../config/productsDb.json'); module.exports = { getByID(id){ return db.find(x => x.id === id); }, getAll(){ return db; }, create(cube){ db.push(cube); return fs.writeFile( path.join(__dirname, '../config/productsDb.json'), // ABSOLUTE PATH JSON.stringify(db), // DATA ) } };<file_sep>const mongoose = require('mongoose'); const config = require('./config'); const config = require('./config'); module.exports = (app) => { mongoose.connect(config.DB_CONECTION, {useNewUrlParser: true}); const db = mongoose.connection; db.on('error', () => console.log.bind(console, 'MogoDB could not conect successfully')); db.on('open', () => console.log.bind(console, 'DB successfully conected!')) };<file_sep>const uniqid = require('uniqid'); const Cube = require('../models/cube'); const productData = require('../data/productData'); function getAll(query){ let cubes = productData.getAll(); if (query.search) { cubes = cubes.filter(x => x.name.toLowerCase().includes(query.search.toLowerCase())); } if (query.from) { cubes = cubes.filter(x => x.difficulty >= query.from); } if (query.to) { cubes = cubes.filter(x => x.difficulty <= query.to); } return cubes; } function getByID(id){ return productData.getByID(id); } function create(data) { let cube = new Cube( uniqid(), data.name, data.description, data.imageUrl, data.difficultyLevel ); return productData.create(cube); } module.exports = { create, getAll, getByID }
eab709a58ead75445df7acef5b73807b08e9c63a
[ "JavaScript" ]
5
JavaScript
m-Mitkov/Cubicle
7e8860bffb71f5bc48134ad64b77460d36dc825a
a167fec2862ea25afd070ef0e0268d7c27c7528b
refs/heads/master
<file_sep># Music_Page Simple task Music page responsive page using html css little javascript <h1>Screen shot</h1> <img src="Screenshot (485).png"> </br> <img src="Screenshot (486).png"> <file_sep>var song = document.getElementById("song"); var icon = document.getElementById("icon"); icon.onclick = function () { if (song.paused) { song.play(); icon.src = "imgs/pause.png"; } else { song.pause(); icon.src = "imgs/play.png"; } }
1f0f14bcd7a7f4e110316a8741c34060eff0f907
[ "Markdown", "JavaScript" ]
2
Markdown
AbanoubBoules/Music_Page
3a2de3c22fcebf90a0c47c16b369bff88e655ce3
fc1956a54211309554a2e59f51f9222c9f64f3bc
refs/heads/master
<repo_name>yasushi-saito/untestify<file_sep>/untestify.go // To use this tool, you must modify golang.org/x/tools/refactor/eg/eg.go and comment out line 233: // // if types.AssignableTo(Tb, Ta) { // // safe: replacement is assignable to pattern. // } else if tuple, ok := Tb.(*types.Tuple); ok && tuple.Len() == 0 { // // safe: pattern has void type (must appear in an ExprStmt). // } else { // return nil, fmt.Errorf("%s is not a safe replacement for %s", Ta, Tb) <<<< comment out this line // } // package main import ( "flag" "fmt" "go/build" "go/parser" "go/token" "os" "github.com/grailbio/base/log" "go/ast" "golang.org/x/tools/go/buildutil" "golang.org/x/tools/go/loader" "golang.org/x/tools/refactor/eg" "io/ioutil" "path/filepath" "strings" ) var ( helpFlag = flag.Bool("help", false, "show detailed help message") verboseFlag = flag.Bool("v", false, "show verbose matcher diagnostics") ) func init() { flag.Var((*buildutil.TagsFlag)(&build.Default.BuildTags), "tags", buildutil.TagsFlagDoc) } const usage = `untestify: convert stretcher/testify to grailbio.com/testutil. Usage: untestify [flags] packages... -help show detailed help message -v show verbose matcher diagnostics ` + loader.FromArgsUsage type substitution struct { signature, beforeBody, afterBody string } var substitutions = []substitution{ {"t TT, err error DECLS", "XX.NoError(t, err ARGS)", "YY.NoError(t, err ARGS)"}, {"t TT, err error, f string DECLS", "XX.NoErrorf(t, err, f ARGS)", "YY.NoError(t, err, f ARGS)"}, {"t TT, err error DECLS", "XX.Error(t, err ARGS)", "YY.NotNil(t, err ARGS)"}, {"t TT, err error, a string DECLS", "XX.EqualError(t, err, a ARGS)", "YY.EQ(t, err, a ARGS)"}, {"t TT, err error, a, f string DECLS", "XX.EqualErrorf(t, err, a, f ARGS)", "YY.EQ(t, err, a, f ARGS)"}, {"t TT, a interface{}, f string DECLS", "XX.NotNilf(t, a, f ARGS)", "YY.NotNil(t, a, f ARGS)"}, {"t TT, a interface{} DECLS", "XX.Nil(t, a ARGS)", "YY.Nil(t, a ARGS)"}, {"t TT, a, b interface{} DECLS", "XX.Equal(t, a, b ARGS)", "YY.EQ(t, b, a ARGS)"}, {"t TT, a, b interface{}, f string DECLS", "XX.Equalf(t, a, b, f ARGS)", "YY.EQ(t, b, a, f ARGS)"}, {"t TT, a, b interface{} DECLS", "XX.NotEqual(t, a, b ARGS)", "YY.EQ(t, b, a ARGS)"}, {"t TT, a, b interface{}, f string DECLS", "XX.NotEqualf(t, a, b, f ARGS)", "YY.NEQ(t, b, a, f ARGS)"}, {"t TT, a, b interface{} DECLS", "XX.Regexp(t, a, b ARGS)", "YY.Regexp(t, b, a ARGS)"}, {"t TT, a bool DECLS", "XX.True(t, a ARGS)", "YY.True(t, a ARGS)"}, {"t TT, a bool DECLS", "XX.False(t, a ARGS)", "YY.False(t, a ARGS)"}, {"t TT, a bool, f string DECLS", "XX.Truef(t, a, f ARGS)", "YY.True(t, a, f ARGS)"}, {"t TT, a bool, f string DECLS", "XX.Falsef(t, a, f ARGS)", "YY.False(t, a, f ARGS)"}, {"t TT, a, b interface{} DECLS", "XX.Contains(t, a, b ARGS)", "YY.That(t, a, h.Contains(b) ARGS)"}, {"t TT, a, b interface{}, f string DECLS", "XX.Containsf(t, a, b, f ARGS)", "YY.That(t, a, h.Contains(b), f ARGS)"}, {"t TT, a interface{} DECLS", "XX.Zero(t, a ARGS)", "YY.That(t, a, h.Zero() ARGS)"}, {"t TT, a interface{}, f string DECLS", "XX.Zerof(t, a, f ARGS)", "YY.EQ(t, a, h.Zero(), f ARGS)"}, {"t TT, a interface{} DECLS", "XX.NotZero(t, a ARGS)", "YY.That(t, a, h.Not(h.Zero()) ARGS)"}, {"t TT, a interface{}, f string DECLS", "XX.NotZerof(t, a, f ARGS)", "YY.EQ(t, a, h.Not(h.Zero()), f ARGS)"}, } var templateSeq = 0 type rewriteType int const ( rewriteRequire rewriteType = iota rewriteAssert ) func addTemplates(conf *loader.Config, rType rewriteType, subs []substitution) int { const dir = "/tmp/.templatestmp" os.Mkdir(dir, 0700) // nolint: errcheck n := 0 for _, sub := range subs { var before, after, imports string switch rType { case rewriteAssert: before = strings.Replace(sub.beforeBody, "XX", "assert", -1) after = strings.Replace(sub.afterBody, "YY", "gexpect", -1) imports = ` "vendor/github.com/stretchr/testify/assert" gexpect "github.com/grailbio/testutil/expect" ` case rewriteRequire: before = strings.Replace(sub.beforeBody, "XX", "require", -1) after = strings.Replace(sub.afterBody, "YY", "gassert", -1) imports = ` "vendor/github.com/stretchr/testify/require" gassert "github.com/grailbio/testutil/assert" ` } if strings.Contains(after, "h.") { imports += ` "github.com/grailbio/testutil/h" ` } type argList struct { decl, arg string } for _, arg := range []argList{ {"", ""}, {", m0 interface{}", ", m0"}, {", m0, m1 interface{}", ", m0, m1"}, {", m0, m1, m2 interface{}", ", m0, m1, m2"}, {", m0, m1, m2, m3 interface{}", ", m0, m1, m2, m3"}, {", m0, m1, m2, m3, m4 interface{}", ", m0, m1, m2, m3, m4"}, } { sig := strings.Replace(sub.signature, "DECLS", arg.decl, -1) sig = strings.Replace(sig, "TT", "testing.TB", -1) before := strings.Replace(before, "ARGS", arg.arg, -1) after := strings.Replace(after, "ARGS", arg.arg, -1) pkgName := fmt.Sprintf("template%08d", templateSeq) templateSeq++ path := filepath.Join(dir, pkgName+".go") body := fmt.Sprintf(` package %s import ( "testing" %s ) func before(%s) { %s } func after(%s) { %s } `, pkgName, imports, sig, before, sig, after) if err := ioutil.WriteFile(path, []byte(body), 0600); err != nil { log.Panic(err) } conf.CreateFromFilenames(pkgName, path) n++ } } return n } func rewriteImports(file *ast.File) int { n := 0 j := 0 for _, imp := range file.Imports { if strings.Contains(imp.Path.Value, "/testify/require") { continue } if strings.Contains(imp.Path.Value, "/testify/assert") { continue } file.Imports[j] = imp j++ } if j != len(file.Imports) { file.Imports = file.Imports[:j] n++ } for _, d := range file.Decls { d, ok := d.(*ast.GenDecl) if ok && d.Tok == token.IMPORT { j = 0 for _, x := range d.Specs { imp := x.(*ast.ImportSpec) if strings.Index(imp.Path.Value, "/testify/require") >= 0 { continue } if strings.Index(imp.Path.Value, "/testify/assert") >= 0 { continue } if strings.Index(imp.Path.Value, "github.com/grailbio/testutil/expect") >= 0 { tmp := ast.Ident{} tmp.Name = "gexpect" imp.Name = &tmp } if strings.Index(imp.Path.Value, "github.com/grailbio/testutil/assert") >= 0 { tmp := ast.Ident{} tmp.Name = "gassert" imp.Name = &tmp } d.Specs[j] = x j++ } if j != len(d.Specs) { d.Specs = d.Specs[:j] n++ } } } return n } func main() { flag.Parse() args := flag.Args() if *helpFlag { fmt.Fprint(os.Stderr, eg.Help) os.Exit(2) } if len(args) == 0 { fmt.Fprint(os.Stderr, usage) os.Exit(1) } conf := loader.Config{ Fset: token.NewFileSet(), ParserMode: parser.ParseComments, } nTemplate := addTemplates(&conf, rewriteRequire, substitutions) nTemplate += addTemplates(&conf, rewriteAssert, substitutions) _, err := conf.FromArgs(args, true) if err != nil { log.Panic(err) } iprog, err := conf.Load() if err != nil { log.Panic(err) } xforms := []*eg.Transformer{} for i := 0; i < nTemplate; i++ { template := iprog.Created[i] xform, err := eg.NewTransformer(iprog.Fset, template.Pkg, template.Files[0], &template.Info, *verboseFlag) if err != nil { log.Panic(err) } xforms = append(xforms, xform) } for _, pkg := range iprog.InitialPackages() { if strings.Contains(pkg.String(), "template000") { continue } fmt.Fprintf(os.Stderr, "=== Package %s (%d files)\n", pkg.String(), len(pkg.Files)) for _, file := range pkg.Files { n := 0 for _, xform := range xforms { n += xform.Transform(&pkg.Info, pkg.Pkg, file) } n += rewriteImports(file) if n == 0 { continue } filename := iprog.Fset.File(file.Pos()).Name() fmt.Fprintf(os.Stderr, "=== %s (%d matches)\n", filename, n) if err := eg.WriteAST(iprog.Fset, filename, file); err != nil { log.Panic(err) } } } }
911e39d7ac0654c2ba87aa864ded5a4d249ef93b
[ "Go" ]
1
Go
yasushi-saito/untestify
092a13f3211beab5d412aa8e759dd6dc79fbe4b9
dcd145b1b08b8c18c89d5d56a7fd3d5b6570680b
refs/heads/master
<repo_name>techstone/leml<file_sep>/pyleml/LEML.py import abc class LEML: """ Abstract base class for LEML model. Subclasses need to override the fit and predict methods. """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def fit(self, train_data, train_labels): """ Train LEML model. """ @abc.abstractmethod def predict(self, test_data): """ Make predictions using trained LEML mdoel. """ @staticmethod def get_instance(backend='single', **extra_args): if backend == 'parallel': from LEML_parallel import LEMLsf return LEMLsf(**extra_args) elif backend == 'single': from LEML_single import LEMLs return LEMLs(**extra_args) raise ValueError("Unknown backend: %r (known backends: " "'parallel', 'single')" % backend)
b671a5712e75732b1193949aa4ce02e936686c22
[ "Python" ]
1
Python
techstone/leml
72f8712af04dee097d59a124863ccba4db073893
b18bac6baa60c7b600ebe5521277572a4f678657
refs/heads/master
<file_sep>prices = [40, 500, 60, 400, 70, 50] multiplier = 1.2 def augment(prices, multiplier) new_prices = [] prices.each do |price| new_prices.push(price * multiplier) end new_prices end print augment(prices, multiplier)
1e7227ac07caa24d2e131d28402d75f932ea4cc8
[ "Ruby" ]
1
Ruby
Fish234/aumento_de_precios
e92002c96829e8d1696c470473b804f8a914a883
5f9d4963a48edac568774d51311dac057867cf1c
refs/heads/master
<repo_name>Hydrogen-Spoiler-Blocker/front-end<file_sep>/modelHandler.js var model; async function fetchVocabulary() { console.log("in getVocabulary"); let url = 'https://raw.githubusercontent.com/Hydrogen-Spoiler-Blocker/models/master/vocabulary.txt'; console.log("fetching url...") let response = await fetch(url); // get one header console.log(response.headers.get('Content-Type')); let body = await response.text(); let vocab_array = body.split("\n") console.log(body[13]) console.log(vocab_array); console.log("vocab fetched") return vocab_array } const encoder = (string, vocabulary) => { let array = string[0].toLowerCase().split(" ") let vectorized = [] for (const element of array) { let position = vocabulary.indexOf(element) if (position === -1) { vectorized.push(1) } else { vectorized.push(position) } } return vectorized } async function loadModel() { const githublink = "https://raw.githubusercontent.com/Hydrogen-Spoiler-Blocker/models/master/model.json" model = await tf.loadLayersModel(githublink); console.log("model loaded") } /* loadModel().then(() => { fetchVocabulary().then(vocab => { const text = "My name is Squidward" //8 st console.log("parsed text from vocabulary: ",encoder(text, vocab)) var vocablength = encoder(text, vocab).length var shape = [1, 8] console.log(model.summary()) var output = model.predict(tf.tensor2d(encoder(text, vocab), [1, vocablength])) //output = model.predict([encoder(text, vocab), [vocablength, 1]]) console.log("PREDICTION : ", output.dataSync()[0] ); }); }) */ var onOffSwitch = localStorage.onOffSwitch || "on"; chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { onOffSwitch = message.switch console.log(onOffSwitch); }); chrome.tabs.onUpdated.addListener((tabId, tab)=>{ if(onOffSwitch != "on") return //console.log("tab", tab.url); //console.log("tabID", tabId); chrome.tabs.insertCSS(tabId, {file: "style.css"}) chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendMessage(tabId, {greeting: "hello"}, function checkIfSpoiler(paragraphs){ //console.log("paragraph:", paragraphs); loadModel().then(() => { console.log("fetched model done") fetchVocabulary().then(vocab => { //test of the vocabulary var vectoriseddata = encoder(["The Avengers go back in time to get the Infinity Stones before they are found at various times in the MCU (Natasha sacrifices herself so Clint can get the Soul Stone). Stark develops a gauntlet which the Hulk puts on and uses to snap back the beings who were killed by the original snap. Thanos arrives and wages a full on war against all the heroes from the MCU movies. When Stark and Thanos fight, Stark takes the stones and uses them to eliminate Thanos and his army so that the universe may live in peace. The power of the stones is too much, and Stark dies. After the funeral, Banner and Wilson help Rogers go back in time to return the stones to their places of origin. Rogers returns as an old man to give the shield to Wilson. We are then shown Rogers dancing with <NAME>, and they kiss as the movie ends. There are no mid or end credit scenes."], vocab) vocab.pop() //console.log("fetched vocabulary done:::::", vocab) //console.log("vectorised data::::::", vectoriseddata) //console.log(model.summary()) var paragraphsIndexToBlock = [] var counter = 0 for (i in paragraphs) { if(paragraphs[i] != null) { var vocablength = encoder([paragraphs[i]], vocab).length //console.log("para witb rback:", [paragraphs[i]]) var output = model.predict(tf.tensor2d([encoder([paragraphs[i]], vocab)], [1, vocablength])) //console.log("prediction made::", output.dataSync()[0]) if(output.dataSync()[0] >= 0){ console.log("predicted spoiler:", output.dataSync()[0], " counter: ", counter); paragraphsIndexToBlock.push(counter) } } counter++ } chrome.tabs.sendMessage(tabId, {block: paragraphsIndexToBlock}); }); }) }); }); chrome.tabs.executeScript(null, {file: './foreground.js'}) })<file_sep>/foreground.js console.log("from foreground"); var array = [] chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if(request.block){ var btn = document.createElement("button") for (element in request.block){ const paragraph = document.getElementsByTagName("p")[request.block[element]] //document.getElementsByTagName("p")[request.block[element]].style.color = 'white' //document.getElementsByTagName("p")[request.block[element]].style.backgroundColor = "white" paragraph.classList.add("isSpoiler") paragraph.innerText = "Content contains spoilers" //document.getElementsByTagName("p")[request.block[element]].appendChild(btn) } } else { var paragraphs = document.getElementsByTagName("p") for (i in paragraphs) { //console.log("paragraph", paragraphs[i].innerText) array.push(paragraphs[i].innerText) }; //console.log("paragraphs to block::::::", array); sendResponse(array) } } ); /* function replaceText(element){ if(element.hasChildNodes()){ element.childNodes.forEach(replaceText) } else if (element.nodeType === Text.TEXT_NODE){ console.log(element.textContent); //if(element.textContent.match(/coronavirus/gi)){ // element.parentElement.style.color = 'black' // element.parentElement.style.backgroundColor = "black" //} //element.textContent = element.textContent.replace(/coronavirus/gi, 'BLOCKED') } } */ /*const first = document.createElement('button'); first.innerText = "SET DATA"; first.id = "first"; const second = document.createElement('button'); second.innerText = "SEND DATA"; second.id = "second"; document.querySelector('body').appendChild(first); document.querySelector('body').appendChild(second); first.addEventListener('click', () => { //chrome.storage.sync chrome.storage.local.set({"password": "123"}); console.log("BUTTON PRESSED"); }); second.addEventListener('click', () => { chrome.runtime.sendMessage({message: 'yo check the storage'}); console.log("sent the message"); });*/ //How to add css to elements on a website. //document.querySelector('name of element id on website').classList.add('name of css function') //sync between device //chrome.storage.sync
8986c6ff929bb61d060c7101e5c457fcf6342b8f
[ "JavaScript" ]
2
JavaScript
Hydrogen-Spoiler-Blocker/front-end
bedeb2ecbc4d2c0daacc12ec17b8418a33140cfc
0f798b28a25c56c337ae9402997f57a8eec8274a
refs/heads/master
<repo_name>wuqisheng0911/zixunguanli<file_sep>/js/myjs.js $(function() { // modal $(".modal").modal({ show:false, backdrop:false }); //栏目管理获取数据 function getLmgl(){ $.get("http://172.16.58.3:8099/manager/category/findAllCategory",function(result){ var arr = result.data; $(".lmgl table tbody").empty(); // 初始选择框 $(".pos select").empty(); $(".pos2 select").empty(); $(".pos select").append("<option value=''>---请选择---</option>"); $(".pos2 select").append("<option value=''>---请选择---</option>"); arr.forEach(function(item,index) { if(!item.parent){ var o = {}; o.name = "无"; }else{ var o = {}; o.name = item.parent.name; } $(".lmgl table tbody").append("<tr><td><input type='checkBox'></td><td>"+item.name+"</td><td>"+o.name+"</td><td>"+item.comment+"</td><td><i class='iconfont icon-xiugai'></i><i class='iconfont icon-shanchu'></i></td></tr>"); $(".lmgl .table tbody tr td input").eq(index).val(item.id); $(".pos select").append("<option value='"+item.id+"'>"+item.name+"</option>"); $(".pos2 select").append("<option value='"+item.id+"'>"+item.name+"</option>"); }); rm_single_column(); upLmgl(); // console.log(result); }); }; $(".left_main_container ul li a").click(function() { var index = $(".left_main_container ul li a").index(this); $(".right_main_container").addClass("showIt"); $(".right_main_container").eq(index).removeClass("showIt"); if (index == 1) { //栏目管理获取数据 getLmgl(); }else if(index==2) { // 资讯管理获取数据 getZxgl(); }else if(index==3) { // 获取用户数据 getYhgl(); } }); //新增栏目 $(".addColumn").click(function() { var o = {}; o.id = $(".pos input:first").val(); o.name = $(".pos input:not(:first)").val(); o.comment = $(".pos textarea").val(); o.no = 232; o.parentId = $(".pos select").val(); if(o.name&&o.comment){ $.post("http://172.16.58.3:8099/manager/category/saveOrUpdateCategory",o,function(result){ // console.log(result); getLmgl(); }); o.name = $(".pos").find("input:not(:first)").val(null); o.comment = $(".pos").find("textarea").val(null); o.parentId = $(".pos").find("select").val(null); }else{ alert("请填写有效信息"); } }); // 栏目修改 function upLmgl() { $(".newAdd").click(function() { $(".pos input:first").hide(); $(".pos input:first").val(null); }); var $i = $(".lmgl>table>tbody>tr i:even"); $i.click(function() { $("#myModal").modal(); $(".pos input:first").show(); var id = $(this).parent().siblings(":first").children().val(); $(".pos input:first").val(id); }); } //栏目批量删除 $(".rm_some_column").click(function() { var arr=[]; $(".lmgl .table tbody tr td input:checked").each(function(index,item){ arr.push($(item).val()); }); var o = { ids:arr.toString() } $.post("http://172.16.58.3:8099/manager/category/batchDeleteCategory",o,function(result) { // console.log(result); getLmgl(); }); }); //栏目删除 function rm_single_column() { var $i = $(".lmgl>table>tbody>tr i:odd"); $i.click(function() { var id = "id="+$(this).parent().siblings(":first").children().val(); $.get("http://172.16.58.3:8099/manager/category/deleteCategoryById",id,function() { getLmgl(); }); }); } //资讯管理获取数据 function getZxgl() { var mark = 0; var o = { page:7, pageSize:20 }; getRe(); $("button.chaxun").click(function() { o.page=$("input.page").val(); o.pageSize=$("input.pageSize").val(); getRe(); }); function getRe() { $("input.page").val(o.page); // $("input.pageSize").val(o.pageSize); $.get("http://172.16.58.3:8099/manager/article/findArticle",o,function(result) { var arr = result.data.list; $(".zxgl table tbody").empty(); arr.forEach(function(item,index) { if(!item.category) { var o = {}; o.name = "无"; }else{ var o = {}; o.name = item.category.name; } $(".zxgl table tbody").append("<tr><td><input type='checkBox'></td><td>"+item.title+"</td><td>"+o.name+"</td><td>"+item.music+"</td><td></td><td>"+item.publishtime+"</td><td>"+item.readtimes+"</td><td><i class='iconfont icon-xiugai'></i><i class='iconfont icon-shanchu'></i></td></tr>"); $(".zxgl table tbody tr td input").eq(index).val(item.id); getLmgl(); }); // console.log(result); rm_zxgl_single(); upZxgl(); }); } } //添加文章 // 选择文章样式 $("div.sty").click(function() { $(this).addClass("cheacked").siblings("div[class^='sty']").removeClass("cheacked"); }); // 获取输入数据并添加 $("button.publish").click(function() { var o ={}; o.id = $(".pos2 input:first").val(); o.title = $(".pos2 input:not(:first)").val(); o.liststyle = $("div.cheacked").attr("name"); o.music = "Error"; o.categoryId = $(".pos2 select").val(); o.content = $(".pos2 textarea").val(); if(o.id){ var date = new Date(); var year = date.getFullYear(); var m = date.getMonth()+1; var d = date.getDate(); var time = year+"-"+m+"-"+d; o.publishtime = time; o.readtimes = "7"; } if(o.title&&o.liststyle) { $.post("http://172.16.58.3:8099/manager/article/saveOrUpdateArticle",o,function(result) { $(".pos2 input:not(:first)").val(""); var content = $(".pos2 textarea").val(""); var categoryId = $(".pos2 select").val(""); getZxgl(); }); } }); //资讯批量删除 $(".rm_zxgl_some").click(function() { var ids = []; $(".zxgl table tbody tr td input:checked").each(function(index,item){ ids.push($(item).val()); // console.log($(item).val()); }); var o ={ ids:ids.toString() } $.post("http://172.16.58.3:8099/manager/article/batchDeleteArticle",o,function(result) { getZxgl(); }); }) // 资讯单个删除 function rm_zxgl_single() { $(".zxgl table tbody tr td i:odd").click(function() { var id = $(this).parent().siblings(":first").children().val(); var o = { id:id }; $.get("http://172.16.58.3:8099/manager/article/deleteArticleById",o,function(){ getZxgl(); }); }); } // 资讯修改 function upZxgl() { $(".addZxgl").click(function() { $(".pos2 input:first").hide(); $(".pos2 input:first").val(null); }); $(".zxgl table tbody tr td i:even").click(function() { $(".pos2 input:first").show(); $("#my2modal").modal(); var id = $(this).parent().siblings(":first").children().val(); $(".pos2 input:first").val(id); }); } //用户管理状态按钮 function anniu(){ $(".open_close").click(function() { $(this).toggleClass("changeColor"); $(this).children(".cicrl").css({"transition":"all .3s"}); $(this).children(".cicrl").toggleClass("move_d"); $(this).children(".tip_open").toggle(); $(this).children(".tip_close").toggle(); }); } //用户管理信息获取 function getYhgl(){ $.get("http://172.16.58.3:8099/manager/user/findAllUser",function(result) { var arr = result.data; $(".yhgl ul").empty(); arr.forEach(function(item,index) { var id = item.id; if(item.enabled){ $(".yhgl ul").append("<li name='"+id+"'><div><span title='删除用户'>X</span><img src='"+item.userface+"' alt='无头像'><table class='user_info'><tbody><tr><td>用户名</td><td>"+item.nickname+"</td><tr><tr><td>真实姓名</td><td>"+item.username+"</td></tr><tr><td>手机号</td><td>XXXXXXXXXXX</td></tr><tr><td>email</td><td>"+item.email+"</td></tr><tr><td>状态</td><td><span class='open_close changeColor'><span class='cicrl'></span><span class='tip_open showde'>开启</span><span class='tip_close hided'>关闭</span></span></td></tr></tbody></div></li>"); }else{ $(".yhgl ul").append("<li name='"+id+"'><div><span title='删除用户'>X</span><img src='"+item.userface+"' alt='无头像'><table class='user_info'><tbody><tr><td>用户名</td><td>"+item.nickname+"</td><tr><tr><td>真实姓名</td><td>"+item.username+"</td></tr><tr><td>手机号</td><td>XXXXXXXXXXX</td></tr><tr><td>email</td><td>"+item.email+"</td></tr><tr><td>状态</td><td><span class='open_close'><span class='cicrl move_d'></span><span class='tip_open'>开启</span><span class='tip_close'>关闭</span></span></td></tr></tbody></div></li>"); } }); delUser(); anniu(); }); } // 添加用户 $("button.addUser").click(function() { var o = {}; o.username = $(".pos3 input").eq(0).val(); o.password = $(".pos3 input").eq(1).val(); o.nickname = $(".pos3 input").eq(2).val(); o.email = $(".pos3 input").eq(3).val(); o.userface = $(".pos3 input").eq(4).val(); // console.log(o.username,o.password,o.nickname,o.email,o.userface); if(o.username&&o.password&&o.nickname&&o.email) { $.post("http://172.16.58.3:8099/manager/user/saveOrUpdateUser",o,function() { getYhgl(); o.username = $(".pos3 input").eq(0).val(null); o.password = $(".pos3 input").eq(1).val(null); o.nickname = $(".pos3 input").eq(2).val(null); o.email = $(".pos3 input").eq(3).val(null); o.userface = $(".pos3 input").eq(4).val(null); }); } }); // 删除用户 function delUser() { // console.log($(".yhgl ul li>div>span")); $(".yhgl ul li>div>span").click(function() { var id = $(this).parent().parent().attr("name"); // console.log(id); var o = { id:id } var val = confirm("是否删除该用户"); if(val){ $.get("http://172.16.58.3:8099/manager/user/deleteUserById",o,function() { getYhgl(); }); } }); } });
27702b5d7e6f757c02373f362d0ec90b760fa123
[ "JavaScript" ]
1
JavaScript
wuqisheng0911/zixunguanli
d3887e4d1651a77905179ef7e7f3c42df69b0475
6b628ccd1eccb720ef5c28373184985b83632ae0
refs/heads/master
<file_sep>/* * Copyright 2016-2018 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nskvortsov import com.intellij.openapi.util.SystemInfo import github.nskvortsov.teamcity.cleanup.ApacheIvyCacheCleanerProvider import github.nskvortsov.teamcity.cleanup.GradleCacheCleanerProvider import github.nskvortsov.teamcity.cleanup.MavenCacheCleanerProvider import github.nskvortsov.teamcity.cleanup.NPMCacheCleanerProvider import jetbrains.buildServer.agent.AgentRunningBuild import jetbrains.buildServer.agent.DirectoryCleanersProviderContext import jetbrains.buildServer.agent.DirectoryCleanersRegistry import jetbrains.buildServer.util.FileUtil import org.assertj.core.api.Assertions.assertThat import org.mockito.Mockito.* import org.testng.annotations.AfterMethod import org.testng.annotations.BeforeMethod import org.testng.annotations.Test import java.io.File import java.util.* import kotlin.properties.Delegates class SimpleCleanerProvidersTest { var registryMap: MutableMap<File, Runnable> by Delegates.notNull() var context: DirectoryCleanersProviderContext by Delegates.notNull() var registry: DirectoryCleanersRegistry by Delegates.notNull() var runningBuild: AgentRunningBuild by Delegates.notNull() var tempDir: File by Delegates.notNull() var oldHome: String? = null @BeforeMethod fun setUp() { tempDir = FileUtil.createTempDirectory("test", "cleanup") FileUtil.copyDir(File("src/test/resources/testData"), tempDir) oldHome = System.getProperty("user.home") System.setProperty("user.home", tempDir.absolutePath) registryMap = HashMap<File, Runnable>() context = mock(DirectoryCleanersProviderContext::class.java) registry = mock(DirectoryCleanersRegistry::class.java) runningBuild = mock(AgentRunningBuild::class.java) `when`(registry.addCleaner(any(), any(), any())).thenAnswer { registryMap.put(it.arguments[0] as File, it.arguments[2] as Runnable) } `when`(registry.addCleaner(any(), any())).thenAnswer { registryMap.put(it.arguments[0] as File, Runnable { (it.arguments[0] as File).delete() } ) } `when`(context.runningBuild).thenAnswer { runningBuild } } @AfterMethod fun tearDown() { System.setProperty("user.home", oldHome) FileUtil.delete(tempDir) } @Test fun testMavenProvider() { val provider = MavenCacheCleanerProvider() val m2repo = File("${System.getProperty("user.home")}/.m2/repository") provider.registerDirectoryCleaners(context, registry) assertThat(registryMap).containsKey(m2repo) registryMap[m2repo]?.run() assertThat(m2repo).doesNotExist() } @Test fun testGradleProvider() { val provider = GradleCacheCleanerProvider() val gradleCache = File("${System.getProperty("user.home")}/.gradle/caches") provider.registerDirectoryCleaners(context, registry) assertThat(registryMap).containsKey(gradleCache) registryMap[gradleCache]?.run() assertThat(gradleCache).doesNotExist() } @Test fun testGradleWrapperProvider() { val provider = GradleCacheCleanerProvider() val wrapperCache = File("${System.getProperty("user.home")}/.gradle/wrapper/dists") provider.registerDirectoryCleaners(context, registry) assertThat(registryMap).containsKey(wrapperCache) registryMap[wrapperCache]?.run() assertThat(wrapperCache).doesNotExist() } @Test fun testGradleDaemonLogsRemoved() { val provider = GradleCacheCleanerProvider() val daemonLogs = File("${System.getProperty("user.home")}/.gradle/daemon") provider.registerDirectoryCleaners(context, registry) assertThat(registryMap).containsKey(File(daemonLogs, "2.5/test.out.log")) assertThat(registryMap).containsKey(File(daemonLogs, "2.6/test.out.log")) assertThat(registryMap).doesNotContainKey(File(daemonLogs, "2.6/other.txt")) } @Test fun testNPMProvider() { val provider = NPMCacheCleanerProvider() val repo = if (SystemInfo.isWindows) File(System.getenv("APPDATA"), "npm-cache") else File("${System.getProperty("user.home")}/.npm") val created = SystemInfo.isWindows && !repo.exists() && repo.mkdirs() provider.registerDirectoryCleaners(context, registry) assertThat(registryMap).containsKey(repo) // Do not clean on Windows as it's actual directory if (!created) return registryMap[repo]?.run() assertThat(repo).doesNotExist() } @Test fun testApacheIvyProvider() { val provider = ApacheIvyCacheCleanerProvider() val repo = File("${System.getProperty("user.home")}/.ivy2/cache") provider.registerDirectoryCleaners(context, registry) assertThat(registryMap).containsKey(repo) registryMap[repo]?.run() assertThat(repo).doesNotExist() } }<file_sep>/* * Copyright 2016-2018 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nskvortsov.teamcity.cleanup import jetbrains.buildServer.agent.DirectoryCleanersProvider import jetbrains.buildServer.agent.DirectoryCleanersProviderContext import jetbrains.buildServer.agent.DirectoryCleanersRegistry import jetbrains.buildServer.util.FileUtil import org.apache.log4j.Logger import java.io.File import java.util.* class MavenCacheCleanerProvider : DirectoryCleanersProvider { var log = Logger.getLogger(MavenCacheCleanerProvider::class.java) override fun registerDirectoryCleaners(context: DirectoryCleanersProviderContext, registry: DirectoryCleanersRegistry) { log.debug("Maven cache cleaner: register dir cleaners") val disabled = context.hasExplicitFalse("teamcity.cleaners.maven.enabled") if (disabled) { log.info("Maven repository cleaner is disabled, skipping.") return } System.getProperty("user.home")?.let { home -> val m2repo = File("$home/.m2/repository") log.debug("Checking if [${m2repo.absolutePath}] exists") if (m2repo.exists()) { log.debug("Maven cache found, registering cleaner.") registry.addCleaner(m2repo, Date(), Cleaner(m2repo, log)) } } } override fun getCleanerName() = "Maven local cache cleaner" } class GradleCacheCleanerProvider : DirectoryCleanersProvider { val log = Logger.getLogger(GradleCacheCleanerProvider::class.java) override fun registerDirectoryCleaners(context: DirectoryCleanersProviderContext, registry: DirectoryCleanersRegistry) { log.debug("Gradle cleaner: register dir cleaners") val disabled = context.hasExplicitFalse("teamcity.cleaners.gradle.enabled") if (disabled) { log.info("Gradle cleaner is disabled, skipping") return } System.getProperty("user.home")?.let { val gradleCache = File(it + "/.gradle/caches") log.debug("Checking if [${gradleCache.absolutePath}] exists") if (gradleCache.exists()) { log.debug("Gradle cache found, registering cleaner.") registry.addCleaner(gradleCache, Date(), Cleaner(gradleCache, log)) } val wrapperCache = File(it + "/.gradle/wrapper/dists") log.debug("Checking if [${wrapperCache.absolutePath}] exists") if (wrapperCache.exists()) { log.debug("Gradle wrapper distributions found, registering cleaner.") registry.addCleaner(wrapperCache, Date(), Cleaner(wrapperCache, log)) } val daemonLogs = File(it + "/.gradle/daemon") log.debug("Looking for Gradle daemon logs.") var count = 0 daemonLogs.walkTopDown().maxDepth(3).filter { it.name.endsWith("out.log") }.forEach { registry.addCleaner(it, Date(it.lastModified())) count++ } log.debug("Finished, found and registered for cleaning $count files") } } override fun getCleanerName() = "Gradle local cache cleaner" } fun DirectoryCleanersProviderContext.hasExplicitFalse(key: String): Boolean { val strValue = runningBuild.sharedConfigParameters[key] return strValue?.equals("false", ignoreCase = true) ?: false } class Cleaner(private val dir: File, private val log: Logger): Runnable { override fun run() { log.debug("Removing ${dir.absolutePath}") val dirOld = File("$dir.old") val movedSuccessfully = FileUtil.moveDirWithContent(dir, dirOld, { log.info("Failed to rename to ${dirOld.name}: $it") }) if (movedSuccessfully) { log.debug("Rename successful, deleting ${dirOld.name}") FileUtil.delete(dirOld) } } } <file_sep>/* * Copyright 2016-2018 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nskvortsov.teamcity.cache import jetbrains.buildServer.agent.* import jetbrains.buildServer.util.EventDispatcher import jetbrains.buildServer.util.FileUtil import java.io.File import java.util.* import kotlin.properties.Delegates /** * Created by Nikita.Skvortsov * date: 09.04.2016. */ class PersistentCacheWithCleaners(agentDispatcher: EventDispatcher<AgentLifeCycleListener>) : DirectoryCleanersProvider { var cacheDirectory: File by Delegates.notNull() companion object { private const val ArtifactRestrictorWhitelistProperty = "teamcity.artifactDependenciesResolution.whiteList" } init { agentDispatcher.addListener(object: AgentLifeCycleAdapter() { override fun agentInitialized(agent: BuildAgent) { val configuration = agent.configuration cacheDirectory = configuration.getCacheDirectory(".persistent_cache") FileUtil.createDir(cacheDirectory) configuration.addSystemProperty("agent.persistent.cache", cacheDirectory.absolutePath) // Ensure it's possible to download artifact dependencies into persistent cache // Restrictor introduced in TeamCity 2018.1 configuration.addConfigurationParameter(ArtifactRestrictorWhitelistProperty, configuration.configurationParameters.getOrDefault(ArtifactRestrictorWhitelistProperty, "") + ";%agent.persistent.cache%") } }) } override fun registerDirectoryCleaners(context: DirectoryCleanersProviderContext, registry: DirectoryCleanersRegistry) { cacheDirectory.listFiles().forEach { registry.addCleaner(it, Date(it.lastModified())) } } override fun getCleanerName() = "Persistent agent cache cleaner" }
71aabb0a8a29570a7847d604ee742701b752095e
[ "Kotlin" ]
3
Kotlin
Bhanditz/teamcity-caches-cleanup-plugin
62af21583507762f991fe03773126a316f38935f
a22fa79681bce1fb8a965d3f3b2d173aa79bc12b
refs/heads/master
<repo_name>rivery811/pythontitanic<file_sep>/web_crawling/service.py from web_crawling.model import BugsCrawler, NaverStockCrawler, KrxCrawler, NaverMovieCrawler class Service: def __init__(self): pass def crawling(self, flag): if flag == 'bugs': print('벅스 크롤링하기') bugs = BugsCrawler('https://music.bugs.co.kr/chart/track/realtime/total?chartdate=20191031&charthour=09') bugs.scrap() elif flag == 'naver_stock': print('네이버 주식 크롤링하기') naver_stock = NaverStockCrawler('005930') naver_stock.scrap() elif flag == 'krx': krx = KrxCrawler('') krx.scrap() elif flag == 'naver_movie': print('네이버 영화 크롤링하기') naver_movie = NaverMovieCrawler('https://movie.naver.com/movie/sdb/rank/rmovie.nhn') naver_movie.scrap()<file_sep>/kbstar/view.py import matplotlib.pyplot as plt from matplotlib import font_manager, rc import seaborn as sns from kbstar.service import Service from kbstar.model import Model rc('font', family = font_manager .FontProperties(fname='C:/Windows/Fonts/H2GTRE.ttf') .get_name()) class View: def __init__(self, fname): service = Service() self._model = service.new_model(fname) <file_sep>/tf_calc/__init__.py import tensorflow as tf from tf_calc.service import Service from tf_calc.model import Model if __name__ == '__main__': model = Model() service = Service() def print_menu(): print('0. 종료') print('+') print('-') print('*') print('/') return input('메뉴 입력\n') while 1: num1 = input('숫자1 입력\n') a = tf.constant(int(num1)) menu = print_menu() num2 = input('숫자2 입력\n') b = tf.constant(int(num2)) if menu == '+': print('a + b = {}'.format(service.plus(a, b))) if menu == '-': pass if menu == '*': pass if menu == '/': pass elif menu == '0': pass<file_sep>/tf_calc/model.py class Model: def __init__(self): self._num1 = 0 self._num2 = 0 @property def num1(self) -> int: return self._num1 @num1.setter def num1(self, num1): self._num1 = num1 @property def num2(self) -> int: return self._num2 @num2.setter def num2(self, num2): self._num2 = num2 <file_sep>/titanic/service.py from titanic.model import Model import pandas as pd import numpy as np from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score import warnings warnings.simplefilter(action='ignore', category=FutureWarning) """ ['PassengerId' 고객ID, 'Survived', 생존여부 'Pclass', 승선권 1 = 1st 2 = 2nd 3 = 3rd 'Name', 'Sex', 'Age', 'SibSp',동반한 형제, 자매, 배우자 'Parch', 동반한 부모, 자식 'Ticket', 티켓번호 'Fare', 요금 'Cabin', 객실번호 'Embarked'] 승선한 항구명 C = 쉐부로, Q = 퀸즈타운, S = 사우스햄톤 self._test_id = test['PassengerId'] """ class Service: def __init__(self): self._this = Model() def new_model(self, param): this = self._this this.context='./data' this.fname=param return pd.read_csv(this.context+'/'+this.fname) def create_train(self, this): return this.train.drop('Survived', axis=1) def create_dummy(self, this): return this.train['Survived'] def create_kfold(self): return KFold(n_splits=10, shuffle=True, random_state=0) @staticmethod def drop_feature(this, feature) -> object: this.train = this.train.drop([feature], axis=1) this.test = this.test.drop([feature], axis=1) return this @staticmethod def embarked_norminal(this) -> object: this.train = this.train.fillna({"Embarked": "S"}) this.train['Embarked'] = this.train['Embarked'].map({"S": 1, "C": 2, "Q": 3}) this.test = this.test.fillna({"Embarked": "S"}) this.test['Embarked'] = this.test['Embarked'].map({"S": 1, "C": 2, "Q": 3}) return this @staticmethod def fareBand_norminal(this) -> object: this.train = this.train.fillna({"FareBand": 1}) this.test = this.test.fillna({"FareBand": 1}) return this @staticmethod def title_nominal(this) -> []: combine = [this.train, this.test] for dataset in combine: dataset['Title'] = dataset.Name.str.extract('([A-Za-z]+)\.', expand=False) for dataset in combine: dataset['Title'] \ = dataset['Title'].replace(['Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev', 'Jonkheer', 'Dona'], 'Rare') dataset['Title'] \ = dataset['Title'].replace(['Countess', 'Lady', 'Sir'], 'Royal') dataset['Title'] \ = dataset['Title'].replace('Mlle', 'Miss') dataset['Title'] \ = dataset['Title'].replace('Ms', 'Miss') dataset['Title'] \ = dataset['Title'].replace('Mme', 'Mrs') this.train[['Title', 'Survived']].groupby(['Title'], as_index=False).mean() """ Title Survived 0 Master 0.575000 1 Miss 0.701087 2 Mr 0.156673 3 Mrs 0.793651 4 Ms 1.000000 5 Rare 0.250000 6 Royal 1.000000 """ title_mapping = {'Mr': 1, 'Miss': 2, 'Mrs': 3, 'Master': 4, 'Royal': 5, 'Rare': 6} for dataset in combine: dataset['Title'] = dataset['Title'].map(title_mapping) dataset['Title'] = dataset['Title'].fillna(0) this.train = this.train this.test = this.test return this @staticmethod def sex_nominal(this) -> []: combine = [this.train, this.test] sex_mapping = {"male": 0, "female": 1} for dataset in combine: dataset['Sex'] = dataset['Sex'].map(sex_mapping) this.train = this.train this.test = this.test return this @staticmethod def age_ordinal(this) -> object: train = this.train test = this.test train['Age'] = train['Age'].fillna(-0.5) test['Age'] = test['Age'].fillna(-0.5) bins = [-1, 0, 5, 12, 18, 24, 35, 60, np.inf] labels = ['Unknown', 'Baby', 'Child', 'Teenager', 'Student', 'Young Adult', 'Adult', 'Senior'] train['AgeGroup'] = pd.cut(train['Age'], bins, labels=labels) test['AgeGroup'] = pd.cut(test['Age'], bins, labels=labels) age_title_mapping = {0: 'Unknown', 1: 'Baby', 2: 'Child', 3: 'Teenager', 4: 'Student', 5: 'Young Adult', 6: 'Adult', 7: 'Senior'} for x in range(len(train['AgeGroup'])): if train['AgeGroup'][x] == 'Unknown': train['AgeGroup'][x] = age_title_mapping[train['Title'][x]] for x in range(len(test['AgeGroup'])): if test['AgeGroup'][x] == 'Unknown': test['AgeGroup'][x] = age_title_mapping[test['Title'][x]] age_mapping = {'Unknown': 0, 'Baby': 1, 'Child': 2, 'Teenager': 3, 'Student': 4, 'Young Adult': 5, 'Adult': 6, 'Senior': 7} train['AgeGroup'] = train['AgeGroup'].map(age_mapping) test['AgeGroup'] = test['AgeGroup'].map(age_mapping) this.train = train this.test = test return this @staticmethod def fare_ordinal(this) -> []: this.train['FareBand'] = pd.qcut(this['Fare'], 4, labels={1, 2, 3, 4}) this.test['FareBand'] = pd.qcut(this['Fare'], 4, labels={1, 2, 3, 4}) return this # 검증 알고리즘 작성 def accuracy_by_knn(self, this): score = cross_val_score(KNeighborsClassifier(n_neighbors=13), this.train, this.dummy, cv=this._kfold, n_jobs=1, scoring='accuracy') return round(np.mean(score) * 100, 2) def accuracy_by_dtree(self,this): score = cross_val_score(DecisionTreeClassifier(), this.train, this.dummy, cv=this.kfold, n_jobs=1, scoring='accuracy') return round(np.mean(score) * 100, 2) def accuracy_by_rforest(self,this): score = cross_val_score(RandomForestClassifier(n_estimators=13), this.train, this.dummy, cv=this.kfold, n_jobs=1, scoring='accuracy') return round(np.mean(score) * 100, 2) def accuracy_by_nb(self, this): score = cross_val_score(GaussianNB(), this.train, this.dummy, cv=this.kfold, n_jobs=1, scoring='accuracy') return round(np.mean(score) * 100, 2) def accuracy_by_svm(self, this): score = cross_val_score(SVC(), this.train, this.dummy, cv=this.kfold, n_jobs=1, scoring='accuracy') return round(np.mean(score) * 100, 2) def submit(self, this): train = this.train test = this.test dummy = this.dummy id = this.id context = this.context clf = SVC() clf.fit(train, dummy) prediction = clf.predict(test) submission = pd.DataFrame( {'PassengerId': id, 'Survived': prediction} ) print(submission.head()) submission.to_csv(context + '/submission.csv', index=False)<file_sep>/titanic/__init__.py from titanic.view import View from titanic.controller import Controller if __name__ == '__main__': def print_menu(): print('0. 종료') print('1. 시각화') print('2. 머신러닝') print('3. 머신생성') return input('메뉴 입력\n') while 1: menu = print_menu() if menu == '1': vue = View('train.csv') menu = input('차트 내용 선택\n' '1. 생존자 vs 사망자\n' '2. 생존자 성별 대비\n') if menu == '1': vue.plot_survived_dead() elif menu == '2': vue.plot_sex() if menu == '2': app = Controller() app.learning('train.csv','test.csv') if menu == '3': app = Controller() app.submit('train.csv','test.csv') elif menu == '0': pass<file_sep>/text_mining/__init__.py from text_mining.controller import Controller if __name__ == '__main__': ctrl = Controller() ctrl.run()<file_sep>/contacts/controller.py from contacts.service import Service class Controller: def __init__(self): self.service = Service() @staticmethod def print_menu(): print('1. 연락처 입력: ') print('2. 연락처 출력: ') print('3. 연락처 삭제: ') print('0. 종료 ') return input('메뉴 선택 \n') def run(self): contacts = [] while 1: menu = self.print_menu() print('메뉴 : %s' % menu) if menu == '1': name = input('이름 \n') phone = input('전화번호 \n') email = input('이메일 \n') addr = input('주소 \n') t = self.service.set_contact(name, phone, email, addr) contacts.append(t) elif menu == '2': print(self.service.get_contacts(contacts)) elif menu == '3': name = input('삭제할 이름') self.service.del_contact(contacts, name) elif menu == '0': print('시스템 종료') break <file_sep>/web_crawling/model.py from bs4 import BeautifulSoup from urllib.request import urlopen import pandas as pd from selenium import webdriver class BugsCrawler: def __init__(self, url): self.url = url def scrap(self): soup = BeautifulSoup(urlopen(self.url),'html.parser') n_artist = 0 n_title = 0 for i in soup.find_all(name='p', attrs=({'class':'artist'})): n_artist += 1 print(str(n_artist)+'위') print('아티스트: '+i.find('a').text) print('----------------') for i in soup.find_all(name='p', attrs=({'class':'title'})): n_title += 1 print(str(n_title)+'위') print('음악: '+i.text) class NaverStockCrawler: def __init__(self, code): self.code = code def scrap(self): url = 'https://finance.naver.com/item/sise_day.nhn?code={code}'.format(code=self.code) soup = BeautifulSoup(urlopen(url),'html.parser') print('출력 \n') for i in soup.find_all(name='span', attrs=({'class':'tah p11'})): print('종가 : '+str(i.text)) class KrxCrawler: def __init__(self, url): self.url = url def scrap(self): code = pd.read_html(self.url)[0] print(code) class NaverMovieCrawler: def __init__(self, url): self.driver = webdriver.Chrome(executable_path='C:/Users/user/H/hanbit/iowa/basic/web_crawling/driver') self.driver.get(url) self.soup = BeautifulSoup(self.driver.page_source, 'html.parser') def scrap(self): print(self.soup.prettify()) all_divs = self.soup.find_all('div', attrs={'class','tit3'}) products = [div.a.string for div in all_divs] for product in products: print(product) self.driver.close()<file_sep>/titanic/view.py import matplotlib.pyplot as plt from matplotlib import font_manager, rc import seaborn as sns from titanic.service import Service from titanic.model import Model rc('font', family = font_manager .FontProperties(fname='C:/Windows/Fonts/H2GTRE.ttf') .get_name()) class View: def __init__(self, fname): service = Service() self._model = service.new_model(fname) def plot_survived_dead(self): this = self._model f, ax = plt.subplots(1, 2, figsize=(18, 8)) this['Survived'] \ .value_counts() \ .plot.pie(explode=[0, 0.1], autopct='%1.1f%%', ax=ax[0], shadow=True) ax[0].set_title('0.사망자 VS 1.생존자') ax[0].set_ylabel('') ax[1].set_title('0.사망자 VS 1.생존자') sns.countplot('Survived', data=this, ax=ax[1]) plt.show() def plot_sex(self): this = self._model f, ax = plt.subplots(1, 2, figsize=(18, 8)) this['Survived'][this['Sex'] == 'male'] \ .value_counts() \ .plot.pie(explode=[0, 0.1], autopct='%1.1f%%', ax=ax[0], shadow=True) this['Survived'][this['Sex'] == 'female'] \ .value_counts() \ .plot.pie(explode=[0, 0.1], autopct='%1.1f%%', ax=ax[1], shadow=True) ax[0].set_title('남성의 생존비율 (0:사망자,1:생존자)') ax[1].set_title('여성의 생존비율 (0:사망자,1:생존자)') plt.show()<file_sep>/web_crawling/controller.py from web_crawling.service import Service from web_crawling.model import BugsCrawler class Controller: def __init__(self): self.service = Service() @staticmethod def print_menu(): print('0. EXIT') print('1. 벅스뮤직') print('2. 네이버 주식') print('3. 네이버 영화') return input('메뉴선택\t') def run(self): while 1: menu = self.print_menu() print('메뉴 : %s ' % menu) if menu == '1': self.service.crawling('bugs') elif menu == '2': self.service.crawling('naver_stock') elif menu == '3': self.service.crawling('naver_movie') elif menu == '0': print('BYE') break <file_sep>/algo_intro/model.py class GreedyAlgorithm: def __init__(self): pass def find_minimun_number_of_coins(self): pass <file_sep>/titanic/controller.py from titanic.service import Service from titanic.model import Model class Controller: def __init__(self): self._service = Service() self._model = Model() def preprocess(self, train, test) -> object: service = self._service this = self._model this.train = service.new_model(train) this.test = service.new_model(test) this.id = this.test['PassengerId'] this = service.drop_feature(this, 'Cabin') this = service.drop_feature(this, 'Ticket') this = service.embarked_norminal(this) this = service.title_nominal(this) this = service.drop_feature(this, 'Name') this = service.drop_feature(this, 'PassengerId') this = service.age_ordinal(this) this = service.drop_feature(this, 'Fare') this = service.sex_nominal(this) this = service.fareBand_norminal(this) print('트레인 컬럼 {}'.format(this.test.columns)) print('널의 수량 {} 개'.format(this.test.isnull().sum())) return this def modeling(self,train, test): service = self._service this = self.preprocess(train, test) this.dummy = service.create_dummy(this) this.train = service.create_train(this) this.kfold = service.create_kfold() this.context = './data' print('<<<< MODELING SUCCESS >>>>') return this def learning(self, train, test): service = self._service this = self.modeling(train, test) print('KNN 활용한 검증 정확도 {} %'.format(service.accuracy_by_knn(this))) print('결정트리 활용한 검증 정확도 {} %'.format(service.accuracy_by_dtree(this))) print('랜덤포리스트 활용한 검증 정확도 {} %'.format(service.accuracy_by_rforest(this))) print('나이브베이즈 활용한 검증 정확도 {} %'.format(service.accuracy_by_nb(this))) print('SVM 활용한 검증 정확도 {} %'.format(service.accuracy_by_svm(this))) print('<<<< TEST SUCCESS >>>>') def submit(self, train, test): service = self._service this = self.modeling(train, test) service.submit(this) print('<<<< SUBMIT SUCCESS >>>>')<file_sep>/contacts/model.py class Contact: def __init__(self, name, phone, email, addr): self.name = name self.phone = phone self.email = email self.addr = addr def to_string(self): return '이름 : {} \n 전화번호 : {} \n 주소 : {} \n 이메일 : {}'\ .format(self.name, self.phone, self.email, self.addr)<file_sep>/mnist/__init__.py import tensorflow as tf from mnist.service import Service if __name__ == '__main__': service = Service() def print_menu(): print('0. 종료') print('1. 모델생성') return input('메뉴 입력\n') while 1: menu = print_menu() if menu == '1': service.create_model() elif menu == '0': pass<file_sep>/kbstar/service.py import pandas as pd import xlwings as xw from kbstar.model import Model class Service: def __init__(self): self._model = Model() def new_model(self, param): model = self._model model.context = './data' model.fname = param print(model.fname) wb = xw.Book(model.context + '/' + model.fname) sheet = wb.sheets['매매종합'] row_num = sheet.range(1, 1).end('down').end('down').row data_range = 'A2:GE' + str(row_num) raw_data = sheet[data_range] \ .options(pd.DataFrame, index=False, header=True).value return raw_data <file_sep>/kbstar/controller.py from kbstar.service import Service from kbstar.model import Model class Controller: def __init__(self): self._service = Service() self._model = Model() def preprocess(self, train, test) -> object: service = self._service this = self._model def modeling(self,train, test): service = self._service this = self.preprocess(train, test) def learning(self, train, test): service = self._service this = self.modeling(train, test) def submit(self, train, test): service = self._service this = self.modeling(train, test)<file_sep>/contacts/service.py from contacts.model import Contact class Service: def __init__(self): pass @staticmethod def set_contact(name, phone, email, addr): return Contact(name, phone, email, addr) @staticmethod def get_contacts(params): contacts = [] for i in params: contacts.append(i.to_string()) return ' '.join(contacts) @staticmethod def del_contact(params, name): for i, t in enumerate(params): if t.name == name: del params[i] <file_sep>/text_mining/service.py from text_mining.model import SamsungReport class Service: def __init__(self): self.sam = SamsungReport() def execute(self, option): if option == '1': self.sam.read_file() elif option == '2': self.sam.download() elif option == '3': self.sam.read_stopword() elif option == '4': self.sam.hook() elif option == '5': self.sam.draw_wordcloud() <file_sep>/calculator/service.py from calculator.model import Calulator class Service: def __init__(self, num1, num2): self.calc = Calulator(num1, num2) def exec(self, op): if op == '+': result = self.calc.add() elif op == '-': result = self.calc.sub() elif op == '*': result = self.calc.multi() elif op == '/': result = self.calc.divid() return result<file_sep>/web_crawling/__init__.py from web_crawling.controller import Controller if __name__ == '__main__': ctrl = Controller() ctrl.run()<file_sep>/tf_calc/service.py import tensorflow as tf from tf_calc.model import Model class Service: def __init__(self): self._this = Model() @tf.function def plus(self, num1, num2): return tf.add(num1, num2) @tf.function def minus(self, this): return tf.subtract(this.num1, this.num2) @tf.function def multiple(self, this): return tf.multiply(this.num1, this.num2) @tf.function def divid(self, this): return tf.div(this.num1, this.num2) <file_sep>/calculator/controller.py from calculator.service import Service class Controller: def __init__(self): num1 = int(input('첫번째 수')) num2 = int(input('두번째 수')) service = Service(num1, num2) op = input('연산자 입력') result = service.exec(op) print('계산결과 : %d' % result)<file_sep>/text_mining/controller.py from text_mining.service import Service class Controller: def __init__(self): self.service = Service() def print_menu(self): print('0. 종료\n') print('1. 파일읽기\n') print('2. 자연어 처리키트 다운로드\n') print('3. 삭제할 단어 보기\n') print('4. 빈출단어 목록보기\n') print('5. 워드클라우드 보기\n') return input('메뉴 선택\n') def run(self): while 1: menu = self.print_menu() if menu == '1': self.service.execute('1') if menu == '2': self.service.execute('2') if menu == '3': self.service.execute('3') if menu == '4': self.service.execute('4') if menu == '5': self.service.execute('5') elif menu == '0': break<file_sep>/titanic/model.py class Model: def __init__(self): self._context = '' self._fname = '' self._train = None self._test = None self._id = None self._dummy = None self._kfold = None @property def context(self) -> str: return self._context @context.setter def context(self, context): self._context = context @property def fname(self) -> str: return self._fname @fname.setter def fname(self, fname): self._fname = fname @property def train(self) -> object: return self._train @train.setter def train(self,train): self._train = train @property def test(self) -> object : return self._test @test.setter def test(self, test): self._test = test @property def id(self) -> object: return self._id @id.setter def id(self, id): self._id = id @property def dummy(self) -> object: return self._dummy @dummy.setter def dummy(self, dummy): self._dummy = dummy @property def kfold(self) -> object: return self._kfold @kfold.setter def kfold(self, kfold): self._kfold = kfold<file_sep>/text_mining/model.py from konlpy.tag import Okt from nltk.tokenize import word_tokenize import nltk import re import pandas as pd from nltk import FreqDist from wordcloud import WordCloud import matplotlib.pyplot as plt class SamsungReport: def __init__(self): self.okt = Okt() def read_file(self): self.okt.pos("삼성전자 글로벌센터 전자사업부", stem=True) filename = './data/kr-Report_2018.txt' with open(filename, 'r', encoding='utf-8') as f: texts = f.read() return texts @staticmethod def extract_hangeul(texts): temp = texts.replace('\n', ' ') tokenizer = re.compile(r'[^ ㄱ-힣]+') temp = tokenizer.sub('', temp) return temp @staticmethod def change_token(texts): tokens = word_tokenize(texts) return tokens def extract_noun(self): noun_tokens = [] tokens = self.change_token(self.extract_hangeul(self.read_file())) for token in tokens: token_pos = self.okt.pos(token) temp = [txt_tag[0] for txt_tag in token_pos if txt_tag[1] == 'Noun'] if len(''.join(temp)) > 1: noun_tokens.append("".join(temp)) texts = " ".join(noun_tokens) return texts @staticmethod def download(): nltk.download() @staticmethod def read_stopword(): stopfile = './data/stopwords.txt' with open(stopfile, 'r', encoding='utf-8') as f: stopwords = f.read() stopwords = stopwords.split(' ') return stopwords def remove_stopword(self): texts = self.extract_noun() tokens = self.change_token(texts) stopwords = self.read_stopword() texts = [text for text in tokens if text not in stopwords] return texts def hook(self): texts = self.remove_stopword() freqtxt = pd.Series(dict(FreqDist(texts))).sort_values(ascending=False) print(freqtxt[:30]) return freqtxt def draw_wordcloud(self): texts = self.remove_stopword() wcloud = WordCloud('./data/D2Coding.ttf', relative_scaling=0.2, background_color='white').generate(" ".join(texts)) plt.figure(figsize=(12,12)) plt.imshow(wcloud, interpolation='bilinear') plt.axis('off') plt.show() <file_sep>/mnist/service.py import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt import numpy as np class Service: def __init__(self): self.class_names = ['T-shirt/top','Trouser','Pullover', 'Dress','Coat','Sandal','Shirt' ,'Sneaker','Bag','Ankle boot'] def create_model(self): fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) \ = fashion_mnist.load_data() """ train_images = train_images / 255.0 test_images = test_images / 255.0 plt.figure() plt.imshow(train_images[15]) plt.colorbar() plt.grid(False) plt.show() """ train_images = train_images / 255.0 test_images = test_images / 255.0 plt.figure(figsize=(10,10)) for i in range(25): plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(train_images[i], cmap=plt.cm.binary) plt.xlabel(self.class_names[train_labels[i]]) plt.show() model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10, activation='softmax') ])
b18a1a4ee694c7f328a89423e7586ade4ecdc0a5
[ "Python" ]
27
Python
rivery811/pythontitanic
0ed92f486e1cc185052f7eb2a1cbb43e936946dd
fbeffb7c110e27b624ce9b51b8723897a4706eb0
refs/heads/master
<file_sep># whatwg-streams-b An unofficial [WHATWG Streams][whatwg/streams] npm package. [whatwg/streams]: https://github.com/whatwg/streams ## License ### `lib/` [CC0-1.0 OR MIT](https://github.com/whatwg/streams/blob/ff1d3c9af8a01f4b03a508281844b72a92b533c7/reference-implementation/LICENSE.md) Copyright (c) 2013–2015 Streams Standard Reference Implementation Authors ### `index.js` and `index.d.ts` [MIT](LICENSE) bouzuya ## Author [bouzuya][user] &lt;[<EMAIL>][email]&gt; ([http://bouzuya.net][url]) [user]: https://github.com/bouzuya [email]: mailto:<EMAIL> [url]: http://bouzuya.net <file_sep>export declare class ReadableByteStreamController<T> { constructor( stream: ReadableStream<T>, underlyingByteSource: Source<T>, highWaterMark: number ); readonly byobRequest: any; readonly desiredSize: number; close(): void; enqueue(chunk: T): void; error(error: any): void; } export declare class ReadableStreamDefaultController<T> { constructor( stream: ReadableStream<T>, underlyingSource: Source<T>, size: ((chunk: T) => number) | undefined, highWaterMark: number ); readonly desiredSize: number; close(): void; enqueue(chunk: T): void; error(error: any): void; } export type ReadableStreamController<T> = ReadableStreamDefaultController<T> | ReadableByteStreamController<T>; export interface ReadableStreamDefaultReader<T> { // constructor(stream) readonly closed: Promise<void>; cancel(reason: any): Promise<void>; read(): Promise<T>; releaseLock(): void; } export interface ReadableStreamBYOBReader<T> { readonly closed: Promise<void>; cancel(reason: any): Promise<void>; read(view: any): Promise<T>; // ArrayBuffer.isView(view) === true && view.byteLength > 0 releaseLock(): void; } export type ReadableStreamReader<T> = ReadableStreamDefaultReader<T> | ReadableStreamBYOBReader<T>; export interface Source<T> { type?: 'bytes' | undefined; start?(controller: ReadableStreamController<T>): Promise<any> | any | void; pull?(controller: ReadableStreamController<T>): Promise<any> | any | void; cancel?(reason: any): Promise<any> | any | void; } export interface QueuingStrategy<T> { size?: (chunk: T) => number; readonly highWaterMark?: number; } export declare class ByteLengthQueuingStrategy< T extends { byteLength: number; } > implements QueuingStrategy<T> { constructor({ highWaterMark }: { highWaterMark: number; }); size: (chunk: { byteLength: number; }) => number; readonly highWaterMark: number; } export declare class CountQueuingStrategy<T> implements QueuingStrategy<T> { constructor({ highWaterMark }: { highWaterMark: number; }); size: (chunk: T) => number; readonly highWaterMark: number; } export declare class ReadableStream<T> { constructor( underlyingSource?: Source<T>, options?: QueuingStrategy<T> ); readonly locked: boolean; cancel(reason: any): Promise<void>; getReader(options?: { mode?: string; }): ReadableStreamReader<T>; pipeThrough<U>( transform: { writable: WritableStream<T>; readable: ReadableStream<U>; }, options?: { preventClose?: boolean; preventAbort?: boolean; preventCancel?: boolean; } ): ReadableStream<U>; pipeTo( dest: WritableStream<T>, options?: { preventClose?: boolean; preventAbort?: boolean; preventCancel?: boolean; } ): Promise<void>; tee(): [ReadableStream<T>, ReadableStream<T>]; } export interface WritableStreamDefaultWriter<T> { // constructor(stream) readonly closed: Promise<void>; readonly desiredSize: number; readonly ready: Promise<void>; abort(reason: any): Promise<void>; close(): Promise<any>; releaseLock(): void; write(chunk: T): Promise<any>; } export interface TransformStreamDefaultController<T> { enqueue(chunk: T): void; close(): void; error(reason: any): void; } export type TransformStreamController<T> = TransformStreamDefaultController<T>; export class TransformStream<T, U> { constructor(transformer: { start?(controller: TransformStreamController<U>): any, transform?( chunk: T, controller: TransformStreamController<U> ): any, flush?( controller: TransformStreamController<U> ): any }); readable: ReadableStream<U>; writable: WritableStream<T>; } export declare class WritableStreamDefaultController<T> { constructor( stream: WritableStream<T>, underlyingSink: Sink<T>, size: ((chunk: T) => number) | undefined, highWaterMark: number ); error(error: any): void; } export type WritableStreamController<T> = WritableStreamDefaultController<T>; export interface Sink<T> { start?(controller: WritableStreamController<T>): Promise<any> | any | void; write?(chunk: T): Promise<any> | any | void; close?(): Promise<any> | any | void; abort?(reason: any): Promise<any> | any | void; } export declare class WritableStream<T> { constructor(underlyingSink?: Sink<T>); // constructor(underlyingSink = {}, { size, highWaterMark = 1 } = {}) readonly locked: boolean; abort(reason: any): Promise<any>; getWriter(): WritableStreamDefaultWriter<T>; }
da0bd3b934f5c904b0527f91242c36b95137d209
[ "Markdown", "TypeScript" ]
2
Markdown
bouzuya/whatwg-streams-b
c7d26cbaa4960ec4b0038413afb92f8d2b5f4ebb
c12dbe56910ce9b3691d3bc213a2bbc5825377b7
refs/heads/master
<file_sep># Action Unit (Multi-label) ## preprocess.py: 数据预处理, 将图片和标签读取,保存为Mxnet读取的rec文件 ```shell python preprocess.py -i ./images/(It's your imags path) -t ./label.txt(your label file) -rec ./data/train.rec(the output .rec file) -s 112 ``` ## train_with_eval.py: train code ```shell python train_with_eval.py -rec ./data/train.rec -e ./data/eval.rec -o ./output/ -gpu 0 ``` <file_sep># -*- coding: utf-8 -*- """ Created on Fri Nov 2 09:44:12 2018 @author: lmx """ import seaborn as sns import pandas as pd import numpy as np f1_path = '../test_data/data1.npy' f2_path = '../test_data/data2.npy' f1 = np.load(f1_path) f2 = np.load(f2_path) f_frown_1 = f1[0:len(f1):2] f_frown = f_frown_1 f_frown_2 = f2[:5] f_frown = np.concatenate([f_frown_1, f_frown_2]) f_laugh_1 = f1[1:len(f1):2] f_laugh = f_laugh_1 f_laugh_2 = f2[5:] f_laugh = np.concatenate([f_laugh_1, f_laugh_2]) # 同一个人两个表情间的距离 dist_inner = [] for i in range(len(f_frown)): dist_inner.append(np.linalg.norm(f_frown[i]-f_laugh[i])) #同一种表情间的距离 dist_frown = [] for i in range(len(f_frown)-1): dist_frown.extend(np.linalg.norm(f_frown[i]-f_frown[i+1:], axis=1)) dist_laugh = [] for i in range(len(f_laugh)-1): dist_laugh.extend(np.linalg.norm(f_laugh[i]-f_laugh[i+1:], axis=1)) dist_ex = np.concatenate([dist_frown, dist_laugh]) S = pd.Series(dist_inner) I = pd.Series(dist_ex) df = pd.concat([S, I], axis=1) sns.boxplot(data=df) dist_inner = pd.DataFrame(dist_inner) dist_frown = pd.DataFrame(dist_frown) dist_laugh = pd.DataFrame(dist_laugh) dist_inner.to_csv('../test_data/v2_inner.csv', index=False) dist_frown.to_csv('../test_data/v2_frown.csv', index=False) dist_laugh.to_csv('../test_data/v2_laugh.csv', index=False) <file_sep>from mxnet.gluon import nn class RegionLayer(nn.HybridBlock): def __init__(self, in_channels, grid=(8, 8), layout='NCHW', **kwargs): super(RegionLayer, self).__init__(**kwargs) self.in_channels = in_channels self.grid = grid self.layout = layout channel_axis = layout.find('C') self.region_layers = dict() with self.name_scope(): for i in range(self.grid[0]): for j in range(self.grid[1]): grid_name = 'region_conv_{}_{}'.format(i, j) features = nn.HybridSequential() features.add(nn.BatchNorm(axis=channel_axis)) features.add(nn.Activation('relu')) features.add(nn.Conv2D(channels=self.in_channels, kernel_size=3, strides=1, padding=1, layout=layout)) self.region_layers[grid_name] = features for name, block in self.region_layers.items(): self.register_child(block, name) def __repr__(self): s = '{name}({mapping}, grid={grid})' mapping = '{0} -> {1}'.format(self.in_channels, self.in_channels) return s.format(name=self.__class__.__name__, mapping=mapping, grid=self.grid) def hybrid_forward(self, F, x, *args, **kwargs): height_axis = self.layout.find('H') width_axis = self.layout.find('W') input_row_list = F.split(x, num_outputs=self.grid[0], axis=height_axis) output_row_list = [] for i, row in enumerate(input_row_list): input_grid_list_of_a_row = F.split(row, num_outputs=self.grid[1], axis=width_axis) output_grid_list_of_a_row = [] for j, grid in enumerate(input_grid_list_of_a_row): grid_name = 'region_conv_{}_{}'.format(i, j) grid = self.region_layers[grid_name](grid) + grid output_grid_list_of_a_row.append(grid) output_row = F.concat(*output_grid_list_of_a_row, dim=width_axis) output_row_list.append(output_row) output = F.concat(*output_row_list, dim=height_axis) output = F.relu(output) return output class DRML(nn.HybridBlock): def __init__(self, classes=12, grid=(8, 8), layout='NCHW', prefix='drml', **kwargs): super(DRML, self).__init__(prefix=prefix, **kwargs) self.classes = classes self.grid = grid channel_axis = layout.find('C') with self.name_scope(): self.features = nn.HybridSequential() # conv1 self.features.add(nn.Conv2D(channels=32, kernel_size=11, layout=layout)) # region2 self.features.add(RegionLayer(in_channels=32, grid=self.grid, layout=layout)) # pool3 self.features.add(nn.MaxPool2D(layout=layout)) self.features.add(nn.BatchNorm(axis=channel_axis)) # conv4~conv7 self.features.add(nn.Conv2D(channels=16, kernel_size=8, activation='relu', layout=layout)) self.features.add(nn.Conv2D(channels=16, kernel_size=8, activation='relu', layout=layout)) self.features.add(nn.Conv2D(channels=16, kernel_size=6, activation='relu', layout=layout)) self.features.add(nn.Conv2D(channels=16, kernel_size=5, activation='relu', layout=layout)) # fc8 self.features.add(nn.Dense(units=4096, activation='relu')) self.features.add(nn.Dropout(0.5)) # fc9 self.features.add(nn.Dense(units=2048, activation='relu')) self.features.add(nn.Dropout(0.5)) # output self.output = nn.Dense(units=self.classes) def hybrid_forward(self, F, x, *args, **kwargs): x = self.features(x) x = self.output(x) return x class PretrainedModel(nn.HybridBlock): def __init__(self, classes, symbol_file, param_file, ctx, **kwargs): super(PretrainedModel, self).__init__(prefix='') self.features = nn.SymbolBlock.imports(symbol_file, ['data'], param_file, ctx) self.output = nn.Dense(units=classes) # todo def hybrid_forward(self, F, x, *args, **kwargs): x1 = self.features(x) x = self.output(x1) return x1, x class VGGFace(nn.HybridBlock): def __init__(self, classes, symbol_file, param_file, ctx, **kwargs): super(VGGFace, self).__init__(prefix='') self.features = nn.SymbolBlock.imports(symbol_file, ['data'], param_file, ctx) self.output = nn.Dense(units=classes) def hybrid_forward(self, F, x, *args, **kwargs): x = self.features(x) x = self.output(x) return x class JAA(nn.HybridBlock): def __init__(self, classes, symbol_file, param_file, ctx, **kwargs): super(JAA, self).__init__(prefix='') self.features = nn.SymbolBlock.imports(symbol_file, ['data'], param_file, ctx) self.fc1 = nn.Dense(512, activation='relu') self.output1 = nn.Dense(classes) self.fc2 = nn.Dense(512, activation='relu') self.output2 = nn.Dense(136) def hybrid_forward(self, F, x, *args, **kwargs): x = self.features(x) x2 = self.fc2(x) x2 = self.output2(x2) x1 = self.fc1(x) x1 = F.concat(x1, x2) x1 = self.output1(x1) return F.concat(x1, x2) class LandmarkBlock(nn.HybridBlock): # todo: 结构 输出激活 def __init__(self, classes=136, prefix='landmark_'): super(LandmarkBlock, self).__init__(prefix) with self.name_scope(): self.features = nn.HybridSequential() self.features.add( self.conv2d_block(80, 5), nn.MaxPool2D(), self.conv2d_block(96, 4), nn.MaxPool2D(), self.conv2d_block(128, 3), self.conv2d_block(128, 3), nn.Flatten(), nn.Dense(1800, activation='relu'), # nn.Dropout(0.5), nn.Dense(1000, activation='relu'), # nn.Dropout(0.5), ) self.output = nn.Dense(classes, activation='sigmoid') # (0,1) @staticmethod def conv2d_block(num_filters, kernel_size): block = nn.HybridSequential() block.add(nn.Conv2D(num_filters, (kernel_size, kernel_size))) block.add(nn.BatchNorm()) block.add(nn.Activation(activation='relu')) return block def hybrid_forward(self, F, x, *args, **kwargs): x = self.features(x) x = self.output(x) return x class MultiTaskV1(nn.HybridBlock): def __init__(self, classes, symbol_file, param_file, ctx, **kwargs): super(MultiTaskV1, self).__init__(prefix='') self.features = nn.SymbolBlock.imports(symbol_file, ['data'], param_file, ctx) self.landmark = LandmarkBlock(classes=(68 - 17 - 8) * 2) self.fc = nn.Dense(512, activation='relu') self.output = nn.Dense(classes) def hybrid_forward(self, F, x, *args, **kwargs): landmark = self.landmark((x - 127.5) * 0.0078125) x = self.features(x) x = F.concat(x, landmark) # 128(512)+136 x = self.fc(x) x = self.output(x) return F.concat(x, landmark) class MultiTaskV2(nn.HybridBlock): def __init__(self, classes, symbol_file, param_file, ctx, **kwargs): super(MultiTaskV2, self).__init__(prefix='') self.emb_feats = nn.SymbolBlock.imports(symbol_file, ['data'], param_file, ctx) self.landmark_fc1 = nn.Dense(256, activation='relu') self.landmark_fc2 = nn.Dense(256, activation='relu') self.landmark_output = nn.Dense((68 - 17 - 8) * 2, activation='sigmoid') # self.au_fc = nn.Dense(512, activation='relu') self.au_output = nn.Dense(classes) def hybrid_forward(self, F, x, *args, **kwargs): feats = self.emb_feats(x) landmark = self.landmark_fc1(feats) landmark = self.landmark_fc2(landmark) landmark = self.landmark_output(landmark) au = feats # au = self.au_fc(au) au = self.au_output(au) return F.concat(au, landmark) <file_sep># -*- coding: utf-8 -*- """ Created on Sun Oct 21 10:07:19 2018 @author: lmx """ # 得到128维特征 import mxnet as mx import mxnet.gluon.data.vision.transforms as T from mxnet import gluon, nd, autograd from tqdm import tqdm from train_with_eval import Transpose, TransposeChannels import numpy as np from sklearn.preprocessing import normalize import pandas as pd import os import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--checkpoint', '-model', default='../model_ziqi/v4_1/checkpoint/model-0100.params', help='path of .params file of model') parser.add_argument('--gpu-device', '-gpu', type=int, required=True, help='specify gpu id') parser.add_argument('--record', '-rec', default='../Data/data_ziqi/rec/train_above50_newlabel.rec', help='path of .rec file of target data') parser.add_argument('--out-dir', '-out', default='../Data/data_ziqi/npy/train/', help='save path of .npy file of target features and labels') args = parser.parse_args() checkpoint =args.checkpoint ctx = mx.gpu(args.gpu_device) if args.gpu_device else mx.cpu() symbol_file = checkpoint[:-11] + 'symbol.json' net = gluon.SymbolBlock.imports(symbol_file, ['data'], checkpoint, ctx) record = args.record out_dir = args.out_dir os.makedirs(out_dir, exist_ok=True) transform = T.Compose([T.Resize(112), Transpose()]) features = [] labels_ori = [] labels = [] dataloader = gluon.data.DataLoader( dataset=gluon.data.vision.ImageRecordDataset( filename=record, transform=lambda x, y: (transform(x), y) ), batch_size=1, shuffle=False, last_batch='keep' ) for x, y in tqdm(dataloader, desc='Evaluating', leave=False): x = x.as_in_context(ctx) y = y.as_in_context(ctx) f, pred = net(x) f = normalize(f.asnumpy()) features.append(f) y = y.asnumpy() y = np.array(y, dtype=np.int) labels_ori.append(y) valid = np.not_equal(y, 999) label = np.bitwise_and(valid, y) labels.append(label) np.save(out_dir + 'features.npy', features) labels_ori = np.squeeze(labels_ori, axis=1) labels_ori = pd.DataFrame(labels_ori) labels = np.squeeze(labels, axis=1) labels = pd.DataFrame(labels) labels_ori.to_csv(out_dir + 'label.csv', index=False) labels.to_csv(out_dir + 'label_no999.csv', index=False)<file_sep># -*- coding: utf-8 -*- """ Created on Sun Oct 21 14:01:48 2018 @author: lmx """ import numpy as np import argparse import pandas as pd if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--target', '-t', default='../new_npy_m0.5/target/features.npy', help='path of .npy file of target features') parser.add_argument('--target-label', '-label', default='../new_npy_m0.5/target/label_no999.csv', help='path of .csv file of target data labels') parser.add_argument('--distractor', '-d', default='../new_npy_m0.5/distractor/features.npy', help='path of .npy file of distractor features') parser.add_argument('--target-class', '-c', default='../tongji/new_target_classes.csv', help='path of .csv file of target classes') args = parser.parse_args() target_features = np.load(args.target) target_features = np.squeeze(target_features, axis=1) distractor_data = np.load(args.distractor) distractor_data = np.squeeze(distractor_data, axis=1) label = pd.read_csv(args.target_label) label = np.array(label) classes = pd.read_csv(args.target_class) classes = np.array(classes) # 将target feature按类组合 target_data = [] for i in range(len(classes)): data = [] for j in range(len(label)): if (label[j] == classes[i]).all(): data.append(target_features[j]) target_data.append(data) print('target classes:', np.shape(target_data)) print('distractor samples:', np.shape(distractor_data)) # 正样本对, 第一列是label,第二列是预测距离标签 pos_data = [] threshold = 1 for i in range(len(target_data)): # 每一类内随机挑2个配 every_class = target_data[i] for j in range(len(every_class)-1): dist = np.linalg.norm(every_class[j]-every_class[j+1:], axis=1) pos_data.extend((dist<threshold).astype(np.int)) pos_label = np.ones(len(pos_data)) print('pos: ', np.shape(pos_data), 'pos_label:', np.shape(pos_label)) # 负样本对 neg_data = [] for i in range(len(target_data)): # target中挑选一个类 every_class = target_data[i] for j in range(len(every_class)): # 挑选类中的一个样本 f1 = every_class[j] # 与distractor中所有去配对 dist = np.linalg.norm(f1-distractor_data, axis=1) neg_data.extend((dist<threshold).astype(np.int)) # target中类与类之间去配对,组成负样本 if i<len(target_data)-1: for c in range(i+1, len(target_data)): # 选其他类 new_class = target_data[c] dist = np.linalg.norm(f1-new_class, axis=1) neg_data.extend((dist<threshold).astype(np.int)) neg_label = np.zeros(len(neg_data)) print('neg: ', np.shape(neg_data), 'neg_label:', np.shape(neg_label)) label = np.hstack((pos_label, neg_label)) data = np.hstack((pos_data, neg_data)) print('all: ', data.shape, label.shape) # 统计tpr fpr # 计算混淆矩阵tp/fp/fn/tn tp = 0 tn = 0 fp = 0 fn = 0 tp += np.sum(np.bitwise_and(np.equal(label, 1), np.equal(data, 1)).astype(np.int32), axis=0) tn += np.sum(np.bitwise_and(np.equal(label, 0), np.equal(data, 0)).astype(np.int32), axis=0) fp += np.sum(np.bitwise_and(np.equal(label, 0), np.equal(data, 1)).astype(np.int32), axis=0) fn += np.sum(np.bitwise_and(np.equal(label, 1), np.equal(data, 0)).astype(np.int32), axis=0) tpr = tp/(tp+fn) fpr = fp/(fp+tn) print('tpr, fpr', tpr,fpr)<file_sep>import os import pickle import random import mxnet as mx from mxnet import recordio from mxnet.gluon.data.dataset import Dataset class ImageRecordDataset(Dataset): def __init__(self, filenames, transform=None, with_landmark=False, horizontal_flip=False): self.filenames = filenames self.transform = transform self.with_landmark = with_landmark self.horizontal_flip = horizontal_flip self._fork() def __getitem__(self, idx): i, j = self.orig_idx[idx] item = self.records[i].read_idx(j) header, s = recordio.unpack(item) img = mx.image.imdecode(s, 1) label = header.label if self.transform: img, label = self.transform(img, label) need_flip = self.horizontal_flip and random.random() > 0.5 img = mx.nd.flip(img, axis=2) if need_flip else img if self.with_landmark: landmark = mx.nd.array(self.landmark_dicts[i][j]) landmark = landmark[17 * 2:-8 * 2] landmark = mx.nd.clip(landmark, 0, 224) if need_flip: landmark[::2] = 224 - landmark[::2] return img, label, landmark return img, label def __len__(self): return len(self.orig_idx) def _fork(self): self.records = [recordio.MXIndexedRecordIO(os.path.splitext(fname)[0] + '.idx', fname, 'r') for fname in self.filenames] self.orig_idx = {} idx = 0 for i, r in enumerate(self.records): for j in r.keys: self.orig_idx[idx] = (i, j) idx += 1 self.landmark_dicts = {} if self.with_landmark: for i, fname in enumerate(self.filenames): landmark_file = os.path.splitext(fname)[0] + '.landmark' with open(landmark_file, 'rb') as f: self.landmark_dicts[i] = pickle.load(f) <file_sep>import numpy as np from mxnet import nd import pdb def _to_numpy(*args): ret = [] for arr in args: if isinstance(arr, nd.NDArray): ret.append(arr.asnumpy()) elif isinstance(arr, np.ndarray): ret.append(arr) else: raise TypeError('Expect type: (numpy.ndarrary, mxnet.nd.NDArray) ' 'but get {}'.format(type(arr))) if len(ret) == 1: ret = ret[0] return ret class Metric(object): def __init__(self, label_names, name='metric'): self.label_names = label_names self.metric_name = name def get(self): raise NotImplementedError def get_name_value(self): return dict(zip(*self.get())) def get_average(self): return float(np.mean(self.get()[1])) def update(self, labels, preds): raise NotImplementedError def reset(self): raise NotImplementedError def _check_shape(self, labels, preds): label_shape, pred_shape = labels.shape, preds.shape if label_shape != pred_shape: raise ValueError("Shape of labels {} does not match shape of " "predictions {}".format(label_shape, pred_shape)) if label_shape[1] != len(self.label_names): raise ValueError("Dimension {} does not match num of " "label_names {}".format(label_shape[1], len(self.label_names))) class Accuracy(Metric): def __init__(self, label_names, name='acc'): super(Accuracy, self).__init__(label_names, name) self.num_correct = np.zeros(len(self.label_names), dtype=np.int32) self.num_total = np.zeros(len(self.label_names), dtype=np.int32) def get(self): return self.label_names, np.divide(self.num_correct, self.num_total).tolist() def update(self, labels, preds): if not isinstance(labels, (list, tuple)): labels = [labels] if not isinstance(preds, (list, tuple)): preds = [preds] assert len(labels) == len(preds) for label, pred in zip(labels, preds): self._check_shape(label, pred) label, pred = _to_numpy(label, pred) valid = np.not_equal(label, 999) correct = np.equal(pred, label) self.num_correct += np.sum(np.bitwise_and(valid, correct).astype(np.int32), axis=0) # self.num_total += np.sum(valid.astype(np.int32), axis=0) self.num_total += (np.ones(label.shape[1], dtype=np.int32) * label.shape[0]) def reset(self): self.num_correct[:] = 0 self.num_total[:] = 0 class F1(Metric): def __init__(self, label_names, name='f1'): super(F1, self).__init__(label_names, name) self.true_positive = np.zeros(len(self.label_names), dtype=np.int32) self.true_negative = np.zeros(len(self.label_names), dtype=np.int32) self.false_positive = np.zeros(len(self.label_names), dtype=np.int32) self.false_negative = np.zeros(len(self.label_names), dtype=np.int32) self.num_total = np.zeros(len(self.label_names), dtype=np.int32) def get(self): denominator = 2 * self.true_positive + self.false_positive + self.false_negative return self.label_names, np.where(denominator > 0, 2 * self.true_positive / denominator, 0).tolist() def update(self, labels, preds): if not isinstance(labels, (list, tuple)): labels = [labels] if not isinstance(preds, (list, tuple)): preds = [preds] assert len(labels) == len(preds) for label, pred in zip(labels, preds): self._check_shape(label, pred) label, pred = _to_numpy(label, pred) self.num_total += np.sum(np.not_equal(label, 999).astype(np.int32), axis=0) self.true_positive += np.sum(np.bitwise_and(np.equal(label, 1), np.equal(pred, 1)).astype(np.int32), axis=0) self.true_negative += np.sum(np.bitwise_and(np.equal(label, 0), np.equal(pred, 0)).astype(np.int32), axis=0) self.false_positive += np.sum(np.bitwise_and(np.equal(label, 0), np.equal(pred, 1)).astype(np.int32), axis=0) self.false_negative += np.sum(np.bitwise_and(np.equal(label, 1), np.equal(pred, 0)).astype(np.int32), axis=0) def reset(self): self.true_positive[:] = 0 self.true_negative[:] = 0 self.false_positive[:] = 0 self.false_negative[:] = 0 self.num_total[:] = 0 class CorruptionMatrix(Metric): def __init__(self, label_names, name='corruption'): super(CorruptionMatrix, self).__init__(label_names, name) self.C_accum = np.zeros((len(label_names), 2, 2)) self.num_example = np.zeros((len(label_names), 2)) def update(self, labels, probs): if not isinstance(labels, (list, tuple)): labels = [labels] if not isinstance(probs, (list, tuple)): probs = [probs] assert len(labels) == len(probs) for label, prob in zip(labels, probs): self._check_shape(label, prob) label, prob = _to_numpy(label, prob) self.C_accum[:, 0, 0] += np.sum(np.bitwise_and(label == 1, prob >= 0.5) * prob, axis=0) self.C_accum[:, 0, 1] += np.sum(np.bitwise_and(label == 1, prob < 0.5) * (1 - prob), axis=0) self.C_accum[:, 1, 0] += np.sum(np.bitwise_and(label == 0, prob >= 0.5) * prob, axis=0) self.C_accum[:, 1, 1] += np.sum(np.bitwise_and(label == 0, prob < 0.5) * (1 - prob), axis=0) self.num_example[:, 0] += np.sum(label == 1, axis=0) self.num_example[:, 1] += np.sum(label == 0, axis=0) def get(self): C = self.C_accum / np.repeat(np.expand_dims(self.num_example, 2), 2, axis=2) return self.label_names, C.reshape((-1, 4)).tolist() def reset(self): self.C_accum[:] = 0 self.num_example[:] = 0 <file_sep># Action Unit (Multi-class) ## data_process: 数据处理 * count.ipynb:数据类别统计和分类 * get_128d.py:利用已训练模型进行特征提取 * tsne_feature.ipynb:利用TSNE将特征降维显示 * acc.py: 计算top-1 * tprfpr.py: 计算tpr、fpr * preprocess.py:数据预处理,将图片和标签读取,保存为Mxnet读取的rec文件 ```shell python preprocess.py -i ./images/(It's your imags path) -t ./label.txt(your label file) -rec ./data/train.rec(the output .rec file) -s 112 ``` ## train: train code ```shell python train.py -num 22(类别数) -rec ./data/train.rec -e ./data/eval.rec -o ./output/ -gpu 0 ``` <file_sep>import argparse import os import glob import cv2 import pandas as pd import mxnet as mx from tqdm import tqdm if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--image-dir', '-i', required=True) parser.add_argument('--txt', '-t', required=True, help='.txt file or directory of .txt files') parser.add_argument('--record', '-rec', required=True) parser.add_argument('--resize', '-s', type=int) args = parser.parse_args() tqdm.write('Arguments:') for k, v in vars(args).items(): tqdm.write(' - {}: {}'.format(k, v)) # Get input arguments image_dir = os.path.abspath(os.path.expanduser(args.image_dir)) txt = os.path.abspath(os.path.expanduser(args.txt)) txt_paths = [txt] if os.path.isfile(txt) else glob.glob(os.path.join(txt, '*.txt')) record_path = os.path.abspath(os.path.expanduser(args.record)) image_size = args.resize or None # Check validity of argument values if not os.path.exists(image_dir): raise IOError('image_dir "{}" not exist!'.format(image_dir)) if not os.path.exists(txt): raise IOError('txt "{}" not exist!'.format(txt)) if image_size and image_size <= 0: raise ValueError('resize value expected to be > 0, but get {}'.format(image_size)) os.makedirs(os.path.dirname(record_path), exist_ok=True) # Scan all images all_images = [] sub_dirs = [name for name in os.listdir(args.image_dir) if os.path.isdir(os.path.join(args.image_dir, name))] for sub_dir in tqdm(sub_dirs, desc='Scanning images'): image_fnames = [name for name in os.listdir(os.path.join(args.image_dir, sub_dir)) if not name.startswith('.') and name.endswith('.jpg')] all_images.extend(image_fnames) all_images = set(all_images) tqdm.write('Found total {} images in "{}".'.format(len(all_images), args.image_dir)) # Load all txt files aus = [1, 2, 4, 5, 6, 9, 12, 17, 20, 25, 26, 43] names = ['image'] + ['AU{:0>2}'.format(i) for i in aus] cols = [0] + [i + 1 for i in aus] types = dict(zip(names, ['str'] + ['int'] * len(aus))) start_index = 0 txt_dfs = [] # Load all txt files for path in tqdm(txt_paths, desc='Loading txt files'): txt_df = pd.read_csv(path, sep='\t', names=names, usecols=cols, dtype=types) txt_df['image'] = txt_df['image'].str[-22:] txt_df.index = list(range(0, txt_df.shape[0])) txt_dfs.append(txt_df) start_index += txt_df.shape[0] # Concatenate and reset index total_df = pd.concat(txt_dfs) tqdm.write('Found {} labels in {}'.format(total_df.shape[0], args.txt)) total_df = total_df[total_df['image'].isin(all_images)] total_df.reset_index(drop=True, inplace=True) # Write record files record = mx.recordio.MXIndexedRecordIO(os.path.splitext(record_path)[0] + '.idx', record_path, 'w') for i, row in tqdm(total_df.iterrows(), total=total_df.shape[0], desc='Converting'): sub_dir = row['image'][:12] path = os.path.join(image_dir, sub_dir, row['image']) image = cv2.imread(path) if image_size: image = cv2.resize(image, (image_size, image_size)) label = row['AU01':'AU43'].tolist() header = mx.recordio.IRHeader(flag=0, label=label, id=i, id2=0) s = mx.recordio.pack_img(header, image, quality=100, img_fmt='.jpg') record.write_idx(i, s) record.close() <file_sep>import argparse import collections import datetime import os import shutil import mxnet as mx import mxnet.gluon.data.vision.transforms as T from colorama import init, Fore from mxboard import SummaryWriter from mxnet import gluon, nd, autograd from mxnet.gluon.model_zoo import vision, model_store from prettytable import PrettyTable from tqdm import tqdm from data import ImageRecordDataset from metric import Accuracy, F1 from network import DRML, PretrainedModel, VGGFace init(autoreset=True) class DataLoaderWrapper(object): def __init__(self, data_loader): self.data_loader = data_loader self._gen = self.__gen__() def __next__(self): return next(self._gen) def __gen__(self): while True: for i in self.data_loader: yield i class RandomCrop(gluon.Block): def __init__(self, size, interp=2): super(RandomCrop, self).__init__() if isinstance(size, collections.Iterable): assert len(size) == 2 self.size = size else: self.size = (size, size) self.interp = interp def forward(self, x): return mx.image.random_crop(x, self.size, self.interp)[0] class TransposeChannels(gluon.HybridBlock): def __init__(self): super(TransposeChannels, self).__init__() def hybrid_forward(self, F, x, *args, **kwargs): return F.reverse(x, axis=0) class Transpose(gluon.HybridBlock): def __init__(self): super(Transpose, self).__init__() def hybrid_forward(self, F, x, *args, **kwargs): return F.cast(F.transpose(x, (2, 0, 1)), dtype='float32') def balance_sampler(samples): """ignore extra negative samples to keep batch balance""" num_pos = nd.sum(samples == 1, axis=0) num_neg = nd.sum(samples == 0, axis=0) drop_prob = (num_neg - num_pos) / num_neg drop_prob = nd.where(nd.lesser(drop_prob, 0), nd.zeros_like(drop_prob), drop_prob) mask = nd.where(nd.greater(nd.random.uniform(0, 1, shape=samples.shape, ctx=samples.context), drop_prob), nd.ones_like(samples), nd.zeros_like(samples)) mask = nd.where(nd.equal(samples, 1), samples, mask) return mask def build_network(name, classes, checkpoint=None, ctx=mx.cpu(), **kwargs): if name == 'drml': grid = kwargs.get('grid', (8, 8)) if checkpoint: print(Fore.GREEN + 'Restoring params from checkpoint: {}'.format(os.path.basename(checkpoint))) symbol_file = checkpoint[:-11] + 'symbol.json' net = gluon.SymbolBlock.imports(symbol_file, ['data'], checkpoint, ctx) else: net = DRML(classes, grid) net.collect_params().initialize(mx.init.Xavier(), ctx=ctx) return net elif name == 'r50': if checkpoint: print(Fore.GREEN + 'Restoring params from checkpoint: {}'.format(os.path.basename(checkpoint))) symbol_file = checkpoint[:-11] + 'symbol.json' net = gluon.SymbolBlock.imports(symbol_file, ['data'], checkpoint, ctx) else: symbol_file = os.path.join(os.path.dirname(__file__), '..', 'model', 'model-r50-am-lfw', 'model-symbol.json') params_file = os.path.join(os.path.dirname(__file__), '..', 'model', 'model-r50-am-lfw', 'model-0000.params') net = PretrainedModel(classes, symbol_file, params_file, ctx) net.output.collect_params().initialize(mx.init.Xavier(), ctx=ctx) return net elif name == 'mobileface': if checkpoint: print(Fore.GREEN + 'Restoring params from checkpoint: {}'.format(os.path.basename(checkpoint))) symbol_file = checkpoint[:-11] + 'symbol.json' net = gluon.SymbolBlock.imports(symbol_file, ['data'], checkpoint, ctx) else: symbol_file = os.path.join(os.path.dirname(__file__), '..', 'model', 'model-y1-test2', 'model-symbol.json') params_file = os.path.join(os.path.dirname(__file__), '..', 'model', 'model-y1-test2', 'model-0000.params') net = PretrainedModel(classes, symbol_file, params_file, ctx) net.output.collect_params().initialize(mx.init.Xavier(), ctx=ctx) return net elif name == 'vggface2': if checkpoint: print(Fore.GREEN + 'Restoring params from checkpoint: {}'.format(os.path.basename(checkpoint))) symbol_file = checkpoint[:-11] + 'symbol.json' net = gluon.SymbolBlock.imports(symbol_file, ['data'], checkpoint, ctx) else: symbol_file = os.path.join(os.path.dirname(__file__), '..', 'model', 'model-r50-vggface2', 'model-symbol.json') params_file = os.path.join(os.path.dirname(__file__), '..', 'model', 'model-r50-vggface2', 'model-0000.params') net = VGGFace(classes, symbol_file, params_file, ctx) net.output.collect_params().initialize(mx.init.Xavier(), ctx=ctx) return net elif name == 'dpn68': if checkpoint: print(Fore.GREEN + 'Restoring params from checkpoint: {}'.format(os.path.basename(checkpoint))) symbol_file = checkpoint[:-11] + 'symbol.json' net = gluon.SymbolBlock.imports(symbol_file, ['data'], checkpoint, ctx) else: symbol_file = os.path.join(os.path.dirname(__file__), '..', 'model', 'model-dpn68-vggface2', 'new', 'model-symbol.json') params_file = os.path.join(os.path.dirname(__file__), '..', 'model', 'model-dpn68-vggface2', 'new', 'model-0009.params') net = VGGFace(classes, symbol_file, params_file, ctx) net.output.collect_params().initialize(mx.init.Xavier(), ctx=ctx) return net elif name == 'd121': if checkpoint: print(Fore.GREEN + 'Restoring params from checkpoint: {}'.format(os.path.basename(checkpoint))) symbol_file = checkpoint[:-11] + 'symbol.json' net = gluon.SymbolBlock.imports(symbol_file, ['data'], checkpoint, ctx) else: symbol_file = os.path.join(os.path.dirname(__file__), '..', 'model', 'model-d121-vggface2', 'new', 'model-symbol.json') params_file = os.path.join(os.path.dirname(__file__), '..', 'model', 'model-d121-vggface2', 'new', 'model-0000.params') net = VGGFace(classes, symbol_file, params_file, ctx) net.output.collect_params().initialize(mx.init.Xavier(), ctx=ctx) return net else: if checkpoint: print(Fore.GREEN + 'Restoring params from checkpoint: {}'.format(os.path.basename(checkpoint))) symbol_file = checkpoint[:-11] + 'symbol.json' net = gluon.SymbolBlock.imports(symbol_file, ['data'], checkpoint, ctx) else: net = vision.get_model(name=name, classes=classes) net.features.load_parameters(model_store.get_model_file(name), ctx=ctx, ignore_extra=True) net.output.collect_params().initialize(mx.init.Xavier(), ctx=ctx) return net def get_transforms(name): if name == 'drml': train_transform = T.Compose([T.RandomResizedCrop(170, (0.9, 1), (1, 1)), T.RandomFlipLeftRight(), T.ToTensor(), T.Normalize(0.5, 0.5)]) eval_transform = T.Compose([T.Resize(170), T.ToTensor(), T.Normalize(0.5, 0.5)]) elif name in ['r50', 'mobileface', 'dpn68', 'd121']: train_transform = T.Compose([T.RandomFlipLeftRight(), Transpose()]) eval_transform = T.Compose([Transpose()]) elif name == 'vggface2': train_transform = T.Compose([T.RandomResizedCrop(224, (0.9, 1), (1, 1)), T.RandomFlipLeftRight(), Transpose(), TransposeChannels(), T.Normalize((91.4953, 103.8827, 131.0912), (1., 1., 1.))]) eval_transform = T.Compose([T.Resize(224), Transpose(), TransposeChannels(), T.Normalize((91.4953, 103.8827, 131.0912), (1., 1., 1.))]) elif name == 'inceptionv3': train_transform = T.Compose([T.RandomResizedCrop(299, (0.9, 1), (1, 1)), T.RandomFlipLeftRight(), T.ToTensor(), T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]) eval_transform = T.Compose( [T.Resize(299), T.ToTensor(), T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]) else: raise ValueError("Invalid Network Input") return train_transform, eval_transform if __name__ == '__main__': num_classes = 12 aus = [1, 2, 4, 5, 6, 9, 12, 17, 20, 25, 26, 43] parser = argparse.ArgumentParser() parser.add_argument('--record', '-rec', nargs='+', required=True, help='path of .rec file for training') parser.add_argument('--eval-record', '-e', nargs='+', help='path of .rec file for evaluating') parser.add_argument('--output-dir', '-o', help='directory for logging and saving model') parser.add_argument('--save-freq', '-sf', type=int, default=500, help='save model every n steps') parser.add_argument('--eval-freq', '-ef', type=int, default=500, help='evaluating model every n steps') parser.add_argument('--print-freq', '-pf', type=int, default=50, help='print logs in terminal every n steps') parser.add_argument('--restart', '-r', action='store_true', help='ignore any checkpoints') parser.add_argument('--freeze-backbone', '-fb', action='store_true', help='freeze the params in backbone') parser.add_argument('--freeze-steps', '-fs', type=int, default=0, help='max steps for freezing the params') parser.add_argument('--gpu-device', '-gpu', type=int, required=True, nargs='+', help='specify gpu id') parser.add_argument('--network', '-net', default='mobileface', help='choose network') parser.add_argument('--max-steps', '-ms', type=int, default=10000, help='max steps for training') parser.add_argument('--batch-size', '-bs', type=int, default=128, help='batch size') parser.add_argument('--learning-rate', '-lr', type=float, default=0.01, help='initial learning rate') parser.add_argument('--optimizer', '-opt', default='adam', choices=['adam', 'sgd', 'nag'], help='type of optimizer') parser.add_argument('--decay-params', '-dp', nargs=2, type=float, default=[500, 0.8], help='decay step and decay rate of learning rate') parser.add_argument('--enable-balance-sampler', '-b', action='store_true', help='enable balance sampler in batching during training') parser.add_argument('--train-au', '-au', choices=aus, type=int) args = parser.parse_args() arg_table = PrettyTable(['Argument', 'Value']) arg_table.align['Argument'] = 'r' arg_table.align['Value'] = 'l' for k, v in vars(args).items(): if isinstance(v, (list, tuple)) and isinstance(v[0], str): v = '\n'.join(v) arg_table.add_row([k, v]) print(arg_table) root_dir = os.path.dirname(os.path.abspath(__file__)) args.record = [os.path.abspath(os.path.expanduser(fname)) for fname in args.record] args.eval_record = [os.path.abspath(os.path.expanduser(fname)) for fname in args.eval_record] if args.eval_record else None args.output_dir = os.path.abspath(os.path.expanduser(args.output_dir)) if args.output_dir else os.path.join( root_dir, datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')) if args.restart: tqdm.write('Existing models and logs will be removed. [{}]'.format(args.output_dir)) while True: confirm = input('Sure to restart? (y)es|(n)o: ').strip() if confirm in ['yes', 'y']: shutil.rmtree(args.output_dir, ignore_errors=True) tqdm.write('Directory removed: {}'.format(args.output_dir)) break elif confirm in ['no', 'n']: break if args.freeze_backbone: print(Fore.CYAN + f'Freeze the params in backbone during first {args.freeze_steps} steps') # Create summary dirs train_log_dir = os.path.join(args.output_dir, 'log', 'train') eval_log_dir = os.path.join(args.output_dir, 'log', 'eval') model_dir = os.path.join(args.output_dir, 'checkpoint') os.makedirs(train_log_dir, exist_ok=True) os.makedirs(eval_log_dir, exist_ok=True) os.makedirs(model_dir, exist_ok=True) if args.train_au: num_classes = 1 au_idx = aus.index(args.train_au) aus = [args.train_au] label_names = ['AU{:0>2}'.format(i) for i in aus] ctx = [mx.gpu(i) for i in args.gpu_device] if args.gpu_device else mx.cpu() # Dataloader train_transform, eval_transform = get_transforms(args.network) train_dataloader = DataLoaderWrapper(gluon.data.DataLoader( ImageRecordDataset( args.record, transform=lambda x, y: (train_transform(x), y)), args.batch_size, shuffle=True, last_batch='rollover', num_workers=8, pin_memory=True )) if args.eval_record: eval_dataloader = gluon.data.DataLoader( ImageRecordDataset( args.eval_record, transform=lambda x, y: (eval_transform(x), y)), args.batch_size, shuffle=False, last_batch='keep', num_workers=0, pin_memory=False ) # Restore last checkpoint checkpoint_files = sorted([fname for fname in os.listdir(model_dir) if fname.endswith('.params')]) last_checkpoint = os.path.join(model_dir, checkpoint_files[-1]) if checkpoint_files else None start_step = int(os.path.splitext(last_checkpoint)[0][-4:]) * 100 + 1 if last_checkpoint else 1 net = build_network(args.network, num_classes, last_checkpoint, ctx) net.hybridize() # Loss and metrics sigmoid_binary_cross_entropy = gluon.loss.SigmoidBinaryCrossEntropyLoss() accuracy = Accuracy(label_names, train_log_dir) f1 = F1(label_names, train_log_dir) eval_accuracy = Accuracy(label_names) eval_f1 = F1(label_names) # Summary Writer train_writer = SummaryWriter(train_log_dir, verbose=False) eval_writer = SummaryWriter(eval_log_dir, verbose=False) # Learning rate decay decay_step, decay_rate = int(args.decay_params[0]), args.decay_params[1] schedule = mx.lr_scheduler.FactorScheduler(decay_step, decay_rate) # Trainer optimizer_params = {'learning_rate': args.learning_rate, 'lr_scheduler': schedule} if args.optimizer != 'adam': optimizer_params['momentum'] = 0.9 def get_trainer(): params2opt = net.collect_params() if not args.freeze_backbone else net.collect_params('dense*') print(Fore.CYAN + f'{len(params2opt.keys())} params will be optimized.') _trainer = gluon.Trainer( params=params2opt, optimizer=args.optimizer, optimizer_params=optimizer_params ) return _trainer trainer = get_trainer() accum_loss = 0.0 # accumulate loss initialize for step in tqdm(range(args.max_steps), leave=False, total=args.max_steps, desc='{},{}'.format(args.network, os.path.basename(args.output_dir))): step += start_step x, y = next(train_dataloader) if args.train_au: y = y[:, au_idx].reshape((-1, 1)) sample_weights = nd.not_equal(y, 999) if args.enable_balance_sampler: sample_weights = sample_weights * balance_sampler(y) x = gluon.utils.split_and_load(x, ctx, even_split=False) y = gluon.utils.split_and_load(y, ctx, even_split=False) sample_weights = gluon.utils.split_and_load(sample_weights, ctx, even_split=False) with autograd.record(train_mode=True): logits = [net(data) for data in x] losses = [sigmoid_binary_cross_entropy(logit, label, sample_weight) for logit, label, sample_weight in zip(logits, y, sample_weights)] for l in losses: l.backward() trainer.step(args.batch_size) # Compute metrics value y_ = [nd.greater_equal(logit, 0) for logit in logits] accuracy.update(labels=y, preds=y_) f1.update(labels=y, preds=y_) curr_loss = sum([nd.mean(l).asscalar() for l in losses]) / len(losses) accum_loss += curr_loss # accumulate loss value if step % args.print_freq == 0: curr_lr = trainer.learning_rate curr_loss = accum_loss / args.print_freq curr_acc = accuracy.get_average() curr_f1 = f1.get_average() # Write summaries train_writer.add_scalar('lr', curr_lr, step) train_writer.add_scalar('loss', curr_loss, step) train_writer.add_scalar('acc', curr_acc, step) train_writer.add_scalar('f1', curr_f1, step) tqdm.write( 'step {:>5d} lr {:.1e} - loss {:.6} - acc {:.6} - f1 {:.6}'.format(step, curr_lr, curr_loss, curr_acc, curr_f1) ) accum_loss = 0.0 accuracy.reset() f1.reset() if args.eval_record and step % args.eval_freq == 0: eval_accuracy.reset() eval_f1.reset() eval_loss = [] for x, y in tqdm(eval_dataloader, desc='Evaluating', leave=False): if args.train_au: y = y[:, au_idx].reshape((-1, 1)) sample_weights = nd.not_equal(y, 999) x = gluon.utils.split_and_load(x, ctx, even_split=False) y = gluon.utils.split_and_load(y, ctx, even_split=False) sample_weights = gluon.utils.split_and_load(sample_weights, ctx, even_split=False) with autograd.predict_mode(): logits = [net(data) for data in x] losses = [sigmoid_binary_cross_entropy(logit, label, sample_weight) for logit, label, sample_weight in zip(logits, y, sample_weights)] # Compute metrics value y_ = [nd.greater_equal(logit, 0) for logit in logits] eval_accuracy.update(labels=y, preds=y_) eval_f1.update(labels=y, preds=y_) curr_loss = sum([nd.mean(l).asscalar() for l in losses]) / len(losses) eval_loss.append(curr_loss) eval_mean_acc = eval_accuracy.get_average() eval_mean_f1 = eval_f1.get_average() eval_mean_loss = sum(eval_loss) / len(eval_loss) eval_writer.add_scalar('loss', eval_mean_loss, step) eval_writer.add_scalar('acc', eval_mean_acc, step) eval_writer.add_scalar('f1', eval_mean_f1, step) tqdm.write( Fore.GREEN + '[eval] step {} - loss {:.6} - acc {:.6} - f1 {:.6}'.format(step, eval_mean_loss, eval_mean_acc, eval_mean_f1) ) if step % args.save_freq == 0: net.export(os.path.join(model_dir, 'model'), epoch=step // 100) # change trainer to optimize different params if args.freeze_backbone and step >= args.freeze_steps: args.freeze_backbone = False trainer = get_trainer() if args.eval_record: table = PrettyTable(['AU', 'Acc', 'F1']) table.float_format = '.3' for t_name, t_acc, t_f1 in zip(label_names, eval_accuracy.get()[1], eval_f1.get()[1]): table.add_row([int(t_name[-2:]), t_acc, t_f1]) table.add_row(['Avg.', eval_accuracy.get_average(), eval_f1.get_average()]) print(table) <file_sep># -*- coding: utf-8 -*- """ Created on Mon Oct 29 10:50:21 2018 @author: lmx """ import numpy as np import argparse import pandas as pd if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--target', '-t', default='../new_npy_m0.5/target/features.npy', help='path of .npy file of target features') parser.add_argument('--target-label', '-label', default='../new_npy_m0.5/target/label_no999.csv', help='path of .csv file of target data labels') parser.add_argument('--distractor', '-d', default='../new_npy_m0.5/distractor/features.npy', help='path of .npy file of distractor features') parser.add_argument('--target-class', '-c', default='../tongji/new_target_classes.csv', help='path of .csv file of target classes') args = parser.parse_args() target_features = np.load(args.target) target_features = np.squeeze(target_features, axis=1) distractor_data = np.load(args.distractor) distractor_data = np.squeeze(distractor_data, axis=1) label = pd.read_csv(args.target_label) label = np.array(label) classes = pd.read_csv(args.target_class) classes = np.array(classes) # 将target feature按类组合 target_data = [] for i in range(len(classes)): data = [] for j in range(len(label)): if (label[j] == classes[i]).all(): data.append(target_features[j]) target_data.append(data) # 正样本对, 同一类中任取两两配对 pos = [] # 保存正样本对 pos_dist = [] # 保存正样本对间距离 for i in range(len(target_data)): # 每一类内随机挑2个配 every_class = target_data[i] for j in range(len(every_class) - 1): for k in range(j + 1, len(every_class)): pos.append([every_class[j], every_class[k]]) dist = np.linalg.norm(every_class[j] - every_class[k]) pos_dist.append(dist) print('pos: ', np.shape(pos), np.shape(pos_dist)) # 正样本对与distractor计算距离 pos_dis_data = [] # 保存所有正样本对与distractor所有的距离 num = 0 tp = 0 for i in range(len(pos)): # 正样本对中挑选其中一个与distractor中所有去计算距离 d2 = [] # 保存每个对中的一个与distractor所有计算的距离 d1 = pos_dist[i] for j in range(2): f1 = pos[i][j] #每个对中的一个距离 # 与distractor中所有去配对 dist = np.linalg.norm(f1 - distractor_data, axis=1) d2.extend(dist) print(sum(d1>np.array(d2, dtype=np.int32))) if sum(d1>np.array(d2, dtype=np.int32)) == 0: tp += 1 num += 1 if i%100==0: print('tp, num:', tp, num) acc = tp/num print('acc: ', acc) <file_sep># Action Unit(AU) ## Introduction * `AU1`:Inner Brow Raiser(眉毛内角抬起) * `AU2`:Outer Brow Raiser (眉毛外角抬起) * `AU4`:Brow Lowerer(皱眉或降低眉毛) * `AU5`:Upper Lid Raiser(上眼睑上升) * `AU6`:Cheek Raiser(脸颊提升) * `AU9`:Nose Wrinkler(皱鼻) * `AU12`:Lip Corner Puller(倾斜向上拉动嘴角) * `AU17`:Chin Raiser(下唇向上) * `AU20`:Lip stretcher(嘴角拉伸) * `AU25`:Lips part(张嘴并指定双唇分离的长度) * `AU26`:Jaw Drop(张嘴并指定颌部下降的距离) * `AU43`:Eyes Closed(闭眼) ## Project Structure 基于`Mxnet`框架实现。 * `model`:存放预训练模型 * `model-y1-test2`:InsightFace mobileface training on MS1M * `Multi_class`:将每种AU组合看做一个类别,以[Arcface](https://arxiv.org/abs/1801.07698)为loss function,进行多分类的网络训练,以mobilefacew为架构,基于预模型fine-tune。 * `Multi_label`:共12种AU识别,每个AU都是一个二分类标签,进行多标签的网络训练,以mobileface为架构,基于预模型fine-tune。 ## Reference 1.[FACS - Facial Action Coding System](https://www.cs.cmu.edu/~face/facs.htm) 2.[Facial Action Coding System (FACS) – A Visual Guidebook](https://imotions.com/blog/facial-action-coding-system/) 3.[面部编码系统-微表情](https://wenku.baidu.com/view/298d8a8a19e8b8f67c1cb969.html) <file_sep># -*- coding: utf-8 -*- """ Created on Fri Oct 26 11:37:33 2018 @author: lmx """ import copy import argparse import collections import datetime import os import shutil import mxnet as mx import mxnet.gluon.data.vision.transforms as T from colorama import init, Fore from mxboard import SummaryWriter from mxnet import gluon, nd, autograd from mxnet.gluon.model_zoo import vision, model_store from prettytable import PrettyTable from tqdm import tqdm from network import DRML, PretrainedModel, VGGFace import math import numpy as np from sklearn.preprocessing import normalize from mxnet import ndarray as nd from mxnet.gluon.loss import Loss from data import ImageRecordDataset from mxnet.gluon.block import HybridBlock init(autoreset=True) class DataLoaderWrapper(object): def __init__(self, data_loader): self.data_loader = data_loader self._gen = self.__gen__() def __next__(self): return next(self._gen) def __gen__(self): while True: for i in self.data_loader: yield i class Transpose(gluon.HybridBlock): def __init__(self): super(Transpose, self).__init__() def hybrid_forward(self, F, x, *args, **kwargs): return F.cast(F.transpose(x, (2, 0, 1)), dtype='float32') def build_network(name, classes, checkpoint=None, ctx=mx.cpu(), **kwargs): if name == 'mobileface': if checkpoint: print(Fore.GREEN + 'Restoring params from checkpoint: {}'.format(os.path.basename(checkpoint))) symbol_file = checkpoint[:-11] + 'symbol.json' net = gluon.SymbolBlock.imports(symbol_file, ['data'], checkpoint, ctx) else: symbol_file = os.path.join(os.path.dirname(__file__), '..', 'model', 'model-y1-test2', 'model-symbol.json') params_file = os.path.join(os.path.dirname(__file__), '..', 'model', 'model-y1-test2', 'model-0000.params') net = PretrainedModel(classes, symbol_file, params_file, ctx) net.output.collect_params().initialize(mx.init.Xavier(), ctx=ctx) return net def get_transforms(name): if name in ['r50', 'mobileface', 'dpn68', 'd121']: train_transform = T.Compose([T.RandomFlipLeftRight(), Transpose()]) eval_transform = T.Compose([Transpose()]) else: raise ValueError("Invalid Network Input") return train_transform, eval_transform class Arcface_loss(Loss): def __init__(self, weight=None, batch_axis=0, **kwargs): super(Arcface_loss, self).__init__(weight, batch_axis, **kwargs) def hybrid_forward(self, F, all_label, _weight, fc, args, sample_weight=None): gt_label = all_label _weight = _weight embedding = fc s = args.margin_s m = args.margin_m assert s > 0.0 assert m >= 0.0 assert m < (math.pi / 2) _weight = F.L2Normalization(_weight, mode='instance') nembedding = F.L2Normalization(embedding, mode='instance') * s fc7 = F.FullyConnected(data=nembedding, weight=_weight, no_bias=True, num_hidden=args.num_classes, name='fc7') zy = F.pick(fc7, gt_label, axis=1) cos_t = zy / s cos_m = math.cos(m) sin_m = math.sin(m) mm = math.sin(math.pi - m) * m # threshold = 0.0 threshold = math.cos(math.pi - m) if args.easy_margin: cond = F.maximum(cos_t, 0) else: cond_v = cos_t - threshold cond = F.maximum(cond_v, 0) body = cos_t * cos_t body = 1.0 - body sin_t = F.sqrt(body) new_zy = cos_t * cos_m b = sin_t * sin_m new_zy = new_zy - b new_zy = new_zy * s if args.easy_margin: zy_keep = zy else: zy_keep = zy - s * mm new_zy = F.where(cond, new_zy, zy_keep) diff = new_zy - zy diff = F.expand_dims(diff, 1) gt_one_hot = F.one_hot(gt_label, depth=args.num_classes, on_value=1.0, off_value=0.0) body = F.broadcast_mul(gt_one_hot, diff) fc7 = fc7 + body # out = F.SoftmaxOutput(data=fc7, label=gt_label, name='softmax', normalization='valid') if args.ce_loss: body = F.SoftmaxActivation(data=fc7) body = F.log(F.clip(body, 1e-25, 1.0)) _label = F.one_hot(gt_label, depth=args.num_classes, on_value=-1.0, off_value=0.0) body = body * _label out = F.sum(body) / len(body) return out if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--num-classes', '-num', type=int, default=22, help='classes number') parser.add_argument('--record', '-rec', nargs='+', default='../rec_version4/train.rec', help='path of .rec file for training') parser.add_argument('--eval-record', '-e', nargs='+', help='path of .rec file for evaluating') parser.add_argument('--output-dir', '-o', default='../model_version4/out/', help='directory for logging and saving model') parser.add_argument('--save-freq', '-sf', type=int, default=500, help='save model every n steps') parser.add_argument('--eval-freq', '-ef', type=int, default=500, help='evaluating model every n steps') parser.add_argument('--print-freq', '-pf', type=int, default=50, help='print logs in terminal every n steps') parser.add_argument('--restart', '-r', action='store_true', help='ignore any checkpoints') parser.add_argument('--freeze-backbone', '-fb', action='store_true', help='freeze the params in backbone') parser.add_argument('--freeze-steps', '-fs', type=int, default=0, help='max steps for freezing the params') parser.add_argument('--gpu-device', '-gpu', type=int, required=True, help='specify gpu id') parser.add_argument('--network', '-net', default='mobileface', help='choose network') parser.add_argument('--max-steps', '-ms', type=int, default=10000, help='max steps for training') parser.add_argument('--batch-size', '-bs', type=int, default=256, help='batch size') parser.add_argument('--learning-rate', '-lr', type=float, default=0.001, help='initial learning rate') parser.add_argument('--optimizer', '-opt', default='adam', choices=['adam', 'sgd', 'nag'], help='type of optimizer') parser.add_argument('--decay-params', '-dp', nargs=2, type=float, default=[500, 0.8], help='decay step and decay rate of learning rate') parser.add_argument('--enable-balance-sampler', '-b', action='store_true', help='enable balance sampler in batching during training') parser.add_argument('--fc7-wd-mult', type=float, default=1.0, help='weight decay mult for fc7') parser.add_argument('--fc7-lr-mult', type=float, default=1.0, help='lr mult for fc7') parser.add_argument('--emb-size', type=int, default=512, help='embedding length') parser.add_argument('--margin-m', type=float, default=0.3, help='margin for loss') parser.add_argument('--margin-s', type=float, default=64.0, help='scale for feature') parser.add_argument('--easy-margin', type=int, default=0, help='') parser.add_argument('--ce-loss', default=True, action='store_true', help='if output ce loss') args = parser.parse_args() arg_table = PrettyTable(['Argument', 'Value']) arg_table.align['Argument'] = 'r' arg_table.align['Value'] = 'l' for k, v in vars(args).items(): if isinstance(v, (list, tuple)) and isinstance(v[0], str): v = '\n'.join(v) arg_table.add_row([k, v]) print(arg_table) root_dir = os.path.dirname(os.path.abspath(__file__)) args.record = [os.path.abspath(os.path.expanduser(fname)) for fname in args.record] args.eval_record = [os.path.abspath(os.path.expanduser(fname)) for fname in args.eval_record] if args.eval_record else None args.output_dir = os.path.abspath(os.path.expanduser(args.output_dir)) if args.output_dir else os.path.join( root_dir, datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')) if args.restart: tqdm.write('Existing models and logs will be removed. [{}]'.format(args.output_dir)) while True: confirm = input('Sure to restart? (y)es|(n)o: ').strip() if confirm in ['yes', 'y']: shutil.rmtree(args.output_dir, ignore_errors=True) tqdm.write('Directory removed: {}'.format(args.output_dir)) break elif confirm in ['no', 'n']: break if args.freeze_backbone: print(Fore.CYAN + f'Freeze the params in backbone during first {args.freeze_steps} steps') # Create summary dirs train_log_dir = os.path.join(args.output_dir, 'log', 'train') eval_log_dir = os.path.join(args.output_dir, 'log', 'eval') model_dir = os.path.join(args.output_dir, 'checkpoint') os.makedirs(train_log_dir, exist_ok=True) os.makedirs(model_dir, exist_ok=True) # Store parameter config with open(os.path.join(args.output_dir, 'train_params.txt'), 'w') as f: f.write(arg_table.get_string()) ctx = mx.gpu(args.gpu_device) if args.gpu_device else mx.cpu() # Dataloader train_transform, eval_transform = get_transforms(args.network) record = args.record[0] train_dataloader = DataLoaderWrapper(gluon.data.DataLoader( dataset=gluon.data.vision.ImageRecordDataset( filename=record, transform=lambda x, y: (train_transform(x), y) ), batch_size=args.batch_size, shuffle=True, last_batch='rollover' )) if args.eval_record: eval_record = args.eval_record[0] eval_dataloader = gluon.data.DataLoader( dataset=gluon.data.vision.ImageRecordDataset( filename=eval_record, transform=lambda x, y: (train_transform(x), y) ), batch_size=args.batch_size, shuffle=False, last_batch='keep' ) # Restore last checkpoint checkpoint_files = sorted([fname for fname in os.listdir(model_dir) if fname.endswith('.params')]) last_checkpoint = os.path.join(model_dir, checkpoint_files[-1]) if checkpoint_files else None start_step = int(os.path.splitext(last_checkpoint)[0][-4:]) * 100 + 1 if last_checkpoint else 1 net = build_network(args.network, args.num_classes, last_checkpoint, ctx) net.hybridize() # Loss and metrics arc = Arcface_loss() accuracy = mx.metric.Accuracy(train_log_dir) eval_accuracy = mx.metric.Accuracy(eval_log_dir) # Summary Writer train_writer = SummaryWriter(train_log_dir, verbose=False) eval_writer = SummaryWriter(eval_log_dir, verbose=False) # Learning rate decay decay_step, decay_rate = int(args.decay_params[0]), args.decay_params[1] schedule = mx.lr_scheduler.FactorScheduler(decay_step, decay_rate) # Trainer optimizer_params = {'learning_rate': args.learning_rate, 'lr_scheduler': schedule} if args.optimizer != 'adam': optimizer_params['momentum'] = 0.9 def get_trainer(): params2opt = net.collect_params() if not args.freeze_backbone else net.collect_params('dense*') print(Fore.CYAN + f'{len(params2opt.keys())} params will be optimized.') _trainer = gluon.Trainer( params=params2opt, optimizer=args.optimizer, optimizer_params=optimizer_params ) return _trainer trainer = get_trainer() accum_loss = 0.0 # accumulate loss initialize for step in tqdm(range(args.max_steps), leave=False, total=args.max_steps, desc='{},{}'.format(args.network, os.path.basename(args.output_dir))): step += start_step x, y = next(train_dataloader) x = x.as_in_context(ctx) y = nd.array(y, dtype='float32') y = y.as_in_context(ctx) with autograd.record(train_mode=True): fc, pred = net(x) arc_loss = arc(y, net.output.weight.data(), fc, args) arc_loss.backward() trainer.step(args.batch_size) # Compute metrics value soft_pred = nd.SoftmaxActivation(pred) pred_label = nd.argmax(soft_pred, axis=-1) accuracy.update(labels=y, preds=pred_label) temp = arc_loss.asnumpy()[0] accum_loss += temp # accumulate loss value if args.eval_record and step % args.eval_freq == 0: eval_accuracy.reset() eval_mean_loss = 0 eval_loss = [] for x, y in tqdm(eval_dataloader, desc='Evaluating', leave=False): x = x.as_in_context(ctx) y = y.as_in_context(ctx) with autograd.predict_mode(): fc, pred = net(x) arc_loss = arc(y, net.output.weight.data(), fc, args) # Compute metrics value soft_pred = nd.SoftmaxActivation(pred) pred_label = nd.argmax(soft_pred, axis=-1) eval_accuracy.update(labels=y, preds=pred_label) curr_loss = arc_loss.asnumpy()[0] eval_loss.append(curr_loss) eval_mean_acc = eval_accuracy.get()[1] eval_mean_loss = sum(eval_loss) / len(eval_loss) eval_writer.add_scalar('loss', eval_mean_loss, step) eval_writer.add_scalar('acc', eval_mean_acc, step) tqdm.write( Fore.GREEN + '[eval] step {} - loss {:.6} - acc {:.6}'.format(step, eval_mean_loss, eval_mean_acc) ) if step % args.print_freq == 0: curr_lr = trainer.learning_rate curr_loss = accum_loss / args.print_freq curr_acc = accuracy.get()[1] # Write summaries train_writer.add_scalar('lr', curr_lr, step) train_writer.add_scalar('loss', curr_loss, step) train_writer.add_scalar('acc', curr_acc, step) tqdm.write( 'step {:>5d} lr {:.1e} - loss {:.6} - acc {:.6}'.format(step, curr_lr, curr_loss, curr_acc) ) accum_loss = 0.0 accuracy.reset() if step % args.save_freq == 0: net.export(os.path.join(model_dir, 'model'), epoch=step // 100) if args.freeze_backbone and step >= args.freeze_steps: args.freeze_backbone = False trainer = get_trainer()
50ba9a793a9d5686600e935389daa7081af09ec6
[ "Markdown", "Python" ]
13
Markdown
meteor518/Action-Unit
0a8a1cb7d1fd91ebde165e330915c0720cb8b81a
740e2d40f29d086c1452d670759ce1246b5ae1c7
refs/heads/master
<repo_name>Hooveralex/invoice-app<file_sep>/app/assets/javascripts/custom.js var datepicker = function() { $( ".datepicker" ).datepicker({ dateFormat: "yy-mm-dd" }); }; // This is a little fix that helps MDL cooperate with rails' Turbolinks document.addEventListener('page:change', function() { componentHandler.upgradeDom(); datepicker(); }); $(datepicker());<file_sep>/app/controllers/static_controller.rb class StaticController < ApplicationController def index @invoices = Invoice.all.reverse @items = Item.all @expenses = Expense.all end def today @today = Date.today @today_format = @today.to_formatted_s(:long) @invoices = Invoice.all @matters = Matter.all @items = Item.where("date=?", Date.today).all @invoices.each do |invoice| range = invoice.start_date..invoice.end_date if range.include?(@today) @invoice = Invoice.find(invoice.id) end end @costs = 0 @hours = 0 # Total Amount Owed (Owed - Expenses) and Total Hours @items.each do |item| if item.invoice_id === @invoice.id @hours += item.hours end end @owed = (@hours * 40) + (@costs || 0) end end <file_sep>/app/models/invoice.rb class Invoice < ActiveRecord::Base has_many :items, dependent: :destroy has_many :expenses, dependent: :destroy end <file_sep>/app/helpers/application_helper.rb module ApplicationHelper def get_owed(items,invoice) @hours = 0 items.each do |item| if item.invoice_id == invoice.id @hours += item.hours end end return @hours * 40 end def get_expenses(expenses,invoice) @costs = 0 expenses.each do |expense| if expense.invoice_id == invoice.id @costs += expense.amount end end return @costs end end <file_sep>/app/models/matter.rb class Matter < ActiveRecord::Base has_many :items has_many :expenses validates :name, presence: true end <file_sep>/README.md # invoice-app Simple invoice app. Work in progress. <file_sep>/app/controllers/invoices_controller.rb class InvoicesController < ApplicationController # http_basic_authenticate_with name: "Alex", password: "<PASSWORD>", except: [:index, :show] def index @invoices = Invoice.all end def show @invoice = Invoice.find(params[:id]) @matters = Matter.all @items = Item.all @expenses = Expense.all @costs = 0 @hours = 0 # Total Expenses @expenses.each do |expense| if expense.invoice_id === @invoice.id @costs += expense.amount end end # Total Amount Owed (Owed - Expenses) and Total Hours @items.each do |item| if item.invoice_id === @invoice.id @hours += item.hours end end @owed = (@hours * 40) end def new @invoice = Invoice.new end def edit @invoice = Invoice.find(params[:id]) end def download @invoice = Invoice.find(params[:id]) @items = Item.all @expenses = Expense.all @costs = 0 @hours = 0 # Total Expenses @expenses.each do |expense| if expense.invoice_id === @invoice.id @costs += expense.amount end end # Total Amount Owed (Owed - Expenses) and Total Hours @items.each do |item| if item.invoice_id === @invoice.id @hours += item.hours end end @owed = (@hours * 40) + (@costs || 0) respond_to do |format| format.html format.pdf do render :pdf => "<NAME> Invoice \##{@invoice.id} (#{@invoice.start_date.to_formatted_s(:long)} - #{@invoice.end_date.to_formatted_s(:long)})", :template => 'invoices/download.html.erb' end end end def create @invoice = Invoice.new(invoice_params) if @invoice.save redirect_to @invoice else render 'new' end end def update @invoice = Invoice.find(params[:id]) if @invoice.update(invoice_params) redirect_to @invoice else render 'edit' end end def destroy @invoice = Invoice.find(params[:id]) @invoice.destroy redirect_to invoices_path end private def invoice_params params.require(:invoice).permit(:start_date, :end_date) end end <file_sep>/db/migrate/20160116180848_create_items.rb class CreateItems < ActiveRecord::Migration def change create_table :items do |t| t.references :invoice, index: true, foreign_key: true t.references :matter, index: true, foreign_key: true t.date :date t.string :desc t.float :hours t.timestamps null: false end end end <file_sep>/app/controllers/items_controller.rb class ItemsController < ApplicationController # http_basic_authenticate_with name: "Alex", password: "<PASSWORD>", only: :destroy def create @invoice = Invoice.find(params[:invoice_id]) @item = @invoice.items.create(item_params) redirect_to request.referer end def destroy @invoice = Invoice.find(params[:invoice_id]) @item = @invoice.items.find(params[:id]) @item.destroy redirect_to request.referer end private def item_params params.require(:item).permit(:date, :matter_id, :desc, :hours) end end <file_sep>/app/controllers/expenses_controller.rb class ExpensesController < ApplicationController # http_basic_authenticate_with name: "Alex", password: "<PASSWORD>", only: :destroy def create @invoice = Invoice.find(params[:invoice_id]) @expense = @invoice.expenses.create(expense_params) redirect_to invoice_path(@invoice) end def destroy @invoice = Invoice.find(params[:invoice_id]) @expense = @invoice.expenses.find(params[:id]) @expense.destroy redirect_to invoice_path(@invoice) end private def expense_params params.require(:expense).permit(:matter_id, :desc, :amount) end end <file_sep>/app/controllers/matters_controller.rb class MattersController < ApplicationController def index @matters = Matter.all @matter = Matter.new end def new @matter = Matter.new end def edit @matter = Matter.find(params[:id]) end def create @matter = Matter.new(matter_params) @matter.save if @matter.save redirect_to action: "index" else render 'new' end end def update @matter = Matter.find(params[:id]) if @matter.update(matter_params) redirect_to action: "index" else render 'edit' end end def destroy @matter = Matter.find(params[:id]) @matter.destroy redirect_to matters_path end private def matter_params params.require(:matter).permit(:name) end end
7193e91c2abb48bddcd30bc0e1500ca6f41cbbc1
[ "JavaScript", "Ruby", "Markdown" ]
11
JavaScript
Hooveralex/invoice-app
fa0df33aa0fd98e8b9cde41dc507516d4c79aed9
e2d980477e74f5f4522acf97891b772ea79c0804
refs/heads/master
<file_sep>import datetime def module_show(): module_type=dir(datetime) print(module_type) def date_now(): return datetime.datetime.now()<file_sep>import func_module import func_module_as #func_module.module_show() # nowdate=func_module.date_now() # now_year=nowdate.year # date_today='{}년 {}월 {}일'.format(nowdate.year,nowdate.month,nowdate.day) # #print(nowdate) # #print(now_year) # print(date_today) # x_mas=nowdate.replace(month=12, day=25) # date_xmas='{}년 {}월 {}일'.format(x_mas.year,x_mas.month,x_mas.day) # print(date_xmas) #교재 #start_time=datetime.datetime.now() #start_time.replace(month=12, day=25) ndate=func_module_as.date_now() print(ndate) func_module_as.remain_data() <file_sep>import datetime as dt def module_show(): module_type=dir(dt) print(module_type) def date_now(): return dt.datetime.now() def remain_data(): #print(dt.date.today()) today=dt.date.today() print('오늘은 {}년 {}월 {}일입니다'.format(today.year, today.month, today.day)) #print(dt.datetime.now().replace(month=12, day=25)) return dt.datetime(2020,12,25)-dt.datetime.now() #남은시간 반환 def remain_data_input(nmonth,nday): #print(dt.date.today()) today=dt.date.today() #print('오늘은 {}년 {}월 {}일입니다'.format(today.year, today.month, today.day)) #print(dt.datetime.now().replace(month=12, day=25)) return dt.datetime(2020,nmonth,nday)-dt.datetime.now() #남은시간 반환 nmonth=int(input('원하는 달을 입력하시오')) nday=int(input('원하는 날을 입력하시오')) print(remain_data_input(nmonth,nday))
0cc069d0eaeb015673f695eb47198d3a1c732b91
[ "Python" ]
3
Python
jiwon73/lecture_3
487e385fde05f5c80822ab2c675060c3fcd1856a
2c4305fddb1b19b174a410981eb4be7e9b1950dc
refs/heads/master
<repo_name>humucai/githubtest<file_sep>/killhello.py #!/usr/bin/python # _*_ coding:utf-8 _*_ import requests import multiprocessing as Process from multiprocessing import Pool import json, re, time class Kill(object): def __init__(self, promId, skuId, addressIds,process_name='xxx'): self._promId = promId self._skuId = skuId self._addressIds = addressIds self.process_name=process_name self._login_url = 'http://www.600280.com/member/loginService' self._query_url = 'http://zf.600280.com//order/querySecKillInfo' self._order_url = 'http://zf.600280.com//order/addSecKill' def login(self, username, password): params = { 'memberUser.mailbox': username, 'memberUser.password': <PASSWORD>, 'validateFlag': 1 } response = requests.post(self._login_url, data=params) cookies = response.cookies result = json.loads(response.content) if result['code'] == 'success': print '%s : login success' % username return cookies else: raise RuntimeError('%s : login failed' % username) def get_captcha_key(self, cookies): param = {'promId': self._promId, 'skuId': self._skuId} headers = { 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36' } pattern = r'<span.*?id="questionInfo".*?>(.*?)<\/span>' page = requests.get(self._query_url,cookies=cookies,params=param,headers=headers) m = re.search(pattern,page.content) if m is not None: return m.group(1) else: raise RuntimeError("获取活动信息失败") def get_captcha_value(self, key): key = unicode(key,'utf-8') captcha = { u'趋之若(?)': '鹜', u'买(?)还珠': '椟', u'茕茕(?)立': '孑', u'平易近(?)': '人', u'悠然(?)得': '自', u'一见(?)情': '钟', u'热(?)朝天': '火', u'(?)清玉洁': '冰', u'(?)木求鱼': '缘', u'安之(?)素': '若', u'美轮美(?)': '奂', u'倾国(?)城': '倾', u'马到(?)功': '成', u'百里(?)一': '挑', u'落英(?)纷': '缤', u'秋(?)伊人': '水', u'世(?)桃源': '外', u'青梅(?)马': '竹', u'喜闻(?)见': '乐', u'天马(?)空': '行' } return captcha[key] def ordering(self, cookies, remark=''): key = self.get_captcha_key(cookies) val = self.get_captcha_value(key) print key, val,self.process_name, submit_post = { "verifyAns": val, "addressIds": self._addressIds, "onlyFee": "0", "remark": remark } headers = { 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded' } result = requests.post(self._order_url,cookies=cookies,data=submit_post,headers=headers) _json = json.loads(result.content) print _json code = _json['result'] if code in ('0', '-1', '-2'): print 'ha ha go go go...' return 1 return -1 def send(username, passwd, promId, skuId, addr): k = Kill(promId, skuId, addr,username) cookie = k.login(username, passwd) while True: return_code = k.ordering(cookie) if return_code == 1: break #time.sleep(0.2) print return_code def main(userinfos): ''' userinfos = [ (username,passwd,promId,skuId,addr), ] ''' # p1 = Process(target=send,args=userinfos[0]) # p2 = Process(target=send,args=userinfos[1]) # p1.start() # p2.start() # p1.join() # p2.join() # print '-----end------' #采用进程池 p = Pool() for info in userinfos: p.apply_async(send,args=info) print 'waiting for all subprocesses done ...' p.close() p.join() print '....done.....' if __name__ == '__main__': userinfos = list() #(username,passwd,promId,skuId,addr), userinfos.append(('<EMAIL>', '<PASSWORD>', '<PASSWORD>', '58812', '46013')) userinfos.append(('<EMAIL>', '<PASSWORD>', '<PASSWORD>', '58812', '46013')) main(userinfos)
a34f606d97de1711531dfeb2afe110240315f3dd
[ "Python" ]
1
Python
humucai/githubtest
3265b8b459dd580a060a7ac9abeaac9f9cd49c04
e2f838652418d45b8ad6d355ea8d9e39196f9f74
refs/heads/master
<file_sep># MyContactContentProviders Content Providers ContentResolver in Android https://tutorial.eyehunts.com/android/content-providers-contentresolver-android/ <file_sep>package in.eyehunt.mycontactcontentproviders; import android.app.LoaderManager; import android.content.ContentValues; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.CursorAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { private CursorAdapter cursorAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cursorAdapter = new ContactsCursorAdapter(this, null, 0); ListView list = (ListView) findViewById(R.id.lv_contacts); list.setAdapter(cursorAdapter); getLoaderManager().initLoader(0, null, this); // add new record - dialog box FloatingActionButton fabtn_add = (FloatingActionButton) findViewById(R.id.fabtn_add); fabtn_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { LayoutInflater li = LayoutInflater.from(MainActivity.this); View getEmpIdView = li.inflate(R.layout.dialog_box, null); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("Add new contact"); builder.setView(getEmpIdView); final EditText et_name = (EditText) getEmpIdView.findViewById(R.id.et_name); final EditText et_number = (EditText) getEmpIdView.findViewById(R.id.et_number); // set dialog message builder .setCancelable(false) .setPositiveButton("Add", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // get user input and set it to result insertContact(et_name.getText().toString(), et_number.getText().toString()); restartLoader(); } }).create() .show(); } }); } //Insert a new contact private void insertContact(String contactName, String contactPhone) { ContentValues values = new ContentValues(); values.put(DatabaseHandler.CONTACT_NAME, contactName); values.put(DatabaseHandler.CONTACT_PHONE, contactPhone); Uri contactUri = getContentResolver().insert(MyContactsProvider.CONTENT_URI, values); Toast.makeText(this, "Created Contact " + contactName, Toast.LENGTH_LONG).show(); } // Delete all contacts private void deleteAllContacts() { getContentResolver().delete(MyContactsProvider.CONTENT_URI, null, null); restartLoader(); Toast.makeText(this, "All contacts has deleted", Toast.LENGTH_LONG).show(); } // reload all data in listivew private void restartLoader() { getLoaderManager().restartLoader(0, null, this); } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { return new CursorLoader(this, MyContactsProvider.CONTENT_URI, null, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { cursorAdapter.swapCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { } //set menu @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return super.onCreateOptionsMenu(menu); } // handle delete action @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_delete: deleteAllContacts(); return true; } return super.onOptionsItemSelected(item); } }
c8dff0b8829233e0549da0daf933dd8ee76fe424
[ "Markdown", "Java" ]
2
Markdown
EyeHunts/MyContactContentProviders
2c6630aa704dc88736f29df655c2a445db4cbbe3
ce6ebf3fbb35f6fc233c8edf4b245f75612dac01
refs/heads/main
<repo_name>MedaR/todolist<file_sep>/src/app/layout/create-list/create-list.component.ts import { Component, OnInit } from '@angular/core'; import { StorageService } from 'src/services/storage.service'; import { ToastrService } from 'ngx-toastr'; import { Router } from '@angular/router'; @Component({ selector: 'app-create-list', templateUrl: './create-list.component.html', styleUrls: ['./create-list.component.css'] }) export class CreateListComponent implements OnInit { name: String; constructor(private storage_service: StorageService, private toastr: ToastrService, private router: Router) { } ngOnInit(): void { } successMessage() { this.toastr.success('nouvel élément ajouté à la TodoList'); } insertElement() { const obj = { title: this.name } this.successMessage(); return this.storage_service.addElement(obj); } backHome() { this.router.navigateByUrl('/home'); } } <file_sep>/src/app/layout/show-list/show-list.component.ts import { Component, OnInit } from '@angular/core'; import { StorageService } from 'src/services/storage.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-show-list', templateUrl: './show-list.component.html', styleUrls: ['./show-list.component.css'] }) export class ShowListComponent implements OnInit { todoList: Array<any>; constructor(private storage_service: StorageService, private router: Router) { } ngOnInit(): void { this.todoList = this.storage_service.getTodoList(); } backHome() { this.router.navigateByUrl('/home'); } } <file_sep>/src/services/storage.service.ts import { Injectable } from '@angular/core'; const storageName = 'todo_list'; const defaultList = [ { title: 'install NodeJS' }, { title: 'install Angular CLI' }, { title: 'create new app' }, { title: 'serve app' }, { title: 'develop app' }, { title: 'deploy app' }, ]; @Injectable({ providedIn: 'root' }) export class StorageService { private todoList: any; constructor() { this.todoList = JSON.parse(localStorage.getItem(storageName)) || defaultList; } getTodoList() { return [...this.todoList]; } addElement(item) { this.todoList.push(item); return this.updateTodoList(); } updateTodoList() { localStorage.setItem(storageName, JSON.stringify(this.todoList)); return this.getTodoList(); } } <file_sep>/src/app/layout/login/login.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { ToastrService } from 'ngx-toastr'; import { Router } from '@angular/router'; const email = "<EMAIL>"; const password = "<PASSWORD>"; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { loginForm: FormGroup; constructor(fb: FormBuilder, private router: Router, private toastr: ToastrService) { this.loginForm = fb.group({ email: new FormControl('', [Validators.required, Validators.email]), password: new FormControl('') }) } ngOnInit(): void { } errorMessage() { this.toastr.error('email ou mot de passe invalide'); } onSubmit() { const form = this.loginForm.value; if(this.loginForm.valid) { if(form.email === email && form.password === password) { this.router.navigateByUrl('/home'); } } else { this.errorMessage(); } } }
bff94d60090c7ce907260ea664871833607043de
[ "TypeScript" ]
4
TypeScript
MedaR/todolist
8327f3c57deb02c773a9adc1bf66844530ef8cc0
853a759b279fe2529bee68b20fe49b63b21d60d7
refs/heads/master
<repo_name>Nicogene/ZfpCompresser<file_sep>/cmake/FindZFP.cmake # # Find the ZFP includes and library # # This module defines # ZFP_INCLUDE_DIR, where to find zfp.h # ZFP_LIBRARIES, the libraries to link against # ZFP_FOUND, if false, you cannot build anything that requires ZFP ######################################################################## find_path(ZFP_INCLUDE_DIR zfp.h /usr/include /usr/local/include $ENV{ZFP_ROOT} $ENV{ZFP_ROOT}/inc DOC "directory containing zfp/zfp.h for ZFP library") find_library(ZFP_LIBRARY NAMES ZFP zfp PATHS /usr/lib /usr/local/lib $ENV{ZFP_ROOT}/lib $ENV{ZFP_ROOT} DOC "ZFP library file") if (WIN32 AND NOT CYGWIN) set(CMAKE_DEBUG_POSTFIX "d") find_library(ZFP_DEBUG_LIBRARY NAMES ZFP${CMAKE_DEBUG_POSTFIX} zfp${CMAKE_DEBUG_POSTFIX} PATHS ${CMAKE_SOURCE_DIR}/../ZFP_wrappers/lib/ /usr/lib /usr/local/lib $ENV{ZFP_ROOT}/lib $ENV{ZFP_ROOT} DOC "ZFP library file (debug version)") endif () if (ZFP_INCLUDE_DIR AND ZFP_LIBRARY) set(ZFP_FOUND TRUE) else () set(ZFP_FOUND FALSE) endif () if (ZFP_DEBUG_LIBRARY) set(ZFP_DEBUG_FOUND TRUE) else () set(ZFP_DEBUG_LIBRARY ${ZFP_LIBRARY}) endif () if (ZFP_FOUND) if (NOT ZFP_FIND_QUIETLY) message(STATUS "Found ZFP library: ${ZFP_LIBRARY}") message(STATUS "Found ZFP include: ${ZFP_INCLUDE_DIR}") endif () else () if (ZFP_FIND_REQUIRED) message(FATAL_ERROR "Could not find ZFP") endif () endif () # TSS: backwards compatibility set(ZFP_LIBRARIES ${ZFP_LIBRARY}) <file_sep>/src/zfpCompresserModule.cpp #include "zfpCompresserModule.h" using namespace yarp::os; using namespace yarp::sig; ZFPCompresserModule::ZFPCompresserModule(int _numIter):numIter(_numIter), interrupted(false){ } ZFPCompresserModule::~ZFPCompresserModule(){ } bool ZFPCompresserModule::configure(yarp::os::ResourceFinder &rf){ //Open ports bool ret=portIn.open("/ZFPCompresser/depthImage:i"); ret &= portOut.open("/ZFPCompresser/depthImage:o"); if(!ret) { yError()<<"Could not connect to some of the ports"; return false; } return true; } bool ZFPCompresserModule::updateModule(){ static int count = numIter; if(count<=0) { yDebug()<<"finishing acquisition..."; return false; } // read port yInfo() <<"ZFPCompresserModule:acquiring images..."; ImageOf<PixelFloat> *image = portIn.read(); if (!image) { yError()<<"Acquisition failed"; return false; } yInfo() <<"ZFPCompresserModule:acquiring images [done]"; //Stamp s; float *compressed = NULL; float *decompressed=NULL; int sizeCompressed; //count -= 1; //comment for an infinite loop compress((float*)image->getRawImage(), compressed, sizeCompressed, image->width(),image->height(),1e-3); decompress(compressed, decompressed, sizeCompressed, image->width(),image->height(),1e-3); ImageOf<PixelFloat> &imageOut=portOut.prepare(); //yDebug()<<decompressed[100];OK if(!decompressed){ yError()<<"Failed to decompress, exiting..."; return false; } //imageOut.setExternal(decompressed,image->width(),image->height());//segmentation fault!! imageOut.resize(image->width(),image->height()); memcpy(imageOut.getRawImage(),decompressed,image->width()*image->height()*4); portOut.write(); if(compressed) free(compressed); if(decompressed) free(decompressed); return true; } int ZFPCompresserModule::compress(float* array, float* &compressed, int &zfpsize, int nx, int ny, float tolerance){ int status = 0; /* return value: 0 = success */ zfp_type type; /* array scalar type */ zfp_field* field; /* array meta data */ zfp_stream* zfp; /* compressed stream */ void* buffer; /* storage for compressed stream */ size_t bufsize; /* byte size of compressed buffer */ bitstream* stream; /* bit stream to write to or read from */ type = zfp_type_float; field = zfp_field_2d(array, type, nx, ny); /* allocate meta data for a compressed stream */ zfp = zfp_stream_open(NULL); /* set compression mode and parameters via one of three functions */ /* zfp_stream_set_rate(zfp, rate, type, 3, 0); */ /* zfp_stream_set_precision(zfp, precision, type); */ zfp_stream_set_accuracy(zfp, tolerance, type); /* allocate buffer for compressed data */ bufsize = zfp_stream_maximum_size(zfp, field); buffer = malloc(bufsize); /* associate bit stream with allocated buffer */ stream = stream_open(buffer, bufsize); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); /* compress entire array */ /* compress array and output compressed stream */ zfpsize = zfp_compress(zfp, field); if (!zfpsize) { fprintf(stderr, "compression failed\n"); status = 1; } else yInfo()<<"compression successful, ratio of compression:"<<(nx*ny*4.0)/(zfpsize)<<":1"<<"orgSize=" <<nx*ny*4.0<<"compressedSize="<<zfpsize;//4 -> float compressed = (float*) malloc(zfpsize); memcpy(compressed,(float*) stream_data(zfp->stream),zfpsize); /* clean up */ zfp_field_free(field); zfp_stream_close(zfp); stream_close(stream); free(buffer); return status; } int ZFPCompresserModule::decompress(float* array, float* &decompressed, int zfpsize, int nx, int ny, float tolerance){ int status = 0; /* return value: 0 = success */ zfp_type type; /* array scalar type */ zfp_field* field; /* array meta data */ zfp_stream* zfp; /* compressed stream */ void* buffer; /* storage for compressed stream */ size_t bufsize; /* byte size of compressed buffer */ bitstream* stream; /* bit stream to write to or read from */ type = zfp_type_float; decompressed = (float*) malloc(nx*ny*sizeof(float)); field = zfp_field_2d(decompressed, type, nx, ny); /* allocate meta data for a compressed stream */ zfp = zfp_stream_open(NULL); /* set compression mode and parameters via one of three functions */ /* zfp_stream_set_rate(zfp, rate, type, 3, 0); */ /* zfp_stream_set_precision(zfp, precision, type); */ zfp_stream_set_accuracy(zfp, tolerance, type); /* allocate buffer for compressed data */ bufsize = zfp_stream_maximum_size(zfp, field); buffer = malloc(bufsize); memcpy(buffer,array,zfpsize); // /* associate bit stream with allocated buffer */ stream = stream_open(buffer, zfpsize); yDebug()<<"3"; zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); /* compress or decompress entire array */ /* read compressed stream and decompress array */ //zfpsize = fread(buffer, 1, bufsize, stdin); //devo metterci il mio puntatore al dato compresso. if (!zfp_decompress(zfp, field)) { fprintf(stderr, "decompression failed\n"); status = 1; } else yInfo()<<"Decompression successful"; yDebug()<<"bufsize"<<bufsize<<"zfpsize"<<zfpsize; //std::cout<<"test decompressed data "<<((float*) field->data)[76799]<<std::endl; //OK // ((float*) field->data)[i + nx * (j)] //nx*ny*sizeof(float) //memcpy(decompressed,(float*) field->data,nx*ny*sizeof(float)); /* clean up */ zfp_field_free(field); zfp_stream_close(zfp); stream_close(stream); free(buffer); return status; } double ZFPCompresserModule::getPeriod(){ return 0.0; } bool ZFPCompresserModule::interruptModule(){ //interrupt ports interrupted=true; portIn.interrupt(); portOut.interrupt(); return true; } bool ZFPCompresserModule::close(){ yInfo()<<"Waiting for worker thread..."; //close ports portIn.close(); portOut.close(); return true; } <file_sep>/include/zfpCompresserModule.h #ifndef ZFPCOMPRESSERMODULE_H #define ZFPCOMPRESSERMODULE_H #include "yarp/os/all.h" #include "yarp/sig/all.h" #include "zfp.h" class ZFPCompresserModule : public yarp::os::RFModule { int numIter; bool interrupted; yarp::os::BufferedPort<yarp::sig::ImageOf<yarp::sig::PixelFloat> > portIn, portOut; public: ZFPCompresserModule(int _numIter); ~ZFPCompresserModule(); bool configure(yarp::os::ResourceFinder &rf); bool updateModule(); double getPeriod(); bool interruptModule(); bool close(); protected: // int compressAndDecompress(float* array, int nx, int ny, float tolerance); int compress(float* array, float* &compressed, int &zfpsize, int nx, int ny, float tolerance); int decompress(float* array, float* &decompressed, int zfpsize, int nx, int ny, float tolerance); }; #endif <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.2.2) SET(PROJECTNAME ZFPCompresserModule) PROJECT(${PROJECTNAME}) # Make CMake aware of the cmake folder for local FindXXX scripts, # append rather than set in case the user has passed their own # additional paths via -D. list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") message(${CMAKE_MODULE_PATH}) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) # Set postfixes for generated libraries based on buildtype. set(CMAKE_RELEASE_POSTFIX "") set(CMAKE_DEBUG_POSTFIX "-debug") # Flags set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall") # Options option(YARP "Enable use of YARP." ON) option(ZFP "Enable use of ZFP compression library." ON) #ZFP if(ZFP) find_package(ZFP REQUIRED) if (ZFP_FOUND) message("-- Found ZFP library: ${ZFP_LIBRARY}") include_directories(${ZFP_INCLUDE_DIR}) else (ZFP_FOUND) message("-- Did not find ZFP library.") endif (ZFP_FOUND) endif(ZFP) # YARP. if (YARP) find_package( YARP REQUIRED ) if (YARP_FOUND) message("-- Found YARP library: ${YARP_LIBRARIES}") include_directories(${YARP_INCLUDE_DIRS}) else (YARP_FOUND) message("-- Did not find YARP library.") endif (YARP_FOUND) endif (YARP) set(SOURCE_DIR ./src) set(INCLUDE_DIR ./include) include_directories(${SOURCE_DIR} ${INCLUDE_DIR} ../src ../include) file(GLOB Executable_SOURCES ${SOURCE_DIR}/*.cpp) file(GLOB Executable_HEADERS ${INCLUDE_DIR}/*.h) add_executable(${PROJECTNAME} ${Executable_SOURCES} ${Executable_HEADERS}) target_link_libraries(${PROJECTNAME} ${YARP_LIBRARIES} ${ZFP_LIBRARY} ) if(${CMAKE_VERSION} VERSION_LESS 3.1) include(CheckCXXCompilerFlag) check_cxx_compiler_flag("-std=c++11" COMPILER_SUPPORTS_CXX11) check_cxx_compiler_flag("-std=c++0x" COMPILER_SUPPORTS_CXX0X) if(COMPILER_SUPPORTS_CXX11) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") elseif(COMPILER_SUPPORTS_CXX0X) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") else() message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.") endif() else() target_compile_features(${PROJECTNAME} PRIVATE cxx_range_for) endif() <file_sep>/src/main.cpp #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <algorithm> #include <zfp.h> #include <yarp/os/all.h> #include "zfpCompresserModule.h" int main (int argc, char** argv) { yarp::os::Network yarp; ZFPCompresserModule mod(10); yarp::os::ResourceFinder rf; rf.configure(argc,argv); //it calls .configure and then .updateModule mod.runModule(rf); return 0; }
661b9ff9705fa747908573b9a078111b8f0283d5
[ "CMake", "C++" ]
5
CMake
Nicogene/ZfpCompresser
968bf19b4b2ac8f521c57141ff91c3db319c919a
d74af74bcd4130688bd324a018e8ca2fc753171e
refs/heads/master
<repo_name>DSimkevicius/react-cv<file_sep>/src/components/pages/skills/Skills.jsx import React, { Component } from "react"; export default class Skills extends Component { render() { return ( <div> <div className="card teal darken-3 z-depth-0"> <div className="card-content"> <h6 className="white-text"> <strong># CODING SKILLS</strong> </h6> <hr /> <div className="row pt"> <div className="col m6 s12"> <p className="grey-text text-lighten-3">HTML5</p> <div className="progress white"> <div className="determinate pink accent-3" style={{ width: "80%" }} ></div> </div> </div> <div className="col m6 s12"> <p className="grey-text text-lighten-3">CSS</p> <div className="progress white"> <div className="determinate pink accent-3 " style={{ width: "80%" }} ></div> </div> </div> </div> <div className="row pt"> <div className="col m6 s12"> <p className="grey-text text-lighten-3">JS</p> <div className="progress white"> <div className="determinate pink accent-3" style={{ width: "55%" }} ></div> </div> </div> <div className="col m6 s12"> <p className="grey-text text-lighten-3">MySQL</p> <div className="progress white"> <div className="determinate pink accent-3" style={{ width: "40%" }} ></div> </div> </div> </div> <div className="row pt"> <div className="col m6 s12"> <p className="grey-text text-lighten-3">NodeJS</p> <div className="progress white"> <div className="determinate pink accent-3" style={{ width: "50%" }} ></div> </div> </div> <div className="col m6 s12"> <p className="grey-text text-lighten-3">React</p> <div className="progress white"> <div className="determinate pink accent-3" style={{ width: "50%" }} ></div> </div> </div> </div> </div> </div> </div> ); } } <file_sep>/src/components/pages/Home.jsx import React, { Component } from "react"; import Profile from "./profile/Profile.jsx"; import Contact from "./contact/Contact.jsx"; import About from "./about/About.jsx"; import Skills from "./skills/Skills.jsx"; import Experiences from "./experiences/Experiences.jsx"; import Educations from "./educations/Educations.jsx"; import References from "../references/References.jsx"; export default class Home extends Component { render() { return ( <section> <div className="row sameHeight"> <div className="col s12 m12 l4 teal darken-3 sameHeight_child"> <Profile /> <Contact /> <Skills /> </div> <div className="col s12 m12 l8 white sameHeight_child"> <About /> <Educations /> <Experiences /> <References /> </div> </div> </section> ); } } <file_sep>/src/components/references/References.jsx import React, { Component } from "react"; export default class References extends Component { render() { return ( <div> <div className="card z-depth-0"> <div className="card-content"> <h6> <strong> <i></i>📱 REFERENCES </strong> </h6> <hr /> <div className="row mt"> <div className="col s12"> <blockquote> <h6 className="no-pad mt-bottom"> <strong><NAME></strong> <span> <strong>Tech Lead, IBM iX</strong> </span> </h6> <p className="pt"><EMAIL></p> <p className="pt">+370 675 74401</p> </blockquote> </div> </div> </div> </div> </div> ); } } <file_sep>/src/components/pages/about/About.jsx import React, { Component } from "react"; export default class About extends Component { render() { return ( <div> <div className="card z-depth-0 hide-on-med-and-down pt"> <div className="card-content social"> <h2 className="grey-text text-darken-3"><NAME></h2> <h5 className="grey-text text-darken-1">Front-End Developer</h5> <a href="https://github.com/DSimkevicius" target="blank"> <i className="fab fa-github-square fa-2x"></i> </a> </div> </div> </div> ); } } <file_sep>/src/components/pages/experiences/Experiences.jsx import React, { Component } from "react"; export default class Experiences extends Component { render() { return ( <div> <div className="card z-depth-0"> <div className="card-content"> <h6> <strong> <i className="fas fa-tools"></i> CODING EXPERIENCE </strong> </h6> <hr /> <div className="row mt"> <div className="col s12"> <blockquote className="content-right"> <h6 className="no-pad mt-bottom"> <strong>FRONT-END DEVELOPER</strong> <span>2020 - 2021</span> </h6> <p className="pt"> CodeAcademy experience by creating projects, apps using web development languages as HTML, CSS, JS, NodeJS, MySQL. Using JS libraries for building web interfaces (React, Vue). Also learned basics how to use platforms such as Firebase, DigitalOcean. As of now, I can write clean, reusable and responsive code in HTML, CSS and Javascript. I have learned how to work with CSS frameworks, such as Bulma, Boostrap and others. </p> </blockquote> </div> </div> </div> </div> </div> ); } } <file_sep>/src/components/pages/profile/Profile.jsx import React, { Component } from "react"; export default class Profile extends Component { render() { return ( <div> <div className="card teal darken-3 z-depth-0 hide-on-large-only"> <div className="card-content center social"> <h2 className="grey-text text-lighten-3"> <strong><NAME></strong> </h2> <h5 className="white-text text-lighten-1">Front-End Developer</h5> <a href="https://github.com/DSimkevicius" target="blank"> <i className="fab fa-github-square fa-2x"></i> </a> </div> </div> </div> ); } }
5eaccec51c33e035092f5c4dec0e475d7789851d
[ "JavaScript" ]
6
JavaScript
DSimkevicius/react-cv
c2732ed5d414cf2c8fb3a2729b235ef8defd2569
2d0e722b45e47ff9e3aaaa93e081cd21c85f0d6a
refs/heads/master
<file_sep>const jwt = require('jsonwebtoken'); const config = require("../config"); const jwtSecret = config.jwtSecret; module.exports = { jwtMiddleware: async (req, res, next) => { try { const header = await req.headers["authorization"]; if(typeof header === "string" && header.indexOf(" ") > -1) { const array = header.split(" "); const token = array[1]; const verified = await jwt.verify(token, jwtSecret); if(verified) { next(); } else { res.status(401).json("Token failed to varify"); } } else { res.status(403).json("No token in header"); } } catch(err) { next(err); } } }<file_sep>const Blog = require("../models/blog-model"); const User = require("../models/user-model"); const config = require("../config"); const mongoose = require("mongoose"); mongoose.connect(config.databaseUrl); module.exports = { //INDEX ROUTE showBlogs: async (req, res, next) => { try{ const blogs = await Blog.find({}); res.status(200).json(blogs); } catch(err) { next(err); } }, //SHOW ROUTE (WITH VALIDATION) showBlog: async (req, res, next) => { try{ const { id } = req.params; const blog = await Blog.findById(id); res.status(200).json(blog); } catch(err){ next(err); } }, //UPDATE ROUTE (WITH VALIDATION) updateBlog: async (req, res, next) => { try{ const { id } = req.value.params; const newBlog = req.value.body; const result = await Blog.findByIdAndUpdate(id, newBlog); res.status(200).json({success: true}); } catch(err){ next(err); } }, //DELETE ROUTE (WITH VALIDATION) deleteBlog: async (req, res, next) => { try{ const id = req.value.params.id; await Blog.findOne({_id: id}, async (err, blog) => { try{ const authorId = blog.author; const author = await User.findById(authorId); const index = author.blogs.indexOf(id); author.blogs.splice(index, 1); await author.save(); await Blog.deleteOne(blog); res.status(200).json({success: true}); } catch(err){ next(err); } }); } catch(err){ next(err); } }, //CREATE BLOG ROUTE (WITH VALIDATION) createBlog: async (req, res, next) => { try{ userId = config.userId; const newBlog = new Blog(req.value.body); const user = await User.findById(userId); newBlog.author = user; await newBlog.save(async () => { try { user.blogs.push(newBlog); await user.save(); res.status(201).json(newBlog); } catch(err) { next(err); } }); } catch(err){ next(err); } } }<file_sep>const config = {}; const dbUserName = "user"; const dbPassword = "<PASSWORD>"; const dbName = "blogauth"; config.databaseUrl = `mongodb://${dbUserName}:${dbPassword}@<EMAIL>:15208/${dbName}`; // config.databaseUrl = "mongodb://user:user@<EMAIL>.<EMAIL>:15208/blogauth"; config.jwtSecret = "<KEY>"; config.port = process.env.PORT || 8001; config.ip = process.env.IP; config.userId; module.exports = config;<file_sep>const User = require("../models/user-model"); const mongoose = require("mongoose"); const jwt = require("jsonwebtoken"); const config = require("../config"); const bcrypt = require("bcrypt"); const saltRounds = 10; mongoose.connect(config.databaseUrl); const jwtSecret = config.jwtSecret; module.exports = { //CREATE USER (WITH VALIDATION) createUser: async (req, res, next) => { try{ const newUser = new User(req.value.body); const password = req.value.body.password; const passwordHashed = await bcrypt.hash(password, saltRounds); newUser.password = <PASSWORD>Hashed; const result = await newUser.save(); res.status(200).json({success: true}); } catch(err){ next(err); } }, //AUTHENTICATE USER (WITH VALIDATION) authenticateUser: async (req, res, next) => { try { const password = req.value.body.password; const email = req.value.body.email; const userFromDb = await User.find({email}); if (userFromDb[0]){ const match = await bcrypt.compare(password, userFromDb[0].password); if (match) { config.userId = userFromDb[0]._id; const token = await jwt.sign({name: userFromDb.name, email: userFromDb.email}, jwtSecret); res.status(200).send({ user: {name: userFromDb.name, email: userFromDb.email}, token: token }); } else { res.status(401).json("Failed to authorize. Wrong password!"); } } else { res.status(403).json("Failed to authorize. No such user!"); } } catch(err) { next(err); } } }<file_sep>const express = require("express"); const router = express.Router() const blogController = require("../controllers/blog-controller"); const { jwtMiddleware } = require("../functions/jwt-token-verification"); const { validateParam, validateBody } = require("../validation/joi-validation-logic"); const { joiBlogSchema, joiIdSchema } = require("../validation/joi-schemas"); router.route("/blogs") .get( blogController.showBlogs ) .post( jwtMiddleware, validateBody(joiBlogSchema), blogController.createBlog ); router.route("/blogs/:id") .get( jwtMiddleware, validateParam(joiIdSchema, "id"), blogController.showBlog ) .put( jwtMiddleware, [ validateParam(joiIdSchema, "id"), validateBody(joiBlogSchema) ], blogController.updateBlog ) .delete( jwtMiddleware, validateParam(joiIdSchema, "id"), blogController.deleteBlog ); module.exports = router; <file_sep>const Joi = require("joi"); module.exports = { joiBlogSchema: Joi.object().keys({ title: Joi.string().required(), image: Joi.string().regex(/^((https:\/\/www\.)|(http:\/\/www\.)|(www\.)|(https:\/\/)|(http:\/\/))[a-zA-Z0-9._/-]+$/), //\.[a-zA-Z.]{2,5} body: Joi.string() }), joiUserLoginSchema: Joi.object().keys({ email: Joi.string().email().required(), password: <PASSWORD>().required() }), joiUserRegistrationSchema: Joi.object().keys({ name: Joi.string().required(), email: Joi.string().email().required(), password: <PASSWORD>().required() }), joiIdSchema: Joi.object().keys({ param: Joi.string().regex(/^[0-9a-fA-F]{24}$/).required() }) }<file_sep>const Blog = require("./models/blog-model"); const mongoose = require("mongoose"); const dbUserName = "user"; const dbPassword = "<PASSWORD>"; const dbName = "blogauth"; databaseUrl = `mongodb://${dbUserName}:${dbPassword}@<EMAIL>:15208/${dbName}`; mongoose.connect(databaseUrl); const showBlogs = async (req, res, next) => { try{ const blogs = await Blog.find({}); return blogs; } catch(err) { next(err); } } console.log( showBlogs() .then( blogs => console.log(blogs) ) );
50cbc6bf50079732e5fb8810271fc07b30e85d03
[ "JavaScript" ]
7
JavaScript
zbigan/angularBlogBackend
57d22cf2c5b17bc606e8aefbe2236a3d20c4cd20
60181d4a611f5257d419f01e3ce9773980d75673
refs/heads/master
<file_sep>#!/bin/bash # Постучите в бубен и помолитесь перед запуском данной программы! Она работает только тогда, когда хочется ей. И не питайте илюзий, что эта программа # решит ваши проблемы c гитхабом. Вы будете мучиться с ним вечно! echo "" echo "Разработчик: <NAME>" echo "Группа: K01-361" echo "Описание: Данная программа заливает файлы на гитхаб только в существующие репозитории" echo "" echo "Начать выполнение? (y/n): "; yn='y' while [ $yn = "y" -o $yn = "Y" ]; do read yn; if [ $yn = "y" -o $yn = "Y" ]; then echo "1) Добавление нового файла в репозиторий на GitHub" echo "2) Удаление файла с GitHub" echo "3) Обновление всех файлов в репозитории GitHub" echo "4) При создании нового репозитория (автодобавление Readme.md)" read case1 case "$case1" in 1 ) echo "Введите директорию:" read d while ! [ -d $d ]; do echo "Такой директории не существует. Повторить? (y/n)" read yn if [ $yn = "y" -o $yn = "Y" ]; then echo "Введите директорию:" read d elif [ $yn = "n" -o $yn = "N" ]; then echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 else while ! [ $yn = "n" -o $yn = "N" -o $yn = "y" -o $yn = "Y" ] do echo "Ошибка ввода! Введите y/n:" read yn if [ $yn = "y" -o $yn = "Y" ]; then echo "Введите директорию:" read d elif [ $yn = "n" -o $yn = "N" ]; then echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 fi done fi done echo "Введите имя файла:" read f echo "Введите содержание коммита" read c echo "Введите имя репозитория" read repo echo "Введите логин на GitHub" read login cd $d touch $f git add $f git commit -m "$c" git remote add origin https://github.com/$login/$repo.git git push -u origin master ;; 2 ) echo "Введите директорию:" read d while ! [ -d $d ]; do echo "Такой директории не существует. Повторить? (y/n)" read yn if [ $yn = "y" -o $yn = "Y" ]; then echo "Введите директорию:" read d elif [ $yn = "n" -o $yn = "N" ]; then echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 else while ! [ $yn = "n" -o $yn = "N" -o $yn = "y" -o $yn = "Y" ] do echo "Ошибка ввода! Введите y/n:" read yn if [ $yn = "y" -o $yn = "Y" ]; then echo "Введите директорию:" read d elif [ $yn = "n" -o $yn = "N" ]; then echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 fi done fi done echo "Введите имя файла:" read f echo "Введите имя репозитория" read repo echo "Введите логин на GitHub" read login cd $d touch $f git rm -f $f git remote add origin https://github.com/$login/$repo.git git push -u origin master ;; 3 ) echo "Введите директорию:" read d while ! [ -d $d ]; do echo "Такой директории не существует. Повторить? (y/n)" read yn if [ $yn = "y" -o $yn = "Y" ]; then echo "Введите директорию:" read d elif [ $yn = "n" -o $yn = "N" ]; then echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 else while ! [ $yn = "n" -o $yn = "N" -o $yn = "y" -o $yn = "Y" ] do echo "Ошибка ввода! Введите y/n:" read yn if [ $yn = "y" -o $yn = "Y" ]; then echo "Введите директорию:" read d elif [ $yn = "n" -o $yn = "N" ]; then echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 fi done fi done echo "Введите содержание коммита" read c echo "Введите имя репозитория" read repo echo "Введите логин на GitHub" read login cd $d git add . git commit -m "$c" git remote add origin https://github.com/$login/$repo.git git push -u origin master ;; 4 ) echo "Введите директорию:" read d while ! [ -d $d ]; do echo "Такой директории не существует. Повторить? (y/n)" read yn if [ $yn = "y" -o $yn = "Y" ]; then echo "Введите директорию:" read d elif [ $yn = "n" -o $yn = "N" ]; then echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 else while ! [ $yn = "n" -o $yn = "N" -o $yn = "y" -o $yn = "Y" ] do echo "Ошибка ввода! Введите y/n:" read yn if [ $yn = "y" -o $yn = "Y" ]; then echo "Введите директорию:" read d elif [ $yn = "n" -o $yn = "N" ]; then echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 fi done fi done echo "Введите имя репозитория" read repo echo "Введите логин на GitHub" read login cd $d touch README.md git init git add README.md git commit -m "first commit" git remote add origin https://github.com/$login/$repo.git git push -u origin master ;; esac echo "Повторить? (y/n): "; yn=y elif [ $yn = "n" -o $yn = "N" ]; then echo "Прекращено пользователем." else echo "Ошибка ввода! Введите y/n:" yn=y fi done echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" <file_sep>#!/bin/bash # цикл для бесконечного выполнения программы clear echo "" echo "Разработчик: <NAME>" echo "Группа: K01-361" echo "Описание: Данная программа выводит права пользователя к файлу" echo "" echo "Начать выполнение? (y/n): "; yn='y' while [ $yn = "y" -o $yn = "Y" ]; do read yn; if [ $yn = "y" -o $yn = "Y" ]; then # # # # # # # # echo "Повторить? (y/n): "; yn=y elif [ $yn = "n" -o $yn = "N" ]; then echo "Прекращено пользователем." clear else echo "Ошибка ввода! Введите y/n:" yn=y fi done clear echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" <file_sep>#!/bin/bash # Проверка существования пользователя echo "Введите имя пользователя" read u clear while ! [ $(getent passwd $u ) ]; do # проверка на наличие пользователя echo "Такого пользователя не существует. Повторить? (y/n)" read yn if [ $yn = "y" -o $yn = "Y" ]; then clear echo "Введите имя пользователя:" read u elif [ $yn = "n" -o $yn = "N" ]; then clear echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 else while ! [ $yn = "n" -o $yn = "N" -o $yn = "y" -o $yn = "Y" ] do echo "Ошибка ввода! Введите y/n:" read yn if [ $yn = "y" -o $yn = "Y" ]; then clear echo "Введите имя пользователя:" read u elif [ $yn = "n" -o $yn = "N" ]; then echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 fi done fi done clear <file_sep>#!/bin/bash # проверка существования файла echo "Введите путь к файлу:" read f clear while ! [ -f $f ]; do echo "Такого файла не существует. Повторить? (y/n)" read yn if [ $yn = "y" -o $yn = "Y" ]; then clear echo "Введите путь к файлу:" read f elif [ $yn = "n" -o $yn = "N" ]; then clear echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 else while ! [ $yn = "n" -o $yn = "N" -o $yn = "y" -o $yn = "Y" ] do echo "Ошибка ввода! Введите y/n:" read yn if [ $yn = "y" -o $yn = "Y" ]; then clear echo "Введите путь к файлу:" read f elif [ $yn = "n" -o $yn = "N" ]; then clear echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 fi done fi done # проверка существования файла или директории echo "Введите путь к файлу:" read f clear while ! [ -e $f ]; do echo "Такого файла не существует. Повторить? (y/n)" read yn if [ $yn = "y" -o $yn = "Y" ]; then clear echo "Введите путь к файлу:" read f elif [ $yn = "n" -o $yn = "N" ]; then clear echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 else while ! [ $yn = "n" -o $yn = "N" -o $yn = "y" -o $yn = "Y" ] do echo "Ошибка ввода! Введите y/n:" read yn if [ $yn = "y" -o $yn = "Y" ]; then clear echo "Введите путь к файлу:" read f elif [ $yn = "n" -o $yn = "N" ]; then clear echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 fi done fi done clear # проверка существования директории echo "Введите директорию:" read f clear while ! [ -d $f ]; do echo "Такой директории не существует. Повторить? (y/n)" read yn if [ $yn = "y" -o $yn = "Y" ]; then clear echo "Введите директорию:" read f elif [ $yn = "n" -o $yn = "N" ]; then clear echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 else while ! [ $yn = "n" -o $yn = "N" -o $yn = "y" -o $yn = "Y" ] do echo "Ошибка ввода! Введите y/n:" read yn if [ $yn = "y" -o $yn = "Y" ]; then clear echo "Введите директорию:" read f elif [ $yn = "n" -o $yn = "N" ]; then clear echo "Программа завершена!" echo "Разработчик: <NAME>" echo "Группа: K01-361" exit 0 fi done fi done clear
e97160fd2dae851dd14785f28ecff30a1232d63c
[ "Shell" ]
4
Shell
Kustov-Daniil/my
540f818544905497b350d45c619043667f57b2d0
489a8ae35dd41e19a2f93abf2a8504a83a21f210
refs/heads/master
<file_sep>#!/usr/bin/env python3 ''' Checks the inventory of the Microsoft Xbox X console on BHPhoto and NewEgg. Best Buy, Target, and Walmart actually have APIs but you need to be registered with them to get an API key. 'Free' email accounts won't work. UPDATE: I found that popfindr.com can pull inventory, and then I can statically scrape inventory from the results. This is for the Target and Best Buy inventory in Fayetteville NC. Use Firefox Developer to pull the right page from PopFindr. Added Microsoft.com inventory scrape. For the sound to work in Linux under Python3: You need: 'sudo apt install sox' on a Debian-based system so that the system can 'beep' at you when the item is found. ''' import requests, time, os from bs4 import BeautifulSoup from datetime import datetime import pandas as pd # due to a bug in Windowz, you'll need 'pip install numpy==1.19' for pandas import platform import winsound def main(): operatingsystem = getplatform() while True: try: now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time: ", current_time) PopFindrBestBuy(operatingsystem) PopFindrTarget(operatingsystem) microsoft(operatingsystem) bhphoto(operatingsystem) newegg(operatingsystem) print('\n') print('Sleeping for 60 seconds') time.sleep(60) print('\n') except Exception: print('Ran into an exception in check function. Pausing for 60 seconds.') time.sleep(60) except KeyboardInterrupt: print('Quitting...') quit() def getplatform(): try: plt = platform.system() if plt == "Windows": print("Your system is Windows") operatingsystem = "Windows" elif plt == "Linux": print("Your system is Linux") operatingsystem = "Linux" elif plt == "Darwin": print("Your system is MacOS") operatingsystem = "Mac" else: #print("Unidentified system") operatingsystem='Linux' return operatingsystem except Exception: print('error in getting OS information.') quit() except KeyboardInterrupt: quit() def beep(operatingsystem): if operatingsystem == 'Linux': duration = 20 # seconds freq = 440 # Hz os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq)) if operatingsystem =='Windows': print('beeping windows!') for i in range(1,10): winsound.PlaySound("SystemAsterisk", winsound.SND_ALIAS) def newegg(operatingsystem): #print('Checking NewEgg') try: producturl = 'https://www.newegg.com/p/N82E16868105273' page = requests.get(producturl) soup = BeautifulSoup(page.content, 'html.parser') stock = soup.find('div', {'class':'product-inventory'}) if 'OUT OF STOCK' not in stock.text.strip(): print('-----------Newegg-----: ' , stock.text.strip()) beep(operatingsystem) elif 'OUT OF STOCK' in stock.text.strip(): print('Newegg: ' , stock.text.strip()) except KeyboardInterrupt: print('Quitting...') quit() except Exception: print('Ran into an exception in NewEgg. Likely a request error.') def bhphoto(operatingsystem): #print('Checking BHPhotoVideo') try: #producturl = 'https://www.bhphotovideo.com/c/product/1573218-REG/microsoft_234_00001_xbox_one_s_1tb.html' producturl = 'https://www.bhphotovideo.com/c/product/1600080-REG/microsoft_rrt_00001_xbox_series_x_1tb.html' page = requests.get(producturl) soup = BeautifulSoup(page.content, 'html.parser') try: stock = soup.find('span', {'data-selenium':'stockStatus'}) if 'In Stock' in stock.text.strip(): print('-----------------BHPhotoVideo: -------' , stock.text.strip()) beep(operatingsystem) elif 'In Stock' not in stock.text.strip(): print('BHPhotoVideo: Not in stock.') except Exception: print('BHPhtoVideo: String Not found (Probably out of stock).') except KeyboardInterrupt: print('Quitting...') quit() except Exception: print('Ran into an exception in bhphoto. Likely a request error.') def PopFindrTarget(operatingsystem): producturl = 'https://popfindr.com/results?pid=207-41-0001&zip=28348&range=25&webpage=target&token=<KEY>' try: page = requests.get(producturl) soup = BeautifulSoup(page.content, 'html.parser') try: tables = soup.find_all('table')[1] row = tables.find_all('tr')[1] cell = row.find_all('th')[2] inventory = cell.text.strip() if inventory == '0': print(f'Target has {inventory}.') elif inventory != '0': print(f'---------------Target has {inventory} IN STOCK!') beep(operatingsystem) except Exception: print('Target: String Not found (Probably out of stock)') except Exception: print('Ran into an exception in PopFindr Target. Likely a request error.') except KeyboardInterrupt: print('Quitting...') quit() def microsoft(operatingsystem): producturl ='https://www.xbox.com/en-us/configure/8WJ714N3RBTL?ranMID=24542&ranEAID=kXQk6*ivFEQ&ranSiteID=kXQk6.ivFEQ-WT4rQZgrrl6u7WL9k7aH9A&epi=kXQk6.ivFEQ-WT4rQZgrrl6u7WL9k7aH9A&irgwc=1&OCID=AID2000142_aff_7593_1243925&tduid=%28ir__gce1vdpse0kfqibbkk0sohzn3m2xsu1wbx0bflsr00%29%287593%29%281243925%29%28kXQk6.ivFEQ-WT4rQZgrrl6u7WL9k7aH9A%29%28%29&irclickid=_gce1vdpse0kfqibbkk0sohzn3m2xsu1wbx0bflsr00' try: page = requests.get(producturl) soup = BeautifulSoup(page.content, 'html.parser') #print(soup) try: stock = soup.find('button', {'class':'src-pages-BundleBuilder-components-BundleBuilderHeader-__BundleBuilderHeader-module___checkoutButton w-100 bg-light-green btn btn-primary'}) if 'Out of stock' not in stock.text.strip(): print('-----------------Microsoft: -------' , stock.text.strip()) beep(operatingsystem) elif 'Out of stock' in stock.text.strip(): print('Microsoft: Not in stock.') except Exception: print('Microsoft: String Not found (Probably out of stock).') except Exception: print('Ran into an exception in Microsoft. Likely a request error.') except KeyboardInterrupt: print('Quitting...') quit() def PopFindrBestBuy(operatingsystem): producturl = 'https://popfindr.com/results?pid=6428324&zip=28348&range=25&webpage=bestbuy&token=<KEY>' try: page = requests.get(producturl) soup = BeautifulSoup(page.content, 'html.parser') try: tables = soup.find_all('table')[1] row = tables.find_all('tr')[1] cell = row.find_all('th')[2] inventory = cell.text.strip() if inventory == '0': print(f'Best Buy has {inventory}.') elif inventory != '0': print(f'---------------Best Buy has {inventory} IN STOCK!') beep(operatingsystem) except Exception: print('Best Buy: String Not found (Probably out of stock) but maybe not?!') except Exception: print('Ran into an exception in PopFindr Best Buy. Likely a request error.') except KeyboardInterrupt: print('Quitting...') quit() if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python3 ''' Summary: Connects to multiple hosts and uploads a file Decription: This uses the hosts.txt file to connect to multiple ESXi hosts and copy the sshd_onfig file. This is used for STIG compliance. The sshd_config and hosts.txt file should be in the same directory as this python script. ''' ''' Importing built-in modules ''' import getpass import csv ''' Importing external modules ''' import paramiko __author__ = "<NAME>" __version__ = "1.0.0" __email__ = "<EMAIL>" __status__ = "Production" def main(): file = 'sshd_config' mypassword = getpass.getpass("Enter password: ") with open('hosts.txt','r') as infile: reader = csv.reader(infile) hosts = {rows[0] for rows in reader} for host in hosts: try: print(f'Connecting to {host}') s = paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(host,22,username='root',password=<PASSWORD>,timeout=4) sftp = s.open_sftp() sftp.put(file, f'/etc/ssh/{file}') except Exception: # Yeah this is ugly but it'll work pass if __name__ == '__main__': main() <file_sep>#!/usr/local/bin/python3 """ Summary: A sample application showing how beautifulsoup can be leveraged in real-world applications. This specific script searches Indeed for a job. Usage: indeed.py [-h] [-j job] [-s state] Searches Indeed for a job in a state. optional arguments: -h, --help show this help message and exit -j job, --job job What job to look for. If using a space "double quotes" must be used. -s state, --state state Where to look (MUST USE A 2 LETTER STATE CODE) Requirements: beautifulsoup, tabulate """ from tabulate import tabulate import requests import argparse import math from bs4 import BeautifulSoup def main(): parser = argparse.ArgumentParser(description='Searches Indeed for a job in a state.', \ formatter_class=argparse.RawTextHelpFormatter) parser.add_argument( '-j', '--job', action='store', metavar='job', required=False, help='What job to look for. If using a space "double quotes" must be used.' ) parser.add_argument( '-s', '--state', action='store', metavar='state', required=False, help='Where to look (MUST USE A 2 LETTER STATE CODE)' ) args = parser.parse_args() # Fix any spaces in the job search args.job = args.job.replace(' ','+') url = f'https://www.indeed.com/jobs?q={args.job}&l={args.state}&start=' # First we have to get the total number of jobs, and coorelate them to the number of # pages to search through. page = requests.get(url+str('0')) soup = BeautifulSoup(page.content, 'html.parser') result = soup.find('div', attrs={'id': 'searchCountPages'}) pages = result.text.strip() splitsentence = pages.split() totaljobs = splitsentence[3] #print(totalpages) # Lose the comma if there are greater than 1000 pages totaljobs = totaljobs.replace(',','') # We have the total jobs, get the total pages to search through, in sections of 10 pages = round(int(totaljobs) / int(10)) jobs = [] # Ugly way to do this but its quick jobheaders = ['Company','Job Title','Location'] jobs.append(jobheaders) print('\n' *2 ) # Go through all the search results, 10 at a time and pull out the data for i in range(0, pages, 10): posturl = 'url' + str(i) page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') results = soup.find_all('div', attrs={'class': 'jobsearch-SerpJobCard'}) for x in results: try: company = x.find('span', attrs={"class":"company"}) #print('Company:', company.text.strip()) job = x.find('a', attrs={'data-tn-element': "jobTitle"}) #print('Job:', job.text.strip()) location = x.find('span', attrs={"class":"location accessible-contrast-color-location"}) #print('Location:' , location.text.strip()) #print('\n') result = [company.text.strip(),job.text.strip(),location.text.strip()] jobs.append(result) except AttributeError: pass print('Found' , len(jobs) , 'matching jobs!') print('\n') print(tabulate(jobs, tablefmt="grid",)) print('\n') if __name__ == "__main__": main() <file_sep># Misc Various scripts I've written in the past for various things. <file_sep>#!/usr/local/bin/python3 """ Summary: Checks for a reservation at the Angus Barn on a very specific date and time. """ import requests import re from bs4 import BeautifulSoup import time from datetime import datetime import winsound import platform import smtplib, ssl import getpass def sendmail(password): port = 465 # For SSL smtp_server = "smtp.gmail.com" sender_email = "@<EMAIL>.com" # Enter your address receiver_email = "@gmail.com" # Enter receiver address #password = getpass("Type your password and press enter: ") #password = '' message = f"""From: {sender_email} To: {receiver_email} SUBJECT: An angus barn appointment is available\n This message is sent from Python. """ context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message) def steak(operatingsystem, password): reservationdate = "05/22/2021" partysize = "5" reservationhour = "06" # I'm not messing w/the minute. #payload = 'authenticity_token=<KEY>&reservation%5Bdate%5D=05/22/2021&reservation%5Bparty_size%5D=5&reservation%5Btime%5D=06%3A00%20PM&reservation%5Bwidget_id%5D=72&utf8=%u2713' url = "http://widgets.espconnects.com/reservations/check.js" payload = f'authenticity_token=<KEY>&reservation%5Bdate%5D={reservationdate}&reservation%5Bparty_size%5D={partysize}&reservation%5Btime%5D={reservationhour}%3A00%20PM&reservation%5Bwidget_id%5D=72&utf8=%u2713' headers = { 'Accept': 'text/html, */*; q=0.01', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded', } now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time: ", current_time) try: response = requests.request("POST", url, headers=headers, data = payload) #print(response.text.encode('utf8')) except: print('Pausing due to requests error') time.sleep(60) # Parse the output for the times available try: soup = BeautifulSoup(response.content, 'html.parser') stock = soup.findAll('button', class_="button button3") print(f'These times are available on {reservationdate}:') for i in stock: print(i.text.strip()) available = str(i.text.strip()) if ('09' in available) or ('05' in available) or ('06' in available) or ('06' in available): print('BOOK NOW!!' *5) sendmail(password) beep(operatingsystem) except Exception: print('Ran into an exception in parsing the data') except KeyboardInterrupt: print('Quitting...') quit() print('Sleeping for 120 seconds.') print('' *3) def getplatform(): try: plt = platform.system() if plt == "Windows": print("Your system is Windows") operatingsystem = "Windows" elif plt == "Linux": print("Your system is Linux") operatingsystem = "Linux" elif plt == "Darwin": print("Your system is MacOS") operatingsystem = "Mac" else: #print("Unidentified system") operatingsystem='Linux' return operatingsystem except Exception: print('error in getting OS information.') quit() except KeyboardInterrupt: quit() def beep(operatingsystem): if operatingsystem == 'Linux': duration = 20 # seconds freq = 440 # Hz os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq)) if operatingsystem =='Windows': print('beeping windows!') for i in range(1,50): winsound.PlaySound("SystemAsterisk", winsound.SND_ALIAS) def main(): password = <PASSWORD>(prompt='GMail sender password: ') operatingsystem = getplatform() while True: try: steak(operatingsystem, password) time.sleep(120) except Exception: print('Ran into an exception in check function. Pausing for 60 seconds.') time.sleep(60) except KeyboardInterrupt: print('Quitting...') quit() if __name__ == "__main__": main()
738a9cfd4636a5cc011d67ec917bfac94b3d4959
[ "Markdown", "Python" ]
5
Python
willyd61/Misc
e22a7fe03b13ca0d23ef7b99e2aac2f67ea7ef4e
1cd3f23f28effca37b025194804784c6911970b4
refs/heads/master
<repo_name>PanoramaTwelve/SelfTriggerDocker<file_sep>/src/test_script.py """ A simple selenium test example written by python """ import unittest import time import os from selenium import webdriver from selenium.webdriver import ActionChains from selenium.common.exceptions import NoSuchElementException class TestTemplate(unittest.TestCase): """Include test cases on a given url""" def setUp(self): """Start web driver""" chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--no-sandbox') #chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') self.driver = webdriver.Chrome(options=chrome_options) self.driver.implicitly_wait(10) def tearDown(self): """Stop web driver""" self.driver.quit() def test_case_1(self): """Login and play arbitrary playlist""" try: self.driver.get('https://accounts.spotify.com/de/login/') self.driver.save_screenshot('./01_login.png') input_username = self.driver.find_element_by_name('username') input_username.send_keys(os.environ['LOGIN_MINE_USERNAME']) input_password = self.driver.find_element_by_name('password') input_password.send_keys(os.environ['LOGIN_MINE_PW']) time.sleep(2) print("Logging in") self.driver.save_screenshot('./02_user_data.png') login_button = self.driver.find_element_by_id('login-button') login_button.click() time.sleep(2) print("Logged in") self.driver.save_screenshot('./03_logged_in.png') self.driver.get('https://open.spotify.com/album/2auiRkQwGGHkVaWTjchszO?si=cvqQ0RxTTJuRi3twtDvq-w') # just some test playlist time.sleep(3) print("Opening Playlist and Clicking Top Play Button") self.driver.save_screenshot('./04_playlist.png') ##play_button = self.driver.find_element_by_xpath("//button[@aria-label='Play']") #play_button = self.driver.find_element_by_xpath("//button[@data-testid='play-button']") #action = ActionChains(self.driver) #action.move_to_element(play_button).perform() #action.click(play_button).perform() play_button_bottom = self.driver.find_element_by_xpath("//button[@data-testid='control-button-play']") action = ActionChains(self.driver) action.move_to_element(play_button_bottom).perform() action.click(play_button_bottom).perform() time.sleep(2) print("Listening") self.driver.save_screenshot('./05_listening.png') time.sleep(2) self.driver.save_screenshot('./06_check_running_01.png') time.sleep(2) self.driver.save_screenshot('./06_check_running_02.png') time.sleep(2) self.driver.save_screenshot('./06_check_running_03.png') time.sleep(2) self.driver.save_screenshot('./06_check_running_04.png') print("That was nice") time.sleep(2) self.driver.get('https://accounts.spotify.com/de/logout/') self.driver.save_screenshot('./07_logout.png') time.sleep(2) except NoSuchElementException as ex: self.fail(ex.msg) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestTemplate) unittest.TextTestRunner(verbosity=2).run(suite) <file_sep>/scripts/execute_automation.sh #!/bin/bash pip3 install selenium apt-get install -y xvfb xvfb-run python3 ./src/test_script.py
181eeabecd3103befe20ddfb64feb70fa625a83b
[ "Python", "Shell" ]
2
Python
PanoramaTwelve/SelfTriggerDocker
3ccf5fa2184ec0b28ab8e551b0cdddf952ce69aa
7db7d6ad8dabc277f2266dcc2b6ec2c3d165e58e
refs/heads/master
<file_sep>import nltk # 通常用在英文 # nltk.download() 超大天荒地老 import numpy as np import pandas as pd # standfordNLP import stanfordnlp # stanfordnlp.download('en') # stanfordnlp.download('zh') import os from pathlib import Path from ckiptagger import data_utils path = os.path.join(str(Path.home()), 'ckip/') if not os.path.exists(path): os.mkdir(path) data_utils.download_data_gdown(path) # gdrive-ckip2GB from stanfordnlp.utils.resources import DEFAULT_MODEL_DIR chinese_sentence = '中華郵政未來智慧物流服務,將取之大眾智慧,帶給民眾更好的便利生活' zh_pipeline = stanfordnlp.Pipeline(processors="tokenize", models_dir=DEFAULT_MODEL_DIR, lang="zh", use_gpu=False) zh_doc = zh_pipeline(chinese_sentence) for i,sentence in enumerate(zh_doc.sentences): print("sentence {}:".format(i)) print("index\ttxt") for word in sentence.words: print("{}\t{}".format(word.index,word.text)) print("iihdsidihdsio")
1c52ea57bf453692e0028a2246dee5fb094a4853
[ "Python" ]
1
Python
QmoG0726/practice-git
37431b74715ec6233fe8a7036021c4d40693d4f6
d621c1856baf63c9c7be40daac06917175abbe79
refs/heads/master
<repo_name>xxl534/CardProject<file_sep>/Assets/Scripts/RarityColorStatic.cs using UnityEngine; using System.Collections; public static class RarityColorStatic { public static Color[] rarityColors; public static Color normal ; public static Color rare; public static Color precious; public static Color legendary; public static Color epic ; static RarityColorStatic() { normal = new Color (0.53f,0.53f,0.53f); rare= new Color (0.177f,1f,0.345f); precious = new Color (0.169f,0.38f,1f); legendary = new Color (0.718f,0.247f,0.88f); epic = new Color (1f,0.518f,0f); rarityColors = new Color[]{normal,rare,precious,legendary,epic}; } } <file_sep>/Assets/Scripts/Card/BaseCard.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Reflection; /// <summary> /// Each base card is a data type of a role.Concrete cards which represent one role are generated from the same base card. /// Each base card has a set of base attributes and abilities. /// Value of concrete card's attributes are result from relative base card and card level. /// The value of instance member with postfix "Base" is attribute's value of concrete card with level 0. /// </summary> public class BaseCard { #region Static member private static float _rate_strength_maxHealth,_rate_strength_physicalDefense,_rate_strength_physicalDamage,_rate_strength_healthResilience, _rate_agility_physicalDefense,_rate_agility_physicalCriticalChance,_rate_agility_evasion, _rate_magic_maxMana,_rate_magic_magicalDefense,_rate_magic_magicalCriticalChance,_rate_magic_magicalDamage,_rate_magic_magicResilience; public static List<int> _maxLevelTable; public static List<int> _experienceTable; #endregion #region Instance member private int _id; private string _cardSprite; private int _strengthBase;private float _strengthGrowth; private int _agilityBase;private float _agilityGrowth; private int _magicBase;private float _magicGrowth; private int _maxHealthBase, _maxManaBase, _physicalDefenseBase, _magicalDefenseBase, _physicalCriticalChanceBase, _magicalCriticalChanceBase, _physicalDamageBase, _magicalDamageBase, _healthResilienceBase, _magicResilienceBase, _evasionBase, _price; private float _drapRate; private Rarity _cardRarity; private string _name; private string _description; public List<int> _abilitiesId; #endregion #region Properties static member //static properties public static float rate_strength_maxHealth { get{return _rate_strength_maxHealth;} private set{ if(value<0f) { Debug.Log("Static attribute rate_strength_maxHealth should not be negative"); throw new ArgumentException("Static attribute rate_strength_maxHealth should not be negative"); } _rate_strength_maxHealth=value; } } public static float rate_strength_physicalDefense { get{return _rate_strength_physicalDefense;} private set{ if(value<0f) { Debug.Log("Static attribute rate_strength_physicalDefense should not be negative"); throw new ArgumentException("Static attribute rate_strength_physicalDefense should not be negative"); } _rate_strength_physicalDefense=value; } } public static float rate_strength_physicalDamage { get{return _rate_strength_physicalDamage;} private set{ if(value<0f) { Debug.Log("Static attribute rate_strength_physicalDamage should not be negative"); throw new ArgumentException("Static attribute rate_strength_physicalDamage should not be negative"); } _rate_strength_physicalDamage=value; } } public static float rate_strength_healthResilience { get{return _rate_strength_healthResilience;} private set{ if(value<0f) { Debug.Log("Static attribute rate_strength_healthResilience should not be negative"); throw new ArgumentException("Static attribute rate_strength_healthResilience should not be negative"); } _rate_strength_healthResilience=value; } } public static float rate_agility_physicalDefense { get{return _rate_agility_physicalDefense;} private set{ if(value<0f) { Debug.Log("Static attribute rate_agility_physicalDefense should not be negative"); throw new ArgumentException("Static attribute rate_agility_physicalDefense should not be negative"); } _rate_agility_physicalDefense=value; } } public static float rate_agility_physicalCriticalChance { get{return _rate_agility_physicalCriticalChance;} private set{ if(value<0f) { Debug.Log("Static attribute rate_agility_physicalCriticalChance should not be negative"); throw new ArgumentException("Static attribute rate_agility_physicalCriticalChance should not be negative"); } _rate_agility_physicalCriticalChance=value; } } public static float rate_agility_evasion { get{return _rate_agility_evasion;} private set{ if(value<0f) { Debug.Log("Static attribute rate_agility_evasion should not be negative"); throw new ArgumentException("Static attribute rate_agility_evasion should not be negative"); } _rate_agility_evasion=value; } } public static float rate_magic_maxMana { get{return _rate_magic_maxMana;} private set{ if(value<0f) { Debug.Log("Static attribute rate_magic_maxMana should not be negative"); throw new ArgumentException("Static attribute rate_magic_maxMana should not be negative"); } _rate_magic_maxMana=value; } } public static float rate_magic_magicalDefense { get{return _rate_magic_magicalDefense;} private set{ if(value<0f) { Debug.Log("Static attribute rate_magic_magicalDefense should not be negative"); throw new ArgumentException("Static attribute rate_magic_magicalDefense should not be negative"); } _rate_magic_magicalDefense=value; } } public static float rate_magic_magicalCriticalChance { get{return _rate_magic_magicalCriticalChance;} private set{ if(value<0f) { Debug.Log("Static attribute rate_magic_magicalCriticalChance should not be negative"); throw new ArgumentException("Static attribute rate_magic_magicalCriticalChance should not be negative"); } _rate_magic_magicalCriticalChance=value; } } public static float rate_magic_magicalDamage { get{return _rate_magic_magicalDamage;} private set{ if(value<0f) { Debug.Log("Static attribute rate_magic_magicalDamage should not be negative"); throw new ArgumentException("Static attribute rate_magic_magicalDamage should not be negative"); } _rate_magic_magicalDamage=value; } } public static float rate_magic_magicResilience { get{return _rate_magic_magicResilience;} private set{ if(value<0f) { Debug.Log("Static attribute rate_magic_magicResilience should not be negative"); throw new ArgumentException("Static attribute rate_magic_magicResilience should not be negative"); } _rate_magic_magicResilience=value; } } /// <summary> /// maxLevelTable has same number item as Enum Rarity does /// It should be sorted /// </summary> /// <value>The max level table.</value> public static List<object> maxLevelTable { get{return _maxLevelTable.ConvertAll(x=>(object)x);} private set{ _maxLevelTable=value.ConvertAll(x=>System.Convert.ToInt32(x)); if(_maxLevelTable.Count!=Enum.GetValues(typeof(Rarity)).Length) { Debug.Log("maxLevelTable count error"); throw new System.ArgumentException("maxLevelTable count error"); } if(!IsIntListSorted(_maxLevelTable)) { Debug.Log("maxLevelTable item sequence error"); throw new System.ArgumentException("maxLevelTable item sequence error"); } } } /// <summary> /// ExperienceTable should be consistent with the max maxLevel and be sorted. /// </summary> /// <value>The experience table.</value> public static List<object> experienceTable { get{return _experienceTable.ConvertAll(x=>(object)x);} private set{ _experienceTable=value.ConvertAll(x=>System.Convert.ToInt32(x)); if(!IsIntListSorted(_experienceTable)) { Debug.Log("ExperienceTable item sequence error"); throw new System.ArgumentException("ExperienceTable item sequence error"); } } } #endregion #region Properties instance member //member properties public int id { get{return _id;} private set{ if(value<=0) { Debug.Log("Attribute id should not be negative"); throw new ArgumentException("Attribute id should not be negative"); } _id=value;} } public string cardSprite { get{return _cardSprite;} set{ _cardSprite=value; } } // public string backgroundSprite // { // get{return _backgroundSprite;} // private set{ // _backgroundSprite=value; // } // } public int strengthBase { get{return _strengthBase;} private set{ if(value<0) { Debug.Log("Attribute strengthBase should not be negative"); throw new ArgumentException("Attribute strengthBase should not be negative"); } _strengthBase=value;} } public float strengthGrowth { get{return _strengthGrowth;} private set{ if(value<0) { Debug.Log("Attribute strengthGrowth should not be negative"); throw new ArgumentException("Attribute strengthGrowth should not be negative"); } _strengthGrowth=value;} } public int agilityBase { get{return _agilityBase;} private set{ if(value<0) { Debug.Log("Attribute agilityBase should not be negative"); throw new ArgumentException("Attribute agilityBase should not be negative"); } _agilityBase=value;} } public float agilityGrowth { get{return _agilityGrowth;} private set{ if(value<0) { Debug.Log("Attribute agilityGrowth should not be negative"); throw new ArgumentException("Attribute agilityGrowth should not be negative"); } _agilityGrowth=value;} } public int magicBase { get{return _magicBase;} private set{ if(value<0) { Debug.Log("Attribute magicBase should not be negative"); throw new ArgumentException("Attribute magicBase should not be negative"); } _magicBase=value;} } public float magicGrowth { get{return _magicGrowth;} private set{ if(value<0) { Debug.Log("Attribute magicGrowth should not be negative"); throw new ArgumentException("Attribute magicGrowth should not be negative"); } _magicGrowth=value;} } public int maxHealthBase { get{return _maxHealthBase;} private set{ if(value<0) { Debug.Log("Attribute maxHealthBase should not be negative"); throw new ArgumentException("Attribute maxHealthBase should not be negative"); } _maxHealthBase=value;} } public int maxManaBase { get{return _maxManaBase;} private set{ if(value<0) { Debug.Log("Attribute maxManaBase should not be negative"); throw new ArgumentException("Attribute maxManaBase should not be negative"); } _maxManaBase=value;} } public int physicalDefenseBase { get{return _physicalDefenseBase;} private set{ // if(value<0) // { // Debug.Log("Attribute physicalDefenseBase should not be negative"); // throw new ArgumentException("Attribute physicalDefenseBase should not be negative"); // } _physicalDefenseBase=value;} } public int magicalDefenseBase { get{return _magicalDefenseBase;} private set{ // if(value<0) // { // Debug.Log("Attribute magicalDefenseBase should not be negative"); // throw new ArgumentException("Attribute magicalDefenseBase should not be negative"); // } _magicalDefenseBase=value;} } public int physicalCriticalChanceBase { get{return _physicalCriticalChanceBase;} set{_physicalCriticalChanceBase=value;} } public int magicalCriticalChanceBase { get{return _magicalCriticalChanceBase;} set{_magicalCriticalChanceBase=value;} } public int physicalDamageBase { get{return _physicalDamageBase;} private set{ if(value<0) { Debug.Log("Attribute physicalDamageBase should not be negative"); throw new ArgumentException("Attribute physicalDamageBase should not be negative"); } _physicalDamageBase=value;} } public int magicalDamageBase { get{return _magicalDamageBase;} private set{ if(value<0) { Debug.Log("Attribute magicalDamageBase should not be negative"); throw new ArgumentException("Attribute magicalDamageBase should not be negative"); } _magicalDamageBase=value;} } public int healthResilienceBase { get{return _healthResilienceBase;} private set{ if(value<0) { Debug.Log("Attribute healthResilienceBase should not be negative"); throw new ArgumentException("Attribute healthResilienceBase should not be negative"); } _healthResilienceBase=value;} } public int magicResilienceBase { get{return _magicResilienceBase;} private set{ if(value<0) { Debug.Log("Attribute magicResilienceBase should not be negative"); throw new ArgumentException("Attribute magicResilienceBase should not be negative"); } _magicResilienceBase=value;} } public int evasionBase { get{return _evasionBase;} private set{ // if(value<0) // { // Debug.Log("Attribute evasionBase should not be negative"); // throw new ArgumentException("Attribute evasionBase should not be negative"); // } _evasionBase=value;} } public float drapRate { get{return _drapRate;} private set{ if(value<0) { Debug.Log("Attribute drapRate should not be negative"); throw new ArgumentException("Attribute drapRate should not be negative"); } _drapRate=value;} } public int price { get{return _price;} private set{ if(value<0) { Debug.Log("Attribute price should not be negative"); throw new ArgumentException("Attribute price should not be negative"); } _price=value;} } public Rarity rarity { get{return _cardRarity;} private set{ _cardRarity=value; } } public string name { get{return _name;} } public string description { get{return _description;} set{_description=value;} } public List<object> abilitiesId { // get{return _abilitiesId;} set{_abilitiesId=value.ConvertAll(x=>System.Convert.ToInt32(x));} } #endregion private BaseCard() {} public static BaseCard GeneBaseCard(KeyValuePair<string,Dictionary<string,object>> cardInfo) { BaseCard baseCard=new BaseCard(); baseCard._name=cardInfo.Key; Type type=typeof(BaseCard); Dictionary<string,object> cardAttr=cardInfo.Value; foreach(string attribute in cardAttr.Keys) { PropertyInfo propertyInfo= type.GetProperty(attribute); if(propertyInfo==null) { Debug.Log(string.Format("Illegal field:Card attribute '{0}' does not exist",attribute)); throw new System.Exception(string.Format("Illegal field:Card attribute '{0}' does not exist",attribute)); } object valueOb=cardAttr[attribute]; if(propertyInfo.PropertyType.IsEnum) { try{ System.Convert.ToInt32(valueOb); }catch{ valueOb= Enum.Parse(propertyInfo.PropertyType,(string)valueOb); } if(!Enum.IsDefined(propertyInfo.PropertyType,valueOb)) { Debug.Log(string.Format("Illegal {0} value :{1}" ,propertyInfo.PropertyType,valueOb)); throw new System.ArgumentException(string.Format("Illegal {0} value :{1}" ,propertyInfo.PropertyType,valueOb)); } } if(valueOb.GetType()!=propertyInfo.PropertyType) { valueOb=System.Convert.ChangeType(valueOb,propertyInfo.PropertyType); } propertyInfo.SetValue(baseCard,valueOb,null); } if(!baseCard.CheckInstanceFields()) { throw new System.ArgumentException(string.Format("The card data is deficient in card that named:{0}",baseCard.name)); } return baseCard; } public static void LoadStaticFields(Dictionary<string,object> staticFields) { Type type=typeof(BaseCard); foreach(string attribute in staticFields.Keys) { PropertyInfo propertyInfo= type.GetProperty(attribute,BindingFlags.Static|BindingFlags.Public); if(propertyInfo==null) { Debug.Log(string.Format("Illegal static field:Card static attribute '{0}' does not exist",attribute)); throw new System.FieldAccessException(string.Format("Illegal static field:Card static attribute '{0}' does not exist",attribute)); } object valueOb=staticFields[attribute]; // Debug.Log("property name:"+propertyInfo.Name+";property type:"+propertyInfo.PropertyType); // Debug.Log(valueOb.GetType()); if(valueOb.GetType()!=propertyInfo.PropertyType) { valueOb= System.Convert.ChangeType(valueOb,propertyInfo.PropertyType); } propertyInfo.SetValue(null,valueOb,null); } } public static bool CheckStaticFields() { bool bPass=true; foreach(PropertyInfo propertyInfo in typeof(BaseCard).GetProperties(BindingFlags.Static|BindingFlags.Public)) { // Debug.Log(propertyInfo.Name+":"+propertyInfo.GetValue(null,null)); if(propertyInfo.PropertyType==typeof(float)) { if(propertyInfo.GetValue(null,null)==(object)0f){ Debug.Log(string.Format("lack of static field: '{0}'",propertyInfo.Name)); bPass=false; } } } if(_maxLevelTable==null) { Debug.Log("lack of static field: maxLevelTable"); bPass=false; } if(_experienceTable==null) { Debug.Log("lack of static field: experienceTable"); bPass=false; } if(_maxLevelTable!=null&&_experienceTable!=null) { if(_experienceTable.Count!=_maxLevelTable[_maxLevelTable.Count-1]) { Debug.Log("experienceTable and maxLevelTable are not consistent"); bPass=false; } } return bPass; } bool CheckInstanceFields() { bool bPass=true; if(_id<=0){ Debug.Log("Lack of id data"); bPass=false; } return bPass; } static bool IsIntListSorted(List<int> intList) { bool bPass=true; for(int i=1;i!=intList.Count;i++) { if(intList[i-1]>intList[i]) bPass=false; } return bPass; } } <file_sep>/Assets/Scripts/ResourcesFolderPath.cs using UnityEngine; using System.Collections; public static class ResourcesFolderPath { public static string json_ability="Json/Ability"; public static string json_card="Json/Card"; public static string json_player="Json/Player"; public static string json_level="Json/Level"; public static string textures_role="Textures/Card"; public static string textures_background="Textures/Background"; public static string textures_ability_icon="Textures/Ability/Icon"; public static string prefabs_ability="Prefabs/Ability"; } <file_sep>/Assets/CompleteSlot.cs using UnityEngine; using System.Collections; public class CompleteSlot : MonoBehaviour { private static float _expIncDuration=3.0f; public UISprite _cardIcon; public UILabel _cardName, _cardLevelLabel, _experienceLabel; public UISlider _experienceSlider; public ConcreteCard _card; private int _level,_experience,_expUpBound; public bool vacant { get; set;} public void LoadConcreteCard(ConcreteCard concreteCard) { vacant = false; _card = concreteCard; _cardIcon.spriteName = concreteCard.name; _cardName .text= concreteCard.name; _level = concreteCard.level; _cardLevelLabel.text = "lv." + _level.ToString (); _experience = concreteCard.experience; _expUpBound=BaseCard._experienceTable[concreteCard.level-1]; _experienceSlider.value = _experience / (float)_expUpBound; _experienceLabel.text = _experience.ToString () + "/" + _expUpBound.ToString (); gameObject.SetActive (true); } public void GainExperience(int experience) { _card.experience += experience; StartCoroutine (GainExperienceDynamic (experience, _expIncDuration)); } IEnumerator GainExperienceDynamic(int experience,float duration) { float fExp = (float)_experience; float perSecond = experience / duration; int dstLevel = _card.level, dstExp = _card.experience; while (_level<dstLevel||_experience<dstExp) { fExp += perSecond*Time.deltaTime; _experience=(int)fExp; if (_experience >= _expUpBound) { while (_level<dstLevel) { _level++; _experience-=_expUpBound; fExp-=(float)_expUpBound; _expUpBound=BaseCard._experienceTable[_level-1]; } } _cardLevelLabel.text = "lv." + _level.ToString (); _experienceSlider.value = _experience / (float)_expUpBound; _experienceLabel.text = _experience.ToString () + "/" + _expUpBound.ToString (); yield return null; } if (_experience > dstExp) { _experience=dstExp; } _cardLevelLabel.text = "lv." + _level.ToString (); _experienceSlider.value = _experience / (float)_expUpBound; _experienceLabel.text = _experience.ToString () + "/" + _expUpBound.ToString (); yield return null; } public void GainExperienceInstant() { StopCoroutine ("GainExperienceDynamic"); _level=_card .level; _experience=_card.experience; _expUpBound=BaseCard._experienceTable[_level-1]; _cardLevelLabel.text = "lv." + _level.ToString (); _experienceSlider.value = _experience / (float)_expUpBound; _experienceLabel.text = _experience.ToString () + "/" + _expUpBound.ToString (); } } <file_sep>/Abandon/0827/CardData.cs using UnityEngine; using System.Collections; public class CardData { } <file_sep>/Assets/Scripts/Card/Abitity/AbilityType.cs using UnityEngine; using System.Collections; /// <summary> /// Ability type. /// Option:Physical,Magical. /// </summary> public enum AbilityType { Physical,Magical }; <file_sep>/Abandon/0827/InstantAbilityBase.cs using UnityEngine; using System.Collections; /// <summary> ///This kind of abliity directly affect the targer,like take damage,weaken defense. /// </summary> public class InstantAbilityBase : AbstractAbilityBase{ protected IAbilityEffect ablityEffect; public override object CastAbility(ConcreteCard from,ConcreteCard to) { ablityEffect.AbilityEffect(from,to,this); return null; } } <file_sep>/Assets/Scripts/Level/LevelData.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Reflection; public class LevelData { private int _level,_experience,_enemiesAbilityLevel; private List<int> _enemiesId,_bossIndices,_dropCards,_dropRates; private Rarity _enemiesRarity; private string _background; public int level { get{return _level;} private set{ _level=value; } } public int experience { get{return _experience;} private set{_experience=value;} } public int enemiesAbilityLevel { get{return _enemiesAbilityLevel;} private set{_enemiesAbilityLevel=value;} } public string background { get{return _background;} private set{_background=value;} } public List<int> enemiesId { get{return _enemiesId;} } private List<object> enemies { set{_enemiesId=value.ConvertAll(x=>System.Convert.ToInt32(x));} } public List<int> dropCards { get{return _dropCards;} } private List<object> dropCard { set{_dropCards=value.ConvertAll(x=>System.Convert.ToInt32(x));} } public List<int> dropRates { get{return _dropRates;} } private List<object> dropRate { set{_dropRates=value.ConvertAll(x=>System.Convert.ToInt32(x));} } public List<int> bossIndices { get{return _bossIndices;} } private List<object> bosses { set{_bossIndices=value.ConvertAll(x=>System.Convert.ToInt32(x));} } public Rarity enemiesRarity { get{return _enemiesRarity;} private set{_enemiesRarity=value;} } private LevelData() {} public static LevelData GetLevelData(Dictionary<string,object> data) { LevelData levelData=new LevelData(); Type type=typeof(LevelData); foreach(string attribute in data.Keys) { PropertyInfo propertyInfo= type.GetProperty(attribute,BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance); if(propertyInfo==null) { Debug.Log(string.Format("Illegal property in Level : '{0}'",attribute)); throw new System.Exception(string.Format("Illegal property in Level : '{0}'",attribute)); } object valueOb=data[attribute]; if(propertyInfo.PropertyType.IsEnum) { try{ System.Convert.ToInt32(valueOb); }catch{ valueOb= Enum.Parse(propertyInfo.PropertyType,(string)valueOb); } if(!Enum.IsDefined(propertyInfo.PropertyType,valueOb)) { Debug.Log(string.Format("Illegal {0} value :{1}" ,propertyInfo.PropertyType,valueOb)); throw new System.ArgumentException(string.Format("Illegal {0} value :{1}" ,propertyInfo.PropertyType,valueOb)); } } if(valueOb.GetType()!=propertyInfo.PropertyType) { valueOb=System.Convert.ChangeType(valueOb,propertyInfo.PropertyType); } propertyInfo.SetValue(levelData,valueOb,null); } if (!levelData.CheckFields ()) { Debug.Log("Failing to pass fields test"); throw new System.Exception("Failing to pass fields test"); } return levelData; } bool CheckFields() { bool bPass = true; if (_level <= 0) { Debug.Log("Level should be positive"); bPass=false; } if (_experience <= 0) { Debug.Log("Experience should be positive"); bPass=false; } if (_enemiesId == null) { Debug.Log("EnemiesId list should not be null"); bPass=false; } if (_bossIndices == null) { Debug.Log ("BossIndices list should not be null"); bPass = false; } return bPass; } } <file_sep>/Assets/Scripts/Card/Abitity/DotAndHot.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class DotAndHot :DurativeState { protected bool _isDot; public bool isDot { get{return _isDot;} } public int interval { get{return _interval;} set{_interval =value;} } public int duration { get{return _duration;} set{_duration=value; } } public int id { get{return _id;} set{_id=value;} } public DotAndHot(int id,string name,bool isDot,BattleCard from,BattleCard to, AbilityType abilityType,int interval,int duration) { this.id = id; _name=name; _isDot=isDot; _castCard = from; _targetCard = to; _abilityType = abilityType; _interval = interval; _duration = duration; _roundCounter = 0; } public override void RoundStart () { _roundCounter++; } public override void RoundEnd () { if (_roundCounter == interval) { _roundCounter=0; effectCard(this); } duration--; } public override void Clear() {} } <file_sep>/Abandon/0827/DurativeAbilityBase.cs using UnityEngine; using System.Collections; public class DurativeAbilityBase : AbstractAbilityBase { protected int _effectInterval; protected int _duration; public override object CastAbility(ConcreteCard from,ConcreteCard to) { return DurativeAbilityMonitor(from,to); } public object DurativeAbilityMonitor(ConcreteCard from,ConcreteCard to) { return null; } } <file_sep>/Assets/Scripts/Tools/Administrator.cs using UnityEngine; using System.Collections; public class Administrator : MonoBehaviour { // public GameObject scripts; public string addScriptName; public string removeScriptName; [ContextMenu("Add Scripts")] void AddComponents() { System.Type T = System.Type.GetType (addScriptName); UIWidget[] childUI = GetComponentsInChildren<UIWidget> (); foreach (UIWidget widget in childUI) { widget.pivot= UIWidget.Pivot.TopLeft; if(widget.gameObject.GetComponent(T)==null) widget.gameObject.AddComponent(T); } } [ContextMenu("Remove Scripts")] void RemoveComponents() { Component com; System.Type T = System.Type.GetType (removeScriptName); UIWidget[] childUI = GetComponentsInChildren<UIWidget> (); foreach (UIWidget widget in childUI) { if((com=widget.gameObject.GetComponent(T))!=null) DestroyImmediate(com); } } } <file_sep>/Assets/test.cs using System; using System.Reflection; using UnityEngine; using System.Collections.Generic; using System.Collections; public class Test:MonoBehaviour { bool b=false; void Start() { CardFactory cf=CardFactory.GetCardFactory(); // Int64 i=1; // int l=System.Convert.ToInt32(i); // typeof(C1).GetProperty("si").SetValue(null,l,null); } // void Update() // { // if(!b) // { // b=true; // Debug .Log(Time.time); // // } // else // StartCoroutine("T"); // } // IEnumerator T() // { // Debug.Log(Time.time); // yield return null; // } } public enum E1 { e1,e2,e3 }; public class C1 { public C1(){} public C1(int i) { typeof(C1).GetProperty("e").SetValue(this,i,null); } static int _si; E1 _e; int[] _i; public int[] i { get{return _i;} set{_i=value;} } public static int si { get{return _si;} set{_si=value;} } public E1 e { get; private set; } }<file_sep>/Assets/Editor/ImspectorEditor_LevelsEditor.cs using UnityEngine; using System.Collections; using UnityEditor; [CustomEditor(typeof(LevelsEditor))] public class ImspectorEditor_LevelsEditor : Editor { int selectValue = 0; public override void OnInspectorGUI () { LevelsEditor myLeverlEditor = (LevelsEditor)target ; if (GUILayout.Button ("Create a map layer")) { myLeverlEditor.GeneNewMapLayer(); } int mapLayerCount = myLeverlEditor.mapLayers.Count; string[] displayOptions = new string[mapLayerCount]; int[] mapLayerIndex = new int[mapLayerCount]; for (int i=0; i!=mapLayerCount; i++) { displayOptions [i] = myLeverlEditor.mapLayers [i].name; mapLayerIndex [i] = i; } selectValue = EditorGUILayout.IntPopup (selectValue, displayOptions, mapLayerIndex); EditorGUILayout.LabelField("haha","zhenshide"); } } <file_sep>/Assets/Scripts/CardComparisonDisplayer.cs using UnityEngine; using System.Collections; using System.Reflection; using System.Collections.Generic; using Holoville.HOTween; public class CardComparisonDisplayer : MonoBehaviour { public UIWidget _container_firstAttr, _container_secondAttr, _container_comparison; public UIWidget _container_firstAbility, _container_secondAbility; public UISprite _icon_first, _icon_second; public UILabel _level_first, _level_second; private AbilityDisplayer[] _firstAbilities, _secondAbilities; private UILabel[] _firstAttrs, _secondAttrs, _comparisonAttrs; private PropertyInfo[] _attrs; private UIPanel _panel; private float _fadeDuration = 0.5f; private bool _canClick = false; void Awake () { _panel = GetComponent<UIPanel> (); _firstAttrs = _container_firstAttr.GetComponentsInChildren<UILabel> (); System.Array.Sort<UILabel> (_firstAttrs, (x,y) => { return x.name.CompareTo (y.name);}); _secondAttrs = _container_secondAttr.GetComponentsInChildren<UILabel> (); System.Array.Sort<UILabel> (_secondAttrs, (x,y) => { return x.name.CompareTo (y.name);}); _comparisonAttrs = _container_comparison.GetComponentsInChildren<UILabel> (); System.Array.Sort<UILabel> (_comparisonAttrs, (x,y) => { return x.name.CompareTo (y.name);}); _firstAbilities = _container_firstAbility.GetComponentsInChildren<AbilityDisplayer> (); _secondAbilities = _container_secondAbility.GetComponentsInChildren<AbilityDisplayer> (); System.Comparison<AbilityDisplayer> cmp = delegate(AbilityDisplayer a, AbilityDisplayer b) { int ax, ay, bx, by; ay = System.Convert.ToInt32 (a.transform.localPosition.y * 100); by = System.Convert.ToInt32 (b.transform.localPosition.y * 100); if (ay < by) return 1; if (ay > by) return -1; ax = System.Convert.ToInt32 (a.transform.localPosition.x * 100); bx = System.Convert.ToInt32 (b.transform.localPosition.x * 100); if (ax > bx) return 1; if (ax < bx) return -1; return 0; }; System.Array.Sort<AbilityDisplayer> (_firstAbilities, cmp); System.Array.Sort<AbilityDisplayer> (_secondAbilities, cmp); _attrs = new PropertyInfo[_firstAttrs.Length]; System.Type typeOfCard = typeof(ConcreteCard); for (int i = 0; i < _attrs.Length; i++) { _attrs [i] = typeOfCard.GetProperty (_firstAttrs [i].name); } } void Start () { Clear (); } void OnClick () { if (_canClick) { Hide (); _canClick = false; } } public void DisplayCardComparison (ConcreteCard second, ConcreteCard first=null) { int[] secondAttrValue = new int[_attrs.Length]; int[] firstAttrValue = new int[_attrs.Length]; for (int i = 0; i < _attrs.Length; i++) { secondAttrValue [i] = (int)_attrs [i].GetValue (second, null); } for (int i = 0; i < _attrs.Length; i++) { _secondAttrs [i].text = secondAttrValue [i].ToString (); } _container_secondAttr.gameObject.SetActive (true); if (first != null) { for (int i = 0; i < _attrs.Length; i++) { firstAttrValue [i] = (int)_attrs [i].GetValue (first, null); } for (int i = 0; i < _attrs.Length; i++) { _firstAttrs [i].text = firstAttrValue [i].ToString (); } for (int i = 0; i < _attrs.Length; i++) { UILabel attrLabel = _comparisonAttrs [i]; int valueDelta = secondAttrValue [i] - firstAttrValue [i]; string valueStr = ""; if (valueDelta > 0) { attrLabel.color = Color.green; valueStr += "+"; } else if (valueDelta < 0) { attrLabel.color = Color.red; } else { attrLabel.color = Color.white; } valueStr += valueDelta.ToString (); attrLabel.text = valueStr; } _container_comparison.gameObject.SetActive (true); _container_firstAttr.gameObject.SetActive (true); } for (int i = 0; i < second.abilities.Count; i++) { _secondAbilities [i].LoadAbility (second.abilities [i]); } if (first != null) { for (int i = 0; i < first.abilities.Count; i++) { Debug.Log ("first"); _firstAbilities [i].LoadAbility (first.abilities [i]); } } _icon_second.spriteName = second.name; _icon_second.gameObject.SetActive (true); _level_second.text = second.level.ToString (); _level_second.gameObject.SetActive (true); _level_second.color = RarityColorStatic.rarityColors [(int)second.rarity]; if (first != null) { _icon_first.spriteName = first.name; _icon_first.gameObject.SetActive (true); _level_first.text = first.level.ToString (); _level_first.gameObject.SetActive (true); _level_first.color = RarityColorStatic.rarityColors [(int)first.rarity]; } gameObject.SetActive (true); HOTween.To (_panel, _fadeDuration, new TweenParms ().Prop ("alpha", 1f).Ease (EaseType.Linear).OnComplete (() => { _canClick = true;})); } void Hide () { HOTween.To (_panel, _fadeDuration, new TweenParms ().Prop ("alpha", 0f).Ease (EaseType.Linear).OnComplete (delegate() { Clear (); })); } void Clear () { _container_comparison.gameObject.SetActive (false); _container_firstAttr.gameObject.SetActive (false); _container_secondAttr.gameObject.SetActive (false); foreach (var item in _firstAbilities) { item.gameObject.SetActive (false); } foreach (var item in _secondAbilities) { item.gameObject.SetActive (false); } _icon_first.gameObject.SetActive (false); _icon_second.gameObject.SetActive (false); _level_first.gameObject.SetActive (false); _level_second.gameObject.SetActive (false); _panel.alpha = 0f; gameObject.gameObject.SetActive (false); } } <file_sep>/Assets/BattleCompleteDisplayer.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using Holoville.HOTween; public class BattleCompleteDisplayer : MonoBehaviour { public CompleteSlot[] _completeSlots; public UIGrid _grid; public UISlider _playerExperienceSlider; public UILabel _playerExperienceLabel; public UILabel _playerLevelLabel; public UILabel _playerCoinLabel; public UISprite _playerIcon; public GameObject _cardIconPrefab; public GameObject _returnButton; public Vector3 _newCardPosition; private PlayerControl _player; private UIPanel _panel; private int _level,_experience,_expUpBound,_coin; private float _fadeTime=0.5f,_addTimeInterval=0.25f, _expIncDuration=3.0f; private List<ConcreteCard> _trophyCards; private SceneFade _fader; private GameController _gamerController; private BattleControl _battleController; private bool _canClick; void Awake() { _player = GameObject.FindGameObjectWithTag (Tags.player).GetComponent<PlayerControl> (); _panel = GetComponent<UIPanel> (); _fader= GameObject.FindGameObjectWithTag (Tags.sceneFader).GetComponent<SceneFade> (); _gamerController = GameObject.FindGameObjectWithTag (Tags.gameController).GetComponent<GameController> (); _battleController = GameObject.FindGameObjectWithTag (Tags.battle).GetComponent<BattleControl> (); } void Start() { Clear (); } void OnClick() { if (_canClick) { DynamicToInstant(); _canClick=false; } } public void DisplayBattleComplete(LevelData levelData,List<ConcreteCard> achieveCards) { _trophyCards = achieveCards; _playerIcon.spriteName = _player.spriteName; LoadPlayerInfo (); IEnumerator slotIter =_completeSlots.GetEnumerator () ; for (int i = 0; i < _player.playCardSet.Count; i++) { if(_player.playCardSet[i]!=null) slotIter.MoveNext(); ((CompleteSlot)slotIter.Current).LoadConcreteCard(_player.playCardSet[i]); } gameObject.SetActive (true); _panel.alpha = 0f; foreach (var item in achieveCards) { _player.GainNewCard(item); } HOTween.To (_panel, _fadeTime, new TweenParms ().Prop ("alpha", 1f).Ease (EaseType.Linear).OnComplete (delegate() { Debug.Log("al=1"); PlayerGainExperience(levelData.experience); foreach (var item in _completeSlots) { if(item.vacant==false) { item.GainExperience(levelData.experience); } } StartCoroutine(gainCardsDynamic()); _returnButton.SetActive(true); _canClick=true; })); } void LoadPlayerInfo() { _level = _player.level; _playerLevelLabel.text = "Lv." +_level.ToString (); _experience = _player.experience; _expUpBound = BaseCard._experienceTable [_level-1]; _playerExperienceLabel.text = _experience.ToString () + "/" + _expUpBound.ToString (); _playerExperienceSlider.value = _experience / (float)_expUpBound; _coin = _player.coins; _playerCoinLabel.text = _coin.ToString (); } void PlayerGainExperience(int experience) { _player.experience += experience; StartCoroutine (PlayerGainExperienceDynamic (experience, _expIncDuration)); } IEnumerator PlayerGainExperienceDynamic(int experience,float duration) { float fExperience=(float)_experience; float perSecond = experience / duration; int dstLevel = _player.level, dstExp =_player.experience; while (_level<dstLevel||_experience<dstExp) { fExperience +=perSecond*Time.deltaTime; // Debug.Log(perSecond.ToString()+"|"+fExperience.ToString()); _experience=(int)fExperience; if (_experience >= _expUpBound) { while (_level<dstLevel) { _level++; _experience-=_expUpBound; fExperience-=(float)_expUpBound; _expUpBound=BaseCard._experienceTable[_level-1]; } } _playerLevelLabel.text = "lv." + _level.ToString (); _playerExperienceSlider.value = _experience / (float)_expUpBound; _playerExperienceLabel.text = _experience.ToString () + "/" + _expUpBound.ToString (); // Debug.Log(_level.ToString()+"|"+_experience.ToString()+"|"+dstLevel.ToString()+"|"+dstExp.ToString()); yield return null; } if (_experience > dstExp) { _experience=dstExp; } _playerLevelLabel.text = "lv." + _level.ToString (); _playerExperienceSlider.value = _experience / (float)_expUpBound; _playerExperienceLabel.text = _experience.ToString () + "/" + _expUpBound.ToString (); yield return null; } void PlayerGainCoins (int coins) { _player.coins += coins; StartCoroutine (gainCoinsDynamic (coins, _expIncDuration)); } IEnumerator gainCoinsDynamic(int coins,float duration) { float perSecond=coins/duration; while (_coin<_player.coins) { _coin+=(int)(perSecond*Time.deltaTime); _playerCoinLabel.text=_coin.ToString(); yield return null; } _coin = _player.coins; _playerCoinLabel.text=_coin.ToString(); yield return null; } IEnumerator gainCardsDynamic() { while (_trophyCards.Count >0) { ConcreteCard card=_trophyCards[_trophyCards.Count-1]; _trophyCards.RemoveAt(_trophyCards.Count-1); GameObject newCard= Instantiate(_cardIconPrefab) as GameObject; newCard.transform.localPosition=_newCardPosition; newCard.GetComponent<UISprite>().spriteName=card.name; _grid.AddChild(newCard.transform); yield return new WaitForSeconds(_addTimeInterval); } yield return null; } void Clear() { foreach (var item in _completeSlots) { item.vacant=true; item.gameObject.SetActive(false); } List<Transform> trophies = _grid.GetChildList (); for (int i = trophies.Count-1; i >=0 ; i--) { Destroy(trophies[i].gameObject); } _canClick = false; gameObject.SetActive (false); // Debug.Log("clear"); } void DynamicToInstant() { StopCoroutine("PlayerGainExperienceDynamic"); StopCoroutine ("gainCoinsDynamic"); StopCoroutine("gainCardsDynamic"); foreach (var item in _completeSlots) { if(item.vacant==false) item.GainExperienceInstant(); } LoadPlayerInfo (); _grid.animateSmoothly = false; for (int i = _trophyCards.Count-1; i >=0;i--) { ConcreteCard card=_trophyCards[i]; GameObject newCard= Instantiate(_cardIconPrefab) as GameObject; newCard.GetComponent<UISprite>().spriteName=card.name; _grid.AddChild(newCard.transform); } _grid.animateSmoothly = true; } public void EndDisplay() { _returnButton.SetActive (false); if (_canClick) { DynamicToInstant(); _canClick=false; } _fader.BeginFading (()=>{ _player.bagManagement.UpdateData(); Clear(); _battleController.gameObject.SetActive(false); _fader.ExitFading(()=>{_gamerController.BattleComplete();}); }); } } <file_sep>/Assets/UnitTest.cs using UnityEngine; using System.Collections; public class UnitTest : MonoBehaviour { public GameController _gameController; bool _gan; // Use this for initialization void Start () { _gan=false; } // Update is called once per frame // void Update () { // if(Time.time>2f&&_gan==false){ // _gameController._selectLevel=_gameController._levels[0]; // _gameController.BattleStart(_gameController._selectLevel.GetComponent<LevelInfo>()); // _gan=true; // } // } } <file_sep>/Assets/Scripts/Card/Abitity/AbilityEntityShell.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using Holoville.HOTween; public class AbilityEntityShell : MonoBehaviour { AbilityEntity _abilityEntity; // public HOTweenComponent[] _hotweenComArray; public float _flyTime; public GameObject[] _moveToTarget; public GameObject[] _atTargetPosition; public GameObject[] _hitEffect; public AbilityEntity abilityEntity { get{return _abilityEntity;} } void Awake() { } void Update() { // Debug.Log (Time.time); } public void Init (AbilityEntity abilityEntity) { // Debug.Log(gameObject.activeSelf); // Debug.Log (gameObject.activeInHierarchy); // Debug.Log (gameObject.transform.parent); // Debug.Log (name); _abilityEntity = abilityEntity; _abilityEntity.castCard.shell.battleController.shieldPanel.Activate (); transform.position = _abilityEntity.castCard.transform.position; Vector3 destination = abilityEntity.targetCard.transform.position; //Set animations playing position foreach (var item in _atTargetPosition) { Debug.Log(8); item.transform.position = destination; } foreach (var item in _hitEffect) { item.SetActive(false); Debug.Log(7); } foreach (var item in _moveToTarget) { item.transform.up=(_abilityEntity.targetCard.transform.position-item.transform.position).normalized; HOTween.To(item.transform,_flyTime,new TweenParms().Prop("position",_abilityEntity.targetCard.transform.position)); } //Set destination of hotweens which tween transform.position. // foreach (HOTweenComponent hotweenCom in _hotweenComArray) { // Debug.Log(hotweenCom.name); // Debug.Log(hotweenCom.tweenDatas==null); // hotweenCom.generatedTweeners; // foreach (HOTweenManager.HOTweenData hotweenData in hotweenCom.tweenDatas) { // if (hotweenData.targetName == "transform") { // foreach (HOTweenManager.HOPropData propData in hotweenData.propDatas) { // if (propData.propName == "position") { // propData.endValVector3 = destination; // } // } // } // } // } } public void Hit() { _abilityEntity.effectCard (_abilityEntity); foreach (var item in _moveToTarget) { item.SetActive(false); } _abilityEntity.targetCard.shell.GetHurt (); foreach (var item in _hitEffect) { item.SetActive(true); } _abilityEntity.castCard.shell.battleController.shieldPanel.Deactivate(); Destroy (gameObject, 0.5f); } public void Abort() { } } <file_sep>/Abandon/levelGateRelative/StarSlotControl.cs using UnityEngine; using System.Collections; using Holoville.HOTween; public class StarSlotControl : MonoBehaviour { public StarControl _childStar; LevelGateControl _level; // Use this for initialization void Awake(){ _childStar = GetComponentInChildren<StarControl> (); _level = GetComponentInParent<LevelGateControl> (); } // Update is called once per frame void Update () { } public void FillStar(bool fill) { _childStar.gameObject.SetActive (fill); } public void GainStar() { _childStar.Activate (); } public Vector3[] GetFlyPath() { Debug.Log ("_level" + _level.name); return _level.GetStarFlyPath (this); } public void Unlock() { gameObject.SetActive (true); GetComponentInChildren<ParticleSystem> ().Play(); UISprite sprite= GetComponent<UISprite> (); sprite.alpha = 0; HOTween.To (sprite, 1f, new TweenParms ().Prop ("alpha", 1f).Ease (EaseType.Linear)); } } <file_sep>/Abandon/levelGateRelative/StarFlyPath.cs using UnityEngine; using System.Collections; public class StarFlyPath : MonoBehaviour { public LevelGateControl _levelControl; static Vector3[] relativePath_starOne; static Vector3[] relativePath_starTwo; static Vector3[] relativePath_starThree; public Vector3[] GetPathOne() { if (relativePath_starOne == null) { float dx=Mathf.Abs( _levelControl._starOne.transform.position.x-_levelControl._mainButton.transform.position.x); float dy=Mathf.Abs( _levelControl._starOne.transform.position.y-_levelControl._mainButton.transform.position.y); relativePath_starOne=new Vector3[5]; relativePath_starOne[0]=Vector3.zero; relativePath_starOne[1]=new Vector3(3*-dx,0f,0f); relativePath_starOne[2]=new Vector3(3*-dx,dy,0f); relativePath_starOne[3]=new Vector3(2*-dx,2*dy,0f); relativePath_starOne[4]=new Vector3(-dx,dy,0f); } return relativePath_starOne; } public Vector3[] GetPathTwo() { if (relativePath_starTwo == null) { float dx=Mathf.Abs( _levelControl._starOne.transform.position.x-_levelControl._mainButton.transform.position.x); float dy=Mathf.Abs( _levelControl._starOne.transform.position.y-_levelControl._mainButton.transform.position.y); relativePath_starTwo=new Vector3[5]; relativePath_starTwo[0]=Vector3.zero; relativePath_starTwo[1]=new Vector3(dx,3*dy,0f); relativePath_starTwo[2]=new Vector3(0.75f*dx,4*dy,0f); relativePath_starTwo[3]=new Vector3(0.5f*dx,3*dy,0f); relativePath_starTwo[4]=new Vector3(0,dy,0f); } return relativePath_starTwo; } public Vector3[] GetPathThree() { if (relativePath_starThree == null) { float dx=Mathf.Abs( _levelControl._starOne.transform.position.x-_levelControl._mainButton.transform.position.x); float dy=Mathf.Abs( _levelControl._starOne.transform.position.y-_levelControl._mainButton.transform.position.y); relativePath_starThree=new Vector3[5]; relativePath_starThree[0]=Vector3.zero; relativePath_starThree[1]=new Vector3(3*dx,0f,0f); relativePath_starThree[2]=new Vector3(3*dx,dy,0f); relativePath_starThree[3]=new Vector3(2*dx,2*dy,0f); relativePath_starThree[4]=new Vector3(dx,dy,0f); } return relativePath_starThree; } } <file_sep>/Assets/Scripts/Card/ShellType.cs using UnityEngine; using System.Collections; public enum ShellType{ Player,Enemy }; <file_sep>/Assets/Test2.cs using UnityEngine; using System.Collections; using System.Text.RegularExpressions; using Holoville.HOTween; using Holoville.HOTween.Plugins; public class Test2 : Test { public UILabel label; // Use this for initialization // void Start () { // Vector3[] path=new Vector3[3]; // path [0] = transform.position; // path [1] = new Vector3 (0f, 10f, 0f); // path [2] = new Vector3 (10f, 0f, 0f); // HOTween.To (transform, 5, new TweenParms ().Prop ("position", new PlugVector3Path (path,EaseType.EaseOutCubic,PathType.Curved)).Loops(-1)); // HOTween.showPathGizmos = true; // } void Start() { // HOTween .To (label) } void Update() { // renderer.material.SetFloat("coldDown",0.9f); } void OnClick() { // Debug.Log("Bgclick"); } } <file_sep>/Abandon/levelGateRelative/StarCounter/StarCounterControl.cs using UnityEngine; using System.Collections; public class StarCounterControl : MonoBehaviour { UILabel _counter; int _sum; int _count; // Use this for initialization void Awake() { _counter = GetComponent<UILabel> (); _sum = GameObject.FindGameObjectsWithTag (Tags.levelGate).Length * 3; _count = 0; } // Update is called once per frame void Update () { } public void GainStar() { _count++; _counter.text = _count + "/" + _sum; } public void Save() { } public void LoadFromPlayerPrefs() {} } <file_sep>/Assets/Scripts/Card/BattleCard.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Reflection; using Holoville.HOTween; /// <summary> ///This kind of card will only exist on battle field . ///The modification of attribute on BattleCard will not effect relative ConcreteCard /// </summary> public class BattleCard : MonoBehaviour { static float _evasionTime = 0.5f; #region Instance member protected BattleCardShell _shell; protected ConcreteCard _concreteCard; protected CardEffected _cardEffect; protected Dictionary<int,DotAndHot> _DotAndHotTable; protected Dictionary<int,DebuffAndBuff> _debuffAndBuffTable; protected Dictionary<Ability,int> _abilityCDTable; protected int _health, _mana, _strength, _agility, _magic, _maxHealth, _maxMana, _physicalDefense, _magicalDefense, _physicalCriticalChance, _magicalCriticalChance, _physicalDamage, _magicalDamage, _healthResilience, _magicResilience, _evasion; #endregion #region Properties /// <summary> /// If health less equal than zero ,this battle card will be dead and be moved from battle field. /// </summary> /// <value>The health.</value> DynamicTextAdmin dynamicText { get{ return _shell.battleController.dynamicTextAdmin;} } public int health { get { return _health;} set { int valueDelta = value - _health; if (valueDelta > 0) { dynamicText.DynamicText (transform.position, "+" + valueDelta.ToString (), Color.green); } else if (valueDelta < 0) { _shell.GetHurt(); dynamicText.DynamicText (transform.position, valueDelta.ToString (), Color.red); } if (value > _maxHealth) { _health = _maxHealth; } else { _health = value; } _shell._label_hp.text=_health.ToString(); if (_health <= 0) { _shell.CardRoleDead(); } } } public int mana { get{ return _mana;} set { int valueDelta = value - _mana; dynamicText.DynamicText (transform.position, "MP:" + valueDelta.ToString (), Color.blue); if (value > _maxMana) { _mana = _maxMana; } else { _mana = value; } _shell._label_mp.text=_mana.ToString(); } } public int maxHealth { get{ return _maxHealth;} set { int valueDelta = value - _maxHealth; dynamicText.DynamicText (transform.position, "HP-MAX:" + valueDelta.ToString (), Color.red); _maxHealth = value; if (_maxHealth > _health) { _health = _maxHealth; } } } public int maxMana { get{ return _maxMana;} set { int valueDelta = value - _maxMana; dynamicText.DynamicText (transform.position, "MP-MAX:" + valueDelta.ToString (), Color.blue); _maxMana = value; if (_maxMana > _mana) { _mana = _maxMana; } } } public int magicalDefense { get{ return _magicalDefense;} set { int valueDelta = value - _magicalDefense; dynamicText.DynamicText (transform.position, "Spell Resistance:" + valueDelta.ToString ()); _magicalDefense = value; } } public int magicalCriticalChance { get{ return _magicalCriticalChance;} set { int valueDelta = value - _magicalCriticalChance; dynamicText.DynamicText (transform.position, "Spell Crit:" + valueDelta.ToString ()); _magicalCriticalChance = value; } } public int magicalDamage { get{ return _magicalDamage;} set { int valueDelta = value - _magicalDamage; dynamicText.DynamicText (transform.position, "Spell Damage:" + valueDelta.ToString ()); _magicalDamage = value; } } public int healthResilience { get{ return _healthResilience;} set { int valueDelta = value - _healthResilience; dynamicText.DynamicText (transform.position, "HP Recovery:" + valueDelta.ToString ()); _healthResilience = value; } } public int magicResilience { get{ return _magicResilience;} set { int valueDelta = value - _magicResilience; dynamicText.DynamicText (transform.position, "MP Recovery:" + valueDelta.ToString ()); _magicResilience = value; } } public int evasion { get{ return _evasion;} set { int valueDelta = value - _evasion; dynamicText.DynamicText (transform.position, "Evasion:" + valueDelta.ToString ()); _evasion = value; } } public int physicalDamage { get{ return _physicalDamage;} set { int valueDelta = value - _physicalDamage; dynamicText.DynamicText (transform.position, "Physical Damage:" + valueDelta.ToString ()); _physicalDamage = value; } } public int physicalCriticalChance { get{ return _physicalCriticalChance;} set { int valueDelta = value - _physicalCriticalChance; dynamicText.DynamicText (transform.position, "Physical Crit:" + valueDelta.ToString ()); _physicalCriticalChance = value; } } public int physicalDefense { get{ return _physicalDefense;} set { int valueDelta = value - _physicalDefense; dynamicText.DynamicText (transform.position, "Defense:" + valueDelta.ToString ()); _physicalDefense = value; } } //The implement, by accumulation, of 3 properties below are different from ConcreteCard. //The reason is for attribute value restoration mechanism in battle /// <summary> /// Max health,physical damage,physical defense and health resilience are changed along with strength /// </summary> /// <value>The strength.</value> public int strength { get{ return _strength;} set { int valueDelta = value - _strength; dynamicText.DynamicText (transform.position, "Strength:" + valueDelta.ToString ()); _strength = value; _maxHealth += (int)(valueDelta * BaseCard.rate_strength_maxHealth); _physicalDamage += (int)(valueDelta * BaseCard.rate_strength_physicalDamage); _physicalDefense += (int)(valueDelta * BaseCard.rate_strength_physicalDefense); _healthResilience += (int)(valueDelta * BaseCard.rate_strength_healthResilience); } } /// <summary> /// Physical defense ,physical critical chance and evasion are changed along with agility /// </summary> /// <value>The agility.</value> public int agility { get{ return _agility;} set { int valueDelta = value - _agility; dynamicText.DynamicText (transform.position, "Agility:" + valueDelta.ToString ()); _agility = value; _physicalDefense += (int)(valueDelta * BaseCard.rate_agility_physicalDefense); _physicalCriticalChance += (int)(valueDelta * BaseCard.rate_agility_physicalCriticalChance); _evasion += (int)(valueDelta * BaseCard.rate_agility_evasion); } } /// <summary> /// Max mana,magical defense,magical critical chance,magical damage and magic resiliense are changed along with magic /// </summary> /// <value>The magic.</value> public int magic { get{ return _magic;} set { int valueDelta = value - _magic; dynamicText.DynamicText (transform.position, "Magic:" + valueDelta.ToString ()); _magic = value; _maxMana += (int)(valueDelta * BaseCard.rate_magic_maxMana); _magicalDefense += (int)(valueDelta * BaseCard.rate_magic_magicalDefense); _magicalCriticalChance += (int)(valueDelta * BaseCard.rate_magic_magicalCriticalChance); _magicalDamage += (int)(valueDelta * BaseCard.rate_magic_magicalDamage); _magicResilience += (int)(valueDelta * BaseCard.rate_magic_magicResilience); } } public ConcreteCard concreteCard { get{ return _concreteCard;} } public BattleCardShell shell { get{return _shell;} } public CardEffected cardEffected { get{ return _cardEffect;} } public List<Ability> abilities { get{ return _concreteCard.abilities;} } public Dictionary<Ability,int> abilityCDTable { get{return _abilityCDTable;} } #endregion public void LoadConcreteCard (ConcreteCard concreteCard) { _concreteCard = concreteCard; _strength = concreteCard.strength; _agility = concreteCard.agility; _magic = concreteCard.magic; _maxHealth = concreteCard.maxHealth; _maxMana = concreteCard.maxMana; _health = _maxHealth; _mana = 0; _physicalDefense = concreteCard.physicalDefense; _magicalDefense = concreteCard.magicalDefense; _physicalCriticalChance = concreteCard.physicalCriticalChance; _magicalCriticalChance = concreteCard.magicalCriticalChance; _physicalDamage = concreteCard.physicalDamage; _magicalDamage = concreteCard.magicalDamage; _healthResilience = concreteCard.healthResilience; _magicResilience = concreteCard.magicResilience; _evasion = concreteCard.evasion; foreach (var item in concreteCard.abilities) { _abilityCDTable.Add(item,0); } } void Awake () { _DotAndHotTable = new Dictionary<int, DotAndHot> (); _debuffAndBuffTable = new Dictionary<int, DebuffAndBuff> (); _abilityCDTable = new Dictionary<Ability, int> (); _shell = GetComponent<BattleCardShell> (); _cardEffect = CardEffectedStatic.CardEffected_Normal; } public void Clear () { FieldInfo[] fields = typeof(BattleCard).GetFields (BindingFlags.NonPublic | BindingFlags.Instance); foreach (var item in fields) { if (item.FieldType == typeof(int)) { item.SetValue (this, 0); } } _debuffAndBuffTable.Clear (); _DotAndHotTable.Clear (); _abilityCDTable.Clear (); } public void AddDotOrHot (DotAndHot dotOrHot) { _DotAndHotTable [dotOrHot.id] = dotOrHot; } public void AddDebuffOrBuff (DebuffAndBuff debuffOrBuff) { _debuffAndBuffTable [debuffOrBuff.id] = debuffOrBuff; } public void Evade () { dynamicText.DynamicText (transform.position, "Evade!!!"); _shell.battleController.shieldPanel.Activate (); HOTween.To (transform, _evasionTime / 2, new TweenParms ().Prop ("localPosition", transform.localPosition + new Vector3 (1f, 0, 0.5f)).Ease (EaseType.Linear).OnComplete (delegate() { HOTween.To (transform, _evasionTime / 2, new TweenParms ().Prop ("localPosition", _shell.originalLocalPosition).Ease (EaseType.Linear).OnComplete (delegate() { _shell.battleController.shieldPanel.Deactivate (); })); })); HOTween.To (transform, _evasionTime / 2, new TweenParms ().Prop ("localRotation", Quaternion.Euler (new Vector3 (0, 0, 20f))).Ease (EaseType.Linear).OnComplete (delegate() { HOTween.To (transform, _evasionTime / 2, new TweenParms ().Prop ("localRotation", Quaternion.identity).Ease (EaseType.Linear)); })); } } <file_sep>/Assets/Scripts/AbilityDetailDisplayer.cs using UnityEngine; using System.Collections; using Holoville.HOTween; public class AbilityDetailDisplayer : MonoBehaviour { public UITexture _texture_abilityIcon; public UILabel _label_level,_label_comsume,_label_cooldown,_label_description,_label_name; public float _fadeTime=0.2f; private UIPanel _panel; void Awake() { _panel=GetComponent<UIPanel>(); _panel.alpha=0; } void Start() { gameObject.SetActive(false); } public void DisplayerAbilityDetail(Ability abililty,float displayCoorY) { DisplayerAbilityDetail(abililty,displayCoorY,-1); } public void DisplayerAbilityDetail(Ability abililty,float displayCoorY,int cdRound) { _texture_abilityIcon.mainTexture=abililty.icon; _label_name.text=abililty.name; _label_level.text="Lv."+abililty.level.ToString(); string txt_cd; if(cdRound>=0) { txt_cd=string.Format("CD:{0}/{1}",cdRound%(abililty.cooldown+1),abililty.cooldown); } else { txt_cd="CD:"+abililty.cooldown.ToString(); } _label_cooldown.text=txt_cd; _label_comsume.text="MP:"+abililty.mana.ToString(); _label_description.text=abililty.GetDescription(); transform.position=new Vector3(transform.position.x,displayCoorY,transform.position.z); gameObject.SetActive(true); HOTween.To(_panel,_fadeTime,new TweenParms().Prop("alpha",1f).Ease( EaseType.Linear)); } public void HideAbilityDetail() { HOTween.To(_panel,_fadeTime,new TweenParms().Prop("alpha",0f).Ease( EaseType.Linear).OnComplete( delegate() { gameObject.SetActive(false); })); } } <file_sep>/Assets/Scripts/Player/BagManagement.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using Holoville.HOTween; public class BagManagement : MonoBehaviour { static System.Comparison<Transform> gridSort_byLevel, gridSort_byLevelReverse, gridSort_byRarity, gridSort_byRarityReverse; public UILabel _playerName, _coin, _level, _experience; public UISlider _experienceSlider; public GameObject _bagSlotPrefab; public UIGrid _grid; public List<BattleSlot> _battleSlots; public ShieldPanel _shieldPanel; public GameObject _popButton; private List<BagSlot> _bagSlots; private UIScrollView _scrollView; private PlayerControl _player; private BagSlot _selectBagSlot; private BattleSlot _selectBattleSlot; private CardComparisonDisplayer _cardComparisonDisplayer; private float _fadeDuration = 0.3f; private int _coinAmount; private Vector3 _initLocalPosition=new Vector3(0,-912f,0); private float _popDuration=0.8f; public int coinAmount { get{ return _coinAmount;} set{ _coinAmount = value;} } static BagManagement () { gridSort_byLevel = delegate(Transform x, Transform y) { ConcreteCard cardX = x.GetComponent<BagSlot> ().concreteCard; ConcreteCard cardY = y.GetComponent<BagSlot> ().concreteCard; if (cardX.level > cardY.level) { return 1; } if (cardX.level < cardY.level) { return -1; } if (cardX.experience > cardY.experience) { return 1; } if (cardX.experience < cardY.experience) { return -1; } return 0; }; gridSort_byLevelReverse = delegate(Transform x, Transform y) { return -gridSort_byLevel (x, y); }; gridSort_byRarity = delegate(Transform x, Transform y) { ConcreteCard cardX = x.GetComponent<BagSlot> ().concreteCard; ConcreteCard cardY = y.GetComponent<BagSlot> ().concreteCard; if (cardX.rarity > cardY.rarity) { return 1; } if (cardX.rarity < cardY.rarity) { return -1; } return gridSort_byLevel (x, y); }; gridSort_byRarityReverse = delegate(Transform x, Transform y) { return -gridSort_byRarity (x, y); }; } void Awake () { _player = GameObject.FindGameObjectWithTag (Tags.player).GetComponent<PlayerControl> (); _bagSlots = new List<BagSlot> (); _scrollView = GetComponentInChildren<UIScrollView> (); _cardComparisonDisplayer = GetComponentInChildren<CardComparisonDisplayer> (); } public void Load () { _playerName.text = _player.playerName; _coinAmount = _player.coins; _coin.text = _coinAmount.ToString (); _level.text = "Lv." + _player.level.ToString (); _experience.text = _player.experience.ToString () + "/" + BaseCard.experienceTable [_player.level - 1].ToString (); _experienceSlider.value = _player.experience / (float)(BaseCard._experienceTable [_player.level - 1]); for (int i = 0; i < _player.playCardSet.Count; i++) { if (_player.playCardSet [i] != null) { _battleSlots [i].LoadConcreteCard (_player.playCardSet [i]); } _battleSlots [i].Index = i; } for (int i = 0; i < _player.cardBag.Count; i++) { AddNewCardToBag(_player.cardBag[i]); } } public void UpdateData() { _coinAmount = _player.coins; _coin.text = _coinAmount.ToString (); _level.text = "Lv." + _player.level.ToString (); _experience.text = _player.experience.ToString () + "/" + BaseCard.experienceTable [_player.level - 1].ToString (); _experienceSlider.value = _player.experience / (float)(BaseCard._experienceTable [_player.level - 1]); foreach (var item in _bagSlots) { item.UpdateData(); } foreach (var item in _battleSlots) { item.UpdateData(); } } public void AddNewCardToBag(ConcreteCard card) { GameObject bagSlotGO = Instantiate (_bagSlotPrefab)as GameObject; bagSlotGO.GetComponent<UIDragScrollView> ().scrollView = _scrollView; BagSlot bagSlot = bagSlotGO.GetComponent<BagSlot> (); bagSlot.LoadConcreteCard (card); _grid.AddChild (bagSlotGO.transform); bagSlotGO.transform.localScale = Vector3.one; _bagSlots.Add (bagSlot); } public void SlotClick (BattleSlot battleSlot) { if (_selectBattleSlot == null) { if (_selectBagSlot != null) { _selectBagSlot.Deselect (); _selectBagSlot = null; } _selectBattleSlot = battleSlot; battleSlot.Select (); } else {//has selected a battleSlot if (_selectBattleSlot.Index == battleSlot.Index) {//Click the same slot,deselect battleSlot.Deselect (); _selectBattleSlot = null; } else if (_selectBattleSlot.concreteCard == null) { _selectBattleSlot.Deselect (); _selectBattleSlot = battleSlot; _selectBattleSlot.Select (); } else { _selectBattleSlot.Deselect (); ConcreteCard first = _selectBattleSlot.concreteCard, second = battleSlot.concreteCard; int indexFst = _selectBattleSlot.Index, indexSec = battleSlot.Index; _player.playCardSet [indexFst] = second; _player.playCardSet [indexSec] = first; HOTween.To (_selectBattleSlot.slotBody, _fadeDuration, new TweenParms ().Prop ("alpha", 0f).Ease (EaseType.Linear).OnStart (() => { _shieldPanel.Activate ();}).OnComplete (() => { if (second != null) { _selectBattleSlot.LoadConcreteCard (second); HOTween.To (_selectBattleSlot.slotBody, _fadeDuration, new TweenParms ().Prop ("alpha", 1f).Ease (EaseType.Linear).OnComplete (() => { _shieldPanel.Deactivate (); _selectBattleSlot = null; })); } else { _shieldPanel.Deactivate (); _selectBattleSlot.Unload (); _selectBattleSlot = null; } })); HOTween.To (battleSlot.slotBody, _fadeDuration, new TweenParms ().Prop ("alpha", 0f).Ease (EaseType.Linear).OnStart (() => { _shieldPanel.Activate ();}).OnComplete (() => { battleSlot.LoadConcreteCard (first); HOTween.To (battleSlot.slotBody, _fadeDuration, new TweenParms ().Prop ("alpha", 1f).Ease (EaseType.Linear).OnComplete (() => { _shieldPanel.Deactivate (); })); })); } } } public void SlotClick (BagSlot bagSlot) { if (_selectBattleSlot == null) { if (_selectBagSlot != null) { _selectBagSlot.Deselect (); } _selectBagSlot = bagSlot; _selectBagSlot.Select (); } else { _selectBattleSlot.Deselect (); ConcreteCard first = _selectBattleSlot.concreteCard, second = bagSlot.concreteCard; int index = _selectBattleSlot.Index; _player.playCardSet [index] = second; _player.cardBag.Remove (second); if (first != null) { _player.cardBag.Add (first); } HOTween.To (_selectBattleSlot.slotBody, _fadeDuration, new TweenParms ().Prop ("alpha", 0f).Ease (EaseType.Linear).OnStart (() => { _shieldPanel.Activate ();}).OnComplete (() => { _selectBattleSlot.LoadConcreteCard (second); HOTween.To (_selectBattleSlot.slotBody, _fadeDuration, new TweenParms ().Prop ("alpha", 1f).Ease (EaseType.Linear).OnComplete (() => { _shieldPanel.Deactivate (); _selectBattleSlot = null; })); })); Debug.Log (bagSlot.slotBody == null); HOTween.To (bagSlot.slotBody, _fadeDuration, new TweenParms ().Prop ("alpha", 0f).Ease (EaseType.Linear).OnStart (() => { _shieldPanel.Activate ();}).OnComplete (() => { if (first != null) { bagSlot.LoadConcreteCard (first); HOTween.To (bagSlot.slotBody, _fadeDuration, new TweenParms ().Prop ("alpha", 1f).Ease (EaseType.Linear).OnComplete (() => { _shieldPanel.Deactivate (); })); } else { _shieldPanel.Deactivate (); _grid.RemoveChild (bagSlot.transform); _bagSlots.Remove (bagSlot); Destroy (bagSlot.gameObject); } })); } } public void SlotShowDetail (BattleSlot battleSlot) { SlotShowDetail (battleSlot.concreteCard); } public void SlotShowDetail (BagSlot bagSlot) { SlotShowDetail (bagSlot.concreteCard); } void SlotShowDetail (ConcreteCard card) { ConcreteCard second = card; ConcreteCard first = null; if (_selectBagSlot != null) { first = _selectBagSlot.concreteCard; } else if (_selectBattleSlot != null) { first = _selectBattleSlot.concreteCard; } if (first == null) { Debug.Log (second == null); _cardComparisonDisplayer.DisplayCardComparison (second); } else { _cardComparisonDisplayer.DisplayCardComparison (second, first); } } public void SellSelectedCards () { List<ConcreteCard> sellList = new List<ConcreteCard> (); // List<Transform> gridChildren = _grid.GetChildList (); for (int i = _bagSlots.Count-1; i >=0; i--) { if (_bagSlots [i].isSell) { Debug.Log ("sell"); sellList.Add (_bagSlots [i].concreteCard); BagSlot bagSlot = _bagSlots [i]; HOTween.To (bagSlot.slotBody, _fadeDuration, new TweenParms ().Prop ("alpha", 0).Ease (EaseType.Linear).OnComplete (() => { Destroy (bagSlot.gameObject);})); bagSlot.transform.parent = null; _bagSlots.RemoveAt (i); } } StartCoroutine (GridRepositionDelay (_fadeDuration)); if (sellList.Count == 0) { return; } _player.Sell (sellList); HOTween.To (this, 2f, new TweenParms ().Prop ("coinAmount", _player.coins).Ease (EaseType.Linear)); StartCoroutine (CoinIncrease ()); } IEnumerator GridRepositionDelay (float delay) { yield return new WaitForSeconds (delay); _grid.Reposition (); yield return null; } IEnumerator CoinIncrease () { while (_coinAmount!=_player.coins) { _coin.text = _coinAmount.ToString (); yield return null; } _coin.text = _player.coins.ToString (); yield return null; } public void SortByLevel () { if (_grid.onCustomSort == gridSort_byLevelReverse) { _grid.onCustomSort = gridSort_byLevel; } else { _grid.onCustomSort = gridSort_byLevelReverse; } _grid.Reposition (); } public void SortByRarity () { if (_grid.onCustomSort == gridSort_byRarityReverse) { _grid.onCustomSort = gridSort_byRarity; } else { _grid.onCustomSort = gridSort_byRarityReverse; } _grid.Reposition (); } public void PopUp() { HOTween.To(transform,_popDuration,new TweenParms().Prop("localPosition",Vector3.zero).Ease(EaseType.EaseOutBounce) .OnComplete(()=>{ _popButton.SetActive(false); })); } public void Pullback() { HOTween.To(transform,_popDuration,new TweenParms().Prop("localPosition",_initLocalPosition).Ease(EaseType.Linear) .OnComplete(()=>{ _popButton.SetActive(true); })); } } <file_sep>/Assets/Scripts/Level/LevelInfo.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class LevelInfo:MonoBehaviour { LevelGateControl _gateControl; string _name; string _uniqueIdentifer; bool _unlocked; private LevelData _levelData; public LevelData leveldata { get{ return _levelData;} } public bool unlocked { get{ return _unlocked;} } public int index { get{ return _gateControl.levelIndex;} } void Awake () { _gateControl = GetComponent<LevelGateControl> (); } public void Unlock () { _unlocked = true; } public void LoadFromJson () { TextAsset text = Resources.Load <TextAsset> (string.Format ("{0}/level_{1:000}", ResourcesFolderPath.json_level, index)); if (text == null) return; string json = text.text; Dictionary<string ,object> dict = MiniJSON.Json.Deserialize (json)as Dictionary<string,object>; _levelData = LevelData.GetLevelData (dict ["level"]as Dictionary<string,object>); // Debug.Log ("experience:"+_levelData.experience); // Debug.Log ("level:"+_levelData.level); // foreach (var item in _levelData.enemiesId) // Debug.Log (item); // foreach (var item in _levelData.bossIndices) { // Debug.Log(item); // } } public void LoadFromPlayerPrefs () { int iUnlock = PlayerPrefs.GetInt (_uniqueIdentifer); if (iUnlock > 0) { _unlocked = true; } } public void Load () { _uniqueIdentifer = string.Format ("level_{0:000}", index); LoadFromJson (); LoadFromPlayerPrefs (); } public void Save () { PlayerPrefs.SetInt (_uniqueIdentifer, _unlocked ? 1 : 0); } } <file_sep>/Assets/Scripts/Battle/BattleControl.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using Holoville.HOTween; public class BattleControl : MonoBehaviour { #region Fields /// <summary> /// The level difference between boss and normal enemy. /// </summary> /// private CardAIScript _enemyAI; // public UICamera _uiCamera; private int _bossLevelDelta = 2; private int _bossAbilityLevelDelta = 1; // private float _shellRotateTime = 1f; private CardFactory _cardFactory; public BattleCardShell[] _playerCardShellSet; public BattleCardShell[] _enemyCardShellSet; public GameObject _background; public Material[] _shellMaterials; public ShieldPanel _shieldPanel; public CardDetailDisplayer _cardDetailDisplayer; public GameObject _cardBGIconPrefab; public UILabel _trophyAmount; public BattleCompleteDisplayer _battleCompleteDisplayer; private PlayerControl _player; private GameController _gameController; private List<ConcreteCard> _enemyCard; private List<ConcreteCard> _playerCard; private int _enemyIndex; private List<int>.Enumerator _bossIndexIter; private Dictionary<LevelInfo,Texture> _backgroundTextureTable; /// <summary> ///Launcher of event(attack boss,merge another card or provide buff....) /// </summary> private BattleCardShell _currentActiveCard; private AbilityShell _currentActiveAbility; private DynamicTextAdmin _dynamicTextAdmin; private List<ConcreteCard> _trophyCards; private LevelData _levelData; private SceneFade _sceneFader; #endregion #region Properties public ShieldPanel shieldPanel { get{ return _shieldPanel;} } public DynamicTextAdmin dynamicTextAdmin { get{ return _dynamicTextAdmin;} } public CardDetailDisplayer cardDetailDisplayer { get{ return _cardDetailDisplayer;} } #endregion void Awake () { _player = GameObject.FindGameObjectWithTag (Tags.player).GetComponent<PlayerControl> (); _gameController = GameObject.FindGameObjectWithTag (Tags.gameController).GetComponent<GameController> (); _sceneFader = GameObject.FindGameObjectWithTag (Tags.sceneFader).GetComponent<SceneFade> (); _dynamicTextAdmin = GetComponentInChildren<DynamicTextAdmin> (); _enemyCard = new List<ConcreteCard> (); _cardFactory = CardFactory.GetCardFactory (); _enemyAI = GetComponent<CardAIScript> (); _backgroundTextureTable = new Dictionary<LevelInfo, Texture> (); _trophyCards = new List<ConcreteCard> (); } void Start() { gameObject.SetActive (false); } void Clear () { _trophyCards.Clear (); _enemyCard.Clear (); _enemyIndex = 0; _currentActiveCard = null; foreach (var item in _enemyCardShellSet) { item.Clear (); item.gameObject.SetActive (false); } foreach (var item in _playerCardShellSet) { item.Clear (); item.gameObject.SetActive (false); } } /// <summary> /// Loads the battle layer elements by level information. /// </summary> /// <param name="levelInfo">The level to load.</param> public void LoadLevel (LevelInfo levelInfo) { //Rules: 1.Every level has at least one boss; // 2.In each wave of enemies,at most one boss could appear; // 3.The last wave of enemie must has boss shown. // 4.Every level has at least one enemy will have odds to drop a whole card or a card fragment out. // 5.Every player card will gain some experience after win the battle. Clear (); _levelData = levelInfo.leveldata; LoadBackground (levelInfo); _bossIndexIter = levelInfo.leveldata.bossIndices.GetEnumerator (); _bossIndexIter.MoveNext (); LoadEnemyConcreteCard (levelInfo); LoadPlayerConcreteCard (); LoadEnemyWave (); LoadPlayerBattleCard (); _trophyAmount.text = "0"; } void LoadBackground (LevelInfo levelInfo) { Texture backgroundTex; if (_backgroundTextureTable.ContainsKey (levelInfo)) { backgroundTex = _backgroundTextureTable [levelInfo]; } else { backgroundTex = Resources.Load<Texture> (ResourcesFolderPath.textures_background + "/" + levelInfo.leveldata.background); _backgroundTextureTable.Add (levelInfo, backgroundTex); } _background.renderer.material.mainTexture = backgroundTex; } /// <summary> /// Loads the enemy ConcreteCard via level imformation. /// </summary> /// <param name="levelInfo">Level information.</param> void LoadEnemyConcreteCard (LevelInfo levelInfo) { LevelData levelData = levelInfo.leveldata; List<int> enemyLevels = new List<int> (); List<int> enemyAbilityLevels = new List<int> (); for (int i = 0; i < levelData.enemiesId.Count; i++) { enemyLevels.Add (levelData.level); enemyAbilityLevels.Add (levelData.enemiesAbilityLevel); } foreach (int i in levelData.bossIndices) { enemyLevels [i] += _bossLevelDelta; enemyAbilityLevels [i] += _bossAbilityLevelDelta; } for (int i = 0; i < levelData.enemiesId.Count; i++) { ConcreteCard enemyCard = _cardFactory.GeneConcreteCard (levelData.enemiesId [i], enemyLevels [i]); foreach (var ability in enemyCard.abilities) { int abilityLevel = enemyAbilityLevels [i]; if (abilityLevel > ability.maxLevel) { abilityLevel = ability.maxLevel; } ability.level = abilityLevel; } _enemyCard.Add (enemyCard); } } void LoadPlayerConcreteCard () { // for (int i = 0; i < _player.playCardSet.Count; i++) { // { // _playerCard.Add (_player.playCardSet [i]); // } // } _playerCard = _player.playCardSet; } /// <summary> /// Loads a wave of enemy battleCard. /// </summary> void LoadEnemyWave () { bool emptyWave = true; for (int i = 0; i < _enemyCardShellSet.Length; i++) { if (_enemyIndex + i < _enemyCard.Count) { if (_enemyCard [i + _enemyIndex] != null) { emptyWave = false; _enemyCardShellSet [i].LoadCard (_enemyCard [i + _enemyIndex]); if (i + _enemyIndex == _bossIndexIter.Current) { _enemyCardShellSet [i].transform.localScale = Vector3.one * 0.02f; HOTween.To (_enemyCardShellSet[i].transform,0.3f,new TweenParms().Prop("localScale",Vector3.one*0.8f).Ease(EaseType.Linear). OnStart(()=>{_shieldPanel.Activate();}).OnComplete(()=>{_shieldPanel.Deactivate();})); _bossIndexIter.MoveNext (); } else { _enemyCardShellSet [i].transform.localScale = Vector3.one * 0.02f; HOTween.To (_enemyCardShellSet[i].transform,0.3f,new TweenParms().Prop("localScale",Vector3.one*0.6f).Ease(EaseType.Linear). OnStart(()=>{_shieldPanel.Activate();}).OnComplete(()=>{_shieldPanel.Deactivate();})); } Invoke("RotateShells",0.3f); } } else { break; } } _enemyIndex += 5; //In case of a wave of empty enemy if (emptyWave) { Debug.Log ("Load a wave of empty enemy"); LoadEnemyWave (); } } /// <summary> /// Loads the player's concrete card into card shells. /// </summary> void LoadPlayerBattleCard () { for (int i = 0; i < _playerCardShellSet.Length; i++) { if (i < _playerCard.Count) { if (_playerCard [i] != null) { BattleCardShell shell = _playerCardShellSet [i]; shell.transform.localScale = Vector3.one * 0.6f; shell.LoadCard (_playerCard [i]); } } } } public void CheckVacantShell () { // Debug.Log ("checkVacant"); bool enemyWaveDead = true, playerRolesDead = true; for (int i = 0; i < _enemyCardShellSet.Length; i++) { if (_enemyCardShellSet [i].vacant == false) { // Debug.Log ("i:" + i); enemyWaveDead = false; break; } } for (int i = 0; i < _playerCardShellSet.Length; i++) { if (_playerCardShellSet [i].vacant == false) { playerRolesDead = false; break; } } if (enemyWaveDead) { _enemyAI.run = false; if (_enemyIndex < _enemyCard.Count) { Debug.Log ("haiyou"); LoadEnemyWave (); RotateShells(); RoundEnd (); } else { Debug.Log ("BattleComplete"); BattleComplete (); return; } } if (playerRolesDead) { _enemyAI.run = false; BattleAbort (); } } public void RotateShells () { foreach (var item in _playerCardShellSet) { if (item.gameObject.activeSelf == true && item.transform.localRotation != Quaternion.identity) { item.TurnToFront (); } } foreach (var item in _enemyCardShellSet) { if (item.gameObject.activeSelf == true && item.transform.localRotation != Quaternion.identity) { item.TurnToFront (); } } } void RoundStart () { foreach (var shell in _playerCardShellSet) { if (shell.vacant == false) { shell.RoundStart (); } } foreach (var shell in _enemyCardShellSet) { if (shell.vacant == false) { shell.RoundStart (); } } StartCoroutine ("CRCheckPlayerCardActivity"); } IEnumerator CRCheckPlayerCardActivity () { while (_shieldPanel.gameObject.activeSelf) { yield return null; } CheckPlayerCardShellSetActivity (); yield return null; } /// <summary> /// Check all the player cards' activity. /// </summary> void CheckPlayerCardShellSetActivity () { // Debug.Log ("CheckPlayerCardShellSetActivity"); bool playerRoundOver = true; foreach (var shell in _playerCardShellSet) { if (CheckPlayerCardActivity (shell)) { shell.HighLight (); playerRoundOver = false; } } if (playerRoundOver) { ExecuteEnemyCards(); } } bool CheckPlayerCardActivity (BattleCardShell cardShell) { // Debug.Log((cardShell.shellType == ShellType.Enemy) .ToString()+(cardShell.vacant)+( cardShell.hasCast)); if (cardShell.shellType == ShellType.Enemy || cardShell.vacant || cardShell.hasCast) { return false; } return cardShell.HasAvailableAbility (); } void ExecuteEnemyCards () { // Debug.Log ("executeEnemycards"); _enemyAI.EnemiesActionStart (); } public void RoundEnd () { foreach (var item in _playerCardShellSet) { if (item.vacant == false) { item.RoundEnd (); } } foreach (var item in _enemyCardShellSet) { if (item.vacant == false) { item.RoundEnd (); } } StartCoroutine ("CRRoundStart"); } IEnumerator CRRoundStart () { while (_shieldPanel.gameObject.activeSelf) { yield return null; } yield return new WaitForSeconds (0.5f); RoundStart (); yield return null; } public void AbilityClick (AbilityShell ability) { _currentActiveAbility = ability; } public void CardClick (BattleCardShell card) { if (_currentActiveAbility == null) { // Debug.Log (1); if (CheckPlayerCardActivity (card)) { { // Debug.Log (2); if (_currentActiveCard == card) { // Debug.Log (3); _currentActiveCard.Hide (); _currentActiveCard = null; } else { // Debug.Log (4); if (_currentActiveCard != null) { _currentActiveCard.Hide (); } _currentActiveCard = card; card.Show (); } } } else { // Debug.Log (5); card.Deny (); } } else { // Debug.Log(6); bool canCast = false; switch (_currentActiveAbility.ability.targetType) { case TargetType.All: { canCast = true; break; } case TargetType.Friend: { if (card.shellType == ShellType.Player) { canCast = true; } break; } case TargetType.Enemy: { // Debug.Log(7); if (card.shellType == ShellType.Enemy) { canCast = true; } break; } case TargetType.Self: { if (card == _currentActiveCard) { canCast = true; } break; } default: break; } if (canCast) { // Debug.Log(8); if (_currentActiveAbility.ability.targetArea == TargetArea.Area) {//If ability is AOE,cast at the middle of enemies; _currentActiveCard.CastAbility (_currentActiveAbility.ability, _enemyCardShellSet [0].battleCard); } else { _currentActiveCard.CastAbility (_currentActiveAbility.ability, card.battleCard); } // _currentActiveAbility.UpdateCDTimer(); _currentActiveAbility = null; _currentActiveCard = null; CheckPlayerCardShellSetActivity (); } else { card.Deny (); } } } public void BackgroundClick () { if (_currentActiveCard != null) { _currentActiveCard.Hide (); _currentActiveCard = null; _currentActiveAbility = null; } } public void BattleComplete () { _battleCompleteDisplayer.DisplayBattleComplete (_levelData, _trophyCards); } void BattleAbort () { _sceneFader.BeginFading (() => { gameObject.SetActive (false); _sceneFader.ExitFading ();}); } public void Drop(BattleCardShell shell) { if (shell.shellType == ShellType.Enemy) { if(shell.battleCard.concreteCard.dropRate>=Random.Range(0.001f,100f)){ _trophyCards.Add (shell.battleCard.concreteCard); _trophyAmount.text=_trophyCards.Count.ToString(); GameObject dropCardIcon =Instantiate( _cardBGIconPrefab,shell.transform.position,Quaternion.identity) as GameObject; dropCardIcon.transform.parent=transform; dropCardIcon.transform.localScale=Vector3.one*0.01f; Destroy(dropCardIcon,2f); } } } // public void ShowCardDetail (BattleCard battleCard) // { // _cardDetailDisplayer.DisplayCardDetail (battleCard); // } } <file_sep>/Assets/Scripts/Unuse/Layers.cs using UnityEngine; using System.Collections; public class Layers { public static int NGUI=8; } <file_sep>/Assets/Scripts/Card/ConcreteCard.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Reflection; /// <summary> /// A concrete card based on an particular role with specilized level and rarity. /// This card are used as battle levels' enemies or player storage which is used for battle. /// </summary> public class ConcreteCard { #region Instance member protected BaseCard _baseCard; protected Texture _cardSprite; protected int _strength, _agility, _magic, _maxHealth, _maxMana, _physicalDefense, _magicalDefense, _physicalCriticalChance, _magicalCriticalChance, _physicalDamage, _magicalDamage, _healthResilience, _magicResilience, _evasion, _price, _maxLevel, /// <summary> /// Level should be positive /// </summary> _level, _experience; /// <summary> /// Active abilities /// </summary> protected List<Ability> _abilities; #endregion #region Properties public int id { get{return _baseCard.id;} } public string name { get{return _baseCard.name;} } public string description { get{return _baseCard.description;} } /// <summary> /// Max health,physical damage,physical defense and health resilience are changed along with strength /// </summary> /// <value>The strength.</value> public int strength { get{return _strength;} set{ _strength=value; _maxHealth=_baseCard.maxHealthBase+(int)(_strength*BaseCard.rate_strength_maxHealth); _physicalDamage=_baseCard.physicalDamageBase+(int)(_strength*BaseCard.rate_strength_physicalDamage); _physicalDefense=_baseCard.physicalDefenseBase+(int)(_strength*BaseCard.rate_strength_physicalDefense); _healthResilience=_baseCard.healthResilienceBase+(int)(_strength*BaseCard.rate_strength_healthResilience); } } /// <summary> /// Physical defense ,physical critical chance and evasion are changed along with agility /// </summary> /// <value>The agility.</value> public int agility { get{return _agility;} set{ _agility=value; _physicalDefense=_baseCard.physicalDefenseBase+(int)(_agility*BaseCard.rate_agility_physicalDefense); _physicalCriticalChance=_baseCard.physicalCriticalChanceBase+(int)(_agility*BaseCard.rate_agility_physicalCriticalChance); _evasion=_baseCard.evasionBase+(int)(_agility*BaseCard.rate_agility_evasion); } } /// <summary> /// Max mana,magical defense,magical critical chance,magical damage and magic resiliense are changed along with magic /// </summary> /// <value>The magic.</value> public int magic { get{return _magic;} set{ _magic=value; _maxMana=_baseCard.maxManaBase+(int)(_magic*BaseCard.rate_magic_maxMana); _magicalDefense=_baseCard.magicalDefenseBase+(int)(_magic*BaseCard.rate_magic_magicalDefense); _magicalCriticalChance=_baseCard.magicalCriticalChanceBase+(int)(_magic*BaseCard.rate_magic_magicalCriticalChance); _magicalDamage=_baseCard.magicalDamageBase+(int)(_magic*BaseCard.rate_magic_magicalDamage); _magicResilience=_baseCard.magicResilienceBase+(int)(_magic*BaseCard.rate_magic_magicResilience); } } public int maxHealth { get{return _maxHealth;} } public int maxMana { get{return _maxMana;} } public int magicalDefense { get{return _magicalDefense;} } public int magicalCriticalChance { get{return _magicalCriticalChance;} } public int magicalDamage { get{return _magicalDamage;} } public int healthResilience { get{return _healthResilience;} } public int magicResilience { get{return _magicResilience;} } public int evasion { get{return _evasion;} } public float dropRate { get{return _baseCard.drapRate;} } public int price { get{return _price;} } public int maxLevel { get{return _maxLevel;} } public int physicalDamage { get{return _physicalDamage;} // set{_physicalDamage=value;} } public int physicalCriticalChance { get{return _physicalCriticalChance;} // set{_physicalCriticalChance=value;} } public int physicalDefense { get{return _physicalDefense;} // set{_physicalDefense=value;} } public Rarity rarity { get{return _baseCard.rarity;} } /// <summary> /// The increase of experience may affect level value. /// </summary> /// <value>The experience.</value> public int experience { get {return _experience;} set{ if(value<_experience) { Debug.Log("Decrease of experience is forbidden"); throw new System.ArgumentException("experience"); } _experience=value; int newLevel=level; while(newLevel<maxLevel&&_experience>BaseCard._experienceTable[newLevel-1]) { _experience-=BaseCard._experienceTable[newLevel-1]; newLevel++; } if(_experience>BaseCard._experienceTable[newLevel-1]) {//When experience exceed the max,it equals the max _experience=BaseCard._experienceTable[newLevel-1]; } level=newLevel; } } /// <summary> /// Strength,agility and magic are changed along with level /// </summary> /// <value>The level.</value> public int level{ get{return _level;} set{ _level=value; strength = _baseCard.strengthBase +(int)(_level * _baseCard.strengthGrowth); agility = _baseCard.agilityBase + (int)(_level * _baseCard.agilityGrowth); magic = _baseCard.magicBase + (int)(_level * _baseCard.magicGrowth); } } public BaseCard baseCard { get{return _baseCard;} } public List<Ability> abilities { get{return _abilities;} } public Texture roleTexture { get{return _cardSprite;} } #endregion public ConcreteCard() { } public ConcreteCard(BaseCard baseCard,int level,List<Ability> abilities,Texture cardSprite) { if (baseCard == null) { throw new System.ArgumentNullException ("baseCard"); } _baseCard = baseCard; _maxLevel = BaseCard._maxLevelTable [(int)rarity]; if (level > _maxLevel || level < 1) { Debug.Log("The level of card should not be less than 1 nor be larger than card's max level."); throw new System.ArgumentException("level"); } this.level = level; if (abilities == null) { throw new System.ArgumentNullException ("abilities"); } _abilities = abilities; _price=baseCard.price; _cardSprite=cardSprite; } } <file_sep>/Assets/Scripts/Card/Abitity/Aura.cs using UnityEngine; using System.Collections; public class Aura : DurativeState { public Aura (int id,string name,BattleCard from, AbilityType abilityType,int interval) { _id=id; _name=name; } public override void RoundStart () { throw new System.NotImplementedException (); } public override void RoundEnd () { throw new System.NotImplementedException (); } public override void Clear () { throw new System.NotImplementedException (); } } <file_sep>/Assets/Scripts/Card/Abitity/AbilityFactory.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class AbilityFactory { private static AbilityFactory _instance; private Dictionary <int,AbilityBase> _BaseAbilityTable; private Dictionary<string ,int> _BaseAbilityIdTable; private Dictionary<string,Texture> _abilityIconTable; private AbilityFactory () { LoadAbilityIcon(); LoadAbilities(); } public static AbilityFactory GetAbilityFactory() { if(_instance==null) _instance=new AbilityFactory(); return _instance; } void LoadAbilities () { _BaseAbilityTable = new Dictionary<int, AbilityBase> (); _BaseAbilityIdTable=new Dictionary<string, int>(); TextAsset[] textAssets = Resources.LoadAll<TextAsset> (ResourcesFolderPath.json_ability); foreach (TextAsset tAsset in textAssets) { string jsonString = tAsset.text; var dict = MiniJSON.Json.Deserialize (jsonString) as Dictionary<string,object>; Dictionary<string,object> abilitiesInfo = dict ["ability"] as Dictionary<string,object>; foreach (string abilityName in abilitiesInfo.Keys) { //Detect existence of cardName if (_BaseAbilityIdTable.ContainsKey (abilityName)) { Debug.Log (string.Format ("Ability name has existed -name:{0} in folder: 'Resources/Json/Ability/{1}'", abilityName, tAsset.name)); throw new System.Exception (string.Format ("Ability name has existed -name:{0} in folder: 'Resources/Json/Card/{1}'", abilityName, tAsset.name)); } KeyValuePair<string,Dictionary<string,object>> abilityInfo = new KeyValuePair<string, Dictionary<string, object>> (abilityName, abilitiesInfo [abilityName]as Dictionary<string,object>); AbilityBase abilityBase; try { abilityBase = AbilityBase.GeneAbilityBase (abilityInfo); } catch (System.Exception e) { Debug.Log (string.Format ("Fail to Generate AbilityBase via ability data that named:{0}", abilityName)); throw e; } int id = abilityBase.id; //Detect existence of baseCard's id if (_BaseAbilityTable.ContainsKey (id)) { Debug.Log (string.Format ("Ability id has existed -name:{0} in folder: 'Resources/Json/Ability/{1}'", abilityName, tAsset.name)); throw new System.Exception (string.Format ("Ability id has existed -name:{0} in folder: 'Resources/Json/Ability/{1}'", abilityName, tAsset.name)); } //Check the validity of ability if (!CheckAbilityValidity (abilityBase)) { Debug.Log (string.Format ("Failure to pass ability validity test about ability named :{0} in folder: 'Resources/Json/Ability/{1}'", abilityName, tAsset.name)); throw new System.Exception (string.Format ("Failure to pass ability validity test about ability named :{0} in folder: 'Resources/Json/Ability/{1}'", abilityName, tAsset.name)); } _BaseAbilityIdTable.Add (abilityName, id); _BaseAbilityTable.Add (id, abilityBase); } } } bool CheckAbilityValidity (AbilityBase abilityBase) { bool bPass = true; bPass &= AbilityCastStatic.HasAbilityCast (abilityBase.abilityCast); // bPass &= EffectCardStatic.HasEffectCard (abilityBase.effectCard); foreach (string variableName in abilityBase.variables) { bPass &= AbilityVariable.HasVariableString (variableName); } return bPass; } void LoadAbilityIcon() { _abilityIconTable=new Dictionary<string, Texture>(); Texture[] icons=Resources.LoadAll<Texture>(ResourcesFolderPath.textures_ability_icon); for (int i = 0; i < icons.Length; i++) { _abilityIconTable.Add (icons[i].name,icons[i]); } } public Ability GeneAbility (int abilityId, int level=1) { return GeneAbility(_BaseAbilityTable[abilityId],level); } public Ability GeneAbility(string abilityName,int level=1) { return GeneAbility(_BaseAbilityIdTable[abilityName],level); } Ability GeneAbility(AbilityBase abilityBase,int level=1) { if(level>abilityBase.maxLevel) { Debug.Log(string.Format("Level of ability '{0}' should not be larger than maxLevel",abilityBase.name)); throw new System.ArgumentException(string.Format("Level of ability '{0}' should not be larger than maxLevel",abilityBase.name)); } string iconName=abilityBase.icon; if(iconName==null) { iconName=abilityBase.name; } Texture icon=_abilityIconTable[iconName]; AbilityCast abilityCast=AbilityCastStatic.GetAbilityCast( abilityBase.abilityCast); // EffectCard effectCard=EffectCardStatic.GetEffectCard(abilityBase.effectCard); Dictionary<string,int > variables=new Dictionary<string, int>(); List<string> variableName=abilityBase._variables; List<int> variableValue=abilityBase._variableValueTable[level-1]; for (int i = 0; i < variableName.Count; i++) { variables.Add(variableName[i],variableValue[i]); } return new Ability(abilityBase,icon,level,abilityCast,variables); } } <file_sep>/Abandon/levelGateRelative/LevelInfo.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public enum StarNum{ ZERO=0, ONE,TWO,TRHEE }; public class LevelInfo:MonoBehaviour { //Level name string _name; StarNum _starNum; bool _unlocked; int _index; private LevelData _levelData; public LevelData leveldata { get{return _levelData;} } public bool unlocked { get{return _unlocked;} } void Awake() { LoadFromJson (); LoadFromPlayerPrefs (); } /// <summary> /// Initializes a new instance of the <see cref="Level_editMode"/> class. /// </summary> /// <param name="name">Name.</param> public void Init(string name) { _name = name; _starNum = StarNum.ZERO; _unlocked = false; } public string levelName{ get{ return _name; } set{ _name=value; } } public void Unlock() { _unlocked = true; } public void GainStar(StarNum starNum) { if (starNum > _starNum) _starNum = starNum; } public int GetLevelIndex() { return _index; } public void SetLevelIndex(int index) { _index = index; } public int GetStarNum() { return (int)_starNum; } public void LoadFromJson() { TextAsset text = Resources.Load <TextAsset>(string.Format("{0}/level_{1:000}",ResourcesFolderPath.json_level ,_index+1)); string json = text.text; Dictionary<string ,object> dict = MiniJSON.Json.Deserialize (json)as Dictionary<string,object>; _levelData=LevelData.GetLevelData(dict["level"]as Dictionary<string,object>); // Debug.Log ("experience:"+_levelData.experience); // Debug.Log ("level:"+_levelData.level); // foreach (var item in _levelData.enemiesId) // Debug.Log (item); // foreach (var item in _levelData.bossIndices) { // Debug.Log(item); // } } public void LoadFromPlayerPrefs() {} } <file_sep>/Assets/Scripts/Player/BagSlot.cs using UnityEngine; using System.Collections; public class BagSlot : MonoBehaviour { public UISprite _Icon; public UILabel _name, _level, _price, _experience; public UIToggle _sell; public UISlider _experienceSlider; public UISprite _slotEdge, _background; public UIWidget _slotBody; private ConcreteCard _concreteCard; private BagManagement _bagManagement; private float _bgAlpha = 0.75f; private float _clickTiming = 0.3f, _clickTimer = 0, _hoverTiming = 2f, _hoverTimer = float.NegativeInfinity; public ConcreteCard concreteCard { get{ return _concreteCard;} } public UIWidget slotBody { get{ return _slotBody;} } public bool isSell { get; set; } void Start () { _bagManagement = GetComponentInParent<BagManagement> (); _sell.instantTween = false; } // Update is called once per frame void Update () { _clickTimer += Time.deltaTime; _hoverTimer += Time.deltaTime; if (_hoverTimer > _hoverTiming) { _bagManagement.SlotShowDetail (this); _hoverTimer = float.NegativeInfinity; } } void OnClick () { if (_clickTimer > _clickTiming) { _bagManagement.SlotClick (this); _clickTimer = 0f; } } void OnHover (bool isOver) { if (isOver) { _hoverTimer = 0; } else { _hoverTimer = float.NegativeInfinity; } if (isOver) { _background.alpha = 1f; } else { _background.alpha = 0.66f; } } public void LoadConcreteCard (ConcreteCard card) { _concreteCard = card; _Icon.spriteName = card.name; _name.text = card.name; _level.text = "Lv." + card.level.ToString (); _price.text = card.price.ToString (); _experience .text = card.experience.ToString () + "/" + BaseCard.experienceTable [card.level - 1]; _sell.value = false; _experienceSlider.value = card.experience / (float)BaseCard._experienceTable [card.level - 1]; _slotEdge.color = Color.white; _background.color = RarityColorStatic.rarityColors [(int)card.rarity]; _background.alpha = _bgAlpha; Deselect (); } public void UpdateData() { _level.text = "Lv." + _concreteCard.level.ToString (); _experience .text = _concreteCard.experience.ToString () + "/" + BaseCard.experienceTable [_concreteCard.level - 1]; _experienceSlider.value = _concreteCard.experience / (float)BaseCard._experienceTable [_concreteCard.level - 1]; } public void Refresh () { _level.text = "Lv." + _concreteCard.level.ToString (); _price.text = _concreteCard.price.ToString (); _experience .text = _concreteCard.experience.ToString () + "/" + BaseCard._experienceTable [_concreteCard.level - 1].ToString (); _experienceSlider.value = _concreteCard.experience / (float)BaseCard._experienceTable [_concreteCard.level - 1]; } public void SetSell () { isSell = _sell.value; } public void Select () { _slotEdge.color = Color.white; } public void Deselect () { _slotEdge.color = Color.black; } } <file_sep>/Abandon/levelGateRelative/StarCounter/StarCounterLayerControl.cs using UnityEngine; using System.Collections; public class StarCounterLayerControl : MonoBehaviour { public BigStarControl _bigStar; StarCounterControl _starCounter; void Awake() { _bigStar = GetComponentInChildren<BigStarControl> (); _starCounter = GetComponentInChildren<StarCounterControl> (); } public void GainStar() { _starCounter.GainStar (); } } <file_sep>/Assets/Scripts/DynamicTextAdmin.cs using UnityEngine; using System.Collections; using Holoville.HOTween; public class DynamicTextAdmin : MonoBehaviour { public UILabel _textPrefab; public float _movementDuration=1f; public Vector3 _movementDirection; public Color _textColor=Color.blue; //Range(0,1). [Range(0f,1f)] public float _fadeOutTiming=0.8f; private Transform _activeSet,_deactiveSet; void Awake() { _activeSet=transform.GetChild(0); _deactiveSet=transform.GetChild(1); } public void DynamicText(Vector3 startPosition,string text) { DynamicText(startPosition,text,_movementDuration,_movementDirection,_textPrefab,_textColor); } public void DynamicText(Vector3 startPosition,string text,Color color) { DynamicText(startPosition,text,_movementDuration,_movementDirection,_textPrefab,color); } public void DynamicText(Vector3 startPosition,string text,float duration,UILabel sample) { DynamicText(startPosition,text,duration,_movementDirection,sample,_textColor); } public void DynamicText(Vector3 startPosition,string text,float duration, Vector3 direction,UILabel sample) { DynamicText(startPosition,text,duration,direction,sample,_textColor); } public void DynamicText(Vector3 startPosition,string text,float duration, Vector3 direction,UILabel sample,Color color) { if(text==null||text=="") { Debug.Log("Please set text's content"); throw new System.ArgumentNullException("Please set text's content"); } if(duration==0) { duration=_movementDuration; } if(sample==null) { sample=_textPrefab; } duration=Random.Range(duration-0.25f,duration+0.25f); startPosition=startPosition+Random.insideUnitSphere*0.5f; ActivateText(startPosition,text,duration,color,direction,sample); } void ActivateText(Vector3 startPosition,string text,float duration, Color color,Vector3 direction,UILabel sample) { GameObject textGO; if(_deactiveSet.childCount>0) { textGO=_deactiveSet.GetChild(0).gameObject; } else { textGO=(Instantiate(sample)as UILabel).gameObject; } textGO.transform.parent=_activeSet; UILabel label=textGO.GetComponent<UILabel>(); textGO.transform.position=startPosition; label.text=text; label.gradientTop=color; label.alpha=1; // label.color=color; textGO.SetActive(true); HOTween.To(textGO.transform,duration,new TweenParms().Prop("position",textGO.transform.position+direction) .Ease(EaseType.EaseOutQuad).OnComplete(delegate() { textGO.SetActive(false); textGO.transform.parent=_deactiveSet; })); StartCoroutine(TextFadeOut(duration*_fadeOutTiming,duration*(1-_fadeOutTiming),label)); } IEnumerator TextFadeOut(float startTime,float duration,UILabel label) { yield return new WaitForSeconds(startTime); HOTween.To(label,duration,new TweenParms().Prop("alpha",0).Ease(EaseType.Linear)); } } <file_sep>/Assets/Scripts/PlayerPrefKeys.cs using UnityEngine; using System.Collections; public static class PlayerPrefKeys { public static string player="player"; } <file_sep>/Assets/Scripts/CardDetailDisplayer.cs using UnityEngine; using System.Collections; using System.Reflection; using System; using Holoville.HOTween; public class CardDetailDisplayer : MonoBehaviour { public UILabel _label_name,_label_level,_label_hp,_label_mp,_label_description; public Renderer _renderer_frame,_renderer_role; public AbilityDisplayer[] _abilitiesDisplayer; public GameObject _labelContainer; public Material[] _shellMaterials; public float _showTime; private UILabel[] _attrLabels; private Type _typeofBattleCard; private PropertyInfo[] _propertiesOfBattleCard; private Vector3 _position; void Awake() { _position=transform.position; _attrLabels = _labelContainer.GetComponentsInChildren<UILabel> (); _typeofBattleCard = typeof(BattleCard); _propertiesOfBattleCard=new PropertyInfo[_attrLabels.Length]; for (int i = 0; i < _attrLabels.Length; i++) { _propertiesOfBattleCard[i]=_typeofBattleCard.GetProperty(_attrLabels[i].name); } } void Start() { gameObject.SetActive(false); foreach (var item in _abilitiesDisplayer) { item.gameObject.SetActive(false); } } void OnClick() { HideCardDetail(); } public void DisplayCardDetail(BattleCard card) { string cardName = card.concreteCard.name; cardName= string.Join ("\n", cardName.Split (new char[]{' '}, System.StringSplitOptions.RemoveEmptyEntries)); _label_name.text = cardName; _label_level.text = card.concreteCard.level.ToString(); _label_hp.text = card.health.ToString(); _label_mp.text = card.mana.ToString(); _label_description.text = card.concreteCard.description; for (int i = 0; i < _attrLabels.Length; i++) { _attrLabels[i].text=_propertiesOfBattleCard[i].GetValue(card,null).ToString(); } _renderer_frame.material = _shellMaterials [(int)card.concreteCard.rarity]; _renderer_role.material.mainTexture = card.concreteCard.roleTexture; for (int i = 0; i < card.abilities.Count&&i<_abilitiesDisplayer.Length; i++) { _abilitiesDisplayer[i].LoadAbility(card.abilities[i]); } gameObject.SetActive (true); HOTween.To(transform,_showTime,new TweenParms().Prop("position",new Vector3(6f,0,0),true).Ease(EaseType.Linear)); // Debug.Log(card.magicalDamage+"|"+card.concreteCard.baseCard.magicalDamageBase+"|"+BaseCard.rate_magic_magicalDamage); } public void HideCardDetail() { HOTween.To (transform,_showTime*(transform.position-_position).magnitude/6f,new TweenParms().Prop("position",_position).Ease(EaseType.Linear).OnComplete( delegate() { foreach (var item in _abilitiesDisplayer) { item.gameObject.SetActive(false); } gameObject.SetActive (false); })); } } <file_sep>/Abandon/0827/SetAbilityCast.cs using UnityEngine; using System.Collections; public class SetAbilityCast : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } [ContextMenu("SetCastMethod")] public void SetCastMethod() { BaseAbility ba = GetComponent<BaseAbility> (); } } <file_sep>/Abandon/0827/PositiveAbilityBase.cs using UnityEngine; using System.Collections; public class PositiveAbilityBase : AbilityBase { } <file_sep>/Assets/Scripts/Card/Abitity/Ability.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class Ability { #region Instance members private Texture _icon; private AbilityBase _baseAbility; private int _mana; private int _cooldown; private Dictionary<string,int> _variableValues; private int _level; // private int _interval,_duration; private AbilityCast _abilityCast; // private EffectCard _effectCard; #endregion #region Properties public string name { get{ return _baseAbility.name;} } public Texture icon { get{return _icon;} } public int mana { get{ return _mana;} } public int cooldown { get{ return _cooldown;} } public string description { get{ return _baseAbility.description;} } public TargetType targetType { get{ return _baseAbility.targetType;} } public TargetArea targetArea { get{ return _baseAbility.targetArea;} } public int level { get{ return _level;} set { if (value < 1 || value > maxLevel) { Debug.Log (string.Format ("Value illegal when set level of ability '{0}'", name)); throw new System.ArgumentException (string.Format ("Value illegal when set level of ability '{0}'", name)); } _level = value; List<int> variableValue = _baseAbility._variableValueTable [_level - 1]; for (int i = 0; i < _baseAbility.variables.Count; i++) { _variableValues [_baseAbility._variables [i]] = variableValue [i]; } } } public int maxLevel { get{ return _baseAbility.maxLevel;} } public AbilityBase baseAbility { get{ return _baseAbility;} } public AbilityType abilityType { get{ return _baseAbility.abilityType;} } public string targetAttr { get{ return _baseAbility.targetAttr;} } public AbilityCast abilityCast { get{return _abilityCast;} } // public EffectCard effectCard // { // get{return _effectCard;} // } #endregion public int GetValue (string variableName) { return _variableValues [variableName]; } public Ability (AbilityBase abilityBase,Texture icon, int level, AbilityCast abilityCast, Dictionary<string,int> variables) { _baseAbility = abilityBase; _icon=icon; _level = level; _abilityCast = abilityCast; // _effectCard=effectCard; _variableValues = variables; if (_variableValues.ContainsKey (AbilityVariable .mana)) { _mana = _variableValues [AbilityVariable .mana]; } else { _mana = 0; } if (_variableValues.ContainsKey (AbilityVariable.cooldown)) { _cooldown = _variableValues [AbilityVariable.cooldown]; } else { _cooldown = 0; } } public string GetDescription() { return ""; } } <file_sep>/Abandon/BossControl.cs using UnityEngine; using System.Collections; public class BossControl : MonoBehaviour { int _health; BattleControl _battleController; float _showDetailTimer; float _timeToShowDetail = 2f; float _clickTimer; float _clickInterval=0.5f; bool _alive; // Use this for initialization void Awake() { _alive = true; _battleController=GameObject.FindGameObjectWithTag(Tags.battle).GetComponent<BattleControl>(); _health=3; _showDetailTimer = 0f; _clickTimer = 0f; } // Update is called once per frame void Update () { if (_alive) { _clickTimer += Time.deltaTime; if (_health <= 0){ _battleController.BattleComplete (); _alive=false; } } } void OnMouseOver() { _showDetailTimer += Time.deltaTime; if (_showDetailTimer > _timeToShowDetail) _battleController.ShowBossDetail (true); } void OnMouseExit() { _showDetailTimer = 0f; _battleController.ShowBossDetail (false); } public void MouseClick() { if (_clickTimer > _clickInterval) { _clickTimer=0f; _battleController.BossClick (); } } public void Showoff(){ Debug.Log("I'm boss"); } public void Injure(int value) { _health-=4; } } <file_sep>/Assets/Scripts/GameController/SceneFade.cs using UnityEngine; using System.Collections; public delegate void FadeEvent(); public class SceneFade : MonoBehaviour { float _fadeTime=1.5f; bool _toLight=false; UITexture fader; FadeEvent _fadeInEvent,_fadeOutEvent; // Use this for initialization void Awake(){ fader = GetComponentInChildren<UITexture> (); fader.alpha = 1f; } // Update is called once per frame void Update () { if (_toLight) FadeToLight (); else FadeToDark (); } public void BeginFading(FadeEvent fadeEvent=null) { _toLight = false; gameObject.SetActive (true); _fadeInEvent = fadeEvent; } void FadeToDark() { fader.alpha = Mathf.Lerp (fader.alpha, 1f, _fadeTime * Time.deltaTime); if (fader.alpha > 0.98) { if(_fadeInEvent!=null){ _fadeInEvent(); _fadeInEvent=null; } fader.alpha = 1f; } } public void ExitFading(FadeEvent fadeEvent=null) { _toLight = true; _fadeOutEvent = fadeEvent; } void FadeToLight() { fader.alpha = Mathf.Lerp (fader.alpha, 0f, _fadeTime * Time.deltaTime); if (fader.alpha < 0.02) { fader.alpha=0; if(_fadeOutEvent!=null){ _fadeOutEvent(); _fadeOutEvent=null; } gameObject.SetActive(false); } } public bool IsOpeque() { return fader.alpha==1; } } <file_sep>/Assets/Scripts/Card/Abitity/TargetType.cs using UnityEngine; using System.Collections; public enum TargetType { Friend,Enemy,Self,All }; <file_sep>/Abandon/0827/DurativeAbilityMonitor.cs using UnityEngine; using System.Collections; public class DurativeAbilityMonitor { ConcreteCard _from,to; DurativeAbilityBase _ability; public static DurativeAbilityMonitor GeneMonitor(ConcreteCard from,ConcreteCard to,DurativeAbilityBase ability) { return null; } } <file_sep>/Assets/Scripts/Card/BattleCardShell.cs using UnityEngine; using System.Collections; using Holoville.HOTween; using System.Collections.Generic; public class BattleCardShell : MonoBehaviour { #region Static fields static float _toggleDistance = 0.3f; static float _clickInterval = 0.5f; static float _getHurtTime = 0.2f; static float _castTime = 0.4f; static float _shellRotateTime = 1f; #endregion #region Instancial fields private BattleControl _battleController; public ShellType _shellType; public GameObject _roleMesh; public GameObject _shellMesh; public UILabel _label_hp, _label_mp; public AbilityShell[] _firstRowAbilityShells; public AbilityShell[] _secondRowAbilityShells; private BattleCard _battleCard; Vector3 _originalLocalPosition; /// <summary> ///If the card has been used,this shell is vacant,When reload a new card to this battle card shell "vacant" is false; /// </summary> private bool _vacant; /// <summary> /// Every card has a chance to cast an ability when a new round started. /// If a card has casted an ability,it's 'hasCast' =true. /// </summary> private bool _hasCast; private bool _displayed; private float _displayTimer = 0f; private BattleCardShell[] _shellQueue; private static float _showTime = 0.3f; private static float _displayTime = 2f; private static float _firstRowAbilityShowTime = 0.2f; private static float _secondRowAbilityShowTime = 0.35f; private static float _firstRowAbilityShowDistance = 0.8f; private static float _secondRowAbilityShowDistance = 1.4f; private static float _deadTime = 0.5f; private static int _abilityCountPerRow = 3; float _clickTimer = 0f; #endregion #region Properties public Vector3 originalLocalPosition { get{ return _originalLocalPosition;} } public bool vacant { get{ return _vacant;} // set{_vacant=value;} } public bool hasCast { get{ return _hasCast;} } public BattleCard battleCard { get{ return _battleCard;} } public BattleControl battleController { get{ return _battleController;} } public ShellType shellType { get{ return _shellType;} } public BattleCardShell[] shellQueue { get{ return _shellQueue;} } #endregion void Awake () { _battleController = GetComponentInParent<BattleControl> (); _originalLocalPosition = transform.localPosition; _battleCard = GetComponent<BattleCard> (); _shellQueue = (_shellType == ShellType.Player) ? _battleController._playerCardShellSet : _battleController._enemyCardShellSet; _vacant = true; _displayed = false; } // Update is called once per frame void Update () { _clickTimer += Time.deltaTime; _displayTimer += Time.deltaTime; if (_displayed && _displayTimer > _displayTime) { _battleController.cardDetailDisplayer.DisplayCardDetail (_battleCard); _displayTimer = -1000f; } } // void OnMouseOver() // { // Debug.Log("on"); // _showCardTimer+=Time.deltaTime; // } void OnHover (bool IsOver) { _displayed = IsOver; if (_displayed) { _displayTimer = 0f; } } void OnClick () { if (_clickTimer > _clickInterval) { MouseClick (); _clickTimer = 0f; } } void OnTriggerEnter (Collider other) { AbilityEntityShell abilityES = other.GetComponentInParent<AbilityEntityShell> (); if (abilityES != null && abilityES.abilityEntity.targetCard == _battleCard) { _battleCard.cardEffected (abilityES); } } void MouseClick () { // Debug.Log ("BattleCardShell click : " + name); _battleController.CardClick (this); } public void Show () { HOTween.To (transform, _showTime, new TweenParms ().Prop ("localPosition", _originalLocalPosition + new Vector3 (0, _toggleDistance, 0)).Ease (EaseType.EaseInOutQuad) .OnStart (delegate() { _battleController.shieldPanel.Activate (); }).OnComplete (delegate() { foreach (var item in _firstRowAbilityShells) { if (item.vacant == false) { item.Show (_firstRowAbilityShowDistance, _firstRowAbilityShowTime); } } foreach (var item in _secondRowAbilityShells) { if (item.vacant == false) { item.Show (_secondRowAbilityShowDistance, _secondRowAbilityShowTime); } } _battleController.shieldPanel.Deactivate (); } )); } public void Hide () { if (_battleCard.concreteCard.abilities.Count <= _abilityCountPerRow) {//Only one row of 'AbilityShell'. foreach (var item in _firstRowAbilityShells) { if (item.vacant == false) { item.Hide (_firstRowAbilityShowTime); } } StartCoroutine (HideAfterTime (_firstRowAbilityShowTime)); } else {//Have two rows of 'AbilityShell'. foreach (var item in _secondRowAbilityShells) { if (item.vacant == false) { item.Hide (_secondRowAbilityShowTime); } } StartCoroutine (HideFirstRowAbility (_secondRowAbilityShowTime - _firstRowAbilityShowTime)); StartCoroutine (HideAfterTime (_secondRowAbilityShowTime)); } } void HideAbilitiesOnly () { if (_battleCard.concreteCard.abilities.Count <= _abilityCountPerRow) {//Only one row of 'AbilityShell'. foreach (var item in _firstRowAbilityShells) { if (item.vacant == false) { item.Hide (_firstRowAbilityShowTime); } } } else {//Have two rows of 'AbilityShell'. foreach (var item in _secondRowAbilityShells) { if (item.vacant == false) { item.Hide (_secondRowAbilityShowTime); } } StartCoroutine (HideFirstRowAbility (_secondRowAbilityShowTime - _firstRowAbilityShowTime)); } } IEnumerator HideAfterTime (float time) { yield return new WaitForSeconds (time); HOTween.To (transform, _showTime, new TweenParms ().Prop ("localPosition", _originalLocalPosition).Ease (EaseType.EaseInOutQuad) .OnStart (delegate() { _battleController.shieldPanel.Activate (); }).OnComplete (delegate() { _battleController.shieldPanel.Deactivate (); })); yield return null; } IEnumerator HideFirstRowAbility (float time) { yield return new WaitForSeconds (time); foreach (var item in _firstRowAbilityShells) { if (item.vacant == false) { item.Hide (_firstRowAbilityShowTime); } } // StartCoroutine (HideAfterTime (_firstRowAbilityShowTime)); yield return null; } public bool CardInteraction (Component other) { if (this == other) return true; // if(other.GetType()==typeof(BattleCardShell)) // { // Debug.Log("action deny"); // return false; // } // else if(other.GetType()==typeof(BossControl)) // { // Debug.Log("attack boss"); // BossControl boss=other as BossControl; // boss.Injure(3); // _vacant=true; // gameObject.SetActive(false); // return true; // } return false; } public void Clear () { _vacant = true; gameObject.SetActive (false); _battleCard.Clear (); foreach (var item in _firstRowAbilityShells) { item.Clear (); item.gameObject.SetActive (false); } foreach (var item in _secondRowAbilityShells) { item.Clear (); item.gameObject.SetActive (false); } } public void LoadCard (ConcreteCard concreteCard) { _battleCard.LoadConcreteCard (concreteCard); _vacant = false; _hasCast = false; _shellMesh.renderer.material = _battleController._shellMaterials [(int)concreteCard.rarity]; _roleMesh.renderer.material.mainTexture = concreteCard.roleTexture; _label_hp.text = _battleCard.health.ToString (); _label_mp.text = _battleCard.mana.ToString (); _label_hp.alpha = 0; _label_mp.alpha = 0; transform.localRotation = Quaternion.Euler (new Vector3 (0, 180f, 0)); if (_shellType == ShellType.Player) {//Load 'AbilityShell' if (_battleCard.abilities.Count <= _abilityCountPerRow) { for (int i = 0; i < _battleCard.abilities.Count; i++) { _firstRowAbilityShells [i].LoadAbility (_battleCard.abilities [i]); } } else { int index = 0; for (int i = 0; i < _abilityCountPerRow; i++) { _secondRowAbilityShells [i].LoadAbility (_battleCard.abilities [index]); index++; } for (int i = 0; i < _abilityCountPerRow&&index<_battleCard.abilities.Count; i++) { _firstRowAbilityShells [i].LoadAbility (_battleCard.abilities [index]); index++; } } } transform.localPosition = _originalLocalPosition; gameObject.SetActive (true); } public void TurnToFront () { HOTween.To (transform, _shellRotateTime, new TweenParms ().Prop ("localRotation", Quaternion.identity).Ease (EaseType.Linear).OnStart (delegate() { _battleController.shieldPanel.Activate (); }).OnComplete (delegate() { _battleController.shieldPanel.Deactivate (); HOTween.To (_label_hp, 0.5f, new TweenParms ().Prop ("alpha", 1f).Ease (EaseType.Linear)); HOTween.To (_label_mp, 0.5f, new TweenParms ().Prop ("alpha", 1f).Ease (EaseType.Linear)); })); } public void CardRoleDead () { HOTween.To (transform, _deadTime, new TweenParms ().Prop ("localScale", Vector3.one*0.001f).Ease (EaseType.Linear).OnStart (()=>{_battleController.shieldPanel.Activate();}).OnComplete (()=>{ if(_shellType== ShellType.Enemy){ _battleController.Drop(this); } Clear(); _battleController.CheckVacantShell (); _battleController.shieldPanel.Deactivate(); })); } public void RoundStart () { _battleCard.health += _battleCard.healthResilience; _battleCard.mana += _battleCard.magicResilience; _hasCast = false; foreach (var item in _battleCard.abilities) { _battleCard.abilityCDTable[item]++; } } public void RoundEnd () { } public void HighLight () { } public bool HasAvailableAbility () { foreach (var item in _battleCard.abilityCDTable) { if (item.Value >= item.Key.cooldown && item.Key.mana <= _battleCard.mana) { return true; } } return false; } public void Deny () { } public void CastAbility (Ability ability, BattleCard target) { // Debug.Log(9); float time = 0f; if (_shellType == ShellType.Player) { HideAbilitiesOnly (); if (_firstRowAbilityShells.Length == 0) { time = 0; } else if (_battleCard.abilities.Count > _abilityCountPerRow) { time = _secondRowAbilityShowTime; } else { time = _firstRowAbilityShowTime; } } if (ability.targetArea == TargetArea.Multiple) { foreach (var item in target.shell._shellQueue) { if (item.vacant == false) { StartCoroutine (CastAbilityAfter (ability, item.battleCard, time)); } } } else { StartCoroutine (CastAbilityAfter (ability, target, time)); } _hasCast = true; StartCoroutine (HideAfterTime (time + _castTime)); _battleCard.abilityCDTable [ability] = 0; } IEnumerator CastAbilityAfter (Ability ability, BattleCard target, float time) { // Debug.Log(10); _battleController.shieldPanel.Activate (); // Debug.Log("ya"); yield return new WaitForSeconds (time); AbilityEntityShell prefab = Resources.Load<AbilityEntityShell> (ResourcesFolderPath.prefabs_ability + "/" + ability.name); AbilityEntityShell abilityEntityShell = Instantiate (prefab) as AbilityEntityShell; // Debug.Log(abilityEntityShell.name); abilityEntityShell.Init (ability.abilityCast (ability, _battleCard, target)); _battleController.shieldPanel.Deactivate (); // Debug.Log("ha"); yield return null; } public void GetHurt () { // if (transform.localPosition == _originalLocalPosition) { // StartCoroutine (Reposition ()); // } // HOTween.To (transform, _getHurtTime, new TweenParms ().Prop ("position", Random.onUnitSphere * 0.4f, true).Ease (EaseType.Linear)); // HOTween.To (transform, _getHurtTime, new TweenParms ().Prop ("rotation", Quaternion.Euler(new Vector3(30f,0,0)), true).Loops(2, LoopType.Yoyo).Ease( EaseType.Linear)); HOTween.To (transform, _getHurtTime, new TweenParms ().Prop ("localRotation", Quaternion.Euler(new Vector3(30f,0,0)), true).Ease( EaseType.Linear).OnComplete(()=>{ HOTween.To (transform,_getHurtTime,new TweenParms().Prop("localRotation",Quaternion.identity).Ease(EaseType.Linear)); })); } // IEnumerator Reposition () // { // yield return new WaitForSeconds (0.1f); // while (transform.localPosition!=_originalLocalPosition) { // transform.localPosition = Vector3.Lerp (transform.localPosition, _originalLocalPosition, 0.3f); // yield return null; // } // yield return null; // } } <file_sep>/Assets/Scripts/Card/Abitity/AbilityCastStatic.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Reflection; public static class AbilityCastStatic { static float _physicalCriticalFactor=2f,_magicalCriticalFactor=1.5f; static Dictionary<string,AbilityCast> abilityCastTable; static AbilityCastStatic() { abilityCastTable=new Dictionary<string, AbilityCast>(); FieldInfo[] fieldInfos= typeof(AbilityCastStatic).GetFields(BindingFlags.Public|BindingFlags.Static); foreach(FieldInfo fieldInfo in fieldInfos) { if(fieldInfo.FieldType==typeof (AbilityCast)){ string abilityCastName=fieldInfo.Name.Substring(12); // Debug .Log(abilityCastName); abilityCastTable.Add(abilityCastName,fieldInfo.GetValue(null) as AbilityCast); } } } public static bool HasAbilityCast(string abilityCastName) { return abilityCastTable.ContainsKey(abilityCastName); } public static AbilityCast GetAbilityCast(string abilityCastName) { return abilityCastTable[abilityCastName]; } public static AbilityCast AbilityCast_PhysicalDamage = delegate(Ability ability,BattleCard from, BattleCard to) { int damage = Random.Range (ability.GetValue (AbilityVariable.minValue), ability.GetValue (AbilityVariable.maxValue)) + from.physicalDamage; int criticalChance = Random.Range (1, 101); if (criticalChance <= from.physicalCriticalChance) { damage = (int)(damage*_physicalCriticalFactor); } AbilityEntity abilityEntity = new AbilityEntity (ability.baseAbility.id,ability.name, from, to, ability.abilityType,EffectCardStatic.EffectCard_PhysicalDamage); abilityEntity.SetValue (AbilityVariable.value, damage); return abilityEntity; }; public static AbilityCast AbilityCast_MagicalDamage = delegate(Ability ability,BattleCard from, BattleCard to) { int damage = Random.Range (ability.GetValue (AbilityVariable.minValue), ability.GetValue (AbilityVariable.maxValue)) + from.magicalDamage; int criticalChance = Random.Range (1, 101); if (criticalChance <= from.magicalCriticalChance) { damage =(int)(damage*_magicalCriticalFactor); } AbilityEntity abilityEntity = new AbilityEntity (ability.baseAbility.id,ability.name, from, to, ability.abilityType,EffectCardStatic.EffectCard_MagicalDamage); abilityEntity.SetValue (AbilityVariable.value, damage); return abilityEntity; }; public static AbilityCast AbilityCast_Healing= delegate(Ability ability, BattleCard from, BattleCard to) { int healing=Random.Range(ability.GetValue (AbilityVariable.minValue), ability.GetValue (AbilityVariable.maxValue)) + from.magicalDamage; AbilityEntity abilityEntity = new AbilityEntity (ability.baseAbility.id,ability.name, from, to, ability.abilityType,EffectCardStatic.EffectCard_Healing); abilityEntity.SetValue (AbilityVariable.value, healing); return abilityEntity; }; public static AbilityCast AbilityCast_DotOrHot = delegate(Ability ability, BattleCard from, BattleCard to) { int value = Random.Range (ability.GetValue (AbilityVariable.minValue), ability.GetValue (AbilityVariable.maxValue)); if(ability.abilityType== AbilityType.Physical) { value+=from.physicalDamage; } else if(ability.abilityType== AbilityType.Magical) { value+=from.magicalDamage; } AbilityEntity abilityEntity = new AbilityEntity (ability.baseAbility.id,ability.name, from, to, ability.abilityType, EffectCardStatic.EffectCard_GenerateDotOrHot); abilityEntity.SetValue(AbilityVariable.value,value); abilityEntity.SetValue(AbilityVariable.dot,ability.GetValue(AbilityVariable.dot)); abilityEntity.SetValue(AbilityVariable.interval,ability.GetValue(AbilityVariable.interval)); abilityEntity.SetValue(AbilityVariable.duration,ability.GetValue(AbilityVariable.duration)); return abilityEntity; }; public static AbilityCast AbilityCast_DebuffOrBuff = delegate(Ability ability, BattleCard from, BattleCard to) { AbilityEntity abilityEntity = new AbilityEntity (ability.baseAbility.id,ability.name, from, to, ability.abilityType, EffectCardStatic.EffectCard_GenerateDebuffOrBuff); abilityEntity.targetAttr = ability.targetAttr; abilityEntity.SetValue (AbilityVariable.value, ability.GetValue (AbilityVariable.value)); abilityEntity.SetValue(AbilityVariable .debuff,ability.GetValue(AbilityVariable.debuff)); abilityEntity.SetValue (AbilityVariable.interval, ability.GetValue (AbilityVariable.interval)); abilityEntity.SetValue (AbilityVariable.duration, ability.GetValue (AbilityVariable.duration)); return abilityEntity; }; } <file_sep>/Assets/Test4.cs using UnityEngine; using System.Collections; public class Test4 : MonoBehaviour { public bool b; public UIGrid grid; void Awake() { // Debug.Log("awke"+name); // label = GetComponent<UILabel> (); // label.text=string.Join("\n",s.Split(new char[]{' '}, System.StringSplitOptions.RemoveEmptyEntries)); } void Update() { if (b) { b=false; grid.AddChild(transform); } } } <file_sep>/Assets/Test3.cs using UnityEngine; using System.Collections; using Holoville.HOTween; using System.Collections.Generic; public class Test3 : MonoBehaviour { public GameObject de; // private Vector3 position; void Awake() { Instantiate (de); Debug.Log("insta"); // position =transform.position; // HOTweenComponent hotc=GetComponent<HOTweenComponent>(); // // Debug.Log (hotc == null); // Debug.Log(hotc.tweenDatas.Count); // Debug.Log(hotc.generatedTweeners.Count); // // List<HOTweenManager.HOTweenData> hotweenDataList=hotc.tweenDatas; // hotweenDataList [0].propDatas [0].endValVector3 = de.transform.position; // hotweenDataList [0].propDatas [0].isActive = true; // foreach (var item in hotc.generatedTweeners) { // item.ResetAndChangeParms(TweenType.To,item.duration,new TweenParms()); // } //// hotc.generatedTweeners [0].Restart (); // // // Debug.Log((hotweenDataList[0].targetName)+"||"+hotweenDataList[0].propDatas[0].propName); // HOTween.To (transform, 5f, new TweenParms ().Prop ("position", de.transform.position,true).Loops(1, LoopType.Yoyo)); } // void OnCollisionEnter() // { // Debug.Log("enter"); // } // // void OnTriggerEnter(Collider other) // { // Debug.Log("trigg"); // } // void Update() // { // if(transform.position!=position) // transform.position=Vector3.Lerp(position,transform.position,0.3f); // } void OnHover() { // Debug.Log("HOver");} } } <file_sep>/Assets/Scripts/SwordControl.cs using UnityEngine; using System.Collections; using Holoville.HOTween; public class SwordControl : MonoBehaviour { ParticleSystem _particle; UISprite _sword; public ShieldPanel _shield; float _anim_time=1.5f; // Use this for initialization void Awake() { _particle = GetComponentInChildren<ParticleSystem> (); _sword = GetComponentInChildren<UISprite> (); foreach (ParticleSystem ps in _particle.GetComponentsInChildren<ParticleSystem>()) { ps.startLifetime=_anim_time; } } // Update is called once per frame void Update () { } // public void Disappear(Operation oper) // { // Holoville.HOTween.Core.TweenDelegate.TweenCallback callback =delegate { // oper(); // } ; // _particle.Play (); // gameObject.AddComponent<RunOnCondition> ().RunDelay (0.5f * _anim_time, delegate { // HOTween.To(_sword.transform,0.5f*_anim_time,new TweenParms().Prop("localScale",Vector3.zero).Ease(EaseType.Linear).OnComplete(callback)); // }); // } public void Show(Vector3 position) { HOTween.To(_sword.transform,_anim_time,new TweenParms().Prop("localPosition",new Vector3(0,-40f,0)).Ease(EaseType.Linear).OnStart(()=>{ _shield.Activate(); }).OnComplete(()=>{ transform.position=position; _particle.Play (); HOTween.To(_sword.transform,_anim_time,new TweenParms().Prop("localPosition",new Vector3(0,20f,0)).Ease(EaseType.Linear).OnComplete(()=>{ _shield.Deactivate(); })); })); _particle.Play (); } } <file_sep>/Abandon/AbilityBase_abandon.cs using UnityEngine; using System.Collections; using Holoville.HOTween; using System; using System.Reflection; public delegate void CastAbility(Card from,Card to); public enum CastTarget { Self, Enemy, Friendly } ; public enum CastArea { Single, Area } ; public class AbilityBase:MonoBehaviour { public CastAbility cast; public string _name; public string name { get{ return _name;} set{ _name = value;} } public string _description; public string description { get{ return _description;} set{ _description = value;} } // protected CastArea _releaseArea; // // public CastArea releaseArea { // get{ return _releaseArea;} // set{ _releaseArea = value;} // } // protected CastTarget _releaseTarget; // // public CastTarget releaseTarget { // get{ return _releaseTarget;} // set{ _releaseTarget = value;} // } public string _targetAttr; // public string targetAttr { // get{ return _targetAttr;} // set{ _targetAttr = value;} // } public object _baseValue; public object baseValue { get{ return _baseValue;} set{ _baseValue = value;} } public bool _relative; public bool relative { set{ _relative = value;} get { return _relative; } } public bool _proportional; public bool proportional { get{return _proportional;} set{_proportional=value;} } /// <summary> /// the count of round for this ability effect.-1 for permanent until cast subject dies; /// 0 for immediately effect like take damage;other positive value for buff and debuff. /// </summary> protected int _baseRound; public int baseRound { get{return _baseRound;} set{_baseRound=value;} } public AbilityBase(){} protected AbilityBase(AbilityBase baseAbility) { _name = baseAbility.name; _description = baseAbility.description; _relative = baseAbility.relative; _proportional = baseAbility.proportional; _baseValue = baseAbility.baseValue; _baseRound = baseAbility.baseRound; } public static void CastAbility (object target, string field, object value, bool relative, bool proportional) { Type t = target.GetType (); FieldInfo fieldInfo; PropertyInfo propertyInfo; if ((fieldInfo = t.GetField (field)) != null) { if (relative) { object orgValue = fieldInfo.GetValue (target); Type valueType = orgValue.GetType (); MethodInfo operMethod; if (proportional) { operMethod = valueType.GetMethod ("op_Multiply"); } else { operMethod = valueType.GetMethod ("op_Addition"); } if (operMethod != null && operMethod.IsSpecialName) { try { object finalValue = operMethod.Invoke (null, new object[] { orgValue, value }); fieldInfo.SetValue (target, finalValue); } catch { Debug.Log ("the value parameter '" + value.ToString () + "' does not have the same type as field '" + fieldInfo.Name + "' of " + t.Name + " '" + target.ToString () + "' does."); return; } } else { Debug.Log ("The type of field '" + fieldInfo.Name + "' of class " + t.Name + " doesn't implement add operator,parameter relative 'true' is illegal."); } } else { try { fieldInfo.SetValue (target, value); } catch { Debug.Log ("The value parameter '" + value.ToString () + "' cannot be converted and stored in the field '" + fieldInfo.Name + "' of " + t.Name + " '" + target.ToString () + "'."); return; } } } else if ((propertyInfo = t.GetProperty (field)) != null) { MethodInfo setMethod = propertyInfo.GetSetMethod (); if (setMethod == null) { Debug.Log ("The property '" + propertyInfo.Name + "' of class '" + t.Name + "'doesn't have set method"); return; } if (relative) { MethodInfo getMethod = propertyInfo.GetGetMethod (); if (getMethod == null) { Debug.Log ("The property '" + propertyInfo.Name + "' of class '" + t.Name + "'doesn't have get method"); return; } object orgValue = getMethod.Invoke (target, null); MethodInfo operMethod; if (proportional) { operMethod = orgValue.GetType ().GetMethod ("op_Multiply"); } else { operMethod = orgValue.GetType ().GetMethod ("op_Addition"); } if (operMethod != null && operMethod.IsSpecialName) { try { object finalValue = operMethod.Invoke (null, new object[] { orgValue, value }); setMethod.Invoke (target, new object[]{finalValue}); } catch { Debug.Log ("the value parameter '" + value.ToString () + "' does not have the same type as property '" + propertyInfo.Name + "' of " + t.Name + " '" + target.ToString () + "' does."); return; } } else { Debug.Log ("The type of property '" + fieldInfo.Name + "' of class " + t.Name + " doesn't implement add operator,parameter relative 'true' is illegal."); } } else { try { setMethod.Invoke (target, new object[]{ value}); } catch { Debug.Log ("The value parameter '" + value.ToString () + "' cannot be converted and set into the property '" + propertyInfo.Name + "' of " + t.Name + " '" + target.ToString () + "'."); return; } } } else { Debug.Log ("The class '" + t.Name + "' doesn't have field or property '" + field + "'"); return; } } // // public virtual void AffectTarget (Card card) // { // CastAbility (card, targetAttr, baseValue, relative,pr); // } }<file_sep>/Abandon/0827/AbstractAbilityBase.cs using UnityEngine; using System.Collections; public abstract class AbstractAbilityBase : MonoBehaviour { public string _name; public string _description; public string _targetAttr; public int _Value; //public IAbilityEffect _abilityEffect; public abstract object CastAbility(ConcreteCard from,ConcreteCard to); } <file_sep>/Assets/Scripts/Card/CardFactory.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using MiniJSON; public class CardFactory { private static CardFactory _cardFactoryInstance; private Dictionary<string,int> _baseCardIdTable; private Dictionary<int,BaseCard> _baseCardTable; private Dictionary<string,Texture> _cardRoleSpriteTable; private AbilityFactory _abilityFactory; public bool ContainsCard (string cardName) { return _baseCardIdTable.ContainsKey (cardName); } public bool ContainsCard (int cardId) { return _baseCardTable.ContainsKey (cardId); } public ConcreteCard GeneConcreteCard (string cardName, int level=1, int[] abilitiesLevel=null) { int cardId = _baseCardIdTable [cardName]; BaseCard baseCard = _baseCardTable [cardId]; // Debug.Log ("Card name:" + cardName + "; Card id:" + cardId + "; BaseCard:" + (baseCard == null)); return GeneConcreteCard (baseCard, level, abilitiesLevel); } public ConcreteCard GeneConcreteCard (int cardId,int level=1, int[] abilitiesLevel=null) { BaseCard baseCard = _baseCardTable [cardId]; return GeneConcreteCard (baseCard, level, abilitiesLevel); } /// <summary> /// Generate ConcreteCard based on BaseCard. /// </summary> /// <returns>The generated ConcreteCard.</returns> /// <param name="baseCard">BaseCard.</param> /// <param name="rarity">ConcreteCard's rarity.</param> /// <param name="level">ConcreteCard level.</param> /// <param name="abilitiesLevel">level of ConcreteCard's abilities.</param> public ConcreteCard GeneConcreteCard (BaseCard baseCard, int level, int[] abilitiesLevel=null) { List<Ability> abilityList = new List<Ability> (); //That's for not to exam whether the array is null every for-loop if (abilitiesLevel == null) abilitiesLevel = new int[0]; for (int i=0; i!= baseCard._abilitiesId.Count; i++) { int abilityLevel = 1; if (i < abilitiesLevel.Length) { abilityLevel = abilitiesLevel [i]; } if (abilityLevel < 1) { Debug.Log ("Level of ability should be positive."); throw new System.ArgumentException ("abilitiesLevel"); } Ability ability = _abilityFactory.GeneAbility (baseCard._abilitiesId [i], abilityLevel); abilityList.Add (ability); } return new ConcreteCard (baseCard, level, abilityList,_cardRoleSpriteTable[baseCard.cardSprite]); } public static CardFactory GetCardFactory () { if (_cardFactoryInstance == null) _cardFactoryInstance = new CardFactory (); return _cardFactoryInstance; } private CardFactory () { _baseCardIdTable = new Dictionary<string, int> (); _baseCardTable = new Dictionary<int, BaseCard> (); _cardRoleSpriteTable = new Dictionary<string, Texture> (); _abilityFactory = AbilityFactory.GetAbilityFactory (); LoadCardTexture(); LoadCards (); LoadCardStatic (); // Debug.Log (_baseCardIdTable.Count + " " + _baseCardTable.Count); } /// <summary> /// Loads the BaseCard from resources. /// </summary> void LoadCards () { TextAsset[] textAssets = Resources.LoadAll<TextAsset> ("Json/Card"); foreach (TextAsset tAsset in textAssets) { string jsonString = tAsset.text; var dict = Json.Deserialize (jsonString) as Dictionary<string,object>; if (dict.ContainsKey ("card")) { Dictionary<string,object> cardInfos = dict ["card"] as Dictionary<string,object>; foreach (string cardName in cardInfos.Keys) { //Detect existence of cardName if (_baseCardIdTable.ContainsKey (cardName)) { Debug.Log (string.Format ("Card name has existed -name:{0} in folder: 'Resources/Json/Card/{1}'", cardName, tAsset.name)); throw new System.Exception (string.Format ("Card name has existed -name:{0} in folder: 'Resources/Json/Card/{1}'", cardName, tAsset.name)); } KeyValuePair<string,Dictionary<string,object>> cardInfo = new KeyValuePair<string, Dictionary<string, object>> (cardName, cardInfos [cardName]as Dictionary<string,object>); BaseCard baseCard; try { baseCard = BaseCard.GeneBaseCard (cardInfo); } catch (System.Exception e) { Debug.Log (string.Format ("Fail to Generate BaseCard via card data that named:{0}", cardName)); throw e; } int id = baseCard.id; //Detect existence of baseCard's id if (_baseCardTable.ContainsKey (id)) { Debug.Log (string.Format ("Card id has existed -name:{0} in folder: 'Resources/Json/Card/{1}'", cardName, tAsset.name)); throw new System.Exception (string.Format ("Card id has existed -name:{0} in folder: 'Resources/Json/Card/{1}'", cardName, tAsset.name)); } //Check the role and background sprites try { CheckSprite (baseCard); } catch (System.Exception e) { Debug.Log (string.Format ("Fail to check sprite texture of BaseCard named:{0}", baseCard.name)); throw e; } _baseCardIdTable.Add (cardName, id); _baseCardTable.Add (id, baseCard); } } } } void LoadCardStatic () { TextAsset textAsset = Resources.Load<TextAsset> (ResourcesFolderPath.json_card + "/cardStatic"); if (textAsset == null) { Debug.Log ("card static infomation file access error"); throw new System.Exception ("card static infomation file access error"); } string json = textAsset.text; Dictionary<string,object> dict = MiniJSON.Json.Deserialize (json) as Dictionary<string,object>; Dictionary<string,object> cardStatics = dict ["cardStatic"] as Dictionary<string,object>; BaseCard.LoadStaticFields (cardStatics); if (!BaseCard.CheckStaticFields ()) { Debug.Log ("BaseCard static fields incomplete error"); throw new System.Exception ("BaseCard static fields incomplete error"); } } /// <summary> /// Checks the legality of BaseCard's cardSprite and backgroundSprite. /// </summary> /// <param name="baseCard">The Basecard for checking.</param> void CheckSprite (BaseCard baseCard) { //Check role texture. if (baseCard.cardSprite == null) { baseCard.cardSprite = baseCard.name; } string roleSpriteName = baseCard.cardSprite; if (!_cardRoleSpriteTable.ContainsKey (roleSpriteName)) { Debug.Log (string.Format ("Illegal cardSprite name:{0} ", roleSpriteName)); throw new System.ArgumentException (string.Format ("Illegal cardSprite name:{0} ", roleSpriteName)); } } void LoadCardTexture() { Texture[] textures=Resources.LoadAll<Texture>(ResourcesFolderPath.textures_role); foreach (var item in textures) { _cardRoleSpriteTable.Add(item.name,item); } } } <file_sep>/Assets/Scripts/LevelsEditor.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class LevelsEditor : MonoBehaviour { public List<UIWidget> _levelButtons=new List<UIWidget>(); UIWidget _levelButtonPrefab; public List<UIWidget> _mapLayers = new List<UIWidget> (); public UIWidget _selectedMapLayer; public List<UIWidget> mapLayers{ get{ _mapLayers.Remove(null); return _mapLayers; } } public string _levelName; public int _left; public int _top; UISprite _pathPointPrefab; public Vector2[] _pathPointsPosition; public List<UISprite> _pathPoints=new List<UISprite>(); void Awake() { _levelButtonPrefab = Resources.Load <UIWidget>(PrefabPath.btn_levelEntrance); _pathPointPrefab = Resources.Load<UISprite> (PrefabPath.path_point); } public void GeneNewMapLayer() { //Create an empty container as new map layer GameObject mapLayerGO = new GameObject (); mapLayerGO.name = "gameLayer_map00" + _mapLayers.Count.ToString(); mapLayerGO.layer=Layers.NGUI; mapLayerGO.transform.parent=GameObject.FindGameObjectWithTag (Tags.UIRoot).transform; UIWidget mapLayer=mapLayerGO.AddComponent<UIWidget> (); _mapLayers.Add (mapLayer); //add map background picture GameObject background = new GameObject (); background.name="Backgound_Map"; background.layer = Layers.NGUI; background.transform.parent = mapLayerGO.transform; background.AddComponent<UISprite> (); } [ContextMenu("Generate new level")] public void GeneNewLevel() { _levelButtons.Add (GeneNewLevel (_levelName,_left, _top,_selectedMapLayer.gameObject)); // GeneNewLevel (newLevel, left, top); } [ContextMenu("Generate path")] public void GenePathPoints() { for (int i = 0; i < _pathPointsPosition.Length; i++) { _pathPoints.Add(GeneNewPathPoint((int)_pathPointsPosition[i].x, (int)_pathPointsPosition[i].y,i+1)); } } UISprite GeneNewPathPoint(int left,int top,int index) { UISprite newPathPoint = GameObject.Instantiate (_pathPointPrefab) as UISprite; newPathPoint.name = "sprite_pathPoint_" + index; Locate (newPathPoint, left, top,_selectedMapLayer); return newPathPoint; } void Locate(UIWidget widget,int left,int top,UIWidget parent) { SetPositionAndSize posAndSize= widget.GetComponent<SetPositionAndSize> (); if (posAndSize == null) posAndSize = widget.gameObject.AddComponent<SetPositionAndSize> (); posAndSize.transform.parent = parent.transform; SetPositionAndSize setPosAndSize = posAndSize.GetComponent<SetPositionAndSize> (); setPosAndSize.localLeft = left; setPosAndSize.localTop = top; setPosAndSize.LocateAndResize (); posAndSize.transform.localScale = Vector3.one; } UIWidget GeneNewLevel(string levelName,int left,int top,GameObject mapLayer) { UIWidget newLevelBtn=GameObject.Instantiate (_levelButtonPrefab) as UIWidget; LevelInfo level=newLevelBtn.gameObject.AddComponent<LevelInfo>(); // level.Init (levelName); newLevelBtn.name = "btn_levelEntrance_" + (_levelButtons.Count+1); UILabel[] labels=newLevelBtn.GetComponentsInChildren<UILabel>(); foreach (UILabel label in labels) { if(label.name=="label_levelName") { // label.text=level.levelName; } } UIWidget parent = GameObject.FindGameObjectWithTag (Tags.UIRoot).GetComponent<UIWidget> (); Locate (newLevelBtn,left,top,parent); return newLevelBtn; } } <file_sep>/Assets/Scripts/Tools/SetPositionAndSize.cs using UnityEngine; using System.Collections; public class SetPositionAndSize : MonoBehaviour { public int localLeft=0; public int localTop=0; public int pixelWidth=0; public int pixelHeight=0; public bool center = false; [ContextMenu("LocateAndResize")] public void LocateAndResize() { UIWidget parentUI = transform.parent.GetComponentInParent<UIWidget> (); UIWidget thisUI = GetComponent<UIWidget> (); if (pixelWidth == 0 || pixelHeight == 0) { pixelWidth=System.Convert.ToInt32(thisUI.localSize.x); pixelHeight=System.Convert.ToInt32(thisUI.localSize.y); } int width = pixelWidth, height = pixelHeight; //thisUI.pivot = UIWidget.Pivot.TopLeft; if (!center){ Debug.Log((parentUI==null)+"dd"); thisUI.SetRect (parentUI.localCorners[1].x+localLeft,parentUI.localCorners[1].y -localTop - pixelHeight, width, height); //UIWidget.SetRect params:left,bottom,width,height } else { thisUI.pivot= UIWidget.Pivot.Center; // Debug.Log(parentUI.localCenter.x+"//"+parentUI.localCenter.y); // Debug.Log(parentUI.name); thisUI.SetRect (parentUI.localCenter.x-thisUI.localSize.x/2+localLeft , parentUI.localCenter.y-thisUI.localSize.y/2-localTop, width, height); } } } <file_sep>/Assets/Scripts/Card/Abitity/AbilityShell.cs using UnityEngine; using System.Collections; using Holoville.HOTween; using System.Collections.Generic; public class AbilityShell : MonoBehaviour { // private static Color _lightColor=Color.white; // private static Color _darkColor=new Color(0.4f,0.4f,0.4f); private static float _clickInterval=0.3f; public BattleCardShell _battleCardShell; public GameObject _glowEdge; public AbilityDetailDisplayer _abilityDetailDisplayer; private Ability _ability; private Vector3 _localPosition; private KeyValuePair<Ability,int> _cdKVPair; private float _timeToShowDetail=2f; private float _showDetailTimer=float.NegativeInfinity; private bool _detailDisplayed=false; /// <summary> /// Recording how how many rounds have passed since last time the ability has cast. /// </summary> // private int _cooldownTimer; /// <summary> /// For setting shader value. /// </summary> private float _cdPercent; /// <summary> /// Indicate if the shell is filled by abililty. /// </summary> private bool _vacant; /// <summary> /// Indicate whether the card is capable to cast the ability.. /// </summary> private bool _available; private float _clickTimer; public bool vacant { get{return _vacant;} } public bool available { get{return _available;} } public Ability ability { get{return _ability;} // set{_ability =value;} } void Awake() { _localPosition=transform.localPosition; _vacant=true; _available=false; _clickTimer=0; _glowEdge.SetActive(false); } void Update() { _clickTimer+=Time.deltaTime; renderer.material.SetFloat("cooldown",_cdPercent); _showDetailTimer+=Time.deltaTime; if(_showDetailTimer>_timeToShowDetail&&_detailDisplayed==false) { // Debug.Log("Show"); _abilityDetailDisplayer.DisplayerAbilityDetail(_ability,transform.position.y+0.5f,_cdKVPair.Value); _detailDisplayed=true; } } void OnHover(bool isOver) { // Debug.Log("Hover"); if(isOver) { _showDetailTimer=0; } else{ if(_detailDisplayed) { _abilityDetailDisplayer.HideAbilityDetail(); } _detailDisplayed=false; _showDetailTimer=float.NegativeInfinity; } } void OnClick() { if (_clickTimer > _clickInterval) { _clickTimer = 0; MouseClick (); } } void MouseClick() { // Debug.Log("Ability activate : "+_ability.name); if(_available) { _glowEdge.SetActive(true); _battleCardShell.battleController.AbilityClick(this); } else if(_cdKVPair.Value<_ability.cooldown) { _battleCardShell.battleController.dynamicTextAdmin.DynamicText(transform.position,"Not Available"); } else { _battleCardShell.battleController.dynamicTextAdmin.DynamicText(transform.position,"Out Of Mana"); } } public void LoadAbility(Ability ability) { gameObject.SetActive(false); _vacant=false; _ability=ability; renderer.material.mainTexture=_ability.icon; Dictionary<Ability,int>.Enumerator iterator= _battleCardShell.battleCard.abilityCDTable.GetEnumerator (); // _cdKVPair = _battleCardShell.battleCard.abilityCDTable.GetEnumerator ().Current; while (iterator.Current.Key!=ability) { iterator.MoveNext(); } _cdKVPair = iterator.Current; iterator.Dispose (); // _cooldownTimer=0; // if (_cooldownTimer == 0) { // _available=true; // } } public void Clear() { _ability=null; _available=false; _vacant=true; _glowEdge.SetActive(false); // _cooldownTimer=0; } public void Show(float distance,float duration) { gameObject.SetActive(true); if(vacant) { Debug.Log("Empty AbilityShell,'Show' method is unsupported"); throw new System.MethodAccessException("Empty AbilityShell,'Show' method is unsupported"); } if(_cdKVPair.Value<_ability.cooldown) { //Is still in cooldown. //_ability.cooldown must be positive due to _clickTimer is less than it and _clickTimer is not negative. _available=false; _cdPercent=(_cdKVPair.Value%_ability.cooldown)/_ability.cooldown; } else if(_battleCardShell.battleCard.mana<_ability.mana) {//Not enough mana. _available=false; _cdPercent=0; } else { //Ability is available to cast _available=true; _cdPercent=1f; } HOTween.To(transform,duration,new TweenParms().Prop("localPosition",transform.localPosition+new Vector3(0,distance,0)).Ease(EaseType.EaseOutQuad) .OnStart(delegate (){ _battleCardShell.battleController.shieldPanel.Activate(); }).OnComplete(delegate() { _battleCardShell.battleController.shieldPanel.Deactivate(); })); } public void Hide(float duration) { _glowEdge.SetActive(false); HOTween.To(transform,duration,new TweenParms().Prop("localPosition",_localPosition).Ease(EaseType.Linear) .OnStart(delegate (){ _battleCardShell.battleController.shieldPanel.Activate(); }).OnComplete(delegate() { gameObject.SetActive(false); _battleCardShell.battleController.shieldPanel.Deactivate(); })); } // public void NewRound() // { // // } // public void UpdateCDTimer() // { // _cooldownTimer=0; // } } <file_sep>/Assets/Scripts/Level/LevelGateControl.cs using UnityEngine; using System.Collections; using System; using System.Collections.Generic; using Holoville.HOTween; public class LevelGateControl : MonoBehaviour,IComparable<LevelGateControl> { private static float _unlockDuration = 1f, _hoverFadeDuration = 0.3f; LevelInfo _levelInfo; GameController _gameController; public PathPointControl _nextPathPoint; public UISprite _mainButton, _whiteEdge; public UILabel _levelName; public int _levelIndex; private float _clickTimer = 0, _clickThreshold = 0.3f; public int levelIndex { get{ return _levelIndex;} } // Use this for initialization void Awake () { _gameController = GameObject.FindGameObjectWithTag (Tags.gameController).GetComponent<GameController> (); _levelInfo = GetComponent<LevelInfo> (); } void Start () { _levelInfo.Load (); Init (); } // Update is called once per frame void Update () { _clickTimer += Time.deltaTime; } void OnClick () { if (_clickTimer > _clickThreshold) { _clickTimer = 0f; _gameController.LevelButtonClick (this); } } void OnHover (bool isOver) { if (_levelInfo.unlocked) { if (isOver) { HOTween.To (_whiteEdge, _hoverFadeDuration, new TweenParms ().Prop ("alpha", 1f).OnStart (() => { _whiteEdge.gameObject.SetActive (true);})); HOTween.To (_levelName, _hoverFadeDuration, new TweenParms ().Prop ("effectDistance", new Vector2 (6f, 6f)).OnStart (() => { _levelName.effectStyle = UILabel.Effect.Shadow;})); } else { HOTween.To (_whiteEdge, _hoverFadeDuration, new TweenParms ().Prop ("alpha", 0f).OnComplete (() => { _whiteEdge.gameObject.SetActive (false);})); HOTween.To (_levelName, _hoverFadeDuration, new TweenParms ().Prop ("effectDistance", Vector2.zero).OnComplete (() => { _levelName.effectStyle = UILabel.Effect.None;})); } } } public int CompareTo (LevelGateControl other) { return _levelIndex - other._levelIndex; } /// <summary> /// Unlock this level and process relative events. /// </summary> public void Unlock () { _mainButton.GetComponentInChildren<ParticleSystem> ().Play (); HOTween.To (_mainButton, _unlockDuration, new TweenParms ().Prop ("color", Color.white).Ease (EaseType.Linear)); HOTween.To (_levelName, _unlockDuration, new TweenParms ().Prop ("alpha", 1f).Ease (EaseType.Linear).OnStart (() => { _levelName.gameObject.SetActive (true); _levelInfo.Unlock (); collider.enabled=true; })); } /// <summary> /// Unlocks the next level through path points. /// </summary> public void UnlockNextLevel () { _nextPathPoint.Activate (); } public void Save () { _levelInfo.Save (); } public void LevelComplete () { _nextPathPoint.Activate (); Debug.Log("levelcom"); } void Init () { bool unlock = _levelInfo.unlocked; if (unlock) { _mainButton.alpha = 1; _levelName.gameObject.SetActive (true); _levelName.alpha = 1; _gameController.LightPathPoints (_levelIndex - 1); collider.enabled=true; } else { _mainButton.color = new Color (0.5f, 0.5f, 0.5f, 0.75f); _levelName.alpha = 0f; _levelName.gameObject.SetActive (false); collider.enabled=false; } _whiteEdge.alpha = 0f; _whiteEdge.gameObject.SetActive (false); _levelName.effectStyle = UILabel.Effect.None; _levelName.effectDistance = Vector2.zero; } public void LightPathPoints () { if (_nextPathPoint != null) { _nextPathPoint.Init (_levelInfo.unlocked); Debug.Log("UNlcok path"); } } } <file_sep>/Assets/Scripts/ShieldPanel.cs using UnityEngine; using System.Collections; public class ShieldPanel : MonoBehaviour { private int _counter; void Awake() { _counter=0; gameObject.SetActive(false); } public void Activate() { if(_counter==0) gameObject.SetActive(true); _counter++; } public void Deactivate() { if(_counter==1) { gameObject.SetActive(false); } if(--_counter<0) { _counter=0; } } } <file_sep>/Abandon/Card.cs using UnityEngine; using System.Collections; using System.Reflection; using System.Collections.Generic; using System; //public abstract class Actor{ //// public abstract void Attack(); //// public abstract void UnderAttack(); //} public class CardBuff { string _field; int _deltaValue; int _round; } public enum CardAttr { Health,Magic,Defense,Damage,DropRate,HealthResilience,MagicResilience,Price }; public abstract class BaseCard{ protected internal Dictionary<CardAttr,int> _attributes; //protected internal int _magic,_health,_defense,_damage,_dropRate,_resilience,_Price; protected internal string _description; //protected internal Ability[] _abilities; } //public delegate void Cast(Card from,Card to); //public abstract class Ability{ // public enum CastTarget{ // Self,Enemy,Friendly // }; // public enum CastArea{ // Single,Area // }; // protected string _name; // protected string _description; // protected CastArea _releaseArea; // protected CastTarget _releaseTarget; // protected Cast _cast; // //} public class InitCard:BaseCard { int _id; } public class Card:BaseCard { public enum Quality{ Normal,Good,Elite,Legend }; int _id,_experience; public Card(InitCard initCard) { } } <file_sep>/Abandon/0827/RealAbility.cs using UnityEngine; using System.Collections; public class RealAbility : MonoBehaviour //,ICastAbility { /// <summary> ///array about experience mount needed for every level to upgrade. /// </summary> protected static int[] experienceSheet; /// <summary> /// Base ability information for "this" to levelup. /// </summary> protected BaseAbility _baseAbility; protected int _maxLevel; protected int _experience; protected int _level; protected int _value; protected ILevelUpgrader _levelUpgrader; public void ExperienceIncrease(int quantity) { _experience += quantity; while (_level<_maxLevel&&_experience>experienceSheet[_level-1]) { _experience-=experienceSheet[_level-1]; _levelUpgrader.Levelup(this); } if (_experience > experienceSheet [_level - 1]) { _experience=experienceSheet[_level-1]; } } // public virtual ICastAbility CastAbilityTo(BattleCard from,BattleCard to,RealAbility b) // { // _baseAbility._abilityEffect.AbilityEffect (from, to, this); // return null; // } } <file_sep>/Abandon/levelGateRelative/PlayerStateBarControl.cs using UnityEngine; using System.Collections; public class PlayerStateBarControl : MonoBehaviour { UILabel _label_value; UISprite _valueBar; int _fullBarLength; int _value = 0; public void SetValue(int value) { _value = value; AlterBar (); } int _maxValue = 0; public void SetMaxValue(int maxValue) { _maxValue = maxValue; AlterBar (); } void Awake() { _label_value = GetComponentInChildren<UILabel> (); foreach (Transform trans in GetComponentsInChildren<Transform>()) { if(trans.name.Equals("valueBar")) _valueBar=trans.GetComponent<UISprite>(); } _fullBarLength = (int)_valueBar.transform.parent.GetComponent<UISprite> ().localSize.x; } void OnMouseEnter() { ShowValue (); } void OnMouseExit() { HideValue (); } void ShowValue() { _label_value.text = _value + "/" + _maxValue; _label_value.gameObject.SetActive (true); } void HideValue() { _label_value.gameObject.SetActive (false); } void AlterBar() { _valueBar.SetRect (_valueBar.localCorners [0].x, _valueBar.localCorners [0].y, _value / _maxValue * _fullBarLength, _valueBar.localSize.y); } } <file_sep>/Abandon/0827/RealCard.cs using UnityEngine; using System.Collections; public class RealCard : BaseCard { protected CardRarity _cardRarity; protected int _experience; protected int _level; public RealCard(BaseCard baseCard):base(baseCard) { _cardRarity = CardRarity.Normal; _experience = 0; _level = 1; } public RealCard(BaseCard baseCard,int level,params int[] abilityLevel) { } /// <summary> /// Used by derived class to initial its base part. /// </summary> /// <param name="realCard">real card.</param> protected RealCard(RealCard realCard) { } public void ExperienceIncrease(int quantity) { } public void LevelUp() {} } <file_sep>/Abandon/0827/DurativelAbility.cs using UnityEngine; using System.Collections; public class DurativeAbility :RealAbility{ protected int _durationalRound; protected int _effectRound; } <file_sep>/Assets/Scripts/FlyStar.cs using UnityEngine; using System.Collections; public class FlyStar : MonoBehaviour { // Use this for initialization Vector3 _lastPosition; ParticleSystem _particle_blow; ParticleSystem _particle_tail; void Awake() { foreach (ParticleSystem ps in GetComponentsInChildren<ParticleSystem>()) { if(ps.name.Equals("particle_blow")) _particle_blow=ps; else if(ps.name.Equals("particle_tail")) _particle_tail=ps; } } // Update is called once per frame void Update () { if (_lastPosition != transform.position) { transform.up=(transform.position-_lastPosition).normalized; } _lastPosition = transform.position; } public void TurnOffTail() { _particle_tail.Stop (); } public void Blow() { _particle_blow.Play (); } } <file_sep>/Assets/Scripts/Card/Abitity/DurativeState.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public abstract class DurativeState:AbilityEntity { protected int _duration,_interval,_roundCounter; public abstract void RoundStart(); public abstract void RoundEnd(); public abstract void Clear(); } <file_sep>/Assets/Scripts/Card/Abitity/DebuffAndBuff.cs using UnityEngine; using System.Collections; using System.Reflection; public class DebuffAndBuff : DurativeState { protected PropertyInfo _targetProperty; protected bool _isDeBuff; protected int _remainTime; public int interval { get{return _interval;} set{_interval =value;} } public int duration { get{return _duration;} } public int remainTime { get{return _remainTime;} } public int id { get; set; } public bool isDebuff { get{return _isDeBuff;} } public DebuffAndBuff(int id,string name,bool isDebuff,BattleCard from,BattleCard to, AbilityType abilityType,int duration,PropertyInfo targetProperty) { this.id = id; _name=name; _isDeBuff=isDebuff; _castCard = from; _targetCard = to; _abilityType = abilityType; _duration = duration; _remainTime=duration; _targetProperty = targetProperty; } public override void RoundStart () { } public override void RoundEnd () { _remainTime--; if(_remainTime==0){ Clear(); } } public override void Clear() { object value= _targetProperty.GetValue(_targetCard,null); value=(object)((int)value+GetValue(AbilityVariable.restorativeValue)); _targetProperty.SetValue(_targetCard,value,null); } } <file_sep>/Assets/Scripts/Tools/ComputeContainerSize.cs using UnityEngine; using System.Collections; public class ComputeContainerSize : MonoBehaviour { [ContextMenu("Compute Containei Size")] void ComputeSize () { SetPositionAndSize posAndSize = GetComponent<SetPositionAndSize> (); int width = 0, height = 0; UIWidget[] widgets = GetComponentsInChildren<UIWidget> (); foreach (UIWidget widget in widgets) { if (widget.transform != transform) { width = (int)Mathf.Max (width, widget.localSize.x + widget.transform.localPosition.x); height = (int)Mathf.Max (height, -widget.transform.localPosition.y+widget.localSize.y); } } posAndSize.pixelWidth = width; posAndSize.pixelHeight = height; } } <file_sep>/Abandon/levelGateRelative/LevelGateControl.cs using UnityEngine; using System.Collections; using System; using System.Collections.Generic; public class LevelGateControl : MonoBehaviour,IComparable<LevelGateControl> { LevelInfo _levelInfo; public StarSlotControl _starOne, _starTwo, _starThree; GameController _gameController; public PathPointControl _nextPathPoint; GameObject _lock; public GameObject _mainButton; string _uniqueIdentityString; StarFlyPath _starPath; // Use this for initialization void Awake () { _uniqueIdentityString = transform.parent.name + name; _gameController = GameObject.FindGameObjectWithTag (Tags.gameController).GetComponent<GameController> (); _levelInfo = GetComponent<LevelInfo> (); // foreach (StarSlotControl starControl in GetComponentsInChildren<StarSlotControl>()) { // switch (starControl.name) { // case "starEmpty_01": // _starOne = starControl; // break; // case "starEmpty_02": // _starTwo = starControl; // break; // case "starEmpty_03": // _starThree = starControl; // break; // default: // break; // } // } foreach (Transform trans in GetComponentsInChildren<Transform>()) { switch (trans.name) { case "starEmpty_01": _starOne = trans.GetComponent<StarSlotControl> (); break; case "starEmpty_02": _starTwo = trans.GetComponent<StarSlotControl> (); break; case "starEmpty_03": _starThree = trans.GetComponent<StarSlotControl> (); break; case "btn_main": _mainButton = trans.gameObject; break; case "icon_lock": _lock = trans.gameObject; break; default: break; } } _starPath = gameObject.AddComponent<StarFlyPath> (); _starPath._levelControl = this; } void Start () { LoadFromJson (_gameController._allInfoDict); LoadFromPlayerPrefs (); Init (); } // Update is called once per frame void Update () { } public int CompareTo (LevelGateControl other) { if (transform.parent.name.Equals (other.transform.parent.name)) return name.CompareTo (other.name); return transform.parent.name.CompareTo (other.transform.parent.name); } /// <summary> /// Unlock this level and process relative events. /// </summary> public void Unlock () { _levelInfo.Unlock (); _mainButton.GetComponentInChildren<ParticleSystem> ().Play (); gameObject.AddComponent<RunOnCondition> ().RunDelay (1.5f, UnlockButton); // Transform[] childTransforms = GetComponentsInChildren<Transform> (); // Debug.Log (childTransforms.Length); // foreach (Transform trans in GetComponentsInChildren<Transform> ()) { // Debug.Log(trans.name); // if (trans.name == "icon_lock") { //// Debug.Log("icon_lock"); // trans.gameObject.SetActive (false); // } else if (trans.name == "btn_main") { //// Debug.Log("btn_main"); // trans.GetComponent<UISprite> ().spriteName = "iconStage_01"; // } // } Debug.Log ("Unlock"); } void UnlockButton () { _mainButton.GetComponent<UISprite> ().spriteName = "iconStage_01"; _lock.SetActive (false); _mainButton.GetComponent<UIPlayAnimation> ().enabled = true; _starOne.Unlock (); _starTwo.Unlock (); _starThree.Unlock (); _gameController.UnlockLevel (); } /// <summary> /// Unlocks the next level through path points. /// </summary> public void UnlockNextLevel () { _nextPathPoint.Activate (); } public void GainStar (StarNum starNum) { _levelInfo.GainStar (starNum); if (starNum >= StarNum.ONE) _starOne.GainStar (); if (starNum >= StarNum.TWO) { gameObject.AddComponent<RunOnCondition> ().RunDelay (0.35f, _starTwo.GainStar); // _starTwo.GainStar (); } if (starNum >= StarNum.TRHEE) { gameObject.AddComponent<RunOnCondition> ().RunDelay (0.7f, _starThree.GainStar); // _starThree.GainStar (); } Debug.Log (name + "GainStar"); UnlockNextLevel (); } public void SetLevelIndex (int index) { _levelInfo.SetLevelIndex (index); } public int GetLevelIndex () { return _levelInfo.GetLevelIndex (); } public void MainButtonMouseEnter () { } public void MainButtonMouseLeave () { } public void MainButtonMouseClick () { if (_levelInfo.unlocked) { _gameController.LevelButtonClick (this); } } public void Save () { if (_levelInfo.unlocked) { PlayerPrefs.SetInt (_uniqueIdentityString, 1); PlayerPrefs.SetInt (_uniqueIdentityString + "_starNum", _levelInfo.GetStarNum ()); } } public void LoadFromPlayerPrefs () { } public void LoadFromJson (Dictionary<string,object> dict) { } void Init () { if (!_levelInfo.unlocked) { _starOne.FillStar (false); _starOne.gameObject.SetActive (false); _starTwo.FillStar (false); _starTwo.gameObject.SetActive (false); _starThree.FillStar (false); _starThree.gameObject.SetActive (false); } else { _mainButton.GetComponent<UISprite> ().spriteName = "iconStage_01"; _lock.SetActive (false); int starNum = _levelInfo.GetStarNum (); if (starNum < 3) _starThree.FillStar (false); if (starNum < 2) _starTwo.FillStar (false); if (starNum < 1) _starOne.FillStar (false); } } public Vector3[] GetStarFlyPath (StarSlotControl starSlot) { Vector3[] path = null; if (starSlot == _starOne) { path = _starPath.GetPathOne (); } else if (starSlot == _starTwo) { path = _starPath.GetPathTwo (); } else if (starSlot == _starThree) { path = _starPath.GetPathThree (); } for (int i=0; i!=path.Length; i++) path [i] += _mainButton.transform.position; return path; } public MapLayerControl GetMapLayer () { return GetComponentInParent<MapLayerControl> (); } public GameObject GetMainButton () { return _mainButton; } } <file_sep>/Abandon/0827/ICastAbility.cs using UnityEngine; using System.Collections; public interface ICastAbility { ICastAbility CastAbilityTo(ICastAbility from,BattleCard to,RealAbility ability); } <file_sep>/Assets/Scripts/Unuse/PrefabPath.cs using UnityEngine; using System.Collections; public class PrefabPath { public static string btn_levelEntrance="Prefabs/btn_levelEntrance"; public static string path_point="Prefabs/path_point"; } <file_sep>/Assets/Scripts/battleBackground.cs using UnityEngine; using System.Collections; public class battleBackground : MonoBehaviour { float _clickTimer = 0; float _clickInterval = 0.3f; public BattleControl _battleController; void Update () { _clickTimer += Time.deltaTime; } void OnClick () { if (_clickTimer > _clickInterval) { _clickTimer = 0; MouseClick (); } } void MouseClick () { _battleController.BackgroundClick (); } } <file_sep>/Abandon/0827/ILevelUpgrader.cs using UnityEngine; using System.Collections; public interface ILevelUpgrader{ void Levelup(RealAbility realAbility); } <file_sep>/Abandon/0827/IAbilityEffect.cs using UnityEngine; using System.Collections; /// <summary> /// This interface defines how an ability acting on target. /// It modifies target one or some attributes(determined by the ability) to some value(determined by the ability too). /// </summary> public interface IAbilityEffect { void AbilityEffect (ConcreteCard from, ConcreteCard to, InstantAbilityBase ability); } <file_sep>/Assets/Scripts/GameController/RunOnCondition.cs using UnityEngine; using System.Collections; public delegate bool BoolMonitor (); public delegate float FloatMonitor (); public delegate void Operation (); enum MonitorType { None, Bool, FloatLarge, FloatLess } ; public class RunOnCondition : MonoBehaviour { MonitorType _monitorType; BoolMonitor _boolMonitor; bool _condition; FloatMonitor _floatMonitor; float _floatThreshold; Operation _oper; float _timer; // Use this for initialization void Awake () { _monitorType = MonitorType.None; _timer = 0f; } // Update is called once per frame void Update () { switch (_monitorType) { case MonitorType.Bool: if (_boolMonitor () == _condition) { _oper (); Destroy (this); } break; case MonitorType.FloatLarge: if (_floatMonitor () >= _floatThreshold) { _oper (); Destroy (this); } break; default: break; } } public void RunWhenBoolChange (BoolMonitor monitor, bool condition, Operation operation) { _monitorType = MonitorType.Bool; _boolMonitor = monitor; _oper = operation; _condition = condition; } public void RunWhenFloatLarger (FloatMonitor monitor, float floatThreshold, Operation operation) { _monitorType = MonitorType.FloatLarge; _floatMonitor = monitor; _oper = operation; _floatThreshold = floatThreshold; } public void RunDelay (float delayTime, Operation operation) { _monitorType = MonitorType.FloatLarge; _floatMonitor = delegate { _timer += Time.deltaTime; return _timer; }; _oper = operation; _floatThreshold = delayTime; } } <file_sep>/Abandon/levelGateRelative/MapLayer_editMode.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class MapLayer_editMode : MonoBehaviour { string _name; UISprite _background; } <file_sep>/Abandon/0827/ActiveAbilityBase.cs using UnityEngine; using System.Collections; public class ActiveAbilityBase :AbilityBase { // public void CastAbility(ConcreteCard from,ConcreteCard to) // { // _abilityEffect(from,to,this); // } } <file_sep>/Assets/Scripts/Card/Abitity/EffectCardStatic.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Reflection; /// <summary> /// This delegate will be called when abilityEntity effects the target card. /// Return the delta value of target attribute of target BattleCard /// This delegate is owed by abilityEntity and called by target BattleCard /// </summary> public delegate int EffectCard(AbilityEntity abilityEntity); public static class EffectCardStatic { static float physicalDamageDeductionBase=50f; static float magicalDamageDeductionBase=100f; static Dictionary<string,EffectCard> effectCardTable; static EffectCardStatic() { effectCardTable=new Dictionary<string, EffectCard>(); FieldInfo[] fieldInfos= typeof(EffectCardStatic).GetFields(BindingFlags.Public|BindingFlags.Static); foreach(FieldInfo fieldInfo in fieldInfos) { if(fieldInfo.FieldType==typeof (EffectCard)){ string effectCardName=fieldInfo.Name.Substring(11); // Debug .Log(effectCardName); effectCardTable.Add(effectCardName,fieldInfo.GetValue(null) as EffectCard); } } } public static bool HasEffectCard(string effectCardName) { return effectCardTable.ContainsKey(effectCardName); } public static EffectCard GetEffectCard(string effectCardName) { return effectCardTable[effectCardName]; } public static EffectCard EffectCard_PhysicalDamage = delegate(AbilityEntity abilityEntity) { BattleCard to=abilityEntity.targetCard; int damage = abilityEntity.GetValue(AbilityVariable.value); damage =(int)(damage/( 1 + to.physicalDefense / physicalDamageDeductionBase)); to.health -= damage; return -damage; }; public static EffectCard EffectCard_MagicalDamage=delegate(AbilityEntity abilityEntity) { BattleCard to=abilityEntity.targetCard; int damage = abilityEntity.GetValue(AbilityVariable.value); damage =(int)(damage/( 1 + to.magicalDefense / magicalDamageDeductionBase)); to.health -= damage; return -damage; }; public static EffectCard EffectCard_Healing=delegate(AbilityEntity abilityEntity) { BattleCard target=abilityEntity.targetCard; int healing=abilityEntity.GetValue(AbilityVariable.value); target.health+=healing; return healing; }; public static EffectCard EffectCard_GenerateDotOrHot = delegate(AbilityEntity abilityEntity) { BattleCard to=abilityEntity.targetCard,from=abilityEntity.castCard; int id=(from.GetHashCode ().ToString () + from.concreteCard.id.ToString ()).GetHashCode (); bool isDot=abilityEntity.GetValue(AbilityVariable.dot)==1; DotAndHot dotOrHot = new DotAndHot (id,abilityEntity.name,isDot, from,to,abilityEntity.abilityType, abilityEntity.GetValue(AbilityVariable.interval),abilityEntity.GetValue(AbilityVariable.duration)); int value=abilityEntity.GetValue(AbilityVariable .value); if(isDot) {// Is a HOT dotOrHot.effectCard=EffectCard_Healing; } else {//Is a DOT if (abilityEntity.abilityType == AbilityType.Physical) { dotOrHot.effectCard = EffectCard_PhysicalDamage; } else if (abilityEntity.abilityType == AbilityType.Magical) { dotOrHot.effectCard = EffectCard_MagicalDamage; } } dotOrHot.SetValue (AbilityVariable.value,value); to.AddDotOrHot (dotOrHot); return 0; }; public static EffectCard EffectCard_GenerateDebuffOrBuff= delegate(AbilityEntity abilityEntity) { BattleCard to=abilityEntity.targetCard,from=abilityEntity.castCard; PropertyInfo propertyInfo=typeof(BattleCard).GetProperty(abilityEntity.targetAttr); bool isDebuff=abilityEntity.GetValue(AbilityVariable.debuff)==1; DebuffAndBuff debuffOrBuff = new DebuffAndBuff (abilityEntity.abilityId,abilityEntity.name,isDebuff, from,to, abilityEntity.abilityType,abilityEntity.GetValue(AbilityVariable.duration),propertyInfo); int valueDelta=abilityEntity.GetValue(AbilityVariable.value); debuffOrBuff.SetValue (AbilityVariable.restorativeValue, -valueDelta); int value =System.Convert.ToInt32(propertyInfo.GetValue(to,null))+valueDelta; propertyInfo.SetValue(to,value,null); return valueDelta; }; } <file_sep>/Abandon/AbilityData.cs using UnityEngine; using System.Collections; public class AbilityData { public AbilityType _abilityType; public TargetType _targetType; public string _name; public string _description; public string _targetAttr; public string _abilityEffect; public object _value; } <file_sep>/Assets/Scripts/Card/Abitity/TargetArea.cs using UnityEngine; using System.Collections; public enum TargetArea { Single,Multiple,Area }; <file_sep>/Abandon/levelGateRelative/StarControl.cs using UnityEngine; using System.Collections; using Holoville.HOTween.Plugins; using Holoville.HOTween; public class StarControl : MonoBehaviour { StarSlotControl _starSlot; Vector3[] _flyPath = null; static float _flyTime = 0.5f; static float _flyToCounterTime = 0.3f; public FlyStar _flystar; StarCounterLayerControl _starCounter; // Use this for initialization void Awake () { _starSlot = GetComponentInParent<StarSlotControl> (); _starCounter = GameObject.FindGameObjectWithTag (Tags.starCounter).GetComponent<StarCounterLayerControl> (); } // Update is called once per frame void Update () { } public void Activate () { if (_flyPath == null || _flyPath.Length == 0) { _flyPath = _starSlot.GetFlyPath (); } _flystar = (Instantiate (Resources.Load<GameObject> ("Prefabs/flyStar"))as GameObject).GetComponent<FlyStar>(); _flystar.transform.parent = _starSlot.transform; Debug.Log("setParent"); _flystar.transform.position = _flyPath [0]; _flystar.transform.localScale = Vector3.one * 1.5f; HOTween.To (_flystar.transform, _flyTime, new TweenParms ().Prop ("position", new PlugVector3Path (_flyPath)).Ease (EaseType.Linear).OnComplete (ActivateComplete)); HOTween.To (_flystar.transform, _flyTime, new TweenParms ().Prop ("localScale", Vector3.one).Ease (EaseType.Linear)); } void ActivateComplete () { _flystar.TurnOffTail (); if (!gameObject.activeInHierarchy) { gameObject.SetActive (true); HOTween.To (_flystar.transform, _flyToCounterTime, new TweenParms ().Prop ("position", _starCounter._bigStar.transform.position).Ease (EaseType.Linear).OnComplete (ActivateNewStar)); HOTween.To (_flystar.transform, _flyToCounterTime, new TweenParms ().Prop ("localScale", Vector3.one * 2.3f).Ease (EaseType.Linear)); } else { Destroy (_flystar); _flystar = null; } } void ActivateNewStar () { _flystar.TurnOffTail (); _flystar.Blow (); Destroy (_flystar.gameObject,0.2f); _starCounter.GainStar (); } } <file_sep>/Assets/Standard Assets/artWork/3D/Prefabs/readMe.txt package包含: 卡牌框架 卡牌可供替换内容的部分 左下角的桃心 右下角的盾牌 左上角的属性特效。 待更新: 卡牌背面美术资源 开拍正面内容参考资源 卡牌上方红色飘带(待定)<file_sep>/Assets/Scripts/Unuse/Tags.cs using UnityEngine; using System.Collections; public class Tags { public static string gameController="GameController"; public static string player="Player"; public static string UIRoot="UIRoot"; public static string mapEditor="MapEditor"; public static string levelGate="LevelGate"; public static string mapLayer="MapLayer"; public static string pathPoint="PathPoint"; public static string starCounter="StarCounter"; public static string sceneFader="Fader"; public static string battle="BattleLayer"; } <file_sep>/Abandon/levelGateRelative/MapLayerControl.cs using UnityEngine; using System.Collections; using System; public class MapLayerControl : MonoBehaviour ,IComparable<MapLayerControl> { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public int CompareTo(MapLayerControl other) { return name.CompareTo (other.name); } } <file_sep>/Assets/Scripts/Card/Abitity/AbilityVariable.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Reflection; public static class AbilityVariable { private static HashSet<string> variableStringSet; public static string maxValue="maxValue"; public static string minValue="minValue"; public static string interval="interval"; public static string duration="duration"; public static string restorativeValue="restorativeValue"; public static string value="value"; public static string dot="dot"; public static string debuff="debuff"; public static string mana="mana"; public static string cooldown="cooldown"; static AbilityVariable() { variableStringSet=new HashSet<string>(); FieldInfo[] fields=typeof(AbilityVariable).GetFields( BindingFlags.Public|BindingFlags.Static); foreach (var item in fields) { if(item.FieldType==typeof(string)) { variableStringSet.Add(item.Name); } } } public static bool HasVariableString(string variableString) { return variableStringSet.Contains(variableString); } } <file_sep>/Assets/Scripts/Player/PlayerControl.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class PlayerControl : MonoBehaviour { public BagManagement _bagManagement; private List<ConcreteCard> _cardBag; private List<ConcreteCard> _playCardSet; private GameController _gameController; private CardFactory _cardFactory; private int _coins, _experience, _level, _maxLevel; private string _name, _spriteName; public BagManagement bagManagement { get{return _bagManagement;} } public List<ConcreteCard> cardBag { get{ return _cardBag;} } public List<ConcreteCard> playCardSet { get{ return _playCardSet;} } public int coins { get{ return _coins;} set{ _coins = value;} } public string playerName { get{ return _name;} } public int level { get{ return _level;} } public int experience { get{ return _experience;} set { if (value < _experience) { Debug.Log ("Decrease of experience is forbidden"); throw new System.ArgumentException ("experience"); } _experience = value; int newLevel = level; while (newLevel<BaseCard._experienceTable.Count&&_experience>BaseCard._experienceTable[newLevel-1]) { _experience -= BaseCard._experienceTable [newLevel - 1]; newLevel++; } if (_experience > BaseCard._experienceTable [newLevel - 1]) {//When experience exceed the max,it equals the max _experience = BaseCard._experienceTable [newLevel - 1]; } _level = newLevel; } } public string spriteName { get{ return _spriteName;} set{ _spriteName = value;} } void Awake () { // _gameController = GameObject.FindGameObjectWithTag (Tags.gameController).GetComponent<GameController> (); _playCardSet = new List<ConcreteCard> (); _cardBag = new List<ConcreteCard> (); _cardFactory = CardFactory.GetCardFactory (); Load (); } // Use this for initialization void Start () { _bagManagement.Load (); } // Update is called once per frame void Update () { } public void Save () { } void Load () { LoadFromJson (); LoadFromPlayerPrefs (); } public void LoadFromPlayerPrefs () { } //when player first enter the game,load information from json and all default card are with level 1. public void LoadFromJson () { TextAsset textAsset = Resources.Load<TextAsset> (ResourcesFolderPath.json_player + "/player"); if (textAsset == null) { Debug.Log ("Player json information file access error"); throw new System.Exception ("Player json information file access error"); } string json = textAsset.text; Dictionary<string,object> dict = MiniJSON.Json.Deserialize (json)as Dictionary<string,object>; Dictionary<string,object> playerInfo = dict ["player"] as Dictionary<string,object>; List<string> CardSet = (playerInfo ["cardSet"] as List<object>).ConvertAll (x => x.ToString ()); foreach (string str in CardSet) { // Debug.Log(str); try { if (_cardFactory.ContainsCard (str)) { _cardBag.Add (_cardFactory.GeneConcreteCard (str)); } else { _cardBag.Add (_cardFactory.GeneConcreteCard (System.Convert.ToInt32 (str))); } } catch (System.Exception e) { Debug.Log (string.Format ("Card:{0} access error", str)); throw e; } } for (int i = 0; i < 5; i++) { if (_cardBag.Count > 0) { _playCardSet.Add (_cardBag [0]); _cardBag.RemoveAt (0); } else { _playCardSet.Add (null); } } _coins = System.Convert.ToInt32 (playerInfo ["coins"]); _name = playerInfo ["playerName"].ToString (); _spriteName = _name; _experience = 0; _level = 1; } public void Sell (List<ConcreteCard> sellList) { foreach (var item in sellList) { _coins += item.price; _cardBag.Remove (item); } } public void GainNewCard(ConcreteCard newCard) { _cardBag.Add (newCard); _bagManagement.AddNewCardToBag (newCard); } } <file_sep>/Abandon/DirectEffectAbility.cs using UnityEngine; using System.Collections; public class DirectEffectAbility : AbilityBase { protected static int[] experiencePerLevel; protected int _maxLevel; public int maxLevel { get{return _maxLevel;} set{_maxLevel=value;} } protected int _experience; // protected int _maxExperienceViaLevel; protected int _level; protected object _pureValue; public DirectEffectAbility (AbilityBase baseAbility):base(baseAbility) { _maxLevel = 1; _experience = 0; _level = 1; _pureValue = base.baseValue; } void ExperienceIncrease(int amount) { _experience += amount; while (_level<_maxLevel&&_experience>=experiencePerLevel[_level-1]) { _experience-=experiencePerLevel[_level-1]; LevelIncrease(); } if (_experience > experiencePerLevel [_level - 1]) _experience = experiencePerLevel [_level - 1]; } void LevelIncrease() { } // public void attack(Card card) // { // // CastAbility (card, targetAttr, baseValue, relative,proportional); // } public static void SetExperiencePerLevel(int[] experienceArray) { experiencePerLevel = experienceArray; // maxLevel = experienceArray.Length; } } <file_sep>/Assets/Scripts/AbilityDisplayer.cs using UnityEngine; using System.Collections; public class AbilityDisplayer : MonoBehaviour { public UILabel _abilityLevel; public UISprite _icon; public AbilityDetailDisplayer _abilityDetailDisplayer; Ability _ability; bool _displayed = false; float _timeToShowDetail = 2f; float _ShowTimer = float.NegativeInfinity; // void Start () // { // gameObject.SetActive (false); // } // Update is called once per frame void Update () { _ShowTimer += Time.deltaTime; if (_ShowTimer > _timeToShowDetail && _displayed == false) { _abilityDetailDisplayer.DisplayerAbilityDetail (_ability, transform.position.y); _displayed = true; } } public void LoadAbility (Ability ability) { _ability = ability; _icon.spriteName=ability.name; _abilityLevel.text = ability.level.ToString (); gameObject.SetActive (true); // Debug.Log("loadabili"); } void OnHover (bool isOver) { if (isOver) { _ShowTimer = 0; } else { if (_displayed) { _abilityDetailDisplayer.HideAbilityDetail (); } _displayed = false; _ShowTimer = float.NegativeInfinity; } } } <file_sep>/Assets/Scripts/Battle/CardAIScript.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class CardAIScript : MonoBehaviour { private BattleControl _battleControl; private GameObject _shieldPanelGO; private List<BattleCardShell> _candidateCards; private bool _run; public bool run { get{return _run;} set{_run=value;} } void Awake () { _battleControl = GetComponent<BattleControl> (); _run = false; _candidateCards = new List<BattleCardShell> (); } void Start() { _shieldPanelGO = _battleControl.shieldPanel.gameObject; } void Update () { if (_run && !_shieldPanelGO.activeInHierarchy) { BattleCardShell activeShell = GetRandomActivaEnemy (); if (activeShell == null) {//No active enemy EnemiesActionOver (); return; } List<Ability> abilities = activeShell.battleCard.abilities; Dictionary<Ability,int> cdTable = activeShell.battleCard.abilityCDTable; for (int i = abilities.Count-1; i >=0; i--) { Ability ability = abilities [i]; if (cdTable [ability] >= ability.cooldown && ability.mana <= activeShell.battleCard.mana) { BattleCardShell targetShell; switch (ability.targetType) { case TargetType.All: { int ran = Random.Range (0, 1); if (ran == 0) { targetShell = GetRandomShell (_battleControl._enemyCardShellSet); } else { targetShell = GetRandomShell (_battleControl._playerCardShellSet); } break; } case TargetType.Friend: { targetShell = GetRandomShell (_battleControl._enemyCardShellSet); break; } case TargetType.Enemy: { targetShell = GetRandomShell (_battleControl._playerCardShellSet); break; } case TargetType.Self: { targetShell = activeShell; break; } default: targetShell = null; break; } if (targetShell != null) { if (ability.targetArea == TargetArea.Area) {//If ability is AOE,cast at the middle of enemies; activeShell.CastAbility (ability, targetShell.shellQueue [0].battleCard); } else { activeShell.CastAbility (ability, targetShell.battleCard); } } } } } } public void EnemiesActionStart () { _run = true; } void EnemiesActionOver () { _run = false; _battleControl.RoundEnd (); } BattleCardShell GetRandomActivaEnemy () { foreach (var item in _battleControl._enemyCardShellSet) { if (item.vacant == false && item.hasCast == false) { _candidateCards.Add (item); } } if (_candidateCards.Count == 0) return null; int index = Random.Range (0, _candidateCards.Count - 1); BattleCardShell returnCard = _candidateCards [index]; _candidateCards.Clear (); return returnCard; } /// <summary> /// Gets the random shell from shell set. /// </summary> /// <returns>The random shell.</returns> /// <param name="shellSet">Player set or enemy set.</param> BattleCardShell GetRandomShell (BattleCardShell[] shellSet) { foreach (var item in shellSet) { if (item.vacant == false) { _candidateCards.Add (item); } } if (_candidateCards.Count == 0) return null; int index = Random.Range (0, _candidateCards.Count - 1); BattleCardShell returnCard = _candidateCards [index]; _candidateCards.Clear (); return returnCard; } } <file_sep>/Assets/Scripts/GameController/GameController.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class GameController : MonoBehaviour { PlayerControl _player; public List<LevelGateControl> _levels; LevelGateControl _selectLevel; public SwordControl _SwordForSelection; SceneFade _sceneFade; BattleControl _battleController; void Awake () { _player = GameObject.FindGameObjectWithTag (Tags.player).GetComponent<PlayerControl> (); _sceneFade = GameObject.FindGameObjectWithTag (Tags.sceneFader).GetComponent<SceneFade> (); _battleController = GameObject.FindGameObjectWithTag (Tags.battle).GetComponent<BattleControl> (); _levels = new List<LevelGateControl> (); } void Start () { Init (); Load (); _sceneFade.ExitFading (); } // Update is called once per frame void Update () { } /// <summary> /// Save imformation about game controller. /// </summary> void Save () { // PlayerPrefs.SetInt (_uniqueIdentityString + "_mapWidth", _mapWidth); // //PlayerPrefs.SetInt (_uniqueIdentityString+ "_selectMapIndex", _selectMapIndex); // PlayerPrefs.SetInt (_uniqueIdentityString + "_firstLockIndex", _lastUnlockIndex); // PlayerPrefs.SetInt (_uniqueIdentityString, 1); } /// <summary> /// Auto save after complete battle.This method may be called by star counter /// </summary> public void SaveAfterCompleteBattle () {//Should Save data of game controller,player controller,select level and of star counter Save (); _player.Save (); _selectLevel.Save (); } /// <summary> /// Load this data of game contorller and proccess relative operations /// </summary> void Load () { } /// <summary> /// Loads data from json and do proccessing. /// </summary> void LoadFromJson (Dictionary<string,object> dict) { } /// <summary> /// Loads data from playerprefs and do proccessing. /// </summary> void LoadFromPlayerPrefs () { } public void LightPathPoints (int levelIndex) { if (levelIndex - 1 >= 0) { _levels [levelIndex - 1].LightPathPoints (); } } /// <summary> /// Initialize game controller. /// </summary> void Init () { foreach (GameObject go in GameObject.FindGameObjectsWithTag (Tags.levelGate)) { _levels.Add (go.GetComponent<LevelGateControl> ()); } _levels.Sort (); _levels [0].Unlock (); LevelButtonClick(_levels[0]); } public void LevelButtonClick (LevelGateControl level) { if (level != _selectLevel) { _SwordForSelection.Show (level.transform.position); _selectLevel = level; } else { BattleStart (level.GetComponent<LevelInfo> ()); } } public void BattleStart (LevelInfo levelInfo) { _sceneFade.BeginFading (); gameObject.AddComponent<RunOnCondition> ().RunWhenBoolChange (_sceneFade.IsOpeque, true, delegate { _battleController.LoadLevel (levelInfo); _battleController.gameObject.SetActive (true); _sceneFade.ExitFading (); // _battleController.gameObject.AddComponent<RunOnCondition> ().RunWhenBoolChange (delegate { // return _sceneFade.gameObject.activeSelf; // }, // false, delegate { // _battleController.RotateShells (); // }); }); } public void BattleComplete () { // Debug.Log ("GC_battleComplete1"); gameObject.AddComponent<RunOnCondition> ().RunWhenBoolChange (delegate { return _sceneFade.gameObject.activeSelf; }, false, delegate { _selectLevel.LevelComplete (); SaveAfterCompleteBattle (); } ); } void AllSave () { } } <file_sep>/Assets/Scripts/Card/Abitity/AbilityBase.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Reflection; /// <summary> /// Generate a ability entity according to the ability that casted. /// </summary> public delegate AbilityEntity AbilityCast (Ability ability,BattleCard from,BattleCard to); //public delegate Ability AbilityLevelUpdater(Ability ability,int level); public class AbilityBase { #region Instance members private int _id; private Rarity _rarity; private AbilityType _abilityType; private TargetType _targetType; private TargetArea _targetArea; private int _maxLevel; private string _name, _description, _icon, _targetAttr, _abilityCast; // _effectCard; public List<string> _variables; public List<List<int>> _variableValueTable; #endregion #region Properties public int id { get{ return _id;} private set{ if(value<=0) { Debug.Log("Attribute id should not be negative"); throw new ArgumentException("Attribute id should not be negative"); } _id=value;} } public string icon { get{return _icon;} private set{_icon=value;} } public Rarity rarity { get{return _rarity;} private set{ Array array= Enum.GetValues( typeof(Rarity)); for (int i = 0; i < array.Length; i++) { if((Rarity)array.GetValue(i)==value) { _rarity=value; return; } } Debug.Log(string.Format("Illegal ability rarity value :{0}" ,value)); throw new System.ArgumentException(string.Format("Illegal ability rarity value :{0}" ,value)); } } public AbilityType abilityType { get{ return _abilityType;} private set{_abilityType=value;} } public TargetType targetType { get{return _targetType;} private set{_targetType=value;} } public TargetArea targetArea { get{return _targetArea;} private set{_targetArea=value;} } public int maxLevel { get{ return _maxLevel;} private set{ if(value<0) { Debug.Log("Attribute maxLevel should not be negative"); throw new ArgumentException("Attribute maxLevel should not be negative"); } _maxLevel=value;} } public string name { get{ return _name;} } public string description { get{ return _description;} private set{_description=value;} } public string targetAttr { get{ return _targetAttr;} private set{_targetAttr=value;} } public List<object> variableValueTable { get{ return _variableValueTable.ConvertAll(x=>(object)x);} private set{ _variableValueTable=value.ConvertAll(x=>{ List<int> intList=(x as List<object>).ConvertAll(y=>System.Convert.ToInt32(y)); return intList;}); } } public string abilityCast { get{ return _abilityCast;} private set{_abilityCast=value;} } // public string effectCard { // get{ return _effectCard;} // private set{_effectCard=value;} // } public List<object> variables { get{ return _variables.ConvertAll(x=>(object)x);} private set{ _variables=value.ConvertAll(x=>x.ToString()); } } #endregion private AbilityBase() {} public static AbilityBase GeneAbilityBase(KeyValuePair<string,Dictionary<string,object>> abilityInfo) { AbilityBase abilityBase=new AbilityBase(); abilityBase._name=abilityInfo.Key; Type type=typeof(AbilityBase); Dictionary<string,object> abilityFeilds=abilityInfo.Value; foreach(string feildName in abilityFeilds.Keys) { PropertyInfo propertyInfo= type.GetProperty(feildName); if(propertyInfo==null) { Debug.Log(string.Format("Illegal field:ability feild '{0}' does not exist",feildName)); throw new System.FieldAccessException(string.Format("Illegal field:ability feild '{0}' does not exist",feildName)); } object valueOb=abilityFeilds[feildName]; if(propertyInfo.PropertyType.IsEnum) { try{ System.Convert.ToInt32(valueOb); }catch{ valueOb= Enum.Parse(propertyInfo.PropertyType,(string)valueOb); } if(!Enum.IsDefined(propertyInfo.PropertyType,valueOb)) { Debug.Log(string.Format("Illegal {0} value :{1}" ,propertyInfo.PropertyType,valueOb)); throw new System.ArgumentException(string.Format("Illegal {0} value :{1}" ,propertyInfo.PropertyType,valueOb)); } } // Debug.Log(propertyInfo.Name); // Debug.Log(valueOb.GetType()+","+propertyInfo.PropertyType); if(valueOb.GetType()!=propertyInfo.PropertyType) { valueOb=System.Convert.ChangeType (valueOb,propertyInfo.PropertyType); } propertyInfo.SetValue(abilityBase,valueOb,null); } if(!abilityBase.CheckInstanceFields()) { throw new System.ArgumentException(string.Format("The ability data is deficient in ability that named:{0}",abilityBase.name)); } return abilityBase; } bool CheckInstanceFields() { bool bPass=true; if(_id<=0){ Debug.Log("Lack of id data"); bPass=false; } // if(_effectCard==null) // { // Debug.Log("Lack of effectCard data"); // bPass=false; // } if(_abilityCast==null) { Debug.Log("Lack of abilityCast data"); bPass=false; } if(_maxLevel<=0) { Debug.Log("Lack of maxLevel data"); bPass=false; } if(_variableValueTable==null||_variableValueTable.Count==0) { Debug.Log("Lack of variableValueTable data"); bPass=false; }else{ if(_variableValueTable.Count!=_maxLevel) { bPass=false; } } if(_variables==null||_variables.Count==0) { Debug.Log("Lack of variables data"); bPass=false; }else if(_variableValueTable!=null&&_variableValueTable.Count>=1) { if(_variables.Count!=_variableValueTable[0].Count) { Debug.Log("Count of variables is incosistent with item of variableValueTable"); bPass=false; } } return bPass; } } <file_sep>/Assets/Scripts/Layers/PathPointControl.cs using UnityEngine; using System.Collections; using System; using Holoville.HOTween; public class PathPointControl : MonoBehaviour { public PathPointControl _nextPathPoint; public LevelGateControl _nextLevelGate; float _glowTime = 0.4f; bool _active; UISprite _sprite; // Use this for initialization void Awake () { _sprite = GetComponent<UISprite> (); _active = false; gameObject.SetActive(false); } // Update is called once per frame void Update () { } /// <summary> ///Activate by game progress.Animation can be inserted /// </summary> public void Activate () { if (_active == false) { _active = true; HOTween.To (_sprite, _glowTime, new TweenParms ().Prop ("alpha", 1f).Ease (EaseType.Linear).OnStart(()=>{ gameObject.SetActive(true); _sprite.alpha=0f; }).OnComplete (ActivateNext)); } } void ActivateNext () { if (_nextPathPoint != null) _nextPathPoint.Activate (); else if (_nextLevelGate != null) _nextLevelGate.Unlock (); } public void Init (bool show) { if (show) { gameObject.SetActive (true); _active = true; _sprite.alpha = 1f; if (_nextPathPoint != null) { _nextPathPoint.Init (show); } } } } <file_sep>/Assets/Scripts/Card/Abitity/AbilityEntity.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class AbilityEntity { #region Instance menbers protected int _id; protected string _name; protected Dictionary<string ,int> _variables; protected string _targetAttr; protected BattleCard _targetCard; protected BattleCard _castCard; protected AbilityType _abilityType; protected EffectCard _effectCard; #endregion #region Properties public int abilityId { get{return _id;} } public string name { get{return _name;} } public BattleCard castCard { get{return _castCard;} set{_castCard=value;} } public BattleCard targetCard { get{return _targetCard;} set{_targetCard=value;} } public AbilityType abilityType { get{return _abilityType;} set{_abilityType=value;} } public EffectCard effectCard { get{return _effectCard;} set{_effectCard=value;} } public string targetAttr { get{return _targetAttr;} set{_targetAttr=value;} } #endregion protected AbilityEntity() { _variables = new Dictionary<string, int> (); } public AbilityEntity(int abilityId,string name,BattleCard from ,BattleCard to,AbilityType abilityType,EffectCard effectCard,string targetAttr=null):this() { castCard = from; targetCard = to; this.abilityType = abilityType; this.effectCard = effectCard; this.targetAttr = targetAttr; _id = abilityId; _name=name; } /// <summary> /// Sets or adds variable to this AbilityEntity. /// </summary> /// <param name="name">Variable name.</param> /// <param name="value">Variable value.</param> public void SetValue(string name,int value) { _variables[name]=value; } /// <summary> /// Gets a variable of this AbilityEntity by name. /// </summary> /// <returns>Variablie value.</returns> /// <param name="name">Variable name.</param> public int GetValue(string name) { return _variables [name]; } void OnTriggleEnter(Collider other) { BattleCard targetBattleCard=other.GetComponent<BattleCard>(); if (targetBattleCard == targetCard) { } } } <file_sep>/Abandon/0827/CardQuality.cs using UnityEngine; using System.Collections; public enum CardQuality { Normal,Excellent,Elite,Legendary,Epic }; <file_sep>/Assets/Scripts/Card/CardEffectedStatic.cs using UnityEngine; using System.Collections; /// <summary> /// This delegate is owed by BattleCard and is called when abilityEntity hit the BattleCard /// </summary> public delegate void CardEffected(AbilityEntityShell abilityES); public static class CardEffectedStatic { public static CardEffected CardEffected_Normal = delegate(AbilityEntityShell abilityES) { if(abilityES.abilityEntity.abilityType== AbilityType.Physical) { int odds=Random.Range(0,100); if(odds<abilityES.abilityEntity.targetCard.evasion) { abilityES.Abort(); abilityES.abilityEntity.targetCard.Evade(); return; } } abilityES.Hit(); }; } <file_sep>/Abandon/levelGateRelative/GameController.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class GameController : MonoBehaviour { /// <summary> /// The json data file. /// </summary> public TextAsset _jsonDataFile; public int _mapWidth; PlayerControl _player; // StarCounterControl _starCounter; List<MapLayerControl> _maps; int _selectMapIndex; public List<LevelGateControl> _levels; public LevelGateControl _selectLevel; string _uniqueIdentityString; /// <summary> /// The index of the last unlocked level.If all the levels are unlocked ,this param equals _levels.Count-1 /// </summary> int _lastUnlockIndex; LevelGateControl _lastUnlockLevel; public SwordControl _SwordForSelection; List<PathPointControl> _pathPoints; SceneFade _sceneFade; BattleControl _battleController; public Dictionary<string,object> _allInfoDict; void Awake () { if (_jsonDataFile != null) _allInfoDict = MiniJSON.Json.Deserialize (_jsonDataFile.text) as Dictionary<string ,object>; _uniqueIdentityString = transform.parent.name + name + GetType ().ToString (); _player = GameObject.FindGameObjectWithTag (Tags.player).GetComponent<PlayerControl> (); // _starCounter = GameObject.FindGameObjectWithTag (Tags.starCounter).GetComponentInChildren<StarCounterControl> (); _sceneFade = GameObject.FindGameObjectWithTag (Tags.sceneFader).GetComponent<SceneFade> (); _battleController = GameObject.FindGameObjectWithTag (Tags.battle).GetComponent<BattleControl> (); //_battleController.gameObject.SetActive (false); _maps = new List<MapLayerControl> (); _levels = new List<LevelGateControl> (); _pathPoints = new List<PathPointControl> (); } void Start () { Init (); Load (); _sceneFade.ExitFading (); } // Update is called once per frame void Update () { } /// <summary> /// Save imformation about game controller. /// </summary> void Save () { PlayerPrefs.SetInt (_uniqueIdentityString + "_mapWidth", _mapWidth); //PlayerPrefs.SetInt (_uniqueIdentityString+ "_selectMapIndex", _selectMapIndex); PlayerPrefs.SetInt (_uniqueIdentityString + "_firstLockIndex", _lastUnlockIndex); PlayerPrefs.SetInt (_uniqueIdentityString, 1); } /// <summary> /// Auto save after complete battle.This method may be called by star counter /// </summary> public void SaveAfterCompleteBattle () {//Should Save data of game controller,player controller,select level and of star counter Save (); _player.Save (); _selectLevel.Save (); } /// <summary> /// Load this data of game contorller and proccess relative operations /// </summary> void Load () { LoadFromJson (_allInfoDict); if (PlayerPrefs.GetInt (_uniqueIdentityString) == 1) LoadFromPlayerPrefs (); } /// <summary> /// Loads data from json and do proccessing. /// </summary> void LoadFromJson (Dictionary<string,object> dict) { } /// <summary> /// Loads data from playerprefs and do proccessing. /// </summary> void LoadFromPlayerPrefs () { //Load data _mapWidth = PlayerPrefs.GetInt (_uniqueIdentityString + "_mapWidth"); _lastUnlockIndex = PlayerPrefs.GetInt (_uniqueIdentityString + "_firstLockIndex"); //process data //Locate map layers position _maps [_selectMapIndex].transform.localPosition = Vector3.zero; for (int i = 0; i < _maps.Count; i++) { if (i < _selectMapIndex) _maps [i].transform.localPosition = new Vector3 (-_mapWidth, 0, 0); else if (i > _selectMapIndex) _maps [i].transform.localPosition = new Vector3 (_mapWidth, 0, 0); } //active path points for (int i = 0; i < _pathPoints.Count; i++) { _pathPoints [i].SetActivated (); if (_pathPoints [i]._nextLevelGate != null && _lastUnlockIndex < _levels.Count && _pathPoints [i]._nextLevelGate == _levels [_lastUnlockIndex]) break; } } public void UnlockLevel () { _lastUnlockIndex++; } /// <summary> /// Initialize game controller. /// </summary> void Init () { foreach (GameObject go in GameObject.FindGameObjectsWithTag (Tags.mapLayer)) { _maps.Add (go.GetComponent<MapLayerControl> ()); } _maps.Sort (); _selectMapIndex = 0; foreach (GameObject go in GameObject.FindGameObjectsWithTag (Tags.levelGate)) { _levels.Add (go.GetComponent<LevelGateControl> ()); } _levels.Sort (); for (int i = 0; i < _levels.Count; i++) { _levels [i].SetLevelIndex (i); } _selectLevel = null; //level No.1 start unlocked _levels [0].GetComponent<LevelInfo> ().Unlock (); _lastUnlockIndex = 0; foreach (GameObject go in GameObject.FindGameObjectsWithTag(Tags.pathPoint)) { _pathPoints.Add (go.GetComponent<PathPointControl> ()); } _pathPoints.Sort (); for (int i = 0; i < _pathPoints.Count-1; i++) { if (_pathPoints [i]._pointPostfix == 1 && _pathPoints [i]._levelPostfix > 0) _levels [_pathPoints [i]._levelPostfix - 1]._nextPathPoint = _pathPoints [i]; if (_pathPoints [i]._pointPostfix == _pathPoints [i + 1]._pointPostfix - 1) { _pathPoints [i]._nextPathPoint = _pathPoints [i + 1]; } else { if (_pathPoints [i]._levelPostfix < _levels.Count) _pathPoints [i]._nextLevelGate = _levels [_pathPoints [i]._levelPostfix]; } } if (_pathPoints [_pathPoints.Count - 1]._levelPostfix < _levels.Count) _pathPoints [_pathPoints.Count - 1]._nextLevelGate = _levels [_pathPoints [_pathPoints.Count - 1]._levelPostfix]; _battleController.gameObject.SetActive (false); } public void LevelButtonClick (LevelGateControl level) { if (level != _selectLevel) { if (_selectLevel != null && _selectLevel.GetMapLayer () == _maps [_selectMapIndex]) { _selectLevel = level; _SwordForSelection.Disappear (ShowSword); } else { _selectLevel = level; ShowSword (); } } else { BattleStart (level.GetComponent<LevelInfo> ()); } } void ShowSword () { // Debug.Log ("showSword"); _SwordForSelection.transform.parent = _selectLevel.GetMainButton ().transform; _SwordForSelection.transform.localPosition = Vector3.zero; _SwordForSelection.transform.localScale = Vector3.one; _SwordForSelection.Show (); } public void BattleStart (LevelInfo levelInfo) { _sceneFade.BeginFading (); gameObject.AddComponent<RunOnCondition> ().RunWhenBoolChange (_sceneFade.IsOpeque, true, delegate { _battleController.LoadLevel (levelInfo); _maps [_selectMapIndex].gameObject.SetActive (false); _battleController.gameObject.SetActive (true); _sceneFade.ExitFading (); _battleController.gameObject.AddComponent<RunOnCondition> ().RunWhenBoolChange (delegate{ return _sceneFade.gameObject.activeSelf;}, false, delegate { _battleController.RotateShells (); }); }); } public void BattleComplete (StarNum starNum) { Debug.Log ("GC_battleComplete1"); _sceneFade.BeginFading (); gameObject.AddComponent<RunOnCondition> ().RunWhenBoolChange (_sceneFade.IsOpeque, true, delegate { _maps [_selectMapIndex].gameObject.SetActive (true); _battleController.gameObject.SetActive (false); _sceneFade.ExitFading (); gameObject.AddComponent<RunOnCondition> ().RunWhenBoolChange (delegate { return _sceneFade.gameObject.activeSelf; }, false, delegate { Debug.Log("battlecomplete"); _selectLevel.GainStar (starNum); SaveAfterCompleteBattle (); } ); } ); Debug.Log ("GC_battleComplete"); // _selectLevel.GainStar (starNum); // SaveAfterCompleteBattle (); } public void MapLayerLeftButtonClick () { if (_selectMapIndex > 0) { _maps [_selectMapIndex - 1].transform.localPosition += new Vector3 (_mapWidth, 0, 0); _maps [_selectMapIndex].transform.localPosition += new Vector3 (_mapWidth, 0, 0); _selectMapIndex--; } } public void MapLayerRightButtonClick () { if (_selectMapIndex + 1 < _maps.Count) { _maps [_selectMapIndex + 1].transform.localPosition -= new Vector3 (_mapWidth, 0, 0); _maps [_selectMapIndex].transform.localPosition -= new Vector3 (_mapWidth, 0, 0); _selectMapIndex++; } } void AllSave () { } } <file_sep>/Abandon/0827/BaseAbility.cs using UnityEngine; using System.Collections; public abstract class BaseAbility : MonoBehaviour { public AbilityType _abilityType; public TargetType _targetType; public string _name; public string _description; public string _targetAttr; public object _Value; //public IAbilityEffect _abilityEffect; public abstract void CastAbility(RealCard card); // // public virtual } <file_sep>/Assets/Scripts/Card/Rarity.cs using UnityEngine; using System.Collections; public enum Rarity { Normal,Rare,Precious,Legendary,Epic }; <file_sep>/Assets/Scripts/Player/BattleSlot.cs using UnityEngine; using System.Collections; public class BattleSlot : MonoBehaviour { public UISprite _Icon; public UISprite _Edge; public UILabel _level; private ConcreteCard _concreteCard; private BagManagement _bagManagement; private float _clickTiming = 0.3f, _clickTimer = 0, _hoverTiming = 2f, _hoverTimer = float.NegativeInfinity; public ConcreteCard concreteCard { get{ return _concreteCard;} } public UIWidget slotBody { get{ return _Icon;} } public int Index { get; set; } void Awake () { _bagManagement = GetComponentInParent<BagManagement> (); } void Update () { _clickTimer += Time.deltaTime; _hoverTimer += Time.deltaTime; if (_hoverTimer > _hoverTiming) { _bagManagement.SlotShowDetail (this); _hoverTimer = float.NegativeInfinity; } } void OnClick () { if (_clickTimer > _clickTiming) { _bagManagement.SlotClick (this); _clickTimer = 0f; } } void OnHover (bool isOver) { if (isOver) { _hoverTimer = 0; } else { _hoverTimer = float.NegativeInfinity; } } public void LoadConcreteCard (ConcreteCard card) { _concreteCard = card; _Icon.spriteName = card.name; Deselect (); _Icon.alpha = 1; _level.text = card.level.ToString (); _level.color = RarityColorStatic.rarityColors [(int)card.rarity]; } public void UpdateData() { if(_concreteCard!=null){ _level.text = _concreteCard.level.ToString (); } } public void Select () { _Edge.color = Color.white; } public void Deselect () { _Edge.color = Color.black; } void SlotClick () { _bagManagement.SlotClick (this); } void SlotHover () { _bagManagement.SlotShowDetail (this); } public void Unload () { _concreteCard = null; _Icon.alpha = 0; } }
7bb0fc959dc070741a893e1eecc5d0f34f134dac
[ "C#", "Text" ]
97
C#
xxl534/CardProject
a6ef57a39155f33968c52fb2554d7a0961a8671f
afc721f1280d283bd849afda17841b6067ad7db1
refs/heads/master
<file_sep>import React, { Component } from "react"; import "./App.css"; import { API, graphqlOperation } from "aws-amplify"; import { withAuthenticator } from "aws-amplify-react"; const ListCities = ` query list { listCitys { items { id name description } } } `; const CreateCity = ` mutation($name: String!, $description: String) { createCity(input: { name: $name description: $description }) { id name description } } `; const SubscribeToCities = ` subscription { onCreateCity { id name description } } `; class App extends Component { state = { cities: [], name: "", description: "" }; async componentDidMount() { const cities = await API.graphql(graphqlOperation(ListCities)); this.setState({ cities: cities.data.listCitys.items }); API.graphql(graphqlOperation(SubscribeToCities)).subscribe({ next: eventData => { const city = eventData.value.data.onCreateCity; const cities = [ ...this.state.cities.filter(i => { return i.name !== city.name && i.description !== city.description; }), city ]; this.setState({ cities }); } }); } onChange = e => { this.setState({ [e.target.name]: e.target.value }); }; createCity = async () => { if (this.state.city === "" || this.state.description === "") return; const city = { name: this.state.name, description: this.state.description }; try { const cities = [...this.state.cities, city]; this.setState({ cities, name: "", description: "" }); await API.graphql(graphqlOperation(CreateCity, city)); console.log("success"); } catch (err) { console.log("error", err); } }; render() { return ( <div className="App"> <div style={{ padding: 20, display: "flex", flexDirection: "column" }}> <input value={this.state.name} name="name" onChange={this.onChange} style={{ height: 35, margin: 10 }} /> <input value={this.state.description} name="description" onChange={this.onChange} style={{ height: 35, margin: 10 }} /> <button onClick={this.createCity}>Create City</button> </div> {this.state.cities.map((c, i) => ( <div key={i}> <h3>{c.name}</h3> <p>{c.description}</p> </div> ))} </div> ); } } export default withAuthenticator(App, { includeGreeting: true }); // export default App;
fcaaf4053b8ee661eb1561ffd5cc124d76227e94
[ "JavaScript" ]
1
JavaScript
bysa/city-info
2556281e817344fb4b89655f4f2fc1bde04a6a37
c0cb200655667bcaf30a6c97696ba5a0239e79e8
refs/heads/main
<repo_name>Vaishnavmatte/Project1.O<file_sep>/PROJECT 1.O.py #!/usr/bin/env python # coding: utf-8 # In[27]: #STUDENT DETAIL PROJECT# name=str(input('enter student name')) clas=int(input('enter the standard')) division=str(input('enter the division')) Rollno=int(input('enter the roll no')) Subject1=str(input('enter the subject1')) mark1=int(input('enter the marks of subject1')) Subject2=str(input('enter the subject2')) mark2=int(input('enter the mark of subject2')) print("Student Details") print("name: "+name) print("clas: ",clas) print("division: ",division) print("Rollno: ",Rollno) print("marks of: ",Subject1+" ",mark1) print("marks of: ",Subject2+" ",mark2) # In[ ]: # In[ ]:
7cf6271a3ad7091b0ecd0785f79c1e8af8d94dea
[ "Python" ]
1
Python
Vaishnavmatte/Project1.O
0952dbbcec70737dac3ef40b2457bd093b12e1b3
3be68c55fcebefc7cce8d4cc1bfa7dae0c250062
refs/heads/master
<repo_name>hpdnnr7/kwk-t1-ttt-2-board-rb-teachers-l1<file_sep>/lib/board.rb # Define the variable board below. board = 9 board = [ " ", " ", " ", " ", " ", " ", " ", " ", " ", ]
216bb08fe1d5152887c4f58965c6e9dbdb79a3d2
[ "Ruby" ]
1
Ruby
hpdnnr7/kwk-t1-ttt-2-board-rb-teachers-l1
71424bb8a601a946eed7e4900877b0d62cb124b5
c877c2f9b3d77bcc40b90d4f430211a098bcd7a2
refs/heads/master
<repo_name>psbanka/react-talk<file_sep>/README.md This repository is used as a companion-piece to a talk to be given on ReactJS. See associated `react-talk.pdf` file for a place to start. <file_sep>/Makefile # # Makefile # .PHONY: build test build: ./node_modules/gulp/bin/gulp.js js test: ./node_modules/jest-cli/bin/jest.js test-watch: fswatch-run -l 0.2 src/talk3/*.js src/talk3/__tests__/*.js ./node_modules/jest-cli/bin/jest.js <file_sep>/src/talk3/__tests__/SearchBar-test.js /** @jsx React.DOM */ jest.dontMock('../SearchBar.js'); var React = require('react/addons'); var TestUtils = React.addons.TestUtils; var SearchBar = require('../SearchBar.js'); function logObject(o) { var cache = []; var output = JSON.stringify(o, function(key, value) { if (typeof value === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { // Circular reference found, discard key return; } cache.push(value); } return value; }, 2); cache = null; console.log(output); } describe('SearchBar', function() { it('creates a searchbar with the correct placeholder', function () { var filterText = ''; var inStockOnly = false; var searchBar = TestUtils.renderIntoDocument( <SearchBar filterText = {filterText} inStockOnly = {inStockOnly} /> ); var form = TestUtils.findRenderedDOMComponentWithTag(searchBar, 'form'); var inputBoxes = TestUtils.scryRenderedDOMComponentsWithTag(searchBar, 'input'); expect(inputBoxes.length).toEqual(2); var paragraph = TestUtils.findRenderedDOMComponentWithTag(searchBar, 'p'); expect(paragraph.getDOMNode().textContent).toEqual('Only show products in stock'); }); it('has the proper initial search text', function () { var filterText = 'cheese'; var inStockOnly = false; var searchBar = TestUtils.renderIntoDocument( <SearchBar filterText = {filterText} inStockOnly = {inStockOnly} /> ); expect(searchBar.props.filterText).toEqual('cheese'); }); }); <file_sep>/src/talk3/__tests__/ProductTable-test.js /** @jsx React.DOM */ jest.dontMock('../ProductTable.js'); var React = require('react/addons'); var TestUtils = React.addons.TestUtils; var ProductTable = require('../ProductTable.js'); describe('ProductTable', function() { var productTable; var cars = [{ category: 'cars', name: 'civvic', price: '$25000.00', stocked: false, }, { category: 'cars', name: 'corolla', price: '$29000.00', stocked: true, }]; it('makes four rows when the filter is blank', function() { var productTable = TestUtils.renderIntoDocument( <ProductTable products={cars} filterText = {''} inStockOnly = {false} /> ); var tableRows = TestUtils.scryRenderedDOMComponentsWithTag(productTable, 'tr'); expect(tableRows.length).toEqual(4); // spot-check expect(tableRows[0].getDOMNode().textContent).toEqual('NamePrice'); expect(tableRows[1].getDOMNode().textContent).toEqual('cars'); expect(tableRows[2].getDOMNode().textContent).toEqual('civvic$25000.00'); }); it('makes only three rows when the filter is useful', function() { var productTable = TestUtils.renderIntoDocument( <ProductTable products={cars} filterText = {'olla'} inStockOnly = {false} /> ); var tableRows = TestUtils.scryRenderedDOMComponentsWithTag(productTable, 'tr'); expect(tableRows.length).toEqual(3); expect(tableRows[2].getDOMNode().textContent).toEqual('corolla$29000.00'); }); it('makes only two rows when the filter eliminates all', function() { var productTable = TestUtils.renderIntoDocument( <ProductTable products={cars} filterText = {'theraininspain'} inStockOnly = {false} /> ); var tableRows = TestUtils.scryRenderedDOMComponentsWithTag(productTable, 'tr'); expect(tableRows.length).toEqual(1); }); it('can filter based on stock', function() { var productTable = TestUtils.renderIntoDocument( <ProductTable products={cars} filterText = {''} inStockOnly = {true} /> ); var tableRows = TestUtils.scryRenderedDOMComponentsWithTag(productTable, 'tr'); expect(tableRows.length).toEqual(3); expect(tableRows[2].getDOMNode().textContent).toEqual('corolla$29000.00'); }); }); <file_sep>/src/talk3/__tests__/hello-test.js /** @jsx React.DOM */ jest.dontMock('../hello.js'); var React = require('react/addons'); var Hello = require('../hello.js'); var TestUtils = React.addons.TestUtils; describe('hello', function() { it('makes a proper greeting', function() { var hello = TestUtils.renderIntoDocument( <Hello name="John" /> ); var helloItem = TestUtils.findRenderedDOMComponentWithTag(hello, 'div'); var domNode = helloItem.getDOMNode(); expect(helloItem.getDOMNode().textContent).toEqual('Hello John'); }); });
31519993cd0c3e7b9196deb8da0ed260fd489828
[ "Markdown", "JavaScript", "Makefile" ]
5
Markdown
psbanka/react-talk
5515996c834c0c5031bbd406f6fa945817606e0b
45083c0a464c796daa062caa7109fa8ce2841e55
refs/heads/master
<file_sep>library(testthat) library(nanny) test_check("nanny") <file_sep>## ---- echo=FALSE, include=FALSE----------------------------------------------- library(knitr) knitr::opts_chunk$set(cache = TRUE, warning = FALSE, message = FALSE, cache.lazy = FALSE) library(dplyr) library(tidyr) library(ggplot2) library(purrr) library(magrittr) library(nanny) my_theme = theme_bw() + theme( panel.border = element_blank(), axis.line = element_line(), panel.grid.major = element_line(size = 0.2), panel.grid.minor = element_line(size = 0.1), text = element_text(size=12), legend.position="bottom", aspect.ratio=1, strip.background = element_blank(), axis.title.x = element_text(margin = margin(t = 10, r = 10, b = 10, l = 10)), axis.title.y = element_text(margin = margin(t = 10, r = 10, b = 10, l = 10)) ) ## ---- eval=FALSE-------------------------------------------------------------- # # devtools::install_github("stemangiola/nanny") # ## ----------------------------------------------------------------------------- mtcars_tidy = mtcars %>% as_tibble(rownames="car_model") %>% mutate_at(vars(-car_model,- hp, -vs), scale) %>% gather(feature, value, -car_model, -hp, -vs) mtcars_tidy ## ----mds, cache=TRUE---------------------------------------------------------- mtcars_tidy_MDS = mtcars_tidy %>% reduce_dimensions(car_model, feature, value, method="MDS", .dims = 3) ## ----plot_mds, cache=TRUE----------------------------------------------------- mtcars_tidy_MDS %>% subset(car_model) %>% select(contains("Dim"), everything()) mtcars_tidy_MDS %>% subset(car_model) %>% GGally::ggpairs(columns = 4:6, ggplot2::aes(colour=factor(vs))) ## ----pca, cache=TRUE, message=FALSE, warning=FALSE, results='hide'------------ mtcars_tidy_PCA = mtcars_tidy %>% reduce_dimensions(car_model, feature, value, method="PCA", .dims = 3) ## ----plot_pca, cache=TRUE----------------------------------------------------- mtcars_tidy_PCA %>% subset(car_model) %>% select(contains("PC"), everything()) mtcars_tidy_PCA %>% subset(car_model) %>% GGally::ggpairs(columns = 4:6, ggplot2::aes(colour=factor(vs))) ## ----tsne, cache=TRUE, message=FALSE, warning=FALSE, results='hide'----------- mtcars_tidy_tSNE = mtcars_tidy %>% reduce_dimensions(car_model, feature, value, method = "tSNE") ## ----------------------------------------------------------------------------- mtcars_tidy_tSNE %>% subset(car_model) %>% select(contains("tSNE"), everything()) mtcars_tidy_tSNE %>% subset(car_model) %>% ggplot(aes(x = `tSNE1`, y = `tSNE2`, color=factor(vs))) + geom_point() + my_theme ## ----rotate, cache=TRUE------------------------------------------------------- mtcars_tidy_MDS.rotated = mtcars_tidy_MDS %>% rotate_dimensions(`Dim1`, `Dim2`, .element = car_model, rotation_degrees = 45, action="get") ## ----plot_rotate_1, cache=TRUE------------------------------------------------ mtcars_tidy_MDS.rotated %>% ggplot(aes(x=`Dim1`, y=`Dim2`, color=factor(vs) )) + geom_point() + my_theme ## ----plot_rotate_2, cache=TRUE------------------------------------------------ mtcars_tidy_MDS.rotated %>% ggplot(aes(x=`Dim1 rotated 45`, y=`Dim2 rotated 45`, color=factor(vs) )) + geom_point() + my_theme ## ----cluster, cache=TRUE------------------------------------------------------ mtcars_tidy_cluster = mtcars_tidy_MDS %>% cluster_elements(car_model, feature, value, method="kmeans", centers = 2, action="get" ) ## ----plot_cluster, cache=TRUE------------------------------------------------- mtcars_tidy_cluster %>% ggplot(aes(x=`Dim1`, y=`Dim2`, color=cluster_kmeans)) + geom_point() + my_theme ## ----SNN, cache=TRUE, message=FALSE, warning=FALSE, results='hide', include=FALSE, eval=FALSE, echo=FALSE---- # mtcars_tidy_SNN = # mtcars_tidy_tSNE %>% # cluster_elements(car_model, feature, value, method = "SNN") ## ----SNN_plot, cache=TRUE, include=FALSE, eval=FALSE, echo=FALSE-------------- # mtcars_tidy_SNN %>% # subset(car_model) %>% # select(contains("tSNE"), everything()) # # mtcars_tidy_SNN %>% # subset(car_model) %>% # ggplot(aes(x = `tSNE1`, y = `tSNE2`, color=cluster_SNN)) + geom_point() + my_theme # ## ----drop, cache=TRUE--------------------------------------------------------- mtcars_tidy_non_redundant = mtcars_tidy_MDS %>% remove_redundancy(car_model, feature, value) ## ----plot_drop, cache=TRUE---------------------------------------------------- mtcars_tidy_non_redundant %>% subset(car_model) %>% ggplot(aes(x=`Dim1`, y=`Dim2`, color=factor(vs))) + geom_point() + my_theme ## ----drop2, cache=TRUE, include=FALSE, eval=FALSE, echo=FALSE----------------- # mtcars_tidy_non_redundant = # mtcars_tidy_MDS %>% # remove_redundancy( # car_model, feature, value, # method = "reduced_dimensions", # Dim_a_column = `Dim1`, # Dim_b_column = `Dim2` # ) ## ----plot_drop2, cache=TRUE, include=FALSE, eval=FALSE, echo=FALSE------------ # mtcars_tidy_non_redundant %>% # subset(car_model) %>% # ggplot(aes(x=`Dim1`, y=`Dim2`, color=factor(vs))) + # geom_point() + # my_theme # ## ----------------------------------------------------------------------------- mtcars_tidy_non_rectangular = mtcars_tidy %>% slice(-1) ## ----------------------------------------------------------------------------- mtcars_tidy_non_rectangular %>% fill_missing(car_model, feature, value, fill_with = 0) ## ----------------------------------------------------------------------------- mtcars_tidy_non_rectangular %>% mutate(vs = factor(vs)) %>% impute_missing( car_model, feature, value, ~ vs) %>% # Print imputed first arrange(car_model != "Mazda RX4" | feature != "mpg") ## ----------------------------------------------------------------------------- mtcars_tidy_permuted = mtcars_tidy %>% permute_nest(car_model, c(feature,value)) mtcars_tidy_permuted ## ----------------------------------------------------------------------------- mtcars_tidy %>% combine_nest(car_model, value) ## ----------------------------------------------------------------------------- mtcars_tidy_permuted %>% # Summarise mpg mutate(data = map(data, ~ .x %>% filter(feature == "mpg") %>% summarise(mean(value)))) %>% unnest(data) %>% # Lower triangular lower_triangular(car_model_1, car_model_2, `mean(value)`) ## ----------------------------------------------------------------------------- mtcars_tidy %>% keep_variable(car_model, feature, value, top=10) ## ----------------------------------------------------------------------------- mtcars_tidy %>% select(car_model, feature, value) %>% spread(feature, value) %>% as_matrix(rownames = car_model) %>% head() ## ----------------------------------------------------------------------------- mtcars_tidy %>% subset(car_model) ## ----------------------------------------------------------------------------- mtcars_tidy %>% nest_subset(data = -car_model) ## ---- cache=TRUE-------------------------------------------------------------- mtcars_tidy ## ---- cache=TRUE-------------------------------------------------------------- mtcars_tidy %>% reduce_dimensions( car_model, feature, value, method="MDS" , .dims = 3, action="add" ) ## ---- cache=TRUE-------------------------------------------------------------- mtcars_tidy %>% reduce_dimensions( car_model, feature, value, method="MDS" , .dims = 3, action="get" ) ## ---- cache=TRUE-------------------------------------------------------------- mtcars_tidy %>% reduce_dimensions( car_model, feature, value, method="MDS" , .dims = 3, action="only" )
4bf9a79b2a47304977967a64b6e58165ba70df47
[ "R" ]
2
R
cran/nanny
4c2e29b8b6081c6de1219266f032a32a435f5994
3f8cc56af72faaaf2000d7d189b94cfb2b8acdc6
refs/heads/main
<file_sep>import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.util.Date; import java.util.Scanner; public class BirthdayCalculator { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Welcome to the 100% Scientifically Accurate Birthday Calculator!"); System.out.println("\nWhat's your birthday?"); String userInput = input.nextLine(); //System.out.println(userInput); String dayBorn = ""; String dayCurrent = ""; String currentDate = ""; String daysLeft = ""; String nextAge = ""; SimpleDateFormat formatter=new SimpleDateFormat("MM-dd-yyyy"); try { Date date = formatter.parse(userInput); //System.out.println("Given:" + date); SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE"); dayBorn = dateFormat.format(date).toUpperCase(); LocalDate currentDateLD = LocalDate.now(); String [ ] dateString = userInput.split("-"); String currentYearBirthday = dateString[0]+"-"+dateString[1]+"-"+currentDateLD.getYear(); Date date2 = formatter.parse(currentYearBirthday); dayCurrent = dateFormat.format(date2).toUpperCase(); currentDate = currentDateLD.getMonthValue() + "-" + currentDateLD.getDayOfMonth() + "-" + currentDateLD.getYear(); Date date3 = formatter.parse(currentDate); long difference_In_Time = date2.getTime() - date3.getTime(); long difference_In_Days = (difference_In_Time / (1000 * 60 * 60 * 24)) % 365; long difference_In_TimeAge = date2.getTime() - date.getTime(); long difference_In_Years = (difference_In_TimeAge / (1000l * 60 * 60 * 24 * 365)); if (difference_In_Days < 0){ String nextYearDate = dateString[0]+"-"+dateString[1]+"-"+(currentDateLD.getYear()+1); Date date4 = formatter.parse(nextYearDate); //System.out.println("date4:" + nextYearDate); //System.out.println("date3:" + currentDate); difference_In_Time = date4.getTime() - date3.getTime(); difference_In_Days = (difference_In_Time / (1000 * 60 * 60 * 24)) % 365; difference_In_Years++; } else if(difference_In_Days == 0){ difference_In_Days = 365; // not accounting leap years difference_In_Years++; } daysLeft = difference_In_Days + ""; nextAge = difference_In_Years + ""; System.out.println("\nThat means you were born on a " + dayBorn + "!"); System.out.println("This year it falls on a " + dayCurrent + "..."); System.out.println("And since today is " + currentDate + ","); System.out.println("there's only " + daysLeft + " until the next one when you turn " + nextAge + "!"); } catch (ParseException e) { e.printStackTrace(); } } }
e3e1e4ef3cdaf557b3201b6a7017e2d2d2886d1b
[ "Java" ]
1
Java
Ant1997/mthree_BirthdayCalculator
1c3c06335aebbb715c301f6ca2b7f09a419f2669
90dd1b76583cb105fa4f3ce366439e6aa07f43ec
refs/heads/main
<repo_name>BiaNunes4/ProjetoNovo<file_sep>/src/mock/api.js import { createServer } from 'miragejs'; const server = createServer({ routes() { this.namespace = 'api'; this.get('/messages', (schema, request) => { let params = request.queryParams; Object.keys(params).forEach( key => { if(!params[key]){ delete params[key]; } } ) return schema.db.messages.where(params); }); this.post('/message', (schema, request) => { return schema.db.messages.insert(request.requestBody); }); this.get('/channels', (schema) => { return schema.db.channels; }); this.get('/triggers', (schema) => { return schema.db.triggers; }); } }); server.db.loadData( { messages: [ { id: 1, channel: 'whatsapp', trigger: 'falou_atendimento', timer: '10:00', message: ' Mensagem de teste' }, { id: 56, channel: 'whatsapp', trigger: 'fez_pix', timer: '5:00', message: ' Mensagem de teste' }, { id: 9875, channel: 'whatsapp', trigger: 'comprou_tele_sena', timer: '37:00', message: 'Deseja deletar essa chave mesmo' }, ], channels: [ { id: 1, name: 'sms' }, { id: 2, name: 'whatsapp' }, { id: 3, name: 'email' }, { id: 4, name: 'Messenger' }, ], triggers: [ { id: 1, name: 'falou_atendimento' }, { id: 2, name: 'fez_pix' }, { id: 3, name: 'fez_transferencia' }, { id: 4, name: 'comprou_tele_sena' }, ] } )<file_sep>/src/routes/index.jsx import { Switch, Route, Redirect } from "react-router" import {Dashboard as DashboardPage, Home as HomePage} from '../pages'; import {Header} from '../components'; import { Snackbar } from "@material-ui/core"; import { useState } from "react"; const ProtectedRoutes = () => { const [openSnackbar, setOpenSnackbar] = useState(false); const [snackbarContent, setSnackbarContent] = useState(''); const handleCloseSnackbar = () => {} return ( <> <Header /> <div className="container pageWrapper"> <Switch> <Route path='/dashboard' component={DashboardPage}/> <Route path='/messages' component={HomePage}/> <Route path='/' exact> <Redirect to="/messages" /> </Route> </Switch> <Snackbar anchorOrigin={{ vertical:'top', horizontal:'top' }} open={openSnackbar} onClose={handleCloseSnackbar} message={snackbarContent} key={Math.random()} /> </div> </> ) } const Routes = () => { return ( <> <Switch> <Route path='/'> <ProtectedRoutes /> </Route> </Switch> </> ) } export { Routes }
4ea1cfbd7a13ad023eb4cb62ea37b0bd38461fbb
[ "JavaScript" ]
2
JavaScript
BiaNunes4/ProjetoNovo
1ba39cf83cc25229ef7ca5c7a97de89ff2d2bdc4
12db0d10b6b10ab532a9f07f087823d58ebf79ec
refs/heads/master
<file_sep>from flask import Flask, render_template, request, redirect, session, flash import re import md5 import os, binascii salt = binascii.b2a_hex(os.urandom(15)) from mysqlconnection import MySQLConnector app = Flask(__name__) app.secret_key = 'secret' EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') mysql = MySQLConnector(app,'login_reg_db') @app.route('/') def index(): if 'user' not in session: return render_template('login.html') else: return render_template('index.html') @app.route('/home', methods=['GET','POST']) def home(): return redirect('/') @app.route('/login', methods=['POST']) def login(): query = "SELECT * FROM users WHERE email = :email" data = { 'email': request.form['email'] } match = mysql.query_db(query, data) if len(match) > 0: encrypted_password = md5.new(request.form['password'] + match[0]['salt']).hexdigest() if match[0]['password'] == encrypted_password: session['user'] = { 'id': match[0]['id'], 'fname': match[0]['fname'], 'lname': match[0]['lname'], 'email': match[0]['email'] } return redirect('/') else: flash('Invalid password!') return redirect('/') else: return redirect('/register') @app.route('/register') def reg(): return render_template('register.html') @app.route('/register', methods=['POST']) def register(): error = False if len(request.form['fname']) < 2 and request.form['fname'].isalpha()==False: error = True flash('First name needs to be at least 2 characters and include letters only') if len(request.form['lname']) < 2 and request.form['lname'].isalpha()==False: error = True flash('Last name needs to be at least 2 characters and include letters only') if not EMAIL_REGEX.match(request.form['email']): error = True flash('Enter a valid email') if len(request.form['password']) in range(0,9): error = True flash('Password needs to be at least 8 characters') if request.form['password'] != request.form['confirm']: error = True flash('Passwords do not match') if error == False: salt = binascii.b2a_hex(os.urandom(15)) hashed_pw = md5.new(request.form['password'] + salt).hexdigest() query = "INSERT INTO users (fname, lname, email, password, salt, created_at, updated_at) VALUES (:fname, :lname, :email, :hashed_pw, :salt, NOW(), NOW())" data = { 'fname': request.form['fname'], 'lname': request.form['lname'], 'email': request.form['email'], 'hashed_pw': hashed_pw, 'salt': salt } user = mysql.query_db(query, data) session['user'] = { 'fname': request.form['fname'], 'lname': request.form['lname'], 'email': request.form['email'] } return redirect('/') else: return redirect('/register') @app.route('/friends') def friends(): query = "SELECT users.id, CONCAT(user2.fname,' ',user2.lname) as name, user2.email as email, DATE_FORMAT(friendships.created_at, '%M %e, %Y') as friends_since FROM users LEFT JOIN friendships ON users.id = friendships.user_id LEFT JOIN users as user2 ON user2.id = friendships.friend_id WHERE users.id = :user_id" data = { 'user_id': session['user']['id'] } friends = mysql.query_db(query, data) return render_template('friends.html', friends = friends) @app.route('/addfriend', methods=['POST']) def addfriend(): if request.form['email'] == session['user']['email']: flash('Cannot add self as friend') return redirect('/friends') query = "SELECT users.id, users.fname, CONCAT(user2.fname,' ',user2.lname) as name, user2.email as email FROM users LEFT JOIN friendships ON users.id = friendships.user_id LEFT JOIN users as user2 ON user2.id = friendships.friend_id WHERE users.id = :user_id AND user2.email = :email" data = { 'user_id': session['user']['id'], 'email': request.form['email'] } repeat = mysql.query_db(query, data) if len(repeat) > 0: flash('Already a friend!') return redirect('/friends') query = "SELECT * FROM users WHERE email = :email" data = { 'email': request.form['email'] } friend = mysql.query_db(query, data) if len(friend) > 0: query = "INSERT INTO friendships(user_id, friend_id, created_at, updated_at) VALUES (:user_id, :friend_id, NOW(), NOW())" data = { 'user_id': session['user']['id'], 'friend_id': friend[0]['id'], } addfriend = mysql.query_db(query, data) else: flash('Friend not found') return redirect('/friends') @app.route('/message', methods=['POST']) def message(): query = "INSERT INTO messages (content, created_at, updated_at, user_id) VALUES (:content, NOW(), NOW(), :user_id)" data = { 'content': request.form['message'], 'user_id': session['user']['id'] } message = mysql.query_db(query, data) return redirect('/wall') @app.route('/comment', methods=['POST']) def comment(): query = "INSERT INTO comments (content, created_at, updated_at, message_id, user_id) VALUES (:content, NOW(), NOW(), :message_id, :user_id)" data = { 'content': request.form['comment'], 'message_id': request.form['msgid'], 'user_id': session['user']['id'] } comment = mysql.query_db(query, data) return redirect('/wall') @app.route('/wall') def wall(): query = "SELECT messages.id, messages.content as messages_content, DATE_FORMAT(messages.created_at, '%M %e, %Y at %h: %m %p') as time, DATE_FORMAT(messages.created_at, '%h: %m') as timer, CONCAT(users.fname,' ',users.lname) as name, comments.message_id as comment_id, comments.content as comment, DATE_FORMAT(comments.created_at, '%M %e, %Y at %h: %m %p') as comment_time, CONCAT(user2.fname,' ',user2.lname) as commenter_name FROM messages JOIN users ON messages.user_id = users.id LEFT JOIN comments ON comments.message_id = messages.id JOIN users as user2 ON comments.user_id = user2.id ORDER BY messages.id DESC" # messages = mysql.query_db("SELECT * FROM messages") # # for message in messages: # message['comments'] = mysql.query_db("SELECT * FROM comments WHERE message_id = :m_id", {'m_id': message['id']}) posts = mysql.query_db(query) box = {} for post in posts: if post['id'] in box: box[post['id']]['comments'].append({'comment': post['comment'], 'comment_time': post['comment_time'], 'commenter_name': post['commenter_name']}) else: box[post['id']] = post box[post['id']]['comments'] = [] box[post['id']]['comments'].append({'comment': post['comment'], 'comment_time': post['comment_time'], 'commenter_name': post['commenter_name']}) for post in box.values(): for comment in post['comments']: print comment return render_template('wall.html', posts = posts, box=box) @app.route('/logout', methods=['POST']) def logout(): session.pop('user') return redirect('/') app.run(debug=True)
e2b9d7a9e7d1a29fb7dd98b90193906af3f2ed44
[ "Python" ]
1
Python
derberbaby/social_page
9ffc37393c5eca1dc25c3d19b27d47621d04171d
50e6876cbcb8c65ecb21c6eb082560f7ade154a1
refs/heads/master
<repo_name>Kizirinoff/CG_courses<file_sep>/AnimatedBall1/RasterWindow.cpp #include "RasterWindow.h" bool RasterWindow::isAnimating() const { return m_isAnimating; } void RasterWindow::setAnimating(bool isAnimating) { m_isAnimating = isAnimating; if (isAnimating) { renderLater(); } } // В конструкторе создадим в динамической памяти новый объект QBackingStore. // В современном C++ не принято использовать "new", но пока вы работаете с Qt, // "new" - это норма, т.к. Qt использует особый механизм управления памятью // parent-child. // Именно поэтому мы передали "this" в конструктор QBackingStore. // Объект класса RasterWindow становится родителем объекта класса QBackingStore. // Когда будет вызван деструктор RasterWindow, Qt удалит и все дочерние объекты. constexpr unsigned WINDOW_WIDTH = 600; constexpr unsigned WINDOW_HEIGHT = 600; // Также мы изменим два существующих метода: конструктор и метод renderNow. // В конструкторе мы будем создавать новый объект сцены, связывая его отношением // parent-child с классом окна путём передачи указателя this: RasterWindow::RasterWindow(QWindow *parent) : QWindow(parent) , m_backingStore(new QBackingStore(this)) , m_scene(std::make_unique<PoolTableScene>(RectF{ 0, 0, float(WINDOW_WIDTH), float(WINDOW_HEIGHT) })) { setMinimumSize(QSize(WINDOW_WIDTH, WINDOW_HEIGHT)); m_updateTimer.start(); } // Опишем метод event: этот метод вызывается при // каждом событии окна, поэтому при его написании следует // действовать аккуратно bool RasterWindow::event(QEvent *event) { if (event->type() == QEvent::UpdateRequest) { renderNow(); return true; } return QWindow::event(event); } // Опишем метод exposeEvent: этот метод класса QWindow // библиотека Qt вызывает при фактическом показе окна. void RasterWindow::exposeEvent(QExposeEvent *) { if (isExposed()) { renderNow(); } } // Опишем метод resizeEvent : этот метод класса QWindow // библиотека Qt вызывает при изменении размера окна. void RasterWindow::resizeEvent(QResizeEvent *resizeEvent) { // Изменяем размер буфера кадра, чтобы он совпадал с размером окна m_backingStore->resize(resizeEvent->size()); if (isExposed()) { renderNow(); } } // Метод “renderLater” будет добавлять в очередь // событий Qt событие обновления экрана (UpdateRequest), // тем самым форсируя перерисовку кадра в ближайшем будущем. void RasterWindow::renderLater() { requestUpdate(); } void RasterWindow::updateScene() { const float MAX_INTERVAL = 0.1f; const float elapsedSeconds = float(m_updateTimer.elapsed()) / 1000.f; // Пропуск обновления в случае, если таймер не успел засечь прошедшее время. if (elapsedSeconds > 0) { m_updateTimer.restart(); m_scene->update(std::min(elapsedSeconds, MAX_INTERVAL)); } } void RasterWindow::renderScene() { QRect rect(0, 0, width(), height()); m_backingStore->beginPaint(rect); QPaintDevice *device = m_backingStore->paintDevice(); QPainter painter(device); painter.fillRect(0, 0, width(), height(), Qt::white); m_scene->redraw(painter); painter.end(); m_backingStore->endPaint(); m_backingStore->flush(rect); } // Теперь реализуем самый сложный метод класса — renderNow. // Метод будет запускать рисование на буфере кадра, очищать // буфер, а потом готовый буфер выводить на экран. void RasterWindow::renderNow() { if (!isExposed()) { return; } updateScene(); renderScene(); if (m_isAnimating) { renderLater(); } } /* QRect rect(0, 0, width(), height()); m_backingStore->beginPaint(rect); QPaintDevice *device = m_backingStore->paintDevice(); QPainter painter(device); painter.fillRect(0, 0, width(), height(), Qt::white); render(&painter); painter.end(); m_backingStore->endPaint(); m_backingStore->flush(rect); // Перейдите к методу “RasterWindow::renderNow()” и // добавьте в конец метода планирование перерисовки: if (m_isAnimating) { renderLater(); } // Остался всего один метод “render”, в котором мы // установим параметры кисти рисования и нарисуем эллипс. */ void RasterWindow::render(QPainter *painter) { // Устанавливаем режим устранения ступенчатости фигур (anti-aliasing mode) painter->setRenderHint(QPainter::Antialiasing); // Устанавливаем кисть жёлтого цвета (цвет задан в RGB) painter->setBrush(QBrush(QColor(0xFA, 0xFE, 0x78))); // Рисуем эллипс на всё окно с отступом 5 пикселей painter->drawEllipse(QRect(5, 5, width() - 10, height() - 10)); } <file_sep>/AnimatedBall1/RasterWindow.h #pragma once // Подключаем заголовки используемых классов. #include <QtGui/QWindow> #include <QtGui/QPainter> #include <QtGui/QResizeEvent> #include <QtGui/QExposeEvent> #include <QtGui/QBackingStore> #include "PoolTableScene.h" #include <QtCore/QElapsedTimer> #include <memory> // Класс RasterWindow наследует все поля и методы класса QWindow class RasterWindow : public QWindow { // Макрос Q_OBJECT является меткой для Qt moc - генератора кода в составе Qt SDK Q_OBJECT public: // Начало секции публично доступных полей и методов // Добавьте в класс RasterWindow новые // публичные методы “isAnimating” и “setAnimating”: bool isAnimating() const; void setAnimating(bool isAnimating); // Затем добавьте булево поле для хранения данных этого свойства //bool m_isAnimating = false; // Конструктор класса: принимает один (опциональный) параметр типа QWindow, // в этом параметре можно передать родительское окно (например, для модального диалога) explicit RasterWindow(QWindow *parent = 0); protected: // Начало секции полей и методов, доступных только в наследниках этого класса // Ниже перегружены полиморфные методы родительского класса QWindow // Библиотека Qt рассылает различные события по этим методам // - метод event вызывается перед обработкой любых событий, включая resizeEvent и exposeEvent bool event(QEvent *event) override; // - метод exposeEvent вызывается при показе окна void exposeEvent(QExposeEvent *event) override; // - метод resizeEvent вызывается при изменении размера окна void resizeEvent(QResizeEvent *event) override; private: // Начало секции полей и методов, доступных только в наследниках этого класса void renderNow(); void renderLater(); void updateScene(); // обновляет состояние сцены void renderScene(); // перерисовывает содержимое сцены void render(QPainter *painter); // Класс QBackingStore предоставляет окну буфер рисования кадра. // Грубо говоря, этот буфер содержит будущие пиксели окна и позволяет // рисовать векторную графику (фигуры, изображения, текст), заполняя // этот буфер пикселей. QBackingStore *m_backingStore = nullptr; std::unique_ptr<PoolTableScene> m_scene; // объект сцены QElapsedTimer m_updateTimer; // таймер обновления сцены bool m_isAnimating = false; }; <file_sep>/AnimatedBall1/PoolTableScene.h #pragma once #include <QtGui/QPainter> #include "Vector2f.h" #include "RectF.h" #include <iostream> // Класс PoolTableScene реализует сцену бильярдного стола, с шариками и стенками. class PoolTableScene { public: explicit PoolTableScene(const RectF& bounds); void update(float deltaSeconds); void redraw(QPainter& painter); private: Vector2f m_ballPosition; //Vector2f m_ballSpeed; const Vector2f m_ballSize; const RectF m_bounds; float m_time = 0; float m_ballPositionX = 50; float m_ballPositionY = 50; bool m_positivX = true; bool m_positivY = true; };
732fa82165b80f480f7df468dbb586942a5f331c
[ "C++" ]
3
C++
Kizirinoff/CG_courses
5eb52fd484baaff3fefc3dbd3ae20a0abecd94f1
a393ca24d786b04aca919ad73b18799b0d92514e
refs/heads/master
<repo_name>giowe/express-explorer<file_sep>/src/static/scripts/headers.js export const getRequestHeaders = (inputs) => { const headers = {}; const headerKeys = []; const headerValues = []; for (let i = 0; i < inputs.length - 2; i++) { const input = inputs[i]; let empty = false; if (input.getAttribute('target') === 'Headers') { if (input.getAttribute('placeholder') === 'key') { empty = !input.value; if (!empty) headerKeys.push(input.value); } else { if (!empty) headerValues.push(input.value); } } } for (let i = 0; i < headerKeys.length; i++) { headers[headerKeys[i]] = headerValues[i]; } return headers; }; export const getResponseHeader = (headers) => { const keys = [...headers.keys()]; const values = [...headers.values()]; const resHeader = {}; keys.map((key, i) => resHeader[key] = values[i]); return resHeader; }; export const mergeHeaders = (headers1 = {}, headers2 = {}) => { return Object.assign(headers1, headers2) }; <file_sep>/src/static/scripts/settings.js import { getRequestHeaders } from './headers'; import { addParam, fillParamsFromObject } from './params'; export const openSettings = (panelID) => { const panel = document.getElementById(panelID); panel.classList.remove('slide-from-right'); panel.classList.add('slide-from-left'); }; export const closeSettings = (panelID) => { const panel = document.getElementById(panelID); panel.classList.remove('slide-from-left'); panel.classList.add('slide-from-right'); }; export const getSettings = () => { const settings = window.localStorage.getItem('default-settings'); if (settings) { return settings; } else { window.localStorage.setItem('default-settings', '{}'); return '{}'; } }; export const updateSettings = (context) => { if (context === 'defHd') { const inputs = document.getElementById('settingsPanel').getElementsByTagName('input'); window.localStorage.setItem('default-settings', JSON.stringify(getRequestHeaders(inputs))); } }; export const generateSettingsPanel = () => { const settings = getSettings(); const context = document.getElementById('settingsPanel'); const input = context.getElementsByTagName('input')[0]; for (let i = 0; i < Object.keys(JSON.parse(settings)).length - 1; i++) { addParam(input, `defHd-params-${i}`, 'defHd-container-params', false); } const inputs = context.getElementsByTagName('input'); if (settings === '{}') { inputs[0].value = ''; inputs[1].value = ''; } else { fillParamsFromObject(inputs, settings); } }; <file_sep>/README.md # Express Explorer <div> <a href="https://www.npmjs.com/package/express-explorer"><img src='http://img.shields.io/npm/v/express-explorer.svg?style=flat'></a> <a href="https://www.npmjs.com/package/express-explorer"><img src='https://img.shields.io/npm/dm/express-explorer.svg?style=flat-square'></a> <a href="https://david-dm.org/giowe/express-explorer"><img src='https://david-dm.org/giowe/express-explorer.svg'></a> <a href="https://www.youtube.com/watch?v=Sagg08DrO5U"><img src='http://img.shields.io/badge/gandalf-approved-61C6FF.svg'></a> </div> Autodiscovering route explorer for every Express.js application. <img src="https://raw.githubusercontent.com/giowe/express-explorer/master/express-explorer.png"></img> ## Installation ``` npm install express-explorer ``` ## Usage ``` const express = require('express'); const explorer = require('express-explorer'); const app = new express(); //settings params is optional and these are default values: const settings = { format: 'html' }; app.use('/explorer', explorer(settings)); ``` ## Settings * `format`: `html` (default) or `json`. If param is `html` you will get the explorer panel otherwise all discovered routes are served as a json. Even if you chose to get the html panel you can require the json format passing the query string `?format=json` to the endpoint you chose for the explorer (ex. `/explorer?format=json`). <file_sep>/src/static/scripts/list.js import { panelHeight, animationTime } from './constants'; export const showMethodList = (id) => { const elem = document.getElementById(id); const father = elem.previousElementSibling; let description; if (father.getElementsByClassName) { description = father.getElementsByClassName('right')[0]; } if (elem.style.display === 'none' || elem.style.display === '') { if (description) description.innerHTML = 'close testing panel'; elem.style.display = 'block'; } else { if (description) { description.innerHTML = `open testing panel`; } elem.style.display = 'none'; } }; export const slideDown = (elem) => { const count = elem.getElementsByClassName('method-container').length; elem.style.maxHeight = ((44 * count) + panelHeight).toString() + 'px';; elem.style.opacity = '1'; }; export const slideUp = (elem) => { elem.style.maxHeight = '0'; once(1, () => { elem.style.opacity = '0'; }); }; export const once = (seconds, callback) => { let counter = 0; const time = window.setInterval(() => { counter++; if (counter >= seconds) { callback(); window.clearInterval(time); } }, animationTime); }; <file_sep>/webpack.config.js const webpack = require('webpack'); const config = { context: __dirname + '/src/static/scripts', entry: { app: './index.js', }, module: { loaders: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: 'babel-loader', query: { presets: ['es2015'] } } ] }, output: { path: __dirname + '/build/static', filename: 'scripts.min.js', libraryTarget: 'var', library: 'Lib' }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ] }; module.exports = config; <file_sep>/src/static/scripts/ajax.js import 'whatwg-fetch'; import { showMethodList } from './list'; import { renderJSON, renderText } from './render'; import { getRequestHeaders, getResponseHeader, mergeHeaders } from './headers'; import { getSettings } from './settings'; export const createRequest = (route, method) => { const startTime = (new Date()).getTime(); const methodContainerID = route + '/' + method; const resPanelID = methodContainerID + '-response'; const resPanel = document.getElementById(resPanelID); const inputs = document.getElementById(methodContainerID).getElementsByTagName('input'); const headers = new Headers(mergeHeaders(JSON.parse(getSettings()), getRequestHeaders(inputs))); const queryString = document.getElementById(methodContainerID + '-query-string').value; const prefix = queryString ? '?' : ''; const url = getUrl(route, inputs) + prefix + queryString; const request = { method, headers, url }; const warnings = document.getElementsByClassName(methodContainerID + '-warningText'); if (warnings.length > 0) { for (let i = 0; i < warnings.length; i++) warnings[i].style.display = 'none'; } const bodyMethods = ['put', 'post']; if (bodyMethods.includes(method)) { let bodyContent = document.getElementById(methodContainerID + '-body').value; if (!bodyContent) { bodyContent = {}; } else { bodyContent = JSON.parse(bodyContent); } request.body = JSON.stringify(bodyContent); } window.fetch(url, request) .then(res => res) .then(res => { const resTime = (new Date()).getTime() - startTime; clearPanel(resPanel); populateResponsePanel(res, resPanelID, resTime, route); if (resPanel.style.display === 'none') { showMethodList(resPanelID, 'response'); } }) .catch(() => { clearPanel(resPanel); const container = document.getElementById(methodContainerID); const warning = document.createElement('p'); warning.style.color = 'red'; warning.className = methodContainerID + '-warningText'; warning.innerHTML = 'CONNECTION REFUSED!'; container.insertBefore(warning, container.childNodes[container.childNodes.length - 4]); }); }; export const getUrl = (route, inputs) => { const segments = route.split('/'); let url = ''; const params = []; let j = 0; for (let i = 0; i < inputs.length; i++) { const input = inputs[i]; if (inputs[i].getAttribute('target') === 'Params') { if (input.value) params.push(input.value); else return new Error('undefined params'); } } for (let i = 0; i < segments.length; i++) { const segment = segments[i]; if (segment[0] === ':') { url += '/' + params[j]; j++; } else { url += '/' + segment; } } return url.slice(1); }; export const populateResponsePanel = (res, panelID) => { const urlEl = document.getElementById(`${panelID}-url`); const statusEl = document.getElementById(`${panelID}-status`); const headerEl = document.getElementById(`${panelID}-header`); const bodyEl = document.getElementById(`${panelID}-body`); urlEl.innerHTML = res.url; statusEl.innerHTML = res.status; renderJSON(prettyPrint(JSON.stringify(getResponseHeader(res.headers))), headerEl); res.text().then(text => createBodyView(text, res.headers.get('Content-Type'), bodyEl)); }; export const createBodyView = (text, contentType, container) => { switch (contentType) { case 'application/json; charset=utf-8': renderJSON(prettyPrint(text), container, '200s'); break; default: renderText(text, container, '95'); } }; export const clearPanel = (panel) => { const divs = panel.getElementsByClassName('clearable'); for (let i = 0; i < divs.length; i++) { divs[i].style.display = 'none'; } }; export const prettyPrint = (text) => JSON.stringify(JSON.parse(text), null, 1); <file_sep>/gulpfile.js 'use strict'; const gulp = require('gulp'); const concat = require('gulp-concat'); const imagemin = require('gulp-imagemin'); const pngquant = require('imagemin-pngquant'); const sass = require('gulp-sass'); const cleanCss = require('gulp-clean-css'); const uglify = require('gulp-uglify'); const nodemon = require('gulp-nodemon'); const replace = require('gulp-replace'); const del = require('del'); const webpack = require('webpack-stream'); const config = require('./webpack.config'); gulp.task('clean', () => { return del.sync('./build'); }); gulp.task('images', () => { return gulp.src('src/static/images/*.*') .pipe(imagemin({ optimizationLevel: 3, //png progressive: true, //jpg intralaced: false, //gif mutlipass: false, //svg svgoPlugins: [{ removeViewBox: false }], use: [pngquant()] })) .pipe(gulp.dest('build/static/images')); }); gulp.task('sass', () => { return gulp.src('./src/static/styles/index.scss') .pipe(sass().on('error', sass.logError)) .pipe(concat('styles.min.css')) .pipe(cleanCss({ compatibility: 'ie8' })) .pipe(gulp.dest('./build/static')); }); gulp.task('js', () => { return gulp.src('./src/static/scripts/index.js') .pipe(webpack(config)) .pipe(gulp.dest('./build/static')); }); gulp.task('views', () => { return gulp.src(['./src/views/**/*']) .pipe(gulp.dest('./build/views')); }); gulp.task('root-files', () => { return gulp.src('./src/express-explorer.js') .pipe(gulp.dest('./build')); }); gulp.task('package', () => { return gulp.src('./package.json') .pipe(replace('"private": true', '"private": false')) .pipe(replace(/,([^}]+)"devDependencies"([^}]+)}/, '')) .pipe(gulp.dest('./build')); }); gulp.task('misc', () => { return gulp.src('./README.md') .pipe(gulp.dest('./build')); }); gulp.task('watch', () => { gulp.watch('./src/static/styles/**/*.scss', ['sass']); gulp.watch('./src/static/scripts/**/*.js', ['js']); gulp.watch('./src/views/**/*', ['views']); gulp.watch('./src/express-explorer.js', ['root-files']); gulp.watch('./src/package.json', ['package']); }); gulp.task('build', ['clean', 'images', 'sass', 'js', 'views', 'root-files', 'package', 'misc']); gulp.task('serve', ['build'], () => { return nodemon({ script: 'test-server.js', watch: ['test-server.js', 'src/express-explorer.js', 'src/package.json'] }) }); gulp.task('default', ['serve', 'watch']); <file_sep>/src/static/scripts/render.js import JSONFormatter from 'json-formatter-js'; export const renderText = (text, panel, height) => { const staticViewer = document.createElement('div'); staticViewer.innerText = text; staticViewer.className = 'clearable'; staticViewer.style.minHeight = `${height}px`; panel.appendChild(staticViewer); }; export const renderJSON = (json, panel) => { const frm = new JSONFormatter(json); panel.appendChild(frm.render()); const textContainer = frm.element.getElementsByClassName('json-formatter-string')[0]; frm.element.classList.add('clearable'); textContainer.innerHTML = textContainer.innerHTML.slice(1, -1); }; <file_sep>/src/static/scripts/index.js import * as params from './params'; import * as list from './list'; import * as ajax from'./ajax'; import * as render from './render'; import * as headers from './headers'; import * as settings from './settings'; settings.generateSettingsPanel(); export default Object.assign(params, list, ajax, render, headers, settings);
fb5c067baa31d612684285e6b2fcf3b32ca86488
[ "JavaScript", "Markdown" ]
9
JavaScript
giowe/express-explorer
13aa4e73b2a0dd6cd4ef62fb39808a024a6a2f7a
81b7261db688a8f6a2c1fffffa8e93d58e545798
refs/heads/master
<repo_name>mlair/RunningAppAndroid<file_sep>/app/src/main/java/s2u/project/startservice/GeoService.java package s2u.project.startservice; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.os.Environment; import android.os.IBinder; import android.util.Log; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.location.LocationServices; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Calendar; import java.util.Date; /** * Created by Maxime on 09/10/2016. */ public class GeoService extends Service implements ConnectionCallbacks, OnConnectionFailedListener{ private static final String TAG = "GeoService"; public volatile GoogleApiClient mGoogleApiClient; private boolean isRunning = false; private boolean connected = false; private Thread geoTask; public volatile int LOCATION_INTERVAL; private static final float LOCATION_DISTANCE = 10f; @Override public void onCreate() { Log.i(TAG, "Service onCreate"); if(mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(this). addConnectionCallbacks(this). addOnConnectionFailedListener(this). addApi(LocationServices.API). build(); } isRunning = true; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "Service onStartCommand"); // retrieve LOCATION_INTERVAL LOCATION_INTERVAL = (int) intent.getExtras().get("LOCATION_INTERVAL"); mGoogleApiClient.connect(); Log.i(TAG, "Connected ? " + connected); return Service.START_STICKY; } @Override public void onConnected(Bundle connectionHint) { // We are now connected! Log.i(TAG, "Geo connected!"); connected = true; //Creating new thread for my service // Always write your long running tasks in a separate thread, to avoid being an ass geoTask = new Thread(new Runnable() { @Override public void run() { // Stalker mod : Never stop tracking you while (true) { try { //get Geoloc - Warning coz AndroidStud is dumb as f*ck Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if(mLastLocation != null) { Log.i(TAG, String.valueOf("LOCATION : " + mLastLocation.getLatitude() + " : " + mLastLocation.getLongitude())); String currentDateandTime = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()); appendLog(currentDateandTime, String.valueOf(mLastLocation.getLatitude()), String.valueOf(mLastLocation.getLongitude())); } else { Log.i(TAG, "NOTHING GEO"); } // Save it into a file (if not already created) Thread.sleep(LOCATION_INTERVAL); Log.i(TAG,String.valueOf(LOCATION_INTERVAL)); if (isRunning) { Log.i(TAG, "Service running"); } } catch(InterruptedException e){ Thread.currentThread().interrupt(); // YOU SHALL NOT PASS ! break; } catch(Exception e) { // ow shiww waddup my boy ! } } } }); geoTask.start(); } public void appendLog(String Date, String Lat, String Long) { File logFile = new File(Environment.getExternalStorageDirectory(), "mlairServiceLog"); if (!logFile.exists()) { try { logFile.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { //BufferedWriter for performance, true to set append to file flag BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); buf.append(Date + "#" + Lat + "#" + Long); buf.newLine(); buf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onConnectionSuspended(int cause) { // We are not connected anymore! Log.i(TAG, "Geo suspended!"); connected = false; } @Override public void onConnectionFailed(ConnectionResult result) { // We tried to connect but failed! Log.i(TAG, "Geo failed!"); connected = false; } @Override public IBinder onBind(Intent arg0) { Log.i(TAG, "Service onBind"); return null; } @Override public void onDestroy() { mGoogleApiClient.disconnect(); if(geoTask.isAlive()) { geoTask .interrupt(); } isRunning = false; Log.i(TAG, "Service onDestroy"); } }
9700558f44ad4e9f66a0722703edcbcfe7cc5bda
[ "Java" ]
1
Java
mlair/RunningAppAndroid
e77f10b5b7095f7ea609e3b64f62b20024bb0e80
2ff89d4ff082d40cecee06e375a255522a50de0f
refs/heads/main
<repo_name>NikhileshSinha/High_school_portal<file_sep>/My_High_School/My_High_School/Certificate.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; namespace My_High_School { public partial class Certificate : Form { //SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\nikhilesh sinha\documents\visual studio 2012\Projects\My_High_School\My_High_School\Student_all_info.mdf;Integrated Security=True"); SqlConnection con = new SqlConnection(Properties.Settings.Default.Student_all_infoConnectionString); public Certificate() { InitializeComponent(); } public Certificate(string rol) { InitializeComponent(); display(rol); } public void display(string rol) { con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "select * from Student_details where roll_no = @c"; cmd.Parameters.AddWithValue("@c", rol); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { l1.Text = dr["Student_name"].ToString(); l2.Text = dr["father_name"].ToString(); l3.Text = dr["Mother_name"].ToString(); l4.Text = dr["language"].ToString(); l5.Text = dr["optional"].ToString(); l6.Text = dr["maths"].ToString(); l7.Text = dr["science"].ToString(); l8.Text = dr["social_science"].ToString(); l9.Text = dr["school_name"].ToString(); l10.Text = dr["roll_no"].ToString(); l11.Text = dr["registration_no"].ToString(); l12.Text = dr["Session"].ToString(); l13.Text = dr["DOB"].ToString(); p1.Text = dr["p_lan"].ToString(); p2.Text = dr["p_opt"].ToString(); p3.Text = dr["p_mat"].ToString(); p4.Text = dr["p_sci"].ToString(); p5.Text = dr["p_ss"].ToString(); t1.Text = dr["t_lan"].ToString(); t2.Text = dr["t_opt"].ToString(); t3.Text = dr["t_mat"].ToString(); t4.Text = dr["t_sci"].ToString(); t5.Text = dr["t_ss"].ToString(); int a = int.Parse(p1.Text) + int.Parse(t1.Text) ; tt1.Text = a.ToString(); int b = int.Parse(p2.Text) + int.Parse(t2.Text); tt2.Text = b.ToString(); int c = int.Parse(p3.Text) + int.Parse(t3.Text); tt3.Text = c.ToString(); int d = int.Parse(p4.Text) + int.Parse(t4.Text); tt4.Text = d.ToString(); int e = int.Parse(p5.Text) + int.Parse(t5.Text); tt5.Text = e.ToString(); int tot = a + b + c + d + e; l14.Text = tot.ToString(); if (tot >= 165) { l15.Text = "PASS"; } else { l15.Text = "FAIL"; } grade1(a); grade2(b); grade3(c); grade4(d); grade5(e); } con.Close(); } private void button3_Click(object sender, EventArgs e) { Crud_portal cp = new Crud_portal(); cp.Show(); this.Close(); } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("Printer is not connected "); } public void grade1(int a) { if (100 >= a && a >= 90) { g1.Text = "A1"; } else if (90 > a && a >= 80) { g1.Text = "A2"; } else if (80 > a && a >= 70) { g1.Text = "B1"; } else if (70 > a && a >= 60) { g1.Text = "B2"; } else if (60 > a && a >= 50) { g1.Text = "C1"; } else if (50 > a && a >= 40) { g1.Text = "C2"; } else if (40 > a && a >= 33) { g1.Text = "D1"; } else if (30 > a) { g1.Text = "D2"; } if (g1.Text == "D2") { fp1.Text = "F"; } else { fp1.Text = "P"; } } public void grade2(int a) { if (100 >= a && a >= 90) { g2.Text = "A1"; } else if (90 > a && a >= 80) { g2.Text = "A2"; } else if (80 > a && a >= 70) { g2.Text = "B1"; } else if (70 > a && a >= 60) { g2.Text = "B2"; } else if (60 > a && a >= 50) { g2.Text = "C1"; } else if (50 > a && a >= 40) { g2.Text = "C2"; } else if (40 > a && a >= 33) { g2.Text = "D1"; } else if (30 > a) { g2.Text = "D2"; } if (g2.Text == "D2") { fp2.Text = "F"; } else { fp2.Text = "P"; } } public void grade3(int a) { if (100 >= a && a >= 90) { g3.Text = "A1"; } else if (90 > a && a >= 80) { g3.Text = "A2"; } else if (80 > a && a >= 70) { g3.Text = "B1"; } else if (70 > a && a >= 60) { g3.Text = "B2"; } else if (60 > a && a >= 50) { g3.Text = "C1"; } else if (50 > a && a >= 40) { g3.Text = "C2"; } else if (40 > a && a >= 33) { g3.Text = "D1"; } else if (30 > a) { g3.Text = "D2"; } if (g3.Text == "D2") { fp3.Text = "F"; } else { fp3.Text = "P"; } } public void grade4(int a) { if (100 >= a && a >= 90) { g4.Text = "A1"; } else if (90 > a && a >= 80) { g4.Text = "A2"; } else if (80 > a && a >= 70) { g4.Text = "B1"; } else if (70 > a && a >= 60) { g4.Text = "B2"; } else if (60 > a && a >= 50) { g4.Text = "C1"; } else if (50 > a && a >= 40) { g4.Text = "C2"; } else if (40 > a && a >= 33) { g4.Text = "D1"; } else if (30 > a) { g4.Text = "D2"; } if (g4.Text == "D2") { fp4.Text = "F"; } else { fp4.Text = "P"; } } public void grade5(int a) { if (100 >= a && a >= 90) { g5.Text = "A1"; } else if (90 > a && a >= 80) { g5.Text = "A2"; } else if (80 > a && a >= 70) { g5.Text = "B1"; } else if (70 > a && a >= 60) { g5.Text = "B2"; } else if (60 > a && a >= 50) { g5.Text = "C1"; } else if (50 > a && a >= 40) { g5.Text = "C2"; } else if (40 > a && a >= 33) { g5.Text = "D1"; } else if (30 > a) { g5.Text = "D2"; } if (g5.Text == "D2") { fp5.Text = "F"; } else { fp5.Text = "P"; } } } } <file_sep>/README.md # High_school_portal - This is a High School Portal Program, fully written in C-Sharp, which can insert, delete and update entities properly. ## Features - Insert the data after cheaking it - Update the Data - Genrates Certificate ## How to Install: To install and run this file on your pc, do following steps : 1. Clone or Download zip from repository 2. Extract High_school_portal 3. Locate the project address 4. Now go to "\High_school_portal\High_school_portal\bin\Debug\" 5. Double click on High_school_portal.exe , and program will run safely !!! ## How to Stop Project! Just follow my steps (at first read the whole instruction and then follow them): 1. Open Task Manager in your PC. 2. Search for "High_school_portal" in task manager, and select it. 3. After selecting the running Program, Press "End Task" or "Del" Key! 4. Program'll Successfully Stopped! ## YouTube Tutorial Link : https://youtu.be/_g3CDgEq1-0 ## Thank You! <file_sep>/My_High_School/My_High_School/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; namespace My_High_School { public partial class Form1 : Form { // SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\nikh<NAME>\documents\visual studio 2012\Projects\My_High_School\My_High_School\Student_all_info.mdf;Integrated Security=True"); SqlConnection con = new SqlConnection(Properties.Settings.Default.Student_all_infoConnectionString); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (int.Parse(th1.Text) > 70 || int.Parse(th2.Text) > 70 || int.Parse(th3.Text) > 70 || int.Parse(th4.Text) > 70 || int.Parse(th5.Text) > 70 || int.Parse(pa1.Text) > 30 || int.Parse(pa2.Text) > 30 || int.Parse(pa3.Text) > 30 || int.Parse(pa4.Text) > 30 || int.Parse(pa5.Text) > 30 ) { MessageBox.Show("Some of your marks are given Wrong value\nPlease chech them"); } else{ con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "insert into Student_details values('" + t5.Text + "','" + t2.Text + "','" + t3.Text + "','" + t4.Text + "','" + t1.Text + "','" + dp.Text + "','" + t6.Text + "','" + t7.Text + "','" + cb1.Text + "','" + cb2.Text + "','" + cb3.Text + "','" + cb4.Text + "','" + cb5.Text + "', " + pa1.Text + ", " + th1.Text + ", " + pa2.Text + ", " + th2.Text + ", " + pa3.Text + ", " + th3.Text + ", " + pa4.Text + ", " + th4.Text + ", " + pa5.Text + ", " + th5.Text + ",'"+cb6.Text+"')"; cmd.ExecuteNonQuery(); con.Close(); MessageBox.Show("Entities has been sucessfully inserted !!!!!"); t1.Text = ""; t2.Text = ""; t3.Text = ""; t4.Text = ""; t5.Text = ""; t6.Text = ""; t7.Text = ""; pa1.Text = ""; pa2.Text = ""; pa3.Text = ""; pa4.Text = ""; pa5.Text = ""; th1.Text = ""; th2.Text = ""; th3.Text = ""; th4.Text = ""; th5.Text = ""; cb1.Text = ""; cb2.Text = ""; cb3.Text = ""; cb4.Text = ""; cb5.Text = ""; cb6.Text = ""; con.Close(); } } private void button2_Click(object sender, EventArgs e) { Crud_portal cp = new Crud_portal(); cp.Show(); this.Hide(); } private void button3_Click(object sender, EventArgs e) { Form1 f = new Form1(); f.Show(); this.Hide(); } private void button4_Click(object sender, EventArgs e) { this.Close(); } } } <file_sep>/My_High_School/My_High_School/Crud_portal.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; namespace My_High_School { public partial class Crud_portal : Form { //SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\nikhilesh sinha\documents\visual studio 2012\Projects\My_High_School\My_High_School\Student_all_info.mdf;Integrated Security=True"); SqlConnection con = new SqlConnection(Properties.Settings.Default.Student_all_infoConnectionString); public int abc = 0; public Crud_portal() { InitializeComponent(); } private void button3_Click(object sender, EventArgs e) { Form1 f = new Form1(); f.Show(); this.Hide(); } private void button1_Click(object sender, EventArgs e) { Crud_portal cp = new Crud_portal(); cp.Show(); this.Hide(); } private void button4_Click(object sender, EventArgs e) { display(); } public void display() { con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "select * from Student_details where roll_no = @c"; cmd.Parameters.AddWithValue("@c", t2.Text); DataTable dt1 = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt1); dg1.DataSource = dt1; int i = cmd.ExecuteNonQuery(); if (dt1.Rows.Count == 0) { MessageBox.Show("Invalid Input !!"); t2.Text = ""; } else { abc = 1; } con.Close(); } private void button2_Click(object sender, EventArgs e) { if (abc == 0) { MessageBox.Show("Enter Roll number First"); } else{ con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "update Student_details set " + cb1.Text + " = @ad where roll_no = @c "; cmd.Parameters.AddWithValue("@c", t2.Text); cmd.Parameters.AddWithValue("@ad", t1.Text); cmd.ExecuteNonQuery(); con.Close(); display(); MessageBox.Show("Update Successfuly !!"); t1.Text = ""; cb1.Text = ""; } } private void button7_Click(object sender, EventArgs e) { if (abc == 0) { MessageBox.Show("Enter Roll number First"); } else { con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "update Student_details set optional = @ad where roll_no = @c "; cmd.Parameters.AddWithValue("@c", t2.Text); cmd.Parameters.AddWithValue("@ad", cb2.Text); cmd.ExecuteNonQuery(); con.Close(); display(); MessageBox.Show("Update Successfuly !!"); cb2.Text = ""; } } private void button6_Click(object sender, EventArgs e) { if (abc == 0) { MessageBox.Show("Enter Roll number First"); } else { con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "update Student_details set language = @ad where roll_no = @c "; cmd.Parameters.AddWithValue("@c", t2.Text); cmd.Parameters.AddWithValue("@ad", cb3.Text); cmd.ExecuteNonQuery(); con.Close(); display(); MessageBox.Show("Update Successfuly !!"); cb3.Text = ""; } } private void button5_Click(object sender, EventArgs e) { if (abc == 0) { MessageBox.Show("Enter Roll number First"); } else { con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "update Student_details set DOB = @ad where roll_no = @c "; cmd.Parameters.AddWithValue("@c", t2.Text); cmd.Parameters.AddWithValue("@ad", dp.Text); cmd.ExecuteNonQuery(); con.Close(); display(); MessageBox.Show("Update Successfuly !!"); dp.Text = ""; } } private void button8_Click(object sender, EventArgs e) { if (abc == 0) { MessageBox.Show("Enter Roll number First"); } else { con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "update Student_details set " + cb4.Text + " = @ad where roll_no = @c "; cmd.Parameters.AddWithValue("@c", t2.Text); cmd.Parameters.AddWithValue("@ad", t3.Text); cmd.ExecuteNonQuery(); con.Close(); display(); MessageBox.Show("Update Successfuly !!"); t3.Text = ""; cb4.Text = ""; } } private void button9_Click(object sender, EventArgs e) { if (t4.Text == "") { MessageBox.Show("Enter Roll number First"); } else{ con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "delete from Student_details where roll_no = @c"; cmd.Parameters.AddWithValue("@c", t4.Text); cmd.ExecuteNonQuery(); MessageBox.Show("Entities has been sucessfully deleted !!!! "); con.Close(); } } private void button10_Click(object sender, EventArgs e) { if (t5.Text == "") { MessageBox.Show("Enter Roll number First"); } else { Certificate c = new Certificate(t5.Text); c.Show(); this.Close(); } } } }
09340526f4005165691a083d771611234c34c8e6
[ "Markdown", "C#" ]
4
C#
NikhileshSinha/High_school_portal
5e74da6d489bbbc7d2ef515ccd3ba631851de247
8a5285ee33341cd992625bd3f1e37897e8909e70
refs/heads/master
<repo_name>acltc/ruby_practice_oop<file_sep>/credit_card.rb # Create a CreditCard class with a non-readable account_number attribute # and a method to display only the last 4 digits with the other numbers hidden. # Driver code credit_card = CreditCard.new(5432405832424344) p credit_card.display_account_number # should be "************4344"<file_sep>/lyrics.rb # Create a Song class with a readable title and lyrics attribute (an array of strings) # and a method to display the lyrics. # Driver code song = Song.new( title: "Jump Around", lyrics: [ "Jump around!", "Jump around!", "Jump around!", "Jump up, jump up, and get down!", "Jump!", "Jump!", "Jump!", "Jump!" ] ) p song.title # should be "Jump Around" song.display_lyrics # should display: # Jump around! # Jump around! # Jump around! # Jump up, jump up, and get down! # Jump! # Jump! # Jump! # Jump!<file_sep>/full_name.rb # Create a person class with readable first_name and last_name attributes # and a method to calculate its full_name. # Driver code person = Person.new(first_name: "Peter", last_name: "Jang") p person.first_name # should be "Peter" p person.last_name # should be "Jang" p person.full_name # should be "<NAME>"<file_sep>/area.rb # Create a Rectangle class with readable width and height attributes # and a method to calculate its area. # Driver code rectangle = Rectangle.new(width: 10, height: 30) p rectangle.width # should be 10 p rectangle.height # should be 30 p rectangle.area # should be 300<file_sep>/tangerine.rb # Create a Tangerine class with a readable age and rotten attribute. # The rotten attribute is true if the age is greater than 5, false otherwise. # The class should also have an increase_age method that increases the age attribute by 1. # Driver code tangerine = Tangerine.new p tangerine.age # should be 0 p tangerine.rotten # should be false
67c786a4f77c9b4baf7e25e7b4af76de75b63864
[ "Ruby" ]
5
Ruby
acltc/ruby_practice_oop
20ffee5f738394e81eb0de01612bbdb930ce7c1a
6cd1463d9c2f1c1ab849f2f0995a882a7dbbba95
refs/heads/master
<repo_name>Lokot/grid-renderers-collection-addon<file_sep>/grid-renderers-collection-addon/src/main/java/org/vaadin/grid/cellrenderers/editable/DateFieldRenderer.java package org.vaadin.grid.cellrenderers.editable; import java.util.Date; import org.vaadin.grid.cellrenderers.EditableRenderer; import org.vaadin.grid.cellrenderers.client.editable.DateFieldRendererServerRpc; import org.vaadin.grid.cellrenderers.client.editable.DateFieldRendererState; import com.vaadin.data.Item; import com.vaadin.data.Property; import com.vaadin.ui.renderers.ClickableRenderer; /** * * @author <NAME> * */ public class DateFieldRenderer extends EditableRenderer<Date> { public DateFieldRenderer() { super(Date.class); registerRpc(new DateFieldRendererServerRpc() { public void onChange(String rowKey, String columnId, Date newValue) { Object itemId = getItemId(rowKey); Object columnPropertyId = getColumn(columnId).getPropertyId(); Item row = getParentGrid().getContainerDataSource().getItem(itemId); @SuppressWarnings("unchecked") Property<Date> cell = (Property<Date>) row.getItemProperty(columnPropertyId); cell.setValue(newValue); fireItemEditEvent(itemId, row, columnPropertyId, newValue); } }); } @Override protected DateFieldRendererState getState() { return (DateFieldRendererState) super.getState(); } }
2d0ab9167c6617e26c88302fdd37845dc32b495f
[ "Java" ]
1
Java
Lokot/grid-renderers-collection-addon
d271a00009753b01ef0b1cd223eeeb74314af8d6
0157920b940495236b270e0332e164e7956e3616
refs/heads/master
<repo_name>EternallyLiu/PartyBuilder<file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/model/ContentModel.java package com.github.rayboot.project.BuilderParty.model; import com.github.rayboot.project.BuilderParty.model.modelobj.ImageModel; import java.util.ArrayList; /** * Created by liupei on 2017/5/3. */ public class ContentModel { private String content_source; private ArrayList<ContentModel> contents; private long content_id; private long content_topic_id; private int content_type; private int content_category; private String content_icon; private String content_title; private String content_subtitle; private String content_author; private long content_time; private String content_url; private String content_html; private ArrayList<ImageModel> content_images; private int content_collection; private int open; private String parent_id; private int content_appendix; private int content_list_type; private int read_status; private int report_status; private int read_time; public int getRead_status() { return read_status; } public void setRead_status(int read_status) { this.read_status = read_status; } public int getReport_status() { return report_status; } public void setReport_status(int report_status) { this.report_status = report_status; } public int getRead_time() { return read_time; } public void setRead_time(int read_time) { this.read_time = read_time; } public String getContent_source() { return content_source; } public void setContent_source(String content_source) { this.content_source = content_source; } public ArrayList<ContentModel> getContents() { return contents; } public void setContents(ArrayList<ContentModel> contents) { this.contents = contents; } public long getContent_id() { return content_id; } public void setContent_id(long content_id) { this.content_id = content_id; } public long getContent_topic_id() { return content_topic_id; } public void setContent_topic_id(long content_topic_id) { this.content_topic_id = content_topic_id; } public int getContent_type() { return content_type; } public void setContent_type(int content_type) { this.content_type = content_type; } public int getContent_category() { return content_category; } public void setContent_category(int content_category) { this.content_category = content_category; } public String getContent_icon() { return content_icon; } public void setContent_icon(String content_icon) { this.content_icon = content_icon; } public String getContent_title() { return content_title; } public void setContent_title(String content_title) { this.content_title = content_title; } public String getContent_subtitle() { return content_subtitle; } public void setContent_subtitle(String content_subtitle) { this.content_subtitle = content_subtitle; } public String getContent_author() { return content_author; } public void setContent_author(String content_author) { this.content_author = content_author; } public long getContent_time() { return content_time; } public void setContent_time(long content_time) { this.content_time = content_time; } public String getContent_url() { return content_url; } public void setContent_url(String content_url) { this.content_url = content_url; } public String getContent_html() { return content_html; } public void setContent_html(String content_html) { this.content_html = content_html; } public ArrayList<ImageModel> getContent_images() { return content_images; } public void setContent_images(ArrayList<ImageModel> content_images) { this.content_images = content_images; } public int getContent_collection() { return content_collection; } public void setContent_collection(int content_collection) { this.content_collection = content_collection; } public int getOpen() { return open; } public void setOpen(int open) { this.open = open; } public String getParent_id() { return parent_id; } public void setParent_id(String parent_id) { this.parent_id = parent_id; } public int getContent_appendix() { return content_appendix; } public void setContent_appendix(int content_appendix) { this.content_appendix = content_appendix; } public int getContent_list_type() { return content_list_type; } public void setContent_list_type(int content_list_type) { this.content_list_type = content_list_type; } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/fragment/BaseFragment.java package com.github.rayboot.project.BuilderParty.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import com.github.rayboot.project.BuilderParty.service.Api; import com.github.rayboot.project.BuilderParty.service.ApiService; /** * Created by liupei on 2017/5/4. */ public class BaseFragment extends Fragment { public ApiService apiService; @Override public void onCreate(@Nullable Bundle savedInstanceState) { apiService = new Api().getApiService(); super.onCreate(savedInstanceState); } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/service/response/BaseResponse.java package com.github.rayboot.project.BuilderParty.service.response; /** * Created by liupei on 2017/5/3. */ public class BaseResponse<T>{ private T data; private int status_code; private String info; public T getData() { return data; } public void setData(T data) { this.data = data; } public int getStatus_code() { return status_code; } public void setStatus_code(int status_code) { this.status_code = status_code; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/fragment/BuilderPartyFragment.java package com.github.rayboot.project.BuilderParty.fragment; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.rayboot.project.BuilderParty.TabMainActivity; import com.github.rayboot.project.BuilderParty.adapter.BaseAdapter; import com.github.rayboot.project.BuilderParty.adapter.cell.BaseCell; import com.github.rayboot.project.BuilderParty.adapter.cell.HomeHorCell; import com.github.rayboot.project.BuilderParty.adapter.cell.HomeVerCell; import com.github.rayboot.project.BuilderParty.application.App; import com.github.rayboot.project.BuilderParty.model.ContentModel; import com.github.rayboot.project.BuilderParty.utils.SchedulersCompat; import com.github.rayboot.project.R; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; public class BuilderPartyFragment extends BaseFragment { @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.builder_recycler) RecyclerView builderRecycler; private List<BaseCell> cells = new ArrayList<>(); private BaseAdapter adapter; public BuilderPartyFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_builder_party, container, false); ButterKnife.bind(this, view); ((TabMainActivity)getActivity()).setSupportActionBar(toolbar); ((TabMainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false); ((TabMainActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(false); ((TabMainActivity)getActivity()).getSupportActionBar().setTitle(""); initRecyclerView(); return view; } private void initRecyclerView() { //注意异步框架的执行顺序 apiService.getHomeContent(App.token, App.userid, "Android", "1.0.0") .compose(SchedulersCompat.applyIoScheduler()) .subscribe(newHomeObjBaseResponse -> { ArrayList<ContentModel> homeModelList = newHomeObjBaseResponse.getData().getContent_list(); initCells(homeModelList); adapter = new BaseAdapter((ArrayList) cells); builderRecycler.setLayoutManager(new LinearLayoutManager(getActivity())); builderRecycler.setAdapter(adapter); }, throwable -> { Log.d(this.getClass().getSimpleName(), throwable.getLocalizedMessage()); }); } private void initCells(ArrayList<ContentModel> homeModelList) { for (int i = 0; i < homeModelList.size(); i++) { switch (homeModelList.get(i).getContent_list_type()) { case 0: HomeVerCell vercell = new HomeVerCell(getActivity(), homeModelList.get(i)); cells.add(vercell); break; case 1: HomeHorCell horcell = new HomeHorCell(getActivity(), homeModelList.get(i)); cells.add(horcell); break; } } } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/global/Global.java package com.github.rayboot.project.BuilderParty.global; import android.hardware.usb.UsbRequest; /** * Created by liupei on 2017/5/4. */ public class Global{ }<file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/fragment/MineFragment.java package com.github.rayboot.project.BuilderParty.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.rayboot.project.R; public class MineFragment extends BaseFragment { public MineFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_mine, container, false); } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/model/modelobj/BooksStudyInfoObj.java package com.github.rayboot.project.BuilderParty.model.modelobj; import com.github.rayboot.project.BuilderParty.model.BookStudyInfoModel; import java.util.ArrayList; /** * Created by liupei on 2017/5/8. */ public class BooksStudyInfoObj { private int current_page; private int total_page; private int total_count; private ArrayList<BookStudyInfoModel> data_list; public int getCurrent_page() { return current_page; } public void setCurrent_page(int current_page) { this.current_page = current_page; } public int getTotal_page() { return total_page; } public void setTotal_page(int total_page) { this.total_page = total_page; } public ArrayList<BookStudyInfoModel> getBook_list() { return data_list; } public void setBook_list(ArrayList<BookStudyInfoModel> book_list) { this.data_list = book_list; } public int getTotal_count() { return total_count; } public void setTotal_count(int total_count) { this.total_count = total_count; } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/adapter/cell/BaseCell.java package com.github.rayboot.project.BuilderParty.adapter.cell; import android.content.Context; import android.view.LayoutInflater; import android.view.ViewGroup; import com.github.rayboot.project.BuilderParty.adapter.holder.BaseHolder; /** * Created by liupei on 2017/5/4. */ public abstract class BaseCell { public Context mContext; public LayoutInflater inflater; //子类cell实现该方法来加载自己的布局 public abstract BaseHolder OncreateViewHolder(ViewGroup viewGroup,int itemType); //向子类cell的view上绑定数据 public abstract void OnBindData(BaseHolder baseHolder,int position); //获取子类cell的类型 public abstract int getItemType(); //选择实现该方法,用于释放资源 public void releaseResouce() {} } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/fragment/MakeBookFragment.java package com.github.rayboot.project.BuilderParty.fragment; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.cjj.MaterialRefreshLayout; import com.cjj.MaterialRefreshListener; import com.github.rayboot.project.BuilderParty.adapter.BaseAdapter; import com.github.rayboot.project.BuilderParty.adapter.cell.BaseCell; import com.github.rayboot.project.BuilderParty.adapter.cell.CommendCell; import com.github.rayboot.project.BuilderParty.adapter.cell.StudyInfoCell; import com.github.rayboot.project.BuilderParty.application.App; import com.github.rayboot.project.BuilderParty.model.BookCommendModel; import com.github.rayboot.project.BuilderParty.model.BookStudyInfoModel; import com.github.rayboot.project.BuilderParty.utils.SchedulersCompat; import com.github.rayboot.project.R; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; public class MakeBookFragment extends BaseFragment implements View.OnClickListener { @Bind(R.id.makebook_tv_left) TextView makebookTvLeft; @Bind(R.id.makebook_tv_center) TextView makebookTvCenter; @Bind(R.id.makebook_tv_right) TextView makebookTvRight; @Bind(R.id.makebook_search) TextView makebookSearch; @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.makebook_recycler) RecyclerView makebookRecycler; @Bind(R.id.make_commend_tv_empty) TextView makebookTvEmpty; @Bind(R.id.makebook_refresh) MaterialRefreshLayout makebookRefreshLayout; private boolean isStudyInfo = false;//设置一个变量来判断是否处在学习资料界面,避免重复加载 private TextView CurrentTv;//设置该变量记录刚才点击的是哪个tab private int CurrentType = 1;//加载更多的时候判断是哪个页面加载更多 private int CurrentPage = 1; private int scrollPosition = 0;//记录recyvlerView需要滚动到的指定位置 private final static int TYPE_STYDYINFO = 1; private final static int TYPE_COMMENDPRODUCTION = 2; private final static int TYPE_MINEPRODUCTION = 3; private ArrayList<BookStudyInfoModel> mStudyInfoList; private ArrayList<BookCommendModel> mCommendList; private List<BaseCell> mCells = new ArrayList<>(); private BaseAdapter<BaseCell> adapter; public MakeBookFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_make_book, container, false); ButterKnife.bind(this, view); makebookTvLeft.setSelected(true); makebookTvLeft.setOnClickListener(this); makebookTvCenter.setOnClickListener(this); makebookTvRight.setOnClickListener(this); getDataFromService(TYPE_STYDYINFO, 1, 2, false, false); makebookRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() { @Override public void onRefresh(MaterialRefreshLayout materialRefreshLayout) { getDataFromService(CurrentType, 1, 2, false, true); materialRefreshLayout.finishRefresh(); } @Override public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) { super.onRefreshLoadMore(materialRefreshLayout); getDataFromService(CurrentType, ++CurrentPage, 2, true, false); materialRefreshLayout.finishRefreshLoadMore(); } }); return view; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.makebook_tv_left: if (!isStudyInfo) { if (mCells != null) { mCells.clear(); } CurrentPage = 1; makebookTvLeft.setSelected(true); if (CurrentTv != null && CurrentTv != makebookTvLeft) { CurrentTv.setSelected(false); getDataFromService(TYPE_STYDYINFO, CurrentPage, 2, false, false); CurrentTv = makebookTvLeft; } } CurrentType = 1; break; case R.id.makebook_tv_center: if (mCells != null) { mCells.clear(); } CurrentPage = 1; makebookTvCenter.setSelected(true); if (CurrentTv != null && CurrentTv != makebookTvCenter) { CurrentTv.setSelected(false); CurrentTv = makebookTvCenter; getDataFromService(TYPE_COMMENDPRODUCTION, CurrentPage, 2, false, false); } CurrentType = 2; break; case R.id.makebook_tv_right: if (mCells != null) { mCells.clear(); } CurrentPage = 1; makebookTvRight.setSelected(true); if (CurrentTv != null && CurrentTv != makebookTvRight) { CurrentTv.setSelected(false); CurrentTv = makebookTvRight; getDataFromService(TYPE_MINEPRODUCTION, CurrentPage, 2, false, false); } CurrentType = 3; break; } } private void getDataFromService(int type, int currentPage, int PageSize, boolean isLoadmore, boolean isPullRefresh) { switch (type) { case TYPE_STYDYINFO: apiService.getStudyInfoBooks(App.token, App.userid, "Android", "1.0.0", currentPage, PageSize) .compose(SchedulersCompat.applyIoScheduler()) .subscribe(booksResponse -> { mStudyInfoList = booksResponse.getData().getBook_list(); initDataAdapter(TYPE_STYDYINFO, currentPage, isLoadmore, isPullRefresh); }, throwable -> { //打印错误日志 Log.e(getClass().getSimpleName(), throwable.getLocalizedMessage()); }); break; case TYPE_COMMENDPRODUCTION: apiService.getCommendBooks(App.token, App.userid, "Android", "1.0.0", CurrentPage, PageSize) .compose(SchedulersCompat.applyIoScheduler()) .subscribe(booksResponse -> { mCommendList = booksResponse.getData().getData_list(); initDataAdapter(TYPE_COMMENDPRODUCTION, currentPage, isLoadmore, isPullRefresh); }, throwable -> { //打印错误日志 Log.e(getClass().getSimpleName(), throwable.getLocalizedMessage()); }); break; case TYPE_MINEPRODUCTION: initDataAdapter(TYPE_MINEPRODUCTION, currentPage, isLoadmore, isPullRefresh); break; } } private void initDataAdapter(int type, int currentPage, boolean isLoadMore, boolean isPullRefresh) { if (isPullRefresh) { mCells.clear();//如果是下拉刷新则先清空一遍数据 } if (adapter != null) { scrollPosition = adapter.cells.size() - 1; } switch (type) { case TYPE_STYDYINFO: for (int i = 0; i < mStudyInfoList.size(); i++) { StudyInfoCell cell = new StudyInfoCell(getActivity(), mStudyInfoList.get(i)); mCells.add(cell); } CurrentTv = makebookTvLeft; break; case TYPE_COMMENDPRODUCTION: for (int i = 0; i < mCommendList.size(); i++) { CommendCell cell = new CommendCell(getActivity(), mCommendList.get(i)); mCells.add(cell); } CurrentTv = makebookTvCenter; break; case TYPE_MINEPRODUCTION: CurrentTv = makebookTvRight; break; } CurrentPage = currentPage; if (!(isLoadMore == true && adapter.cells.size() != 0)) { if (mCells.size() == 0 || mCells == null) { makebookTvEmpty.setVisibility(View.VISIBLE); if (adapter != null) { adapter.clear(); } return; } } adapter = new BaseAdapter<>((ArrayList<BaseCell>) mCells); makebookRecycler.setLayoutManager(new LinearLayoutManager(getActivity())); makebookRecycler.setAdapter(adapter); makebookRecycler.scrollToPosition(scrollPosition);//滚动到本次加载的第一个item makebookTvEmpty.setVisibility(View.GONE); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/adapter/cell/CommendCell.java package com.github.rayboot.project.BuilderParty.adapter.cell; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.Toast; import com.github.rayboot.project.BuilderParty.adapter.holder.BaseHolder; import com.github.rayboot.project.BuilderParty.model.BookCommendModel; import com.github.rayboot.project.R; import java.text.SimpleDateFormat; /** * Created by liupei on 2017/5/9. */ public class CommendCell extends BaseCell implements View.OnClickListener{ private BookCommendModel commendModel; private PopupWindow mPop; public CommendCell(Context context, BookCommendModel model) { this.mContext = context; this.commendModel = model; inflater = LayoutInflater.from(mContext); } @Override public BaseHolder OncreateViewHolder(ViewGroup viewGroup, int itemType) { View itemView = inflater.inflate(R.layout.makebook_commendproduction, viewGroup, false); return new BaseHolder(itemView); } @Override public void OnBindData(BaseHolder baseHolder, int position) { baseHolder.getTextView(R.id.make_commend_tv_bookname).setText(commendModel.getBook_title()); baseHolder.getTextView(R.id.make_commend_tv_bookeauthor).setText(commendModel.getBook_author()); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); baseHolder.getTextView(R.id.make_commend_tv_booktime).setText("时间:" + formatter.format(commendModel.getBook_create_time())); baseHolder.getTextView(R.id.make_commend_tv_share).setOnClickListener(this); baseHolder.getDraweeView(R.id.make_commend_dv).setImageURI(Uri.parse(commendModel.getBook_cover())); View popupView = inflater.inflate(R.layout.popup_commend, null, false); // 创建PopupWindow对象 mPop = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); //设置点击窗口外popupWindow消失 mPop.setBackgroundDrawable(new BitmapDrawable()); mPop.setOutsideTouchable(true); //设置焦点可以被点击 mPop.setFocusable(true); LinearLayout popup_ll = (LinearLayout) popupView.findViewById(R.id.popup_ll); popup_ll.setOnClickListener(this); } @Override public int getItemType() { return 1; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.make_commend_tv_share: if (!mPop.isShowing()) { mPop.showAsDropDown(v,200,20); } break; case R.id.popup_ll: Toast.makeText(mContext, "分享中...", Toast.LENGTH_SHORT).show(); if (mPop.isShowing()) { mPop.dismiss(); } break; } } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/model/BookCommendModel.java package com.github.rayboot.project.BuilderParty.model; /** * Created by liupei on 2017/5/9. */ public class BookCommendModel{ private int book_status; private String book_summary; private String book_title; private String book_author; private String extra; private long book_id; private long book_create_time; private String book_cover; private int book_total_page; private int book_type; public int getBook_status() { return book_status; } public void setBook_status(int book_status) { this.book_status = book_status; } public String getBook_summary() { return book_summary; } public void setBook_summary(String book_summary) { this.book_summary = book_summary; } public String getBook_title() { return book_title; } public void setBook_title(String book_title) { this.book_title = book_title; } public String getBook_author() { return book_author; } public void setBook_author(String book_author) { this.book_author = book_author; } public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } public long getBook_id() { return book_id; } public void setBook_id(long book_id) { this.book_id = book_id; } public long getBook_create_time() { return book_create_time; } public void setBook_create_time(long book_create_time) { this.book_create_time = book_create_time; } public String getBook_cover() { return book_cover; } public void setBook_cover(String book_cover) { this.book_cover = book_cover; } public int getBook_total_page() { return book_total_page; } public void setBook_total_page(int book_total_page) { this.book_total_page = book_total_page; } public int getBook_type() { return book_type; } public void setBook_type(int book_type) { this.book_type = book_type; } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/TabMainActivity.java package com.github.rayboot.project.BuilderParty; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.TextView; import com.facebook.drawee.backends.pipeline.Fresco; import com.github.rayboot.project.BuilderParty.adapter.HomePagerAdapter; import com.github.rayboot.project.BuilderParty.base.BaseAppCompatActivity; import com.github.rayboot.project.BuilderParty.fragment.BuilderPartyFragment; import com.github.rayboot.project.BuilderParty.fragment.MakeBookFragment; import com.github.rayboot.project.BuilderParty.fragment.MineFragment; import com.github.rayboot.project.BuilderParty.view.MyViewPager; import com.github.rayboot.project.R; import java.util.ArrayList; import butterknife.Bind; import butterknife.ButterKnife; public class TabMainActivity extends BaseAppCompatActivity implements View.OnClickListener { @Bind(R.id.home_viewpager) MyViewPager homeViewpager; @Bind(R.id.tablayout) TabLayout tablayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Fresco.initialize(this); setContentView(R.layout.activity_tab_main); ButterKnife.bind(this); initTabLayout(); } private void initTabLayout() { ArrayList<Fragment> mFragments = new ArrayList<>(); mFragments.add(new BuilderPartyFragment()); mFragments.add(new MakeBookFragment()); mFragments.add(new MineFragment()); String[] mTitles = new String[]{"党建平台", "一键成书", "我的"}; int[] mImages = new int[]{R.drawable.selector_partybuilder, R.drawable.selector_makebook, R.drawable.selector_mine}; tablayout.addTab(tablayout.newTab()); tablayout.addTab(tablayout.newTab()); tablayout.addTab(tablayout.newTab()); HomePagerAdapter homePagerAdapter = new HomePagerAdapter(this, getSupportFragmentManager(), mFragments, mTitles, mImages); homeViewpager.setAdapter(homePagerAdapter); tablayout.setTabGravity(TabLayout.GRAVITY_FILL); tablayout.setTabMode(TabLayout.MODE_FIXED); tablayout.setupWithViewPager(homeViewpager); for (int i = 0; i < tablayout.getTabCount(); i++) { TabLayout.Tab tab = tablayout.getTabAt(i); tab.setCustomView(homePagerAdapter.getTabView(i)); TextView tab_tv = (TextView) tab.getCustomView().findViewById(R.id.tab_tv); tab_tv.setTag(R.string.tag_index, i); tab_tv.setOnClickListener(this); } homeViewpager.setOffscreenPageLimit(3); homeViewpager.setCurrentItem(0); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tab_tv: homeViewpager.setCurrentItem((int) v.getTag(R.string.tag_index)); break; } } @Override protected void onRestart() { super.onRestart(); homeViewpager.setCurrentItem(0); } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/base/BaseAppCompatActivity.java package com.github.rayboot.project.BuilderParty.base; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import com.github.rayboot.project.BuilderParty.application.App; import com.github.rayboot.project.BuilderParty.global.Global; import com.github.rayboot.project.BuilderParty.service.Api; import com.github.rayboot.project.BuilderParty.service.ApiFactory; import com.github.rayboot.project.BuilderParty.service.ApiService; import com.github.rayboot.project.BuilderParty.service.body.LoginRequset; import com.github.rayboot.project.BuilderParty.utils.SchedulersCompat; import com.umeng.analytics.MobclickAgent; import rx.Subscription; import rx.subscriptions.CompositeSubscription; /** * @author rayboot * @from 14/11/3 14:04 * @TODO */ public class BaseAppCompatActivity extends AppCompatActivity { public LayoutInflater mInflater; private CompositeSubscription mCompositeSubscription; private ApiService apiService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); apiService = new Api().getApiService(); mInflater = LayoutInflater.from(this); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } @Override protected void onDestroy() { if (this.mCompositeSubscription != null) { this.mCompositeSubscription.unsubscribe(); } super.onDestroy(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } public CompositeSubscription getCompositeSubscription() { if (this.mCompositeSubscription == null) { this.mCompositeSubscription = new CompositeSubscription(); } return this.mCompositeSubscription; } public void addSubscription(Subscription s) { getCompositeSubscription().add(s); } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/model/BookStudyInfoModel.java package com.github.rayboot.project.BuilderParty.model; /** * Created by liupei on 2017/5/8. */ public class BookStudyInfoModel { private long content_time; private String content_title; private String content_id; private String content_icon; private int content_type; public long getContent_time() { return content_time; } public void setContent_time(long content_time) { this.content_time = content_time; } public String getContent_title() { return content_title; } public void setContent_title(String content_title) { this.content_title = content_title; } public String getContent_id() { return content_id; } public void setContent_id(String content_id) { this.content_id = content_id; } public String getContent_icon() { return content_icon; } public void setContent_icon(String content_icon) { this.content_icon = content_icon; } public int getContent_type() { return content_type; } public void setContent_type(int content_type) { this.content_type = content_type; } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/adapter/cell/HomeVerCell.java package com.github.rayboot.project.BuilderParty.adapter.cell; import android.content.Context; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.github.rayboot.project.BuilderParty.adapter.holder.BaseHolder; import com.github.rayboot.project.BuilderParty.model.ContentModel; import com.github.rayboot.project.R; import java.util.ArrayList; /** * Created by liupei on 2017/5/5. */ public class HomeVerCell extends BaseCell{ public ContentModel contentModel; public ArrayList<ContentModel> mData; private TextView home_ver_tv1; private TextView home_ver_tv2; private TextView home_ver_tv3; private TextView home_ver_top_title; private ArrayList<TextView> mTvList; private ArrayList<View> mLines; private View line1; private View line2; public HomeVerCell(Context context,ContentModel contentModel) { this.contentModel = contentModel; this.mContext = context; mData = contentModel.getContents(); inflater = LayoutInflater.from(mContext); mTvList = new ArrayList<>(); mLines = new ArrayList<>(); } @Override public BaseHolder OncreateViewHolder(ViewGroup viewGroup, int itemType) { View itemView = inflater.inflate(R.layout.home_recycler_ver, viewGroup, false); return new BaseHolder(itemView); } @Override public void OnBindData(BaseHolder baseHolder, int position) { home_ver_tv1 = baseHolder.getTextView(R.id.home_ver_tv1); home_ver_tv2 = baseHolder.getTextView(R.id.home_ver_tv2); home_ver_tv3 = baseHolder.getTextView(R.id.home_ver_tv3); line1 = baseHolder.getView(R.id.home_ver_line1); line2 = baseHolder.getView(R.id.home_ver_line2); home_ver_top_title = baseHolder.getTextView(R.id.builderparty_tv); mLines.add(line1); mLines.add(line2); mTvList.add(home_ver_tv1); mTvList.add(home_ver_tv2); mTvList.add(home_ver_tv3); for (int i = 0; i < mData.size(); i++) { if (i == 3) { break; } String title = mData.get(i).getContent_title(); mTvList.get(i).setText(title); } //隐藏掉无用的组件 if (mData.size() < 3) { for (int j = 3; j > mData.size(); j--) { mTvList.get(j - 1).setVisibility(View.GONE); if (j != 3) { mLines.get(j - 1).setVisibility(View.GONE); if (j == 2) { mLines.get(0).setVisibility(View.GONE); } } } } home_ver_top_title.setText(contentModel.getContent_title()); } @Override public int getItemType() { return contentModel.getContent_list_type(); } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/service/body/LoginRequset.java package com.github.rayboot.project.BuilderParty.service.body; import android.util.Base64; /** * Created by liupei on 2017/5/3. */ public class LoginRequset { private String phone; private String password; private String verify_code; public LoginRequset(String phone, String password) { this.phone = phone; this.password = Base64.encodeToString(password.getBytes(), Base64.DEFAULT);; } public LoginRequset(String phone, String password, String verify_code) { this.phone = phone; this.password = Base64.encodeToString(password.getBytes(), Base64.DEFAULT);; this.verify_code = verify_code; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getVerify_code() { return verify_code; } public void setVerify_code(String verify_code) { this.verify_code = verify_code; } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/adapter/BaseAdapter.java package com.github.rayboot.project.BuilderParty.adapter; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import com.github.rayboot.project.BuilderParty.adapter.cell.BaseCell; import com.github.rayboot.project.BuilderParty.adapter.holder.BaseHolder; import java.util.ArrayList; import java.util.List; /** * Created by liupei on 2017/5/4. */ public class BaseAdapter<T extends BaseCell> extends RecyclerView.Adapter<BaseHolder> { public ArrayList<T> cells; public BaseAdapter(ArrayList<T> cells) { this.cells = cells; } @Override public BaseHolder onCreateViewHolder(ViewGroup parent, int viewType) { for (int i = 0; i < cells.size(); i++) { if (viewType == cells.get(i).getItemType()) { return cells.get(i).OncreateViewHolder(parent,viewType); } } throw new RuntimeException("错误的布局类型!"); } @Override public void onBindViewHolder(BaseHolder holder, int position) { cells.get(position).OnBindData(holder, position); } @Override public int getItemCount() { return cells.size(); } @Override public int getItemViewType(int position) { return cells.get(position).getItemType(); } public void add(T cell) { add(cells.size(),cell); } public void add(int index, T cell) { cells.add(index, cell); notifyItemChanged(index); } public void addAll(List<T> list) { cells.addAll(list); notifyItemRangeChanged(cells.size() - list.size(),list.size()); } public void remove(T cell) { remove(cells.indexOf(cell)); } public void remove(int index) { cells.remove(index); notifyItemRemoved(index); } public void remove(int start, int count) { if (start + count >= cells.size() || start < 0) { return; } for (int i = 0; i < count; i++) { cells.remove(start + i); } notifyItemRangeChanged(start, count); } public void clear() { cells.clear(); notifyDataSetChanged(); } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/model/modelobj/LoginDataObj.java package com.github.rayboot.project.BuilderParty.model.modelobj; import com.github.rayboot.project.BuilderParty.model.UserModel; /** * Created by liupei on 2017/5/3. */ public class LoginDataObj{ private UserModel user_model; public UserModel getUser_model() { return user_model; } public void setUser_model(UserModel user_model) { this.user_model = user_model; } } <file_sep>/app/src/main/java/com/github/rayboot/project/BuilderParty/adapter/holder/BaseHolder.java package com.github.rayboot.project.BuilderParty.adapter.holder; import android.sax.RootElement; import android.support.v7.widget.RecyclerView; import android.util.SparseArray; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.facebook.drawee.view.DraweeView; import com.facebook.drawee.view.SimpleDraweeView; /** * Created by liupei on 2017/5/4. */ public class BaseHolder extends RecyclerView.ViewHolder { private SparseArray<View> views; private View itemView; public BaseHolder(View itemView) { super(itemView); this.itemView = itemView; views = new SparseArray<>(); } public <V extends View> V getView(int resId) { View view = views.get(resId); if (view == null) { view = itemView.findViewById(resId); } return (V) view; } public TextView getTextView(int resId) { return getView(resId); } public ImageView getImageView(int resId) { return getView(resId); } public Button getButton(int resId) { return getView(resId); } public SimpleDraweeView getDraweeView(int resId) { return getView(resId); } public LinearLayout getLinearLayout(int resId) { return getView(resId); } }
4cf910db9d84b091e03bb004118967c30dd1cb11
[ "Java" ]
19
Java
EternallyLiu/PartyBuilder
6061b64a51ccc09d6dd2275a8f07235cece03690
a38213a41c2413ce3b6adfabe922b8565aa7b01a
refs/heads/master
<file_sep># MOIRA ##### Most Outstanding IP Reporting Assistant ### Installation You may install MOIRA via NPM as follows: npm install moira The source code is available on [GitHub](https://github.com/mjhasbach/MOIRA). ### Command #### moira.getIP( callback( ```err```, ```ip```, ```service``` )) Retrieve your external IP address asynchronously by requesting it from several different IP-fetching services simultaneously. ```moira.getIP()``` reports the quickest result after verifying that it is a valid IP address and terminating all other requests. ```err``` is null if an IP address was found. ```ip``` is an IPv4 address. ```service``` is the URL of the IP-reporting service that returned ```ip``` (e.g. http://whatismyip.akamai.com/). Example: var moira = require( 'moira' ); moira.getIP( function( err, ip, service ){ if( err ) throw err; console.log( 'Your external IP address is ' + ip ); console.log( 'The fastest service to return your IP address was ' + service ); }); ### Test npm test ### Improving MOIRA If you would like to contribute code or simply add an IP reporting service, feel free to submit a pull request. Please report issues [here](https://github.com/mjhasbach/MOIRA/issues).<file_sep>var moira = require( '../lib/moira' ); moira.getIP( function( err, ip, service ){ if ( err ) throw err; console.log( 'Your external IP address is ' + ip ); console.log( 'The fastest service to return your IP address was ' + service ); });<file_sep>'use strict'; var request = require( 'request' ); // HTTP requests to a service should return an IP address ONLY in the response body var services = [ 'http://ifconfig.me/ip', 'http://icanhazip.com/', 'http://ip.appspot.com/', 'http://curlmyip.com/', 'http://ident.me/', 'http://whatismyip.akamai.com/', 'http://tnx.nl/ip', 'http://myip.dnsomatic.com/', 'http://ipecho.net/plain' ]; function getIP( callback ){ var GetIP = this; GetIP.done = false; GetIP.requests = []; GetIP.isOnItsLastResponse = function() { return GetIP.completedRequests === services.length }; GetIP.completedRequests = 0; services.forEach( function( service ){ GetIP.requests.push( request( service, function( err, response, address ){ GetIP.completedRequests++; if ( address ) address = address.trim(); if ( GetIP.done === false && thisIsAnIP( address )){ GetIP.done = true; GetIP.requests.forEach( function( req ){ req.abort() }); callback( null, address, response.request.uri.href ) } if ( GetIP.done === false && GetIP.isOnItsLastResponse() ){ callback( new Error( 'All attempts to retrieve your IP address were exhausted' ), null, null ) } }) ) }) } function thisIsAnIP( address ){ var octet = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.', isIP = new RegExp( '^' + octet + octet + octet + octet.slice( 0, -1 ) + '$' ); if( address ) { return isIP.test( address )} else { return( null )} } exports.getIP = getIP;
b1e36a5028226ed2032636a4a36803f2a2712bb1
[ "Markdown", "JavaScript" ]
3
Markdown
mjhasbach/MOIRA
bafd0a32433d72a3a96eaccbbdb56638d33bc8a7
181aae97d1335ed639bf8e62a288961e6d2bd7a1
refs/heads/master
<file_sep>#include <stdio.h> int main(void) { char c; int i = 0; int n = 0; int b = 0; while (scanf("%c", &c) == 1) { if (c == '(') { i++; n++; } else if (c == ')') { i++; n--; if (b == 0 && n == -1) b = i; } } printf("%d\n%d\n", n, b); return 0; } <file_sep>#include <stdio.h> #include <string.h> #include <ctype.h> #include <limits.h> int calc_array(void); int calc_object(void); int gsum = 0; int calc_int(char head, char *last) { int n = 0, x; char ss[32]; char c; ss[n++] = head; while (scanf("%c", &c) == 1) { if (!isdigit(c)) break; ss[n++] = c; } ss[n] = '\0'; *last = c; sscanf(ss, "%d", &x); gsum += x; return x; } int check_red(void) { int state = 0; char c; while (scanf("%c", &c) == 1) { if (c == '"') break; if (state == 0 && c == 'r') state = 1; else if (state == 1 && c == 'e') state = 2; else if (state == 2 && c == 'd') state = 3; else state = -1; } if (state == 3) return 1; return 0; } int calc_object(void) { int sum = 0; char c; int state = 0; int red = 0; while (scanf("%c", &c) == 1) { next: if (c == '}') break; if (state == 0 && c == '"') state = 1; else if (state == 1 && c == '"') state = 2; else if (state == 2 && c == ':') state = 3; else if (state == 3) { if (c == '{') sum += calc_object(); else if (c == '[') sum += calc_array(); else if (c == '-' || isdigit(c)) { sum += calc_int(c, &c); state = 0; goto next; } else if (c == '"') { int a = check_red(); if (!red) red = a; } state = 0; } } return (red ? 0 : sum); } int calc_array(void) { int sum = 0; char c; while (scanf("%c", &c) == 1) { next: if (c == ']') break; if (c == '{') sum += calc_object(); else if (c == '[') sum += calc_array(); else if (c == '-' || isdigit(c)) { sum += calc_int(c, &c); goto next; } else if (c == '"') check_red(); } return sum; } int main(void) { char c; int sum = 0; scanf("%c", &c); if (c == '{') sum = calc_object(); else if (c == '[') sum = calc_array(); printf("%d\n%d\n", gsum, sum); return 0; } <file_sep>TARGET=day01 day02 day03 day04 day05 day06 day07 day09 day10 day12 day13 day14 day15 day16 day17 GEN_TARGET=day07.c CFLAGS=-O2 -Wall -lcrypto ifeq ($(V),1) quiet= else quiet=q_ endif call_cmd=@echo "$($(quiet)$(1)_cmd)"; $($(1)_cmd) cc_cmd=$(CC) $(CFLAGS) $< -o $@ q_cc_cmd="CC $@" gen_cmd=python3 $< < $(word 2,$^) > $@ q_gen_cmd="GEN $@" all: $(TARGET) run: all @for i in $(TARGET); do echo $$i; if [ -f $$i.input ]; then ./$$i < $$i.input; else ./$$i; fi; echo; done $(GEN_TARGET): %.c: %.py %.input $(call call_cmd,gen) % : %.c $(call call_cmd,cc) clean: $(RM) $(TARGET) $(GEN_TARGET) <file_sep>#!/usr/bin/env python3 import sys def opd(o): if o.isnumeric(): return '((unsigned short)%s)' % o else: return '%s(t)' % o.upper() def do_header(ll, end=''): print('unsigned short %s(int t)%s' % (ll[-1].upper(), end)) def do_static(): print('static unsigned short ss[2] = {};') print('if (ss[t] != 0) return ss[t];') def do_return(expr): print('return ss[t]=%s;' % expr) def do_func(ret): do_header(ll) print('{') do_static() do_return(ret) print('}') def do_assign(ll): do_header(ll) print('{') do_static() if ll[len(ll)-1] == 'b': print('if (t) return ss[t]=A(0);\nelse ', end='') do_return(opd(ll[0])) print('}') def do_not(ll): do_func('~'+opd(ll[1])) def do_and_or(ll): op = '&' if ll[1] == 'AND' else '|' do_func(opd(ll[0])+op+opd(ll[2])) def do_shift(ll): op = '<<' if ll[1] == 'LSHIFT' else '>>' do_func(opd(ll[0])+op+opd(ll[2])) lines = [ line for line in sys.stdin ] for line in lines: ll = line.strip().split(' ') do_header(ll, ';') for line in lines: ll = line.strip().split(' ') if ll[1] == '->': do_assign(ll) elif ll[0] == 'NOT': do_not(ll) elif ll[1] == 'AND' or ll[1] == 'OR': do_and_or(ll) elif ll[1] == 'RSHIFT' or ll[1] == 'LSHIFT': do_shift(ll) print('#include<stdio.h>') print('int main(void){') print('printf("%hu\\n%hu\\n", A(0), A(1));') print('return 0;}') <file_sep>#include <stdio.h> #include <string.h> char names[10][16] = { "children:", "cats:", "samoyeds:", "pomeranians:", "akitas:", "vizslas:", "goldfish:", "trees:", "cars:", "perfumes:", }; int target[10] = { 3,7,2,3,0,0,5,3,2,1 }; int nameid(char *name) { int i; for (i = 0; strcmp(name, names[i]) != 0; i++); return i; } int greater(int id) { return id == 1 || id == 7; } int fewer(int id) { return id == 3 || id == 6; } int main(void) { char t[16]; int i; char n[3][16]; int v[3]; int id = 0, id1 = 0, id2 = 0; while(scanf("%s", t) == 1) { id++; for (i = 0; i < 9; i++) { if (i == 2 || i == 5 || i == 8) scanf("%d", &v[(i-2)/3]); else if (i == 1 || i == 4 || i == 7) scanf("%s", n[(i-1)/3]); else scanf("%s", t); } for (i = 0; i < 3; i++) { if (target[nameid(n[i])] != v[i]) break; if (i == 2) id1 = id; } for (i = 0; i < 3; i++) { int aid = nameid(n[i]); if (greater(aid) && v[i] <=target[aid]) break; if (fewer(aid) && v[i] >= target[aid]) break; if (!greater(aid) && !fewer(aid) && v[i] != target[aid]) break; if (i == 2) id2 = id; } } printf("%d\n%d\n", id1, id2); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> int calc_dist(int speed, int dur, int rest, int time) { int total_seg = time / (dur+rest); int residue = time % (dur+rest); int dist = 0; dist += speed * dur * total_seg; residue = residue > dur ? dur : residue; dist += speed * residue; return dist; } int main(void) { char t[64]; char name[16][16]; int speed[16], dur[16], rest[16]; int i, j, n = 0; int time = 2503; int maxd; int score[16] = {}; /* Rudolph can fly 22 km/s for 8 seconds, but then must rest for 165 seconds. */ while (scanf("%s", name[n]) == 1) { for (i = 0; i < 14; i++) { if (i == 2) scanf("%d", &speed[n]); else if (i == 5) scanf("%d", &dur[n]); else if (i == 12) scanf("%d", &rest[n]); else scanf("%s", t); } n++; } for (maxd = 0, i = 0; i < n; i++) { int d = calc_dist(speed[i], dur[i], rest[i], time); if (d > maxd) { maxd = d; } } printf("%d\n", maxd); for (j = 1; j <= time; j++) { for (maxd = 0, i = 0; i < n; i++) { int d = calc_dist(speed[i], dur[i], rest[i], j); if (d > maxd) { maxd = d; } } for (i = 0; i < n; i++) { if (calc_dist(speed[i], dur[i], rest[i], j) == maxd) score[i]++; } } for (maxd = 0, i = 0; i < n; i++) if (score[i] > maxd) maxd = score[i]; printf("%d\n", maxd); return 0; } <file_sep>#include <stdio.h> #include <limits.h> int bn; int box[21]; int method[151][21]; int method2[151][21]; int num[151][21]; int calc(int liter, int first) { int i, v = 0; if (method[liter][first] >= 0) return method[liter][first]; if (liter >= box[first]) { v = 0; for (i = first + 1; i < bn; i++) v += calc(liter - box[first], i); } method[liter][first] = v; return v; } int calc2(int liter, int first) { int i, v = 0; if (method2[liter][first] >= 0) return method2[liter][first]; if (liter >= box[first]) { v = 0; for (i = first + 1; i < bn; i++) { int t = calc2(liter - box[first], i); if (t == 0) continue; if (num[liter][first] > num[liter-box[first]][i]+1) { num[liter][first] = num[liter-box[first]][i]+1; v = t; } else if (num[liter][first] == num[liter-box[first]][i]+1) { v += t; } } } method[liter][first] = v; return v; } int main(void) { int i, j; box[bn++] = 0; while (scanf("%d", &box[bn]) == 1) bn++; for (i = 0; i < bn; i++) for (j = 0; j < 151; j++) { method[j][i] = -1; method2[j][i] = -1; num[j][i] = INT_MAX; } for (i = 0; i < bn; i++) { method[box[i]][i] = 1; method2[box[i]][i] = 1; num[box[i]][i] = 1; } printf("%d\n", calc(150, 0)); printf("%d\n", calc2(150, 0)); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> int main(void) { /* * Sugar: capacity 3, durability 0, flavor 0, texture -3, calories 2 * Sprinkles: capacity -3, durability 3, flavor 0, texture 0, calories 9 * Candy: capacity -1, durability 0, flavor 4, texture 0, calories 1 * Chocolate: capacity 0, durability 0, flavor -2, texture 2, calories 8 */ int i, j, k, l; int max = 0, max2 = 0; int attr[4][5] = { { 3, 0, 0, -3, 2 }, { -3, 3, 0, 0, 9 }, {-1, 0, 4, 0, 1 }, { 0, 0, -2, 2, 8 }, }; for (i = 0; i <= 100; i++) for (j = 0; j <= 100-i; j++) for (k = 0; k < 100-i-j; k++) { int sum[5]; int a; int prod; l = 100 - i - j - k; for (a = 0; a < 5; a++) { sum[a] = i*attr[0][a] + j*attr[1][a] + k*attr[2][a] + l*attr[3][a]; if (sum[a] <= 0) goto backout; } prod = sum[0]*sum[1]*sum[2]*sum[3]; max = prod > max ? prod : max; if (sum[4] == 500) max2 = prod > max2 ? prod : max2; backout: ; } printf("%d\n%d\n", max, max2); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> struct pos { union { struct { int x; int y; }; long xy; }; }; int pos_cmp(const void *a, const void *b) { const struct pos *pa = a; const struct pos *pb = b; return (pa->xy < pb->xy) - (pa->xy > pb->xy); } int main(void) { char c; struct pos *pos; struct pos *pos2; int i; int n = 1; int total, total2; pos = malloc(16384*sizeof(struct pos)); pos2 = malloc(16384*sizeof(struct pos)); pos[0] = (struct pos){ .xy = 0 }; pos2[0] = (struct pos){ .xy = 0 }; pos2[1] = (struct pos){ .xy = 0 }; pos2 = &pos2[1]; while (scanf("%c", &c) == 1) { int dx = 0, dy = 0; switch (c) { case '<': dx = -1; break; case '>': dx = 1; break; case '^': dy = 1; break; case 'v': dy = -1; break; } pos[n] = (struct pos){ .x = pos[n-1].x + dx, .y = pos[n-1].y + dy}; pos2[n] = (struct pos){ .x = pos2[n-2].x + dx, .y = pos2[n-2].y + dy}; n++; } qsort(pos, n, sizeof(struct pos), pos_cmp); qsort(pos2, n, sizeof(struct pos), pos_cmp); for (total = 1, total2 = 1, i = 1; i < n; i++) { if (pos[i].xy != pos[i-1].xy) total++; if (pos2[i].xy != pos2[i-1].xy) total2++; } printf("%d\n%d\n", total, total2); return 0; } <file_sep>#include <stdio.h> int light[1000][1000]; int light2[1000][1000]; int main(void) { char cmd[16]; int sx,sy,ex,ey; char t[16],u[16],v[16]; int sum = 0, sum2 = 0; int i, j; while (scanf("%s", cmd) == 1) { if (cmd[1] == 'u') scanf("%s", cmd); scanf("%d%c%d%s%d%c%d", &sx, t, &sy, u, &ex, v, &ey); for (i = sx; i <= ex; i++) { for (j = sy; j <= ey; j++) { if (cmd[0] == 't') { light[i][j] = !light[i][j]; light2[i][j] += 2; } else if (cmd[1] == 'n') { light[i][j] = 1; light2[i][j]++; } else { light[i][j] = 0; light2[i][j] = light2[i][j] > 0 ? light2[i][j]-1 : 0; } } } } for (i = 0; i < 1000; i++) { for (j = 0; j < 1000; j++) { sum += light[i][j]; sum2 += light2[i][j]; } } printf("%d\n%d\n", sum, sum2); return 0; } <file_sep>#include <stdio.h> #include <string.h> #include <limits.h> #define swap(a, b) do { int __t = a; a = b; b = __t; } while (0) int score[9][9]; char names[8][16] = { "AlphaCentauri", "Snowdin", "Tambi", "Faerun", "Norrath", "Straylight", "Tristram", "Arbre", }; int nameid(char *name) { int i; for (i = 0; strcmp(name, names[i]) != 0; i++); return i; } void calc(int p[], int r, int *max, int *min) { int s = 0; int i; for (i = 0; i < r; i++) { s += score[p[i]][p[i+1]]; } (*max) = (*max) > s ? (*max) : s; (*min) = (*min) < s ? (*min) : s; } void permute(int p[], int l, int r, void (*calc)(int *, int, int *, int *), int *max, int *min) { int i; if (l == r) { calc(p, r, max, min); return; } for (i = l; i <= r; i++) { swap(p[l], p[i]); permute(p, l+1, r, calc, max, min); swap(p[l], p[i]); } } int main(void) { char a[16], b[16], t[16]; int p[8] = {0,1,2,3,4,5,6,7}; int s, i; int min = INT_MAX; int max = 0; while(scanf("%s", a) == 1) { for (i = 0; i < 4; i++) { if (i == 3) { scanf("%d", &s); } else if (i == 1) { scanf("%s", b); } else { scanf("%s", t); } } score[nameid(a)][nameid(b)] = s; score[nameid(b)][nameid(a)] = s; } permute(p, 0, 7, calc, &max, &min); printf("%d\n%d\n", min, max); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> void looknsay(char *str, char *new) { int n = 0; int i, j; for (i = 0; str[i];) { for (j = i+1; str[j] == str[i]; j++); new[n] = '0' + (j - i); new[n+1] = str[i]; n += 2; i = j; } new[n] = 0; } int main(void) { int i; char *str, *new, *t; str = malloc(10000000); new = malloc(10000000); strcpy(str, "1321131112"); for (i = 0; i < 50; i++) { looknsay(str, new); t = str; str = new; new = t; if (i == 39) printf("%lu\n", strlen(str)); } printf("%lu\n", strlen(str)); return 0; } <file_sep>#include <stdio.h> #include <string.h> #include <openssl/md5.h> int main(void) { char key[] = "yzbqklnj"; char buf[64]; unsigned char out[MD5_DIGEST_LENGTH]; int i, k = 0; for (i = 1; i < 10000000; i++) { MD5_CTX c; sprintf(buf, "%s%d", key, i); MD5_Init(&c); MD5_Update(&c, buf, strlen(buf)); MD5_Final(out, &c); if (out[0] == 0 && out[1] == 0 && out[2] == 0) { printf("%d\n", i); break; } if (k == 0 && out[0] == 0 && out[1] == 0 && (out[2] & 0xf0) == 0) { printf("%d\n", i); k = 1; } } return 0; } <file_sep>#include <stdio.h> int main(void) { int l, w, h; char t, u; int total = 0; int totalr = 0; while (scanf("%d%c%d%c%d", &l, &t, &w, &u, &h) == 5) { int a1 = l*w; int a2 = w*h; int a3 = h*l; int maxl; int mina = a1 < a2 ? a1 : a2; mina = mina < a3 ? mina : a3; total += 2*a1 + 2*a2 + 2*a3 + mina; maxl = l > w ? l : w; maxl = maxl > h ? maxl : h; totalr += 2*(l+w+h-maxl) + l*w*h; } printf("%d\n%d\n", total, totalr); return 0; } <file_sep>#include <stdio.h> #include <string.h> int main(void) { char str[32]; int i; int count1 = 0; int count2 = 0; while(scanf("%s", str) == 1) { int vow = 0; int repeat = 0; if (strstr(str, "ab")) goto part2; if (strstr(str, "cd")) goto part2; if (strstr(str, "pq")) goto part2; if (strstr(str, "xy")) goto part2; for (i = 0; str[i]; i++) { if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') vow++; if (i > 0 && str[i] == str[i-1]) repeat = 1; } if (vow >= 3 && repeat) count1++; part2: repeat = 0; for (i = 0; str[i]; i++) { if (i > 1 && str[i] == str[i-2]) repeat |= 1; if (i > 2) { char *sp; char temp[] = { str[i-1], str[i], 0 }; sp = strstr(str, temp); if (sp && sp <= &str[i-3]) repeat |= 2; } } if (repeat == 3) count2++; } printf("%d\n%d\n", count1, count2); return 0; } <file_sep>#include <stdio.h> #define swap(a, b) do { int __t = a; a = b; b = __t; } while (0) int score[9][9]; int nameid(char *name) { if (name[0] == 'M') return 7; return name[0] - 'A'; } void calc(int p[], int r, int *max) { int s = 0; int i; for (i = 0; i <= r + 1; i++) { if (i < r + 1) { s += score[p[i]][p[i+1]]; s += score[p[i+1]][p[i]]; } else { s += score[p[i]][p[0]]; s += score[p[0]][p[i]]; } } (*max) = (*max) > s ? (*max) : s; } void permute(int p[], int l, int r, void (*calc)(int *, int, int *), int *max) { int i; if (l == r) { calc(p, r, max); return; } for (i = l; i <= r; i++) { swap(p[l], p[i]); permute(p, l+1, r, calc, max); swap(p[l], p[i]); } } int main(void) { char a[16], b[16], t[16]; int p[9] = {0,1,2,3,4,5,6,7,8}; int minus, s, i; int max = 0; while(scanf("%s", a) == 1) { for (i = 0; i < 10; i++) { if (i == 2) { scanf("%d", &s); s = (minus) ? -s : s; } else if (i == 9) { scanf("%s", b); } else { scanf("%s", t); if (i == 1) minus = (t[0] == 'l'); } } score[nameid(a)][nameid(b)] = s; } permute(p, 0, 6, calc, &max); printf("%d\n", max); max=0; permute(p, 0, 7, calc, &max); printf("%d\n", max); }
bed0b78abf2945f51d045bb907aa6ae6230f8b11
[ "C", "Python", "Makefile" ]
16
C
tuxoko/advent
3357fc62d50db1c7a958d5e1aa711c71f0456fd2
9058722a2d918e44cadf0679e314bced56657f85
refs/heads/master
<repo_name>imclab/eecs_268<file_sep>/lib/make_button.rb module ButtonMaker def button_for(name, url, image) html = "<a class=\"button\" href=\"#{url}\">" html << " <img src=\"/css/blueprint/plugins/buttons/icons/#{image}.png\" alt=\"\"/> #{name}" html << "</a>" html end end Webby::Helpers.register(ButtonMaker)<file_sep>/tasks/commit.rake desc "Commit to git" task :push do |t| `git push origin master` end<file_sep>/content/files/intro/makefile all:HelloWorld.o MyClass.o g++ HelloWorld.o MyClass.o -o lab1 HelloWorld.o:HelloWorld.cpp MyClass.h g++ -c HelloWorld.cpp MyClass.o:MyClass.h MyClass.cpp g++ -c MyClass.cpp clean: rm -f *.o *~ lab1 tar: clean cd ..;tar cf ./jvalland_lab1.tar ./jvalland_lab1<file_sep>/content/files/comments/someClass.h /** @file * An example file * @author <NAME> * @date 28 August 2007 * @version 0.1 */ /** This is a class. It does things. */ class Some { public: /** Default constructor. */ Some(); /** Accessor method for data * @pre None. * @post None. * @return The value stored in data. */ int getData() const; /** Mutator method for data. * @param x An integer value. * @pre x has desired new value for data. * @post data now has the value of x. */ void setData(inx x); private: /** The data member in the class Some. */ int data; };
87c2d8207b0cf856f15d110c777d6aa3a6a9de7c
[ "Makefile", "Ruby", "C++" ]
4
Ruby
imclab/eecs_268
54989316d4c5b69cbc7b28cc8e97239955241e85
cec7b2948fd63783fb210f0b22810f0b0da89730
refs/heads/master
<repo_name>abyrne85/sortable-list<file_sep>/README.md demo : http://andrewjbyrne.com/sortable-list<file_sep>/app/scripts/controllers/onelist.js 'use strict'; /** * @ngdoc function * @name angulistApp.controller:OnelistCtrl * @description * # OnelistCtrl * Controller of the angulistApp */ angular.module('angulistApp') .controller('OneListCtrl', function ($scope, $http) { $scope.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; $scope.showMovedJobs=false; $scope.updatedList =[]; function initList(){ $http.get('jobs.json').success(function(data){ $scope.pool = data[0]; }); } initList(); $scope.sortableOptions = { 'stop':function(){ updateList(); } }; $scope.resetList = function(){ $scope.showMovedJobs=false; initList(); }; function updateList(){ $scope.updatedList=[]; $scope.showMovedJobs=true; for(var i=0;i<$scope.pool.length;i++){ $scope.updatedList.push($scope.pool[i].name); } } });
d886fc95357019945451ea9293dba20af8418148
[ "Markdown", "JavaScript" ]
2
Markdown
abyrne85/sortable-list
ee2eb4e06eda8f7928eb9e7165280f32c6be2e7d
6a02db9ab7cd9a128b119fe3cfcc93240bcb65bb
refs/heads/master
<repo_name>valentin-b99/Projet-PPE-Terminale<file_sep>/main.ino /* Programme réalisé par <NAME> dans le cadre des PPE - Terminale SSI, Groupe panneau solaire orientable Année 2017-2018 */ //Setup Motors #include <DRV8835MotorShield.h> #define LED_PIN 13 DRV8835MotorShield motors; //Setup photocells int photocellPinA2 = 2; // the cell connected to a2 int photocellPinA3 = 3; // the cell connected to a3 int photocellPinA4 = 4; // the cell connected to a4 int photocellPinA5 = 5; // the cell connected to a5 int photocellReadingA2; // the analog reading from the analog resistor divider a2 int photocellReadingA3; // the analog reading from the analog resistor divider a3 int photocellReadingA4; // the analog reading from the analog resistor divider a4 int photocellReadingA5; // the analog reading from the analog resistor divider a5 int averageLeft; //average of photocellReading A2 and A3 int averageRight; //average of photocellReading A4 and A5 boolean Night; //Boolean value of night boolean ResetMotor; //Boolean value of reset motor void setup() { Serial.begin(9600); //Information via the Serial monitor //Setup Channel A pinMode(LED_PIN, OUTPUT); pinMode(12, OUTPUT); //Initiates Motor Channel A pin pinMode(9, OUTPUT); //Initiates Brake Channel A pin } void loop() { photocellReadingA2 = analogRead(photocellPinA2); photocellReadingA3 = analogRead(photocellPinA3); photocellReadingA4 = analogRead(photocellPinA4); photocellReadingA5 = analogRead(photocellPinA5); /*Serial.print("A2 : "); Serial.print(photocellReadingA2); // the raw analog reading Serial.println("\n"); Serial.print("A3 : "); Serial.print(photocellReadingA3); // the raw analog reading Serial.println("\n"); Serial.print("A4 : "); Serial.print(photocellReadingA4); // the raw analog reading Serial.println("\n"); Serial.print("A5 : "); Serial.print(photocellReadingA5); // the raw analog reading Serial.println("\n");*/ averageRight = (photocellReadingA2+photocellReadingA3)/2; averageLeft = (photocellReadingA4+photocellReadingA5)/2; Serial.print("\nAverage Right : "); Serial.print(averageRight); Serial.print("\nAverage Left : "); Serial.print(averageLeft); if ((averageLeft + averageRight) > (300*2)){ Night = false; ResetMotor = false; Serial.print("\nDay !"); } else { Night = true; Serial.print("\nNight !"); } if ((averageLeft >= averageRight) && (Night == false)){ digitalWrite(LED_PIN, LOW); motors.setM1Speed(-400); Serial.print("\nChasing sun !"); } else { digitalWrite(LED_PIN, LOW); motors.setM1Speed(0); Serial.print("\nStop Rotate"); } if ((Night == true) && (ResetMotor == false)){ Serial.print("\nGood night ! (Reset)"); digitalWrite(LED_PIN, HIGH); motors.setM1Speed(400); Serial.print("\nReset start !"); Serial.print("\nReset stake 0%"); delay(10000); Serial.print("\nReset stake 10%"); delay(10000); Serial.print("\nReset stake 20%"); delay(10000); Serial.print("\nReset stake 30%"); delay(10000); Serial.print("\nReset stake 40%"); delay(10000); Serial.print("\nReset stake 50%"); delay(10000); Serial.print("\nReset stake 60%"); delay(10000); Serial.print("\nReset stake 70%"); delay(10000); Serial.print("\nReset stake 80%"); delay(10000); Serial.print("\nReset stake 90%"); delay(10000); Serial.print("\nReset stake 100%"); delay(5000); Serial.print("\nReset Done !"); digitalWrite(LED_PIN, LOW); motors.setM1Speed(0); ResetMotor = true; } } <file_sep>/README.md Projet PPE - Terminale Dans le cadre du Baccalauréat, mon équipe et moi-même avons créé un panneau solaire orientable. En effet, nous avions pour objectif d’avoir un rendement maximum en suivant la trajectoire du soleil. En Juin, nous avons pu présenter notre projet terminé et fonctionnel. La partie programmation ainsi que la réflexion des composants électroniques a été réalisé par moi-même. La programmation a été faite en Arduino.
f7c3130081296313115193fc58b6b5663b0c41ed
[ "Markdown", "C++" ]
2
C++
valentin-b99/Projet-PPE-Terminale
2b320ddc8340b7ace5dfefaddd965cdaf9072b23
509d631f22011b1f94943169662798b61e2cf722
refs/heads/main
<file_sep>// Simply finds the comment element and removes it if comments exist var commentSection = document.getElementById("cbox_module"); if (commentSection !== null) { commentSection.remove(); }<file_sep># naver-news-comments-removal ## Description A simple Google Chrome Extension to remove the comments section in Naver News section. Go to "chrome://extensions/" and click "Load unpacked". Select the folder with the files and turn on the chrome extension.
0920dfc82c1892ae483e758ded2e6bfc42449927
[ "JavaScript", "Markdown" ]
2
JavaScript
byunsy/naver-news-comments-removal
765d4cea2f77ac228a2284949475a9e971a9fcbd
75e3fd4aa8c91a4b5e25df568bf48c23eb795095
refs/heads/master
<file_sep>import requests,re from threading import Thread,activeCount,Lock from html import unescape from queue import Queue from urllib.parse import urlparse from html import unescape import sys,os,chardet import argparse domains = list() wait_verify_domains = list() js_list = list() api_list = list() lock = Lock() requests.packages.urllib3.disable_warnings() def parse_args(): parser = argparse.ArgumentParser(epilog='\tUsage:\npython ' + sys.argv[0] + " -d www.baidu.com --keyword baidu") parser.add_argument("-d", "--domain", help="Site you want to scrapy") parser.add_argument("-f", "--file", help="File of domain or target you want to scrapy") parser.add_argument("--keyword", help="Keywords of domain regexp") parser.add_argument("--save", help="Saving apis file.") parser.add_argument("--savedomain", help="Saving domains file.") parser.add_argument("--batch", help="Don\'t need to enter the keywords") return parser.parse_args() def send_request(url): # if not url.startswith(('http://','https://')): # url = 'http://' + url headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'} session = requests.session() session.headers = headers try: resp = session.get(url,timeout=(5,20),verify=False) except Exception as e: print('[Error]Can\'t access to {}'.format(url.strip())) return try: encoding = resp.encoding if encoding in [None,'ISO-8859-1']: encodings = requests.utils.get_encodings_from_content(resp.text) if encodings: encoding = encodings[0] else: encoding = resp.apparent_encoding return resp.content.decode(encoding) except: if 'charset' not in resp.headers.get('Content-Type', " "): resp.encoding = chardet.detect(resp.content).get('encoding') # 解决网页编码问题 return resp.text def parse_href(href,url_parse): if 'javascript' in href:return href = unescape(href) black_list = ['jpg','png','css','apk','ico','js','jpeg','exe','gif'] for bk in black_list: if (href[-len(bk):] or href.split('?')[0][-len(bk):]) == bk:return if href.startswith(('http://','https://')):return href elif href.startswith('////'): href = url_parse.scheme + ':' + href[2:] return href elif href.startswith('///'): href = url_parse.scheme + ':' + href[1:] return href elif href.startswith('//'): href = url_parse.scheme + ':' + href return href elif href.startswith('/'): href = url_parse.scheme + '://' + url_parse.netloc + href return href else: return url_parse.scheme + '://' + url_parse.netloc + url_parse.path + '/' + href def parse_script(script,url_parse): if 'javascript' in script:return script = unescape(script) black_list = ['jpg','png','css','apk','ico','jpeg','exe','gif'] for bk in black_list: if (script[-len(bk):] or script.split('?')[0][-len(bk):]) == bk:return if script.startswith(('http://','https://')):return script elif script.startswith('////'): script = url_parse.scheme + ':' + script[2:] return script elif script.startswith('///'): script = url_parse.scheme + ':' + script[1:] return script elif script.startswith('//'): script = url_parse.scheme + ':' + script return script elif script.startswith('/'): script = url_parse.scheme + '://' + url_parse.netloc + script return script else: return url_parse.scheme + '://' + url_parse.netloc + url_parse.path + '/' + script def find_href(url): href_pattern = re.compile('href=["|\'](.*?)["|\']',re.S) resp = send_request(url) if resp: url_parse = urlparse(url) href_result = re.findall(href_pattern,resp) for _ in href_result: href = parse_href(_,url_parse) if href: href_parse = urlparse(href) href_domain = href_parse.netloc if lock.acquire(): if href_domain not in domains: for keyword in keywords: if keyword in href_domain: #print(href_domain) domains.append(href_domain) print('[{}]{}'.format(len(domains),href_domain)) wait_verify_domains.append(href_domain) break lock.release() find_js(url,resp) def find_js(url,resp): #queue_script = Queue() script_dict = {} url_parse = urlparse(url) script_pattern = re.compile('src=["|\'](.*?)["|\']',re.S) script_text_pattern = re.compile('<script>(.*?)</script>',re.S) script_result = re.findall(script_pattern,resp) if script_result: for _ in script_result: _ = parse_script(_,url_parse) if _: if lock.acquire(): if _ not in js_list: # print(_) script_parse = urlparse(_) script_root_domain = script_parse.netloc if script_root_domain not in domains: # print(script_root_domain) for keyword in keywords: if keyword in script_root_domain: domains.append(script_root_domain) print('[{}]{}'.format(len(domains),script_root_domain)) wait_verify_domains.append(script_root_domain) break js_list.append(_) resp = send_request(_) if resp: script_dict[script_parse] = resp lock.release() script_text_result = re.findall(script_text_pattern,resp) if script_text_result: for _ in script_text_result: script_dict[url_parse] = script_text_result #print(script_dict) if script_dict: find_api(script_dict) def find_api(script_dict): pattern_raw = r""" (?:"|') # Start newline delimiter ( ((?:[a-zA-Z]{1,10}://|//) # Match a scheme [a-Z]*1-10 or // [^"'/]{1,}\. # Match a domainname (any character + dot) [a-zA-Z]{2,}[^"']{0,}) # The domainextension and/or path | ((?:/|\.\./|\./) # Start with /,../,./ [^"'><,;| *()(%%$^/\\\[\]] # Next character can't be... [^"'><,;|()]{1,}) # Rest of the characters can't be | ([a-zA-Z0-9_\-/]{1,}/ # Relative endpoint with / [a-zA-Z0-9_\-/]{1,} # Resource name \.(?:[a-zA-Z]{1,4}|action) # Rest + extension (length 1-4 or action) (?:[\?|/][^"|']{0,}|)) # ? mark with parameters | ([a-zA-Z0-9_\-]{1,} # filename \.(?:php|asp|aspx|jsp|json| action|html|js|txt|xml) # . + extension (?:\?[^"|']{0,}|)) # ? mark with parameters ) (?:"|') # End newline delimiter """ pattern = re.compile(pattern_raw, re.VERBOSE) for script_parse,script_text in script_dict.items(): print('[Working]Logging in scrapy {} api.'.format(script_parse.netloc)) result = re.finditer(pattern, str(script_text)) if result == None: continue for match in result: match = match.group().strip('"').strip("'") match = parse_href(match,script_parse) if match: if lock.acquire(): if match not in api_list: for keyword in keywords: if keyword in match: api_list.append(match.strip()) if api_file: with open(api_file,'a+',encoding='utf-8') as f: f.write(match.strip() + '\n') else: print('[Find]{}'.format(match.strip())) break api_netloc = urlparse(match).netloc.strip() if api_netloc not in domains: for keyword in keywords: if keyword in api_netloc: if api_netloc.endswith('\\'): api_netloc = api_netloc[:-1] domains.append(api_netloc) print('[{}]{}'.format(len(domains),api_netloc)) wait_verify_domains.append(api_netloc) break lock.release() def main(domain): # global keywords find_href(domain) queue = Queue() lock = Lock() num = 0 while len(wait_verify_domains)>0: num = num+1 print('------------------------------------------------------第{}次轮询开始'.format(num)) # domain = wait_verify_domains.pop() # if not domain.startswith(('http://','https://')): # domain = 'http://' + domain #print(domain) for domain in wait_verify_domains: wait_verify_domains.remove(domain) if not domain.startswith(('http://','https://')): domain = 'http://' + domain queue.put(domain) while queue.qsize()>0: if activeCount()<=20: href_thread = Thread(target=find_href,args=(queue.get(),)) href_thread.start() href_thread.join() print('Working done!All find {} api and {} domain'.format(len(api_list),len(domains))) with open(save_domainfile,'a+',encoding='utf-8') as f: for _ in domains: f.write(_.strip()+'\n') # find_href(domain) if __name__ == '__main__': args = parse_args() domain = args.domain domain_file = args.file api_file = args.save save_domainfile = args.savedomain if domain: #domain_netloc = urlparse(domain).netloc if not domain.startswith(('http://','https://')): domain = 'http://' + domain try: domain_netloc = urlparse(domain).netloc domains.append(domain_netloc) except: print('[Error!]Can\'t access to domain:{}'.format(domain)) if args.keyword: keywords = args.keyword.split(',') else: keywords = None if keywords is None: if len(domain_netloc.split('.'))>=3: keywords = domain_netloc.split('.')[1:2] #print(domain_netloc.split('.')) elif len(domain_netloc.split('.'))<3: keywords = domain_netloc.split('.')[0:1] keyword_check = input('由于未指定关键字,程序选取关键字为{},若不正确,请输入你的关键字:'.format(keywords)) if keyword_check : keywords = keyword_check.split(',') # print(keyword_check) #print(keywords) #return domains.append(domain_netloc) main(domain) elif domain_file: queue_file = Queue() with open(domain_file,'r+') as f: for _ in f: domains.append(_) if not _.startswith(('http://','https://')): _ = 'http://' + _ queue_file.put(_.strip()) while queue_file.qsize()>0: if activeCount()<=10: domain = queue_file.get() try: domain_netloc = urlparse(domain).netloc except: print('[Error!]Can\'t access to domain:{}'.format(domain)) if args.keyword: keywords = args.keyword.split(',') else: keywords = None if keywords is None: if len(domain_netloc.split('.'))>=3: keywords = domain_netloc.split('.')[1:2] #print(domain_netloc.split('.')) elif len(domain_netloc.split('.'))<3: keywords = domain_netloc.split('.')[0:1] if not args.batch: keyword_check = input('由于未指定关键字,程序选取关键字为{},若不正确,请输入你的关键字:'.format(keywords)) if keyword_check: keywords = keyword_check.split(',') #print(keywords) domain_thread = Thread(target=main,args=(domain,)) domain_thread.start() domain_thread.join() <file_sep># JSINFO-SCAN ### 前言 很早以前就想写一款对网站进行爬取,并且对网站中引入的JS进行信息搜集的一个工具,之前一直没有思路,因为对正则的熟悉程度没有到可以对js中的info进行匹配的地步,最近实验室的朋友写了一款工具:[JSFinder](https://github.com/Threezh1/JSFinder "JSFinder"),借用了他的思路,写了一款递归爬取域名(netloc/domain),以及递归从JS中获取信息的工具。 ### 思路 写这个工具主要有这么几个点: - 如何爬取域名 - 如何爬取JS - 如何从JS中获取信息 三个点的解决方案: - 正则匹配href属性中的链接 - 正则匹配src属性中的链接,并判断链接是否为js。正则匹配`<script></script>`标签中的文本。 - 使用LinkFinder的正则从JS中匹配敏感信息 ### 优点 - 实现递归爬取 - 对JS中匹配到的info进行了处理,直观的展示出来 ### 缺点 使用的是单线程,因为目前多线程还没学够,如果冒昧使用担心引起数据混乱的问题,也并不熟悉使用Lock()函数,怕使用的地方多了,多线程也变成了单线程。 ### Usage ``` python3 jsinfo.py -d jd.com --keyword jd --save jd.api.txt --savedomain jd.domain.txt ``` - -d/-f 对单个域名或对域名文件进行扫描,文件需要一行一个域名。 - --keyword 设置爬取关键字,会使用该关键字对域名进行匹配,必选项。 - --savedomain 设置爬取出来的域名保存路径 - --save 设置api保存路径 ### 实例 - 对京东进行爬取 只爬取jd.com,设置keyword为jd,joybuy,360: ![enter image description here](https://s2.ax1x.com/2019/06/27/Zma4Tf.png) - 对百度进行爬取 ![enter image description here](https://s2.ax1x.com/2019/06/27/Zmablj.png) ### Update 2019-7-5:重构代码,加入了爬行深度的设定,深度为1~2,默认为1,2即为深度爬取,同时增加了url的存储,即深度爬取爬取到的链接。 2020-2-10:重构代码,整体使用了协程,使用队列的方式作为递归标准,默认递归深度为8,可根据自身需要进行修改。 经过测试,速度是v1版本的十倍不止,并且获取到的域名也是v1版本的两倍,但是这一版取消了获取api。 效果: ![](https://s2.ax1x.com/2020/02/10/1ImiUe.jpg) 2020-2-16:增加搜集其他信息的功能,比如邮箱,代码作者,ip等。 效果: ![3Ufg5n.png](https://s2.ax1x.com/2020/02/26/3Ufg5n.png) <file_sep>from aiomultiprocess import Pool import asyncio import aiohttp import argparse import os import re from urllib.parse import urlparse from loguru import logger from html import unescape from tldextract import extract from aiohttp import TCPConnector import argparse import sys sub_domains = [] def parse_args(): parser = argparse.ArgumentParser(epilog='\tUsage:\npython ' + sys.argv[0] + " -d www.baidu.com --keyword baidu") parser.add_argument("--depth", help="Scrapy depth.") parser.add_argument("-f", "--file", help="File of domain or target you want to scrapy",required=True) parser.add_argument("--keyword", help="Keywords of domain regexp",required=True) parser.add_argument("-o","--output", help="Saving domains file.") parser.add_argument("-io","--info_output", help="Saving info file.") return parser.parse_args() class JSINFO(): def __init__(self,domain,keyword,domain_output,depth,info_output): if not domain.startswith(('http://','https://')): self.domain = 'http://'+domain else: self.domain = domain self.keywords = keyword self.domain_output = domain_output self.links_new = {} self.links = [] self.count = 1 self.links.append(self.domain) self.links_new[self.domain] = self.count self.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'} self.domains = [] self.jslinks = [] self.apis = [] self.mails = [] self.iplist = [] self.authors = [] self.info_output = info_output if depth: self.maxcount = int(depth) else: self.maxcount = 8 self.rootdomains = [] self.extract_links = [] self.rootdomains.append(self.domain) self.link_pattern = re.compile('href="(.*?)"',re.S) self.js_pattern = re.compile('<script.*?src="(.*?)"',re.S) self.js_text_pattern = re.compile('<script.*?>(.*?)</script>',re.S) self.js_ip_pattern = re.compile('([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})',re.S) logger.info('max deepth is :{}'.format(self.maxcount)) # start the work def run(self): loop = asyncio.get_event_loop() n = 1 while len(list(self.links_new.keys())) > 0: if len(list(self.links_new.keys())) < 50: logger.info('-----------------------------------------------------------------------------------') logger.info('|正在进行第{}次迭代'.format(n)) logger.info('|当前url列表数量:{}'.format(len(list(self.links_new.keys())))) logger.info('|当前域名数量:{}'.format(len(sub_domains))) logger.info('|当前根域名数量:{}'.format(len(self.rootdomains))) logger.info('|已解析链接数量:{}'.format(len(self.extract_links)-len(list(self.links_new.keys())))) logger.info('-----------------------------------------------------------------------------------') n+=1 i = 0 tasks = [] del_list = [] while i < len(self.links_new): for k,v in self.links_new.items(): if v>=self.maxcount: del_list.append(k) i += 1 continue else: i+=1 del_list.append(k) tasks.append(k) for del_key in del_list: self.links_new.pop(del_key) tasks_loop = [asyncio.ensure_future(self.find_link(url))for url in tasks] self.count +=1 if tasks_loop: loop.run_until_complete(asyncio.wait(tasks_loop)) else: break else: logger.info('-----------------------------------------------------------') logger.info('|正在进行第{}次迭代'.format(n)) logger.info('|当前url列表数量:{}'.format(len(list(self.links_new.keys())))) logger.info('|当前域名数量:{}'.format(len(sub_domains))) logger.info('|当前根域名数量:{}'.format(len(self.rootdomains))) logger.info('|已解析链接数量:{}'.format(len(self.extract_links)-len(list(self.links_new.keys())))) logger.info('-----------------------------------------------------------') n+=1 i = 0 tasks = [] del_list = [] while i<=50: for k,v in self.links_new.items(): if v > self.maxcount: del_list.append(k) # self.links_new.pop(k) continue else: if i <= 50: i+=1 del_list.append(k) tasks.append(k) else: break break for del_key in del_list: if del_key in self.links_new: self.links_new.pop(del_key) tasks_loop = [asyncio.ensure_future(self.find_link(url))for url in tasks] self.count += 1 if tasks_loop: loop.run_until_complete(asyncio.wait(tasks_loop)) else: break logger.info('all subdomain\'s count:{}'.format(len(sub_domains))) if self.info_output: for mail in self.mails: with open(self.info_output,'a+') as f: f.write(mail+'\n') for ip in self.iplist: with open(self.info_output,'a+') as f: f.write(ip+'\n') for author in self.authors: with open(self.info_output,'a+') as f: f.write(str(author)+'\n') async def find_link(self,link): sem = asyncio.Semaphore(1024) try: async with aiohttp.ClientSession() as session: async with sem: async with session.get(link,timeout=20,headers=self.headers) as resp: resp = await resp.text("utf-8","ignore") except Exception as e: logger.warning('resolve {} fail,exception:{}',link,e) return links = re.findall(self.link_pattern,resp) self.other_info(resp) try: parse_url = urlparse(link) except: return script_urls = self.parse_url(re.findall(self.js_pattern,resp),parse_url) script_text = re.findall(self.js_text_pattern,resp) self.parse_url(links,parse_url) for js_url in script_urls: try: async with aiohttp.ClientSession() as session: async with sem: async with session.get(js_url,timeout=20,headers=self.headers) as resp: resp = await resp.text("utf-8","ignore") except Exception as e: logger.warning('resolve {} fail,exception:{}',link,e) if resp: script_text.append(resp) self.extract_js(script_text,parse_url) def extract_js(self,script_text,parse_url): func_apis = [] #logger.info('extract {} in js now',parse_url.netloc) pattern = r""" (?:"|') # Start newline delimiter ( ((?:[a-zA-Z]{1,10}://|//) # Match a scheme [a-Z]*1-10 or // [^"'/]{1,}\. # Match a domainname (any character + dot) [a-zA-Z]{2,}[^"']{0,}) # The domainextension and/or path | ((?:/|\.\./|\./) # Start with /,../,./ [^"'><,;| *()(%%$^/\\\[\]] # Next character can't be... [^"'><,;|()]{1,}) # Rest of the characters can't be | ([a-zA-Z0-9_\-/]{1,}/ # Relative endpoint with / [a-zA-Z0-9_\-/]{1,} # Resource name \.(?:[a-zA-Z]{1,4}|action) # Rest + extension (length 1-4 or action) (?:[\?|/][^"|']{0,}|)) # ? mark with parameters | ([a-zA-Z0-9_\-]{1,} # filename \.(?:php|asp|aspx|jsp|json| action|html|js|txt|xml) # . + extension (?:\?[^"|']{0,}|)) # ? mark with parameters ) (?:"|') # End newline delimiter """ pattern = re.compile(pattern, re.VERBOSE) for text in script_text: results = re.finditer(pattern, str(text)) self.other_info(str(text)) if results: for match in results: match = match.group().strip('"').strip("'") if match not in func_apis and match not in self.apis: self.apis.append(match) func_apis.append(match) self.parse_url(func_apis,parse_url) def parse_url(self,urls,parse_url): func_js = [] #logger.info('parse {} links now',parse_url.netloc) black_type = ['jpg','png','css','apk','ico','jpeg','exe','gif','avi','mp3','mp4'] JSExclusionList = ['jquery', 'google-analytics','gpt.js'] for url in urls: url = unescape(url) filename = os.path.basename(url) # start solve black type if filename.split('.')[-1:][0] in black_type: continue elif 'javascript:' in url: continue elif filename.split('.')[0:1] in JSExclusionList: continue # start solve url scheme if url.startswith('////'): url = 'http:' + url[2:] elif url.startswith('//'): url = 'http:' + url elif url.startswith('/'): url = parse_url.scheme + '://' + parse_url.netloc + url elif url.startswith('./'): url = parse_url.scheme + '://' + parse_url.netloc + parse_url.path + url[1:] elif 'http://' in url or 'https://' in url: url = url else: url = parse_url.scheme + '://' + parse_url.netloc + parse_url.path + '/' + url extract_domain = extract(url) root_domain = extract_domain.domain + '.' + extract_domain.suffix if url: if url not in self.extract_links: for keyword in self.keywords: if keyword in root_domain: self.links_new[url] = self.count #self.links.append(url) self.extract_links.append(url) try: parse_netloc = urlparse(url).netloc except: continue if parse_netloc: for keyword in self.keywords: if keyword in parse_netloc: if keyword in root_domain: if parse_netloc not in sub_domains: if 'en.alibaba.com' not in parse_netloc: sub_domains.append(parse_netloc) logger.info('Collect a new domain:{}',parse_netloc) if 'http://' + parse_netloc + '/' not in self.extract_links and 'http://' + parse_netloc not in self.extract_links and 'https://' + parse_netloc not in self.extract_links and 'https://' + parse_netloc +'/' not in self.extract_links: #self.links.append('http://' + parse_netloc + '/') if 'en.alibaba.com' not in 'http://' + parse_netloc + '/': self.links_new['http://' + parse_netloc + '/'] = self.count self.extract_links.append('http://' + parse_netloc + '/') if root_domain not in self.rootdomains: self.rootdomains.append(root_domain) if url not in func_js and url not in self.jslinks: self.jslinks.append(url) func_js.append(url) return func_js def other_info(self,text): mail_pattern = re.compile('([-_\w\.]{0,64}@[-\w]{1,63}\.*[-\w]{1,63})',re.S) ip_pattern = re.compile('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}',re.S) author_pattern = re.compile('@author[: ]+(.*?) ',re.S) mails_result = re.findall(mail_pattern,text) #print(text) if mails_result != []: for mail in mails_result: mail = mail.strip() if '.' not in mail: continue if mail not in self.mails: self.mails.append(mail) logger.info('Find a mail:{}'.format(mail)) ip_result = re.findall(ip_pattern,text) if ip_result != []: for ip in ip_result: ip = ip.strip() if ip not in self.iplist: self.iplist.append(ip.strip()) logger.info('Find a ip:{}'.format(ip)) author_result = re.findall(author_pattern,text) if author_result != []: for author in author_result: author = author.strip() if author not in self.authors: self.authors.append(author) logger.info('Find a author:{}'.format(author)) if __name__ == "__main__": args = parse_args() domain_file = args.file output = args.output keywords = args.keyword.split(',') depth = args.depth domains = [] info_output = args.info_output with open(domain_file,'r+') as f1: for domain in f1: domains.append(domain.strip()) for domain in domains: JSINFO(domain,keywords,output,depth,info_output).run() if output: with open(output,'a+') as f: for domain in sub_domains: f.write(domain+'\n')
0cab432848b4923c76452095c53c85f6b7762bda
[ "Markdown", "Python" ]
3
Python
mmg1/JSINFO-SCAN
717e095659f1d56c5e09841fac47b9bf2f23149a
ec6149bb76ed06068a7c732a8104a391e0a6f754
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import {QuizQuestionsService} from '../../../shared/quiz-questions.service'; import {QuizQuestion} from './quiz-question.model'; @Component({ selector: 'app-quiz-question', templateUrl: './quiz-question.component.html', styleUrls: ['./quiz-question.component.scss'] }) export class QuizQuestionComponent implements OnInit { correctCount = 0; currentQuestion = 0; progressValue = 0; questionCount; questions$; selectedOption; // image urls overridden by Data URLs in constructor for stackblitz workaround constructor(private quizQuestionsService: QuizQuestionsService) { } ngOnInit() { this.questions$ = this.quizQuestionsService.getQuestions(); this.questions$.subscribe((questions: QuizQuestion[]) => { this.questionCount = questions['quiz-questions'].length; this.progressValue = 100 * (this.currentQuestion + 1) / this.questionCount; }); } nextQuestion(answer: number) { if (answer === this.selectedOption) {this.correctCount++; } delete this.selectedOption; this.currentQuestion++; this.progressValue = 100 * (this.currentQuestion + 1) / this.questionCount; } } <file_sep># angular-kmhr6g [Edit on StackBlitz ⚡️](https://stackblitz.com/edit/angular-kmhr6g)
9cad075a6f737bc8f6282d2442553914a2c2f050
[ "Markdown", "TypeScript" ]
2
TypeScript
seebhoopi/angular-kmhr6g
8e568d2dccad32ebe8fb3bf9ad789e297c173ee7
f8871363b46ebcd94a3313a56192ecd78030768d
refs/heads/master
<repo_name>geeh-xx/edne-correios<file_sep>/Gemfile source :rubygems gem "rake" gem "data_mapper" #gem "dm-sqlite-adapter" gem "dm-postgres-adapter" gem "dm-migrations" gem 'dm-mysql-adapter', '~> 1.2' gem 'mysql2', '0.3.20' gem "pry"
b41bf1d93de83ff53547e41e6c30a853a7c662ad
[ "Ruby" ]
1
Ruby
geeh-xx/edne-correios
7258e8679409fc64afb52dc5d4f7d504ee16b65d
52ba69ca69b3a2ed02444a5ed9130e9de630b4f6
refs/heads/main
<file_sep># nasmtutorial ## This tutorial can be found at https://cs.lmu.edu/~ray/notes/nasmtutorial/. 1. Clone the repository. 2. Open the index.html in your browser. ## Links #### Intel vs. AT&T syntax: http://staffwww.fullcoll.edu/aclifton/courses/cs241/syntax.html #### Review of x86 assembly: http://www.scs.stanford.edu/nyu/04fa/notes/l2.pdf #### x86 calling conventions: https://en.wikipedia.org/wiki/X86_calling_conventions#x86-64_Calling_Conventions #### Differences in Intel (NASM) vs AT&T (GAS) Syntax. https://sdasgup3.github.io/Intel_Vs_Att_format/ #### Linux assemblers: A comparison of GAS and NASM. https://developer.ibm.com/articles/l-gas-nasm/ #### Floating Point Instructions. http://rayseyfarth.com/asm/pdf/ch11-floating-point.pdf #### Where the top of the stack is on x86. https://eli.thegreenplace.net/2011/02/04/where-the-top-of-the-stack-is-on-x86/ #### Stack frame layout on x86-64. https://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64/ <file_sep>PR['registerLangHandler']( PR['createSimpleLexer']( [ [PR['PR_COMMENT'], /^;[^\r\n]*/, null, ';'], [PR['PR_PLAIN'], /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'], ], [ [PR['PR_KEYWORD'], /^\b(?:[e|r]?(ax|bx|cx|dx|si|di|sp|bp)|[a-d](h|l)|(r|xmm|ymm)([0-9]|1[0-5])|st[0-7]?)\b/, null], ]), ['asm']);
d1f8335092489eaf6c2306cc82cdc152e42c680d
[ "Markdown", "JavaScript" ]
2
Markdown
bimlu/nasmtutorial
11b5d4d4599f67e32dbc6dfd3ee0cab265ec493e
b8329d6c5ccc6572fe67655aa10f7c44110afe69
refs/heads/master
<repo_name>hsqlu/bifrost.js<file_sep>/packages/api-derive/src/util/types.ts // Copyright 2020 @bifrost-finance/api-derive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import BN from 'bn.js'; import { Token } from '@bifrost-finance/types/interfaces'; export interface timestampListAndBlockHeight{ timestamp: number, blockHeight: BN } export interface timestampListAndBlockHeightList{ timestampList: number[], blockHeightList: BN[] } export type CEXName = 'binance' | 'huobi' | 'okex'; export interface CEXTokenPrice{ symbol: Token, price: number } export interface symbolUSDValue{ symbol: Token, usdValue: number } <file_sep>/packages/api/src/index.ts // Copyright 2020 @bifrost-finance/api authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { types as bifrostTypes } from '@bifrost-finance/types'; import { derive as bifrostDerives } from '@bifrost-finance/api-derive'; import { ApiOptions } from '@polkadot/api/types'; export const defaultOptions: ApiOptions = { types: bifrostTypes }; export const options = ({ types = {}, ...otherOptions }: ApiOptions = {}): ApiOptions => ({ derives: { ...bifrostDerives }, types: { ...bifrostTypes, ...types }, ...otherOptions }); <file_sep>/packages/api-derive/src/convert/convert.ts // Copyright 2020 @bifrost-finance/api-derive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { ApiInterfaceRx } from '@polkadot/api/types'; import { map, mergeMap } from 'rxjs/operators'; import { Observable, combineLatest } from 'rxjs'; import { ConvertPool } from '@bifrost-finance/types/interfaces'; import { BlockHash } from '@polkadot/types/interfaces/chain'; import { memo, getDesignatedBlockHash } from '../util'; import BN from 'bn.js'; import { vToken } from '../type'; /** * @name getPoolInfo * @description get Single Token Pool information * @param instanceId * @param api */ /** Some notes for understanding: * Memo function takes two parameters, of which the second is a function. * The return value of memo is the function we've sent to it as a parameter for cache optimization sake. * The returned function from memo is also the return value of function getPoolInfo which is shown in the latter part of the function signature. * The returned function's input parameters are tokenSymbol and preBlockHash, and output is a Observable<ConvertPool> type. */ export function getPoolInfo (instanceId: string, api: ApiInterfaceRx): (tokenSymbol: vToken, preBlockHash?: BlockHash) => Observable<ConvertPool> { return memo(instanceId, (tokenSymbol: vToken, preBlockHash?: BlockHash) => { if (preBlockHash === undefined) { return api.query.convert.pool(tokenSymbol); } else { return api.query.convert.pool.at(preBlockHash, tokenSymbol); } }); } /** * @name getAllVtokenConvertInfo * @description get all vToken convertPool information * @param instanceId * @param api */ export function getAllVtokenConvertInfo (instanceId: string, api: ApiInterfaceRx): (vTokenArray?:vToken[]) => Observable<ConvertPool[]> { return memo(instanceId, (vTokenArray?:vToken[]) => { let vTokenList: vToken[]; if (vTokenArray === undefined) { vTokenList = ['vDOT', 'vKSM', 'vEOS']; } else { vTokenList = vTokenArray; } const getPoolInfoQuery = getPoolInfo(instanceId, api); return combineLatest(vTokenList.map((vtk) => getPoolInfoQuery(vtk))); }); } /** * @name getConvertPriceInfo * @description get single Token/vToken convert price information * @param instanceId * @param api */ export function getConvertPriceInfo (instanceId: string, api: ApiInterfaceRx): (tokenSymbol: vToken, preBlockHash?: BlockHash) => Observable<BN> { return memo(instanceId, (tokenSymbol: vToken, preBlockHash?: BlockHash) => { const convertPoolQuery = getPoolInfo(instanceId, api); return convertPoolQuery(tokenSymbol, preBlockHash).pipe( map((result) => { let convertPrice; const tokenPool = new BN(result.token_pool.toNumber()); if (result.vtoken_pool.toNumber()) { const vtokenPool = new BN(result.vtoken_pool.toNumber()); convertPrice = tokenPool.div(vtokenPool); } else { convertPrice = new BN(0); } return convertPrice; }) ); }); } /** * @name getAllConvertPriceInfo * @description get all vToken current convert price information * @param instanceId * @param api */ export function getAllConvertPriceInfo (instanceId: string, api: ApiInterfaceRx): (vTokenArray?:vToken[]) => Observable<BN[]> { return memo(instanceId, (vTokenArray?:vToken[]) => { let vTokenList: vToken[]; if (vTokenArray === undefined) { vTokenList = ['vDOT', 'vKSM', 'vEOS']; } else { vTokenList = vTokenArray; } const getConvertPriceInfoQuery = getConvertPriceInfo(instanceId, api); return combineLatest(vTokenList.map((vtk) => getConvertPriceInfoQuery(vtk))); }); } /** * @name getAnnualizedRate * @description get Single Token Annualized Rate information * @param instanceId * @param api */ export function getAnnualizedRate (instanceId: string, api: ApiInterfaceRx): (tokenSymbol: vToken) => Observable<BN> { return memo(instanceId, (tokenSymbol: vToken) => { const convertPriceQuery = getConvertPriceInfo(instanceId, api); // Query the convert price of current block const currentPrice$ = convertPriceQuery(tokenSymbol); // Query the convert price of the designated block const preBlockHashQuery = getDesignatedBlockHash(instanceId, api); const historicalPrice$ = preBlockHashQuery().pipe( mergeMap((preHash) => { // mergeMap operator is used to flatten the two levels of Observables into one. return convertPriceQuery(tokenSymbol, preHash); } ) ); // combine two Observables together, destruct the values we need, and do necessary calculations before returning the results. return combineLatest([ currentPrice$, historicalPrice$ ]).pipe( map(([currentPrice, historicalPrice]): BN => { let annualizedRate: BN; if (historicalPrice.toNumber() !== 0) { annualizedRate = currentPrice.sub(historicalPrice).div(historicalPrice).div(new BN(7)).mul(new BN(365)); } else { annualizedRate = new BN(0); } return annualizedRate; } ) ); } ); } /** * @name getAllAnnualizedRate * @description get all vToken Annualized Rate information * @param instanceId * @param api */ export function getAllAnnualizedRate (instanceId: string, api: ApiInterfaceRx): (vTokenArray?:vToken[]) => Observable<BN[]> { return memo(instanceId, (vTokenArray?:vToken[]) => { let vTokenList: vToken[]; if (vTokenArray === undefined) { vTokenList = ['vDOT', 'vKSM', 'vEOS']; } else { vTokenList = vTokenArray; } const getAnnualizedRateQuery = getAnnualizedRate(instanceId, api); return combineLatest(vTokenList.map((vtk) => getAnnualizedRateQuery(vtk))); }); } /** * @name getBatchConvertPrice * @description get the header information of current block * @param instanceId * @param api */ export function getBatchConvertPrice (instanceId: string, api: ApiInterfaceRx): (tokenSymbol: vToken, blockHashArray: Observable<BlockHash[]>) => Observable<BN[]> { return memo(instanceId, (tokenSymbol: vToken, blockHashArray: Observable<BlockHash[]>) => { const getConvertPriceInfoQuery = getConvertPriceInfo(instanceId, api); return blockHashArray.pipe(mergeMap((blockHashList) => { return combineLatest(blockHashList.map((blockHash) => { return getConvertPriceInfoQuery(tokenSymbol, blockHash); })); })); } ); } <file_sep>/packages/types/src/interfaces/definitions.ts // Copyright 2020 @bifrost-finance/types authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. export { default as primitives } from './primitives/definitions'; <file_sep>/packages/api-derive/src/util/getHeader.ts // Copyright 2020 @bifrost-finance/api-derive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { ApiInterfaceRx } from '@polkadot/api/types'; import { mergeMap, map } from 'rxjs/operators'; import { Observable, combineLatest } from 'rxjs'; import { memo } from './memo'; import { BlockHash } from '@polkadot/types/interfaces/chain'; import { Header } from '@polkadot/types/interfaces'; import { timestampListAndBlockHeightList, timestampListAndBlockHeight } from './types'; import BN from 'bn.js'; /** * @name getHeader * @description get the header information of current block * @param instanceId * @param api */ export function getHeader (instanceId: string, api: ApiInterfaceRx): () => Observable<Header> { return memo(instanceId, () => { return api.rpc.chain.getHeader(); } ); } /** * @name getDesignatedBlockHash * @description get the hash value fo the designated blocks back. If no blocks back number provide, SEVEN_DAY_BLOCK_NUM will be the default value. * @param instanceId * @param api */ export function getDesignatedBlockHash (instanceId: string, api: ApiInterfaceRx): (numBlockBack?: number) => Observable<BlockHash> { return memo(instanceId, (numBlockBack?: number) => { const BLOCK_INTERVAL = 6; // 6 seconds to generate a block const SEVEN_DAY_BLOCK_NUM = 7 * 24 * 60 * 60 / BLOCK_INTERVAL; const getHeaderQuery = getHeader(instanceId, api); let numBlockBackCount = 0; if (numBlockBack === undefined) { numBlockBackCount = SEVEN_DAY_BLOCK_NUM; // if no numBlockBack sent in, the default value for numBlockBack_count is SEVEN_DAY_BLOCK_NUM, which means we are querying the exact block seven days ago. } else { numBlockBackCount = numBlockBack; } const currentHeader = getHeaderQuery(); return currentHeader.pipe( mergeMap((result) => { return api.rpc.chain.getBlockHash(result.number.unwrap().subn(numBlockBackCount)); }) ); } ); } /** * @name getBatchBlockHash * @description get the header information of current block * @param instanceId * @param api */ export function getBatchBlockHash (instanceId: string, api: ApiInterfaceRx): (blockHeightList: BN[]) => Observable<BlockHash[]> { return memo(instanceId, (blockHeightList: BN[]) => { const getDesignatedBlockHashQuery = getDesignatedBlockHash(instanceId, api); return combineLatest(blockHeightList.map((blockHeight) => { return getDesignatedBlockHashQuery(blockHeight.toNumber()); })); }); } /** * @name calCurrentDateHourZeroBlockHeight * @description Calculate the block height of time 00:00:00 of current date. * @param instanceId * @param api * @param var date = new Date(2016, 6, 27, 13, 30, 0); */ export function calCurrentDateHourZeroBlockHeight (instanceId: string, api: ApiInterfaceRx): () => Observable<timestampListAndBlockHeight> { return memo(instanceId, () => { const BLOCK_INTERVAL = 6; // 6 seconds to generate a block const getHeaderQuery = getHeader(instanceId, api); const currentBlockNumber = getHeaderQuery().pipe( map((result) => { return result.number.unwrap(); })); const currentTime = new Date(); const currentTimestamp = currentTime.getTime(); const currentDateHourZero = currentTime; currentDateHourZero.setHours(0, 0, 0); const currentDateHourZeroTimestamp = currentDateHourZero.getTime(); const blockDifference = Math.floor((currentTimestamp - currentDateHourZeroTimestamp) / 1000 / BLOCK_INTERVAL); return currentBlockNumber.pipe( map((blockNum) => { return { blockHeight: blockNum.subn(blockDifference), timestamp: currentDateHourZeroTimestamp }; })); } ); } /** * @name generateBachBlockHeightList * @description According to the set rule, generate a list of block heights, ending time is time 00:00:00 of current date. * @param instanceId * @param api */ export function generateBachBlockHeightList (instanceId: string, api: ApiInterfaceRx): (intervalBlocks?: number, totalNumber?: number) => Observable<timestampListAndBlockHeightList> { return memo(instanceId, (intervalBlocks?: number, totalNumber?: number) => { const BLOCK_INTERVAL = 6; // 6 seconds to generate a block const ONE_DAY_BLOCKS = 60 * 60 * 24 / BLOCK_INTERVAL; const MILLISECONDS_PER_DAY = 1000 * 60 * 60 * 24; let interValBlockNum: number; let totalNum: number; const calCurrentDateHourZeroBlockHeightQuery = calCurrentDateHourZeroBlockHeight(instanceId, api); const zeroBlockInfo = calCurrentDateHourZeroBlockHeightQuery(); if (intervalBlocks === undefined) { interValBlockNum = ONE_DAY_BLOCKS; } else { interValBlockNum = intervalBlocks; } if (totalNumber === undefined) { totalNum = 30; } else { totalNum = totalNumber; } return zeroBlockInfo.pipe(map((result) => { const timestampList = []; const blockHeightList = []; let calTimestamp = result.timestamp; let calBlockHeight = result.blockHeight; for (let i = 0; i < totalNum; i++) { timestampList.push(calTimestamp); blockHeightList.push(calBlockHeight); calTimestamp = calTimestamp - MILLISECONDS_PER_DAY; calBlockHeight = calBlockHeight.subn(interValBlockNum); if (calBlockHeight.toNumber() < 0) { break; } } return { blockHeightList: blockHeightList, timestampList: timestampList }; })); } ); } <file_sep>/packages/api-derive/src/index.ts // Copyright 2020 @bifrost-finance/api-derive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import * as aggregated from './aggregated'; import * as assets from './assets'; import * as convert from './convert'; export const derive = { aggregated, assets, convert }; <file_sep>/packages/api-derive/src/assets/types.ts // Copyright 2020 @bifrost-finance/api-derive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { AccountId, Balance } from '@polkadot/types/interfaces/runtime'; import { AccountAsset } from '@bifrost-finance/types/interfaces'; import { allTokens } from '../type'; export interface DeriveVtokenAssetsInfo{ symbol: string, totalSupply: Balance } export interface assetInfo{ tokenName: allTokens, assetInfo: AccountAsset } export interface accountsAssetInfo{ accountName: AccountId, assetsInfo: assetInfo[] } <file_sep>/packages/api-derive/src/aggregated/getCEXTokenPrice.ts // Copyright 2020 @bifrost-finance/api-derive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { ApiInterfaceRx } from '@polkadot/api/types'; import { Observable, of } from 'rxjs'; import { memo } from '../util'; import { CEXName, CEXTokenPrice, symbolUSDValue } from '../util/types'; import { AccountId } from '@polkadot/types/interfaces/runtime'; import { Token } from '@bifrost-finance/types/interfaces'; import BN from 'bn.js'; /** * @name getBinancePrices * @description get token prices from Binance exchange * @param instanceId * @param api */ export function getBinancePrices (instanceId: string, api: ApiInterfaceRx): () => Observable<CEXTokenPrice[]> { return memo(instanceId, (): any => { return of([{ price: 2.584, symbol: 'EOSUSDT' }, { price: 10730.96, symbol: 'BTCUSDT' }, { price: 355.89, symbol: 'ETHUSDT' } ]); }); } /** * @name getCEXTokenPrices * @description get Token information * @param instanceId * @param api */ export function getCEXTokenPrices (instanceId: string, api: ApiInterfaceRx): (exchangeName?: CEXName) => Observable<CEXTokenPrice[]> { return memo(instanceId, (exchangeName?: CEXName):any => { const binanceQuery = () => { const getBinancePricesQuery = getBinancePrices(instanceId, api); return getBinancePricesQuery(); } switch (exchangeName) { case 'binance': binanceQuery; default: binanceQuery; } }); } /** * @name getAccountSingleTokenUSDValue * @description get Token information * @param instanceId * @param api */ export function getAccountSingleTokenUSDValue (instanceId: string, api: ApiInterfaceRx): (accountName: AccountId, tokenSymbol: Token, exchangeName?: CEXName) => Observable<symbolUSDValue> { return memo(instanceId, (accountName: AccountId, tokenSymbol: Token, exchangeName?: CEXName) => { // const getAccountAssetsQuery = getAccountAssets(instanceId, api); // getAccountAssetsQuery(); return of({ symbol: <unknown>'vEos' as Token, usdValue: 5 }); }); } /** * @name getAccountManyTokenUSDValues * @description get Token information * @param instanceId * @param api */ export function getAccountManyTokenUSDValues (instanceId: string, api: ApiInterfaceRx): (accountName: AccountId, tokenArray: Token[], exchangeName?: CEXName) => Observable<symbolUSDValue[]> { return memo(instanceId, (accountName: AccountId, tokenSymbol: Token, exchangeName?: CEXName) => { // const getAccountAssetsQuery = getAccountAssets(instanceId, api); // getAccountAssetsQuery(); const tokenValueArray = [ { symbol: <unknown>'vEos' as Token, usdValue: 5 }, { symbol: <unknown>'Dot' as Token, usdValue: 500.5 }, { symbol: <unknown>'vKSM' as Token, usdValue: 259 } ]; return of(tokenValueArray); }); } /** * @name getAccountTotalValue * @description get token prices from Binance exchange * @param instanceId * @param api */ export function getAccountTotalValue (instanceId: string, api: ApiInterfaceRx): (accountName: AccountId) => Observable<BN> { return memo(instanceId, (accountName: AccountId) => { // const getAccountManyTokenUSDValuesQuery = getAccountManyTokenUSDValues(instanceId, api); // const getAccountAssetsQuery = getAccountAssets(instanceId, api); return of(new BN(0)); }); } /** * @name getAccountIncomeValue * @description get token prices from Binance exchange * @param instanceId * @param api */ export function getAccountIncomeValue (instanceId: string, api: ApiInterfaceRx): (accountName: AccountId) => Observable<BN> { return memo(instanceId, (accountName: AccountId) => { // const getAllTokenPoolInfoQuery = getAllTokenPoolInfo(instanceId, api); return of(new BN(0)); }); } <file_sep>/packages/api-derive/src/aggregated/vtokenPool.ts // Copyright 2020 @bifrost-finance/api-derive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { DeriveVtokenPoolInfo } from '../type/index'; import { ApiInterfaceRx } from '@polkadot/api/types'; import { map, mergeMap } from 'rxjs/operators'; import { Observable, combineLatest, of } from 'rxjs'; import { vToken, timestampAndConvertPrice } from '../type'; import { getAllVtokenConvertInfo, getAllConvertPriceInfo, getAllAnnualizedRate, getBatchConvertPrice } from '../convert'; import { getAllTokenInfo } from '../assets'; import { memo, generateBachBlockHeightList, getBatchBlockHash } from '../util'; import BN from 'bn.js'; /** * @name getAllTokenPoolInfo * @description get all vToken aggregated pool information * @param instanceId * @param api */ export function getAllTokenPoolInfo (instanceId: string, api: ApiInterfaceRx): (vTokenArray?: vToken[]) => Observable<DeriveVtokenPoolInfo[]> { return memo(instanceId, (vTokenArray?: vToken[]) => { let vTokenList: vToken[]; if (vTokenArray === undefined) { vTokenList = ['vDOT', 'vKSM', 'vEOS']; } else { vTokenList = vTokenArray; } const getTokenInfoQuery = getAllTokenInfo(instanceId, api); const getAllVtokenConvertInfoQuery = getAllVtokenConvertInfo(instanceId, api); const getAllConvertPriceInfoQuery = getAllConvertPriceInfo(instanceId, api); const getAllAnnualizedRateQuery = getAllAnnualizedRate(instanceId, api); return combineLatest( [getTokenInfoQuery(vTokenList), getAllVtokenConvertInfoQuery(vTokenList), getAllConvertPriceInfoQuery(vTokenList), getAllAnnualizedRateQuery(vTokenList) ] ).pipe( map(([assetsInfo, convertInfo, convertPriceInfo, annualizedRateInfo]) => { return assetsInfo.map((vtk, i) => { return { annualizedRate: annualizedRateInfo[i], convertPrice: convertPriceInfo[i], symbol: vTokenList[i], tokenPool: convertInfo[i].token_pool, totalSupply: vtk.totalSupply }; }); }) ); }); } /** * @name getVtokneConvertPriceHistory * @description get the header information of current block * @param instanceId * @param api */ export function getVtokenConvertPriceHistory (instanceId: string, api: ApiInterfaceRx): (tokenSymbol: vToken, intervalBlocks?: number, totalHistoryBlockNumber?: number) => Observable<timestampAndConvertPrice> { return memo(instanceId, (tokenSymbol: vToken, intervalBlocks?: number, totalHistoryBlockNumber?: number) => { const generateBachBlockHeightListQuery = generateBachBlockHeightList(instanceId, api); const getBatchConvertPriceQuery = getBatchConvertPrice(instanceId, api); const getBatchBlockHashQuery = getBatchBlockHash(instanceId, api); const result = generateBachBlockHeightListQuery(intervalBlocks, totalHistoryBlockNumber); return result.pipe(mergeMap((resultSet) => { const timestampList = resultSet.timestampList; const blockHeightList = resultSet.blockHeightList; const blockHashArray = getBatchBlockHashQuery(blockHeightList); const convertPriceArray = getBatchConvertPriceQuery(tokenSymbol, blockHashArray); return convertPriceArray.pipe((map((convertPriceList) => { return { convertPriceList: convertPriceList, timestampList: timestampList }; }))); })) }); } /** * @name getVtokenMarketPriceValue * @description get vToken market Price * @param instanceId * @param api */ export function getVtokenMarketPriceValue (instanceId: string, api: ApiInterfaceRx): (tokenSymbol: vToken) => Observable<BN> { return memo(instanceId, ():any => { return of(new BN(0)); }); } /** * @name getVtokenConvertPriceValue * @description get vToken market Price * @param instanceId * @param api */ export function getVtokenConvertPriceValue (instanceId: string, api: ApiInterfaceRx): (tokenSymbol: vToken) => Observable<BN> { return memo(instanceId, ():any => { return of(new BN(0)); }); } /** * @name getVtokenPriceDiff * @description get the difference between current convert price and market price of vtoken. * @param instanceId * @param api */ export function getVtokenPriceDiff (instanceId: string, api: ApiInterfaceRx): (tokenSymbol: vToken) => Observable<BN> { return memo(instanceId, (tokenSymbol: vToken):any => { // const getVtokenMarketPriceQuery = getVtokenMarketPrice(instanceId, api); // const currentMarketPrice = getVtokenMarketPriceQuery(tokenSymbol); // const getConvertPriceInfoQuery = getConvertPriceInfo(instanceId, api); // const currentConvertPrice = getConvertPriceInfoQuery(tokenSymbol); // return combineLatest([currentMarketPrice, currentConvertPrice]).pipe((map(([marketPrice, convertPrice])=>{ // return convertPrice.sub(marketPrice); // }))) return of(new BN(0)); }); } <file_sep>/packages/api-derive/src/type/aggregatedTypes.ts // Copyright 2020 @bifrost-finance/api-derive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { DeriveVtokenAssetsInfo } from '../assets/types'; import { DeriveVtokenConvertInfo } from '../convert/types'; import BN from 'bn.js'; // interface that aggregates DeriveVtokenPoolInfo from asset types and DeriveVtokenConvertInfo from convert types export interface DeriveVtokenPoolInfo extends DeriveVtokenAssetsInfo, DeriveVtokenConvertInfo { // symbol: string, // totalSupply: Balance; // tokenPool: Balance; // convertPrice: BN; // annualizedRate: BN; } export type vToken = 'vDOT' | 'vKSM' | 'vEOS'; export type allTokens = 'vDOT' | 'vKSM' | 'vEOS'| 'DOT' | 'KSM' | 'EOS' | 'aUSD'; export interface timestampAndConvertPrice { timestampList: number[], convertPriceList: BN[] } <file_sep>/packages/api-derive/src/convert/types.ts // Copyright 2020 @bifrost-finance/api-derive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { Balance } from '@polkadot/types/interfaces/runtime'; import BN from 'bn.js'; export interface DeriveVtokenConvertInfo{ symbol: string, tokenPool: Balance; convertPrice: BN; annualizedRate: BN; } <file_sep>/packages/api-derive/src/assets/assets.ts // Copyright 2020 @bifrost-finance/api-derive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { ApiInterfaceRx } from '@polkadot/api/types'; import { map } from 'rxjs/operators'; import { Observable, combineLatest } from 'rxjs'; import { memo } from '../util'; import { allTokens } from '../type'; import { accountsAssetInfo, assetInfo } from './types'; import { AccountId } from '@polkadot/types/interfaces/runtime'; import { Token } from '@bifrost-finance/types/interfaces'; /** * @name getTokenInfo * @description get Token information * @param instanceId * @param api */ export function getTokenInfo (instanceId: string, api: ApiInterfaceRx): (tokenSymbol: allTokens) => Observable<Token> { return memo(instanceId, (tokenSymbol: allTokens) => { return api.query.assets.tokens(tokenSymbol).pipe( map((result: Token) => result) ); }); } /** * @name getAllTokenInfo * @description get all vToken information * @param instanceId * @param api */ export function getAllTokenInfo (instanceId: string, api: ApiInterfaceRx): (tokenArray?: allTokens[]) => Observable<Token[]> { return memo(instanceId, (tokenArray?: allTokens[]) => { let tokenList: allTokens[]; if (tokenArray === undefined) { tokenList = ['vDOT', 'vKSM', 'vEOS', 'DOT', 'KSM', 'EOS', 'aUSD']; } else { tokenList = tokenArray; } const getTokenInfoQuery = getTokenInfo(instanceId, api); return combineLatest(tokenList.map((tk) => getTokenInfoQuery(tk))); }); } /** * @name getSingleAccountAsset * @description get one account one asset Info * @param instanceId * @param api */ export function getSingleAccountAsset (instanceId: string, api: ApiInterfaceRx): (accountName: AccountId, tokenSymbol: allTokens) => Observable<assetInfo> { return memo(instanceId, (accountName: AccountId, tokenSymbol: allTokens) => { const result = api.query.assets.accountAssets([tokenSymbol, accountName]); return result.pipe(map((result) => { return { assetInfo: result, tokenName: tokenSymbol }; })); }); } /** * @name getAccountAssets * @description get one account all token Assets Info * @param instanceId * @param api */ export function getAccountAssets (instanceId: string, api: ApiInterfaceRx): (accountName: AccountId, tokenArray?: allTokens[]) => Observable<accountsAssetInfo> { return memo(instanceId, (accountName: AccountId, tokenArray?: allTokens[]) => { let tokenList: allTokens[]; if (tokenArray === undefined) { tokenList = ['vDOT', 'vKSM', 'vEOS', 'DOT', 'KSM', 'EOS', 'aUSD']; } else { tokenList = tokenArray; } const getSingleAccountAssetQuery = getSingleAccountAsset(instanceId, api); const result = combineLatest(tokenList.map((tk) => getSingleAccountAssetQuery(accountName, tk))); return result.pipe(map((result) => { return { accountName: accountName, assetsInfo: result }; })); }); } /** * @name getManyAccountsAssets * @description get many account all token Assets Info * @param instanceId * @param api */ export function getManyAccountsAssets (instanceId: string, api: ApiInterfaceRx): (accountNameArray: AccountId[], tokenArray?: allTokens[]) => Observable<accountsAssetInfo[]> { return memo(instanceId, (accountNameArray: AccountId[], tokenArray?: allTokens[]) => { let tokenList: allTokens[]; if (tokenArray === undefined) { tokenList = ['vDOT', 'vKSM', 'vEOS', 'DOT', 'KSM', 'EOS', 'aUSD']; } else { tokenList = tokenArray; } const getAccountAssetsQuery = getAccountAssets(instanceId, api); return combineLatest(accountNameArray.map((accountName) => getAccountAssetsQuery(accountName, tokenList))); }); }
7a4abd5463404e735960f0e0929ea3d4251096f7
[ "TypeScript" ]
12
TypeScript
hsqlu/bifrost.js
a4ae5118be235167d462264e4a0499f52689dad7
b985a3aac6c1914e3b3c9e742c5cec5f0da35bcc
refs/heads/master
<repo_name>H4XOR98/SRCR-Componente_Individual<file_sep>/XlsParser/src/Freguesia.java public class Freguesia { private int id; private String nome; private static int ID = 0; public Freguesia(String nome) { this.id = ID++; this.nome = nome; } public int getId() { return id; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("freguesia( " + id + ", '" + this.nome + "' ).\n"); return sb.toString(); } } <file_sep>/XlsParser/src/Ponto.java public class Ponto { private double latitude; private double longitude; public Ponto(double latitude, double longitude) { this.latitude = latitude; this.longitude = longitude; } public double getLatitude() { return latitude; } public double getLongitude() { return longitude; } public double distanciaEuclidiana(Ponto ponto){ return Math.sqrt(Math.pow((this.latitude - ponto.getLatitude()),2) + Math.pow(this.longitude - ponto.getLongitude(),2)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.latitude + ", " + this.longitude); return sb.toString(); } }<file_sep>/XlsParser/src/Carreira.java import java.util.ArrayList; import java.util.List; public class Carreira { private int id; private List<Paragem> percurso; private List<Adjacente> adjacentes; public Carreira(int id) { this.id = id; this.percurso = new ArrayList<>(); this.adjacentes = new ArrayList<>(); } public void addParagem(Paragem paragem){ if(!percurso.contains(paragem)) { this.addAdjacente(paragem); this.percurso.add(paragem); } } private void addAdjacente(Paragem paragem){ if(this.percurso.size() > 0) { Paragem paragemAnterior = this.percurso.get(this.percurso.size() - 1); this.adjacentes.add(new Adjacente(this.id, paragemAnterior.getGid(), paragem.getGid(), paragemAnterior.getLocalizacao(), paragem.getLocalizacao())); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); for(Adjacente adjacente : this.adjacentes){ sb.append(adjacente.toString() + "\n"); } return sb.toString(); } } <file_sep>/XlsParser/src/Paragem.java import java.util.ArrayList; import java.util.List; import java.util.Objects; public class Paragem { private int gid; private Ponto localizacao; private String estado; private String tipo; private String publicidade; private List<Integer> carreiras; private Operadora operadora; private Rua rua; public Paragem(int gid, double latitude, double longitude, String estado, String tipo, String publicidade, Operadora operadora, Rua rua) { this.gid = gid; this.localizacao = new Ponto(latitude,longitude); this.estado = estado; this.tipo = tipo; this.carreiras = new ArrayList<>(); this.publicidade = publicidade; this.operadora = operadora; this.rua = rua; } public Ponto getLocalizacao() { return localizacao; } public void addCarreira(int carreira){ this.carreiras.add(carreira); } public int getGid() { return gid; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || this.getClass() != o.getClass()) return false; Paragem paragem = (Paragem) o; return this.gid == paragem.gid; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("paragem( " + this.gid + ", " + this.localizacao.toString() + ", '" + this.estado + "', '" + this.tipo + "', '" + this.publicidade + "', [ "); for(int i = 0; i < this.carreiras.size() ; i++){ sb.append(this.carreiras.get(i)); if(i != this.carreiras.size()-1){ sb.append(", "); } } sb.append(" ], " + this.operadora.getId() + ", " + this.rua.getCodigo() + " )."); return sb.toString().replaceAll("\n","")+"\n"; } }<file_sep>/README.md # SRCR-Componente_Individual Sistema de Transportes do Concelho de Oeiras <file_sep>/XlsParser/src/Adjacente.java public class Adjacente { private int idCarreira; private int gidOrigem; private int gidDestino; private double distancia; public Adjacente(int idCarreira, int gidOrigem, int gidDestino, Ponto origem, Ponto destino) { this.idCarreira = idCarreira; this.gidOrigem = gidOrigem; this.gidDestino = gidDestino; this.distancia = origem.distanciaEuclidiana(destino); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("adjacente( " + this.gidOrigem + ", " + this.gidDestino + ", " + this.idCarreira + ", " + String.valueOf(this.distancia).replaceAll(",",".") + " )."); return sb.toString(); } }
ae9c286b034ca6943f571b51e72f6d3d27d5aff2
[ "Markdown", "Java" ]
6
Java
H4XOR98/SRCR-Componente_Individual
6224d66b1cfabc3182d085dac8d1c60d7c198046
7279b88b83536d67a0211cebc7e2ee2a4336b562
refs/heads/master
<repo_name>parksence/WebProject<file_sep>/src/util/Gmail.java package util; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class Gmail extends Authenticator { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("<EMAIL>", "<PASSWORD>!"); } }
2c74310086847b6b6b8e12e3c1de1e68da9775c3
[ "Java" ]
1
Java
parksence/WebProject
29b6992162a1e0b4566399cb664590f85c1eb659
700cd94a8bfdd467806279812c55303645383482
refs/heads/main
<file_sep>class GossipController < ApplicationController def index #methode page welcome end def show #methode page pour montrer les gossips @this_gossip = Gossip.find(params[:id]) @author_id = Gossip.find(params[:id]).author_id @author_name = Author.find(Gossip.find(params[:id]).author_id).first_name @author_city = City.find(@this_gossip.author.city_id).name end def new #methode page pour montrer les gossips @gossip = Gossip.new #@comment = Comment.new(gossip_id: params[:gossip_id]) end def create @gossip = Gossip.new(title: params["title"], content: params["content"], author_id: Author.all.sample.id, date: Faker::Time.forward) # avec xxx qui sont les données obtenues à partir du formulaire # @gossip.author = Author.find_by(id: session[:user_id]) if @gossip.save # essaie de sauvegarder en base @gossip # si ça marche, il redirige vers la page d'index du site flash[:notice] = 'Successfully entered the Gossip !' redirect_to "/" else # sinon, il render la view new (qui est celle sur laquelle on est déjà) render "/gossip/new" end end def edit @gossip = Gossip.find(params[:id]) end def update @gossip = Gossip.find(params[:id]) gossip_params = params.require(:gossip).permit(:title, :content) @gossip.update(gossip_params) flash[:notice] = 'Successfully edited the Gossip !' redirect_to gossip_path end def destroy @gossip = Gossip.find(params[:id]) @gossip.destroy flash[:notice] = 'Successfully deleted the Gossip !' redirect_to root_path end private end<file_sep> require'faker' Author.destroy_all Gossip.destroy_all City.destroy_all #crée la base de données 5.times do City.create(name: Faker::Nation.capital_city, zip_code: Faker::Address.zip_code, ) end 5.times do Author.create(first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, age: Faker::Number.number(digits: 2), description: Faker::Lorem.sentences(number: 1), city_id: City.all.sample.id, ) end 5.times do Gossip.create( title:Faker::House.furniture, content:Faker::ChuckNorris.fact, date: Faker::Time.forward, author_id: Author.all.sample.id, ) end<file_sep> Versions rails: 5.2.3!!! Voici notre site de gossip dans sa version beta ! Il contient un page cachée :o ...et des pages pas cachées avec plein de potins ! La capacité incroyable de voir qui a ecrit ces potins ! :o La date de leur creation ! ... et bien d'autres features plus incroyables les unes que les autres ! ... Que faire en ouvrant le dossier? 1- $bundle install 2- $rails db:migrate 3- $rails db:seed 4- $rails server 5- tapper l'adresse : " localhost:3000 " sur votre navigateur préféré :) Enjoy!! <file_sep>Rails.application.routes.draw do resources :sessions, only: [:new, :create, :destroy] resources :gossip resources :author resources :city # definit tous les chemins root to: 'gossip#index' get 'team', to: 'static#team' get 'contact', to: 'static#contact' get '/welcome/:id', to: 'static#hidden' end <file_sep> class SessionsController < ApplicationController def new @author = Author.new end def create current_author = Author.find_by(email: params[:email]) # on vérifie si l'utilisateur existe bien ET si on arrive à l'authentifier (méthode bcrypt) avec le mot de passe if current_author && current_author.authenticate(params[:password]) session[:author_id] = current_author.id # redirige où tu veux, avec un flash ou pas flash.now[:danger] = 'ya qqch qui saffiche' redirect_to root_path else flash.now[:danger] = 'Invalid email/password combination' render :new end end def destroy session.delete(:author_id) end end<file_sep>class Author < ApplicationRecord # validates :password_digest, # presence: true, # length:{ in:6..15} has_secure_password belongs_to :city has_many :gossips #has_many :comments end <file_sep>class CityController < ApplicationController def show @this_city = City.find(params[:id]) end end<file_sep>module SessionHelper def current_user Author.find_by(id: session[:author_id]) end end<file_sep>class AuthorController < ApplicationController def author #methode page pour montrer les auteurs end def new @author = Author.new end def create @author = Author.new(first_name: params[:firstname], last_name: params[:lastname], email: params[:email], age: Faker::Number.number(digits: 2), description: Faker::Lorem.sentences(number: 1), city_id: City.all.sample.id, password: params[:password]) @author.save redirect_to "/" end def show #methode page pour montrer les gossips @this_author = Author.find(params[:id]) end end<file_sep>class Gossip < ApplicationRecord validates :title, presence: true, length:{ in:3..14} validates :content, presence: true validates :date, presence: true belongs_to :author #has_many :comments end <file_sep>class StaticController < ApplicationController def team #methode page team end def contact #methode page contact end def hidden #methode page cachée @user = params[:id] end end
80feec1dc8d51f07801d2b90ead9be51dacb4fc5
[ "Markdown", "Ruby" ]
11
Ruby
MatteoTHP/TGP_Matteo_Facebook
79c2aca7d487604071f2b5ce0f6837c555b8b7cb
e59e35f58b71300affa132a345226293acaa61b3
refs/heads/main
<file_sep>#ifndef POS_KERN_PANIC_H #define POS_KERN_PANIC_H void _panic(const char *file, int line, const char *fmt,...); void _warn(const char *file, int line, const char *fmt,...); #endif<file_sep>#ifndef POS_INC_MMU_H #define POS_INC_MMU_H #define PTE_P 0x001 // Present #define PTE_W 0x002 // Writeable #define PTE_U 0x004 // User // Page directory and page table constants. #define NPDENTRIES 1024 // page directory entries per page directory #define NPTENTRIES 1024 // page table entries per page table #define PGSIZE 4096 // bytes mapped by a page #define PGSHIFT 12 // log2(PGSIZE) #define PTSIZE (PGSIZE*NPTENTRIES) // bytes mapped by a page directory entry #define PTXSHIFT 12 // offset of PTX in a linear address #define PDXSHIFT 22 // offset of PDX in a linear address // Control Register flags #define CR0_PE 0x00000001 // Protection Enable #define CR0_MP 0x00000002 // Monitor coProcessor #define CR0_EM 0x00000004 // Emulation #define CR0_TS 0x00000008 // Task Switched #define CR0_NE 0x00000020 // Numeric Errror #define CR0_WP 0x00010000 // Write Protect #define CR0_AM 0x00040000 // Alignment Mask #define CR0_PG 0x80000000 // Paging // Application segment type bits #define STA_X 0x8 // Executable segment #define STA_W 0x2 // Writeable (non-executable segments) #define STA_R 0x2 // Readable (executable segments) #ifdef __ASSEMBLER__ /* * Macros to build GDT entries in assembly. */ #define SEG_NULL \ .word 0, 0; \ .byte 0, 0, 0, 0 #define SEG(type,base,lim) \ .word (((lim) >> 12) & 0xffff), ((base) & 0xffff); \ .byte (((base) >> 16) & 0xff), (0x90 | (type)), \ (0xC0 | (((lim) >> 28) & 0xf)), (((base) >> 24) & 0xff) #endif // not __ASSEMBLER__ // page number field of address #define PGNUM(la) (((uintptr_t) (la)) >> PTXSHIFT) // page directory index #define PDX(la) ((((uintptr_t) (la)) >> PDXSHIFT) & 0x3FF) // page table index #define PTX(la) ((((uintptr_t) (la)) >> PTXSHIFT) & 0x3FF) // offset in page #define PGOFF(la) (((uintptr_t) (la)) & 0xFFF) // construct linear address from indexes and offset #define PGADDR(d, t, o) ((void*) ((d) << PDXSHIFT | (t) << PTXSHIFT | (o))) // Address in page table or page directory entry #define PTE_ADDR(pte) ((physaddr_t) (pte) & ~0xFFF) #endif /* !POS_INC_MEMLAYOUT_H */
d12bd13b77d416084387c0172f7d592bbcf92f32
[ "C" ]
2
C
czm048000/pos-2
aba5d171948473a1c6b2a5f9d0e5217b184bcec8
5744b9766ffea350c65a603c71b2194de2e66d39
refs/heads/master
<repo_name>M-Elsaeed/SoleekTable<file_sep>/src/app/home/home.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, FormBuilder } from '@angular/forms' import { ProductsService } from '../products.service' import { CommonModule } from '@angular/common' @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { showItemModally = false; searchForm = this.formBuilder.group({ sku: [''], name: [''] }); /** * Resets the form to its initial state. */ resetForm() { this.searchForm = this.formBuilder.group({ sku: [''], name: [''] }); } /** * Prompts modal component to show the selected product. * @param product Product to be modally Shown. */ showProductModal(product) { this.prodService.shownProduct.showModal = true; this.prodService.shownProduct.isSpecific = true; this.prodService.shownProduct.product = product; } constructor(private formBuilder: FormBuilder, public prodService: ProductsService) { } ngOnInit() { } } <file_sep>/src/services/app.route.ts import { ModuleWithProviders } from '@angular/core' import { Routes, RouterModule } from '@angular/router' /** * @Components */ import { HomeComponent } from '../app/home/home.component'; import { AddingComponent } from '../app/adding/adding.component'; import { EditComponent } from 'src/app/edit/edit.component'; /** * Routes */ const routes: Routes = [ { path: '', redirectTo: 'Home', pathMatch: 'full' }, { path: 'Home', component: HomeComponent }, { path: 'Add', component: AddingComponent }, { path: 'Edit', component: EditComponent }, { path: 'Edit/:Delete', component: EditComponent }, { path: "**", redirectTo: "/Home" } ]; /** * Router Module Configuration */ export const router: ModuleWithProviders = RouterModule.forRoot(routes); <file_sep>/src/app/edit/edit.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { ProductsService } from '../products.service'; import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms' @Component({ selector: 'app-edit', templateUrl: './edit.component.html', styleUrls: ['./edit.component.css'] }) export class EditComponent implements OnInit { displayedProduct = undefined;// Product To Be Displayed deletionMode = false;// State Boolean editingForm: FormGroup; // Form Binding /** * Analyzes Query and URL Parameters and sets state booleans accordingly. */ fetchProduct() { this.activatedRoute.params.subscribe(routeParams => { if (routeParams == undefined) { this.deletionMode = false; } else if (String(routeParams.Delete).toLowerCase() == "delete") { this.deletionMode = true; } else { this.deletionMode = false; } } ); this.activatedRoute.queryParams.subscribe(params => { console.log(params) let productSKU = undefined; productSKU = params['sku']; if (productSKU != undefined) this.displayedProduct = this.prodService.findProductSKU(productSKU); if (this.displayedProduct != undefined) { this.displayedProduct = this.displayedProduct[0]; } } ); } objKeys(obj) { return Object.keys(obj); } /** * Submits the Form to the Products Service to allow editing of an existing Product. */ onSubmit() { console.log('submitted') if (this.editingForm.valid) { let controlVals = this.editingForm.controls; let newProd = { sku: this.displayedProduct.sku, name: controlVals.name.value, image: controlVals.image.value == "" ? "https://dummyimage.com/600x400/000/fff.png" : controlVals.image.value, categories: controlVals.categories.value.split(","), price: controlVals.price.value, day: controlVals.day.value, month: controlVals.month.value, year: controlVals.year.value, }; console.log(newProd); this.prodService.editProduct(this.displayedProduct, newProd); this.prodService.shownProduct.isSpecific = true; this.prodService.shownProduct.product = newProd; this.prodService.shownProduct.showModal = true; this.prodService.shownProduct.isEdited = true; this.fetchProduct(); } else { console.log(this.editingForm.controls); console.log("invalid form"); } } /** * Resets to provided model */ reset() { this.editingForm.reset({ sku: this.displayedProduct.sku, name: this.displayedProduct.name, image: this.displayedProduct.image, categories: String(this.displayedProduct.categories), price: this.displayedProduct.price, day: this.displayedProduct.day, month: this.displayedProduct.month, year: this.displayedProduct.year, }); } /** * Returns a Form Group with the required Validators */ createFormGroupWithBuilder() { return this.formBuilder.group({ sku: [], name: ["", Validators.compose([Validators.minLength(3), Validators.required])], image: ["", Validators.compose([Validators.minLength(3), Validators.pattern(/(https?:\/\/.*\.(?:png|jpg|gif))/i)])], categories: ["", Validators.compose([Validators.minLength(3), Validators.required])], price: ["", Validators.compose([Validators.required])], day: ["", Validators.compose([Validators.required, Validators.min(1), Validators.max(31)])], month: ["", Validators.required], year: ["", Validators.compose([Validators.required, Validators.min(new Date().getFullYear()), Validators.max(2100)])], }); } constructor(private activatedRoute: ActivatedRoute, public prodService: ProductsService, private formBuilder: FormBuilder) { this.editingForm = this.createFormGroupWithBuilder() } ngOnInit() { this.prodService.shownProduct.showModal = false; this.fetchProduct(); this.reset(); } } <file_sep>/src/app/adding/adding.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms' import { ProductsService } from '../products.service' @Component({ selector: 'app-adding', templateUrl: './adding.component.html', styleUrls: ['./adding.component.css'] }) export class AddingComponent implements OnInit { addingForm: FormGroup; /** * Returns an array of Keys....For Use in Templates as Object is not recognized there. * @param obj Object Whose Keys are to be obtained. */ objKeys(obj) { return Object.keys(obj); } /** * Submits the Form to the Products Service to allow adding the newly created product. */ onSubmit() { if (this.addingForm.valid) { let controlVals = this.addingForm.controls; console.log(controlVals.sku.value, controlVals.name.value, controlVals.image.value, controlVals.categories.value.split(","), controlVals.price.value, controlVals.day.value, controlVals.month.value, controlVals.year.value); let newProd = { sku: controlVals.sku.value, name: controlVals.name.value, image: controlVals.image.value == "" ? "https://dummyimage.com/600x400/000/fff" : controlVals.image.value, categories: controlVals.categories.value.split(","), price: controlVals.price.value, day: controlVals.day.value, month: controlVals.month.value, year: controlVals.year.value, }; console.log(newProd); this.prodService.addNewProduct(newProd); this.prodService.shownProduct.isSpecific = false; this.prodService.shownProduct.product = newProd; this.prodService.shownProduct.showModal = true; this.reset(); } else { console.log(this.addingForm.controls); console.log("invalid form"); } } /** * Resets to provided model. */ reset() { this.addingForm.reset(this.addingForm = this.createFormGroupWithBuilder()); } /** * Returns a Form Group with the required Validators */ createFormGroupWithBuilder() { return this.formBuilder.group({ sku: ["", Validators.compose([Validators.minLength(5), Validators.required])], name: ["", Validators.compose([Validators.minLength(3), Validators.required])], image: ["", Validators.compose([Validators.minLength(3), Validators.pattern(/(https?:\/\/.*\.(?:png|jpg|gif))/i)])], categories: ["", Validators.compose([Validators.minLength(3), Validators.required])], price: ["", Validators.compose([Validators.required])], day: ["", Validators.compose([Validators.required, Validators.min(1), Validators.max(31)])], month: ["", Validators.compose([Validators.required, Validators.min(1), Validators.max(12)])], year: ["", Validators.compose([Validators.required, Validators.min(new Date().getFullYear()), Validators.max(2100)])], }); } constructor(private formBuilder: FormBuilder, public prodService: ProductsService) { } ngOnInit() { this.addingForm = this.createFormGroupWithBuilder(); } } <file_sep>/src/app/navbar/navbar.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '../../../node_modules/@angular/router'; import { Location } from '@angular/common'; @Component({ selector: 'app-navbar', templateUrl: './navbar.component.html', styleUrls: ['./navbar.component.css'] }) export class NavbarComponent implements OnInit { // boolean defining if the navbar is open or cloased. active = false; constructor(private router: Router, private location: Location) { } /** * ONLY IF the orientation mandates a side navbar to top navbar transformation, Reload. */ reloadComponent() { if (window.innerWidth > 1200 && window.innerHeight <= 1200 || window.innerWidth <= 1200 && window.innerHeight > 1200) location.reload(); } ngOnInit() { //Registering a listener for orientation change. window.addEventListener("orientationchange", this.reloadComponent, false); } /** * * @param navBar The navBar element which is binded in the template to #main. * * This function toggles the animation responsible for hiding and showing of the navbar * as a whole and also of the text content of the navbar. */ toggleNav(navBar,content) { console.log(this.active); if (!this.active) { this.active = true; navBar.style.animation = 'none'; navBar.offsetHeight; /* trigger reflow */ content.style.animation = 'none'; content.offsetHeight; /* trigger reflow */ content.style.animation = 'fadeIn 1s ease 0s 1 normal forwards running'; if (window.innerWidth <= 1200) { navBar.style.animation = 'fadeInDown 1s ease 0s 1 normal forwards running'; } else { navBar.style.animation = 'fadeInLeft 1s ease 0s 1 normal forwards running'; } } else { this.active = false; navBar.style.animation = 'none'; navBar.offsetHeight; /* trigger reflow */ content.style.animation = 'none'; content.offsetHeight; /* trigger reflow */ content.style.animation = 'fadeOut 1s ease 0s 1 normal forwards running'; if (window.innerWidth <= 1200) { navBar.style.animation = 'retreatUp-nav 1s ease 0s 1 normal forwards running'; } else { navBar.style.animation = 'retreat-nav 1s ease 0s 1 normal forwards running'; } } } } <file_sep>/src/app/products.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ProductsService { /** * Some Mock Products. */ private productsList: any = [{ sku: "123456", name: "potatoes", image: "https://food.fnr.sndimg.com/content/dam/images/food/fullset/2003/9/29/0/ig1a07_roasted_potatoes.jpg.rend.hgtvcom.826.620.suffix/1446840363593.jpeg", categories: ["Food", "Vegetables"], price: 32, day: 4, month: 9, year: 2020 }, { "sku": "783-90-6277", "name": "<NAME> Full Lid", "image": "http://dummyimage.com/136x240.bmp/cc0000/ffffff.png", "categories": ["Comedy"], "price": "4872.29", "day": 1, "month": 8, "year": 2031 }, { "sku": "729-89-4217", "name": "Beer - <NAME>, Pale Ale", "image": "http://dummyimage.com/168x141.jpg/dddddd/000000.png", "categories": ["Action", "Crime", "Drama", "Thriller"], "price": "9812.24", "day": 30, "month": 9, "year": 2034 }, { "sku": "408-60-1346", "name": "Beer - Maudite", "image": "http://dummyimage.com/241x155.png/cc0000/ffffff.png", "categories": ["Documentary"], "price": "3015.24", "day": 16, "month": 6, "year": 2079 }, { "sku": "857-98-8881", "name": "Bread - Raisin Walnut Oval", "image": "http://dummyimage.com/131x201.bmp/ff4444/ffffff.png", "categories": ["Drama", "Sci-Fi", "War"], "price": "6970.54", "day": 4, "month": 6, "year": 2041 }, { "sku": "320-67-4023", "name": "Juice - Apple, 1.36l", "image": "http://dummyimage.com/208x233.jpg/5fa2dd/ffffff.png", "categories": ["Drama", "Romance"], "price": "6406.57", "day": 20, "month": 4, "year": 2054 }, { "sku": "888-13-9281", "name": "Pepper - Chilli Seeds Mild", "image": "http://dummyimage.com/199x210.jpg/cc0000/ffffff.png", "categories": ["Documentary"], "price": "9559.27", "day": 27, "month": 2, "year": 2088 }, { "sku": "713-42-1166", "name": "Soup - Knorr, Chicken Gumbo", "image": "http://dummyimage.com/176x209.png/5fa2dd/ffffff.png", "categories": ["Horror"], "price": "9681.60", "day": 27, "month": 9, "year": 2067 }, { "sku": "543-86-9798", "name": "Wine - <NAME>", "image": "http://dummyimage.com/210x150.bmp/cc0000/ffffff.png", "categories": ["Drama"], "price": "8769.70", "day": 5, "month": 3, "year": 2078 }, { "sku": "496-16-3407", "name": "Turnip - Mini", "image": "http://dummyimage.com/147x141.bmp/cc0000/ffffff.png", "categories": ["Action", "Comedy"], "price": "1944.69", "day": 7, "month": 2, "year": 2081 }, { "sku": "436-24-2084", "name": "Lamb - Leg, Bone In", "image": "http://dummyimage.com/221x221.jpg/5fa2dd/ffffff.png", "categories": ["Action", "Comedy", "Drama"], "price": "5912.53", "day": 24, "month": 12, "year": 2074 }, { "sku": "391-69-6234", "name": "Scallops 60/80 Iqf", "image": "http://dummyimage.com/196x110.bmp/5fa2dd/ffffff.png", "categories": ["Crime", "Drama", "Thriller"], "price": "786.29", "day": 10, "month": 2, "year": 2039 }, { "sku": "262-06-5100", "name": "Mushroom - Morels, Dry", "image": "http://dummyimage.com/146x149.jpg/5fa2dd/ffffff.png", "categories": ["Action", "Drama", "Thriller"], "price": "7885.58", "day": 23, "month": 11, "year": 2019 }, { "sku": "614-36-4132", "name": "Bread - <NAME>", "image": "http://dummyimage.com/247x249.png/dddddd/000000.png", "categories": ["Animation", "Children", "Drama"], "price": "5131.74", "day": 11, "month": 7, "year": 2030 }, { "sku": "725-84-2019", "name": "Soup - Knorr, Veg / Beef", "image": "http://dummyimage.com/173x104.jpg/5fa2dd/ffffff.png", "categories": ["Children", "Drama", "Fantasy", "Mystery", "Thriller"], "price": "7540.83", "day": 4, "month": 11, "year": 2091 }, { "sku": "258-20-7811", "name": "Soup - Beef Conomme, Dry", "image": "http://dummyimage.com/227x229.jpg/5fa2dd/ffffff.png", "categories": ["Drama"], "price": "6042.89", "day": 8, "month": 6, "year": 2062 }, { "sku": "882-75-6786", "name": "Oyster - In Shell", "image": "http://dummyimage.com/141x181.bmp/dddddd/000000.png", "categories": ["Crime", "Drama"], "price": "388.74", "day": 3, "month": 12, "year": 2038 }, { "sku": "862-41-2965", "name": "Plasticknivesblack", "image": "http://dummyimage.com/117x140.jpg/ff4444/ffffff.png", "categories": ["Action", "Comedy", "Drama"], "price": "3584.53", "day": 27, "month": 5, "year": 2035 }, { "sku": "549-06-2801", "name": "Soup - Camp<NAME>", "image": "http://dummyimage.com/103x247.jpg/dddddd/000000.png", "categories": ["Comedy"], "price": "4157.94", "day": 1, "month": 10, "year": 2044 }, { "sku": "196-72-6781", "name": "Soda Water - Club Soda, 355 Ml", "image": "http://dummyimage.com/169x136.bmp/dddddd/000000.png", "categories": ["Comedy", "Drama", "Horror"], "price": "2286.25", "day": 23, "month": 3, "year": 2066 }, { "sku": "578-14-0647", "name": "Sugar - Brown", "image": "http://dummyimage.com/227x228.jpg/dddddd/000000.png", "categories": ["Crime", "Drama"], "price": "92.12", "day": 28, "month": 11, "year": 2098 }]; /** * Status For Modal Component Entry/Exit/Data. */ shownProduct = { showModal: false, isSpecific: false, isEdited: false, product: undefined }; /** * A string [] comparator function. * @param arr1 first string array to be compared * @param arr2 second string array to be compared */ private compareArr(arr1: string, arr2: string) { if (!arr1 || !arr2) return false; if (!(arr1.length === arr2.length)) return false; for (let i = 0; i < arr1.length; i++) { if (arr1[i].toLowerCase() != arr2[i].toLowerCase()) return false; } return true; } /** * A Function returning the index of the passed product in the produtsList array; Returns -1 if it is not Found. * @param prod Product to be compared */ private indexFinder(prod) { return this.productsList.findIndex( (element: any) => { if (element.sku.toLowerCase() === prod.sku.toLowerCase() && element.name.toLowerCase() === prod.name.toLowerCase() && element.image.toLowerCase() === prod.image.toLowerCase() && this.compareArr(element.categories, prod.categories) && element.price === prod.price && element.day === prod.day && element.month === prod.month && element.year === prod.year) return true; }); } /** * Adds the passed product to the productsList. * @param newProduct New Product to be added to the productsList []. */ addNewProduct(newProduct): void { this.productsList.push(newProduct); } /** * Returns an [] containing the products whose SKU is or contains part of the productSKU. * @param productSKU SKU of the product to be found. */ findProductSKU(productSKU) { if (productSKU == undefined) return this.productsList; let list = []; this.productsList.forEach(element => { if (element.sku.toLowerCase().includes(productSKU.toLowerCase())) list.push(element); }); if (list.length > 0) return list; else return undefined; } /** * Returns an [] containing the products whose name is or contains part of the productName. * @param productName Name of the product(s) to be found. */ findProductName(productName) { if (productName == null || productName == undefined || productName == "") return this.productsList; let list = []; this.productsList.forEach(element => { if (element.name.toLowerCase().includes(productName.toLowerCase())) list.push(element); }); console.log(list); if (list.length > 0) return list; else return undefined; } /** * Removes the passed product (product Object) from the productsList []. * @param product Product to be removed from the productsList [] */ removeProduct(product): boolean { let ind = this.indexFinder(product); if (ind >= 0) { this.productsList.splice(ind, 1); return true; } else return false; } /** * Edits the passed product (product Object) in the productsList []. * @param product Product to be edited in the productsList [] */ editProduct(product, editedProduct): boolean { let ind = this.indexFinder(product); if (ind >= 0) { this.productsList[ind] = editedProduct; return true; } return false; } /** * Returns the Last product added to producList [] or the specified prdouct in the shownProduct Object. */ getProductToDisplay() { if (this.shownProduct.isSpecific) { return this.shownProduct.product; } else { return this.productsList[this.productsList.length - 1]; } } constructor() { } }<file_sep>/src/app/modal/modal.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router' import { ProductsService } from 'D:/SoleekTable/src/app/products.service'; @Component({ selector: 'app-modal', templateUrl: './modal.component.html', styleUrls: ['./modal.component.css'] }) export class ModalComponent implements OnInit { displayedProduct = this.prodService.getProductToDisplay(); constructor(public prodService: ProductsService, public router: Router) { } ngOnInit() { } /** * This Function allows smooth exit of the Component. * @param htmlStructure This is the main div Container. */ destructMe(htmlStructure) { htmlStructure.className = 'main-container'; this.resetAnimation(htmlStructure); setTimeout(() => { this.prodService.shownProduct = { showModal: false, isSpecific: false, isEdited:false, product: undefined }; }, 1000); } /** * Resets the animation of an HTML element * @param element The element whoose animaiton will be reset */ resetAnimation(element) { element.style.animation = 'none'; element.offsetHeight; /* trigger reflow */ element.style.animation = 'fadeOutRight 1s ease 0s 1 normal forwards running'; } }
c69bddc69974c3b5b739b9295e800ca2f07d2028
[ "TypeScript" ]
7
TypeScript
M-Elsaeed/SoleekTable
3769944c79d22c2a22df61d69d8c2e344b1a935c
0a1481f94b19cdafb3eb9663201f9034aec59c9d
refs/heads/master
<file_sep>import java.util.Scanner; public class RetiroDeposito extends Interfaz { private int monto, saldo; public RetiroDeposito() { Atm atm = new Atm(); saldo = atm.saldototal; setEfectivo(saldo); } @Override public void makeOperation() { saldo = getEfectivo(); if(opcion == 2) { Scanner entry = new Scanner(System.in); Atm atm = new Atm(); System.out.print("\nMonto a retirar: "); monto = entry.nextInt(); atm.saldototal -= monto; System.out.println("\n-----------------------"); System.out.println("Retirado: " + monto); System.out.println("Su saldo actual es: " + atm.saldototal); System.out.println("-----------------------"); setEfectivo(saldo); Bucle(); } if(opcion == 3) { Scanner entry = new Scanner(System.in); Atm atm = new Atm(); System.out.print("\nMonto a depositar: "); monto = entry.nextInt(); atm.saldototal += monto; System.out.println("\n-----------------------"); System.out.println("Depositado: " + monto); System.out.println("Su saldo actual es: " + atm.saldototal); System.out.println("-----------------------"); setEfectivo(saldo); Bucle(); } } }
14cb5739516e5ded47a936ad82dfeab5d02884d2
[ "Java" ]
1
Java
hidanscript/ATM
b91f467fd4c970169f208fff4a612dcf59050933
641d53ddf7450bacd89c7c572efc68ae98fbe030
refs/heads/master
<file_sep>find_package(OpenCV REQUIRED) find_package(Boost REQUIRED) include_directories(${OpenCV_INCLUDE_DIRS}) include_directories(${Boost_INCLUDE_DIR}) include_directories(${facedetection_SOURCE_DIR/include}) add_executable(image_detection image_detection.cpp) target_link_libraries(image_detection facedetection ${OpennCV_LIBS} ${Boost_LIBS}) add_executable(video_tracking video_tracking.cpp) target_link_libraries(video_tracking facedetection ${OpennCV_LIBS} ${Boost_LIBS})<file_sep>// // Tracker.cpp // kalman_tracker // // Created by <NAME> on 4/28/17. // Copyright © 2017 <NAME>. All rights reserved. // #include "Tracker.hpp" using namespace std; Tracker::Tracker(Measurement initial, cv::Size frameSize) { restartTimer(); // create filter kf = cv::KalmanFilter(kfNumStates, kfNumMeas); cv::setIdentity(kf.transitionMatrix); cv::setIdentity(kf.measurementMatrix); cv::setIdentity(kf.processNoiseCov, 1E-4); cv::setIdentity(kf.measurementNoiseCov, 2.5); cv::setIdentity(kf.errorCovPre, 0.5); kf.statePost.at<float>(0) = initial.data[0]; kf.statePost.at<float>(1) = initial.data[1]; } ChronoTime Tracker::restartTimer() { timer = chrono::system_clock::now(); return timer; } float Tracker::getTimeDelta(ChronoTime atTime) { chrono::duration<float> deltaSeconds = atTime - timer; return deltaSeconds.count(); } void Tracker::update(Measurement meas) { timer = chrono::system_clock::now(); kf.correct(meas.toKalmanMeasurement()); } Measurement Tracker::estimate() { ChronoTime now = chrono::system_clock::now(); float dt = getTimeDelta(now); timer = now; // update transition matrix kf.transitionMatrix.at<float>(0, 2) = dt; //dx kf.transitionMatrix.at<float>(1, 3) = dt; //dx cv::Mat state = kf.predict(); return Measurement(state.at<float>(0), state.at<float>(1)); }<file_sep>find_package(OpenCV REQUIRED) include_directories(${OpenCV_INCLUDE_DIRS}) include_directories(${facedetection_SOURCE_DIR}/include) file(GLOB facedetection_SRCFILES "*.cpp" "*.c") file(GLOB facedetection_INCLUDEFILES "*.hpp" "*.h") set(facedetection_SOURCES ${facedetection_SRCFILES}) set(facedetection_HEADERS ${facedetection_INCLUDEFILES}) #please revide the previous two lines with regards to the next line add_library(facedetection SHARED ${facedetection_SOURCES} ${facedetection_HEADERS}) target_link_libraries(facedetection ${Opencv_LIBS} opencv_objdetect opencv_video) install(TARGETS facedetection DESTINATION lib) install(FILES ${facedetection_HEADERS} DESTINATION include) add_subdirectory(samples) add_subdirectory(tests) <file_sep>// // Tracker.hpp // kalman_tracker // // Created by <NAME> on 4/28/17. // Copyright © 2017 <NAME>. All rights reserved. // #ifndef Tracker_hpp #define Tracker_hpp #include <opencv2/opencv.hpp> #include <chrono> // Convenient representation of time typedef std::chrono::time_point<std::chrono::system_clock> ChronoTime; // This struct is an interface to let some external process interact with the Tracker class typedef struct Measurement { float data[4]; // hold measurement data: [x y width height] Measurement(float x, float y, float w = 0, float h = 0) { data[0] = x; data[1] = y; data[2] = w; data[3] = h; } // Create a string representation of an instance. Useful for cout. std::string toString(bool jusXY = true) { if(jusXY) return cv::format("[x: %.1f, y: %.1f]", data[0], data[1]); return cv::format("[x: %.1f, y: %.1f, w: %.1f, h: %.1f]", data[0], data[1], data[2], data[3]); } // Convert an instance to a cv::KalmanFilter style measurement Mat // justXY: if true, only use the fist two elements of Measurement.data cv::Mat toKalmanMeasurement(bool jusXY = true) { return cv::Mat((jusXY ? 2 : 4), 1, CV_32F, data); } } Measurement; // This class abstracts typical Kalman filter operations like prediction and correction. // It initializes a filter and sets-up the transition, noise and erorr matrices. // It also maintains a timer object class Tracker { private: ChronoTime timer; // keep track of time int kfNumStates = 4; // x y dx dy [w h dw dh] int kfNumMeas = 2; // x y [w h] cv::KalmanFilter kf; // the filter public: // Provide an intial measurement Tracker(Measurement initial = Measurement(0,0,0,0), cv::Size frameSize = cv::Size(-1, -1)); // Record the current time with the timer ChronoTime restartTimer(); // Get the time difference sine the last time the timer was updated float getTimeDelta(ChronoTime atTime = std::chrono::system_clock::now()); // Correct the filter state at the time of calling and update the timer void update(Measurement meas); // Predict the filter state at the time of calling and update the timer Measurement estimate(); }; #endif /* Tracker_hpp */ <file_sep>`facedetection` A simple face detector using OpenCV. <file_sep>/* description Run tests to verify correct operation of the FaceDetector class */ #include "facedetector.hpp" using namespace cv; using namespace std; using namespace tkcv; void test_faceDetection(){ string folder = TEST_IMAGES_PATH; Mat image = imread(folder + "faces1.jpg"); std::chrono::time_point<std::chrono::system_clock> start, end; std::vector<Face> faces; FaceDetector fd; start = std::chrono::system_clock::now(); fd.detectFaces(image, faces); end = std::chrono::system_clock::now(); for(auto face: faces){ fd.drawFaceRectInImage(face, image, Scalar(255,255,0), true, "face"); } printf("image size: %dx%d\n", image.size().width, image.size().height); printf("faces detected: %d\n", (int)faces.size()); printf("detection time: %lldms\n", chrono::duration_cast<chrono::milliseconds>(end - start).count()); } int main(){ test_faceDetection(); }<file_sep>/* description Run the face detector on an input image provided on the command line */ #include "Tracker.hpp" #include "facedetector.hpp" using namespace cv; using namespace std; using namespace tkcv; void DrawBoxInImage(Point center, Size size, cv::Mat& image, cv::Scalar color=cv::Scalar(255,255,0)) { Point tl = Point(center.x-size.width/2, center.y-size.height/2); Point br = tl + Point(size.width, size.height); rectangle(image, tl - Point(150,80), br + Point(150,80), color, 2); } int main(int argc, char *argv[]){ // std::chrono::time_point<std::chrono::system_clock> start, end; Tracker *tracker = nullptr; bool startTracking = false; std::vector<Face> faces; FaceDetector fd; VideoCapture vCap(0); vCap.set(CV_CAP_PROP_FRAME_WIDTH, 640); vCap.set(CV_CAP_PROP_FRAME_HEIGHT, 480); namedWindow("faces"); int minTimeout = 6; long timeout = 0; Size lastFaceSize; Point lastFaceCenter; ChronoTime lastDetectionTime;// = chrono::system_clock::now(); for(;;) { Mat frame; vCap >> frame; cv::flip(frame, frame, 1); fd.detectFaces(frame, faces); bool faceDetected = faces.size() > 0; if(!faces.empty()) { lastDetectionTime = chrono::system_clock::now(); // fd.drawFaceRectInImage(faces[0], frame, Scalar(255,255,0), true, "#"+to_string(0)); Measurement meas = Measurement(faces[0].center.first, faces[0].center.second); if(!startTracking) { startTracking = true; tracker = new Tracker(meas); lastFaceSize = Size(faces[0].width, faces[0].height); lastFaceCenter = Point(faces[0].center.first, faces[0].center.second); } else { if(timeout >= minTimeout) { tracker->update(meas); timeout = 0; lastFaceSize = Size(faces[0].width, faces[0].height); lastFaceCenter = Point(faces[0].center.first, faces[0].center.second); } } } if(startTracking) { // keep estimating the face location Measurement predicted = tracker->estimate(); chrono::duration<float> sinceDetection = chrono::system_clock::now() - lastDetectionTime; if(sinceDetection.count() < 0.5) DrawBoxInImage(Point(predicted.data[0], predicted.data[1]), lastFaceSize, frame, Scalar(0,0,255)); else { delete tracker; tracker = nullptr; startTracking = false; } } faces.clear(); imshow("faces", frame); if(waitKey(30) == 27) break; timeout++; } if(tracker != nullptr) { delete tracker; } }<file_sep>find_package(OpenCV REQUIRED) include_directories(${OpenCV_INCLUDE_DIRS}) include_directories(${facedetection_SOURCE_DIR/include}) add_executable(facedetection_test facedetection_test.cpp) target_link_libraries(facedetection_test facedetection) <file_sep>#pragma once #include <iostream> #include <vector> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <opencv2/opencv.hpp> #include <string> namespace tkcv { //hold data related to face detections typedef struct Face { std::pair<unsigned,unsigned> center = std::make_pair(0,0); //center coordinates of face unsigned height = 0; //height of face unsigned width = 0; //width of face float confidence; Face(std::pair<unsigned,unsigned> _center, int _height, int _width, float _confidence=1.0f) : center(_center), height(_height), width(_width), confidence(_confidence) { } } Face; //interface to the face detector class FaceDetector { private: std::string cascadeFilePath; //path to cascade file cv::CascadeClassifier faceCascade; //face classifier public: FaceDetector(); //detect faces in an image //image:input the image in which to detect the faces //faces:output array of detected faces void detectFaces(const cv::Mat& image, std::vector<Face>& faces); //draw face region of interest in an image //face:input the face to draw //image:input the image in which to draw the face //color:input/optional the color of the annotation //annotate:input/optional set true to annotate face //annotateWith:input/optional annotate the face with this text void drawFaceRectInImage( const Face& face, cv::Mat& image, cv::Scalar color=cv::Scalar(255,255,0), bool annotate=false, std::string annotateValue=""); }; } <file_sep>/* description Run the face detector on an input image provided on the command line */ #include "facedetector.hpp" using namespace cv; using namespace std; using namespace tkcv; int main(int argc, char *argv[]){ //command line args if(argc != 2){ cout << "Correct usage: image_detection <path_to_image_file>" << endl; exit(-1); } //read the image Mat image = imread(argv[1]); std::chrono::time_point<std::chrono::system_clock> start, end; std::vector<Face> faces; FaceDetector fd; start = std::chrono::system_clock::now(); //detect the faces fd.detectFaces(image, faces); end = std::chrono::system_clock::now(); //draw the faces for(int i = 0 ; i < faces.size(); i++){ fd.drawFaceRectInImage(faces[i], image, Scalar(255,255,0), true, "#"+to_string(i)); } //stats printf("image size: %dx%d\n", image.size().width, image.size().height); printf("faces detected: %d\n", (int)faces.size()); printf("detection time: %lldms\n", chrono::duration_cast<chrono::milliseconds>(end - start).count()); //display namedWindow("faces"); imshow("faces", image); waitKey(); }<file_sep>#include "facedetector.hpp" using namespace std; using namespace cv; using namespace tkcv; FaceDetector::FaceDetector(){ string folder = SUPPORT_PATH; cascadeFilePath = folder + "haarcascade_frontalface_alt.xml"; if(!faceCascade.load(cascadeFilePath)){ cout << "Could not load classifier file!\n"; exit(-1); } } void FaceDetector::detectFaces(const cv::Mat& image, std::vector<Face>& faces){ //get gray assert(image.type() == CV_8UC3 || image.type() == CV_8U); Mat gray; if(image.type() == CV_8UC3) cvtColor(image, gray, CV_BGR2GRAY); else gray = image.clone(); //detect std::vector<Rect> detections; faceCascade.detectMultiScale( gray, detections, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(50, 50)); //convert detections Rect to Face for(auto detection: detections){ cv::Point centerPoint = (detection.tl() + detection.br()) / 2; pair<unsigned,unsigned> center = make_pair(centerPoint.x, centerPoint.y); faces.push_back(Face(center, detection.size().height, detection.size().width)); } } void FaceDetector::drawFaceRectInImage(const Face& face, cv::Mat& image, cv::Scalar color, bool annotate, std::string annotateValue){ //circle(image, cv::Point(face.center.first, face.center.second), (face.height+face.width)/2, Scalar(255,255,0)); Point tl = Point(face.center.first-face.width/2, face.center.second-face.height/2); Point br = tl + Point(face.width, face.height); rectangle(image, tl, br, color); if(annotate){ int baseline=0; float fontScale = 1.0; int fontFace = FONT_HERSHEY_PLAIN; int thickness = 1; //Size textSize = getTextSize(annotateValue, fontFace, fontScale, thickness, &baseline); putText(image, annotateValue, tl-Point(4,4), fontFace, fontScale, Scalar(0,0,0)); putText(image, annotateValue, tl-Point(5,5), fontFace, fontScale, color); } } <file_sep>cmake_minimum_required(VERSION 2.6) project(facedetection) set(CMAKE_CXX_COMPILER /usr/bin/g++) set(CMAKE_CXX_STANDARD 11) set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) add_definitions(-DSUPPORT_PATH="${facedetection_SOURCE_DIR}/src/support/") add_definitions(-DTEST_IMAGES_PATH="${facedetection_SOURCE_DIR}/src/tests/test_images/") add_subdirectory(src)
0657f1495c811db4d54a6c68a48ade0cb46dfdb1
[ "Markdown", "CMake", "C++" ]
12
CMake
TernaK/facedetection
959d1ef0e583f9f0e648d42aa2a383a3cf216c2f
44625c9966b292983e08c0c0b2695eed084c0a62
refs/heads/master
<file_sep>console.log('%c HI', 'color: firebrick') const imgUrl = 'https://dog.ceo/api/breeds/image/random/4' const breedUrl = 'https://dog.ceo/api/breeds/list/all' const dogBreeds = document.querySelector("#dog-breeds") let breeds = [] function fetchImgs() { return fetch(imgUrl) .then(resp => resp.json()) .then(json => renderImgs(json)) } function renderImgs(json) { i = 0 while (i < json.message.length) { const div = document.querySelector('#dog-image-container') let img = document.createElement('img') img.src = json.message[i] div.appendChild(img) i++; } } function fetchBreeds() { return fetch(breedUrl) .then(resp => resp.json()) .then(json => { breeds = Object.keys(json.message) listBreeds(breeds) }) } function listBreeds(breeds) { breeds.forEach(dog => { let li = document.createElement('li') let ul = document.querySelector('#dog-breeds') ul.appendChild(li); li.innerText = dog; changeColor(li); }) } function changeColor(dog) { dog.addEventListener('click', () => { dog.style.color = 'blue' }) } document.addEventListener('DOMContentLoaded', function() { fetchImgs(); fetchBreeds(); }) function filteredList(){ let breedDropdown = document.querySelector('#breed-dropdown'); breedDropdown.addEventListener('change', (e) => { let filteredList = breeds.filter(breed => breed.startsWith(e.target.value)) dogBreeds.innerHTML = "" listBreeds(filteredList) }) } // document.addEventListener('DOMContentLoaded', function() { // })
6dc7670be4895b4bedd5e96e6c8f54543ae4453a
[ "JavaScript" ]
1
JavaScript
AnthonyM5/jsdom-fetch-dog-ceo-challenge-onl01-seng-pt-030220
6852e66ef9694660b660bed79de128a11e689fc2
fc66f3b66350e4c9075bd28a76d6b99065e48dee
refs/heads/master
<repo_name>steltz/sportsfactory-dfs-research<file_sep>/db/migrate/20150929140348_create_fdplayers.rb class CreateFdplayers < ActiveRecord::Migration def change create_table :fdplayers do |t| t.string :name t.string :position t.string :team t.integer :week_1 t.integer :week_2 t.integer :week_3 t.integer :week_4 t.integer :week_5 t.integer :week_6 t.integer :week_7 t.integer :week_8 t.integer :week_9 t.integer :week_10 t.integer :week_11 t.integer :week_12 t.integer :week_13 t.integer :week_14 t.integer :week_15 t.integer :week_16 t.timestamps null: false end end end <file_sep>/db/migrate/20150928160224_add_yr_pos_to_runningbacks.rb class AddYrPosToRunningbacks < ActiveRecord::Migration def change add_column :runningbacks, :yr, :string end end <file_sep>/db/migrate/20150929180240_add_contest_id_game_id_to_contest_games.rb class AddContestIdGameIdToContestGames < ActiveRecord::Migration def change add_column :contest_games, :contest_id, :integer add_column :contest_games, :game_id, :integer end end <file_sep>/lib/tasks/import_fanduel.rake include ActionView::Helpers::SanitizeHelper include ActionView::Helpers::TextHelper require "nokogiri" require "open-uri" require "pry" require "csv" chrome_user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36" desc 'Import player values from Fanduel' task :import_fanduel => :environment do CSV.read("lib/tasks/import_fanduel.csv", :headers=>true, :header_converters=>:symbol).each do |player| name = "#{player[:first_name]} #{player[:last_name]}" position = player[:position] team = player[:team] week_6 = salary = player[:salary].to_i Fdplayer.where(name: name).update_or_create(position: position, team: team, week_6: week_6) end end<file_sep>/db/migrate/20150928000850_create_quarterbacks.rb class CreateQuarterbacks < ActiveRecord::Migration def change create_table :quarterbacks do |t| t.string :team t.string :name t.string :year t.string :pos t.integer :g t.integer :att t.string :comp t.float :pct t.integer :yards t.float :ypa t.integer :td t.integer :int t.float :rating t.float :apg t.float :ypg t.timestamps null: false end end end <file_sep>/test/controllers/fdplayers_controller_test.rb require 'test_helper' class FdplayersControllerTest < ActionController::TestCase setup do @fdplayer = fdplayers(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:fdplayers) end test "should get new" do get :new assert_response :success end test "should create fdplayer" do assert_difference('Fdplayer.count') do post :create, fdplayer: { name: @fdplayer.name, position: @fdplayer.position, team: @fdplayer.team, week_10: @fdplayer.week_10, week_11: @fdplayer.week_11, week_12: @fdplayer.week_12, week_13: @fdplayer.week_13, week_14: @fdplayer.week_14, week_15: @fdplayer.week_15, week_16: @fdplayer.week_16, week_1: @fdplayer.week_1, week_2: @fdplayer.week_2, week_3: @fdplayer.week_3, week_4: @fdplayer.week_4, week_5: @fdplayer.week_5, week_6: @fdplayer.week_6, week_7: @fdplayer.week_7, week_8: @fdplayer.week_8, week_9: @fdplayer.week_9 } end assert_redirected_to fdplayer_path(assigns(:fdplayer)) end test "should show fdplayer" do get :show, id: @fdplayer assert_response :success end test "should get edit" do get :edit, id: @fdplayer assert_response :success end test "should update fdplayer" do patch :update, id: @fdplayer, fdplayer: { name: @fdplayer.name, position: @fdplayer.position, team: @fdplayer.team, week_10: @fdplayer.week_10, week_11: @fdplayer.week_11, week_12: @fdplayer.week_12, week_13: @fdplayer.week_13, week_14: @fdplayer.week_14, week_15: @fdplayer.week_15, week_16: @fdplayer.week_16, week_1: @fdplayer.week_1, week_2: @fdplayer.week_2, week_3: @fdplayer.week_3, week_4: @fdplayer.week_4, week_5: @fdplayer.week_5, week_6: @fdplayer.week_6, week_7: @fdplayer.week_7, week_8: @fdplayer.week_8, week_9: @fdplayer.week_9 } assert_redirected_to fdplayer_path(assigns(:fdplayer)) end test "should destroy fdplayer" do assert_difference('Fdplayer.count', -1) do delete :destroy, id: @fdplayer end assert_redirected_to fdplayers_path end end <file_sep>/README.md # sportsfactory-dfs-research <file_sep>/app/views/runningbacks/index.json.jbuilder json.array!(@runningbacks) do |runningback| json.extract! runningback, :id, :team, :name, :year, :pos, :g, :att, :yards, :avg, :td, :apg, :ypg json.url runningback_url(runningback, format: :json) end <file_sep>/test/controllers/runningbacks_controller_test.rb require 'test_helper' class RunningbacksControllerTest < ActionController::TestCase setup do @runningback = runningbacks(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:runningbacks) end test "should get new" do get :new assert_response :success end test "should create runningback" do assert_difference('Runningback.count') do post :create, runningback: { apg: @runningback.apg, att: @runningback.att, avg: @runningback.avg, g: @runningback.g, name: @runningback.name, pos: @runningback.pos, td: @runningback.td, team: @runningback.team, yards: @runningback.yards, year: @runningback.year, ypg: @runningback.ypg } end assert_redirected_to runningback_path(assigns(:runningback)) end test "should show runningback" do get :show, id: @runningback assert_response :success end test "should get edit" do get :edit, id: @runningback assert_response :success end test "should update runningback" do patch :update, id: @runningback, runningback: { apg: @runningback.apg, att: @runningback.att, avg: @runningback.avg, g: @runningback.g, name: @runningback.name, pos: @runningback.pos, td: @runningback.td, team: @runningback.team, yards: @runningback.yards, year: @runningback.year, ypg: @runningback.ypg } assert_redirected_to runningback_path(assigns(:runningback)) end test "should destroy runningback" do assert_difference('Runningback.count', -1) do delete :destroy, id: @runningback end assert_redirected_to runningbacks_path end end <file_sep>/app/views/fdplayers/index.json.jbuilder json.array!(@fdplayers) do |fdplayer| json.extract! fdplayer, :id, :name, :position, :team, :week_1, :week_2, :week_3, :week_4, :week_5, :week_6, :week_7, :week_8, :week_9, :week_10, :week_11, :week_12, :week_13, :week_14, :week_15, :week_16 json.url fdplayer_url(fdplayer, format: :json) end <file_sep>/app/models/contest.rb class Contest < ActiveRecord::Base has_many :contest_games has_many :games, :through => :contest_games end <file_sep>/app/controllers/runningbacks_controller.rb class RunningbacksController < ApplicationController before_action :set_runningback, only: [:show, :edit, :update, :destroy] # GET /runningbacks # GET /runningbacks.json def index @runningbacks = Runningback.all end # GET /runningbacks/1 # GET /runningbacks/1.json def show end # GET /runningbacks/new def new @runningback = Runningback.new end # GET /runningbacks/1/edit def edit end # POST /runningbacks # POST /runningbacks.json def create @runningback = Runningback.new(runningback_params) respond_to do |format| if @runningback.save format.html { redirect_to @runningback, notice: 'Runningback was successfully created.' } format.json { render :show, status: :created, location: @runningback } else format.html { render :new } format.json { render json: @runningback.errors, status: :unprocessable_entity } end end end # PATCH/PUT /runningbacks/1 # PATCH/PUT /runningbacks/1.json def update respond_to do |format| if @runningback.update(runningback_params) format.html { redirect_to @runningback, notice: 'Runningback was successfully updated.' } format.json { render :show, status: :ok, location: @runningback } else format.html { render :edit } format.json { render json: @runningback.errors, status: :unprocessable_entity } end end end # DELETE /runningbacks/1 # DELETE /runningbacks/1.json def destroy @runningback.destroy respond_to do |format| format.html { redirect_to runningbacks_url, notice: 'Runningback was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_runningback @runningback = Runningback.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def runningback_params params.require(:runningback).permit(:team, :name, :year, :pos, :g, :att, :yards, :avg, :td, :apg, :ypg) end end <file_sep>/app/models/contest_game.rb class ContestGame < ActiveRecord::Base belongs_to :contest belongs_to :game end <file_sep>/db/migrate/20150928160159_add_yr_pos_to_quarterbacks.rb class AddYrPosToQuarterbacks < ActiveRecord::Migration def change add_column :quarterbacks, :yr, :string end end <file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) game_1 = Game.new(away_team: "Away Team 1", home_team: "Home Team 1") game_2 = Game.new(away_team: "Away Team 2", home_team: "Home Team 2") contest_1 = Contest.create!(title: "Contest 1", games: [game_1, game_2])<file_sep>/db/migrate/20150928160230_add_yr_pos_to_receivers.rb class AddYrPosToReceivers < ActiveRecord::Migration def change add_column :receivers, :yr, :string end end <file_sep>/app/models/game.rb class Game < ActiveRecord::Base has_many :contest_games has_many :contests, :through => :contest_games end <file_sep>/app/controllers/quarterbacks_controller.rb class QuarterbacksController < ApplicationController before_action :set_quarterback, only: [:show, :edit, :update, :destroy] # GET /quarterbacks # GET /quarterbacks.json def index @quarterbacks = Quarterback.all end # GET /quarterbacks/1 # GET /quarterbacks/1.json def show end # GET /quarterbacks/new def new @quarterback = Quarterback.new end # GET /quarterbacks/1/edit def edit end # POST /quarterbacks # POST /quarterbacks.json def create @quarterback = Quarterback.new(quarterback_params) respond_to do |format| if @quarterback.save format.html { redirect_to @quarterback, notice: 'Quarterback was successfully created.' } format.json { render :show, status: :created, location: @quarterback } else format.html { render :new } format.json { render json: @quarterback.errors, status: :unprocessable_entity } end end end # PATCH/PUT /quarterbacks/1 # PATCH/PUT /quarterbacks/1.json def update respond_to do |format| if @quarterback.update(quarterback_params) format.html { redirect_to @quarterback, notice: 'Quarterback was successfully updated.' } format.json { render :show, status: :ok, location: @quarterback } else format.html { render :edit } format.json { render json: @quarterback.errors, status: :unprocessable_entity } end end end # DELETE /quarterbacks/1 # DELETE /quarterbacks/1.json def destroy @quarterback.destroy respond_to do |format| format.html { redirect_to quarterbacks_url, notice: 'Quarterback was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_quarterback @quarterback = Quarterback.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def quarterback_params params.require(:quarterback).permit(:team, :name, :year, :pos, :g, :att, :comp, :pct, :yards, :ypa, :td, :int, :rating, :apg, :ypg) end end <file_sep>/lib/tasks/scrape_stats.rake include ActionView::Helpers::SanitizeHelper include ActionView::Helpers::TextHelper require "nokogiri" require "open-uri" require "pry" chrome_user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36" teams = [164,288,196,726,404,663,651,718,690,719,128,67,147,193,234,367, 255,545,415,490,457,688,746,749,742,328,311,51,327,522,521,703, 698,700,301,306,768,392,312,416,418,428,463,509,518,539,559,587, 458,229,796,231,388,366,497,419,664,523,704,574,706,77,772,725, 513,5,47,71,86,129,204,400,331,414,519,503,709,774,721,156,66, 96,277,466,473,626,630,465,731,811,28,107,29,157,529,528,657,674, 110,732,756,754,8,31,235,37,257,334,365,433,430,434,648,694,697, 27,736,253,30,254,295,671,498,472,716,646,670] desc 'Scrape Games from Covers' task :scrape_stats => :environment do teams_scraped = 0 teams.each do |team| passing_uri = URI.parse("http://www.cfbstats.com/2015/team/#{team}/passing/index.html") passing_doc = Nokogiri::HTML(open(passing_uri)) rushing_uri = URI.parse("http://www.cfbstats.com/2015/team/#{team}/rushing/index.html") rushing_doc = Nokogiri::HTML(open(rushing_uri)) receiving_uri = URI.parse("http://www.cfbstats.com/2015/team/#{team}/receiving/index.html") receiving_doc = Nokogiri::HTML(open(receiving_uri)) passing_doc.children.css('tr').each_with_index do |row, index| if index > 0 player_row = index - 1 team = row.xpath('//*[@id="breadcrumb"]')[0].children[11].text name = row.children.css('.player-name a').text break if name.empty? || name.strip == "Team" || name.strip == "Total" || name.strip == "Opponents" yr = row.xpath('//table/tr/td[3]')[player_row].text pos = row.xpath('//table/tr/td[4]')[player_row].text g = row.xpath('//table/tr/td[5]')[player_row].text.to_i att = row.xpath('//table/tr/td[6]')[player_row].text.to_i comp = row.xpath('//table/tr/td[7]')[player_row].text.to_i pct = row.xpath('//table/tr/td[8]')[player_row].text.to_f yards = row.xpath('//table/tr/td[9]')[player_row].text.to_i ypa = row.xpath('//table/tr/td[10]')[player_row].text.to_f td = row.xpath('//table/tr/td[11]')[player_row].text.to_i int = row.xpath('//table/tr/td[12]')[player_row].text.to_i rating = row.xpath('//table/tr/td[13]')[player_row].text.to_f apg = row.xpath('//table/tr/td[14]')[player_row].text.to_f ypg = row.xpath('//table/tr/td[15]')[player_row].text.to_f Quarterback.where(name: name).update_or_create(team: team, yr: yr, pos: pos, g: g, att: att, comp: comp, pct: pct, yards: yards, ypa: ypa, td: td, int: int, rating: rating, apg: apg, ypg: ypa) end end rushing_doc.children.css('tr').each_with_index do |row, index| if index > 0 player_row = index - 1 team = row.xpath('//*[@id="breadcrumb"]')[0].children[11].text name = row.children.css('.player-name').text break if name.empty? || name.strip == "Team" || name.strip == "Total" || name.strip == "Opponents" yr = row.xpath('//table/tr/td[3]')[player_row].text pos = row.xpath('//table/tr/td[4]')[player_row].text g = row.xpath('//table/tr/td[5]')[player_row].text.to_i att = row.xpath('//table/tr/td[6]')[player_row].text.to_i yards = row.xpath('//table/tr/td[7]')[player_row].text.to_i avg = row.xpath('//table/tr/td[8]')[player_row].text.to_f td = row.xpath('//table/tr/td[9]')[player_row].text.to_i apg = row.xpath('//table/tr/td[10]')[player_row].text.to_f ypg = row.xpath('//table/tr/td[11]')[player_row].text.to_f Runningback.where(name: name).update_or_create(team: team, yr: yr, pos: pos, g: g, att: att, yards: yards, avg: avg, td: td, apg: apg, ypg: ypg) end end receiving_doc.children.css('tr').each_with_index do |row, index| rank = row.xpath('//table/tr/td[1]')[0].children.text.to_i if index > 0 player_row = index - 1 team = row.xpath('//*[@id="breadcrumb"]')[0].children[11].text name = row.children.css('.player-name').text break if name.empty? || name.strip == "Team" || name.strip == "Total" || name.strip == "Opponents" yr = row.xpath('//table/tr/td[3]')[player_row].text pos = row.xpath('//table/tr/td[4]')[player_row].text g = row.xpath('//table/tr/td[5]')[player_row].text.to_i rec = row.xpath('//table/tr/td[6]')[player_row].text.to_i yards = row.xpath('//table/tr/td[7]')[player_row].text.to_i avg = row.xpath('//table/tr/td[8]')[player_row].text.to_f td = row.xpath('//table/tr/td[9]')[player_row].text.to_i rpg = row.xpath('//table/tr/td[10]')[player_row].text.to_f ypg = row.xpath('//table/tr/td[11]')[player_row].text.to_f Receiver.where(name: name).update_or_create(team: team, yr: yr, pos: pos, g: g, rec: rec, yards: yards, avg: avg, td: td, rpg: rpg, ypg: ypg) end end teams_scraped += 1 puts "(#{teams_scraped} / #{teams.length})" end end <file_sep>/app/controllers/fdplayers_controller.rb class FdplayersController < ApplicationController before_action :set_fdplayer, only: [:show, :edit, :update, :destroy] # GET /fdplayers # GET /fdplayers.json def index @fdplayers = Fdplayer.all end # GET /fdplayers/1 # GET /fdplayers/1.json def show end # GET /fdplayers/new def new @fdplayer = Fdplayer.new end # GET /fdplayers/1/edit def edit end # POST /fdplayers # POST /fdplayers.json def create @fdplayer = Fdplayer.new(fdplayer_params) respond_to do |format| if @fdplayer.save format.html { redirect_to @fdplayer, notice: 'Fdplayer was successfully created.' } format.json { render :show, status: :created, location: @fdplayer } else format.html { render :new } format.json { render json: @fdplayer.errors, status: :unprocessable_entity } end end end # PATCH/PUT /fdplayers/1 # PATCH/PUT /fdplayers/1.json def update respond_to do |format| if @fdplayer.update(fdplayer_params) format.html { redirect_to @fdplayer, notice: 'Fdplayer was successfully updated.' } format.json { render :show, status: :ok, location: @fdplayer } else format.html { render :edit } format.json { render json: @fdplayer.errors, status: :unprocessable_entity } end end end # DELETE /fdplayers/1 # DELETE /fdplayers/1.json def destroy @fdplayer.destroy respond_to do |format| format.html { redirect_to fdplayers_url, notice: 'Fdplayer was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_fdplayer @fdplayer = Fdplayer.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def fdplayer_params params.require(:fdplayer).permit(:name, :position, :team, :week_1, :week_2, :week_3, :week_4, :week_5, :week_6, :week_7, :week_8, :week_9, :week_10, :week_11, :week_12, :week_13, :week_14, :week_15, :week_16) end end <file_sep>/lib/tasks/scrape_covers.rake include ActionView::Helpers::SanitizeHelper include ActionView::Helpers::TextHelper require "nokogiri" require "open-uri" require "pry" chrome_user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36" desc 'Scrape Games from Covers' task :scrape_covers => :environment do base_url = "http://www.covers.com/odds/football/college-football-odds.aspx" doc = Nokogiri::HTML(open(base_url)) games = doc.xpath('//*[@class="bg_row"]') games.each do |game| # add week away_team = game.children.css("strong")[0].text home_team = game.children.css("strong")[1].text game_date = game.children[3].css(".team_away").text.strip game_time = game.children[3].css(".team_home").text.strip over_under = game.children[7].css(".line_top").text.strip line = game.children[7].css(".covers_bottom").text.strip Game.create!(:away_team => away_team, :home_team => home_team, :game_date => game_date, :game_time => game_time, :over_under => over_under, :line => line) end puts "Rake Task Complete..." end<file_sep>/app/views/quarterbacks/index.json.jbuilder json.array!(@quarterbacks) do |quarterback| json.extract! quarterback, :id, :team, :name, :year, :pos, :g, :att, :comp, :pct, :yards, :ypa, :td, :int, :rating, :apg, :ypg json.url quarterback_url(quarterback, format: :json) end <file_sep>/db/migrate/20150928001158_create_runningbacks.rb class CreateRunningbacks < ActiveRecord::Migration def change create_table :runningbacks do |t| t.string :team t.string :name t.string :year t.string :pos t.integer :g t.integer :att t.integer :yards t.float :avg t.integer :td t.float :apg t.float :ypg t.timestamps null: false end end end <file_sep>/db/migrate/20150929133338_add_weeks_to_fd_players.rb class AddWeeksToFdPlayers < ActiveRecord::Migration def change add_column :fd_players, :week_1, :integer add_column :fd_players, :week_2, :integer add_column :fd_players, :week_3, :integer add_column :fd_players, :week_4, :integer add_column :fd_players, :week_5, :integer add_column :fd_players, :week_6, :integer add_column :fd_players, :week_7, :integer add_column :fd_players, :week_8, :integer add_column :fd_players, :week_9, :integer add_column :fd_players, :week_10, :integer add_column :fd_players, :week_11, :integer add_column :fd_players, :week_12, :integer add_column :fd_players, :week_13, :integer add_column :fd_players, :week_14, :integer add_column :fd_players, :week_15, :integer add_column :fd_players, :week_16, :integer end end <file_sep>/app/views/receivers/index.json.jbuilder json.array!(@receivers) do |receiver| json.extract! receiver, :id, :team, :name, :year, :pos, :g, :rec, :yards, :avg, :td, :rpg, :ypg json.url receiver_url(receiver, format: :json) end <file_sep>/db/migrate/20150929133739_remove_salary_from_fd_players.rb class RemoveSalaryFromFdPlayers < ActiveRecord::Migration def change remove_column :fd_players, :salary end end <file_sep>/test/controllers/quarterbacks_controller_test.rb require 'test_helper' class QuarterbacksControllerTest < ActionController::TestCase setup do @quarterback = quarterbacks(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:quarterbacks) end test "should get new" do get :new assert_response :success end test "should create quarterback" do assert_difference('Quarterback.count') do post :create, quarterback: { apg: @quarterback.apg, att: @quarterback.att, comp: @quarterback.comp, g: @quarterback.g, int: @quarterback.int, name: @quarterback.name, pct: @quarterback.pct, pos: @quarterback.pos, rating: @quarterback.rating, td: @quarterback.td, team: @quarterback.team, yards: @quarterback.yards, year: @quarterback.year, ypa: @quarterback.ypa, ypg: @quarterback.ypg } end assert_redirected_to quarterback_path(assigns(:quarterback)) end test "should show quarterback" do get :show, id: @quarterback assert_response :success end test "should get edit" do get :edit, id: @quarterback assert_response :success end test "should update quarterback" do patch :update, id: @quarterback, quarterback: { apg: @quarterback.apg, att: @quarterback.att, comp: @quarterback.comp, g: @quarterback.g, int: @quarterback.int, name: @quarterback.name, pct: @quarterback.pct, pos: @quarterback.pos, rating: @quarterback.rating, td: @quarterback.td, team: @quarterback.team, yards: @quarterback.yards, year: @quarterback.year, ypa: @quarterback.ypa, ypg: @quarterback.ypg } assert_redirected_to quarterback_path(assigns(:quarterback)) end test "should destroy quarterback" do assert_difference('Quarterback.count', -1) do delete :destroy, id: @quarterback end assert_redirected_to quarterbacks_path end end
2953ed3827e685b3bd33a57f0e60686f16879f0a
[ "Markdown", "Ruby" ]
27
Ruby
steltz/sportsfactory-dfs-research
9f9c62dcdc725c67d652ed26e6b768639134dbf6
09e88eca32c2f2f0f6163fddf8380df9617f613d
refs/heads/master
<repo_name>Cameron-Carter/ICS2O-Unit5-07-HTML<file_sep>/myscript.js // JavaScript File // let statements let numberOne; let numberTwo; let total; // function that simulates multiplication and alerts the answer function multiply() { // assigning values to the input numbers and the total being added to numberOne = document.getElementById("input1").value; numberTwo = document.getElementById("input2").value; total = 0; // making them be treated as numbers and not strings of characters numberOne = +numberOne; numberTwo = +numberTwo; // what happens if the second number input is positive if (numberTwo > 0) { // loop that runs a number of times equal to the second number for(let i = 0; i < numberTwo; i++) { // each time the loop is run, the total adds an extra of the first number, simulating multiplication total = total + numberOne; } // ouputs answer alert(total); } // what happens if the second number input is positive else if (numberTwo < 0) { // numberTwo = numberTwo * -1; // loop that runs a number of times equal to the second number for(let i = 0; i < numberTwo; i++) { // each time the loop is run, the total adds an extra of the first number, simulating multiplication total = total + numberOne; } // switches number back to a negative or positive total = total * -1; // ouputs answer alert(total); } // only other number that the second input could be is 0 and anything times zero is zero else { // alerts 0 alert(0); } } // event listener activated by the submit button that triggers the 'multiplication' function document.getElementById("btn").addEventListener("click", multiply);
5d2019f5559450e2b3c337cde66d8d32aa2bd3e8
[ "JavaScript" ]
1
JavaScript
Cameron-Carter/ICS2O-Unit5-07-HTML
e51fe408786cdb7003934b61e2b84563492a0f29
cc17c0e8c1baa240199b49016d4d6269590165a6
refs/heads/master
<file_sep>#!/usr/bin/env ruby # encoding: UTF-8 # Le constructeur du fichier des tâches require 'yaml' require 'sass' require './lib/taches.rb' require './lib/tache.rb' class Builder class << self # Méthode principale construisant la liste des tâches # # @retourne self (pour chainage) # def build options = nil File.exist?(path) && File.unlink(path) write head_html write '<body>' liste_taches write end_html if options && options[:open] `open "#{path}"` end return self end def liste_taches write '<ul id="taches">' Taches.new.sort.each{|tache| write tache.as_li} write '</ul>' end # --------------------------------------------------------------------- # Méthodes fonctionnelles # --------------------------------------------------------------------- # Écrit le code +code+ dans le fichier HTML def write code fref.write code end private def fref @fref ||= File.open(path,'a') end def path @path ||= File.join(folder, 'lib', 'taches.html') end def path_yaml_file @path_yaml_file ||= File.join(folder, 'TACHES.yaml') end def path_run_file @path_run_file ||= File.join(folder, '__run__.rb') end def folder @folder ||= File.expand_path('.') end # --------------------------------------------------------------------- # ÉLÉMENTS HTML # --------------------------------------------------------------------- SASS_OPTIONS = { line_comments: false, syntax: :sass, style: :compressed } def styles_css Sass.compile(File.read('./lib/todo.sass'), SASS_OPTIONS) end def head_html <<-HTML <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>TODO list</title> <style type="text/css">#{styles_css}</style> </head> HTML end def end_html lien_open_taches + '</body></html>' end def lien_open_taches '<div class="tiny">'+ "<a href='atm:open?url=file://#{path_yaml_file}'>Ouvrir le fichier des tâches</a>"+ ' – ' + "<a href='atm:open?url=file://#{path_run_file}'>Actualiser les tâches</a>"+ '</div>' end end end <file_sep>#!/usr/bin/env ruby # encoding: UTF-8 # Classe d'une tache UNE_HEURE = 3600 UN_JOUR = UNE_HEURE * 24 UNE_ANNEE = UN_JOUR * 365 class Tache attr_reader :id, :tache, :pour, :hot def initialize hdata # On dispatche les données de la tâche hdata.each{|k,v| instance_variable_set("@#{k}", v)} end def echeance @echeance ||= echeance_from_pour end # --------------------------------------------------------------------- # Méthodes d'helper HTML # --------------------------------------------------------------------- def as_li tid = "tache-#{id}" c = "<li id='#{tid}' class='tache #{style}'>" # Toutes les infos c << div_infos # Le CB c << "<input type='checkbox' id='#{tid}-cb' />" # La tache c << "<label for='#{tid}-cb' class='tache'>#{tache}</label>" c << '</li>' return c end # --------------------------------------------------------------------- # Méthodes d'helper private HTML # --------------------------------------------------------------------- # /* private */ def div_infos c = "<div class='infos'>" c << "<span class='echeance'>#{echeance_h} (dans #{reste_h})</span>" c << "</div>" return c end private def outofdate? echeance < Time.now end # Style de la tache en fonction de l'échéance def style if outofdate? 'warning' else if @actual 'orange' elsif reste_jours > 6 'cool' else if @hot 'orange' else '' end end end end # L'échéance en format humain def echeance_h @echeance_h ||= echeance.strftime('%d %m %Y') end # Le temps qu'il reste en jour jusqu'à l'échéance en nombre de jours ou d'heures def reste_jours @reste || (echeance - Time.now) / UN_JOUR end # Le temps restant, en version humaine def reste_h @reste ||= begin if outofdate? '' else r = echeance - Time.now if r > UN_JOUR r = (r / UN_JOUR).to_i s = r > 1 ? 's' : '' "#{r} jour#{s}" else r = (r / UNE_HEURE).to_i s = r > 1 ? 's' : '' "#{r} heure#{s}" end end end end def echeance_from_pour now = Time.now case pour when nil return Time.now + UNE_ANNEE when 'auj' return Time.new(now.year, now.month, now.day, 23,59,59) when 'dem' return Time.new(now.year, now.month, now.day + 1, 23,59,59) # + UN_JOUR else jour, mois, annee = @pour.split(' ') end Time.new((annee|| Time.now.year).to_i, (mois||Time.now.month + 1).to_i, jour.to_i, 23, 59, 59) end end <file_sep>#!/usr/bin/env ruby # encoding: UTF-8 # --------------------------------------------------------------------- # LANCER CE FICHIER (CMD + i dans Atom) POUR ACTUALISER LES TACHES # # Les tâches doivent avoir été définies dans le fichier TACHES.yaml # --------------------------------------------------------------------- require './lib/builder' Builder.build(open: true) <file_sep>#!/usr/bin/env ruby -wKU # encoding: UTF-8 # Classe des Taches comme un ensemble class Taches def taches @taches ||= begin id = 0 taches_yaml.collect do |htache| id += 1 Tache.new(htache.merge(id: id)) end end end alias :all :taches # Classe la liste des taches par échéance, de la plus proche à la plus # lointaine. # @retourne self, pour le chainage def sort @taches = taches.sort_by{|t| t.echeance } return self end def each taches.each do |tache| yield tache end end def taches_yaml @taches_yaml ||= YAML.load_file('TACHES.yaml') end end
416e7623cb01a674c83ce8c8fcc69901cea7f4bf
[ "Ruby" ]
4
Ruby
PhilippePerret/TODO
dc8017c42d401ab12db3b771420c7197bf723f67
aab85c0ee10941b9f373398f17ffee06390cb1ac
refs/heads/master
<repo_name>YutaSawagami/ex-emp-management<file_sep>/src/main/java/jp/co/sample/controller/AdministratorController.java package jp.co.sample.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import jp.co.sample.domain.Administrator; import jp.co.sample.form.InsertAdministratorForm; import jp.co.sample.form.LoginForm; import jp.co.sample.service.AdministratorService; @Controller @RequestMapping("/") public class AdministratorController { @Autowired private HttpSession session; @Autowired private AdministratorService admistService; @ModelAttribute public InsertAdministratorForm setUpInsertAdministratorForm() { return new InsertAdministratorForm(); } @ModelAttribute public LoginForm setUpLoginForm() { return new LoginForm(); } @RequestMapping("/toInsert") public String toInsert() { return "administrator/insert.html"; } @RequestMapping("/insert") public String insert(InsertAdministratorForm insertAdministratorForm) { //Formクラスをドメインに変換してserviceのinsertに渡す処理 System.out.println(insertAdministratorForm.getName()); Administrator administrator = new Administrator(); BeanUtils.copyProperties(insertAdministratorForm, administrator); admistService.insert(administrator); return "redirect:/"; } @RequestMapping("") public String toLogin() { return "administrator/login"; } @RequestMapping("/login") public String login(LoginForm loginForm, Model model) { try { System.out.println(loginForm.getMailAddress()); Administrator administrator = admistService.login(loginForm.getMailAddress(), loginForm.getPassword()); System.out.println(administrator); session.setAttribute("administratorName", administrator.getName()); System.out.println("成功"); return "redirect:/employee/showList"; }catch (EmptyResultDataAccessException e) { System.out.println("データがないです。"); model.addAttribute("message", "メールアドレスかパスワードが間違ってます。"); return "administrator/login"; } } @RequestMapping("/logout") public String logout() { session.invalidate(); return "redirect:/"; } } <file_sep>/src/main/java/jp/co/sample/service/AdministratorService.java package jp.co.sample.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import jp.co.sample.domain.Administrator; import jp.co.sample.repository.AdministratorRepository; @Transactional @Service public class AdministratorService { @Autowired private AdministratorRepository administRepository; public void insert(Administrator administrator) { administRepository.insert(administrator); } public Administrator findByMailAddressAndPassword(String mailAddress, String password) throws EmptyResultDataAccessException{ return administRepository.findByMailAddressAndPassWord(mailAddress, password); } public Administrator login(String mailAddress, String password) { return administRepository.findByMailAddressAndPassWord(mailAddress, password); } } <file_sep>/src/main/java/jp/co/sample/service/EmployeeService.java package jp.co.sample.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import jp.co.sample.domain.Employee; import jp.co.sample.repository.EmployeeRepository; @Service @Transactional public class EmployeeService { @Autowired private EmployeeRepository empRepository; public List<Employee> showList(){ List<Employee> employeeList = empRepository.findAll(); return employeeList; } public Employee showDetail(int id) { Employee emp = empRepository.load(id); return emp; } public void update(Employee employee) { empRepository.update(employee); } }
ee0ba0270cc04355e4a362590de7ae3206fde30c
[ "Java" ]
3
Java
YutaSawagami/ex-emp-management
2689a3371579cd90ecf09dc2004c003b080d66ee
e0bba210e079ff74692389967befe1dafe2f48b7
refs/heads/main
<file_sep>module.exports = "0B!0m@88"<file_sep># 10_Employee_Tracker * [Acceptance Criteria](#acceptancecriteria) * [Installation](#installation) * [Project Status](#projectstatus) * [License](#license) * [Deployment](#deployment) * [Usage](#usage) * [Preview of the App](#previewApp) # Employee_Tracker For this project, I aim to create an Employee Tracker application that can be used to track the organization's employees. This application will use MySQL, InquirerJs, and console.table dependencies to make the app function. My main motivation for this project is to create an application that will allow employers to successfully track their employees and view their information by department and role. # Acceptance Criteria Build a command-line application that at a minimum allows the user to: * Add departments, roles, employees * View departments, roles, employees * Update employee roles # Installation In order to use this app, you will need to install MySQL, InquirerJs, and console.table. # Project Status This project was completed on April 24, 2021. # License MIT [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/sdca/advdv) # Deployment [Link](https://drive.google.com/file/d/1O19XE915vSMxjYLlFQsY-bE4j2_3muhJ/view?usp=sharing) # Usage When you open the terminal, you will be able to view all employees, view employees by department and by role, view all departments, add new employees and new Departments, update an employee's information and remove employees. Add screenShot # Preview of the App * This is how the app looks ![NoteTakingApp Screenshot](./assets/trackerSnapshot.PNG)<file_sep>--Create Database Schema-- DROP DATABASE IF EXISTS emp_trackerDB; CREATE DATABASE emp_trackerDB; USE emp_trackerDB; CREATE TABLE department ( id INT NOT NULL AUTO_INCREMENT , name VARCHAR(30) NOT NULL , PRIMARY KEY (id) ); CREATE TABLE role ( id INT NOT NULL AUTO_INCREMENT , title VARCHAR(30) NOT NULL , salary DECIMAL(8, 2) , department_id INT , PRIMARY KEY (id) ); CREATE TABLE employee ( id INT NOT NULL AUTO_INCREMENT , first_name VARCHAR(30) , last_name VARCHAR(30) , role_id INT , manager_id INT DEFAULT NULL , PRIMARY KEY (id) ); --Create Starting Table Data-- INSERT INTO department (name) VALUES ("Operations") , ("Sales") , ("Finance") , ("Legal") , ("Engineering"); INSERT INTO role (title, salary, department_id) VALUES ("CEO", 350000, 1) , ("COO", 300000, 1) , ("CTO", 200000, 5) , ("CFO", 250000, 3) , ("Sales Team Lead", 125000, 2) , ("Salesperson", 90000, 2) , ("Controller", 135000, 3) , ("Accountant", 80000, 3) , ("Legal Team Lead", 200000, 4) , ("Lawyer", 160000, 4) , ("Engineer Team Lead", 190000, 5) , ("Software Engineer", 150000, 5); INSERT INTO employee (first_name, last_name, role_id, manager_id) VALUES("Alicia", "Yao", 1, NULL) , ("Obi", "Ude", 2, NULL) , ("Natasha", "Martinez", 3, NULL) , ("Robert", "Yes", 4, NULL) , ("Crystal", "Warren", 5, 2) , ("Joanne", "Algranati", 6, 5) , ("Dahlene", "Scott", 7, 4) , ("Busola", "Oye", 8, 7) , ("Dean", "Rodney", 9, 2) , ("Diann", "Pena", 10, 9) , ("Douglas", "Wright", 11, 3) , ("Lamont", "Franks", 12, 11);
5f3b7395fd2ea01cee9b8a7f02bd10d7043e0bc5
[ "JavaScript", "SQL", "Markdown" ]
3
JavaScript
Obi1002/10_Employee_Tracker
da0720ef476779d1ce76b695c70d89eeed5728f0
6345c67af38828af64ec2c3238ebc66526bd201f
refs/heads/master
<file_sep>package com.example.mbrecka.topviewrefactor.di import android.app.Application import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.mbrecka.topviewrefactor.* import dagger.Binds import dagger.Component import dagger.Module import dagger.Provides import dagger.android.ContributesAndroidInjector import dagger.multibindings.IntoMap import javax.inject.Singleton @Singleton @Component( modules = [ AndroidModule::class, ActivityBuilderModule::class, ViewModelModule::class ] ) interface AppComponent { fun inject(application: MyApp) } @Module abstract class ActivityBuilderModule { @ContributesAndroidInjector abstract fun contributeMainActivity(): MainActivity } @Module class AndroidModule(val application: Application) { @Provides fun provideApplicationContext(): Context { return application } } @Module abstract class ViewModelModule { @Binds @IntoMap @ViewModelKey(SignpostViewModel::class) internal abstract fun bindSignpostViewModel(viewModel: SignpostViewModel): ViewModel @Binds @IntoMap @ViewModelKey(IncidentViewModel::class) internal abstract fun bindIncidentViewModel(viewModel: IncidentViewModel): ViewModel @Binds @IntoMap @ViewModelKey(EndOfRouteViewModel::class) internal abstract fun bindEndOfRouteViewModel(viewModel: EndOfRouteViewModel): ViewModel @Binds @IntoMap @ViewModelKey(OnlyVisibleViewModel::class) internal abstract fun bindOnlyVisibleViewModel(viewModel: OnlyVisibleViewModel): ViewModel @Binds internal abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory }<file_sep>package com.example.mbrecka.topviewrefactor import android.app.Activity import android.app.Application import com.example.mbrecka.topviewrefactor.di.AndroidModule import com.example.mbrecka.topviewrefactor.di.AppComponent import com.example.mbrecka.topviewrefactor.di.DaggerAppComponent import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.HasActivityInjector import javax.inject.Inject /** * Created by Matej on 29. 7. 2016. */ class MyApp : Application(), HasActivityInjector { @Inject lateinit var activityInjector: DispatchingAndroidInjector<Activity> lateinit var component: AppComponent private set override fun onCreate() { super.onCreate() component = DaggerAppComponent.builder() .androidModule(AndroidModule(this)) .build() .also { it.inject(this) } } override fun activityInjector(): AndroidInjector<Activity>? { return activityInjector } }<file_sep>package com.example.mbrecka.topviewrefactor import androidx.databinding.ObservableField import androidx.lifecycle.ViewModel import com.jakewharton.rxrelay2.BehaviorRelay import io.reactivex.Observable import javax.inject.Inject interface TopViewViewModel { val text: ObservableField<String> val isVisible: Observable<Boolean> fun setVisible(isVisible: Boolean) fun onDismiss() val isDismissable : Boolean } abstract class BaseTopViewModel : ViewModel(), TopViewViewModel { private val relay = BehaviorRelay.createDefault(false) override fun setVisible(isVisible: Boolean) { relay.accept(isVisible) } override val isVisible: Observable<Boolean> = relay override fun onDismiss() { // TODO: nejaka drsnejsia logika setVisible(false) } override val isDismissable: Boolean get() = true } class SignpostViewModel @Inject constructor() : BaseTopViewModel() { override val text = ObservableField<String>("Signpost") // Observable.interval(1000, TimeUnit.MILLISECONDS) // .map { it % 2L == 0L } override val isDismissable: Boolean get() = false } class IncidentViewModel @Inject constructor() : BaseTopViewModel() { override val text = ObservableField<String>("Incident") // Observable.interval(1500, TimeUnit.MILLISECONDS) // .map { it % 2L == 0L } } class EndOfRouteViewModel @Inject constructor() : BaseTopViewModel() { override val text = ObservableField<String>("EndOfRoute") // Observable.interval(2500, TimeUnit.MILLISECONDS) // .map { it % 2L == 0L } } class OnlyVisibleViewModel @Inject constructor() : BaseTopViewModel() { override val text = ObservableField<String>("OnlyVisible") // Observable.interval(3000, TimeUnit.MILLISECONDS) // .map { it % 2L == 0L } }<file_sep>package com.example.mbrecka.topviewrefactor import android.util.Log import android.view.LayoutInflater import androidx.recyclerview.widget.RecyclerView import android.view.ViewGroup import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.DiffUtil import com.example.mbrecka.topviewrefactor.databinding.* import java.lang.RuntimeException class TopViewAdapter : RecyclerView.Adapter<TopViewHolder>() { private val data = mutableListOf<TopViewViewModel>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TopViewHolder { val inflater = LayoutInflater.from(parent.context) return when (viewType) { 2 -> ItemSignpostBinding.inflate(inflater).let(::SignpostViewHolder) 3 -> ItemIncidentBinding.inflate(inflater).let(::IncidentViewHolder) 4 -> ItemEndofrouteBinding.inflate(inflater).let(::EndOfRouteViewHolder) 5 -> ItemOnlyvisibleBinding.inflate(inflater).let(::OnlyVisibleViewHolder) else -> throw RuntimeException() } } override fun getItemViewType(position: Int): Int { return when (data[position]) { is SignpostViewModel -> 2 is IncidentViewModel -> 3 is EndOfRouteViewModel -> 4 is OnlyVisibleViewModel -> 5 else -> throw RuntimeException() } } override fun getItemCount() = data.size override fun onBindViewHolder(holder: TopViewHolder, position: Int) { val item = data[position] when (holder) { is SignpostViewHolder -> { (holder.binding as ItemSignpostBinding).viewModel = item as SignpostViewModel } is IncidentViewHolder -> { (holder.binding as ItemIncidentBinding).viewModel = item as IncidentViewModel } is EndOfRouteViewHolder -> { (holder.binding as ItemEndofrouteBinding).viewModel = item as EndOfRouteViewModel } is OnlyVisibleViewHolder -> { (holder.binding as ItemOnlyvisibleBinding).viewModel = item as OnlyVisibleViewModel } } } fun submitList(viewmodels: List<TopViewViewModel>) { Log.d("matej", "submitList() called with: viewmodels = [$viewmodels]") DiffUtil.calculateDiff(diffCallback(viewmodels)) .dispatchUpdatesTo(this) data.clear() data.addAll(viewmodels) } private fun diffCallback(viewmodels: List<TopViewViewModel>): DiffUtil.Callback { return object : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return data[oldItemPosition] == viewmodels[newItemPosition] } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return data[oldItemPosition] == viewmodels[newItemPosition] } override fun getOldListSize() = data.size override fun getNewListSize() = viewmodels.size } } fun isDismissable(viewHolder: RecyclerView.ViewHolder) = data[viewHolder.adapterPosition].isDismissable fun foo(viewHolder: RecyclerView.ViewHolder) { data[viewHolder.adapterPosition].onDismiss() } } sealed class TopViewHolder(val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {init { Log.d("matej", "TopViewHolder.init") } } class SignpostViewHolder(binding: ItemSignpostBinding) : TopViewHolder(binding) {init { Log.d("matej", "SignpostViewHolder.init") } } class IncidentViewHolder(binding: ItemIncidentBinding) : TopViewHolder(binding) {init { Log.d("matej", "IncidentViewHolder.init") } } class EndOfRouteViewHolder(binding: ItemEndofrouteBinding) : TopViewHolder(binding) {init { Log.d("matej", "EndOfRouteViewHolder.init") } } class OnlyVisibleViewHolder(binding: ItemOnlyvisibleBinding) : TopViewHolder(binding) {init { Log.d("matej", "OnlyVisibleViewHolder.init") } } <file_sep>package com.example.mbrecka.topviewrefactor import android.content.Context import android.util.AttributeSet import android.util.Log import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import kotlin.math.max @Suppress("unused") class AnchoredToTopViewBehavior(context: Context, attributeSet: AttributeSet) : androidx.coordinatorlayout.widget.CoordinatorLayout.Behavior<View>(context, attributeSet) { override fun layoutDependsOn( parent: androidx.coordinatorlayout.widget.CoordinatorLayout, child: View, dependency: View ): Boolean { if (dependency.id == R.id.recycler) return true return super.layoutDependsOn(parent, child, dependency) } override fun onDependentViewChanged( parent: androidx.coordinatorlayout.widget.CoordinatorLayout, child: View, dependency: View ): Boolean { if (dependency.id == R.id.recycler) { val recycler = (dependency as RecyclerView) // TODO: extension function (0 until recycler.childCount) .maxBy { recycler.getChildAt(it).let { it.y + it.height } } .let { child.translationY = if (it != null) recycler.getChildAt(it).let { it.y + it.height } else 0f } } return super.onDependentViewChanged(parent, child, dependency) } }<file_sep>package com.example.mbrecka.topviewrefactor import android.os.Bundle import android.util.Log import android.view.animation.AccelerateDecelerateInterpolator import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProviders import com.example.mbrecka.topviewrefactor.di.ViewModelFactory import dagger.android.AndroidInjection import javax.inject.Inject import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.LinearLayoutManager import com.example.mbrecka.topviewrefactor.databinding.ActivityMainBinding import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import jp.wasabeef.recyclerview.animators.SlideInDownAnimator import java.lang.RuntimeException import kotlin.random.Random // TODO: item nech sa vysunie popod predosly item, nie ponad class ViewModelRulebase { private val hiddenBy = mapOf( TopVm.SIGNPOST to listOf(TopVm.ONLY_VISIBLE), TopVm.INCIDENT to listOf(TopVm.ONLY_VISIBLE, TopVm.END_OF_ROUTE), TopVm.END_OF_ROUTE to listOf(TopVm.ONLY_VISIBLE), TopVm.ONLY_VISIBLE to emptyList() ) private fun isAllowedByState(viewModel: TopViewViewModel, vms: Map<TopVm, Boolean>): Boolean { val hiddenBy = hiddenBy[viewModel.toEnum()]!! val currentState = vms.keys return hiddenBy.intersect(currentState).isEmpty() } fun applyRules(it: Map<TopViewViewModel, Boolean>): List<TopViewViewModel> { val vms = it.toList() val mappedVms = vms .asSequence() .filter { it.second } .associate { it.first.toEnum() to it.second } return vms .asSequence() .filter { it.second && isAllowedByState(it.first, mappedVms) } .map { it.first } .toList() } private fun TopViewViewModel.toEnum(): TopVm { return when (this) { is SignpostViewModel -> TopVm.SIGNPOST is IncidentViewModel -> TopVm.INCIDENT is EndOfRouteViewModel -> TopVm.END_OF_ROUTE is OnlyVisibleViewModel -> TopVm.ONLY_VISIBLE else -> throw RuntimeException() } } enum class TopVm { SIGNPOST, INCIDENT, END_OF_ROUTE, ONLY_VISIBLE } } class MainActivity : AppCompatActivity() { @Inject lateinit var viewModelFactory: ViewModelFactory val viewModelRulebase = ViewModelRulebase() val adapter = TopViewAdapter() lateinit var binding: ActivityMainBinding private val disposable = CompositeDisposable() override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val signpostViewModel = ViewModelProviders.of(this, viewModelFactory).get(SignpostViewModel::class.java) val incidentViewModel = ViewModelProviders.of(this, viewModelFactory).get(IncidentViewModel::class.java) val endOfRouteViewModel = ViewModelProviders.of(this, viewModelFactory).get(EndOfRouteViewModel::class.java) val onlyVisibleViewModel = ViewModelProviders.of(this, viewModelFactory).get(OnlyVisibleViewModel::class.java) binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main).apply { recycler.adapter = adapter recycler.itemAnimator = SlideInDownAnimator(AccelerateDecelerateInterpolator()) recycler.setChildDrawingOrderCallback { childCount, i -> childCount - (i + 1) } // reverse drawing order recycler.layoutManager = object : LinearLayoutManager(this@MainActivity) { override fun canScrollHorizontally(): Boolean { return false } override fun canScrollVertically(): Boolean { return false } } ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun getSwipeDirs(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int { return if(adapter.isDismissable(viewHolder)){ ItemTouchHelper.LEFT }else{ 0 } } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { adapter.foo(viewHolder) } }).attachToRecyclerView(recycler) signpostSwitch.setOnCheckedChangeListener { _, isChecked -> signpostViewModel.setVisible(isChecked) } disposable += signpostViewModel.isVisible.subscribe { signpostSwitch.isChecked = it } incidentSwitch.setOnCheckedChangeListener { _, isChecked -> incidentViewModel.setVisible(isChecked) } disposable += incidentViewModel.isVisible.subscribe { incidentSwitch.isChecked = it } endOfRouteSwitch.setOnCheckedChangeListener { _, isChecked -> endOfRouteViewModel.setVisible(isChecked) } disposable += endOfRouteViewModel.isVisible.subscribe { endOfRouteSwitch.isChecked = it } onlyVisibleSwitch.setOnCheckedChangeListener { _, isChecked -> onlyVisibleViewModel.setVisible(isChecked) } disposable += onlyVisibleViewModel.isVisible.subscribe { onlyVisibleSwitch.isChecked = it } fab.setOnClickListener { it.alpha = Random.nextFloat() } } val visibilityStreams = listOf( signpostViewModel, incidentViewModel, endOfRouteViewModel, onlyVisibleViewModel ) disposable += Observable.combineLatest(visibilityStreams.map { it.isVisible.startWith(false) }) { linkedMapOf<TopViewViewModel, Boolean>() .apply { it.forEachIndexed { index, b -> this[visibilityStreams[index]] = b as Boolean } } } .map { viewModelRulebase.applyRules(it) } .observeOn(AndroidSchedulers.mainThread()) .subscribe({ adapter.submitList(it) Log.d("matej", "${adapter.itemCount}") }, { Log.e("matej", "onCreate: ", it) }) } } data class Foo( val a: Pair<TopViewViewModel, Boolean>, val b: Pair<TopViewViewModel, Boolean>, val c: Pair<TopViewViewModel, Boolean>, val d: Pair<TopViewViewModel, Boolean> )
4ee96417837f9fa1c4b24bd1730e656968cbc66d
[ "Kotlin" ]
6
Kotlin
jozoprocko69/TopviewRefactor
ab8f548d950c6dd031d294fa3e1c0e4c5669447f
4a28157bd394b66f1cef034965c64ab0a7ca570a
refs/heads/master
<repo_name>Alquimerico/Piedra--papel-o-tijeras<file_sep>/src/Main.java import java.util.Random; public class Main { @SuppressWarnings("static-access") public static void main(String[] args) { // TODO Auto-generated method stub gui1 n = new gui1(); //n.main(null); } public int match(int jugada, int jugadaEnemiga) { //Returns 1 if player 1 wins, 2 player 2 wins, 3 for a drawn //Piedra = 1, Papel = 2, Tijera = 3 if(jugada == jugadaEnemiga) return 3; if(jugada == 1 && jugadaEnemiga == 3) return 1; return 2; } public int random1_3() { //Computer player uses this one Random rand = new Random(); int randomNum = rand.nextInt((3 - 1) + 1) + 1; return randomNum; } public static String matchOutcome(int n) { if(n==1) return "El jugador gana."; if(n==2) return "La maquina gana."; if(n==3) return "Ha habido un empate."; return "Algo ha salido muy mal :< "; } public static String intToppt(int n) { if(n==1) return "piedra"; if(n==2) return "papel"; if(n==3) return "tijeras"; return "Algo ha salido muy mal :< "; } }
315e2fc2c5ffc81700332e48193e2e76c6747dc2
[ "Java" ]
1
Java
Alquimerico/Piedra--papel-o-tijeras
61c292e878abf463e855084ce8f1d3afa4bbd07f
ad7d033452b52625fabe442a415c30757dc56880
refs/heads/master
<file_sep>CREATE TABLE PERSON3 ( ID INTEGER(5) PRIMARY KEY, NAME VARCHAR(100), COUNTRY VARCHAR(100) );<file_sep>package com.mypack.dao; import java.util.List; import org.springframework.orm.hibernate3.HibernateTemplate; import com.mypack.beans.Person3; public class Person3DaoImpl implements Person3Dao{ private HibernateTemplate template; public void setTemplate(HibernateTemplate template) { this.template = template; } @Override public void save(Person3 p) { template.setCheckWriteOperations(false); template.save(p); } @SuppressWarnings("unchecked") @Override public List<Person3> list() { List<Person3> personList = (List<Person3>)template.find("from Person3"); return personList; } }
6b9312e06241cdb0be01a11d4ba8ffaed6e8d52e
[ "Java", "SQL" ]
2
SQL
ik21191/springHibernate
9a4a6b74d1e31edb4e8f10480490f2433d2694b4
e3b2410b84901352701e05f3871af692e8c3ffba
refs/heads/master
<repo_name>jeffScott001/free-delivery-movies-and-series<file_sep>/item/ordered_items.php <?php header('Access-Control-Allow-Origin: *'); header('Content-Type: application/json'); header('Access-control-Allow-Methods: POST'); header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods,Authorization,X-Requested-With'); require_once '../models/item.php'; require_once '../config/Database.php'; // Instatiate DB and connect to DB $database = new Database(); $db = $database->connect(); // Instantiate the user class $item = new Item($db); // Get the raw data $data = json_decode(file_get_contents("php://input")); foreach($data->items as $i) { $item->user_id = $data->user_id; $item->phone_number = $data->phone_number; $item->area = $data->area; $item->item_name = $i->title; $item->seasons = implode(", ",$i->seasons); $item->episodes = implode(", ",$i->episodes); $item->price = count($i->seasons)*30; $item->mpesa_code = $data->mpesa_code; $item->orderedItems(); } echo json_encode(['msg'=>'success']); <file_sep>/js/main_cart.js // video elements const cart_container = document.querySelector('.trailers-container'); // Event Listeners cart_container.addEventListener('click', transitionsContainer); // Functions let seasons = []; let episodes = []; function transitionsContainer(e){ console.log(e.target.className); if(e.target.id == 'add-to-cart-btn'){ e.target.parentElement.classList.remove('active'); e.target.parentElement.classList.add('domant'); e.target.parentElement.nextElementSibling.classList.remove('inactive'); e.target.parentElement.nextElementSibling.classList.add('active'); console.log(e.target) } if(e.target.id == 'foward-season-btn'){ e.target.parentElement.parentElement.previousElementSibling.classList.remove('domant'); e.target.parentElement.parentElement.previousElementSibling.classList.add('domant2'); e.target.parentElement.parentElement.classList.remove('active'); e.target.parentElement.parentElement.classList.add('domant'); e.target.parentElement.parentElement.nextElementSibling.classList.remove('inactive'); e.target.parentElement.parentElement.nextElementSibling.classList.add('active'); } if(e.target.id == 'backward-episodes-btn'){ e.target.parentElement.parentElement.previousElementSibling.previousElementSibling.classList.remove('domant2'); e.target.parentElement.parentElement.previousElementSibling.previousElementSibling.classList.add('domant'); e.target.parentElement.parentElement.previousElementSibling.classList.remove('domant'); e.target.parentElement.parentElement.previousElementSibling.classList.add('active'); e.target.parentElement.parentElement.classList.remove('active'); e.target.parentElement.parentElement.classList.add('inactive'); } if(e.target.id == 'foward-episodes-btn'){ e.target.parentElement.parentElement.previousElementSibling.previousElementSibling.classList.remove('domant2'); e.target.parentElement.parentElement.previousElementSibling.previousElementSibling.classList.add('domant3'); e.target.parentElement.parentElement.previousElementSibling.classList.remove('domant'); e.target.parentElement.parentElement.previousElementSibling.classList.add('domant2'); e.target.parentElement.parentElement.classList.remove('active'); e.target.parentElement.parentElement.classList.add('domant'); e.target.parentElement.parentElement.nextElementSibling.classList.remove('inactive'); e.target.parentElement.parentElement.nextElementSibling.classList.add('active'); } if(e.target.id == 'confirm-backward-btn'){ e.target.parentElement.parentElement.previousElementSibling.previousElementSibling.previousElementSibling.classList.remove('domant3'); e.target.parentElement.parentElement.previousElementSibling.previousElementSibling.previousElementSibling.classList.add('domant2'); e.target.parentElement.parentElement.previousElementSibling.previousElementSibling.classList.remove('domant2'); e.target.parentElement.parentElement.previousElementSibling.previousElementSibling.classList.add('domant'); e.target.parentElement.parentElement.previousElementSibling.classList.remove('domant'); e.target.parentElement.parentElement.previousElementSibling.classList.add('active'); e.target.parentElement.parentElement.classList.remove('active'); e.target.parentElement.parentElement.classList.add('inactive'); } // Selection if(e.target.className == "seasons-lists"){ // console.log(e.target.textContent); let values = seasons.filter(season => season == e.target.textContent); // console.log(values); if(values.length == 0){ seasons.push(e.target.textContent); e.target.style.background = 'green'; } else { seasons = seasons.filter(season => season != e.target.textContent); e.target.style.background = '#333'; } } if(e.target.className == "episode-lists"){ // console.log(e.target.textContent); let values = episodes.filter(season => season == e.target.textContent); // console.log(values); if(values.length == 0){ episodes.push(e.target.textContent); e.target.style.background = 'green'; } else { episodes = episodes.filter(season => season != e.target.textContent); e.target.style.background = '#333'; } } if(e.target.id == 'btn-confirm'){ console.log( e.target.parentElement.parentElement.firstElementChild.attributes['value'].value) const title = e.target.parentElement.parentElement.firstElementChild.attributes['value'].value const thumnail_url = e.target.parentElement.parentElement.firstElementChild.nextElementSibling.attributes['value'].value const cart_data = { title, thumnail_url, episodes, seasons } if(localStorage.getItem('cart_data') != null) { const data = localStorage.getItem('cart_data'); let data2 = JSON.parse(data); data2.push(cart_data); const data3 = JSON.stringify(data2); localStorage.setItem('cart_data', data3); } else { let array = []; array.push(cart_data); const to_string = JSON.stringify(array); localStorage.setItem('cart_data', to_string); } if(seasons.length != 0 || episodes.length != 0){ addToCart(); } e.target.parentElement.previousElementSibling.previousElementSibling.previousElementSibling.classList.remove('domant3'); e.target.parentElement.previousElementSibling.previousElementSibling.previousElementSibling.classList.add('active'); e.target.parentElement.previousElementSibling.previousElementSibling.classList.remove('domant2'); e.target.parentElement.previousElementSibling.previousElementSibling.classList.add('inactive'); e.target.parentElement.previousElementSibling.classList.remove('domant'); e.target.parentElement.previousElementSibling.classList.add('inactive'); e.target.parentElement.classList.remove('active'); e.target.parentElement.classList.add('inactive'); } } function addToCart() { let data = JSON.parse(localStorage.getItem('cart_data')); const container = document.querySelector('.cart-items-container'); document.querySelector('.count-container').innerHTML = data.length; let content = `<a href="http://localhost/online_freedelivery_movies_series/Order_details.php" class="confirm-order-cart">Order</a>` data.forEach((obj, index) => { let tag = `<div class="each-item"> <div class="img-container"> <img class="img-container-a" src=${obj.thumnail_url} alt="NON"> <i id= ${index} class="far fa-trash-alt"></i> </div> <div> <p class="color-white">${obj.title}</p> <p class="color-white">${obj.seasons.toString()}</p> </div> </div>` content += tag }) container.innerHTML = content seasons = []; episodes = []; } <file_sep>/pretty.php <?php header('Access-Control-Allow-Origin: *'); header('Content-Type: application/json'); $yt_api = "<KEY>"; $channelId = "UC_x5XG1OV2P6uZZ5FSM9Ttw"; // Call for the videos // $ch = curl_init(); $yt_api_url = "https://www.googleapis.com/youtube/v3/search?key=$yt_api&channelId=$channelId&part=snippet,id&order=date&maxResults=20"; // curl_setopt($ch, CURLOPT_URL, $yt_api_url); // curl_setopt($ch, CURLOPT_HEADER, 0); // curl_exec($ch); // curl_close($ch); $yt_json = file_get_contents($yt_api_url); echo $yt_json;<file_sep>/models/user.php <?php class User { private $conn; private $table = 'users'; public $id; public $fName; public $lName; public $email; public $phoneNumber; public $password; public $town; public $street; public $building; // constructor with db public function __construct($db) { $this->conn = $db; } // Check if user exist public function checkEmail() { // query $query = 'SELECT * FROM ' . $this->table . ' WHERE email = :email'; // Prepare statements $stmt = $this->conn->prepare($query); // clean the data $this->email = htmlspecialchars(strip_tags($this->email)); // Bind data $stmt->bindParam(':email', $this->email); // Execute $stmt->execute(); if($stmt->rowCount() > 0) { return true; } else { return false; } } // Register user public function register() { // query $query = 'INSERT INTO ' . $this->table . ' SET fName = :fName, lName = :lName, email = :email, phoneNumber = :phoneNumber, password = <PASSWORD>, town = :town, street = :street, building = :building'; // Prepare statements $stmt = $this->conn->prepare($query); // Clean the data $this->fName = htmlspecialchars(strip_tags($this->fName)); $this->lName = htmlspecialchars(strip_tags($this->lName)); $this->email = htmlspecialchars(strip_tags($this->email)); $this->phoneNumber = htmlspecialchars(strip_tags($this->phoneNumber)); $this->password = htmlspecialchars(strip_tags($this->password)); $this->town = htmlspecialchars(strip_tags($this->town)); $this->street = htmlspecialchars(strip_tags($this->street)); $this->building = htmlspecialchars(strip_tags($this->building)); // Bind data $stmt->bindParam(':fName', $this->fName); $stmt->bindParam(':lName', $this->lName); $stmt->bindParam(':email', $this->email); $stmt->bindParam(':phoneNumber', $this->phoneNumber); $stmt->bindParam(':password', $<PASSWORD>-><PASSWORD>); $stmt->bindParam(':town', $this->town); $stmt->bindParam(':street', $this->street); $stmt->bindParam(':building', $this->building); // Execute if($stmt->execute()) { return true; } else { // error printf("Error: %s.\n", $stmt->error); return false; } } // Log in user function logIn() { $query = 'SELECT * FROM ' . $this->table . ' WHERE email=:email'; // Prepare statements $stmt = $this->conn->prepare($query); // Clean data $this->email = htmlspecialchars(strip_tags($this->email)); // Bind params $stmt->bindParam(':email', $this->email); $stmt->execute(); return $stmt; } }<file_sep>/user/register.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../css/style.css"> <script src="https://kit.fontawesome.com/be994c5cbf.js" crossorigin="anonymous"></script> <title>ScottMovies</title> </head> <body class="body-register"> <?php include ("../inc/navbar.php"); ?> <div class="background-register"> <div class="register-container"> <h2 class="register"><i class="fas fa-user-plus"></i> Register</h2> <div class="form-group-register-container"> <form method="POST" action="../auth/register.php" class="form-group-register"> <label class="fname">First Name *</label> <input class="fname-input <?php if(isset($_GET['fName'])) { echo empty($_GET['fName']) ? 'box-error' : '';} ?>" type="text" value="<?php if(isset($_GET['fName'])) { echo !empty($_GET['fName']) ? $_GET['fName'] : '';} ?>" name="fName" placeholder="Enter your first name"/> <?php if(isset($_GET['fName'])) { echo empty($_GET['fName']) ? '<p class="error-msg">* Must input first name</p>' : '';} ?> <label class="lname">Last Name *</label> <input class="lname-input <?php if(isset($_GET['lName'])) { echo empty($_GET['lName']) ? 'box-error' : '';} ?>" type="text" value="<?php if(isset($_GET['lName'])) { echo !empty($_GET['lName']) ? $_GET['lName'] : '';} ?>" name="lName" placeholder="Enter your last name"/> <?php if(isset($_GET['lName'])) { echo empty($_GET['lName']) ? '<p class="error-msg">* Must input last name</p>' : '';} ?> <div class="contacts-container"> <div class="contact-contianer"> <label class="email">Email *</label> <input class="email-input <?php if(isset($_GET['email'])) { echo empty($_GET['email']) ? 'box-error' : '';} ?><?php if(isset($_GET['email_error_msg'])) { echo 'box-error';} ?>" type="email" value="<?php if(isset($_GET['email'])) { echo !empty($_GET['email']) ? $_GET['email'] : '';} ?>" name="email" placeholder="Enter your email"/> <?php if(isset($_GET['email'])) { echo empty($_GET['email']) ? '<p class="error-msg">* Must input email</p>' : '';} ?> <?php if(isset($_GET['email_error_msg'])) { echo '<p class="error-msg">Email already exits</p>';} ?> </div> <div class="contact-contianer"> <label class="phone-number">Phone Number *</label> <input class="phone-input <?php if(isset($_GET['phoneNumber'])) { echo empty($_GET['phoneNumber']) ? 'box-error' : '';} ?>" type="text" value="<?php if(isset($_GET['phoneNumber'])) { echo !empty($_GET['phoneNumber']) ? $_GET['phoneNumber'] : '';} ?>" name="phoneNumber" placeholder="Enter mobile number"/> <?php if(isset($_GET['phoneNumber'])) { echo empty($_GET['phoneNumber']) ? '<p class="error-msg">* Must input phone number</p>' : '';} ?> </div> </div> <div class="passwords-container"> <div class="password-container"> <label class="password">Password *</label> <input class="password-input <?php if(isset($_GET['password'])) { echo empty($_GET['password']) ? 'box-error' : '';} ?>" type="password" value="" name="password" placeholder="Enter password"/> <?php if(isset($_GET['password'])) { echo empty($_GET['password']) ? '<p class="error-msg">* Must input password</p>' : '';} ?> </div> <div class="password-container"> <label class="password2"> confirm Password *</label> <input class="password2-input <?php if(isset($_GET['password2'])) { echo empty($_GET['password2']) ? 'box-error' : '';} if(isset($_GET['pwdmatcherror'])) { echo 'box-error';} ?>" type="password" value="" name="password2" placeholder="Confirm password"/> <?php if(isset($_GET['password2'])) { echo empty($_GET['password2']) ? '<p class="error-msg">* Must input confirm password</p>' : '';} ?> <?php if(isset($_GET['pwdmatcherror'])) { echo '<p class="error-msg">* Password don\'t match</p>';} ?> </div> </div> <label class="county">Town/Area</label> <input class="county-input" type="text" value="<?php if(isset($_GET['town'])) { echo !empty($_GET['town']) ? $_GET['town'] : '';} ?>" name="town" placeholder="Enter your current county"/> <label class="region">Street</label> <input class="region-input" type="text" value="<?php if(isset($_GET['street'])) { echo !empty($_GET['street']) ? $_GET['street'] : '';} ?>" name="street" placeholder="Enter your current region"/> <label class="street">Building & Room no</label> <input class="street-input" type="text" name="building" value="<?php if(isset($_GET['building'])) { echo !empty($_GET['building']) ? $_GET['building'] : '';} ?>" placeholder="e.g Annex - G5"/> <input type="submit" value="Sign Up" class="btn-submit" /> </form> <div class="links"> <a class="link" href="http://localhost/online_freedelivery_movies_series/user/login.php">Already have an account?</a> </div> </div> </div> </div> <script src="../js/register.js"></script> </body> </html><file_sep>/contact.php <?php include ('inc/header.php'); include ("inc/navbar.php"); ?> <body> </body> </html><file_sep>/js/video.js // video elements const add_to_cart_container = document.querySelector('.icon-add'); const episodes_container = document.querySelector('.select-episodes'); const season_container = document.querySelector('.select-season'); const confirm_container = document.querySelector('.confirm-order'); const add_to_cart_btn = document.querySelector('#add-to-cart-btn'); const season_forward_btn = document.querySelector('#foward-season-btn'); const episodes_forward_btn = document.querySelector('#foward-episodes-btn'); const episodes_backward_btn = document.querySelector('#backward-episodes-btn'); const confirm_backward_btn = document.querySelector('#confirm-backward-btn'); const confirm_btn = document.querySelector('.btn-confirm'); // Event Listeners add_to_cart_btn.addEventListener('click', seasonContainer); season_forward_btn.addEventListener('click', episodesContainer); episodes_backward_btn.addEventListener('click', backToSeasonContainer); episodes_forward_btn.addEventListener('click', confirmContainer); confirm_backward_btn.addEventListener('click', backToEpisodesContainer); confirm_btn.addEventListener('click', completeOrder); // Functions // Transitions function seasonContainer(e){ add_to_cart_container.classList.remove('active'); add_to_cart_container.classList.add('domant'); season_container.classList.remove('inactive'); season_container.classList.add('active'); } function episodesContainer(){ add_to_cart_container.classList.remove('domant'); add_to_cart_container.classList.add('domant2'); season_container.classList.remove('active'); season_container.classList.add('domant'); episodes_container.classList.remove('inactive'); episodes_container.classList.add('active'); } function backToSeasonContainer(){ add_to_cart_container.classList.remove('domant2'); add_to_cart_container.classList.add('domant'); season_container.classList.remove('domant'); season_container.classList.add('active'); episodes_container.classList.remove('active'); episodes_container.classList.add('inactive'); } function confirmContainer(){ add_to_cart_container.classList.remove('domant2'); add_to_cart_container.classList.add('domant3'); season_container.classList.remove('domant'); season_container.classList.add('domant2'); episodes_container.classList.remove('active'); episodes_container.classList.add('domant'); confirm_container.classList.remove('inactive'); confirm_container.classList.add('active'); } function backToEpisodesContainer(){ add_to_cart_container.classList.remove('domant3'); add_to_cart_container.classList.add('domant2'); season_container.classList.remove('domant2'); season_container.classList.add('domant'); episodes_container.classList.remove('domant'); episodes_container.classList.add('active'); confirm_container.classList.remove('active'); confirm_container.classList.add('inactive'); } // Selection // const add_to_cart_container = document.querySelector('.icon-add'); // const episodes_container = document.querySelector('.select-episodes'); // const season_container = document.querySelector('.select-season'); // const confirm_container = document.querySelector('.confirm-order'); // EventListeners season_container.addEventListener('click', seasonSelection) episodes_container.addEventListener('click', episodeSelection) // Functions // let object = { // S01: ["E01","E02","E03","E04","E05","E06"], // S02: ["E01","E02","E03","E04","E05","E06"], // S03: ["E01","E02","E03","E04","E05","E06"], // S04: ["E01","E02","E03","E04","E05","E06"], // S05: ["E01","E02","E03","E04","E05","E06"], // S06: ["E01","E02","E03","E04","E05","E06"], // S07: ["E01","E02","E03","E04","E05","E06"], // S08: ["E01","E02","E03","E04","E05","E06"], // S09: ["E01","E02","E03","E04","E05","E06"], // S10: ["E01","E02","E03","E04","E05","E06"] // } let seasons = []; function seasonSelection(e){ if(e.target.tagName == "LI"){ // console.log(e.target.textContent); let values = seasons.filter(season => season == e.target.textContent); // console.log(values); if(values.length == 0){ seasons.push(e.target.textContent); e.target.style.background = 'green'; } else { seasons = seasons.filter(season => season != e.target.textContent); e.target.style.background = '#333'; } } // const filtered = Object.keys(object) // .filter(key => seasons.includes(key)) // .reduce((obj, key) => { // obj[key] = object[key]; // return obj; // }, {}); // console.log(filtered); } let episodes = []; function episodeSelection(e){ if(e.target.tagName == "LI"){ // console.log(e.target.textContent); let values = episodes.filter(season => season == e.target.textContent); // console.log(values); if(values.length == 0){ episodes.push(e.target.textContent); e.target.style.background = 'green'; } else { episodes = episodes.filter(season => season != e.target.textContent); e.target.style.background = '#333'; } } // const filtered = Object.keys(object) // .filter(key => episodes.includes(key)) // .reduce((obj, key) => { // obj[key] = object[key]; // return obj; // }, {}); // console.log(filtered); } function completeOrder(){ const title = document.querySelector('#title-video').value const thumnail_url = document.querySelector('#thumnail-video').value const cart_data = { title, thumnail_url, episodes, seasons } if(localStorage.getItem('cart_data') != null) { const data = localStorage.getItem('cart_data'); let data2 = JSON.parse(data); data2.push(cart_data); const data3 = JSON.stringify(data2); localStorage.setItem('cart_data', data3); } else { let array = []; array.push(cart_data); const to_string = JSON.stringify(array); localStorage.setItem('cart_data', to_string); } if(seasons.length != 0 || episodes.length != 0){ addToCart(); } add_to_cart_container.classList.remove('domant3'); add_to_cart_container.classList.add('active'); season_container.classList.remove('domant2'); season_container.classList.add('inactive'); episodes_container.classList.remove('domant'); episodes_container.classList.add('inactive'); confirm_container.classList.remove('active'); confirm_container.classList.add('inactive'); } function addToCart() { let data = JSON.parse(localStorage.getItem('cart_data')); const container = document.querySelector('.cart-items-container'); document.querySelector('.count-container').innerHTML = data.length; let content = `` data.forEach((obj, index) => { let tag = `<div class="each-item"> <div class="img-container"> <img class="img-container-a" src=${obj.thumnail_url} alt="NON"> <i id= ${index} class="far fa-trash-alt"></i> </div> <div> <p class="color-white">${obj.title}</p> <p class="color-white">${obj.seasons.toString()}</p> </div> </div>` content += tag }) container.innerHTML = content seasons = []; episodes = []; } // let keys = document.querySelectorAll('.seasons-list'); // // console.log(Array.from(keys)); // keys = Array.from(keys).map(key => key.textContent); // let properties = []; // let arrays = document.querySelectorAll('.episodes-lists'); // arrays.forEach(array => { // properties.push(Array.from(array.children).map(child => child.textContent)); // }) // // console.log(properties) // let object = {}; // for(const key of keys) { // properties.forEach(property => { // object[key] = property // }); // } // console.log(object) <file_sep>/apis/category_trailers.php <?php // Headers header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods,Authorization,X-Requested-With'); // Get the channel data // UCRg_lFHDC6WXQnXG7S9anxA // UC_x5XG1OV2P6uZZ5FSM9Ttw // UCbGvldOvvO89dit8MqVRnzQ $yt_api = "<KEY>"; $channelId = "UC_x5XG1OV2P6uZZ5FSM9Ttw"; $videos = new stdClass(); if(isset($_GET['playlist'])){ $playlist_id = $_GET['playlist']; $api_url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=20&playlistId=$playlist_id&key=$yt_api"; $playlist = file_get_contents($api_url); if($playlist) { session_start(); $_SESSION['object'] = $playlist; $videos = json_decode($playlist); } else { $videos = array('msg'=>'No contents'); } } <file_sep>/apis/all_trailers.php <?php // Headers header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods,Authorization,X-Requested-With'); // Get the channel data // UCRg_lFHDC6WXQnXG7S9anxA // UC_x5XG1OV2P6uZZ5FSM9Ttw // UCbGvldOvvO89dit8MqVRnzQ $yt_api = "<KEY>"; $channelId = "UC_x5XG1OV2P6uZZ5FSM9Ttw"; // Call for the videos // $ch = curl_init(); $yt_api_url = "https://www.googleapis.com/youtube/v3/search?key=$yt_api&channelId=$channelId&part=snippet,id&order=date&maxResults=20"; // curl_setopt($ch, CURLOPT_URL, $yt_api_url); // curl_setopt($ch, CURLOPT_HEADER, 0); // curl_exec($ch); // curl_close($ch); $yt_json = file_get_contents($yt_api_url); if($yt_api) { session_start(); $_SESSION['object'] = $yt_json; $videos = json_decode($yt_json); } else { $videos = array('msg'=>'No contents'); } // var_dump($videos->items); // session_start(); // $_SESSION['object'] = $yt_json; // echo $yt_json; // Next page call // if(isset($_GET['page'])){ // $yt_next_api = "https://www.googleapis.com/youtube/v3/search?pageToken=CBkQAA&part=snippet&maxResults=25&order=relevance&q=site%3Ayoutube.com&topicId=%2Fm%2F02vx4&key={YOUR_API_KEY}"; // $yt_json = file_get_contents($yt_next_api); // echo $yt_json; // } <file_sep>/js/register.js const fname = document.querySelector('.fname-input'); const lname = document.querySelector('.lname-input'); const email = document.querySelector('.email-input'); const phone = document.querySelector('.phone-input'); const password = document.querySelector('.password-input'); const password2 = document.querySelector('.password2-input'); // event listeners fname.addEventListener('input', removeClass); lname.addEventListener('input', removeClass); email.addEventListener('input', removeClass); phone.addEventListener('input', removeClass); password.addEventListener('input', removeClass); password2.addEventListener('input', removeClass); // function function removeClass(e) { e.preventDefault() e.target.classList.remove('box-error'); if(e.target.nextElementSibling.className == 'error-msg') { e.target.nextElementSibling.classList.add('domant-msg'); } } <file_sep>/js/nav_cart2.js // Dom Elements const cart_active = document.querySelector('.cart-active'); const cart_items_container = document.querySelector('.cart-items-container'); const show_videos = document.querySelector('.trailers-container'); const body = document; // Event listners // cart_active.addEventListener('change', cartActivate); body.addEventListener('click', cartActivateDeactivate); // Cart deactivate function cartActivateDeactivate(e) { if(e.target.checked || e.target.className == 'cart-items-container active' || e.target.className == 'each-item' || e.target.className == 'img-container' || e.target.className == 'img-container-a' || e.target.className == 'far fa-trash-alt' || e.target.className == 'color-white'){ cart_items_container.classList.remove('domant'); cart_items_container.classList.add('active'); }else { cart_items_container.classList.remove('active'); cart_items_container.classList.add('domant'); cart_active.checked = false; } if(e.target.className == 'far fa-trash-alt') { console.log(e.target.id); const data = JSON.parse(localStorage.getItem('cart_data')); const filtered = data.filter((array, index) => { if(index != e.target.id){ return array; } }) const string = JSON.stringify(filtered); localStorage.setItem('cart_data', string); addToCart() } } window.onload = addToCart(); function addToCart() { if(localStorage.getItem('cart_data') != null) { let data = JSON.parse(localStorage.getItem('cart_data')); const container = document.querySelector('.cart-items-container2'); document.querySelector('.count-container').innerHTML = data.length; let content = `` data.forEach((obj, index) => { let tag = `<div class="each-item"> <div class="img-container"> <img class="img-container-a" src=${obj.thumnail_url} alt="NON"> <i id= ${index} class="far fa-trash-alt"></i> </div> <div> <p class="color-white">${obj.title}</p> <p class="color-white">${obj.seasons.toString()}</p> </div> </div>` content += tag }) container.innerHTML = content } } // Drop down if(document.querySelector('#list') != null) { const btn = document.querySelector('#drop-down-index'); const drop = document.querySelector('#list'); document.addEventListener('click', activateDeactivateDropdown); function activateDeactivateDropdown(e) { console.log(drop.className) if(e.target.className == 'fas fa-caret-down domant') { btn.classList.remove('domant'); btn.classList.add('active'); drop.classList.remove('domant'); drop.classList.add('active'); }else { btn.classList.remove('active'); btn.classList.add('domant'); drop.classList.remove('active'); drop.classList.add('domant'); } } } <file_sep>/js/main.js const btn = document.querySelector('#drop-down-index'); const drop = document.querySelector('#list'); document.addEventListener('click', activateDeactivateDropdown); function activateDeactivateDropdown(e) { if(e.target.className == 'fas fa-caret-down domant') { e.target.classList.remove('domant'); e.target.classList.add('active'); drop.classList.remove('domant'); drop.classList.add('active'); }else { btn.classList.remove('active'); btn.classList.add('domant'); drop.classList.remove('active'); drop.classList.add('domant'); } } document.querySelector('.cancel').addEventListener('click', remove); function remove(){ document.querySelector('.cancel').parentElement.classList.add('remove'); } <file_sep>/auth/register.php <?php header('Access-Control-Allow-Origin: *'); header('Access-control-Allow-Methods: POST'); header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods,Authorization,X-Requested-With'); require_once '../models/user.php'; require_once '../config/Database.php'; // Instatiate DB and connect to DB $database = new Database(); $db = $database->connect(); // Instantiate the user class $user = new User($db); // Get the data form the form $fName = !empty($_POST['fName']) ? $_POST['fName'] : ''; $lName = !empty($_POST['lName']) ? $_POST['lName'] : ''; $email = !empty($_POST['email']) ? $_POST['email'] : ''; $phoneNumber = !empty($_POST['phoneNumber']) ? $_POST['phoneNumber'] : ''; $password = !empty($_POST['password']) ? true : ''; $password2 = !empty($_POST['password2']) ? true : ''; $town = !empty($_POST['town']) ? $_POST['town'] : ''; $street = !empty($_POST['street']) ? $_POST['street'] : ''; $building = !empty($_POST['building']) ? $_POST['building'] : ''; if(empty($_POST['fName']) || empty($_POST['lName']) || empty($_POST['email']) || empty($_POST['phoneNumber']) || empty($_POST['password']) || empty($_POST['password2'])){ header('Location: http://localhost/online_freedelivery_movies_series/user/register.php?' . 'fName=' . $fName . '&lName=' . $lName . '&email=' . $email . '&phoneNumber=' . $phoneNumber . '&password=' . $password . '&password2=' . $password2 . '&town=' . $town . '&street=' . $street . '&building=' . $building); die(); } if($_POST['password'] !== $_POST['password2']) { header('Location: http://localhost/online_freedelivery_movies_series/user/register.php?' . 'fName=' . $fName . '&lName=' . $lName . '&email=' . $email . '&phoneNumber=' . $phoneNumber . '&password=' . $<PASSWORD> . '&password2=' . $<PASSWORD> . '&town=' . $town . '&street=' . $street . '&building=' . $building . '&pwdmatcherror=1'); die(); } $hashPassword = password_hash($_POST['password'], PASSWORD_DEFAULT); $user->fName = $fName; $user->lName = $lName; $user->email = $email; $user->phoneNumber = $phoneNumber; $user->password = $<PASSWORD>; $user->town = $town; $user->street = $street; $user->building = $building; if($user->checkEmail()) { header('Location: http://localhost/online_freedelivery_movies_series/user/register.php?' . 'fName=' . $fName . '&lName=' . $lName . '&email=' . $email . '&phoneNumber=' . $phoneNumber . '&password=' . $<PASSWORD> . '&password2=' . $<PASSWORD> . '&town=' . $town . '&street=' . $street . '&building=' . $building . '&msg=registration_failed&email_error_msg=exits'); die(); } if($user->register()) { header('Location: http://localhost/online_freedelivery_movies_series/user/login.php?registration_msg=success'); } else { header('Location: http://localhost/online_freedelivery_movies_series/user/register.php?' . 'fName=' . $fName . '&lName=' . $lName . '&email=' . $email . '&phoneNumber=' . $phoneNumber . '&password=' . $password . '&password2=' . $<PASSWORD> . '&town=' . $town . '&street=' . $street . '&building=' . $building . '&msg=registration_failed'); }<file_sep>/order.php <?php session_start(); ?> <?php if($_SESSION['verified']){ ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./css/style.css"> <script src="https://kit.fontawesome.com/be994c5cbf.js" crossorigin="anonymous"></script> <title>OrderMovies</title> </head> <body class=""> <?php include ("inc/navbar.php"); // include ("inc/searchbar.php"); ?> <div class="body-order"> <div class="order-container"> <h1 class="order-title">Order confirmation</h1> <form> <label class="location-lable">Delivery Address(edit if required)</label> <div class="order-input-container"> <input type="text" id="location" class="location-input" value="<?php echo $_SESSION['street'] . ' - ' . $_SESSION['building'] ; ?>"/> </div> <label class="location-lable">Phone Number(edit if required)</label> <div class="order-input-container"> <input type="text" id="phone" class="location-input" name="phone_number" value="<?php echo $_SESSION['phone_number']; ?>" /> </div> <div id="items-container"> </div> <label class="method-payment-lable">Method of Payment</label> <div> <select name="payment_method" class="order-select-payment" > <option value="M-pesa">M-pesa</option> <option value="Pay on Delivery">Pay on Delivery</option> </select> <input id="m_pesa_code" type="text" placeholder="Enter M-pesa payment code" /> </div> <input type="hidden" id="user_id" value="<?php echo $_SESSION['user_id']; ?>"> <input type="submit" class="place-order" value="Place your order" /> </form> </div> <!-- <div class="model-container"> <div class={`model`}> <h3 class="model-title">Select Your New Delivery Location</h3> <label class="order-region-lable">County</label> <div> <select name="county" class="order-select-location" > <option value="Nakuru">Nakuru</option> <option value="Muran'ga">Muran'ga</option> </select> </div> <label class="order-region-lable">Region</label> <div> <select name="region" class="order-select-location" > <option value="Gilgil">Gilgil</option> <option value="Mukuyu">Mukuyu</option> </select> </div> <label class="order-region-lable">Street</label> <div> <select name="street" class="order-select-location" > <option value="G.T.I">G.T.I</option> <option value="Mukuyu town">Mukuyu Town</option> </select> </div> <div class="btn-container-order"> <button class="btn-order-location-change" >Change</button> <button class="btn-order-location-change" >Cancel</button> </div> </div> </div> --> </div> <!-- <script src="js/main.js"></script> --> <script src="js/nav_cart2.js"></script> <script src="js/order.js"></script> </body> </html> <?php } else { header('Location:http://localhost/online_freedelivery_movies_series/user/login.php'); } <file_sep>/models/item.php <?php class ITEM { private $conn; private $table = 'ordered_items'; public $item_id; public $user_id; public $phone_number; public $area; public $item_name; public $seasons; public $episodes; public $price; public $paid; public $deliverd; public $date_delivered; public $mpesa_code; // constructor with db public function __construct($db) { $this->conn = $db; } // Register user public function orderedItems() { // query $query = 'INSERT INTO ' . $this->table . ' SET user_id = :user_id, phone_number = :phone_number, area = :area, item_name = :item_name, seasons = :seasons, episodes = :episodes, mpesa_code = :mpesa_code, price = :price'; // Prepare statements $stmt = $this->conn->prepare($query); // Clean the data $this->user_id = htmlspecialchars(strip_tags($this->user_id)); $this->phone_number = htmlspecialchars(strip_tags($this->phone_number)); $this->area = htmlspecialchars(strip_tags($this->area)); $this->item_name = htmlspecialchars(strip_tags($this->item_name)); $this->seasons = htmlspecialchars(strip_tags($this->seasons)); $this->episodes = htmlspecialchars(strip_tags($this->episodes)); $this->mpesa_code = htmlspecialchars(strip_tags($this->mpesa_code)); $this->price = htmlspecialchars(strip_tags($this->price)); // Bind data $stmt->bindParam(':user_id', $this->user_id); $stmt->bindParam(':phone_number', $this->phone_number); $stmt->bindParam(':area', $this->area); $stmt->bindParam(':item_name', $this->item_name); $stmt->bindParam(':seasons', $this->seasons); $stmt->bindParam(':episodes', $this->episodes); $stmt->bindParam(':mpesa_code', $this->mpesa_code); $stmt->bindParam(':price', $this->price); // Execute if($stmt->execute()) { return true; } else { // error printf("Error: %s.\n", $stmt->error); return false; } } }<file_sep>/config/keys.php <?php // Get the channel data // UCRg_lFHDC6WXQnXG7S9anxA // UC_x5XG1OV2P6uZZ5FSM9Ttw // UCbGvldOvvO89dit8MqVRnzQ $yt_api = "<KEY>"; $channelId = "UC_x5XG1OV2P6uZZ5FSM9Ttw";<file_sep>/index.php <?php session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./css/style.css"> <script src="https://kit.fontawesome.com/be994c5cbf.js" crossorigin="anonymous"></script> <title>ScottMovies</title> </head> <body class=""> <div class="container-index"> <?php if(isset($_GET['msg'])){ ?> <div class="confirm-msg"> <span class="cancel">X</span> YOUR ORDER HAS BEEN SUCCESSFULLY PLACED, WE WILL GET BACK TO YOU REGARDING THE DELIVERY. THANK YOU FOR SHOPPING WITH US</div> <?php }?> <div class="cover"> <div class="logo-index"> <p class="logo-title-index">JeffMovies</p> </div> <div class="user-known"> <div class="loggers-btn-index"> <?php if(isset($_SESSION['verified'])) {?> <p class="user">Welcome <?php echo $_SESSION['user_name']; ?><i id="drop-down-index" class="fas fa-caret-down domant"></i></p> <div id="list" class="options domant"> <a href="#">Profile</a> <a href="#">Favorites</a> <a href="http://localhost/online_freedelivery_movies_series/auth/logout.php?sign_out=1">Log Out</a> </div> <?php }else { ?> <a class="sign-in-btn-index" href="http://localhost/online_freedelivery_movies_series/user/login.php">Log In</a> <span >|</span> <a class="register-btn-index" href="http://localhost/online_freedelivery_movies_series/user/register.php">Register</a> <?php } ?> </div> </div> <div class="video-container-index"> <iframe class="iframe-more-details\" src="https://www.youtube.com/embed/-jtZB-CsE3s?rel=0&controls=0&autoplay=1&loop=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> <div class="links-landing-page"> <a href="all_trailers.php">Trailers</a> <a href="http://localhost/online_freedelivery_movies_series/movies_trailers.php?playlist_name=all_movies&playlist=PL3kx5h2TrYGweGaJ7yoHBtil5dnlhn6nK">Movies Trailers</a> <a href="http://localhost/online_freedelivery_movies_series/series_trailers.php?playlist_name=all_series&playlist=PL3kx5h2TrYGweGaJ7yoHBtil5dnlhn6nK">Series Trailers</a> </div> </div> </div> <div class="about-section"> </div> <script src="js/main.js"></script> </body> </html> <file_sep>/video.php <?php session_start(); $video_data = json_decode($_SESSION['object'])->items; if(isset($_GET['videoid'])){ function compare($var){ $id = $_GET['videoid']; if(isset($var->id->videoId)){ return($var->id->videoId == $id); } } $details = array_filter($video_data, "compare"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./css/style.css"> <script src="https://kit.fontawesome.com/be994c5cbf.js" crossorigin="anonymous"></script> <title>ScottMovies</title> </head> <body class="main"> <body class="more-details"> <?php include ("inc/navbar.php"); ?> <body> <div class="video-more-details-container"> <div> <div class="viewer-details"> <a class="here" href="#here">Make an Order</a> <?php echo "<iframe class=\"iframe-more-details\" src=\"https://www.youtube.com/embed/".$_GET['videoid']."\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>"; ?> </div> <div class="description-container"> <?php foreach($details as $detail): ?> <h4><?php echo $detail->snippet->title;?></h4> <p><?php echo $detail->snippet->description;?></p> <input id="title-video" type="hidden" value="<?php echo $detail->snippet->title?>"> <input id="thumnail-video" type="hidden" value="<?php echo $detail->snippet->thumbnails->default->url?>"> <?php endforeach; ?> </div> <div class="seasons"> <ul> <li>Season 2 | <span>Episodes: 20</span></li> <li>Season 1 | <span>Episodes: 20</span></li> <li>Season 3 | <span>Episodes: 20</span></li> <li>Season 4 | <span>Episodes: 20</span></li> <li>Season 5 | <span>Episodes: 20</span></li> <li>Season 6 | <span>Episodes: 20</span></li> <li>Season 7 | <span>Episodes: 20</span></li> <li>Season 8 | <span>Episodes: 20</span></li> <li>Season 9 | <span>Episodes: 20</span></li> <li>Season 10 | <span>Episodes: 20</span></li> <li>Season 11 | <span>Episodes: 20</span></li> </ul> </div> </div> <div id="here" class="add-to-cart"> <div id="add-to-cart-btn" class="icon-add active"> <p>Click To Place Order</p> <i class="fas fa-film"></i> <i class="fas fa-plus"></i> </div> <div class="select-season inactive"> <p>Select the Seasons</p> <ul id="seasons-list"> <li>S01</li> <li>S02</li> <li>S03</li> <li>S04</li> <li>S05</li> </ul> <p><i id="foward-season-btn" class="fas fa-chevron-right"></i></p> </div> <div id="episodes-container" class="select-episodes inactive"> <p class="seasons-list">S01</p> <ul class="episodes-lists"> <li>S01E01</li> <li>S01E02</li> <li>S01E03</li> <li>S01E04</li> <li>S01E05</li> </ul> <p class="seasons-list">S02</p> <ul class="episodes-lists"> <li>S02E01</li> <li>S02E02</li> <li>S02E03</li> <li>S02E04</li> <li>S02E05</li> <li>S02E06</li> <li>S02E07</li> <li>S02E08</li> <li>S02E09</li> <li>S02E10</li> </ul> <p class="seasons-list">S03</p> <ul class="episodes-lists"> <li>S03E01</li> <li>S03E02</li> <li>S03E03</li> <li>S03E04</li> <li>S03E05</li> <li>S03E06</li> <li>S03E07</li> <li>S03E08</li> <li>S03E09</li> <li>S03E10</li> </ul> <p class="seasons-list">S04</p> <ul class="episodes-lists"> <li>S04E01</li> <li>S04E02</li> <li>S04E03</li> <li>S04E04</li> <li>S04E05</li> <li>S04E06</li> <li>S04E07</li> <li>S04E08</li> <li>S04E09</li> <li>S04E10</li> </ul> <p class="seasons-list">S05</p> <ul class="episodes-lists"> <li>S05E01</li> <li>S05E02</li> <li>S05E03</li> <li>S05E04</li> <li>S05E05</li> <li>S05E06</li> </ul> <p><i id="backward-episodes-btn" class="fas fa-chevron-left"></i><i id="foward-episodes-btn" class="fas fa-chevron-right"></i></p> </div> <div class="confirm-order inactive"> <button class="btn-confirm">Confirm</button> <button class="btn-view">View Order</button> <p><i id="confirm-backward-btn" class="fas fa-chevron-left"></i></p> </div> </div> </div> <script src="js/video.js"></script> <script src="js/nav_cart2.js"></script> </body> </html> <file_sep>/inc/navbar.php <nav class="nav-bar"> <h1 id="logo-text"><a href="/">JeffMovies</a></h1> <ul class="nav-links"> <li class="nav-link"><a href="http://localhost/online_freedelivery_movies_series/index.php">Home</a></li> <li class="nav-link"><a href="http://localhost/online_freedelivery_movies_series/index.php#about">About</a></li> <li class="nav-link"><a href="http://localhost/online_freedelivery_movies_series/index.php#contact">Contact</a></li> </ul> <!-- <div class="loggers-btn"> <a href="http://localhost/online_freedelivery_movies_series/user/login.php" class="btn" id="login">Log In</a> <a href="http://localhost/online_freedelivery_movies_series/user/register.php" class="btn" id="register">Register</a> <a href="user/logout.php" class="btn" id="logout">Log Out</a> </div> --> <div class="loggers-btn"> <?php if(isset($_SESSION['verified'])) {?> <p class="user-nav">Welcome <?php echo $_SESSION['user_name']; ?><i id="drop-down-index" class="fas fa-caret-down domant"></i></p> <div id="list" class="options-nav domant"> <a href="#">Profile</a> <a href="#">Favorites</a> <a href="http://localhost/online_freedelivery_movies_series/auth/logout.php?sign_out=1">Log Out</a> </div> <?php }else { ?> <a class="sign-in-btn-index" href="http://localhost/online_freedelivery_movies_series/user/login.php">Log In</a> <span >|</span> <a class="register-btn-index" href="http://localhost/online_freedelivery_movies_series/user/register.php">Register</a> <?php } ?> </div> <div class="cart-icon"> <div class="cart-container"> <i class="fas fa-film"></i> <span class="count-container">0</span> <input type="checkbox" class="cart-active"> </div> <div class="cart-items-container domant"> <div class="cart-items-container2"></div> <a href="http://localhost/online_freedelivery_movies_series/order.php" class="confirm-order-cart">Order</a> </div> </div> </nav> <file_sep>/auth/logout.php <?php if(isset($_GET['sign_out'])){ session_start(); session_destroy(); header('Location: http://localhost/online_freedelivery_movies_series/index.php'); } else { header('Location: http://localhost/online_freedelivery_movies_series/index.php'); }<file_sep>/series_trailers.php <?php require_once './apis/category_trailers.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./css/style.css"> <script src="https://kit.fontawesome.com/be994c5cbf.js" crossorigin="anonymous"></script> <title>ScottMovies</title> </head> <body class="main"> <?php include ("inc/navbar.php"); include ("inc/searchbar.php"); ?> <div class="container"> <div class="categories-container"> <ul class="categories-list"> <li><h1 class="title-cat" href="index.php">Series</h1></li> <li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?playlist_name=all_series&playlist=PL3kx5h2TrYGweGaJ7yoHBtil5dnlhn6nK">All</a></li> <li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?playlist_name=action&playlist=PL3kx5h2TrYGweGaJ7yoHBtil5dnlhn6nK">Action</a></li> <li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?playlist_name=animation&playlist=lMtP-vxyE-A&list=PLBDA074E6B463154D">Animation</a></li> <li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?playlist_name=drama&playlist=PLCDWgWmd8TqAQQ5hPtfmWuyls-tUl5EJd">Drama</a></li> <li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?playlist_name=sci-fi&playlist=playlist=PLSBlhbfM-l3t5iuu_3GJ39nwwc-fBqRoW">SC-FI</a></li> <li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?playlist_name=horror&playlist=playlist=3Y9XeruN5RY&list=PLriZt3RmcI33ZsErogMXngeeT7Mwq1FNe">Horror</a></li> <li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?playlist_name=thriller&playlist=playlist=PLelK7aEMtfK2wpv7tv472alrDpNwO_0jw">Thriller</a></li> </ul> </div> <div class="trailers-container"> <?php foreach($videos->items as $video):?> <div class="video"> <input id="title-video" type="hidden" value="<?php echo $video->snippet->title?>"> <input id="thumnail-video" type="hidden" value="<?php echo $video->snippet->thumbnails->default->url?>"> <iframe width="250" height="200" src="https://www.youtube.com/embed/<?php echo $video->id->videoId; ?>" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <p class="video-title"><?php echo $video->snippet->title; ?></p> <a href="video.php?videoid=<?php echo $video->id->videoId; ?>" class="link-class">More Details | Make Order</a> <!--add to Cart --> <div class="icon-add-main active"> <i id="add-to-cart-btn" class="fas fa-cart-plus"></i> <span id="add-to-cart-btn">Add to cart</span> </div> <div class="select-season inactive"> <p>Select the Seasons</p> <ul id="seasons-list"> <li class="seasons-lists">S01</li> <li class="seasons-lists">S02</li> <li class="seasons-lists">S03</li> <li class="seasons-lists">S04</li> <li class="seasons-lists">S05</li> <li class="seasons-lists">S06</li> <li class="seasons-lists">S07</li> <li class="seasons-lists">S08</li> <li class="seasons-lists">S09</li> <li class="seasons-lists">S10</li> </ul> <p><i id="foward-season-btn" class="fas fa-chevron-right"></i></p> </div> <div class="select-episodes inactive"> <p>S01</p> <ul> <li class="episode-lists">S01E01</li> <li class="episode-lists">S01E02</li> <li class="episode-lists">S01E03</li> <li class="episode-lists">S01E04</li> <li class="episode-lists">S01E05</li> <li class="episode-lists">S01E06</li> <li class="episode-lists">S01E07</li> <li class="episode-lists">S01E08</li> <li class="episode-lists">S01E09</li> <li class="episode-lists">S01E10</li> </ul> <p>S02</p> <ul> <li class="episode-lists">S02E01</li> <li class="episode-lists">S02E02</li> <li class="episode-lists">S02E03</li> <li class="episode-lists">S02E04</li> <li class="episode-lists">S02E05</li> <li class="episode-lists">S02E06</li> <li class="episode-lists">S02E07</li> <li class="episode-lists">S02E08</li> <li class="episode-lists">S02E09</li> <li class="episode-lists">S02E10</li> </ul> <p>S03</p> <ul> <li class="episode-lists">S03E01</li> <li class="episode-lists">S03E02</li> <li class="episode-lists">S03E03</li> <li class="episode-lists">S03E04</li> <li class="episode-lists">S03E05</li> <li class="episode-lists">S03E06</li> <li class="episode-lists">S03E07</li> <li class="episode-lists">S03E08</li> <li class="episode-lists">S03E09</li> <li class="episode-lists">S03E10</li> </ul> <p>S04</p> <ul> <li class="episode-lists">S04E01</li> <li class="episode-lists">S04E02</li> <li class="episode-lists">S04E03</li> <li class="episode-lists">S04E04</li> <li class="episode-lists">S04E05</li> <li class="episode-lists">S04E06</li> <li class="episode-lists">S04E07</li> <li class="episode-lists">S04E08</li> <li class="episode-lists">S04E09</li> <li class="episode-lists">S04E10</li> </ul> <p>S05</p> <ul> <li class="episode-lists">S05E01</li> <li class="episode-lists">S05E02</li> <li class="episode-lists">S05E03</li> <li class="episode-lists">S05E04</li> <li class="episode-lists">S05E05</li> <li class="episode-lists"S05>E06</li> <li class="episode-lists">S05E07</li> <li class="episode-lists">S05E08</li> <li class="episode-lists">S05E09</li> <li class="episode-lists">S05E10</li> </ul> <p><i id="backward-episodes-btn" class="fas fa-chevron-left"></i><i id="foward-episodes-btn" class="fas fa-chevron-right"></i></p> </div> <div class="confirm-order inactive"> <button id='btn-confirm' class="btn-confirm">Confirm</button> <button class="btn-view">View Order</button> <p><i id="confirm-backward-btn" class="fas fa-chevron-left"></i></p> </div> </div> <?php endforeach;?> </div> <div class="pagination-container"> <button class="more-videos" id="20">More Trailers <br><i class="fas fa-chevron-circle-down"></i></button> <!-- <p class="back"><i class="fas fa-arrow-left"></i></p> <p class="forward"><i class="fas fa-arrow-right"></i></p> --> </div> </div> <body> <!-- <script src="js/main.js"></script> --> <script src="js/nav_cart2.js"></script> <script src="js/main_cart.js"></script> </body> </html> <file_sep>/user/login.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../css/style.css"> <script src="https://kit.fontawesome.com/be994c5cbf.js" crossorigin="anonymous"></script> <title>ScottMovies</title> </head> <body class="body-login"> <?php include ("../inc/navbar.php"); ?> <div class="background-login"> <div class="login-container"> <h2 class="login"><i class="fas fa-sign-in-alt"></i> Sign in</h2> <p id="success-msg" class="<?php if(isset($_GET['registration_msg'])) { echo 'success-msg';} ?>"><?php if(isset($_GET['registration_msg'])) { echo 'Account successfully created!';} ?></p> <p id="error-msg-login" class="<?php if(isset($_GET['null_fields'])) { echo 'error-msg-login';} ?>"><?php if(isset($_GET['null_fields'])) { echo 'Fill All Fields!';} ?></p> <p id="error-msg-login2" class="<?php if(isset($_GET['email_error_msg'])) { echo 'error-msg-login';} ?>"><?php if(isset($_GET['email_error_msg'])) { echo 'Email Does not Exist!';} ?></p> <p id="error-msg-login3" class="<?php if(isset($_GET['password_error'])) { echo 'error-msg-login';} ?>"><?php if(isset($_GET['password_error'])) { echo 'Wrong Password!';} ?></p> <form method="POST" action="../auth/login.php" class="form-group-login"> <label class="email">Email</label> <input class="email-input" type="email" value="<?php if(isset($_GET['email'])) { echo !empty($_GET['email']) ? $_GET['email'] : '';} ?>" name="email" placeholder="Enter your email" /> <label class="password">Password</label> <input class="password-input" type="<PASSWORD>" value="" name="password" placeholder="<PASSWORD> password" /> <input type="submit" value="Log in" class="btn-submit" /> </form> <div class="links"> <a class="link" href="http://localhost/online_freedelivery_movies_series/user/register.php">Don't have an account?</a> </div> </div> </div> <script src="../js/login.js"></script> </body> </html><file_sep>/auth/login.php <?php header('Access-Control-Allow-Origin: *'); header('Access-control-Allow-Methods: POST'); header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods,Authorization,X-Requested-With'); require_once '../models/user.php'; require_once '../config/Database.php'; // Instatiate DB and connect to DB $database = new Database(); $db = $database->connect(); // Instantiate the user class $user = new User($db); // Get user data // Get the data form the form $email = htmlspecialchars(!empty($_POST['email']) ? $_POST['email'] : ''); $password = htmlspecialchars(!empty($_POST['password']) ? $_POST['password'] : ''); // Check if user has input all fields if(empty($_POST['email']) || empty($_POST['password'])) { header('Location: http://localhost/online_freedelivery_movies_series/user/login.php?email=' . $email . '&null_fields=1'); die(); } // Check if the user exists $user->email = $email; if(!$user->checkEmail()) { header('Location: http://localhost/online_freedelivery_movies_series/user/login.php?email=' . $email . '&email_error_msg=does_not_exist'); die(); } // Verify user $data = $user->logIn(); $row = $data->fetch(PDO::FETCH_ASSOC); if(password_verify($password, $row['password'])) { session_start(); $_SESSION['verified'] = true; $_SESSION['user_id'] = $row['id']; $_SESSION['user_name'] = $row['lName']; $_SESSION['street'] = $row['street']; $_SESSION['building'] = $row['building']; $_SESSION['phone_number'] = $row['phoneNumber']; header('Location: http://localhost/online_freedelivery_movies_series/index.php'); die(); } else { header('Location: http://localhost/online_freedelivery_movies_series/user/login.php?email=' . $email . '&password_error=1'); } <file_sep>/js/order.js const container = document.querySelector('#items-container'); const data = JSON.parse(localStorage.getItem('cart_data')); console.log(data); let content = `<input type="hidden" name="data" value="" />`; data.forEach(obj => { content += `<div class="order-container-shoe"> <div class="order-shoe-img-container"> <img class="order-img" src=${obj.thumnail_url} alt="NON" /> </div> <div class="order-shoe-prop-container"> <p class="order-shoe-name">Name - <span>${obj.title}</span></p> <p class="order-shoe-price">Ksh. <span>30</span></p> <p class="order-shoe-color">Season(s) - <span>${obj.seasons.toString()}</span></p> <p class="order-shoe-color">Episode(s) - <span>${obj.episodes.toString()}</span></p> </div> </div>` }) container.innerHTML = content; const form = document.querySelector('form'); form.addEventListener('submit', completeOrder); function completeOrder(e) { e.preventDefault(); if(e.target.className = 'place-order') { console.log(e.target) const cart_items = { 'user_id': document.querySelector('#user_id').value, 'phone_number': document.querySelector('#phone').value, 'area': document.querySelector('#location').value, 'mpesa_code': document.querySelector('#m_pesa_code').value, 'items': data } const data2 = JSON.stringify(cart_items) console.log(data2) fetch('item/ordered_items.php', { method:'POST', headers: { 'Content-type': 'application/json' }, body: data2 }) .then((res) => res.json()) .then((msg) => { localStorage.removeItem('cart_data'); window.location.replace(`http://localhost/online_freedelivery_movies_series/index.php?msg=${msg.msg}`) }) } }
bf9a607be3777a4f81c7490353036d08ce878d45
[ "JavaScript", "PHP" ]
24
PHP
jeffScott001/free-delivery-movies-and-series
fefd073de43b847cbca134011ce23e416b0a3b60
8805eafb5f094c4e913786b88b8dac8f8c463bb1
refs/heads/master
<repo_name>flensted/rehh<file_sep>/RibeEsbjergHH/Controllers/SkoleAdminController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using RibeEsbjergHH.Models; namespace RibeEsbjergHH.Controllers { public class SkoleAdminController : Controller { // // GET: /SkoleAdmin/ public ActionResult Index() { var repo = new ParticipantRepository(); return View(repo.GetAll()); } // // GET: /SkoleAdmin/Details/5 public ActionResult Details(int id) { var repo = new ParticipantRepository(); return View(repo.Get(id)); } public ActionResult FullList() { var repo = new ParticipantRepository(); return View(repo.GetAll()); } public ActionResult CSV() { var repo = new ParticipantRepository(); return View(repo.GetAll()); } // // GET: /SkoleAdmin/Create //public ActionResult Create() //{ // return View(new Participant()); //} //// //// POST: /SkoleAdmin/Create //[HttpPost] //public ActionResult Create(Participant newParticipant) //{ // try // { // var repo = new ParticipantRepository(); // repo.Add(newParticipant); // return RedirectToAction("Index"); // } // catch // { // return View(); // } //} //// //// GET: /SkoleAdmin/Edit/5 //public ActionResult Edit(int id) //{ // var repo = new ParticipantRepository(); // return View(repo.Get(id)); //} //// //// POST: /SkoleAdmin/Edit/5 //[HttpPost] //public ActionResult Edit(int id, Participant newParticipant) //{ // try // { // var repo = new ParticipantRepository(); // repo.Change(id, newParticipant); // return RedirectToAction("Index"); // } // catch // { // return View(); // } //} //// //// GET: /SkoleAdmin/Delete/5 //public ActionResult Delete(int id) //{ // try // { // var repo = new ParticipantRepository(); // repo.Delete(id); // return RedirectToAction("Index"); // } // catch // { // return View(); // } //} //// //// POST: /SkoleAdmin/Delete/5 //[HttpPost] //public ActionResult Delete(int id, FormCollection collection) //{ // try // { // var repo = new ParticipantRepository(); // repo.Delete(id); // return RedirectToAction("Index"); // } // catch // { // return View(); // } //} } } <file_sep>/README.md rehh ==== Ri<NAME> HH's tilmelding til håndboldskole
2e817da27429b46bb78b4cd25ce3b37a8e9ed1dd
[ "Markdown", "C#" ]
2
C#
flensted/rehh
2704fe6254f251b4d554f91d431594c4444531fd
1ee044d353d92ca992bed13a8ceb6b6d9cd82973
refs/heads/master
<file_sep>package vip import ( "errors" "fmt" "math" "net" "strconv" "strings" ) // IP represents a single IPv4 address type IP uint32 // IPs is a slice of IP type IPs []IP // EmptyIP is 0.0.0.0 var EmptyIP = IP(0) // MaxIP is 255.255.255.255 var MaxIP = Quad(255, 255, 255, 255) // Parse an IPv4 "dotted-quad" func Parse(ip string) (IP, error) { q := strings.SplitN(ip, ".", 4) if len(q) != 4 { return IP(0), errors.New("expected dotted-quad") } u := uint32(0) for i := 0; i < 4; i++ { n, err := strconv.ParseUint(q[i], 10, 8) if err != nil { return IP(0), err } u = u | uint32(n)<<uint8((3-i)*8) } return IP(u), nil } // MustParse panics on Parse failure func MustParse(ip string) IP { x, err := Parse(ip) if err != nil { panic(err) } return x } func (ip IP) String() string { a, b, c, d := ip.Quad() return fmt.Sprintf("%d.%d.%d.%d", a, b, c, d) } // IsZero returns if the IP is 0.0.0.0 func (ip IP) IsZero() bool { return ip == EmptyIP } // Delta many spots from the IP func (ip IP) Delta(d int64) IP { n := int64(ip) + d if n < 0 { return EmptyIP } else if n > math.MaxUint32 { return MaxIP } return IP(n) } // Next IP after this one func (ip IP) Next() IP { return ip.Delta(1) } // Prev IP before this one func (ip IP) Prev() IP { return ip.Delta(-1) } // Quad returns 4 bytes representing each quad func (ip IP) Quad() (uint8, uint8, uint8, uint8) { return quadSpread(uint32(ip)) } // Quad returns 4 bytes representing each quad func Quad(a uint8, b uint8, c uint8, d uint8) IP { return IP(quadJoin(a, b, c, d)) } // MarshalJSON allows IPNets to be json.Unmarshalled func (ip IP) MarshalJSON() ([]byte, error) { return []byte(`"` + ip.String() + `"`), nil } // UnmarshalJSON allows IPNets to be json.Unmarshalled func (ip *IP) UnmarshalJSON(b []byte) error { tmp, err := Parse(strings.Trim(string(b), `"`)) if err != nil { return err } *ip = tmp return nil } // StdIP converts a standard-library net.IP to a vip.IP func StdIP(ip net.IP) IP { v4 := ip.To4() return Quad(v4[0], v4[1], v4[2], v4[3]) } // ToStd converts a vip.IP to a standard-library net.IP func (ip IP) ToStd() net.IP { a, b, c, d := ip.Quad() return net.IP([]byte{a, b, c, d}) } // IsMulticast returns whether IP is a multi-cast address func (ip IP) IsMulticast() bool { return Multicast.Contains(ip) } // IsPrivate returns whether IP is a private address func (ip IP) IsPrivate() bool { return Private10.Contains(ip) || Private172.Contains(ip) || Private192.Contains(ip) } // IsSSDP returns whether IP is an SSDP address func (ip IP) IsSSDP() bool { return ip == SSDP } // Mask returns a CIDR func (ip IP) Mask(bits uint8) IPNet { return IPNet{ IP: ip, Mask: Mask(bits), } } // IPBytes 4 bytes to an vip.IP func IPBytes(b [4]byte) IP { return Quad(b[0], b[1], b[2], b[3]) } <file_sep>package vip import ( "encoding/json" "strconv" "strings" "testing" ) func TestNW1(t *testing.T) { m := Mask(24) s := strconv.FormatUint(uint64(m.BitMask()), 2) if s != "11111111111111111111111100000000" { t.Fatalf("bad str: %s", s) } } func TestNW2(t *testing.T) { nw := QuadMask(10, 0, 0, 0, 24) s := nw.String() if s != "10.0.0.0/24" { t.Fatalf("bad str: %s", s) } } func TestNW3(t *testing.T) { nw := QuadMask(10, 0, 0, 7, 24) if nw.IP != Quad(10, 0, 0, 7) { t.Fatalf("bad nw ip") } if nw.NetworkIP() != Quad(10, 0, 0, 0) { t.Fatalf("bad nw addr") } if ip := nw.BroadcastIP(); ip != Quad(10, 0, 0, 255) { t.Fatalf("bad bc addr: %s", ip) } } func TestNWParse1(t *testing.T) { nw, err := ParseCIDR("1.2.3.4/24") if err != nil { t.Fatalf("parse err: %s", err) } else if nw != QuadMask(1, 2, 3, 4, 24) { t.Fatalf("parse mismatch") } } func TestNWParse2(t *testing.T) { _, err := ParseCIDR("1.2.3.4/33") if err == nil { t.Fatalf("expected err") } else if !strings.Contains(err.Error(), "value out of range") { t.Fatalf("expected range err") } } func TestNWParse3(t *testing.T) { nw, err := ParseCIDR("172.16.17.3216/32") if err != nil { t.Fatalf("parse err: %s", err) } else if nw != QuadMask(5, 196, 192, 216, 32) { t.Fatalf("parse mismatch") } } func TestNWContains1(t *testing.T) { nw := MustParseCIDR("10.1.1.0/24") if !nw.Contains(MustParse("10.1.1.13")) { t.Fatalf("expected to be in network") } else if nw.Contains(MustParse("10.1.0.13")) { t.Fatalf("expected not to be in network 1") } else if nw.Contains(MustParse("10.0.1.13")) { t.Fatalf("expected not to be in network 2") } } func TestNWContains2(t *testing.T) { nw := MustParseCIDR("10.1.1.17/28") if nw.NetworkIP() != Quad(10, 1, 1, 16) { t.Fatalf("unexpected network addr") } if nw.BroadcastIP() != Quad(10, 1, 1, 31) { t.Fatalf("unexpected broadcast addr") } if nw.Contains(MustParse("10.1.1.13")) { t.Fatalf("expected not to be in network 1") } if !nw.Contains(MustParse("10.1.1.19")) { t.Fatalf("expected to be in network 2") } if nw.Contains(MustParse("10.1.1.32")) { t.Fatalf("expected not to be in network 3") } } func TestNWSize(t *testing.T) { if MustParseCIDR("10.1.1.0/24").Size() != 256 { t.Fatalf("expected size (1)") } else if MustParseCIDR("10.1.1.0/28").Size() != 16 { t.Fatalf("expected size (2)") } } func TestNWJSON(t *testing.T) { data := struct { Net IPNet `json:"net"` }{} buff := []byte(`{"net":"10.0.0.7/24"}`) if err := json.Unmarshal(buff, &data); err != nil { t.Fatalf("unmarshal json: %s", err) } else if data.Net != QuadMask(10, 0, 0, 7, 24) { t.Fatalf("data mismatch") } //change address data.Net.IP = Quad(10, 3, 3, 6) //reencode if buff2, err := json.Marshal(&data); err != nil { t.Fatalf("marshal json: %s", err) } else if string(buff2) != `{"net":"10.3.3.6/24"}` { t.Fatalf("buff mismatch") } } func TestPrivate(t *testing.T) { for ip, private := range map[string]bool{ "1.2.3.4": false, "10.2.3.4": true, "172.16.58.3": false, "192.168.3.4": true, } { i, err := Parse(ip) if err != nil { t.Fatalf("parse err: %s", err) } if i.IsPrivate() != private { t.Fatalf("expected private: %v", private) } } } <file_sep># vip [![GoDoc](https://godoc.org/github.com/jpillora/vip?status.svg)](https://godoc.org/github.com/jpillora/vip) An IPv4 addressing package, based on `uint32` instead of `[]byte`. <file_sep>module github.com/jpillora/vip go 1.13 <file_sep>package vip import ( "strings" "testing" ) func TestIP1(t *testing.T) { ip := Quad(1, 1, 1, 1) s := ip.String() if s != "1.1.1.1" { t.Fatalf("bad str: %s", s) } } func TestIP2(t *testing.T) { ip := Quad(1, 2, 3, 4) s := ip.String() if s != "1.2.3.4" { t.Fatalf("bad str: %s", s) } } func TestIPParse1(t *testing.T) { ip, err := Parse("1.2.3.4") if err != nil { t.Fatalf("parse err: %s", err) } else if ip != Quad(1, 2, 3, 4) { t.Fatalf("parse mismatch") } } func TestIPParse2(t *testing.T) { _, err := Parse("1.2.333.4") if err == nil { t.Fatalf("expected err") } else if !strings.Contains(err.Error(), "value out of range") { t.Fatalf("expected range err") } } <file_sep>package vip import ( "errors" "fmt" "math" "net" "strconv" ) //Mask represents the size of a bit-mask type Mask uint8 //BitMask returns the bit-mask func (m Mask) BitMask() uint32 { return math.MaxUint32 << (32 - uint8(m)) } //String number of bits func (m Mask) String() string { return strconv.FormatUint(uint64(m), 10) } //Hex representation of bit mask func (m Mask) Hex() string { return fmt.Sprintf("%x", m.BitMask()) } //IP representation of bit mask func (m Mask) IP() IP { return IP(uint32(MaxIP) & m.BitMask()) } //ToStd converts back to standard-library mask func (m Mask) ToStd() net.IPMask { a, b, c, d := quadSpread(m.BitMask()) return net.IPMask([]byte{a, b, c, d}) } //MaskBytes converts a quad into a mask func MaskBytes(b [4]byte) (Mask, error) { target := quadJoin(b[0], b[1], b[2], b[3]) for b := uint8(32); b >= 0; b-- { if target == math.MaxUint32<<(32-b) { return Mask(b), nil } } return Mask(0), errors.New("invalid mask") } //StdMask converts a standard-library mask func StdMask(m net.IPMask) (Mask, error) { b := [4]byte{} n := copy(b[:], m) if n != 4 { return Mask(0), errors.New("invalid mask") } return MaskBytes(b) } <file_sep>package vip import "testing" func TestMask(t *testing.T) { m, err := MaskBytes([4]byte{255, 255, 255, 0}) if err != nil { t.Fatal(err) } if uint(m) != 24 { t.Fatalf("unexpected mask: %d", m) } } <file_sep>package vip //commmon ranges and such var ( //Multicast CIDR Multicast = QuadMask(224, 0, 0, 0, 4) //SSDP CIDR SSDP = Quad(239, 255, 255, 250) //Private CIDR Private10 = QuadMask(10, 0, 0, 0, 8) Private172 = QuadMask(172, 16, 0, 0, 12) Private192 = QuadMask(192, 168, 0, 0, 16) ) func quadSpread(n uint32) (uint8, uint8, uint8, uint8) { a := uint8(n >> 24) b := uint8(n >> 16) c := uint8(n >> 8) d := uint8(n >> 0) return a, b, c, d } func quadJoin(a uint8, b uint8, c uint8, d uint8) uint32 { u := uint32(0) u = u | (uint32(a) << 24) u = u | (uint32(b) << 16) u = u | (uint32(c) << 8) u = u | (uint32(d) << 0) return u } <file_sep>package vip import ( "errors" "net" "strconv" "strings" ) //IPNet reprents an IPv4 address and network mask type IPNet struct { IP Mask } //CIDR is an alias for IPNet type CIDR = IPNet //IPNets is a slice of IPNet type IPNets []IPNet //EmptyIPNet is 0.0.0.0/0 var EmptyIPNet = IPNet{} //ParseHostCIDR converts a CIDR string into an IPNet, //and ensures the resulting IP is a host. func ParseHostCIDR(cidr string) (IPNet, error) { nw, err := ParseCIDR(cidr) if err != nil { return IPNet{}, err } if !nw.IsHost(nw.IP) { return IPNet{}, errors.New("expecting host ip") } return nw, nil } //ParseCIDR converts a CIDR string into an IPNet func ParseCIDR(cidr string) (IPNet, error) { c := strings.SplitN(cidr, "/", 2) if len(c) != 2 { return IPNet{}, errors.New("expected <ip>/<mask>") } ip, err := Parse(c[0]) if err != nil { return IPNet{}, err } mask, err := strconv.ParseUint(c[1], 10, 8) if err != nil { return IPNet{}, err } else if mask > 32 { return IPNet{}, errors.New("value out of range") } return IPNet{IP: ip, Mask: Mask(mask)}, nil } //MustParseCIDR panics on failure func MustParseCIDR(cidr string) IPNet { x, err := ParseCIDR(cidr) if err != nil { panic(err) } return x } //QuadMask creates a IPNet from a quad and a mask func QuadMask(a uint8, b uint8, c uint8, d uint8, bits uint8) IPNet { return IPNet{IP: Quad(a, b, c, d), Mask: Mask(bits)} } func (nw IPNet) String() string { return nw.IP.String() + "/" + nw.Mask.String() } //NetworkIP returns the network address //For example 10.0.0.7/24 returns 10.0.0.0 func (nw IPNet) NetworkIP() IP { return IP(uint32(nw.IP) & nw.BitMask()) } //IsNetworkIP determines if the IP is network's //network address func (nw IPNet) IsNetworkIP(ip IP) bool { return nw.Mask != 32 && nw.NetworkIP() == ip } //BroadcastIP returns the broadcast address //For example 10.0.0.7/24 returns 10.0.0.255 func (nw IPNet) BroadcastIP() IP { return IP(uint32(nw.IP) | ^nw.BitMask()) } //IsBroadcastIP determines if the IP is network's //broadcast address func (nw IPNet) IsBroadcastIP(ip IP) bool { return nw.Mask != 32 && nw.BroadcastIP() == ip } //IsHost determines if the IP is a host in the //network (not the network ad not broadcast address) func (nw IPNet) IsHost(ip IP) bool { return nw.Mask == 32 || (!nw.IsNetworkIP(ip) && !nw.IsBroadcastIP(ip)) } //Contains determines if IP is contained in the network func (nw IPNet) Contains(ip IP) bool { return nw.NetworkIP() == IP(uint32(ip)&nw.BitMask()) } //Size represents number of addresses in the network func (nw IPNet) Size() uint32 { return 1 << (32 - nw.Mask) } //MarshalJSON allows IPNets to be json.Unmarshalled func (nw IPNet) MarshalJSON() ([]byte, error) { return []byte(`"` + nw.String() + `"`), nil } //UnmarshalJSON allows IPNets to be json.Unmarshalled func (nw *IPNet) UnmarshalJSON(b []byte) error { tmp, err := ParseCIDR(strings.Trim(string(b), `"`)) if err != nil { return err } *nw = tmp return nil } //MarshalText ... func (nw IPNet) MarshalText() (text []byte, err error) { return []byte(nw.String()), nil } //UnmarshalText ... func (nw *IPNet) UnmarshalText(text []byte) error { return nw.UnmarshalJSON(text) } //StdNet converts a standard-library *net.IPNet to a vip.IPNet func StdNet(nw *net.IPNet) IPNet { m, err := StdMask(nw.Mask) if err != nil { m = Mask(32) } return IPNet{ IP: StdIP(nw.IP), Mask: m, } } //ToStd converts a vip.IPNet to a standard-library *net.IPNet func (nw IPNet) ToStd() net.IPNet { return net.IPNet{ IP: nw.NetworkIP().ToStd(), Mask: nw.Mask.ToStd(), } }
76084a3ab6c03d83ab0984ccdda157c5c25470bf
[ "Markdown", "Go Module", "Go" ]
9
Go
jpillora/vip
510042374ebf299f7537f51eb824d43ee86ddb7b
482b767fce2b001e29bea210fdb210b30413ffbc
refs/heads/master
<file_sep># ATTOMdata API KEY, active for 30 days, apprx till Nov 14, 2018 # API_KEY = "<KEY>" API_KEY = "1e89cfd9a117d449e06bcc838a0c4186"<file_sep># import dependencies import matplotlib.pyplot as plt import numpy as np import pandas as pd from flask import Flask, render_template, jsonify, request, redirect from flask_pymongo import PyMongo import pickle max_vals = pickle.load( open( "max_vals.p", "rb" ) ) model = pickle.load( open( "model.p", "rb" ) ) ins = pickle.load( open( "ins.p", "rb" ) ) labels = model.labels_ from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans # import the function to return the ML'd data from cluster.Cluster import RealestateClustering # init the Flask app = Flask(__name__) @app.route("/NJRE_results") def njre_results(): # create a link to whatever the zipcodes data source will be under here # Will most likely be AWS link ###### app.config["MONGO_URI"] = 'mongodb://localhost:27017/NJRE_test' # mongo = PyMongo(app) # db = mongo.db # # create a variable containing the data # prefZips = db.flask_test.find_one() # #testing json # # prefZips = { # # "zipcodes": ['07001', '07002', '07003'], # # "Rating": [.62, .3, .08], # # "Lat": [-72, -60, -65], # # "Long": [120, 118, 110] # # } # print(prefZips) # prefZips_zip = prefZips["zipcodes"] # prefZips_rat = prefZips["rating"] # prefZips_lat = prefZips["Lat"] # prefZips_long = prefZips["Long"] # # convert the pulled data into a json to render # prefZips_dict = {"zipcode":prefZips_zip, 'rating':prefZips_rat, 'Lat': prefZips_lat, 'Long': prefZips_long} return render_template('njre_results.html') # create a index route @app.route('/') def index(): # Return the template return render_template('index.html') @app.route('/output_page', methods=['POST']) def output_zipcodes(): # if values are not populated, it means that they are not important for the user parks = request.form['parks'] if parks == "": parks = 10 price = request.form['price'] if price == "": price = 0 tax = request.form['tax'] if tax == "": tax = 10 schools = request.form['schools'] if schools == "": schools = 10 crime = request.form['crime'] if crime == "": crime = 10 transportation = request.form['transportation'] if transportation == "": transportation = 10 eats = request.form['eats'] if eats == "": eats = 10 income = request.form['income'] if income == "": income = 0 shop = request.form['shop'] if shop == "": shop = 10 ## Convert money to digits only for price and income # price = '$1,425,232' -> price ='1425232' price = price.replace("$","").replace(",","") income = income.replace("$","").replace(",","") input_dict = {'parks': int(parks), 'eats': int(eats), 'shop': int(shop), 'income': int(income), 'price': int(price), 'transportation': int(transportation), 'tax': int(tax)} zips_dict = RealestateClustering(input_dict) #input_predict = [input_list] #predicted = model.predict(input_predict) #zip_cluster_vals = pd.DataFrame([ins, labels],).transpose().values #zip_cluster = pd.DataFrame(zip_cluster_vals, columns=['zip_code', 'label']) #zips_predicted = zip_cluster.loc[zip_cluster['label'] == predicted[0]] #zips = zips_predicted['zip_code'].values #zips_dict = {'zips': []} #for zip in zips: # zips_dict['zips'].append("0" + str(zip)) # return render_template('results.html') return jsonify(zips_dict) # return render_template('results.html', **zips_dict) # """ # parks: %s # price: %s # tax: %s # schools: %s # crime: %s # transportation: %s # eats: %s # income: %s # shop: %s # """ % (parks, price, tax, schools, crime, transportation, eats, income, shop) # put on pre line% (eats) if __name__ == "__main__": app.run(debug=True) <file_sep> # coding: utf-8 # In[1]: import http.client # from ib_proj3_config import API_KEY from jons_config import api_key from pprint import pprint import json import pandas as pd import time import pymongo import ast import os # In[2]: zips = pd.read_csv("zips.csv") zip_list = list(zips) # In[25]: zip_latlong = pd.read_csv("data/zip_codes_states.csv") zip_latlong.set_index("zip_code", inplace=True) int_zip = [] for zipp in zip_list: try: int_zip.append(int(zipp)) except: int_zip.append(int(round(float(zipp)))) nj_zips = zip_latlong.loc[int_zip] # In[21]: lats = list(nj_zips['latitude']) long = list(nj_zips['longitude']) # In[ ]: # Create connection variable for Project3 database in MLab # mongodb://<dbuser>:<dbpassword>@ds<EMAIL>.ml<EMAIL>:37003/project3 # connMLAB = 'mongodb://localhost:27017' # connMLAB = "mongodb://ibaloyan:<EMAIL>:37003/project3" connMLAB = "mongodb://jonathan:<EMAIL>:37003/project3" # connMLAB = "mongodb://grothjd:<EMAIL>:37003/" # Pass connection to the pymongo instance. client = pymongo.MongoClient(connMLAB) # Connect to a database. Will create one if not already available. # db = client.Apple_y_y # Fix done for Heroku deployment # db = client.heroku_8nx1c4b9 db = client.project3 # In[ ]: # loop through all zip codes for n in range(len(zip_list)): conn = http.client.HTTPSConnection("search.onboard-apis.com") headers = { 'accept': "application/json", 'apikey': api_key, } ## conn.request("GET", "/propertyapi/v1.0.0/property/detail?address1=4529%20Winona%20Court&address2=Denver%2C%20CO", headers=headers) # Manalapan county # conn.request("GET", "/communityapi/v2.0.0/Area/Full/?AreaId=CO34025", headers=headers) # conn.request("GET", "/communityapi/v2.0.0/Area/Full/?AreaId=ZI07726", headers=headers) # com_url = '/propertyapi/v1.0.0/property/expandedprofile?address1=' + firstPart + "&address2=" + secondPart + "%2C+NJ" # conn.request("GET", com_url, headers=headers) conn.request("GET", "/propertyapi/v1.0.0/school/snapshot?latitude=" + str(lats[n]) + "&longitude=" + str(long[n]) + "&radius=5&filetypetext=public", headers=headers) # Get response record in json format res = conn.getresponse() data = res.read() ###print(data) # print(res) # import json # pprint(json.loads(json.dumps(zip_com_json))) # #print(json.dumps(json.loads(zip_com_json))) # pprint(data.decode("utf-8") null = None zip_com_json = eval(data.decode("utf-8")) #pprint(zip_com_json["school"]) try: # Creates a collection in the database and insert document for item in zip_com_json["school"]: db.schools.insert_one( item ) except: pass <file_sep>''' Data Processing toolbox: contains pre and post processing function for cluster analysis of realestate data.''' def LoadData(): ''' loads data from csv file to dataframe ''' import pandas as pd input_df = pd.read_csv('zip_data.csv') input_df.drop('Unnamed: 0', axis=1, inplace=True) return input_df def TransformInput(input_dict): import pickle max_vals = pickle.load( open( "max_vals.p", "rb" ) ) parks = (input_dict['parks']/10)*max_vals['recreation'] eats = (input_dict['eats']/10)*max_vals['eating-drinking'] shop = (input_dict['shop']/10)*max_vals['shopping'] transportation = (input_dict['transportation']/10)*max_vals['trwpublic'] tax = ((10 - input_dict['tax'])/10)*max_vals['avg_prop_tax'] input_list = [parks, eats, shop, input_dict['income'], input_dict['price'], transportation, tax] input_list = [input_list] return input_list def ConcatAndScale(Transformed_user_input, data): ''' concatenates and scales data with x1 concatenated on top of x2 ''' import numpy as np from sklearn.preprocessing import StandardScaler scaler = StandardScaler() data_std = scaler.fit_transform(data) input_std = scaler.transform(Transformed_user_input) input_concat = np.concatenate((input_std, data_std), axis=0) return input_concat def FindDistanceSortZips(x1, x2, zips_dict): ''' finds distance ''' from sklearn.neighbors import DistanceMetric from sklearn.preprocessing import StandardScaler import pandas as pd import numpy as np x2_predicted = x2.loc[x2['zip_codes'] == zips_dict['zips'][0]].values for i in range(len(zips_dict['zips'])-1): vector = x2.loc[x2['zip_codes'] == zips_dict['zips'][i+1]].values x2_predicted = np.concatenate((x2_predicted, vector), axis=0) x2_array = x2_predicted[:,1:] scaler = StandardScaler() x2_std = scaler.fit_transform(x2_array) x1_std = scaler.transform(x1) X = np.concatenate((x1_std, x2_std)) dist = DistanceMetric.get_metric('euclidean') distance = dist.pairwise(X) distance = distance[0] distance_dict = {'distance': list(distance)[1:]} zip_dist = {**zips_dict, **distance_dict} zip_dist_df = pd.DataFrame(zip_dist) zip_dist_df.sort_values('distance', axis=0, ascending=True, inplace=True) zip_codes_sorted = zip_dist_df['zips'].values.astype(str) zip_codes_sorted_dict = {'zip_codes': list(zip_codes_sorted)} return zip_codes_sorted_dict <file_sep>import csv from pprint import pprint import json import pandas as pd import pymongo import ast import os # Create connection variable for Project3 database in MLab connMLAB = "mongodb://jonathan:<EMAIL>:37003/project3" # Pass connection to the pymongo instance. client = pymongo.MongoClient(connMLAB) # Connect to a database. Will create one if not already available. db = client.project3 posts = db.zip_community_test5.find({"response.result":{'$exists':True}}) community = [] for post in posts: community.append(post["response"]["result"]["package"]["item"]) community_df = pd.DataFrame(community) print(community_df.head()) <file_sep># chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security FLASK_APP=app.py flask run <file_sep> def RealestateClustering(input_dict): import pandas as pd from cluster.util_funct.data_processing import LoadData, TransformInput, ConcatAndScale, FindDistanceSortZips from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering realestate_data = LoadData() user_input = TransformInput(input_dict) realestate_array = realestate_data.iloc[:,1:8].values concat_data = ConcatAndScale(user_input, realestate_array) cluster = AgglomerativeClustering(n_clusters=7, affinity='cosine', linkage='complete') labels = cluster.fit_predict(concat_data) ins = realestate_data['zip_codes'].values zip_cluster_vals = pd.DataFrame([ins, labels[1:]],).transpose().values zip_cluster = pd.DataFrame(zip_cluster_vals, columns=['zip_code', 'label']) zips_predicted = zip_cluster.loc[zip_cluster['label'] == labels[0]] zips = zips_predicted['zip_code'].values zips_dict = {'zips': list(zips)} sorted_zips = FindDistanceSortZips(user_input, realestate_data, zips_dict) return sorted_zips if __name__ == "__main__": parks = 7 price = 100000 tax = 8 transportation = 7 eats = 8 income = 91000 shop = 3 input_dict = {'parks': parks, 'price': price, 'tax': tax, 'transportation': transportation, 'eats': eats, 'income': income, 'shop': shop} output_zips = RealestateClustering(input_dict) print(output_zips) <file_sep># NJ-RE-Trends Use Machine Learning to research New Jersey Real Estate Trends. ![Use Machine Learning to research New Jersey Real Estate Trends](image/pic1.PNG) ![Use Machine Learning to research New Jersey Real Estate Trends](image/pic01.PNG) ![Use Machine Learning to research New Jersey Real Estate Trends](image/pic02.PNG) ![Use Machine Learning to research New Jersey Real Estate Trends](image/pic2.PNG) ![Use Machine Learning to research New Jersey Real Estate Trends](image/pic3.PNG) ![Use Machine Learning to research New Jersey Real Estate Trends](image/pic4.PNG) ![Use Machine Learning to research New Jersey Real Estate Trends](image/pic5.PNG) <file_sep>api_key = "<KEY>" <file_sep>certifi==2018.8.24 chardet==3.0.4 Click==7.0 Flask==1.0.2 Flask-Cors==3.0.6 Flask-PyMongo==2.1.0 gunicorn==19.9.0 idna==2.7 inflection==0.3.1 itsdangerous==0.24 Jinja2==2.10.1 joblib==0.13.2 MarkupSafe==1.0 more-itertools==4.3.0 numpy==1.15.2 pandas==0.23.4 pymongo==3.7.2 python-dateutil==2.7.3 pytz==2018.5 Quandl==3.4.2 requests==2.20.0 scikit-learn==0.21.1 scipy==1.3.0 six==1.11.0 sklearn==0.0 urllib3==1.24.2 Werkzeug==0.14.1 wincertstore==0.2
36386ce95c2b96c360b3b61dab1a911eefe991fd
[ "Markdown", "Python", "Text", "Shell" ]
10
Python
ibaloyan/NJ-RE-Trends
741054168effbfd90e789c9dd7e8597aa520a3b1
ef4bacdf746c05f821b9083b823dc30fa6f50ffd
refs/heads/master
<repo_name>adrianomucha/npd_c2_a1<file_sep>/npd_c2_a1/assignment_1/original.py st login: Mon Jul 11 13:00:45 on ttys002 172-30-49-113:~ adrianmucha$ cd vagrant-python-env -bash: cd: vagrant-python-env: No such file or directory 172-30-49-113:~ adrianmucha$ ls Applications README.md Applications (original) Vagrantfile Creative Cloud Files VirtualBox VMs Creative Cloud Files (archived) (1) directory Desktop directory_contents.txt Documents get_pizza Downloads intro-programming Library node_modules Movies scripts Music untitled folder Pictures vagrant-workspace Public vagrant_folder 172-30-49-113:~ adrianmucha$ cd Va -bash: cd: Va: No such file or directory 172-30-49-113:~ adrianmucha$ cd Vagrantfile -bash: cd: Vagrantfile: Not a directory 172-30-49-113:~ adrianmucha$ ls Applications README.md Applications (original) Vagrantfile Creative Cloud Files VirtualBox VMs Creative Cloud Files (archived) (1) directory Desktop directory_contents.txt Documents get_pizza Downloads intro-programming Library node_modules Movies scripts Music untitled folder Pictures vagrant-workspace Public vagrant_folder 172-30-49-113:~ adrianmucha$ cd Vagrantfile -bash: cd: Vagrantfile: Not a directory 172-30-49-113:~ adrianmucha$ cd intro-programming/ 172-30-49-113:intro-programming adrianmucha$ ls 172-30-49-113:intro-programming adrianmucha$ ls 172-30-49-113:intro-programming adrianmucha$ cd .. 172-30-49-113:~ adrianmucha$ ls Applications README.md Applications (original) Vagrantfile Creative Cloud Files VirtualBox VMs Creative Cloud Files (archived) (1) directory Desktop directory_contents.txt Documents get_pizza Downloads intro-programming Library node_modules Movies scripts Music untitled folder Pictures vagrant-workspace Public vagrant_folder 172-30-49-113:~ adrianmucha$ cd vagrant-workspace/ 172-30-49-113:vagrant-workspace adrianmucha$ vagrant up Bringing machine 'default' up with 'virtualbox' provider... ==> default: Checking if box 'hashicorp/precise64' is up to date... ==> default: Machine already provisioned. Run `vagrant provision` or use the `--provision` ==> default: flag to force provisioning. Provisioners marked to run always will still run. 172-30-49-113:vagrant-workspace adrianmucha$ vagrant ssh Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.2.0-23-generic x86_64) * Documentation: https://help.ubuntu.com/ New release '14.04.4 LTS' available. Run 'do-release-upgrade' to upgrade to it. Welcome to your Vagrant-built virtual machine. Last login: Mon Jul 11 17:01:18 2016 from 10.0.2.2 vagrant@precise64:~$ ls course_setup.sh npd Python-3.4.1.tar.xz course_vars.cfg postinstall.sh task_database_python.txt intro-programming python vagrant-python-env my_stuff Python-3.4.1 vagrant-python-env1 vagrant@precise64:~$ cd my_stuff/ vagrant@precise64:~/my_stuff$ virtualenv -p python3.4 venv The program 'virtualenv' is currently not installed. You can install it by typing: sudo apt-get install python-virtualenv vagrant@precise64:~/my_stuff$ ls game vagrant@precise64:~/my_stuff$ cd .. vagrant@precise64:~$ ls course_setup.sh npd Python-3.4.1.tar.xz course_vars.cfg postinstall.sh task_database_python.txt intro-programming python vagrant-python-env my_stuff Python-3.4.1 vagrant-python-env1 vagrant@precise64:~$ mkdir python_exercise vagrant@precise64:~$ ls course_setup.sh postinstall.sh task_database_python.txt course_vars.cfg python vagrant-python-env intro-programming Python-3.4.1 vagrant-python-env1 my_stuff Python-3.4.1.tar.xz npd python_exercise vagrant@precise64:~$ cd python_exercise/ vagrant@precise64:~/python_exercise$ sudo apt-get install python-virtualenv Reading package lists... Done Building dependency tree Reading state information... Done The following extra packages will be installed: python-pip python-setuptools The following NEW packages will be installed: python-pip python-setuptools python-virtualenv 0 upgraded, 3 newly installed, 0 to remove and 185 not upgraded. Need to get 2,648 kB of archives. After this operation, 3,779 kB of additional disk space will be used. Do you want to continue [Y/n]? Y Get:1 http://us.archive.ubuntu.com/ubuntu/ precise/main python-setuptools all 0.6.24-1ubuntu1 [441 kB] Get:2 http://us.archive.ubuntu.com/ubuntu/ precise/universe python-pip all 1.0-1build1 [95.1 kB] Get:3 http://us.archive.ubuntu.com/ubuntu/ precise/universe python-virtualenv all 1.7.1.2-1 [2,112 kB] Fetched 2,648 kB in 2s (896 kB/s) Selecting previously unselected package python-setuptools. (Reading database ... 53608 files and directories currently installed.) Unpacking python-setuptools (from .../python-setuptools_0.6.24-1ubuntu1_all.deb) ... Selecting previously unselected package python-pip. Unpacking python-pip (from .../python-pip_1.0-1build1_all.deb) ... Selecting previously unselected package python-virtualenv. Unpacking python-virtualenv (from .../python-virtualenv_1.7.1.2-1_all.deb) ... Processing triggers for man-db ... Setting up python-setuptools (0.6.24-1ubuntu1) ... Setting up python-pip (1.0-1build1) ... Setting up python-virtualenv (1.7.1.2-1) ... vagrant@precise64:~/python_exercise$ virtualenv -p python3.4 venv Running virtualenv with interpreter /usr/local/bin/python3.4 New python executable in venv/bin/python3.4 Also creating executable in venv/bin/python Failed to import the site module Traceback (most recent call last): File "/home/vagrant/python_exercise/venv/lib/python3.4/site.py", line 67, in <module> import os File "/home/vagrant/python_exercise/venv/lib/python3.4/os.py", line 614, in <module> from _collections_abc import MutableMapping ImportError: No module named '_collections_abc' ERROR: The executable venv/bin/python3.4 is not functioning ERROR: It thinks sys.prefix is '/home/vagrant/python_exercise' (should be '/home/vagrant/python_exercise/venv') ERROR: virtualenv is not compatible with this system or executable vagrant@precise64:~/python_exercise$ virtualenv -p python3.4 venv Running virtualenv with interpreter /usr/local/bin/python3.4 Overwriting venv/lib/python3.4/site.py with new content Overwriting venv/lib/python3.4/orig-prefix.txt with new content Overwriting venv/lib/python3.4/no-global-site-packages.txt with new content New python executable in venv/bin/python3.4 Not overwriting existing python script venv/bin/python (you must use venv/bin/python3.4) Failed to import the site module Traceback (most recent call last): File "/home/vagrant/python_exercise/venv/lib/python3.4/site.py", line 67, in <module> import os File "/home/vagrant/python_exercise/venv/lib/python3.4/os.py", line 614, in <module> from _collections_abc import MutableMapping ImportError: No module named '_collections_abc' ERROR: The executable venv/bin/python3.4 is not functioning ERROR: It thinks sys.prefix is '/home/vagrant/python_exercise' (should be '/home/vagrant/python_exercise/venv') ERROR: virtualenv is not compatible with this system or executable vagrant@precise64:~/python_exercise$ python3 venv /usr/local/bin/python3: can't find '__main__' module in 'venv' vagrant@precise64:~/python_exercise$ python Python 2.7.3 (default, Jun 22 2015, 19:33:41) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> KeyboardInterrupt >>> :q File "<stdin>", line 1 :q ^ SyntaxError: invalid syntax >>> KeyboardInterrupt >>> >>> exit Use exit() or Ctrl-D (i.e. EOF) to exit >>> vagrant@precise64:~/python_exercise$ bpython >>> def square(n): ... '''Square a number n''' ... return n**2 ... ... def get_first_100(): File "<input>", line 5 def get_first_100(): ^ SyntaxError: invalid syntax >>> vagrant@precise64:~/python_exercise$ touch python_exercise.py vagrant@precise64:~/python_exercise$ vim python_exercise.py vagrant@precise64:~/python_exercise$ vim python_exercise.py vagrant@precise64:~/python_exercise$ python python_exercise.py File "python_exercise.py", line 11 return_value = [] ^ IndentationError: unindent does not match any outer indentation level vagrant@precise64:~/python_exercise$ vim python_exercise.py vagrant@precise64:~/python_exercise$ python python_exercise.py Traceback (most recent call last): File "python_exercise.py", line 23, in <module> print(solve_probblem()) NameError: name 'solve_probblem' is not defined vagrant@precise64:~/python_exercise$ vim python_exercise.py vagrant@precise64:~/python_exercise$ python python_exercise.py Traceback (most recent call last): File "python_exercise.py", line 23, in <module> print(solve_problem()) File "python_exercise.py", line 18, in solve_problem sum_squares_first_hundred = sum(square_list(first_100)) NameError: global name 'square_list' is not defined vagrant@precise64:~/python_exercise$ vim python_exercise.py vagrant@precise64:~/python_exercise$ vim python_exercise.py vagrant@precise64:~/python_exercise$ python python_exercise.py Traceback (most recent call last): File "python_exercise.py", line 23, in <module> print(solve_problem()) File "python_exercise.py", line 18, in solve_problem sum_squares_first_hundred = sum(square_list(first_100)) NameError: global name 'square_list' is not defined vagrant@precise64:~/python_exercise$ vim python_exercise.py vagrant@precise64:~/python_exercise$ python python_exercise.py Traceback (most recent call last): File "python_exercise.py", line 23, in <module> print(solve_problem()) File "python_exercise.py", line 18, in solve_problem sum_squares_first_hundred = sum(square_list(first_100)) NameError: global name 'square_list' is not defined vagrant@precise64:~/python_exercise$ vim python_exercise.py vagrant@precise64:~/python_exercise$ python python_exercise.py Traceback (most recent call last): File "python_exercise.py", line 23, in <module> print(solve_problem()) File "python_exercise.py", line 18, in solve_problem sum_squares_first_hundred = sum(square_list(first_100)) File "python_exercise.py", line 13, in square_list return_value.append(square(number)) NameError: global name 'square' is not defined vagrant@precise64:~/python_exercise$ vim python_exercise.py vagrant@precise64:~/python_exercise$ python python_exercise.py Traceback (most recent call last): File "python_exercise.py", line 23, in <module> print(solve_problem()) File "python_exercise.py", line 20, in solve_problem return sum_sqares_first_hundred - square_sum_first_hundred NameError: global name 'sum_sqares_first_hundred' is not defined vagrant@precise64:~/python_exercise$ vim python_exercise.py vagrant@precise64:~/python_exercise$ python python_exercise.py Traceback (most recent call last): File "python_exercise.py", line 23, in <module> print(solve_problem()) File "python_exercise.py", line 20, in solve_problem return sum_sqares_first_hundred - square_sum_first_hundred NameError: global name 'sum_sqares_first_hundred' is not defined vagrant@precise64:~/python_exercise$ vim python_exercise.py vagrant@precise64:~/python_exercise$ python python_exercise.py -25502499 vagrant@precise64:~/python_exercise$ ls python_exercise.py venv vagrant@precise64:~/python_exercise$ git clone https://github.com/adrianomucha/npd_c2_a1.git Cloning into 'npd_c2_a1'... remote: Counting objects: 3, done. remote: Compressing objects: 100% (2/2), done. remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0 Unpacking objects: 100% (3/3), done. vagrant@precise64:~/python_exercise$ ls npd_c2_a1 python_exercise.py venv vagrant@precise64:~/python_exercise$ cd npd_c2_a1/ vagrant@precise64:~/python_exercise/npd_c2_a1$ ls vagrant@precise64:~/python_exercise/npd_c2_a1$ ls vagrant@precise64:~/python_exercise/npd_c2_a1$ git status # On branch master nothing to commit (working directory clean) vagrant@precise64:~/python_exercise/npd_c2_a1$ ls vagrant@precise64:~/python_exercise/npd_c2_a1$ ls vagrant@precise64:~/python_exercise/npd_c2_a1$ ls vagrant@precise64:~/python_exercise/npd_c2_a1$ cd .. vagrant@precise64:~/python_exercise$ ls npd_c2_a1 python_exercise.py venv vagrant@precise64:~/python_exercise$ cd npd_c2_a1/ vagrant@precise64:~/python_exercise/npd_c2_a1$ ls vagrant@precise64:~/python_exercise/npd_c2_a1$ touch original.py vagrant@precise64:~/python_exercise/npd_c2_a1$ touch refactored.py vagrant@precise64:~/python_exercise/npd_c2_a1$ ls original.py refactored.py vagrant@precise64:~/python_exercise/npd_c2_a1$ vim original.py vagrant@precise64:~/python_exercise/npd_c2_a1$ ls original.py refactored.py vagrant@precise64:~/python_exercise/npd_c2_a1$ cd .. vagrant@precise64:~/python_exercise$ ls npd_c2_a1 python_exercise.py venv vagrant@precise64:~/python_exercise$ ;s -bash: syntax error near unexpected token `;' vagrant@precise64:~/python_exercise$ ls npd_c2_a1 python_exercise.py venv vagrant@precise64:~/python_exercise$ vim python_exercise.py vagrant@precise64:~/python_exercise$ cd npd_c2_a1/ vagrant@precise64:~/python_exercise/npd_c2_a1$ ls original.py refactored.py vagrant@precise64:~/python_exercise/npd_c2_a1$ vim refactored.py vagrant@precise64:~/python_exercise/npd_c2_a1$ vim original.py vagrant@precise64:~/python_exercise/npd_c2_a1$ cd .. vagrant@precise64:~/python_exercise$ ls npd_c2_a1 python_exercise.py venv vagrant@precise64:~/python_exercise$ python python_exercise.py -25502499 vagrant@precise64:~/python_exercise$ vim python_exercise.py vagrant@precise64:~/python_exercise$ ls npd_c2_a1 python_exercise.py venv vagrant@precise64:~/python_exercise$ cd npd_c2_a1/ vagrant@precise64:~/python_exercise/npd_c2_a1$ ls original.py refactored.py vagrant@precise64:~/python_exercise/npd_c2_a1$ vim original.py vagrant@precise64:~/python_exercise/npd_c2_a1$ python original.py File "original.py", line 17 return return_value = [] ^ SyntaxError: invalid syntax vagrant@precise64:~/python_exercise/npd_c2_a1$ vim original.py vagrant@precise64:~/python_exercise/npd_c2_a1$ python original.py File "original.py", line 19 for number in first_fifty: ^ IndentationError: unexpected indent vagrant@precise64:~/python_exercise/npd_c2_a1$ vim original.py vagrant@precise64:~/python_exercise/npd_c2_a1$ python original.py File "original.py", line 17 return return_value = [] ^ SyntaxError: invalid syntax vagrant@precise64:~/python_exercise/npd_c2_a1$ vim original.py vagrant@precise64:~/python_exercise/npd_c2_a1$ python original.py File "original.py", line 19 return return_value SyntaxError: 'return' outside function vagrant@precise64:~/python_exercise/npd_c2_a1$ vim original.py vagrant@precise64:~/python_exercise/npd_c2_a1$ python original.py File "original.py", line 17 for number in first_fifty: ^ IndentationError: expected an indented block vagrant@precise64:~/python_exercise/npd_c2_a1$ vim original.py vagrant@precise64:~/python_exercise/npd_c2_a1$ python original.py File "original.py", line 18 if number % 2 == 0: ^ IndentationError: expected an indented block vagrant@precise64:~/python_exercise/npd_c2_a1$ ls original.py refactored.py vagrant@precise64:~/python_exercise/npd_c2_a1$ cd .. vagrant@precise64:~/python_exercise$ ls npd_c2_a1 python_exercise.py venv vagrant@precise64:~/python_exercise$ git add npd_c2_a1/ fatal: Not a git repository (or any of the parent directories): .git vagrant@precise64:~/python_exercise$ git init Initialized empty Git repository in /home/vagrant/python_exercise/.git/ vagrant@precise64:~/python_exercise$ git add npd_c2_a1/ vagrant@precise64:~/python_exercise$ git commit -m"for later" [master (root-commit) 854e7fd] for later 2 files changed, 120 insertions(+) create mode 100644 npd_c2_a1/.gitignore create mode 100644 npd_c2_a1/original.py create mode 100644 npd_c2_a1/refactored.py vagrant@precise64:~/python_exercise$ git push fatal: No configured push destination. Either specify the URL from the command-line or configure a remote repository using git remote add <name> <url> and then push using the remote name git push <name> vagrant@precise64:~/python_exercise$ git push -u origin master fatal: 'origin' does not appear to be a git repository fatal: The remote end hung up unexpectedly vagrant@precise64:~/python_exercise$ ls npd_c2_a1 python_exercise.py venv vagrant@precise64:~/python_exercise$ cd npd_c2_a1/ vagrant@precise64:~/python_exercise/npd_c2_a1$ ls original.py refactored.py vagrant@precise64:~/python_exercise/npd_c2_a1$ vim original.py 1 e range of numbers 1 to 50 2 # sum even integers 3 # define the sum of numbers which are divisble by 7 4 # print 5 6 def first_fifty(): 7 return list(range(1,51)) 8 9 print(first_fifty()) 10 11 def return_value(): 12 for number in first_fifty: 13 if number % 2 == 0: 14 return_value.append(number) 15 return return_value 16 17 def solve_problem(): 18 first_50 = first_fifty() 19 sum_first_50 = sum(even_numbers(first_50)) 20 21 22 23 24 25 26 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ original.py [+] 1,8 All 23 fewer lines; before #3 2 seconds ago
539c2260b407efa7e19e55f16254f282e925357b
[ "Python" ]
1
Python
adrianomucha/npd_c2_a1
df97051544dfc277be8fa79a526496811cc54aae
bfa9534f35c7062977d30515f9823fa2c4a1293f
refs/heads/master
<file_sep># ThisBotFindsFascists Parse a redditor's comments for far-right identifiers. <file_sep>import os import time import praw import re import collections import datetime import string import sys from cryptography.fernet import Fernet reddit = praw.Reddit(client_id=os.environ['REDDIT_ID'], client_secret=os.environ['REDDIT_SECRET'], password=os.environ['REDDIT_<PASSWORD>'], user_agent=os.environ['REDDIT_AGENT'], username=os.environ['REDDIT_USER']) secret_key=os.environ['SECRET_KEY'] f = Fernet(str.encode(secret_key)) users = [ b'<KEY>', b'<KEY>', b'<KEY> ] slurs = [ '<NAME>', 'beaner', 'beaney', 'blackpill', 'black pill', 'btfo', 'chink', 'coontown', 'cuck', 'cucked', 'codeword for anti-white', 'codeword for white genocide', 'classical liberal', 'classical liberalism', 'chimp out', 'darky', 'darkey', 'darkie', 'degeneracy', 'degenerate', 'dindu', 'dindu nuffin', 'ethnic nationalist', 'ethno national', 'ethno-national', 'fag', 'faggot', 'gook', 'goy', 'goyim', 'goyum', 'groid', 'gyppo', 'gippo', 'gypo', 'gyppie', 'gyppy', 'gipp', 'gorillion', 'globalist', 'globalism', 'gib', 'gibsmedat', 'heeb', 'hebe', 'hymie', 'jew', 'jidf', 'kebab', 'kike', 'kyke', 'kangs', 'kangz', 'leftard', 'leftist', 'leftism', 'liberalism', 'libtard', 'multicultural', 'multiculturalism', 'multiculturalist', 'marxist', 'cultural marxism', 'mongrel', 'niglet', 'nig-nog', 'nignong', 'nigger', 'nigga', 'niggar', 'nip', 'negro', 'oy vey', 'pikey', 'piky', 'piker', 'peaceful ethnic cleansing', 'pikie', 'queer', 'rapefugee','race realist', 'redpill', 'red pill', 'race mix', 'radical islamic terror', 'religion of peace', 'regressive left', 'shylock', 'spearchucker', 'spick', 'shitskin', 'shill', 'shekel', 'shoah', 'soros', 'sjw', 'sharia', 'snackbar', 'the whites', 'the white race', 'the blacks', 'tranny', 'thug', 'virtue signal', 'wetback', 'wop', 'white nationalist', 'white genocide', 'we must secure the existence of our people and a future for white children', 'yid', 'youths', 'young male', '1488' ] #Add in standard plurals with_plural_slurs = slurs + [slur + 's' for slur in slurs] + [slur + 'z' for slur in slurs] multi_word_slurs = [slur for slur in with_plural_slurs if ' ' in slur] single_word_slurs = [slur for slur in with_plural_slurs if ' ' not in slur] # Our punctuation remover translator = str.maketrans('', '', string.punctuation) def CheckUser(redditorSuspect, recMessage): incidents = [] lastCommentID = '' for comment in redditorSuspect.comments.new(limit=None): quoteFree = re.sub(r">.*\n", "", comment.body).strip('#\n \t') contained = [] # Check against multi-word slurs, as they're unique enough to just do a string compare contained.extend([slur for slur in multi_word_slurs if slur in quoteFree.lower()]) # Check against echo parentheses if('(((' in quoteFree and ')))' in quoteFree): contained.extend(['(((',')))']) # Strip the punctuation, split the comment into single words, check against all our single word slurs contained.extend([slur for slur in single_word_slurs if slur in quoteFree.lower().translate(translator).split()]) if contained: if lastCommentID == '': url = 'http://np.reddit.com/comments/' + comment.link_id[3:] + '/_/' + comment.id else: url = 'http://www.reddit.com/user/' + redditorSuspect.name + '/comments/?limit=1&after=t1_' + lastCommentID abstract = re.sub('\(http.*\)', '', quoteFree.split('\n')[0]) incidents.append('\n* **/r/' + repr(comment.subreddit.display_name).rstrip('\'').lstrip('\'') + ' - ' + repr(contained) + '** - [' + abstract + '](' + url + ')') lastCommentID = comment.id messageBodies = [''] if not incidents: recMessage.reply('Nothing found: /u/' + redditorSuspect.name) return for incident in incidents: if len(messageBodies[-1]) + len(incident) < 10000: messageBodies[-1] += incident else: messageBodies.append(incident) for messageBody in reversed(messageBodies): recMessage.reply(messageBody) while(True): messages = reddit.inbox.unread(mark_read=True); for rMessage in messages: rMessage.mark_read() if str.encode(rMessage.author) in [f.decrypt(user) for user in users] and rMessage.subject != 'comment reply': try: if rMessage.subject == 'username mention': parent = reddit.comment(rMessage).parent() CheckUser(parent.author, rMessage) else: CheckUser(reddit.redditor(re.sub('/.*?/','', rMessage.body)), rMessage) except: rMessage.reply('Error parsing: /u/' + re.sub('/.*?/','', rMessage.body))<file_sep>decorator==4.0.11 praw==4.2.0 prawcore==0.6.0 Pygments==2.0.2 requests==2.12.5 six==1.10.0 update-checker==0.16 cryptography==1.8.1
d20741f3c94ff9097f30f4af8f99809dc18088cc
[ "Markdown", "Python", "Text" ]
3
Markdown
bswearingen/ThisBotFindsFascists
90cc8579c72240869d413c54ad3f707c56d63df6
3ed9551d486271fc89bf43759cf3991a0a778969
refs/heads/main
<repo_name>SimpleArt/recursive_cache<file_sep>/examples.py from recursive_cache import recursive_cache @recursive_cache def fib(n): """Testing if it can evaluate deep recursion.""" return n if n < 2 else fib(n-2) + fib(n-1) @recursive_cache def foo(n): """Testing if it can handle exceptions bouncing between multiple recursive functions.""" if n < 0: raise ValueError return bar(n-1) @recursive_cache def bar(n): """Test helper for foo.""" return foo(n-1) @recursive_cache def func1(n): if n <= 0: raise ValueError return func2(n, n) @recursive_cache def func2(m, n): if n <= 0: return func1(m-1) return func3(m, n-1) @recursive_cache def func3(m, n): return func2(m, n-1) print(fib(3000)) print(foo(3000)) print(func1(3000)) <file_sep>/recursive_cache.py from __future__ import annotations import sys from typing import overload, Any, Callable, Dict, Hashable, Iterable, Iterator, Mapping, NoReturn, Sequence, Tuple, TypeVar from types import TracebackType from functools import wraps from itertools import groupby E = TypeVar("E", bound=Exception) S = TypeVar("S", bound=Hashable) T = TypeVar("T") TypedCallable = TypeVar("TypedCallable", bound=Callable[..., Any]) # arguments should be Hashable KeyType = Tuple[Tuple[Hashable], Tuple[Tuple[str, Hashable]]] HashifyType = Callable[[T, Dict[KeyType, T], KeyType], S] UnhashifyType = Callable[[T, Dict[KeyType, T], KeyType], S] # Global flag for toggling if the traceback should be stripped of anything from this module. STRIP_TRACEBACK = True toggle_message = f""" toggle {__name__}.STRIP_TRACEBACK to enable/disable reduced traceback. When enabled, the traceback is stripped of parts from {__name__} except for the last raise, repeated cycles of traceback are extracted out as chained exceptions, and the middle of the traceback is deleted so that only 90% of the sys.getrecursionlimit() is reached, since usually most of the traceback is repeating itself past that point. Note that tracebacks are limited to the most recent calls up to the system recursion limit, so deleting repeated information may be beneficial for seeing the original source of the exception. Note that chained recursion exceptions are in the form: recent traceback causes recursive traceback causes exception in original call which flattens out into: exception in original call recursive traceback recursive traceback recursive traceback ... recent traceback This helps you find the original call first at the end of the traceback and makes recursive calls more compact.""" class InfoException(Exception): """Used to raise from when stripping the traceback to provide additional information.""" def __init__(self, msg: str = toggle_message, *args): super().__init__(msg, *args) # True if this is the main call, False if this is a recursive call. _base_call = True # Store cached functions in the form: # func_cache[func_id] = (func, cache) _func_cache = list() # Store calls that are currently being evaluated in the form: # temp_cache[func_id, args, kwargs] = None _temp_cache = dict() def identity(x: T) -> T: return x def equal_tracebacks(tb1: TracebackType, tb2: TracebackType) -> bool: """Compares two tracebacks.""" return ( tb1.tb_lasti == tb2.tb_lasti and tb1.tb_lineno == tb2.tb_lineno and all( getattr(tb1.tb_frame, f_attr) == getattr(tb2.tb_frame, f_attr) for f_attr in dir(tb1.tb_frame) if f_attr.startswith("f_") if f_attr not in {"f_back", "f_locals"} ) ) def traceback_iter(tb: TracebackType) -> Iterator[TracebackType]: """Loops through the traceback, starting from source to most recent call.""" while tb is not None: yield tb tb = tb.tb_next def traceback_join(tbs: Iterable[TracebackType]) -> TracebackType: """Merges the traceback back together, starting from source to most recent call.""" it = iter(tbs) root_tb = curr_tb = next(it, None) for tb in it: curr_tb.tb_next = tb curr_tb = tb curr_tb.tb_next = None return root_tb def strip_traceback(e: E) -> E: """ Strips the traceback of anything from this module, removes repeated cycles of traceback, and shortens the traceback if its too long. """ # Strip the traceback of anything from this file. e.with_traceback(traceback_join( tb for tb in traceback_iter(e.__traceback__) if tb.tb_frame.f_code.co_filename != __spec__.origin )) tracebacks = list(traceback_iter(e.__traceback__)) # Detect cycles in the traceback starting from the middle. for index in range(len(tracebacks) // 2, len(tracebacks) * 3 // 4): pointer = tracebacks[index] # Find the length of the cycle, assuming the next match is a cycle. cycle_start = next( ( i for i in reversed(range(index)) if equal_tracebacks(tracebacks[i], pointer) ), None, ) # Cycle possibly exists. if cycle_start is not None: cycle = tracebacks[cycle_start:index] # Find all cycles. cycles = [ i for i in range(len(tracebacks)) if all( equal_tracebacks(tb1, tb2) for tb1, tb2 in zip(tracebacks[i:i+len(cycle)], cycle) ) ] # Find the contiguous groups of cycles. subcycles = (cyc - len(cycle) * i for i, cyc in enumerate(cycles)) grouped_cycles = [list(group) for _, group in groupby(cycles, lambda _: next(subcycles))] cause = None # Delete from the traceback in reversed order. for group in reversed(grouped_cycles): # Only pull out groups that are sufficiently long. if len(cycle) > 1 and len(group) > 3: # Pull out the source of the exception that was called by the recursion. if group[-1] + len(cycle) < len(tracebacks): next_cause = InfoException( f"[Previous lines caused an exception in the below recursion]" ).with_traceback(traceback_join(tracebacks[group[-1]+len(cycle):])) next_cause.__cause__ = cause cause = next_cause # Pull out the recursion. next_cause = InfoException( f"[Previous {len(cycle)} lines repeated {len(group)-1} more times " f"and caused an exception in the code below which called it]" ).with_traceback(traceback_join(tracebacks[group[0]:group[1]])) next_cause.__cause__ = cause cause = next_cause # Cut it off of the tracebacks. del tracebacks[group[0]:] # Nothing to chain? if cause is None: continue # Chain the exceptions together. base_cause = e while base_cause.__cause__ is not None: base_cause = base_cause.__cause__ base_cause.__cause__ = cause break # If still too long, delete the middle portion. max_traceback = sys.getrecursionlimit() * 9 // 10 if len(tracebacks) > max_traceback: del tracebacks[max_traceback // 2 : len(tracebacks) - max_traceback // 2] # Use the new tracebacks. return e.with_traceback(traceback_join(tracebacks)) def raise_exception(e: Exception) -> NoReturn: """Re-raise an exception.""" raise e def hashify(obj: T, cache: Dict[KeyType, T], key: KeyType) -> Tuple[Callable[[S], T], S]: """ Store a shallow hashable copy of an object into the cache with the given key. Cases: - Use type(obj).copy(obj) if type(obj) has a copy method. - Hash Exception as obj itself. Unhash by raising obj. - Hash Hashable as obj itself. - Hash set as frozenset. - Hash Mapping as tuple(obj.items()). Unhash as dict(tuple). - Hash Iterator as obj. Unhash as iter(obj). - Hash Iterable or Sequence as tuple(obj). Unhash as tuple. - Otherwise just use the given object. """ if hasattr(type(obj), "copy"): cache[key] = (type(obj).copy, obj) elif isinstance(obj, Exception): cache[key] = (raise_exception, obj) elif isinstance(obj, Hashable): cache[key] = (identity, obj) elif isinstance(obj, set): cache[key] = (set, frozenset(obj)) elif isinstance(obj, Mapping): cache[key] = (dict, tuple(obj.items())) elif isinstance(obj, Iterator): cache[key] = (iter, obj) elif isinstance(obj, (Iterable, Sequence)): cache[key] = (identity, tuple(obj)) else: cache[key] = (identity, obj) return cache[key] def unhashify(obj: Tuple[Callable[[S], T], S], cache: Dict[KeyType, T], key: KeyType) -> T: """ Return an unhashed object. If obj[1] is an Exception or Iterator, it is removed from the cache. """ if isinstance(obj[1], (Exception, Iterator)): return obj[0](cache.pop(key)[1]) return obj[0](obj[1]) @overload def recursive_cache(*, hashify: HashifyType = hashify, unhashify: UnhashifyType = unhashify) -> Callable[[TypedCallable], TypedCallable]: ... @overload def recursive_cache(func: TypedCallable, *, hashify: HashifyType = hashify, unhashify: UnhashifyType = unhashify) -> TypedCallable: ... def recursive_cache(*args, hashify = hashify, unhashify = unhashify): """ Caches a function to avoid repeating completed function calls and handles recursive functions which require more calls than the call stack limit. Check help(hashify) to view the caching behavior. If the call stack limit is reached, function calls are cleared and the latest unfinished function call is re-called and cached if finished. Takes at most roughly double the amount of function calls to finish. Relies on RecursionError to work. """ # Parse overloaded function. if len(args) == 0: return lambda func, /: recursive_cache(func, hashify, unhashify) elif len(args) > 1: raise TypeError(f"recursive_cache() takes 0 or 1 positional arguments but {len(args)} were given") func = args[0] # Already cached function. if any(func == f for f, cache in _func_cache): return func # Store results in the cache. cache = dict() func_id = len(_func_cache) _func_cache.append((func, cache)) # Make the wrapper look like the given func. @wraps(func) def wrapper(*args: Hashable, **kwargs: Hashable) -> Any: global _base_call # Check if this is a recursive call or not. local_call = _base_call # Future calls must be recursive calls. _base_call = False # Break down the args and kwargs into tuple keys. key = (func_id, tuple(args), tuple(kwargs.items())) # Already running current call means infinite recursion. if key in _temp_cache: raise RecursionError("infinite recursion") # Store current call if we haven't computed it before. if key[1:] not in cache: _temp_cache[key] = None # Base call loop: # Re-calls the last call to continue making progress # while caching them to avoid recomputing # until every call is in the cache. while local_call and _temp_cache: # Get the last call that needs evaluating. temp_key = next(reversed(_temp_cache)) func_key = temp_key[0] temp_args = temp_key[1:] temp_func, temp_func_cache = _func_cache[func_key] # Attempt the next function call. try: hashify(temp_func(*temp_args[0], **dict(temp_args[1])), temp_func_cache, temp_args) # If too many calls occur, reset the stack. except RecursionError as e: # If infinite recursion, stop. if str(e) == "infinite recursion": _base_call = True _temp_cache.clear() raise e # If we make no further progress, stop. elif temp_key == next(reversed(_temp_cache)): _base_call = True _temp_cache.clear() raise RecursionError("recursion blocked by other functions") from e # If an exception occurs, store it for re-raising and remove the call from the stack. except Exception as e: hashify(e, temp_func_cache, temp_args) del _temp_cache[temp_key] # If no exceptions occur, the temp_key succeeded and can be removed. else: del _temp_cache[temp_key] try: # If the key is already in the cache, unhash it. if key[1:] in cache: result = unhashify(cache[key[1:]], cache, key[1:]) # Otherwise compute it. else: result = unhashify(hashify(func(*args, **kwargs), cache, key[1:]), cache, key[1:]) # Don't do anything to RecursionError. except RecursionError as e: raise e # Other exceptions are the expected result of the function. # For example, they may be caught later. # Remove it from the cache and re-raise the exception. except Exception as e: if key in _temp_cache: del _temp_cache[key] # On the last raise before exiting the wrapper, # if toggled (which is by default), # then strip the traceback of anything from this module # and raise it from an additional custom info exception. if local_call and STRIP_TRACEBACK: e = strip_traceback(e) cause = e while cause.__cause__ is not None: cause = cause.__cause__ cause.__cause__ = InfoException() raise e # Otherwise just raise the exception normally. else: raise e # The result is properly finished. # Remove it from the cache and return the result. else: if key in _temp_cache: del _temp_cache[key] return result # Ensure the base call gets reset. finally: _base_call = local_call return wrapper <file_sep>/README.md Python is well known for its conservative restriction on the amount of recursive calls one may have at any given moment. One way to work around this is to cache results to avoid recursing deeper when unnecessary. The issue with this approach is that you need to start finishing recursive calls and caching their results before the amount of recursive calls becomes too large. This module seeks to provide an alternative caching mechanism which allows deep recursion that goes well beyond the recursion limit. Examples may be seen in the `examples.py` file. # Deep Recursion Recursion may be done deeper than the recursion limit without modifying the recursion limit or call stack. Here's an example of a memoized fibonacci function involving recursion deeper than `functools.lru_cache` can handle: ```python @recursive_cache def fib(n): return n if n < 2 else fib(n-2) + fib(n-1) print(fib(3000)) ``` # Iterators Iterators, such as generators, cannot be easily handled. This is because they are lazily evaluated and wait until a value is requested to begin computation. Furthermore, they are one-time-use objects which must be re-evaluated on every call. However, this does mean deep recursion with iterators is impossible. It just means that any deep recursion must be taken care of *before* the iterator starts. This might mean using `itertools.chain` and generator expressions instead of generators. For example, the following generator does not successfully run due to blocking recursion when used: ```python from number_theory import is_prime @recursive_cache def generator(n): if n >= 0: for i in range(n): if is_prime(i): yield i yield from generator(n-1) ``` The following is a corrected version using `return` and `filter` to perform the recursion before any iteration occurs while still allowing mostly lazy iterators: ```python from itertools import chain from number_theory import is_prime @recursive_cache def generator(n): if n >= 0: return chain(filter(is_prime, range(n)), generator(n-1)) return iter([]) ``` Or using generator expressions: ```python from itertools import chain from number_theory import is_prime @recursive_cache def generator(n): if n >= 0: return chain((i for i in range(n) if is_prime(i)), generator(n-1)) return iter([]) ``` Another solution is to wrap the generator and pre-compute anything that occurs recursively outside: ```python from itertools import chain from number_theory import is_prime # Isolate the generator from the recursion. def helper(n, iterable): for i in range(n): if is_prime(i): yield i yield from iterable # Isolate the recursion from the generator. @recursive_cache def generator(n): return helper(n, generator(n-1)) if n >= 0 else iter([]) ``` # Exceptions/Traceback Additionally, exception traceback is reduced by default to make recursive tracebacks more understandable. Note that normally such tracebacks will be fully expanded and then truncated to the recursion limit, which is extremely unhelpful if the majority of it is the same few lines repeated thousands of times. ```python >>> @recursive_cache ... def foo(n): ... if n < 0: ... raise ValueError ... return bar(n-1) ... >>> @recursive_cache ... def bar(n): ... return foo(n-1) ... >>> foo(3000) recursive_cache.InfoException: ... The above exception was the direct cause of the following exception: Traceback (most recent call last): ... recursive_cache.InfoException: [Previous lines caused an exception in the below recursion] The above exception was the direct cause of the following exception: Traceback (most recent call last): ... recursive_cache.InfoException: [Previous 2 lines repeated 1499 more times and caused an exception in the code below which called it] The above exception was the direct cause of the following exception: Traceback (most recent call last): ... ValueError ```
1e77e25f5457a150ab7ea54051f6e8a5722a9949
[ "Markdown", "Python" ]
3
Python
SimpleArt/recursive_cache
2d0fbecddfe9acdb7111ecf78b72c92cdaf0e49b
d53dd8349c9da0e6fe039a43cd8eff7c5d6c4ea4
refs/heads/master
<file_sep># Non-wearable AI Elderly Home (LEGO Mindstorms EV3) IVE Final Year Project : Non-wearable AI Elderly Home (LEGO Mindstorms EV3) ## Background What if an elderly, due to a stroke or other health issue and without notice, needs attention? What if there is no one around to help him or her? In Hong Kong, there are so many tragedies resulting in the death of some elderly. ## Concept ["Non-wearable AI Elderly Home"](https://www.linkedin.com/pulse/non-wearable-ai-elderly-home-kai-wing-man/) is an automated AI system that detects a single elderly who falls down and immediately calls for emergency assistance. It is a combination of AI and IoT with cloud computing to provide a multi-functional watchdog system. ## Set up ev3dev Following the below instructions to set up the basic configuration for ev3. https://www.ev3dev.org/docs/getting-started/ Connect to the ev3dev and run below command. ```bash apt-get update sudo apt-get install cron ``` Change the file permission that make sure the cron job can run it. ```bash sudo chmod -R +x /home/robot ``` Create a cron job to check the script is running. ```bash crontab -l crontab -e ``` Add the following line to create a cron job. ```bash */10 * * * * /home/robot/ev3dev/cronjob_checker.sh ``` ## Reference https://www.ev3dev.org/ https://python-ev3dev.readthedocs.io/en/ev3dev-stretch/index.html https://github.com/aws/aws-iot-device-sdk-python <file_sep>#!/usr/bin/env python3 from time import sleep, time from __init__ import debug_print from ev3dev2.motor import LargeMotor, OUTPUT_A, OUTPUT_D, SpeedPercent, MoveTank from ev3dev2.sensor.lego import TouchSensor, GyroSensor, UltrasonicSensor from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3 gyro_sensor = GyroSensor(INPUT_1) # 2 sonic_sensor = UltrasonicSensor(INPUT_2) touch_sensor = TouchSensor(INPUT_3) # 3 gyro_sensor.mode='GYRO-ANG' sonic_sensor.mode='US-DIST-CM' # Attach large motors to ports B and C mA = LargeMotor('outA') mD = LargeMotor('outD') def touchsensor_hit(): if touch_sensor.is_pressed: return True else: return False def move_ev3(action): # action = move_forword, move_backward, turn_left, turn_right try: if action == 'move_forword': speed = 360 elif action == 'move_backward': speed = -360 else: speed = 100 t_end = time() + 1 if action != 'turn_left': mA.run_forever(speed_sp=speed) if action != 'turn_right': mD.run_forever(speed_sp=speed) if action == 'move_forword' or 'move_backward': while sonic_sensor.value() > 200 and not touchsensor_hit() and time() < t_end: sleep(0.005) else: if sonic_sensor.value() < 200: debug_print('Detected something in front of the robot during moving.') return if touchsensor_hit(): debug_print("Robot hit something during moving") return else: gyro_sensor.reset() while sonic_sensor.value() > 200 and not touchsensor_hit() and gyro_sensor.value() < 15: sleep(0.005) else: if sonic_sensor.value() < 200: debug_print('Detected something in front of the robot during moving.') return if touchsensor_hit(): debug_print("Robot hit something during moving") return if action != 'turn_left': mA.stop(stop_action="brake") if action != 'turn_right': mD.stop(stop_action="brake") except: debug_print('fill wrong action')<file_sep>#!/usr/bin/env python3 from iot.toAWS import toAWSIoT from config import TOPIC def main(): toAWSIoT(TOPIC) #iot/ev3 if __name__ == "__main__": main()<file_sep>import time from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient from logs.logger import create_logger from control import move_ev3 def test_connection_with_AWS(): myMQTTClient = AWSIoTMQTTClient("ev3") myMQTTClient.configureEndpoint("a3vp0n4b48aqlf-ats.iot.us-east-1.amazonaws.com", 8883) myMQTTClient.configureCredentials(u"/home/robot/cert/AmazonRootCA1.pem", u"/home/robot/cert/391ba739a7-private.pem.key", u"/home/robot/cert/391ba739a7-certificate.pem.crt") myMQTTClient.configureOfflinePublishQueueing(-1) myMQTTClient.configureDrainingFrequency(2) myMQTTClient.configureConnectDisconnectTimeout(10) myMQTTClient.configureMQTTOperationTimeout(5) def customCallback(): pass myMQTTClient.connect() apple = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ) myMQTTClient.publish("myTopic", apple+"myPayload", 0) myMQTTClient.subscribe("myTopic", 1, customCallback) myMQTTClient.unsubscribe("myTopic") myMQTTClient.disconnect() def test_logger(): logger = create_logger('test') # 在 logs 目錄下建立 tutorial 目錄 logger.info('Start \n') def test_lego_control(): move_ev3('move_forword') move_ev3('move_backward') move_ev3('turn_left') move_ev3('turn_right') if __name__ == "__main__": test_connection_with_AWS() test_logger() test_lego_control()<file_sep>import logging import json import time import sys import AWSIoTPythonSDK from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient from control import move_ev3 from __init__ import debug_print from config import ELDERLY_ID, IOT_ENDPOINT from logs.logger import create_logger logging.basicConfig() MQTTClient = AWSIoTMQTTClient("ev3dev") def Callback(client, userdata, message): payload = message.payload.decode('utf8').replace("'", '"') debug_print("#Received a new message: ", payload) debug_print("#From topic: ", message.topic, "\n--------------\n\n") js = json.loads(payload) status = js['status'] check_elderly = js['elderly'] if ELDERLY_ID != check_elderly: return now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) #'2009-01-05 22:14:39' debug_print('status: ', status) topic = 'iot/ev3/action' logger = create_logger('ev3_activity') logger.info('Recive Meesage: '+str(payload)) # action = move_forword, move_backward, turn_left, turn_right if status == 'fall down': logger.info('Elderly fall down') return elif status == 'move forward': move_ev3('move_forword') logger.info('Ev3 move forward') return elif status == 'move backward': move_ev3('move_backward') logger.info('Ev3 move backward') return elif status == 'turn left': move_ev3('turn_left') logger.info('Ev3 turn left') return elif status == 'turn right': move_ev3('turn_right') logger.info('Ev3 turn right') return else: return def aws_iot_config(MQTTClient): logging.basicConfig() # Configurations # For TLS mutual authentication debug_print(IOT_ENDPOINT) MQTTClient.configureEndpoint(IOT_ENDPOINT, 8883) # For TLS mutual authentication with TLS ALPN extension MQTTClient.configureCredentials(u"/home/robot/cert/AmazonRootCA1.pem", u"/home/robot/cert/391ba739a7-private.pem.key", u"/home/robot/cert/391ba739a7-certificate.pem.crt") # Infinite offline Publish queueing MQTTClient.configureOfflinePublishQueueing(-1) MQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz MQTTClient.configureConnectDisconnectTimeout(10) # 10 sec MQTTClient.configureMQTTOperationTimeout(5) # 5 sec debug_print('#Config and Connected to AWS IoT') def publish_to_iot(topic, message): MQTTClient.publish(topic, message, 0) def toAWSIoT(topic): aws_iot_config(MQTTClient) while True: times_to_connect = 0 try: if times_to_connect == 10: sys.exit() MQTTClient.connect() break except Exception as e: connect_logger = create_logger('Connection') connect_logger.info('Start \n') connect_logger.error(e) debug_print('fail') debug_print(e) # Stop the internal worker MQTTClient._mqtt_core._event_consumer.stop() time.sleep(10) times_to_connect += 1 continue while True: MQTTClient.subscribe(topic, 1, Callback) #iot/ev3 debug_print('sleep') time.sleep(60) alive_time = str(int(time.time())) publish_to_iot("iot/ev3/alive", '{"elderly_id":"%s","alive_time":"%s"}'%(str(ELDERLY_ID), alive_time)) if __name__ == "__main__": pass <file_sep># !/bin/bash pid_file='/home/robot/ev3dev/main.pid' if [ ! -s "$pid_file" ] || ! kill -0 $(cat $pid_file) > /dev/null 2>&1; then echo $$ > "$pid_file" exec /usr/bin/python3.5 /home/robot/ev3dev/main.py fi <file_sep>IOT_ENDPOINT = "a3vp0n4b48aqlf-ats.iot.us-east-1.amazonaws.com" TOPIC = "iot/ev3" ELDERLY_ID = '001653654713' #BOARD_INFO_SERIAL_NUM<file_sep>import os import sys def debug_print(*args, **kwargs): '''Print debug messages to stderr. This shows up in the output panel in VS Code. ''' print(*args, **kwargs, file=sys.stderr)
c7850e262039bde2b0b624c2efac5c6c68d67a5d
[ "Markdown", "Python", "Shell" ]
8
Markdown
Ekko-Man/Non-wearable-AI-Elderly-Home-LEGO-Mindstorms-EV3
64c92070ddbedc763cefec43dd0066234f9c055c
e9d4eb78d6512d62ea4f98b38cb926934b6705ae
refs/heads/master
<repo_name>LaurelButler/knex-practice<file_sep>/src/practice.js //requiring the library const knex = require('knex') //using the environment variable require('dotenv').config() //invoking the knex() function. the arguments specify where to connect to, the username and password to use for connecting and which driver to use const knexInstance = knex({ client: 'pg', // connection: 'postgresql://dunder-mifflin@localhost/knex-practice', //if you set a password for the user, you need to specify the connection like this: // connection: 'postgresql://dunder-mifflin:password-here@localhost/knex-practice', //move the connection string into an environment variable, you dont want the connect details hard coded connection: process.env.DB_URL }) //to start building the query, you first tell the knex instance which table you want to query // const q1 = knexInstance('amazong_products').select('*').toQuery() // const q2 = knexInstance.from('amazong_products').select('*').toQuery() // console.log('q1:', q1) // console.log('q2:', q2) //this knexInstance shows all (*) // knexInstance.from('amazong_products').select('*') // .then(result => { // console.log(result) // }) //build a query to select the identifier, name, price, and category of one product: //the .first() method will only select the first item found knexInstance .select('product_id', 'name', 'price', 'category') .from('amazong_products') .where({ name: 'Point of view gun' }) .first() .then(result => { console.log(result) }) const qry = knexInstance .select('product_id', 'name', 'price', 'category') .from('amazong_products') .where({ name: 'Point of view gun' }) .first() .toQuery() // .then(result => { // console.log(result) // }) console.log(qry) //The LIKE operator specifies we want to search by a pattern //The % is a "wildcard" for 0 or more characters //This will allow 0 or more characters either side of the searchTerm. For example, the SQL we want would be like so if the searchTerm was "cheese": // SELECT product_id, name, price, category // FROM amazong_products // WHERE name LIKE '%cheese%'; but it must be changed to ILIKE which is the case insensitive search const searchTerm = 'holo' knexInstance .select('product_id', 'name', 'price', 'category') .from('amazong_products') .where('name', 'ILIKE', `%${searchTerm}%`) .then(result => { console.log(result) }) //put it in a function that accepts the searchTerm as a parameter so that we can use the word that the person decides when they're ready function searchByProduceName(searchTerm) { knexInstance .select('product_id', 'name', 'price', 'category') .from('amazong_products') .where('name', 'ILIKE', `%${searchTerm}%`) .then(result => { console.log(result) }) } searchByProduceName('holo') //You need to build a query that allows customers to paginate the amazong_products table products, 10 products at a time //use the LIMIT and OFFSET operators to achieve pagination. Limit tells us the number of items to display and offset will be the starting position in the list to count up to the limit from //we want page 4, to find the offset: we'd minus one from the page number (3), multiply this number by the limit, 10, giving us 30 // SELECT product_id, name, price, category // FROM amazong_products // LIMIT 10 // OFFSET 30; //paginateProducts function function paginateProducts(page) { const productsPerPage = 10 const offset = productsPerPage * (page - 1) knexInstance .select('product_id', 'name', 'price', 'category') .from('amazong_products') .limit(productsPerPage) .offset(offset) .then(result => { console.log(result) }) } paginateProducts(2) //You need to build a query that allows customers to filter the amazong_products table for products that have images //We can't use image != NULL in our query as it would return every row, in SQL NULL gets special treatment, two NULL values can't be equivalent. So, we need to use the IS NOT NULL operator // SELECT product_id, name, price, category, image // FROM amazong_products // WHERE image IS NOT NULL; //In knex, we use the .whereNotNull() method and supply a column name function getProductsWithImages() { knexInstance .select('product_id', 'name', 'price', 'category', 'image') .from('amazong_products') .whereNotNull('image') .then(result => { console.log(result) }) } getProductsWithImages() //You need to build a query that allows customers to see the most popular videos by view at Whopipe by region for the last 30 days //query the whopipe_video_views table. Each row in this table reflects one view of a video. Each row has a region that the video was viewed and the datetime of the view. We need to count the number of views for each combination of region and video name //We'll use the count() function to count the dates viewed // We'll group our results by a combination of the video's name and region // We'll sort the results by the region and order by the count with most popular first // We need to use a WHERE to filter only results within the last 30 days //count(date_viewed) to get the number of views for each combination of the GROUP BY video_name, region. We've also renamed the count(date_viewed) to "views" // SELECT video_name, region, count(date_viewed) AS views // FROM whopipe_video_views //used now() - '30 days'::INTERVAL to calculate the datetime that's 30 days before now by using 30 days::interval from now(). Then we look for any date_viewed that is greater than 30 days before now. // WHERE date_viewed > (now() - '30 days':: INTERVAL) // GROUP BY video_name, region // ORDER BY region ASC, views DESC; function mostPopularVideosForDays(days) { knexInstance .select('video_name', 'region') //To achieve the SQL count(date_viewed) AS views we needed to use the .count method instead of listing the column in the select method .count('date_viewed AS views') .where( 'date_viewed', '>', knexInstance.raw(`now() - '?? days'::INTERVAL`, days) ) .from('whopipe_video_views') .groupBy('video_name', 'region') //orderBy method allows us to "order by" multiple columns by specifying an array, we can also use objects in the array to specify different directions (ascending or descending) to "order by" .orderBy([ { column: 'region', order: 'ASC' }, { column: 'views', order: 'DESC' }, ]) .then(result => { console.log(result) }) } mostPopularVideosForDays(30) //Knex doesn't have methods for the now() - '30 days'::INTERVAL. Instead, knex provides a fallback method called .raw(). We can use the raw method to pass in "raw" SQL as a string. // An extra security measure is to tell the raw method that the raw SQL contains user input.We used ?? to tell knex that this is the position in the raw SQL that will contain user input.We then specify the value for the user input as the second argument to.raw().This is called a prepared statement<file_sep>/src/shopping-list.js require('dotenv').config() const knex = require('knex') const shoppingListService = require('./shopping-list-service') const knexInstance = knex({ client: 'pg', connection: process.env.DB_URL, }) //have to pass knexInstance into allItems from the shopping-list-service file function //this simply logs the data // console.log(shoppingListService.allItems(knexInstance)) //this logs all items in the shopping list shoppingListService.allItems(knexInstance).then(data => { console.log(data); })<file_sep>/sql-scripts/create.whopipe-and-amazong.sql -- this is first creating a table that has 4 columns -- the IF NOT EXISTS prevents the CREATE TABLE being attempted when the table already exists CREATE TABLE IF NOT EXISTS whopipe_video_views ( view_id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, video_name TEXT NOT NULL, region TEXT NOT NULL, date_viewed TIMESTAMP DEFAULT now() NOT NULL ); --this transaction and the third one create a new type called department which is an ENUM (enum is a list of options that may be used by columns (which have this new type) in table rows) --CREATE TYPE doesnt support IF NOT EXISTS; instead remove the type if it does exist first DROP TYPE IF EXISTS department; CREATE TYPE department AS ENUM ( 'Electronics', 'Cleaning', 'Grocery', 'Furniture', 'Stationery', 'Clothing', 'DIY', 'Sports', 'Homeware', 'Games', 'Transport' ); --this is to create a table that has 4 columns. price column is set to decimal which can be 12 in "precision" and 2 decimal points --when inserting rows into this table, their value for category needs to be one of those listed in the ENUM for department CREATE TABLE IF NOT EXISTS amazong_products ( product_id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, name TEXT NOT NULL, price decimal(12,2) NOT NULL, image TEXT, category department NOT NULL );<file_sep>/src/drills.js require('dotenv').config() const knex = require('knex') const knexInstance = knex({ client: 'pg', connection: process.env.DB_URL }); function searchName(searchTerm) { knexInstance .select('*') .from('shopping_list') .where('name', 'ILIKE', `%${searchTerm}%`) .then(result => { console.log({ searchTerm }) console.log(result) }) }; searchName('urger'); function getAllItemsPaginated(pageNumber) { const itemLimit = 6 const offset = itemLimit * (pageNumber - 1); knexInstance .select('*') .from('shopping_list') .limit(itemLimit) .offset(offset) .then(result => { console.log('PAGINATE ITEMS', { pageNumber }) console.log(result) }) }; getAllItemsPaginated(2); // function addedProducts(daysAgo) { // knexInstance // .select('*') // .from('shopping_list') // .where('date_added' '>' ) // } function costPerCategory() { knexInstance .select('category') .count('price as total') .from('shopping_list') .groupBy('category') .then(result => { console.log(result) }) } costPerCategory()
3037fa262017beda7b63ca3609f3c6360bc57708
[ "JavaScript", "SQL" ]
4
JavaScript
LaurelButler/knex-practice
a45283bd083a7f5ae40307231f5541ba5b11ea76
09e9bf05d657720dfeebafc60c92306fbf5742b0