branch_name
stringclasses
15 values
target
stringlengths
26
10.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
9
num_files
int64
1
1.47k
repo_language
stringclasses
34 values
repo_name
stringlengths
6
91
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
input
stringclasses
1 value
refs/heads/main
<file_sep># Add-ons The core package aims to be lightweight and dependence free. While the add-ons are wrapping popular packages into the consistent API style. ## Head - [`@vueuse/head`](https://github.com/vueuse/head) <carbon-link class="external-link"/> Document head manager for Vue 3. SSR ready. Created and maintained by [@egoist](https://github.com/egoist) ## Motion - [`@vueuse/motion`](https://github.com/vueuse/motion) <carbon-link class="external-link"/> **Vue Composables** putting your **components** in **motion**. - ๐ŸŽ **Smooth animations** based on [**Popmotion**](https://popmotion.io/) - ๐ŸŽฎ **Declarative** API - ๐Ÿš€ **Plug** & **play** with **10+ presets** - โœ… Supports **Vue 2 & 3** using [**vue-demi**](https://github.com/antfu/vue-demi) - ๐Ÿšš Supports **Nuxt** using [**nuxt-use-motion**](https://github.com/Tahul/nuxt-use-motion) - โœจ Written in **TypeScript** - ๐Ÿ‹๏ธโ€โ™€๏ธ Lightweight with **<20kb** bundle size > Created and maintained by [@Tahul](https://github.com/Tahul) ## Gesture - [`@vueuse/gesture`](https://github.com/vueuse/gesture) <carbon-link class="external-link"/> **Vue Composables** making your app **interactive** - ๐Ÿš€ **Plug** & **play** - ๐Ÿ•น **Mouse** & **Touch** support - ๐ŸŽฎ **Directives** support (**v-drag**, **v-pinch**, **v-move**...) - โœจ Written in **TypeScript** - โœ… Supports **Vue 2 & 3** using [**vue-demi**](https://github.com/antfu/vue-demi) - ๐Ÿคน Plays well with [**vueuse/motion**](https://github.com/vueuse/motion) or **any other** animation solution > Created and maintained by [@Tahul](https://github.com/Tahul) ## Sound - [`@vueuse/sound`](https://github.com/vueuse/sound) <carbon-link class="external-link"/> Vue composables for playing sound effects. - ๐Ÿ‘‚ Lets your website **communicate** using 2 **human senses** instead of 1 - ๐Ÿ”ฅ Built with **Vue** Composition API - โœ… Supports **Vue 2 & 3** using [**vue-demi**](https://github.com/antfu/vue-demi) - ๐Ÿšš Supports **Nuxt** using [**nuxt-use-sound**](https://github.com/Tahul/nuxt-use-sound) - โšก๏ธ **<1kb** bytes (gzip) in your **bundle**! **~10kb** loaded **async**. - โœจ Built with **TypeScript** - ๐Ÿ—ฃ Uses a powerful, battle-tested audio utility: [**Howler.js**](https://howlerjs.com/) > Created and maintained by [@Tahul](https://github.com/Tahul) <!--GENERATED LIST, DO NOT MODIFY MANUALLY--> <!--ADDONS_LIST_STARTS--> ## Router - [`@vueuse/router`](https://vueuse.org/router/README.html) Utilities for vue-router - [`useRouteHash`](https://vueuse.org/router/useRouteHash/) โ€” shorthand for reactive route.hash - [`useRouteQuery`](https://vueuse.org/router/useRouteQuery/) โ€” shorthand for reactive route.query ## Integrations - [`@vueuse/integrations`](https://vueuse.org/integrations/README.html) Integration wrappers for utility libraries - [`useAxios`](https://vueuse.org/integrations/useAxios/) โ€” wrapper for [`axios`](https://github.com/axios/axios) - [`useCookies`](https://vueuse.org/integrations/useCookies/) โ€” wrapper for [`universal-cookie`](https://www.npmjs.com/package/universal-cookie) - [`useDrauu`](https://vueuse.org/integrations/useDrauu/) โ€” reactive instance for [drauu](https://github.com/antfu/drauu) - [`useFocusTrap`](https://vueuse.org/integrations/useFocusTrap/) โ€” reactive wrapper for [`focus-trap`](https://github.com/focus-trap/focus-trap) - [`useFuse`](https://vueuse.org/integrations/useFuse/) โ€” reactive wrapper for [Fuse.js](https://github.com/krisk/fuse) - [`useJwt`](https://vueuse.org/integrations/useJwt/) โ€” wrapper for [`jwt-decode`](https://github.com/auth0/jwt-decode) - [`useNProgress`](https://vueuse.org/integrations/useNProgress/) โ€” reactive wrapper for [`nprogress`](https://github.com/rstacruz/nprogress) - [`useQRCode`](https://vueuse.org/integrations/useQRCode/) โ€” wrapper for [`qrcode`](https://github.com/soldair/node-qrcode) ## RxJS - [`@vueuse/rxjs`](https://vueuse.org/rxjs/README.html) Enables RxJS reactive functions in Vue - [`from`](https://vueuse.org/rxjs/from/) โ€” / fromEvent - [`toObserver`](https://vueuse.org/rxjs/toObserver/) โ€” sugar function to convert a ref in an observer - [`useObservable`](https://vueuse.org/rxjs/useObservable/) โ€” use an Observable - [`useSubscription`](https://vueuse.org/rxjs/useSubscription/) โ€” uses subscriptions without worry about unsubscribing to it or memory leaks ## Firebase - [`@vueuse/firebase`](https://vueuse.org/firebase/README.html) Enables realtime bindings for Firebase - [`useAuth`](https://vueuse.org/firebase/useAuth/) โ€” reactive [Firebase Auth](https://firebase.google.com/docs/auth) binding - [`useFirestore`](https://vueuse.org/firebase/useFirestore/) โ€” reactive [Firestore](https://firebase.google.com/docs/firestore) binding - [`useRTDB`](https://vueuse.org/firebase/useRTDB/) โ€” reactive [Firebase Realtime Database](https://firebase.google.com/docs/database) binding ## Electron - [`@vueuse/electron`](https://vueuse.org/electron/README.html) Electron renderer process modules for VueUse - [`useIpcRenderer`](https://vueuse.org/electron/useIpcRenderer/) โ€” provides [ipcRenderer](https://www.electronjs.org/docs/api/ipc-renderer) and it's all APIs - [`useIpcRendererInvoke`](https://vueuse.org/electron/useIpcRendererInvoke/) โ€” reactive [ipcRenderer.invoke API](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererinvokechannel-args) result - [`useIpcRendererOn`](https://vueuse.org/electron/useIpcRendererOn/) โ€” use [ipcRenderer.on](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendereronchannel-listener) with ease and [ipcRenderer.removeListener](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererremovelistenerchannel-listener) automatically on unmounted - [`useZoomFactor`](https://vueuse.org/electron/useZoomFactor/) โ€” reactive [WebFrame](https://www.electronjs.org/docs/api/web-frame#webframe) zoom factor - [`useZoomLevel`](https://vueuse.org/electron/useZoomLevel/) โ€” reactive [WebFrame](https://www.electronjs.org/docs/api/web-frame#webframe) zoom level <!--ADDONS_LIST_ENDS--> <file_sep>export * from './useAxios' export * from './useCookies' export * from './useDrauu' export * from './useFocusTrap' export * from './useFuse' export * from './useJwt' export * from './useNProgress' export * from './useQRCode' <file_sep>import { resolve, join, relative } from 'path' import fs from 'fs-extra' import matter from 'gray-matter' import fg from 'fast-glob' import parser from 'prettier/parser-typescript' import prettier from 'prettier' import YAML from 'js-yaml' import { packages } from '../meta/packages' import { PackageIndexes, VueUseFunction, VueUsePackage } from '../meta/types' const DOCS_URL = 'https://vueuse.org' const GITHUB_BLOB_URL = 'https://github.com/vueuse/vueuse/blob/main/packages' const DIR_ROOT = resolve(__dirname, '..') const DIR_SRC = resolve(__dirname, '../packages') const DIR_TYPES = resolve(__dirname, '../types/packages') export async function getTypeDefinition(pkg: string, name: string): Promise<string | undefined> { const typingFilepath = join(DIR_TYPES, `${pkg}/${name}/index.d.ts`) if (!fs.existsSync(typingFilepath)) return let types = await fs.readFile(typingFilepath, 'utf-8') if (!types) return // clean up types types = types .replace(/import\(.*?\)\./g, '') .replace(/import[\s\S]+?from ?["'][\s\S]+?["']/g, '') return prettier .format( types, { semi: false, parser: 'typescript', plugins: [parser], }, ) .trim() } export function hasDemo(pkg: string, name: string) { return fs.existsSync(join(DIR_SRC, pkg, name, 'demo.vue')) } export function getFunctionHead(pkg: string, name: string) { let head = packages.find(p => p.name === pkg)!.addon ? `available in add-on [\`@vueuse/${pkg}\`](/${pkg}/README)` : '' if (head) head = `\n::: tip\n${head}\n:::\n` return head } export async function getFunctionFooter(pkg: string, name: string) { const URL = `${GITHUB_BLOB_URL}/${pkg}/${name}` const hasDemo = fs.existsSync(join(DIR_SRC, pkg, name, 'demo.vue')) const types = await getTypeDefinition(pkg, name) const typingSection = types && `## Type Declarations\n\n\`\`\`typescript\n${types.trim()}\n\`\`\`` const links = ([ ['Source', `${URL}/index.ts`], hasDemo ? ['Demo', `${URL}/demo.vue`] : undefined, ['Docs', `${URL}/index.md`], ]) .filter(i => i) .map(i => `[${i![0]}](${i![1]})`).join(' โ€ข ') const sourceSection = `## Source\n\n${links}\n` return `${typingSection || ''}\n\n${sourceSection}\n` } export async function listFunctions(dir: string, ignore: string[] = []) { const files = await fg('*', { onlyDirectories: true, cwd: dir, ignore: [ '_*', 'dist', 'node_modules', ...ignore, ], }) files.sort() return files } export async function readIndexes() { const indexes: PackageIndexes = { packages: {}, categories: [], functions: [], } for (const info of packages) { const dir = join(DIR_SRC, info.name) const functions = await listFunctions(dir) const pkg: VueUsePackage = { ...info, dir: relative(DIR_ROOT, dir).replace(/\\/g, '/'), docs: info.addon ? `${DOCS_URL}/${info.name}/README.html` : undefined, } indexes.packages[info.name] = pkg for (const fnName of functions) { const mdPath = join(dir, fnName, 'index.md') const fn: VueUseFunction = { name: fnName, package: pkg.name, } if (fs.existsSync(join(dir, fnName, 'component.ts'))) fn.component = true if (fs.existsSync(join(dir, fnName, 'directive.ts'))) fn.directive = true if (!fs.existsSync(mdPath)) { fn.internal = true indexes.functions.push(fn) continue } fn.docs = `${DOCS_URL}/${pkg.name}/${fnName}/` const mdRaw = await fs.readFile(join(dir, fnName, 'index.md'), 'utf-8') const { content: md, data: frontmatter } = matter(mdRaw) const category = frontmatter.category let description = (md .replace(/\r\n/g, '\n') .match(/# \w+[\s\n]+(.+?)(?:, |\. |\n|\.\n)/m) || [] )[1] || '' description = description.trim() description = description.charAt(0).toLowerCase() + description.slice(1) fn.category = ['core', 'shared'].includes(pkg.name) ? category : `@${pkg.display}` fn.description = description if (description.includes('DEPRECATED')) fn.depreacted = true indexes.functions.push(fn) } } indexes.categories = getCategories(indexes.functions) return indexes } export function getCategories(functions: VueUseFunction[]): string[] { return uniq( functions .filter(i => !i.internal) .map(i => i.category) .filter(Boolean), ).sort() } export async function updateImport({ packages, functions }: PackageIndexes) { for (const { name, dir, manualImport } of Object.values(packages)) { if (manualImport) continue let imports: string[] if (name === 'components') { imports = functions .sort((a, b) => a.name.localeCompare(b.name)) .flatMap((fn) => { const arr: string[] = [] // don't include integration components if (fn.package === 'integrations') return arr if (fn.component) arr.push(`export * from '../${fn.package}/${fn.name}/component'`) if (fn.directive) arr.push(`export * from '../${fn.package}/${fn.name}/directive'`) return arr }) } else { imports = functions .filter(i => i.package === name) .map(f => f.name) .sort() .map(name => `export * from './${name}'`) } if (name === 'core') { imports.push( 'export * from \'./types\'', 'export * from \'@vueuse/shared\'', ) } await fs.writeFile(join(dir, 'index.ts'), `${imports.join('\n')}\n`) } } export function uniq<T extends any[]>(a: T) { return Array.from(new Set(a)) } export function stringifyFunctions(functions: VueUseFunction[], title = true) { let list = '' const categories = getCategories(functions) for (const category of categories) { if (category.startsWith('_')) continue if (title) list += `### ${category}\n` const categoryFunctions = functions.filter(i => i.category === category).sort((a, b) => a.name.localeCompare(b.name)) for (const { name, docs, description, depreacted } of categoryFunctions) { if (depreacted) continue const desc = description ? ` โ€” ${description}` : '' list += ` - [\`${name}\`](${docs})${desc}\n` } list += '\n' } return list } export function replacer(code: string, value: string, key: string, insert: 'head' | 'tail' | 'none' = 'none') { const START = `<!--${key}_STARTS-->` const END = `<!--${key}_ENDS-->` const regex = new RegExp(`${START}[\\s\\S]*?${END}`, 'im') const target = value ? `${START}\n${value}\n${END}` : `${START}${END}` if (!code.match(regex)) { if (insert === 'none') return code else if (insert === 'head') return `${target}\n\n${code}` else return `${code}\n\n${target}` } return code.replace(regex, target) } export async function updatePackageREADME({ packages, functions }: PackageIndexes) { for (const { name, dir } of Object.values(packages)) { const readmePath = join(dir, 'README.md') if (!fs.existsSync(readmePath)) continue const functionMD = stringifyFunctions(functions.filter(i => i.package === name), false) let readme = await fs.readFile(readmePath, 'utf-8') readme = replacer(readme, functionMD, 'FUNCTIONS_LIST') await fs.writeFile(readmePath, `${readme.trim()}\n`, 'utf-8') } } export async function updateIndexREADME({ packages, functions }: PackageIndexes) { let readme = await fs.readFile('README.md', 'utf-8') const functionsCount = functions.filter(i => !i.internal).length readme = readme.replace(/img\.shields\.io\/badge\/-(.+?)%20functions/, `img.shields.io/badge/-${functionsCount}%20functions`) await fs.writeFile('README.md', `${readme.trim()}\n`, 'utf-8') } export async function updateFunctionsMD({ packages, functions }: PackageIndexes) { let mdFn = await fs.readFile('packages/functions.md', 'utf-8') const coreFunctions = functions.filter(i => ['core', 'shared'].includes(i.package)) const functionListMD = stringifyFunctions(coreFunctions) mdFn = replacer(mdFn, functionListMD, 'FUNCTIONS_LIST') await fs.writeFile('packages/functions.md', mdFn, 'utf-8') let mdAddons = await fs.readFile('packages/add-ons.md', 'utf-8') const addons = Object.values(packages) .filter(i => i.addon && !i.deprecated) .map(({ docs, name, display, description }) => { return `## ${display} - [\`@vueuse/${name}\`](${docs})\n${description}\n${ stringifyFunctions(functions.filter(i => i.package === name), false)}` }) .join('\n') mdAddons = replacer(mdAddons, addons, 'ADDONS_LIST') await fs.writeFile('packages/add-ons.md', mdAddons, 'utf-8') } export async function updateFunctionREADME(indexes: PackageIndexes) { const hasTypes = fs.existsSync(DIR_TYPES) if (!hasTypes) console.warn('No types dist found, run `npm run build:types` first.') for (const fn of indexes.functions) { const mdPath = `packages/${fn.package}/${fn.name}/index.md` if (!fs.existsSync(mdPath)) continue let readme = await fs.readFile(mdPath, 'utf-8') const { content, data = {} } = matter(readme) data.category = fn.category || 'Unknown' readme = `---\n${YAML.dump(data)}---\n\n${content.trim()}` await fs.writeFile(mdPath, `${readme.trim()}\n`, 'utf-8') } } export async function updatePackageJSON(indexes: PackageIndexes) { const { version } = await fs.readJSON('package.json') for (const { name, description, author, submodules, iife } of packages) { const packageDir = join(DIR_SRC, name) const packageJSONPath = join(packageDir, 'package.json') const packageJSON = await fs.readJSON(packageJSONPath) packageJSON.version = version packageJSON.description = description || packageJSON.description packageJSON.author = author || '<NAME> <https://github.com/antfu>' packageJSON.bugs = { url: 'https://github.com/vueuse/vueuse/issues', } packageJSON.homepage = name === 'core' ? 'https://github.com/vueuse/vueuse#readme' : `https://github.com/vueuse/vueuse/tree/main/packages/${name}#readme` packageJSON.main = './index.cjs' packageJSON.types = './index.d.ts' packageJSON.module = './index.mjs' if (iife !== false) { packageJSON.unpkg = './index.iife.min.js' packageJSON.jsdelivr = './index.iife.min.js' } packageJSON.exports = { '.': { import: './index.mjs', require: './index.cjs', }, './*': './*', } if (submodules) { indexes.functions .filter(i => i.package === name) .forEach((i) => { packageJSON.exports[`./${i.name}`] = { import: `./${i.name}.mjs`, require: `./${i.name}.cjs`, } if (i.component) { packageJSON.exports[`./${i.name}/component`] = { import: `./${i.name}/component.mjs`, require: `./${i.name}/component.cjs`, } } }) } await fs.writeJSON(packageJSONPath, packageJSON, { spaces: 2 }) } } <file_sep>--- category: Sensors --- # useElementHover Reactive element's hover state. ## Usage ```vue <template> <button ref="myHoverableElement"> {{ isHovered }} </button> </template> <script setup> import { useElementHover } from '@vueuse/core' const myHoverableElement = ref() const isHovered = useElementHover(myHoverableElement) </script> ``` <file_sep>--- category: '@Integrations' --- # useFuse Reactive wrapper for [Fuse.js](https://github.com/krisk/fuse). ## Install ### NPM ```bash npm install fuse.js ``` ### Yarn ```bash yarn add fuse.js ``` ## Usage ```ts import { ref } from 'vue' import { useFuse } from '@vueuse/integrations/useFuse' const data = [ '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', ] const input = ref('<NAME>') const { results } = useFuse(input, data) /* * Results: * * { "item": "<NAME>", "index": 1 } * { "item": "<NAME>", "index": 0 } * { "item": "<NAME>", "index": 2 } * */ ``` <file_sep>--- category: '@Integrations' --- # useFocusTrap Reactive wrapper for [`focus-trap`](https://github.com/focus-trap/focus-trap) For more info on what options can be passed see [`createOptions`](https://github.com/focus-trap/focus-trap#createfocustrapelement-createoptions) in the `focus-trap` docs. ## Usage **Basic Usage** ```html <script setup> import { ref } from 'vue' import { useFocusTrap } from '@vueuse/integrations/useFocusTrap' const target = ref() const { hasFocus, activate, deactivate } = useFocusTrap(target) </script> <template> <div> <button @click="activate()">Activate</button> <div ref="target"> <span>Has Focus: {{ hasFocus }}</span> <input type="text" /> <button @click="deactivate()">Deactivate</button> </div> </div> </template> ``` **Automatically Focus** ```html <script setup> import { ref } from 'vue' import { useFocusTrap } from '@vueuse/integrations/useFocusTrap' const target = ref() const { hasFocus, activate, deactivate } = useFocusTrap(target, { immediate: true }) </script> <template> <div> <div ref="target">...</div> </div> </template> ``` ## Using Component This function can't properly activate focus on elements with conditional rendering. In this case, you can use the `UseFocusTrap` component. Focus Trap will be activated automatically on mounting this component and deactivated on unmount. ```html <script setup> import { ref } from 'vue' import { UseFocusTrap } from '@vueuse/integrations/useFocusTrap/component' const show = ref(false) </script> <template> <UseFocusTrap v-if="show"> <div class="modal">...</div> </UseFocusTrap> </template> ``` <file_sep>--- category: Sensors --- # useScroll Reactive scroll position and state ## Usage ```html <script setup lang="ts"> import { useScroll } from '@vueuse/core' const el = ref<HTMLElement | null>(null) const { x, y, isScrolling, arrivedState } = useScroll(el) </script> <template> <div ref="el"></div> </template> ``` ```js // With offsets const { x, y, isScrolling, arrivedState } = useScroll(el, { offset: { top: 30, bottom: 30, right: 30, left: 30 }, }) ``` <file_sep>/* eslint-disable @typescript-eslint/no-var-requires */ const disabled = [ 'useFetch', 'toRefs', ] /** * Auto import for VueUse in Nuxt * Usage: * * ```ts * // nuxt.config.js * export deafult { * buildModules: [ * '@vueuse/core/nuxt' * ] * } * ``` */ module.exports = function() { const { nuxt } = this nuxt.hook('autoImports:sources', (sources) => { sources.push({ from: '@vueuse/core', names: require('./indexes.json') .functions .filter(i => (i.package === 'core' || i.package === 'shared') && !i.internal) .map(i => i.name) .filter(i => i.length >= 4 && !disabled.includes(i)), }) }) } <file_sep>import { ref, unref } from 'vue-demi' import { Fn, Pausable, MaybeRef } from './types' export type FunctionArgs<Args extends any[] = any[], Return = void> = (...args: Args) => Return export interface FunctionWrapperOptions<Args extends any[] = any[], This = any> { fn: FunctionArgs<Args, This> args: Args thisArg: This } export type EventFilter<Args extends any[] = any[], This = any> = ( invoke: Fn, options: FunctionWrapperOptions<Args, This> ) => void export interface ConfigurableEventFilter { /** * Filter for if events should to be received. * * @see https://vueuse.org/guide/config.html#event-filters */ eventFilter?: EventFilter } /** * @internal */ export function createFilterWrapper<T extends FunctionArgs>(filter: EventFilter, fn: T) { function wrapper(this: any, ...args: any[]) { filter(() => fn.apply(this, args), { fn, thisArg: this, args }) } return wrapper as any as T } export const bypassFilter: EventFilter = (invoke) => { return invoke() } /** * Create an EventFilter that debounce the events * * @param ms */ export function debounceFilter(ms: MaybeRef<number>) { let timer: ReturnType<typeof setTimeout> | undefined const filter: EventFilter = (invoke) => { const duration = unref(ms) if (timer) clearTimeout(timer) if (duration <= 0) return invoke() timer = setTimeout(invoke, duration) } return filter } /** * Create an EventFilter that throttle the events * * @param ms * @param [trailing=true] * @param [leading=true] */ export function throttleFilter(ms: MaybeRef<number>, trailing = true, leading = true) { let lastExec = 0 let timer: ReturnType<typeof setTimeout> | undefined let preventLeading = !leading const clear = () => { if (timer) { clearTimeout(timer) timer = undefined } } const filter: EventFilter = (invoke) => { const duration = unref(ms) const elapsed = Date.now() - lastExec clear() if (duration <= 0) { lastExec = Date.now() return invoke() } if (elapsed > duration) { lastExec = Date.now() if (preventLeading) preventLeading = false else invoke() } else if (trailing) { timer = setTimeout(() => { lastExec = Date.now() if (!leading) preventLeading = true clear() invoke() }, duration) } if (!leading && !timer) timer = setTimeout(() => preventLeading = true, duration) } return filter } /** * EventFilter that gives extra controls to pause and resume the filter * * @param extendFilter Extra filter to apply when the PausableFilter is active, default to none * */ export function pausableFilter(extendFilter: EventFilter = bypassFilter): Pausable & { eventFilter: EventFilter } { const isActive = ref(true) function pause() { isActive.value = false } function resume() { isActive.value = true } const eventFilter: EventFilter = (...args) => { if (isActive.value) extendFilter(...args) } return { isActive, pause, resume, eventFilter } } <file_sep>export * from './and' export * from './biSyncRef' export * from './controlledComputed' export * from './controlledRef' export * from './createEventHook' export * from './createGlobalState' export * from './createSharedComposable' export * from './debouncedWatch' export * from './eagerComputed' export * from './extendRef' export * from './get' export * from './ignorableWatch' export * from './isDefined' export * from './makeDestructurable' export * from './not' export * from './or' export * from './pausableWatch' export * from './reactify' export * from './reactifyObject' export * from './reactivePick' export * from './refDefault' export * from './set' export * from './syncRef' export * from './throttledWatch' export * from './toReactive' export * from './toRefs' export * from './tryOnBeforeUnmount' export * from './tryOnMounted' export * from './tryOnScopeDispose' export * from './tryOnUnmounted' export * from './until' export * from './useCounter' export * from './useDebounce' export * from './useDebounceFn' export * from './useInterval' export * from './useIntervalFn' export * from './useLastChanged' export * from './useThrottle' export * from './useThrottleFn' export * from './useTimeout' export * from './useTimeoutFn' export * from './useToggle' export * from './utils' export * from './watchAtMost' export * from './watchOnce' export * from './watchWithFilter' export * from './whenever' <file_sep>import { ConfigurableFlush, watchWithFilter, ConfigurableEventFilter, MaybeRef, RemoveableRef } from '@vueuse/shared' import { ref, Ref, unref, shallowRef } from 'vue-demi' import { useEventListener } from '../useEventListener' import { ConfigurableWindow, defaultWindow } from '../_configurable' export type Serializer<T> = { read(raw: string): T write(value: T): string } export const StorageSerializers: Record<'boolean' | 'object' | 'number' | 'any' | 'string' | 'map' | 'set', Serializer<any>> = { boolean: { read: (v: any) => v === 'true', write: (v: any) => String(v), }, object: { read: (v: any) => JSON.parse(v), write: (v: any) => JSON.stringify(v), }, number: { read: (v: any) => Number.parseFloat(v), write: (v: any) => String(v), }, any: { read: (v: any) => v, write: (v: any) => String(v), }, string: { read: (v: any) => v, write: (v: any) => String(v), }, map: { read: (v: any) => new Map(JSON.parse(v)), write: (v: any) => JSON.stringify(Array.from((v as Map<any, any>).entries())), }, set: { read: (v: any) => new Set(JSON.parse(v)), write: (v: any) => JSON.stringify(Array.from((v as Set<any>).entries())), }, } export type StorageLike = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> export interface StorageOptions<T> extends ConfigurableEventFilter, ConfigurableWindow, ConfigurableFlush { /** * Watch for deep changes * * @default true */ deep?: boolean /** * Listen to storage changes, useful for multiple tabs application * * @default true */ listenToStorageChanges?: boolean /** * Write the default value to the storage when it does not existed * * @default true */ writeDefaults?: boolean /** * Custom data serialization */ serializer?: Serializer<T> /** * On error callback * * Default log error to `console.error` */ onError?: (error: unknown) => void /** * Use shallow ref as reference * * @default false */ shallow?: boolean } export function useStorage(key: string, initialValue: MaybeRef<string>, storage?: StorageLike, options?: StorageOptions<string>): RemoveableRef<string> export function useStorage(key: string, initialValue: MaybeRef<boolean>, storage?: StorageLike, options?: StorageOptions<boolean>): RemoveableRef<boolean> export function useStorage(key: string, initialValue: MaybeRef<number>, storage?: StorageLike, options?: StorageOptions<number>): RemoveableRef<number> export function useStorage<T> (key: string, initialValue: MaybeRef<T>, storage?: StorageLike, options?: StorageOptions<T>): RemoveableRef<T> export function useStorage<T = unknown> (key: string, initialValue: MaybeRef<null>, storage?: StorageLike, options?: StorageOptions<T>): RemoveableRef<T> /** * Reactive LocalStorage/SessionStorage. * * @see https://vueuse.org/useStorage * @param key * @param initialValue * @param storage * @param options */ export function useStorage<T extends(string|number|boolean|object|null)> ( key: string, initialValue: MaybeRef<T>, storage: StorageLike | undefined = defaultWindow?.localStorage, options: StorageOptions<T> = {}, ): RemoveableRef<T> { const { flush = 'pre', deep = true, listenToStorageChanges = true, writeDefaults = true, shallow, window = defaultWindow, eventFilter, onError = (e) => { console.error(e) }, } = options const rawInit: T = unref(initialValue) const type = rawInit == null ? 'any' : rawInit instanceof Set ? 'set' : rawInit instanceof Map ? 'map' : typeof rawInit === 'boolean' ? 'boolean' : typeof rawInit === 'string' ? 'string' : typeof rawInit === 'object' ? 'object' : Array.isArray(rawInit) ? 'object' : !Number.isNaN(rawInit) ? 'number' : 'any' const data = (shallow ? shallowRef : ref)(initialValue) as Ref<T> const serializer = options.serializer ?? StorageSerializers[type] function read(event?: StorageEvent) { if (!storage || (event && event.key !== key)) return try { const rawValue = event ? event.newValue : storage.getItem(key) if (rawValue == null) { data.value = rawInit if (writeDefaults && rawInit !== null) storage.setItem(key, serializer.write(rawInit)) } else { data.value = serializer.read(rawValue) } } catch (e) { onError(e) } } read() if (window && listenToStorageChanges) useEventListener(window, 'storage', e => setTimeout(() => read(e), 0)) if (storage) { watchWithFilter( data, () => { try { if (data.value == null) storage.removeItem(key) else storage.setItem(key, serializer.write(data.value)) } catch (e) { onError(e) } }, { flush, deep, eventFilter, }, ) } return data as RemoveableRef<T> } <file_sep>import { getCurrentInstance, onMounted, onUpdated, customRef, Ref } from 'vue-demi' /** * Shorthand for binding ref to template element. * * @see https://vueuse.org/templateRef * @param key * @param initialValue */ export function templateRef<T extends HTMLElement | SVGElement | null>( key: string, initialValue: T | null = null, ): Readonly<Ref<T>> { const instance = getCurrentInstance() let _trigger = () => {} const element = customRef((track, trigger) => { _trigger = trigger return { get() { track() return instance?.proxy?.$refs[key] ?? initialValue }, set() {}, } }) onMounted(_trigger) onUpdated(_trigger) return element as Readonly<Ref<T>> } <file_sep>::: tip ๐Ÿ“ฐ [Recently updated functions](/recently-updated) ::: # Core Functions <!--GENERATED LIST, DO NOT MODIFY MANUALLY--> <!--FUNCTIONS_LIST_STARTS--> ### Animation - [`useInterval`](https://vueuse.org/shared/useInterval/) โ€” reactive counter increases on every interval - [`useIntervalFn`](https://vueuse.org/shared/useIntervalFn/) โ€” wrapper for `setInterval` with controls - [`useNow`](https://vueuse.org/core/useNow/) โ€” reactive current Date instance - [`useRafFn`](https://vueuse.org/core/useRafFn/) โ€” call function on every `requestAnimationFrame` - [`useTimeout`](https://vueuse.org/shared/useTimeout/) โ€” update value after a given time with controls - [`useTimeoutFn`](https://vueuse.org/shared/useTimeoutFn/) โ€” wrapper for `setTimeout` with controls - [`useTimestamp`](https://vueuse.org/core/useTimestamp/) โ€” reactive current timestamp - [`useTransition`](https://vueuse.org/core/useTransition/) โ€” transition between values ### Browser - [`useActiveElement`](https://vueuse.org/core/useActiveElement/) โ€” reactive `document.activeElement` - [`useBreakpoints`](https://vueuse.org/core/useBreakpoints/) โ€” reactive viewport breakpoints - [`useBrowserLocation`](https://vueuse.org/core/useBrowserLocation/) โ€” reactive browser location - [`useClipboard`](https://vueuse.org/core/useClipboard/) โ€” reactive [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) - [`useCssVar`](https://vueuse.org/core/useCssVar/) โ€” manipulate CSS variables - [`useDark`](https://vueuse.org/core/useDark/) โ€” reactive dark mode with auto data persistence - [`useEventListener`](https://vueuse.org/core/useEventListener/) โ€” use EventListener with ease - [`useFavicon`](https://vueuse.org/core/useFavicon/) โ€” reactive favicon - [`useFetch`](https://vueuse.org/core/useFetch/) โ€” reactive [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provides the ability to abort requests - [`useFullscreen`](https://vueuse.org/core/useFullscreen/) โ€” reactive [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API) - [`useMediaControls`](https://vueuse.org/core/useMediaControls/) โ€” reactive media controls for both `audio` and `video` elements - [`useMediaQuery`](https://vueuse.org/core/useMediaQuery/) โ€” reactive [Media Query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries) - [`usePermission`](https://vueuse.org/core/usePermission/) โ€” reactive [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API) - [`usePreferredColorScheme`](https://vueuse.org/core/usePreferredColorScheme/) โ€” reactive [prefers-color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) media query - [`usePreferredDark`](https://vueuse.org/core/usePreferredDark/) โ€” reactive dark theme preference - [`usePreferredLanguages`](https://vueuse.org/core/usePreferredLanguages/) โ€” reactive [Navigator Languages](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages) - [`useScriptTag`](https://vueuse.org/core/useScriptTag/) โ€” script tag injecting - [`useShare`](https://vueuse.org/core/useShare/) โ€” reactive [Web Share API](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share) - [`useTitle`](https://vueuse.org/core/useTitle/) โ€” reactive document title - [`useUrlSearchParams`](https://vueuse.org/core/useUrlSearchParams/) โ€” reactive [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) - [`useWakeLock`](https://vueuse.org/core/useWakeLock/) โ€” reactive [Screen Wake Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API) provides a way to prevent devices from dimming or locking the screen when an application needs to keep running ### Component - [`computedInject`](https://vueuse.org/core/computedInject/) โ€” combine computed and inject - [`templateRef`](https://vueuse.org/core/templateRef/) โ€” shorthand for binding ref to template element - [`tryOnBeforeUnmount`](https://vueuse.org/shared/tryOnBeforeUnmount/) โ€” safe `onBeforeUnmount` - [`tryOnMounted`](https://vueuse.org/shared/tryOnMounted/) โ€” safe `onMounted` - [`tryOnScopeDispose`](https://vueuse.org/shared/tryOnScopeDispose/) โ€” safe `onScopeDispose` - [`tryOnUnmounted`](https://vueuse.org/shared/tryOnUnmounted/) โ€” safe `onUnmounted` - [`unrefElement`](https://vueuse.org/core/unrefElement/) โ€” unref for dom element - [`useTemplateRefsList`](https://vueuse.org/core/useTemplateRefsList/) โ€” shorthand for binding refs to template elements and components inside `v-for` - [`useVirtualList`](https://vueuse.org/core/useVirtualList/) โ€” composable virtual list - [`useVModel`](https://vueuse.org/core/useVModel/) โ€” shorthand for v-model binding - [`useVModels`](https://vueuse.org/core/useVModels/) โ€” shorthand for props v-model binding ### Formatters - [`useTimeAgo`](https://vueuse.org/core/useTimeAgo/) โ€” reactive time ago ### Misc - [`useEventSource`](https://vueuse.org/core/useEventSource/) โ€” an [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) or [Server-Sent-Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) instance opens a persistent connection to an HTTP server - [`useWebSocket`](https://vueuse.org/core/useWebSocket/) โ€” reactive [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket) client - [`useWebWorker`](https://vueuse.org/core/useWebWorker/) โ€” simple [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) registration and communication - [`useWebWorkerFn`](https://vueuse.org/core/useWebWorkerFn/) โ€” run expensive function without blocking the UI ### Sensors - [`onClickOutside`](https://vueuse.org/core/onClickOutside/) โ€” listen for clicks outside of an element - [`onKeyStroke`](https://vueuse.org/core/onKeyStroke/) โ€” listen for keyboard key being stroked - [`onStartTyping`](https://vueuse.org/core/onStartTyping/) โ€” fires when users start typing on non-editable elements - [`useBattery`](https://vueuse.org/core/useBattery/) โ€” reactive [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API) - [`useDeviceMotion`](https://vueuse.org/core/useDeviceMotion/) โ€” reactive [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent) - [`useDeviceOrientation`](https://vueuse.org/core/useDeviceOrientation/) โ€” reactive [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent) - [`useDevicePixelRatio`](https://vueuse.org/core/useDevicePixelRatio/) โ€” reactively track [`window.devicePixelRatio`](https://developer.mozilla.org/ru/docs/Web/API/Window/devicePixelRatio) - [`useDevicesList`](https://vueuse.org/core/useDevicesList/) โ€” reactive [enumerateDevices](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices) listing avaliable input/output devices - [`useDisplayMedia`](https://vueuse.org/core/useDisplayMedia/) โ€” reactive [`mediaDevices.getDisplayMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia) streaming - [`useDocumentVisibility`](https://vueuse.org/core/useDocumentVisibility/) โ€” reactively track [`document.visibilityState`](https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState) - [`useDraggable`](https://vueuse.org/core/useDraggable/) โ€” make elements draggable - [`useElementBounding`](https://vueuse.org/core/useElementBounding/) โ€” reactive [bounding box](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) of an HTML element - [`useElementHover`](https://vueuse.org/core/useElementHover/) โ€” reactive element's hover state - [`useElementSize`](https://vueuse.org/core/useElementSize/) โ€” reactive size of an HTML element - [`useElementVisibility`](https://vueuse.org/core/useElementVisibility/) โ€” tracks the visibility of an element within the viewport - [`useGeolocation`](https://vueuse.org/core/useGeolocation/) โ€” reactive [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) - [`useIdle`](https://vueuse.org/core/useIdle/) โ€” tracks whether the user is being inactive - [`useIntersectionObserver`](https://vueuse.org/core/useIntersectionObserver/) โ€” detects that a target element's visibility - [`useKeyModifier`](https://vueuse.org/core/useKeyModifier/) โ€” reactive [Modifier State](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState) - [`useMagicKeys`](https://vueuse.org/core/useMagicKeys/) โ€” reactive keys pressed state - [`useMouse`](https://vueuse.org/core/useMouse/) โ€” reactive mouse position - [`useMouseInElement`](https://vueuse.org/core/useMouseInElement/) โ€” reactive mouse position related to an element - [`useMousePressed`](https://vueuse.org/core/useMousePressed/) โ€” reactive mouse pressing state - [`useMutationObserver`](https://vueuse.org/core/useMutationObserver/) โ€” watch for changes being made to the DOM tree - [`useNetwork`](https://vueuse.org/core/useNetwork/) โ€” reactive [Network status](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API) - [`useOnline`](https://vueuse.org/core/useOnline/) โ€” reactive online state - [`usePageLeave`](https://vueuse.org/core/usePageLeave/) โ€” reactive state to show whether the mouse leaves the page - [`useParallax`](https://vueuse.org/core/useParallax/) โ€” create parallax effect easily - [`usePointer`](https://vueuse.org/core/usePointer/) โ€” reactive [pointer state](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events) - [`usePointerSwipe`](https://vueuse.org/core/usePointerSwipe/) โ€” reactive swipe detection based on [PointerEvents](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent) - [`useResizeObserver`](https://vueuse.org/core/useResizeObserver/) โ€” reports changes to the dimensions of an Element's content or the border-box - [`useScroll`](https://vueuse.org/core/useScroll/) โ€” reactive scroll position and state - [`useSpeechRecognition`](https://vueuse.org/core/useSpeechRecognition/) โ€” reactive [SpeechRecognition](https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition) - [`useSpeechSynthesis`](https://vueuse.org/core/useSpeechSynthesis/) โ€” reactive [SpeechSynthesis](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis) - [`useSwipe`](https://vueuse.org/core/useSwipe/) โ€” reactive swipe detection based on [`TouchEvents`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent) - [`useUserMedia`](https://vueuse.org/core/useUserMedia/) โ€” reactive [`mediaDevices.getUserMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) streaming - [`useWindowFocus`](https://vueuse.org/core/useWindowFocus/) โ€” reactively track window focus with `window.onfocus` and `window.onblur` events - [`useWindowScroll`](https://vueuse.org/core/useWindowScroll/) โ€” reactive window scroll - [`useWindowSize`](https://vueuse.org/core/useWindowSize/) โ€” reactive window size ### State - [`createGlobalState`](https://vueuse.org/shared/createGlobalState/) โ€” keep states in the global scope to be reusable across Vue instances - [`createSharedComposable`](https://vueuse.org/shared/createSharedComposable/) โ€” make a composable function usable with multiple Vue instances - [`useLocalStorage`](https://vueuse.org/core/useLocalStorage/) โ€” reactive [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) - [`useSessionStorage`](https://vueuse.org/core/useSessionStorage/) โ€” reactive [SessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) - [`useStorage`](https://vueuse.org/core/useStorage/) โ€” reactive [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)/[SessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) ### Utilities - [`and`](https://vueuse.org/shared/and/) โ€” `AND` condition for refs - [`asyncComputed`](https://vueuse.org/core/asyncComputed/) โ€” computed for async functions - [`autoResetRef`](https://vueuse.org/core/autoResetRef/) โ€” a ref which will be reset to the default value after some time - [`biSyncRef`](https://vueuse.org/shared/biSyncRef/) โ€” two-way refs synchronization - [`controlledComputed`](https://vueuse.org/shared/controlledComputed/) โ€” explicitly define the deps of computed - [`controlledRef`](https://vueuse.org/shared/controlledRef/) โ€” fine-grained controls over ref and its reactivity - [`createEventHook`](https://vueuse.org/shared/createEventHook/) โ€” utility for creating event hooks - [`eagerComputed`](https://vueuse.org/shared/eagerComputed/) โ€” eager computed without lazy evaluation - [`extendRef`](https://vueuse.org/shared/extendRef/) โ€” add extra attributes to Ref - [`get`](https://vueuse.org/shared/get/) โ€” shorthand for accessing `ref.value` - [`isDefined`](https://vueuse.org/shared/isDefined/) โ€” non-nullish checking type guard for Ref - [`makeDestructurable`](https://vueuse.org/shared/makeDestructurable/) โ€” make isomorphic destructurable for object and array at the same time - [`not`](https://vueuse.org/shared/not/) โ€” `NOT` condition for ref - [`or`](https://vueuse.org/shared/or/) โ€” `OR` conditions for refs - [`reactify`](https://vueuse.org/shared/reactify/) โ€” converts plain functions into reactive functions - [`reactifyObject`](https://vueuse.org/shared/reactifyObject/) โ€” apply `reactify` to an object - [`reactivePick`](https://vueuse.org/shared/reactivePick/) โ€” reactively pick fields from a reactive object - [`refDefault`](https://vueuse.org/shared/refDefault/) โ€” apply default value to a ref - [`set`](https://vueuse.org/shared/set/) โ€” shorthand for `ref.value = x` - [`syncRef`](https://vueuse.org/shared/syncRef/) โ€” keep target refs in sync with a source ref - [`toReactive`](https://vueuse.org/shared/toReactive/) โ€” converts ref to reactive - [`toRefs`](https://vueuse.org/shared/toRefs/) โ€” extended [`toRefs`](https://v3.vuejs.org/api/refs-api.html#torefs) that also accepts refs of an object - [`useAsyncState`](https://vueuse.org/core/useAsyncState/) โ€” reactive async state - [`useConfirmDialog`](https://vueuse.org/core/useConfirmDialog/) โ€” creates event hooks to support modals and confirmation dialog chains - [`useCounter`](https://vueuse.org/shared/useCounter/) โ€” basic counter with utility functions - [`useDebounce`](https://vueuse.org/shared/useDebounce/) โ€” debounce execution of a ref value - [`useDebouncedRefHistory`](https://vueuse.org/core/useDebouncedRefHistory/) โ€” shorthand for `useRefHistory` with debounced filter - [`useDebounceFn`](https://vueuse.org/shared/useDebounceFn/) โ€” debounce execution of a function - [`useEventBus`](https://vueuse.org/core/useEventBus/) โ€” a basic event bus - [`useLastChanged`](https://vueuse.org/shared/useLastChanged/) โ€” records the timestamp of the last change - [`useManualRefHistory`](https://vueuse.org/core/useManualRefHistory/) โ€” manually track the change history of a ref when the using calls `commit()` - [`useRefHistory`](https://vueuse.org/core/useRefHistory/) โ€” track the change history of a ref - [`useThrottle`](https://vueuse.org/shared/useThrottle/) โ€” throttle changing of a ref value - [`useThrottledRefHistory`](https://vueuse.org/core/useThrottledRefHistory/) โ€” shorthand for `useRefHistory` with throttled filter - [`useThrottleFn`](https://vueuse.org/shared/useThrottleFn/) โ€” throttle execution of a function - [`useToggle`](https://vueuse.org/shared/useToggle/) โ€” a boolean switcher with utility functions ### Watch - [`debouncedWatch`](https://vueuse.org/shared/debouncedWatch/) โ€” debounced watch - [`ignorableWatch`](https://vueuse.org/shared/ignorableWatch/) โ€” ignorable watch - [`pausableWatch`](https://vueuse.org/shared/pausableWatch/) โ€” pausable watch - [`throttledWatch`](https://vueuse.org/shared/throttledWatch/) โ€” throttled watch - [`until`](https://vueuse.org/shared/until/) โ€” promised one-time watch for changes - [`watchAtMost`](https://vueuse.org/shared/watchAtMost/) โ€” `watch` with the number of times triggered - [`watchOnce`](https://vueuse.org/shared/watchOnce/) โ€” `watch` that only triggers once - [`watchWithFilter`](https://vueuse.org/shared/watchWithFilter/) โ€” `watch` with additional EventFilter control - [`whenever`](https://vueuse.org/shared/whenever/) โ€” shorthand for watching value to be truthy <!--FUNCTIONS_LIST_ENDS--> <br> More functions avaliable in [Add-ons](./add-ons). <file_sep>import { ref, reactive } from 'vue-demi' import { useThrottleFn, useDebounceFn, noop, MaybeRef } from '@vueuse/shared' import { useEventListener } from '../useEventListener' export interface UseScrollOptions { /** * Throttle time for scroll event,itโ€™s disabled by default. * * @default 0 */ throttle?: number /** * The check time when scrolling ends. * This configuration will be setting to (throttle + idle) when the `throttle` is configured. * * @default 200 */ idle?: number /** * Offset arrived states by x pixels * */ offset?: { left?: number right?: number top?: number bottom?: number } /** * Trigger it when scrolling. * */ onScroll?: () => void /** * Trigger it when scrolling ends. * */ onStop?: () => void /** * Listener options for scroll event. * * @default {capture: false, passive: true} */ eventListenerOptions?: boolean | AddEventListenerOptions } /** * Reactive scroll. * * @see https://vueuse.org/useScroll * @param element * @param options */ export function useScroll( element: MaybeRef<HTMLElement | SVGElement | Window | Document | null | undefined>, options: UseScrollOptions = {}, ) { const { throttle = 0, idle = 200, onStop = noop, onScroll = noop, offset = { left: 0, right: 0, top: 0, bottom: 0, }, eventListenerOptions = { capture: false, passive: true, }, } = options const x = ref(0) const y = ref(0) const isScrolling = ref(false) const arrivedState = reactive({ left: true, right: false, top: true, bottom: false, }) if (element) { const onScrollEnd = useDebounceFn(() => { isScrolling.value = false onStop() }, throttle + idle) const onScrollHandler = (e: Event) => { const eventTarget = ( e.target === document ? (e.target as Document).documentElement : e.target ) as HTMLElement const scrollLeft = eventTarget.scrollLeft arrivedState.left = scrollLeft <= 0 + (offset.left || 0) arrivedState.right = scrollLeft + eventTarget.clientWidth >= eventTarget.scrollWidth - (offset.right || 0) x.value = scrollLeft const scrollTop = eventTarget.scrollTop arrivedState.top = scrollTop <= 0 + (offset.top || 0) arrivedState.bottom = scrollTop + eventTarget.clientHeight >= eventTarget.scrollHeight - (offset.bottom || 0) y.value = scrollTop isScrolling.value = true onScrollEnd() onScroll() } useEventListener( element, 'scroll', throttle ? useThrottleFn(onScrollHandler, throttle) : onScrollHandler, eventListenerOptions, ) } return { x, y, isScrolling, arrivedState, } } export type UseScrollReturn = ReturnType<typeof useScroll> <file_sep>import { until } from '@vueuse/shared' import fetchMock from 'jest-fetch-mock' import { nextTick, ref } from 'vue-demi' import { createFetch, useFetch } from '.' describe('useFetch', () => { beforeEach(() => { fetchMock.resetMocks() fetchMock.enableMocks() fetchMock.doMock() }) test('should have status code of 200 and message of Hello World', async() => { fetchMock.mockResponse('Hello World', { status: 200 }) const { data, statusCode, isFinished } = useFetch('https://example.com') await until(isFinished).toBe(true) expect(statusCode.value).toBe(200) expect(data.value).toBe('Hello World') }) test('should be able to use the Headers object', async() => { fetchMock.mockResponse('Hello World', { status: 200 }) const myHeaders = new Headers() myHeaders.append('Authorization', 'test') const { statusCode, isFinished } = useFetch('https://example.com', { headers: myHeaders }) await until(isFinished).toBe(true) expect(statusCode.value).toBe(200) expect(fetchMock.mock.calls[0][1]!.headers).toMatchObject({ authorization: 'test' }) }) test('should parse response as json', async() => { fetchMock.mockResponse(JSON.stringify({ message: 'Hello World' }), { status: 200 }) const { data, isFinished } = useFetch('https://example.com').json() await until(isFinished).toBe(true) expect(data.value).toStrictEqual({ message: 'Hello World' }) }) test('should have an error on 400', async() => { fetchMock.mockResponse('', { status: 400 }) const { error, statusCode, isFinished } = useFetch('https://example.com') await until(isFinished).toBe(true) expect(statusCode.value).toBe(400) expect(error.value).toBe('Bad Request') }) test('should abort request and set aborted to true', async() => { fetchMock.mockResponse(() => new Promise(resolve => setTimeout(() => resolve({ body: 'ok' }), 1000))) const { aborted, abort, isFinished, execute } = useFetch('https://example.com') setTimeout(() => abort(), 0) await until(isFinished).toBe(true) expect(aborted.value).toBe(true) execute() setTimeout(() => abort(), 0) await until(isFinished).toBe(true) expect(aborted.value).toBe(true) }) test('should not call if immediate is false', async() => { fetchMock.mockResponse('') useFetch('https://example.com', { immediate: false }) await nextTick() expect(fetchMock).toBeCalledTimes(0) }) test('should refetch if refetch is set to true', async() => { fetchMock.mockResponse('') const url = ref('https://example.com') const { isFinished } = useFetch(url, { refetch: true }) await until(isFinished).toBe(true) url.value = 'https://example.com/test' await nextTick() await until(isFinished).toBe(true) expect(fetchMock).toBeCalledTimes(2) }) test('should auto refetch when the refetch is set to true and the payload is a ref', async() => { fetchMock.mockResponse(JSON.stringify({ message: 'Hello World' }), { status: 200 }) const param = ref({ num: 1 }) const { isFinished } = useFetch('https://example.com', { refetch: true }).post(param) await until(isFinished).toBe(true) param.value.num = 2 await nextTick() await until(isFinished).toBe(true) expect(fetchMock).toBeCalledTimes(2) }) test('should create an instance of useFetch with a base url', async() => { fetchMock.mockResponse('') const useMyFetch = createFetch({ baseUrl: 'https://example.com', fetchOptions: { headers: { Authorization: 'test' } } }) const { isFinished } = useMyFetch('test', { headers: { 'Accept-Language': 'en-US' } }) await until(isFinished).toBe(true) expect(fetchMock.mock.calls[0][1]!.headers).toMatchObject({ 'Authorization': 'test', 'Accept-Language': 'en-US' }) expect(fetchMock.mock.calls[0][0]).toEqual('https://example.com/test') }) test('should run the beforeFetch function and add headers to the request', async() => { fetchMock.mockResponse('') const { isFinished } = useFetch('https://example.com', { headers: { 'Accept-Language': 'en-US' } }, { beforeFetch({ options }) { options.headers = { ...options.headers, Authorization: 'my-auth-token', } return { options } }, }) await until(isFinished).toBe(true) expect(fetchMock.mock.calls[0][1]!.headers).toMatchObject({ 'Authorization': 'my-auth-token', 'Accept-Language': 'en-US' }) }) test('should run the beforeFetch function and cancel the request', async() => { fetchMock.mockResponse('') const { execute } = useFetch('https://example.com', { immediate: false, beforeFetch({ cancel }) { cancel() }, }) await execute() expect(fetchMock).toBeCalledTimes(0) }) test('should run the afterFetch function', async() => { fetchMock.mockResponse(JSON.stringify({ title: 'HxH' }), { status: 200 }) const { isFinished, data } = useFetch('https://example.com', { afterFetch(ctx) { if (ctx.data.title === 'HxH') ctx.data.title = 'Hunter x Hunter' return ctx }, }).json() await until(isFinished).toBe(true) expect(data.value).toStrictEqual({ title: 'Hunter x Hunter' }) }) test('should run the onFetchError function', async() => { fetchMock.mockResponse(JSON.stringify({ title: 'HxH' }), { status: 400 }) const { isFinished, data, statusCode } = useFetch('https://example.com', { onFetchError(ctx) { if (ctx.data.title === 'HxH') ctx.data.title = 'Hunter x Hunter' return ctx }, }).json() await until(isFinished).toBe(true) expect(statusCode.value).toStrictEqual(400) expect(data.value).toStrictEqual({ title: 'Hunter x Hunter' }) }) test('should run the onFetchError function when network error', async() => { fetchMock.mockResponse('Internal Server Error', { status: 500 }) const { isFinished, data, statusCode } = useFetch('https://example.com', { onFetchError(ctx) { ctx.data = { title: 'Hunter x Hunter' } return ctx }, }).json() await until(isFinished).toBe(true) expect(statusCode.value).toStrictEqual(500) expect(data.value).toStrictEqual({ title: 'Hunter x Hunter' }) }) test('should emit onFetchResponse event', async() => { let didEventFire = false const { isFinished, onFetchResponse } = useFetch('https://example.com') onFetchResponse(() => { didEventFire = true }) await until(isFinished).toBe(true) expect(didEventFire).toBe(true) }) test('should emit onFetchResponse event', async() => { fetchMock.mockResponse('', { status: 200 }) let didResponseEventFire = false let didErrorEventFire = false let didFinallyEventFire = false const { isFinished, onFetchResponse, onFetchError, onFetchFinally } = useFetch('https://example.com') onFetchResponse(() => didResponseEventFire = true) onFetchError(() => didErrorEventFire = true) onFetchFinally(() => didFinallyEventFire = true) await until(isFinished).toBe(true) expect(didResponseEventFire).toBe(true) expect(didErrorEventFire).toBe(false) expect(didFinallyEventFire).toBe(true) }) test('should emit onFetchError event', async() => { fetchMock.mockResponse('', { status: 400 }) let didResponseEventFire = false let didErrorEventFire = false let didFinallyEventFire = false const { isFinished, onFetchResponse, onFetchError, onFetchFinally } = useFetch('https://example.com') onFetchResponse(() => didResponseEventFire = true) onFetchError(() => didErrorEventFire = true) onFetchFinally(() => didFinallyEventFire = true) await until(isFinished).toBe(true) expect(didResponseEventFire).toBe(false) expect(didErrorEventFire).toBe(true) expect(didFinallyEventFire).toBe(true) }) test('setting the request method w/ get and return type w/ json', async() => { fetchMock.mockResponse(JSON.stringify({ message: 'Hello World' }), { status: 200 }) const { data, isFinished } = useFetch('https://example.com').get().json() await until(isFinished).toBe(true) expect(data.value).toStrictEqual({ message: 'Hello World' }) }) test('setting the request method w/ post and return type w/ text', async() => { fetchMock.mockResponse(JSON.stringify({ message: 'Hello World' }), { status: 200 }) const { data, isFinished } = useFetch('https://example.com').post().text() await until(isFinished).toBe(true) expect(data.value).toStrictEqual(JSON.stringify({ message: 'Hello World' })) }) test('allow setting response type before doing request', async() => { fetchMock.mockResponse(JSON.stringify({ message: 'Hello World' }), { status: 200 }) const shell = useFetch('https://example.com', { immediate: false, }).get().text() shell.json() shell.execute() const { isFinished, data } = shell await until(isFinished).toBe(true) expect(data.value).toStrictEqual({ message: 'Hello World' }) }) test('not allowed setting response type while doing request', async() => { fetchMock.mockResponse(JSON.stringify({ message: 'Hello World' }), { status: 200 }) const shell = useFetch('https://example.com').get().text() const { isFetching, isFinished, data } = shell await until(isFetching).toBe(true) shell.json() await until(isFinished).toBe(true) expect(data.value).toStrictEqual(JSON.stringify({ message: 'Hello World' })) }) test('should abort request when timeout reached', async() => { fetchMock.mockResponse(() => new Promise(resolve => setTimeout(() => resolve({ body: 'ok' }), 1000))) const { aborted, isFinished, execute } = useFetch('https://example.com', { timeout: 10 }) await until(isFinished).toBe(true) expect(aborted.value).toBe(true) execute() await until(isFinished).toBe(true) expect(aborted.value).toBe(true) }) test('should not abort request when timeout is not reached', async() => { fetchMock.mockResponse(JSON.stringify({ message: 'Hello World' }), { status: 200 }) const shell = useFetch('https://example.com', { timeout: 100 }).get().text() const { isFetching, isFinished, data } = shell await until(isFetching).toBe(true) shell.json() await until(isFinished).toBe(true) expect(data.value).toStrictEqual(JSON.stringify({ message: 'Hello World' })) }) }) <file_sep>import { Ref, ref } from 'vue-demi' import { MaybeRef } from '@vueuse/shared' import { useEventListener } from '../useEventListener' export function useElementHover(el: MaybeRef<EventTarget>): Ref<boolean> { const isHovered = ref(false) useEventListener(el, 'mouseenter', () => isHovered.value = true) useEventListener(el, 'mouseleave', () => isHovered.value = false) return isHovered } <file_sep>import { Ref, ref, shallowRef } from 'vue-demi' import axios, { AxiosError, AxiosRequestConfig, AxiosResponse, CancelTokenSource, AxiosInstance } from 'axios' export interface UseAxiosReturn<T> { /** * Axios Response */ response: Ref<AxiosResponse<T> | undefined> /** * Axios response data */ data: Ref<T | undefined> /** * Indicates if the request has finished */ isFinished: Ref<boolean> /** * Indicates if the request is currently loading */ isLoading: Ref<boolean> /** * Indicates if the request was canceled */ aborted: Ref<boolean> /** * Any errors that may have occurred */ error: Ref<AxiosError<T> | undefined> /** * Aborts the current request */ abort: (message?: string | undefined) => void } export function useAxios<T = any>(url: string, config?: AxiosRequestConfig): UseAxiosReturn<T> export function useAxios<T = any>(url: string, instance?: AxiosInstance): UseAxiosReturn<T> export function useAxios<T = any>(url: string, config: AxiosRequestConfig, instance: AxiosInstance): UseAxiosReturn<T> /** * Wrapper for axios. * * @see https://vueuse.org/useAxios * @param url * @param config */ export function useAxios<T = any>(url: string, ...args: any[]) { let config: AxiosRequestConfig = {} let instance: AxiosInstance = axios if (args.length > 0) { /** * Unable to use `instanceof` here becuase of (https://github.com/axios/axios/issues/737) * so instead we are checking if there is a `requset` on the object to see if it is an * axios instance */ if ('request' in args[0]) instance = args[0] else config = args[0] } if (args.length > 1) { if ('request' in args[1]) instance = args[1] } const response = shallowRef<AxiosResponse<T>>() const data = shallowRef<T>() const isFinished = ref(false) const isLoading = ref(true) const aborted = ref(false) const error = shallowRef<AxiosError<T>>() const cancelToken: CancelTokenSource = axios.CancelToken.source() const abort = (message?: string) => { if (isFinished.value || !isLoading.value) return cancelToken.cancel(message) aborted.value = true isLoading.value = false isFinished.value = false } instance(url, { ...config, cancelToken: cancelToken.token }) .then((r: any) => { response.value = r data.value = r.data }) .catch((e: any) => { error.value = e }) .finally(() => { isLoading.value = false isFinished.value = true }) return { response, data, error, finished: isFinished, loading: isLoading, isFinished, isLoading, cancel: abort, canceled: aborted, aborted, abort, } } <file_sep>import Fuse from 'fuse.js' import { ref, computed, watch, unref, ComputedRef } from 'vue-demi' import { MaybeRef } from '@vueuse/shared' export type FuseOptions<T> = Fuse.IFuseOptions<T> export type UseFuseOptions<T> = { fuseOptions?: FuseOptions<T> resultLimit?: number matchAllWhenSearchEmpty?: boolean } export function useFuse<DataItem>( search: MaybeRef<string>, data: MaybeRef<DataItem[]>, options?: MaybeRef<UseFuseOptions<DataItem>>, ) { const createFuse = (data: MaybeRef<DataItem[]>, options?: FuseOptions<DataItem>) => { const _options = options return new Fuse( unref(data) ?? [], _options, ) } const fuse = ref(createFuse(data, unref(options)?.fuseOptions)) watch( () => unref(options)?.fuseOptions, (newOptions) => { fuse.value = createFuse(data, newOptions) }, { deep: true }, ) watch( () => unref(data), (newData) => { fuse.value.setCollection(newData) }, { deep: true }, ) const results: ComputedRef<Fuse.FuseResult<DataItem>[]> = computed(() => { // This will also be recomputed when `data` changes, as it causes a change // to the Fuse instance, which is tracked here. if (unref(options)?.matchAllWhenSearchEmpty && !unref(search)) return unref(data).map((item, index) => ({ item, refIndex: index })) const limit = unref(options)?.resultLimit return fuse.value.search(unref(search), (limit ? { limit } : undefined)) }) return { results, } } export type UseFuseReturn = ReturnType<typeof useFuse>
cd3e49ac94889f4dc797def47a885536ba7b2f7c
[ "Markdown", "TypeScript", "JavaScript" ]
18
Markdown
Yill625/vueuse
30e690132d5addeef78d90e2159d128122119f6d
7f188227b5f00e500b81c4735c397b85a834cfdb
refs/heads/master
<repo_name>fabricio22/api-controle-gasto<file_sep>/src/main/java/br/com/controle/gastos/vo/MovimentoAtualizacaoVo.java package br.com.controle.gastos.vo; import java.math.BigDecimal; import java.util.Date; import br.com.controle.gastos.enums.TipoMovimento; import br.com.controle.gastos.models.Categoria; public class MovimentoAtualizacaoVo { private Date dataReferencia; private String descricaoMovimento; private BigDecimal valorMovimento; private TipoMovimento tipoMovimento; private Categoria categoria; public MovimentoAtualizacaoVo() { } public Date getDataReferencia() { return dataReferencia; } public void setDataReferencia(Date dataReferencia) { this.dataReferencia = dataReferencia; } public String getDescricaoMovimento() { return descricaoMovimento; } public void setDescricaoMovimento(String descricaoMovimento) { this.descricaoMovimento = descricaoMovimento; } public BigDecimal getValorMovimento() { return valorMovimento; } public void setValorMovimento(BigDecimal valorMovimento) { this.valorMovimento = valorMovimento; } public TipoMovimento getTipoMovimento() { return tipoMovimento; } public void setTipoMovimento(TipoMovimento tipoMovimento) { this.tipoMovimento = tipoMovimento; } public Categoria getCategoria() { return categoria; } public void setCategoria(Categoria categoria) { this.categoria = categoria; } } <file_sep>/src/main/java/br/com/controle/gastos/vo/CategoriaDescricaoVo.java package br.com.controle.gastos.vo; import java.util.Date; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import br.com.controle.gastos.models.Categoria; public class CategoriaDescricaoVo { @NotBlank(message = "Nรฃo รฉ permitido categoria em branco") @NotEmpty(message = "Nรฃo รฉ permitido categoria vazia.") private String descricao; public CategoriaDescricaoVo() { } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public static Categoria converterCategoria(String descricao) { Categoria categoria = new Categoria(); categoria.setDescricao(descricao); categoria.setDataInclusao(new Date()); return categoria; } } <file_sep>/src/main/java/br/com/controle/gastos/services/CategoriaServiceImpl.java package br.com.controle.gastos.services; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.controle.gastos.models.Categoria; import br.com.controle.gastos.repository.CategoriaRepository; import br.com.controle.gastos.vo.CategoriaDescricaoVo; import br.com.controle.gastos.vo.CategoriaVo; @Service public class CategoriaServiceImpl implements CategoriaService { @Autowired CategoriaRepository categoriaRepository; @Override public CategoriaVo retornaCategoria(Long id) { return categoriaRepository.findById(id).map(categoria -> new CategoriaVo(categoria)).get(); } @Override public CategoriaVo criarCategoria(CategoriaDescricaoVo categoriaDesricaoVo) { Categoria categoria = categoriaRepository .save(CategoriaDescricaoVo.converterCategoria(categoriaDesricaoVo.getDescricao())); return new CategoriaVo(categoria); } @Override public List<CategoriaVo> listaCategorias() { return categoriaRepository.findAll().stream().map(categoria -> new CategoriaVo(categoria)) .collect(Collectors.toList()); } @Override public void deleteCategoria(Long id) { categoriaRepository.deleteById(id); } @Override public CategoriaVo atualizaCategoria(Long id, CategoriaDescricaoVo descricao) { Optional<Categoria> optionalCategoria = categoriaRepository.findById(id); if (optionalCategoria.isPresent()) { Categoria categoria = optionalCategoria.get(); categoria.setDescricao(descricao.getDescricao()); categoriaRepository.save(categoria); return new CategoriaVo(categoria); } return null; } } <file_sep>/src/main/java/br/com/controle/gastos/models/SumarizacaoDia.java package br.com.controle.gastos.models; import java.math.BigDecimal; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import br.com.controle.gastos.vo.SumarizacaoVo; @Entity @Table(name = "SUMARIZACAODIA") public class SumarizacaoDia { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID_SUMARIZACAO_DIA") private Long id; @Column(name = "DATA") private Date data; @Column(name = "VALOR_TOTAL") private BigDecimal valorTotal; @Column(name = "DATA_INCLUSAO") private Date dataInclusao; public SumarizacaoDia() { } public SumarizacaoDia(SumarizacaoVo sumarizacaoVo) { this.data = sumarizacaoVo.getData(); this.valorTotal = sumarizacaoVo.getValorTotal(); this.dataInclusao = new Date(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getData() { return data; } public void setData(Date data) { this.data = data; } public BigDecimal getValorTotal() { return valorTotal; } public void setValorTotal(BigDecimal valorTotal) { this.valorTotal = valorTotal; } public Date getDataInclusao() { return dataInclusao; } public void setDataInclusao(Date dataInclusao) { this.dataInclusao = dataInclusao; } } <file_sep>/src/main/java/br/com/controle/gastos/vo/CategoriaVo.java package br.com.controle.gastos.vo; import java.util.Date; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import com.fasterxml.jackson.annotation.JsonFormat; import br.com.controle.gastos.models.Categoria; public class CategoriaVo { private Long id; @NotBlank(message = "Nรฃo รฉ permitido categoria em branco") @NotEmpty(message = "Nรฃo รฉ permitido categoria vazia.") private String descricao; @JsonFormat(pattern = "dd/MM/yyyy") private Date dataInclusao; public CategoriaVo() { } public CategoriaVo(Categoria categoria) { this.id = categoria.getId(); this.descricao = categoria.getDescricao(); this.dataInclusao = categoria.getDataInclusao(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public Date getDataInclusao() { return dataInclusao; } public void setDataInclusao(Date dataInclusao) { this.dataInclusao = dataInclusao; } } <file_sep>/src/main/java/br/com/controle/gastos/vo/SumarizacaoVo.java package br.com.controle.gastos.vo; import java.math.BigDecimal; import java.util.Date; public class SumarizacaoVo { private Date data; private BigDecimal valorTotal; public SumarizacaoVo() { } public SumarizacaoVo(Date data, BigDecimal valorTotal) { this.data = data; this.valorTotal = valorTotal; } public Date getData() { return data; } public void setData(Date data) { this.data = data; } public BigDecimal getValorTotal() { return valorTotal; } public void setValorTotal(BigDecimal valorTotal) { this.valorTotal = valorTotal; } } <file_sep>/src/main/java/br/com/controle/gastos/repository/SumarizacaoDiaRepository.java package br.com.controle.gastos.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import br.com.controle.gastos.models.SumarizacaoDia; import br.com.controle.gastos.vo.SumarizacaoGeralVo; import br.com.controle.gastos.vo.SumarizacaoVo; @Repository public interface SumarizacaoDiaRepository extends JpaRepository<SumarizacaoDia, Long> { @Query(value = "SELECT new br.com.controle.gastos.vo.SumarizacaoVo(m.dataReferencia AS data," + " SUM(m.valorMovimento) AS valorTotal)" + " FROM Movimentacao m" + " GROUP BY m.dataReferencia") public List<SumarizacaoVo> getSumarizacaoEntradaDia(); @Query(value = "SELECT new br.com.controle.gastos.vo.SumarizacaoGeralVo(SUM(m.valorMovimento) AS valorTotal) FROM Movimentacao m") public SumarizacaoGeralVo getTotal(); } <file_sep>/src/main/java/br/com/controle/gastos/models/Movimentacao.java package br.com.controle.gastos.models; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import br.com.controle.gastos.enums.TipoMovimento; @Entity @Table(name = "MOVIMENTACOES") public class Movimentacao { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID_MOVIMENTACOES") private Long id; @Column(name = "DATA_REFERENCIA") private Date dataReferencia; @Column(name = "DESCRICAO_MOVIMENTO") private String descricaoMovimento; @Column(name = "VALOR_MOVIMENTO") private BigDecimal valorMovimento; @Column(name = "DATA_INCLUSAO") private Date dataInclusao; @Column(name = "TIPO_MOVIMENTO") @Enumerated(EnumType.STRING) private TipoMovimento tipoMovimento; @ManyToOne @JoinColumn(name = "ID_CATEGORIA") private Categoria categoria; public Movimentacao() { this.dataInclusao = new Date(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getDataReferencia() { return dataReferencia; } public void setDataReferencia(Date dataReferencia) { this.dataReferencia = dataReferencia; } public String getDescricaoMovimento() { return descricaoMovimento; } public void setDescricaoMovimento(String descricaoMovimento) { this.descricaoMovimento = descricaoMovimento; } public BigDecimal getValorMovimento() { return valorMovimento; } public void setValorMovimento(BigDecimal valorMovimento) { this.valorMovimento = valorMovimento; } public Date getDataInclusao() { return dataInclusao; } public void setDataInclusao(Date dataInclusao) { this.dataInclusao = dataInclusao; } public TipoMovimento getTipoMovimento() { return tipoMovimento; } public void setTipoMovimento(TipoMovimento tipoMovimento) { this.tipoMovimento = tipoMovimento; } public Categoria getCategoria() { return categoria; } public void setCategoria(Categoria categoria) { this.categoria = categoria; } } <file_sep>/src/main/java/br/com/controle/gastos/controller/CategoriaController.java package br.com.controle.gastos.controller; import java.util.List; import java.util.stream.Collectors; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import br.com.controle.gastos.services.CategoriaService; import br.com.controle.gastos.vo.CategoriaDescricaoVo; import br.com.controle.gastos.vo.CategoriaVo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Api(value = "Api Rest - Controle de Gastos - Mรณdulo Categoria") @RestController @RequestMapping("/categoria") public class CategoriaController { @Autowired CategoriaService categoriaService; @ApiOperation(value = "Retorna uma categoria por Id.") @GetMapping("/{id}") @ResponseBody @ResponseStatus(code = HttpStatus.OK) public ResponseEntity<?> retornaCategoria(@PathVariable("id") Long id) { CategoriaVo categoriaRetornada = categoriaService.retornaCategoria(id); return new ResponseEntity<CategoriaVo>(categoriaRetornada, HttpStatus.OK); } @ApiOperation(value = "Cria uma categoria") @PostMapping @ResponseBody @ResponseStatus(code = HttpStatus.CREATED) public ResponseEntity<?> criarCategoria(@Valid @RequestBody CategoriaDescricaoVo categoriaDescricao, Errors errors) { if (!errors.hasErrors()) { return new ResponseEntity<CategoriaVo>(categoriaService.criarCategoria(categoriaDescricao), HttpStatus.CREATED); } return ResponseEntity.badRequest().body(errors.getAllErrors().stream() .map(mensagem -> mensagem.getDefaultMessage()).collect(Collectors.joining(","))); } @ApiOperation(value = "Retorna uma lista de categoria") @GetMapping("/lista-categoria") @ResponseStatus(code = HttpStatus.OK) @ResponseBody public ResponseEntity<?> listaCategorias() { return new ResponseEntity<List>(categoriaService.listaCategorias(), HttpStatus.OK); } @ApiOperation(value = "Remove uma categoria") @DeleteMapping("/{id}") @ResponseStatus(code = HttpStatus.NO_CONTENT) public void deleteCategoria(@PathVariable("id") Long id) { categoriaService.deleteCategoria(id); } @ApiOperation(value = "Atualiza Categoria") @PatchMapping("/{id}") @ResponseBody @ResponseStatus(code = HttpStatus.OK) public ResponseEntity<?> atualizaCategoria(@Valid @PathVariable("id") Long id, @RequestBody CategoriaDescricaoVo descricao, Errors errors) { if (!errors.hasErrors()) { return new ResponseEntity<CategoriaVo>(categoriaService.atualizaCategoria(id, descricao), HttpStatus.OK); } return ResponseEntity.badRequest().body(errors.getAllErrors().stream() .map(mensagem -> mensagem.getDefaultMessage()).collect(Collectors.joining(","))); } } <file_sep>/src/main/java/br/com/controle/gastos/services/MovimentacoesServiceImpl.java package br.com.controle.gastos.services; import java.math.BigDecimal; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.controle.gastos.enums.TipoMovimento; import br.com.controle.gastos.models.Movimentacao; import br.com.controle.gastos.models.SumarizacaoDia; import br.com.controle.gastos.repository.MovimentacoesRepository; import br.com.controle.gastos.repository.SumarizacaoDiaRepository; import br.com.controle.gastos.vo.MovimentacaoVo; import br.com.controle.gastos.vo.MovimentoAtualizacaoVo; import br.com.controle.gastos.vo.SumarizacaoGeralVo; @Service public class MovimentacoesServiceImpl implements MovimentacoesService { @Autowired MovimentacoesRepository movimentacoesRepository; @Autowired SumarizacaoDiaRepository sumarizacaoDiaRepository; @Override public MovimentacaoVo criarMovimento(Movimentacao movimentacao) { if (movimentacao.getTipoMovimento() == TipoMovimento.SAIDA) { movimentacao.setValorMovimento(BigDecimal.valueOf(movimentacao.getValorMovimento().doubleValue() * -1)); } if (movimentacao.getTipoMovimento() == TipoMovimento.ENTRADA) { movimentacao .setValorMovimento(BigDecimal.valueOf(Math.abs(movimentacao.getValorMovimento().doubleValue()))); } this.movimentacoesRepository.save(movimentacao); atualizaSumarizacaoDia(); return new MovimentacaoVo(movimentacao); } private void atualizaSumarizacaoDia() { this.sumarizacaoDiaRepository.deleteAll(); this.sumarizacaoDiaRepository.getSumarizacaoEntradaDia().forEach(sumarizacao -> { this.sumarizacaoDiaRepository.save(new SumarizacaoDia(sumarizacao)); }); } @Override public List<MovimentacaoVo> listaMovimentos() { return this.movimentacoesRepository.findAll().stream().map(movimentacao -> new MovimentacaoVo(movimentacao)) .collect(Collectors.toList()); } @Override public void removeMovimento(Long id) { this.movimentacoesRepository.deleteById(id); atualizaSumarizacaoDia(); } @Override public MovimentacaoVo atualizaMovimento(Long id, MovimentoAtualizacaoVo movimentos) { return this.movimentacoesRepository.findById(id).map(movimento -> { movimento.setCategoria(movimentos.getCategoria()); movimento.setDataReferencia(movimentos.getDataReferencia()); movimento.setDescricaoMovimento(movimentos.getDescricaoMovimento()); movimento.setTipoMovimento(movimentos.getTipoMovimento()); if ((TipoMovimento.SAIDA == movimentos.getTipoMovimento() && movimentos.getValorMovimento().doubleValue() > 0) || (TipoMovimento.ENTRADA == movimentos.getTipoMovimento() && movimentos.getValorMovimento().doubleValue() < 0)) { throw new RuntimeException("Valor do movimento รฉ invรกlido para o tipo de movimento."); } if (movimento.getValorMovimento() != movimentos.getValorMovimento()) { movimento.setValorMovimento(movimentos.getValorMovimento()); this.movimentacoesRepository.save(movimento); atualizaSumarizacaoDia(); } else { movimento.setValorMovimento(movimentos.getValorMovimento()); this.movimentacoesRepository.save(movimento); } return new MovimentacaoVo(movimento); }).get(); } @Override public SumarizacaoGeralVo getTotalGeral() { return this.sumarizacaoDiaRepository.getTotal(); } } <file_sep>/src/main/java/br/com/controle/gastos/models/Categoria.java package br.com.controle.gastos.models; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import com.mysql.cj.x.protobuf.MysqlxCursor.Fetch; @Entity @Table(name = "CATEGORIAS") public class Categoria { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID_CATEGORIAS") private Long id; @Column(name = "DESCRICAO") private String descricao; @Column(name = "DATA_INCLUSAO") private Date dataInclusao; @OneToMany(mappedBy = "categoria", targetEntity = Movimentacao.class, fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<Movimentacao> movimentacao; public Categoria() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public Date getDataInclusao() { return dataInclusao; } public void setDataInclusao(Date dataInclusao) { this.dataInclusao = dataInclusao; } } <file_sep>/src/main/java/br/com/controle/gastos/repository/MovimentacoesRepository.java package br.com.controle.gastos.repository; import org.springframework.data.jpa.repository.JpaRepository; import br.com.controle.gastos.models.Movimentacao; public interface MovimentacoesRepository extends JpaRepository<Movimentacao, Long> { } <file_sep>/src/main/java/br/com/controle/gastos/services/CategoriaService.java package br.com.controle.gastos.services; import java.util.List; import br.com.controle.gastos.vo.CategoriaDescricaoVo; import br.com.controle.gastos.vo.CategoriaVo; public interface CategoriaService { public CategoriaVo retornaCategoria(Long id); public CategoriaVo criarCategoria(CategoriaDescricaoVo categoriaDesricaoVo); public List<CategoriaVo> listaCategorias(); public void deleteCategoria(Long id); public CategoriaVo atualizaCategoria(Long id, CategoriaDescricaoVo descricao); }
e0b280be7d5febfa70f9d80232c0ac799a206e11
[ "Java" ]
13
Java
fabricio22/api-controle-gasto
b1f480f32423e3c3d65c802d7ae6f2ca305506c3
c300880e4d53e0dcb94fb01177063bf7748e2962
refs/heads/master
<file_sep>use std::{ convert::TryInto, error::Error, fmt::{self, Display, Formatter}, }; #[derive(Debug, Clone)] pub struct BufferTooSmall; impl Display for BufferTooSmall { fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> { write!(fmt, "buffer too small") } } impl Error for BufferTooSmall {} #[derive(Debug, Copy, Clone, PartialEq)] pub struct Header<'a>(&'a [u8]); impl<'a> Header<'a> { pub fn from_slice(buf: &'a [u8]) -> Result<Self, BufferTooSmall> { if buf.len() < 12 { return Err(BufferTooSmall); } Ok(Header(&buf[..12])) } #[inline] pub fn version(&self) -> u8 { let buf = self.as_slice(); let byte = buf[0]; byte >> 6 } #[inline] pub fn ssrc(&self) -> u32 { u32::from_be_bytes(self.as_slice()[8..12].try_into().unwrap()) } #[inline] pub fn as_slice(&self) -> &[u8] { match self { Header(buf) => buf, } } } #[cfg(test)] mod test { use super::*; #[test] fn test_parse_rtp() { let header = Header(&[128, 96, 0, 17, 0, 0, 140, 160, 0, 0, 0, 16]); assert_eq!(2, header.version()); assert_eq!(17, header.sequence_number()); assert_eq!(36000, header.timestamp()); assert_eq!(16, header.ssrc()); } } <file_sep>#[macro_use] extern crate clap; #[macro_use] extern crate log; use std::{ error::Error, io::{BufWriter, Write}, net::{SocketAddr, TcpStream, UdpSocket}, sync::{ mpsc::{self, Receiver, SyncSender}, Arc, }, thread, time::Duration, }; use clap::{App, AppSettings, Arg, SubCommand}; use rmpv::ValueRef; #[derive(Debug)] enum Address { Udp(SocketAddr), Https(String, u16), } impl Address { pub fn from_str(addr: &str) -> Result<Self, Box<dyn Error>> { if !addr.contains("://") { return Err("invalid address - must be an URL".into()); } let mut it = addr.splitn(2, "://"); let protocol = match it.next() { Some(protocol) => protocol, None => return Err("missing protocol".into()), }; let addr = match it.next() { Some(addr) => addr, None => return Err("missing address".into()), }; match protocol { "udp" => { let addr = addr.parse()?; Ok(Address::Udp(addr)) } "https" => { let (host, port) = split_host_port(addr)?; Ok(Address::Https(host.into(), port)) } protocol => Err(format!("unknown protocol: {}", protocol).into()), } } } fn split_host_port(addr: &str) -> Result<(&str, u16), Box<dyn Error>> { let mut it = addr.rsplitn(2, ':'); let port = match it.next() { Some(port) => port.parse()?, None => 443, }; let host = match it.next() { Some(host) => host, None => return Err("missing hostname".into()), }; Ok((host, port)) } fn main() -> Result<(), Box<dyn Error>> { env_logger::init(); let matches = App::new(crate_name!()) .version(crate_version!()) .author(crate_authors!()) .setting(AppSettings::SubcommandRequired) .subcommand(SubCommand::with_name("scan").about("scan local network for cleverdog camera(s)")) .subcommand( SubCommand::with_name("stream") .about("stream H264 from camera") .arg( Arg::with_name("addr") .long("addr") .value_name("ADDRESS") .help("network address, udp:// or https://") .required(true) .takes_value(true), ) .arg( Arg::with_name("retries") .long("retries") .value_name("NUMBER") .default_value("18446744073709551615") .help("number of retries in case of camera hanging") .takes_value(true), ), ) .get_matches(); match matches.subcommand() { ("scan", ..) => { let info = cleverdog::lookup()?; println!("Address: {}", info.addr()); println!("CID: {}", core::str::from_utf8(info.cid())?); println!("MAC: {}", info.mac()); println!("Version: {}", info.version()); } ("stream", Some(matches)) => { // This cannot panic because of CLAP required flag. let dst = matches.value_of("addr").unwrap(); let mut num: u64 = matches.value_of("retries").unwrap().parse()?; let addr = Address::from_str(dst)?; info!("Destination address: {:?}", addr); let info = cleverdog::lookup()?; info!("Successfully resolved camera"); info!(" Address: {}", info.addr()); info!(" CID: {}", core::str::from_utf8(info.cid())?); info!(" MAC: {}", info.mac()); info!(" Version: {}", info.version()); match addr { Address::Udp(addr) => { let sock = UdpSocket::bind("0.0.0.0:0")?; cleverdog::stream(info.cid(), info.addr(), |buf| { debug!("-> {}", buf.len()); sock.send_to(buf, addr)?; Ok(()) })?; } Address::Https(host, port) => { let addr = format!("{}:{}", host, port); let (tx, rx): (SyncSender<Vec<u8>>, Receiver<Vec<u8>>) = mpsc::sync_channel(4096); let thread = thread::spawn(move || { let mut cfg = rustls::ClientConfig::new(); cfg.root_store.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS); let cfg = Arc::new(cfg); let hostname = webpki::DNSNameRef::try_from_ascii_str(&host).expect("ASCII hostname"); loop { let mut session = rustls::ClientSession::new(&cfg, hostname); debug!("connecting to {}", addr); let mut stream = match TcpStream::connect(&addr) { Ok(stream) => stream, Err(err) => { error!("failed to connect to {}: {}", addr, err); thread::sleep(Duration::new(1, 0)); continue; } }; let mut stream = BufWriter::new(rustls::Stream::new(&mut session, &mut stream)); info!("successfully connected to {}", addr); while let Ok(buf) = rx.recv() { if let Err(err) = stream.write_all(&buf) { error!("failed to send bytes: {}", err); break; } } thread::sleep(Duration::new(1, 0)); } }); let on_data = |buf: &[u8]| { debug!("-> {}", buf.len()); let mut msg = Vec::new(); if let Err(err) = rmpv::encode::write_value_ref(&mut msg, &ValueRef::Binary(buf)) { error!("failed to encode datagram: {}", err); } if let Err(..) = tx.try_send(msg) { error!("failed to send datagram due to backpressuring"); } Ok(()) }; while num > 0 { if let Err(err) = cleverdog::stream(info.cid(), info.addr(), on_data) { warn!("streaming stopped: {}", err); } num -= 1; thread::sleep(Duration::new(1, 0)); } thread.join().unwrap(); } } } (..) => unreachable!(), } Ok(()) } // ffmpeg -protocol_whitelist file,udp,rtp -i /mnt/hls/camera.sdp -preset // ultrafast -vcodec libx264 -r 15 -b 300k -f flv rtmp://localhost/show/camera0 <file_sep>use core::{ fmt::{self, Display, Formatter, LowerHex, UpperHex}, num::ParseIntError, str::FromStr, }; use std::error::Error; /// An error that can occur during parsing a MAC address string. #[derive(Debug, Clone)] pub enum ParseError { /// Parsing of the MAC address contained an invalid digit. InvalidDigit(ParseIntError), /// The MAC address did not have the correct length. InvalidLength, } impl Display for ParseError { fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> { match self { ParseError::InvalidDigit(..) => write!(fmt, "invalid digit"), ParseError::InvalidLength => fmt.write_str("invalid length"), } } } impl Error for ParseError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { ParseError::InvalidDigit(err) => Some(err), ParseError::InvalidLength => None, } } } /// MAC address. #[derive(Debug, Clone, Copy)] pub struct MacAddr([u8; 6]); impl MacAddr { /// Constructs a new MAC address from the given fixed array. #[inline] pub fn new(buf: [u8; 6]) -> Self { Self(buf) } /// Parses the specified string into MAC address. /// /// ``` /// use cleverdog::mac::MacAddr; /// /// let mac: MacAddr = "dc:a9:04:97:9d:9b".parse().unwrap(); /// assert_eq!(mac.as_bytes(), [220, 169, 4, 151, 157, 155]); /// ``` #[inline] pub fn from_str(s: &str) -> Result<Self, ParseError> { <MacAddr as FromStr>::from_str(s) } /// Returns the underlying byte array. #[inline] pub fn as_bytes(&self) -> [u8; 6] { match self { MacAddr(buf) => *buf, } } } impl FromStr for MacAddr { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut buf = [0u8; 6]; let mut idx = 0; for b in s.split(':') { if idx == 6 { return Err(ParseError::InvalidLength); } buf[idx] = u8::from_str_radix(b, 16).map_err(|err| ParseError::InvalidDigit(err))?; idx += 1; } if idx != 6 { return Err(ParseError::InvalidLength); } Ok(MacAddr::new(buf)) } } impl Display for MacAddr { fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> { <MacAddr as LowerHex>::fmt(self, fmt) } } impl LowerHex for MacAddr { fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> { write!(fmt, "{:<02x}", self.as_bytes()[0])?; for v in self.as_bytes().iter().skip(1) { write!(fmt, ":{:<02x}", v)?; } Ok(()) } } impl UpperHex for MacAddr { fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> { write!(fmt, "{:<02X}", self.as_bytes()[0])?; for v in self.as_bytes().iter().skip(1) { write!(fmt, ":{:<02X}", v)?; } Ok(()) } } #[cfg(test)] mod test { use super::*; #[test] fn test_parse() { let v = "dc:a9:04:97:9d:9b"; let mac = v.parse::<MacAddr>().unwrap(); assert_eq!(mac.as_bytes(), [220, 169, 4, 151, 157, 155]); } #[test] fn test_display() { let mac = MacAddr::new([220, 169, 4, 151, 157, 155]); assert_eq!(&format!("{}", mac), "dc:a9:04:97:9d:9b"); } #[test] fn test_display_lower_hex() { let mac = MacAddr::new([220, 169, 4, 151, 157, 155]); assert_eq!(&format!("{:x}", mac), "dc:a9:04:97:9d:9b"); } #[test] fn test_display_upper_hex() { let mac = MacAddr::new([220, 169, 4, 151, 157, 155]); assert_eq!(&format!("{:X}", mac), "DC:A9:04:97:9D:9B"); } } <file_sep>pub use crate::protocol::{ scan::{LookupInfo, ScanInfo}, version::Version, }; mod scan; mod version; /// Magic constant that is prepended to each camera frame. /// /// Represents a big-endian integer representation of `[0x4d, 0x4a]` array. pub const MAGIC: u16 = 19786; #[cfg(test)] mod test { use super::*; #[test] fn test_magic_endianess() { assert_eq!([0x4d, 0x4a], MAGIC.to_be_bytes()); } } <file_sep>edition = "2018" merge_imports = true wrap_comments = true reorder_imports = true max_width = 120 error_on_line_overflow = true use_field_init_shorthand = true <file_sep>use core::{num::ParseIntError}; use core::fmt::{self, Display, Formatter}; #[derive(Debug, Clone, Copy)] pub struct Version([u16; 4]); impl Version { #[inline] pub fn new(buf: [u16; 4]) -> Self { Self(buf) } pub fn from_str(v: &str) -> Result<Self, ParseIntError> { let mut buf = [0u16; 4]; let mut idx = 0; for b in v.split('.') { if idx == 4 { break; } buf[idx] = u16::from_str_radix(b, 10)?; idx += 1; } Ok(Self::new(buf)) } } impl Display for Version { fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> { let Version([major, minor, patch, release]) = self; write!(fmt, "{}.{}.{}.{}", major, minor, patch, release) } } <file_sep>[package] name = "cleverdog" version = "0.1.1" authors = ["<NAME> <<EMAIL>>"] edition = "2018" description = "Cleverdog Camera API and basic streaming proxy" license = "MIT" [dependencies] byteorder = "1" log = "0.4" [dev-dependencies] clap = "2" env_logger = "0.6" rustls = "0.15" webpki = "0.19" webpki-roots = "0.16" rmpv = "0.4" [profile.release] panic = "abort" <file_sep>use core::{convert::TryFrom, str}; use std::net::SocketAddr; use crate::{mac::MacAddr, protocol::version::Version}; #[derive(Debug, Clone, Copy)] pub struct ScanInfo { /// Camera MAC address. mac: MacAddr, /// Firmware version. version: Version, } impl TryFrom<&[u8]> for ScanInfo { type Error = &'static str; fn try_from(v: &[u8]) -> Result<Self, Self::Error> { let mut it = v.split(|&ch| ch == b'\0'); let mac = match it.next() { Some(mac) => match str::from_utf8(mac.into()) { Ok(mac) => match MacAddr::from_str(mac) { Ok(mac) => mac, Err(..) => return Err("MAC address is invalid"), }, Err(..) => return Err("MAC address contains invalid UTF-8 sequence"), }, None => return Err("missing MAC address"), }; let version = match it.next() { Some(version) => match str::from_utf8(version.into()) { Ok(version) => match Version::from_str(version) { Ok(version) => version, Err(..) => return Err("version is invalid"), }, Err(..) => return Err("version contains invalid UTF-8 sequence"), }, None => return Err("missing version"), }; let v = Self { mac, version }; Ok(v) } } #[derive(Debug, Clone, Copy)] pub struct LookupInfo { /// Camera endpoint. addr: SocketAddr, /// Camera ID. cid: [u8; 16], /// Scan info. info: ScanInfo, } impl LookupInfo { pub fn new(addr: SocketAddr, cid: [u8; 16], info: ScanInfo) -> Self { Self { addr, cid, info } } /// Returns socket address where the camera is bound. #[inline] pub fn addr(&self) -> SocketAddr { self.addr } /// Returns camera's client id. #[inline] pub fn cid(&self) -> &[u8] { &self.cid[..] } /// Returns camera's MAC address. #[inline] pub fn mac(&self) -> &MacAddr { &self.info.mac } /// Returns camera's firmware version. #[inline] pub fn version(&self) -> &Version { &self.info.version } } <file_sep>use core::{convert::TryFrom, time::Duration}; use std::{ error::Error, io::{Cursor, ErrorKind, Read, Write}, net::{SocketAddr, UdpSocket}, time::{Instant, SystemTime}, }; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use crate::{ protocol::{LookupInfo, ScanInfo, MAGIC}, rtp::Header, }; pub mod mac; pub mod protocol; mod rtp; enum Command { Scan, ScanReply, StartRtp, } impl Command { pub fn as_u16(&self) -> u16 { match self { Command::Scan => 0x1004, Command::ScanReply => 0x100e, Command::StartRtp => 0x1007, } } pub fn encode(&self, cid: &[u8], args: &[u8]) -> Result<Vec<u8>, Box<dyn Error>> { let mut cid = cid; if cid.len() > 15 { cid = &cid[..15] } let mut buf = Cursor::new(Vec::new()); buf.write_u16::<BigEndian>(MAGIC)?; buf.write_u16::<BigEndian>(self.as_u16())?; buf.write_all(cid)?; buf.write_all(&b"000000000000000"[..15usize.saturating_sub(cid.len())])?; buf.write_all(&[0x0])?; buf.write_all(args)?; Ok(buf.into_inner()) } } pub fn lookup() -> Result<LookupInfo, Box<dyn Error>> { let sock = UdpSocket::bind("0.0.0.0:0")?; sock.set_broadcast(true)?; sock.set_read_timeout(Some(Duration::new(1, 0)))?; let comm = Command::Scan.encode(b"", b"00000000000000000000000000000000000000")?; sock.send_to(&comm, "192.168.1.71:10008")?; let mut buf = [0; 4096]; loop { let (size, addr) = match sock.recv_from(&mut buf[..]) { Ok((size, addr)) => (size, addr), Err(ref err) if err.kind() == ErrorKind::WouldBlock => { return Err("timed out".into()); } Err(err) => return Err(err.into()), }; let mut buf = Cursor::new(&buf[..size]); let magic = buf.read_u16::<BigEndian>()?; if magic != MAGIC { return Err("invalid magic header".into()); } let comm = buf.read_u16::<BigEndian>()?; if comm != Command::ScanReply.as_u16() { continue; } let mut cid = [0; 16]; buf.read_exact(&mut cid[..])?; let idx = buf.position() as usize; let info = ScanInfo::try_from(&buf.into_inner()[idx..])?; let info = LookupInfo::new(addr, cid, info); return Ok(info); } } pub fn stream<F>(cid: &[u8], src: SocketAddr, f: F) -> Result<(), Box<dyn Error>> where F: Fn(&[u8]) -> Result<(), Box<dyn Error>>, { let sock = UdpSocket::bind("0.0.0.0:0")?; sock.set_read_timeout(Some(Duration::new(10, 0)))?; let local_addr = sock.local_addr()?; let mut args = Cursor::new(Vec::new()); args.write_all(b"00000000000000000000000000000000000000")?; args.write_fmt(format_args!("{}:{}\0", local_addr.port(), local_addr.port()))?; let comm = Command::StartRtp.encode(cid, &args.into_inner())?; sock.send_to(&comm, src)?; let mut timestamp = Instant::now(); let mut buf = [0; 4096]; loop { let (size, addr) = sock.recv_from(&mut buf[..])?; if timestamp.elapsed() >= Duration::from_secs(1) { timestamp = Instant::now(); send_rtcp(&sock, &addr)?; } if buf[..size].len() < 16 { continue; } let hdr = Header::from_slice(&buf[4..])?; if hdr.version() != 2 { continue; } // Skip non-video frames. if buf[2] != 1 { continue; } if hdr.ssrc() != 16 { continue; } f(&buf[4..size])?; } } fn send_rtcp(sock: &UdpSocket, camera: &SocketAddr) -> Result<(), Box<dyn Error>> { let mut buf = Cursor::new(Vec::new()); buf.write_all(&[ 0x00, 0x00, 0x01, 0x00, // Header. 0x80, // RTP v2 0xc8, // RTCP sender report packet type 0x00, 0x06, ])?; buf.write_u32::<BigEndian>(0x00000002)?; let msecs = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_nanos() / 1e6 as u128 + 2208988800000; let seconds = (msecs / 1000) as u32; let fraction = (0x100000000 * (msecs % 1000) / 1000) as u32; buf.write_u32::<BigEndian>(seconds)?; buf.write_u32::<BigEndian>(fraction)?; buf.write_u32::<BigEndian>(0)?; buf.write_u32::<BigEndian>(0)?; buf.write_u32::<BigEndian>(0)?; sock.send_to(&buf.into_inner(), camera)?; Ok(()) }
516fee09beb3f85eaab69f713900f2023b5b7a98
[ "TOML", "Rust" ]
9
Rust
3Hren/cleverdog
b248b5fe7c2dcda8749d650b682e66ef64d65123
16618150ac89e325a4803508070bbd16ad4cd0e7
refs/heads/master
<file_sep>case-study-churn-analysis ============================== Mobile app user churn analysis. A collaborative case study performed as part of the Galvanize Data Science Immersive. <file_sep>import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import mean_squared_error, r2_score from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.ensemble import GradientBoostingClassifier class Cleaner: def __init__(self): self.len_train = 0 self.feature_names = [] self.today = pd.datetime(2014,7,1) def stage_cleaning(self,train_data): self.rider_null = train_data['avg_rating_by_driver'].median() self.driver_null = train_data['avg_rating_of_driver'].median() self.dist_null = train_data['avg_dist'].median() self.dist_mu = train_data['avg_dist'].mean() self.dist_sigma = train_data['avg_dist'].std() self.surge_null = train_data['avg_surge'].median() self.surgepct_null = train_data['surge_pct'].median() self.first30_null = train_data['trips_in_first_30_days'].median() self.black_null = 0 self.weekday_null = train_data['weekday_pct'].median() return None def clean(self,data): #first create DF with android iphone dummy clean_data = self.phone_types(data) #account age, days since last trip #clean_data['inactive_days']=self.inactive_days(data) #clean_data['acct_age']=self.acct_age(data) clean_data['rider_rtg']=self.rider_rtg(data) clean_data['driver_rtg']=self.driver_rtg(data) #observed non-null in training, will write cleaning methods if null appears in test clean_data['avg_dist']=data['avg_dist'].apply(lambda x: (self.dist_null-self.dist_mu)/self.dist_sigma if pd.isnull(x) else (x-self.dist_mu)/self.dist_sigma) clean_data['avg_surge']=data['avg_surge'].apply(lambda x: self.surge_null if pd.isnull(x) else x) clean_data['surge_pct']=data['surge_pct'].apply(lambda x: self.surgepct_null/100 if pd.isnull(x) else x/100) clean_data['first_30']=data['trips_in_first_30_days'].apply(lambda x: self.first30_null if pd.isnull(x) else x) clean_data['black']= data['luxury_car_user'].astype('int64').apply(lambda x: self.black_null if pd.isnull(x) else x) clean_data['weekday_pct']= data['weekday_pct'].apply(lambda x: self.weekday_null/100 if pd.isnull(x) else x/100) #clean_data['surge_bool']=data['surge_pct'].where(data['surge_pct']==0,1) clean_data['weekend_signup']=data['signup_date'].apply(lambda x: x.weekday()>4) clean_data['weekday_pct']= data['weekday_pct'].apply(lambda x: self.weekday_null/100 if pd.isnull(x) else x/100) #map cities clean_data = clean_data.merge(self.cities(data), left_index=True,right_index = True) clean_data = clean_data.drop('iPhone',axis = 1) return clean_data # def phone_types(self,df): return pd.get_dummies(df['phone'].map({'Android':'Android','iPhone':'iPhone'})) def inactive_days(self,df): return (self.today-df['last_trip_date']).apply(lambda x: x.days) def acct_age(self,df): return (self.today-df['signup_date']).apply(lambda x: x.days) def rider_rtg(self,df): return df['avg_rating_by_driver'].apply(lambda x: self.rider_null if pd.isnull(x) else x) def driver_rtg(self,df): return df['avg_rating_of_driver'].apply(lambda x: (self.driver_null) if pd.isnull(x) else x) def cities(self,df): return pd.get_dummies(df['city'].map({'Astapor':'Astapor','Winterfell':'Winterfell'})) if __name__ == '__main__': df = pd.read_csv('data/churn_train.csv',parse_dates = ['last_trip_date','signup_date']) from data_clean import Cleaner today = pd.datetime(2014,7,1) churn_thresh = pd.Timedelta(30, 'D') churn =(today-df['last_trip_date'] >churn_thresh).astype('int64').values clnr = Cleaner() clnr.stage_cleaning(df) clean_data = clnr.clean(df) gb = GradientBoostingClassifier(learning_rate=0.005,max_depth=10, n_estimators = 1000,min_samples_leaf=50, max_features = 5) df_test = pd.read_csv('data/churn_train.csv',parse_dates = ['last_trip_date','signup_date']) churn_test =(today-df_test['last_trip_date'] >churn_thresh).astype('int64').values clean_data_test = clnr.clean(df_test) gb.fit(clean_data,churn) print(gb.score(clean_data_test,churn_test)) <file_sep>import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn import preprocessing from data_clean import Cleaner #Shane's class for cleaning class MeanVisualization(): ''' For use with the ridesharing dataset/case study: https://github.com/gSchool/dsi-churn-case-study Using Shane's Cleaner class, this class will clean the data and then visualize the means of each feature broken down by churned vs. did not churn. Attributes: --------------- filepath: string with the filepath of the data to import (must be csv) a filepath must be passed in each time this class is instantiated df: pandas dataframe created automatically once filepath in passed in Methods: --------------- raw_viz: return barplot with means from raw (unscaled) data standardized_viz: return barplot with means from standardized data ''' def __init__(self, filepath): self.filepath = filepath #should be a string with the filepath of the raw data (must be csv) self.df = pd.read_csv(self.filepath, parse_dates=['last_trip_date','signup_date']) #parse_dates is hard coded for our specific reqs. def raw_viz(self): ''' Creates barplot of the means using raw (unscaled) data. ''' #cleaning the data df = self.df clnr = Cleaner() clnr.stage_cleaning(df) clean_data = clnr.clean(df) #creating binary column for churn clean_data.loc[df['last_trip_date'] > '2014-05-31', 'churn'] = 0 # did not churns clean_data.loc[df['last_trip_date'] < '2014-06-01', 'churn'] = 1 # did churns #creating pivot table with means to visualize, re-formatting for easy seaborn barplotting pivot_mean = pd.pivot_table(clean_data, columns='churn', aggfunc=np.mean) churn_col = pd.DataFrame(pivot_mean[1]) churn_col['churn'] = 1 churn_col.columns = ['mean', 'churn'] non_churn_col = pd.DataFrame(pivot_mean[0]) non_churn_col['churn'] = 0 non_churn_col.columns = ['mean', 'churn'] new_df = churn_col.append(non_churn_col) new_df.reset_index(level=0, inplace=True) # if they exist, dropping acct_age and inactive_days columns # because they're uninformative and skew the y-axis of the plot if 'inactive_days' in new_df: viz_df = new_df[(new_df['index'] != 'acct_age') & (new_df['index'] != 'inactive_days')] else: viz_df = new_df #plotting fig, ax = plt.subplots(figsize=(15, 5)) ax = sns.barplot(x='index', y='mean', hue='churn', data=viz_df) plt.title('Unscaled means') def standardized_viz(self): ''' Creates barplot of the means using scaled data. Uses standard scaler from sklearn on all features. ''' #cleaning the data df = self.df clnr = Cleaner() clnr.stage_cleaning(df) clean_data_unscaled = clnr.clean(df) #scaling the data x = clean_data_unscaled.values #returns a numpy array scaler = preprocessing.StandardScaler() x_scaled = scaler.fit_transform(x) clean_data = pd.DataFrame(x_scaled) clean_data.columns = list(clean_data_unscaled) #replaces column names lost during scaling #creating binary churn column clean_data.loc[df['last_trip_date'] > '2014-05-31', 'churn'] = 0 # did not churns clean_data.loc[df['last_trip_date'] < '2014-06-01', 'churn'] = 1 # did churns #creating pivot table with means to visualize, re-formatting for easy seaborn barplotting pivot_mean = pd.pivot_table(clean_data, columns='churn', aggfunc=np.mean) churn_col = pd.DataFrame(pivot_mean[1]) churn_col['churn'] = 1 churn_col.columns = ['mean', 'churn'] non_churn_col = pd.DataFrame(pivot_mean[0]) non_churn_col['churn'] = 0 non_churn_col.columns = ['mean', 'churn'] new_df = churn_col.append(non_churn_col) new_df.reset_index(level=0, inplace=True) # if they exist, dropping acct_age and inactive_days columns # because they're uninformative and skew the y-axis of the plot if 'inactive_days' in new_df: viz_df = new_df[(new_df['index'] != 'acct_age') & (new_df['index'] != 'inactive_days')] else: viz_df = new_df #plotting fig, ax = plt.subplots(figsize=(15, 5)) ax = sns.barplot(x='index', y='mean', hue='churn', data=viz_df) plt.title('Scaled means')<file_sep>import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import mean_squared_error, r2_score from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC class Cleaner: def __init__(self): self.len_train = 0 self.feature_names = [] self.today = pd.to_datetime('7/1/2014') def stage_and_clean(self, df): # send data to staging for initialization and separation X, y = self.stage(df) # clean x and y X = self.cleanX(X) y = self.cleany(y) return X, y def stage(self, df): # save null values self.rider_null = df['avg_rating_by_driver'].median() self.driver_null = df['avg_rating_of_driver'].median() df['last_trip_date'] = pd.to_datetime(df['last_trip_date']) df['signup_date'] = pd.to_datetime(df['signup_date']) # separate x and y y = df.drop('last_trip_date', axis=1) X = df return X, y def cleany(self, y): inactive_days = (pd.Timedelta self.today - y).apply(lambda x: x.days) churn_mask = inactive_days > 30 return churn_mask.astype('int64') def cleanX(self, X): # first create clean df with android iphone dummy clean_X = self.phone_types(X) # convert datetimes to datetimes clean_X['acct_age'] = (self.today - X['signup_date'])\ .apply(lambda x: x.days) # map dummies clean_X = clean_X.merge(self.cities(X), left_index=True, right_index=True) clean_X['black'] = X['luxury_car_user'].astype('int64') # ensure full columns in rating columns, using staged values as needed clean_X['rider_rtg'] = self.rider_rtg(X) clean_X['driver_rtg'] = self.driver_rtg(X) # observed to be non-null in training data # will write cleaning methods if null appears in test clean_X['avg_dist'] = X['avg_dist'] clean_X['avg_surge'] = X['avg_surge'] clean_X['surge_pct'] = X['surge_pct'] clean_X['first_30'] = X['trips_in_first_30_days'] clean_X['weekday_pct'] = X['weekday_pct'] # save cleaned changes return clean_X def phone_types(self,df): return pd.get_dummies(df['phone'].map({'Android':'Android','iPhone':'iPhone'})) def rider_rtg(self,df): return df['avg_rating_by_driver'].apply(lambda x: self.rider_null if pd.isnull(x) else x) def driver_rtg(self,df): return df['avg_rating_of_driver'].apply(lambda x: self.driver_null if pd.isnull(x) else x) def cities(self,df): return pd.get_dummies(df['city'].map({'Astapor':'Astapor','Winterfell':'Winterfell'})) <file_sep>import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression, LogisticRegressionCV # from sklearn.linear_model import Ridge from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from data_clean import Cleaner sns.set(style="ticks") df = pd.read_csv('data/churn_train.csv') dcc = Cleaner() df['last_trip_date'] = pd.to_datetime(df['last_trip_date']) df['signup_date'] = pd.to_datetime(df['signup_date']) dcc.stage_cleaning(df) df = dcc.clean(df) # sns.pairplot(df) # plt.savefig('scatter_matrix.png') print(df.head()) # plt.hist(df['driver_rtg']) # plt.show() # high_driver_rating = df[df['driver_rtg'] == 5.0] # low_driver_rating = df[df['driver_rtg'] < 5.0] y = df.pop('surge_bool') X = df # kf = KFold(n_splits=5, shuffle=True) # preds = [] # for i, (train_index, test_index) in enumerate(kf.split(y)): # X_train, X_test = X.iloc[train_index], X.iloc[test_index] # y_train, y_test = y.iloc[train_index], y.iloc[test_index] # log_reg = LogisticRegression(solver='lbfgs') # log_reg.fit(X_train, y_train) # preds.append(log_reg.predict(X_test)) # print(preds) # preds = np.array([np.mean(preds[:, i]) for i in range(len(preds[0]))]) clf = LogisticRegressionCV(cv=5, random_state=0, solver='liblinear', n_jobs=-1).fit(X, y) print("Logistic Regression score: ", clf.score(X, y)) print(clf.predict_proba(X))
04aa24457c096994237ee656de65bcbcbe5ce701
[ "Markdown", "Python" ]
5
Markdown
DataAna1ytics/case-study-churn-analysis
846b3c693143b26a9beb8504918a59986a19ec71
c8afbe8d02f128430667bb494208617e32bff143
refs/heads/main
<repo_name>EmanuelLP/Jose_Emanuel_Lopez_Paez_IC_602_Taller_SO<file_sep>/Practica_Sockets/servidor.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #define PORT 4455 #define MAX_DATA 1024 void main(){ //Estructuras de tipo sockaddr para guardar la informacion int sockfd; struct sockaddr_in serverAddr; int newSocket; struct sockaddr_in newAddr; socklen_t addr_size; char buffer[MAX_DATA]; char *buf; //Definir socket /*SI el resultado es -1 hubo un error*/ sockfd=socket(PF_INET,SOCK_STREAM,0); if(sockfd<0){ printf("[**]NO se puedo crear el servidor[**]\n"); exit (-1); }else{ printf("[**]SERVIDOR CREADO EXITOSAMENTE[**]\n"); memset(&serverAddr,'\0',sizeof(serverAddr)); //Configuracion del servidor serverAddr.sin_family=AF_INET;//Familia tcp/ip serverAddr.sin_port=htons(PORT); //Puerto serverAddr.sin_addr.s_addr=inet_addr("127.0.0.1");//DIreccion en especifico /*Se puede moficar para que cualquiera pudiera conectar cambiando la direccion por: INADDR_ANY*/ //Avisar al sistema que se creo un socket /*SI el resultado es -1 hubo un error*/ if(bind(sockfd,(struct sockaddr*)&serverAddr,sizeof(serverAddr))<0){ printf("[++]Error en el bind[++]\n"); printf("++Intente mรกs tarde++\n"); exit (-1); }else{ printf("[++]Numero de puerto %d[++]\n",4455); //Poner el socket en modo escucha /*SI el resultado es -1 hubo un error*/ if(listen(sockfd,5)<0){ printf("[//]Error en el listen[\\]"); exit (-1); }else{ printf("[//]Listen[\\]\n"); addr_size=sizeof(newAddr); //Aceptar conexion newSocket=accept(sockfd,(struct sockaddr*)&newAddr,&addr_size); strcpy(buffer,"HOLA, servidor disponible\n"); //SE envia al cliente la cadena send(newSocket,buffer,strlen(buffer),0); printf("[~~]Enviando informacion al cliente[~~]\n"); //Primer valor printf("[~~]Recibiendo valores[~~]\n"); //LImpiar buffer memset(&buffer,'\0',sizeof(buffer)); recv(newSocket,buffer,MAX_DATA,0); printf("[^^]INF. RECIVIDA[^^]: %s \n",buffer); //Tamaรฑo de numeros unsigned long int numbytes=strlen(buffer); printf ("Bytes:%lu\n",numbytes); //Convertir cadena a entero //unsigned long int valor1=atoi(buffer); unsigned long int valor1=strtoul(buffer, &buf, 0); printf("Numero en entero %lu\n",valor1); if(strlen(buf)>=1){ printf("ERROR ~~Ingreso caracteres~~\n"); printf("%s\n",buf); } //SE envia al cliente la cadena memset(&buffer,'\0',sizeof(buffer)); strcpy(buffer,"Envie el segundo valor\n"); send(newSocket,buffer,strlen(buffer),0); printf("[~~]Enviando informacion al cliente[~~]\n"); //Segundo valor //LImpiar buffer memset(&buffer,'\0',sizeof(buffer)); recv(newSocket,buffer,MAX_DATA,0); printf("[^^]INF. RECIVIDA[^^]: %s \n",buffer); //Tamaรฑo de numeros numbytes=strlen(buffer); printf ("Bytes:%lu\n",numbytes); //Convertir cadena a entero //unsigned long long int valor2=atoi(buffer); unsigned long int valor2=strtoul(buffer, &buf, 0); printf("Numero en entero %lu\n",valor2); if(strlen(buf)>=1){ printf("ERROR ~~Ingreso caracteres~~\n"); printf("%s\n",buf); } memset(&buffer,'\0',sizeof(buffer)); unsigned long int suma=valor1+valor2; /*itoa no funcina en Ubuntu*/ //itoa(suma,buffer,10); sprintf(buffer, "%lu",suma); //SE envia al cliente la cadena send(newSocket,buffer,strlen(buffer),0); printf("[~~]Enviando informacion al cliente[~~]\n"); } } } } <file_sep>/Scheduler/scheduler.c #include "scheduler.h" int num_procesos(){ int num_proc; printf("Ingrese la cantidad de procesos a ejecutar\n"); printf("\tNum procesos= "); fflush(stdin); scanf("%d",&num_proc); return num_proc; } int quantum(){ int time_ejec; printf("Ingrese la cantidad de tiempo que tendra un proceso en ejecucion en la CPU (Seg)\n"); printf("\tQuantum= "); fflush(stdin); scanf("%d",&time_ejec); return time_ejec; } Proceso *llenar_proceso(char *nombre, int tiempo){ Proceso *proc=(Proceso *)malloc(sizeof(Proceso)); char *SI="Inicializado"; strcpy(proc->nombre,nombre); proc->tiempo=tiempo; strcpy(proc->estado,SI); return proc; } void imprimir(Proceso vproc[], int num_proc){ printf("\t\t TABLA DE PROCESOS\n"); printf("Nombre del proceso |\tTiempo\t|\tEstado\t|\n"); int i; for(i=0;i<num_proc;i++){ printf("\t%s\t", vproc[i].nombre); printf("\t%d\t", vproc[i].tiempo); printf("\t%s\n", vproc[i].estado); } } void agregar(Proceso vproc[],Proceso *proc,int posicion){ strcpy(vproc[posicion].nombre,proc->nombre); vproc[posicion].tiempo=proc->tiempo; strcpy(vproc[posicion].estado,proc->estado); } void llenar_estructura(Proceso vproc[],Proceso *proc,int num_proc){ char nombre[TAM_TEXTO]; int tiempo,i; for(i=0; i<num_proc; i++){ printf("Ingrese el nombre del procesos a ejecutar[%d]\n",(i+1)); printf("\tNombre: "); memset(nombre,'\0',TAM_TEXTO); scanf("%s",nombre); printf("Ingrese la cantidad de tiempo del proceso a ejecutar (Seg)\n"); printf("\tTiempo= "); fflush(stdin); scanf("%d",&tiempo); proc=llenar_proceso(nombre,tiempo); agregar(vproc,proc,i); } } bool vector_finalizado(Proceso vproc[],int num_proc){ bool bandera; int i,cn=0; for(i=0;i<num_proc;i++){ if(vproc[i].tiempo == 0 && strcasecmp(vproc[i].estado,"Finalizado")==0 ){ cn++; } } if(cn==num_proc){ printf("\nSimulacion terminada"); bandera=true; }else{ bandera=false; } return bandera; } void imprimir_posicion(Proceso vproc[], int posicion){ printf("\n\t%s\t", vproc[posicion].nombre); printf("\t%d\t", vproc[posicion].tiempo); printf("\t%s\n", vproc[posicion].estado); } void round_robin(Proceso vproc[], int time_ejec,int num_proc){ int i=0,time_cpu=0; bool bandera; char *SE="Ejecucion",*SB="Bloqueado",*SF="Finalizado"; do{ if(strcasecmp(vproc[i].estado,"Inicializado") == 0 ){ imprimir_posicion(vproc,i); } bandera=vector_finalizado(vproc,num_proc); if(bandera==false){ if(strcasecmp(vproc[i].estado,"Finalizado") == 0 ){ i++; } if(vproc[i].tiempo > 0){ strcpy(vproc[i].estado,SE); imprimir_posicion(vproc,i); } if(vproc[i].tiempo > 0 && vproc[i].tiempo >= time_ejec){ vproc[i].tiempo=vproc[i].tiempo-time_ejec; if(vproc[i].tiempo == 0){ strcpy(vproc[i].estado,SF); } if(vproc[i].tiempo > 0){ strcpy(vproc[i].estado,SB); } time_cpu=time_cpu+time_ejec; } else if(vproc[i].tiempo > 0 && vproc[i].tiempo < time_ejec){ vproc[i].tiempo=0; strcpy(vproc[i].estado,SF); time_cpu=time_cpu+vproc[i].tiempo; } imprimir_posicion(vproc,i); } i++; if(i==num_proc){ i=0; } }while(bandera==false); printf("\nEl tiempo en la CPU fue %d\n",time_cpu); } <file_sep>/Multiprogramacion/simulacion.c #include <stdio.h> #include <stdlib.h> //Para usar variables tipo boolean #include <string.h> #include <math.h> typedef struct { char nombre[20]; int tiempo; char estado[20]; }Proceso; typedef struct { char nombre[20]; int tiempo; char estado[20]; int gantt; }DGantt; int main(){ //Datos iniciales int num_proc, time_ejec; printf("Ingrese la cantidad de tiempo que tendra un proceso en ejecucion en laPU (Seg)\n"); printf("Quantum= "); fflush(stdin); scanf("%d",&time_ejec); printf("Ingrese la cantidad de procesos a ejecutar\n"); printf("Num procesos= "); fflush(stdin); scanf("%d",&num_proc); //Lenado de las estrcturas deprocesos Proceso proc[num_proc]; int i; char *SI,*SE,*SF,*SB; for(i=0; i<num_proc; i++){ printf("Ingrese el nombre del procesos a ejecutar[%d]\n",(i+1)); printf("Nombre: "); fflush(stdin); gets(proc[i].nombre); printf("Ingrese la cantidad de tiempo del proceso a ejecutar (Seg)\n"); printf("Tiempo= "); fflush(stdin); scanf("%d",&proc[i].tiempo); SI="Inicializado"; strcpy(proc[i].estado,SI); } //Tabla de procesos printf("\t\t TABLA DE PROCESOS\n"); printf("Nombre del proceso |\tTiempo\t|\tEstado\t|\n"); for(i=0;i<num_proc;i++){ printf("\t%s\t", proc[i].nombre); printf("\t%d\t", proc[i].tiempo); printf("\t%s\n", proc[i].estado); } //Simulacion multiprogramacion (Mรฉtodo Round Robin) [tamaรฑo de tabla] int bandera=0,j=0,contador=0,time_act,k=0; int suma=0,total=0, l=0, tm=0, cn=0; Proceso temporal[num_proc]; //Llenamos un array temporal for(i=0;i<num_proc;i++){ temporal[i]=proc[i]; } //Determinacion del tamaรฑo del segundo vector do{ //Se verifica que todos los valores en tiempo, for para recorrer //if para que el tiempo sea <= 0 y que este se ejecute hasta la ultima //posicion del array for(i=0;i<num_proc;i++){ if(temporal[i].tiempo <= 0 && (l+1)==num_proc ){ cn++; } } if(temporal[l].tiempo>0){ total++; tm=temporal[l].tiempo-time_ejec; temporal[l].tiempo=tm; } if((l+1)==num_proc){ l=0; suma++; }else{ l++; } if(cn==num_proc){ bandera=1; } }while(bandera==0); int tam; tam=(total+suma)+(num_proc*3); //Simulacion multiprogramacion (Mรฉtodo Round Robin) [Estados y tiempo ] i=0; cn=0; bandera=0; DGantt tabla[tam]; char *n="Vuelta>",*s="---------"; int t=0, timecpu=0, m=0; do{ for(m=0;m<num_proc;m++){ if(proc[m].tiempo == 0 && (i+1)==num_proc ){ cn++; } } //Se toma los valores iniciales como son declarados if(strcasecmp(proc[i].estado,"Inicializado")==0 ){ strcpy(tabla[j].nombre,proc[i].nombre); tabla[j].tiempo=proc[i].tiempo; strcpy(tabla[j].estado,proc[i].estado); tabla[j].gantt=timecpu; } //Si el proceso tiene un estado finalizado y tiempo en 0, se es ignorado y continua // if(strcasecmp(proc[i].estado,"Finalizado")==0 && proc[i].tiempo==0){ // i++; // } if(proc[i].tiempo<time_ejec && proc[i].tiempo != 0){ timecpu=timecpu+proc[i].tiempo; time_act=0; SF="Finalizado"; //Se hace el recorrido +1 en j la cual ayuda a llenar valores en el vector tabla j++; //Se actualiza el estado en el vector proc[i] strcpy(proc[i].estado,SF); proc[i].tiempo=time_act; //Se llena los datos del atributo para el vector tabla strcpy(tabla[j].nombre,proc[i].nombre); tabla[j].tiempo=proc[i].tiempo; strcpy(tabla[j].estado,proc[i].estado); //Se guarda el estado que se finalizo el proceso tabla[j].gantt=timecpu; }else if(proc[i].tiempo>=time_ejec){ //Optencion del tiempo restante del proceso time_act=proc[i].tiempo-time_ejec; //Si el tiempo restante es igual a cero se declara el estado finalizado if(time_act==0){ //Se suma el tiempo en el cpu timecpu=timecpu+time_ejec; SF="Finalizado"; j++; strcpy(proc[i].estado,SF); proc[i].tiempo=time_act; strcpy(tabla[j].nombre,proc[i].nombre); tabla[j].tiempo=proc[i].tiempo; strcpy(tabla[j].estado,proc[i].estado); tabla[j].gantt=timecpu; } else{ SE="Ejecucion"; //Se actualiza el el vector proc[i] proc[i].tiempo= time_act; strcpy(proc[i].estado,SE); //Se recorre una posicion para el vector tabla "Ejecucion" j++; //Se llena los datos del atributo para el vector tabla strcpy(tabla[j].nombre,proc[i].nombre); tabla[j].tiempo=proc[i].tiempo; strcpy(tabla[j].estado,proc[i].estado); tabla[j].gantt=timecpu; //Se suma el tiempo en la cpu con el quantum timecpu=timecpu+time_ejec; SB="Bloqueado"; //Se actualiza el el vector proc[i] strcpy(proc[i].estado,SB); //Se recorre una posicion para el vector tabla "Bloqueado" j++; //Se llena los datos del atributo para el vector tabla strcpy(tabla[j].nombre,proc[i].nombre); tabla[j].tiempo=proc[i].tiempo; strcpy(tabla[j].estado,proc[i].estado); tabla[j].gantt=timecpu; } } //Si i es igual al numero de procesos de coloca en 0 //para que el ciclo del vector se realice de nuevo if((i+1)==num_proc){ i=0; //Posicion para llenar un vector de detalles j++; //Numero de vuelta=t t++; //Se llena un espacio en el vector tabla // para especidcar el numero de vuelta strcpy(tabla[j].nombre,n); tabla[j].tiempo=t; strcpy(tabla[j].estado,s); tabla[j].gantt=t; }else{ i++; } if(cn==num_proc){ bandera=1; } }while(bandera==0); //Tabla de estados de los procesos printf("\n\n\t\t HISTORAL DE PROCESOS\n"); printf("Nombre del proceso|\tTiempo\t|\tEstado\t|\tTiempo en el CPU\n"); //Se recorre el vector tabla para imprimir sus datos for(i=0;i<tam;i++){ printf("\t%s\t", tabla[i].nombre); printf("\t%d\t", tabla[i].tiempo); printf("\t%s", tabla[i].estado); printf("\t%d\n", tabla[i].gantt); } //Tabla de procesos finalizado printf("\t\t TABLA DE PROCESOS RESULTADO\n"); printf("Nombre del proceso |\tTiempo\t|\tEstado\t|\n"); for(i=0;i<num_proc;i++){ printf("\t%s\t", proc[i].nombre); printf("\t%d\t", proc[i].tiempo); printf("\t%s\n", proc[i].estado); } return 0; } <file_sep>/Practica_Sockets/cliente.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #define PORT 4455 #define MAX_DATA 1024 void main(){ int clientSocket; //Estrcutura para guardar informacion sel servidor remoto struct sockaddr_in serverAddr; char buffer[MAX_DATA]; //Creacion del socket /*SI el resultado es -1 hubo un error*/ clientSocket=socket(PF_INET, SOCK_STREAM, 0); if(clientSocket<0){ printf ("[**]No puedo establecer conexion con el servidor[**]\n"); exit (-1); }else{ printf("[**]CLIENTE CREADO EXITOSAMENTE[**]\n"); memset(&serverAddr,'\0',sizeof(serverAddr)); //Datos del servidor serverAddr.sin_family=AF_INET;//Familia tcp/ip serverAddr.sin_port=htons(PORT);//Puerto serverAddr.sin_addr.s_addr=inet_addr("127.0.0.1");//Direccion en especifico //Conectarse al servidor /*SI el resultado es -1 hubo un error*/ if(connect(clientSocket, (struct sockaddr*)&serverAddr,sizeof(serverAddr))<0){ printf("[++]Conexion fallida[++]\n"); exit (-1); } else{ printf("[++]Coneccion a servidor[++]\n"); memset(&buffer,'\0',sizeof(buffer)); //Revibir datos del servidor recv(clientSocket,buffer,MAX_DATA,0); printf("[^^]INF. RECIVIDA[^^]: %s \n",buffer); //Pedir primer valor char valor1[MAX_DATA]; printf("Ingrese el primer valor de (1-19 digitos)\n"); scanf("%s",valor1); //Enviando valor1 //strcpy(valor1,"1111111111111111111"); send(clientSocket,valor1,strlen(valor1),0); printf("[~~]Valor 1 enviado[~~]\n"); memset(&buffer,'\0',sizeof(buffer)); //Recibir datos del servidor recv(clientSocket,buffer,MAX_DATA,0); printf("[^^]INF. RECIVIDA[^^]: %s \n",buffer); //Pedir segundo valor char valor2[MAX_DATA]; printf("Ingrese el segundo valor de (1-19 digitos)\n"); scanf("%s",valor2); //Enviando valor2 //strcpy(valor2,"2222222222222222222"); send(clientSocket,valor2,strlen(valor2),0); printf("[~~]Valor 2 enviado[~~]\n"); memset(&buffer,'\0',sizeof(buffer)); //Recibir datos del servidor recv(clientSocket,buffer,MAX_DATA,0); printf("[^^]Suma[^^]: %s \n",buffer); printf("[##]Cerrando conexion[##]\n"); } } } <file_sep>/Bash/ingresar_Usuarios.sh #!/bin/bash ROOT_UID=0 SUCCESS=0 # Run as root, of course. (this might not be necessary, because we have to run the script somehow with root anyway) if [ "$UID" -ne "$ROOT_UID" ] then echo "Se debe estar como root para ejecutar este script" exit $E_NOTROOT fi file=$1 if [ "${file}X" = "X" ]; then echo "Debe indicar el archivo con el listado de usuarios a ingresar..." exit 1 fi # Del archivo con el listado de usuarios a ingresar: # Este es el formato: # ejemplo # | # f1:f2:f3:f4:f5:f6:f7 #$f1 = username #$f2 = password (por defecto <PASSWORD>) #$f3 = User ID (no se utiliza si se deja en blanco) #$f4 = Group ID, debe de existir en /etc/group #$f5 = User ID Info #$f6 = home directory #$f7 = Comand Shell ingresarUsuario(){ #se puede realizar tambien con cut -d y asignando que cada : sea la variable #echo "----> Ingresar Usuario <----" eval user="$1" eval password="$2" eval userid="$3" eval grupoid="$4" eval info="$5" eval home="$6" eval shell="$7" #echo "Username = ${user}" #echo "-------------------------" #Si existe grupoid(f4) se crea el usuario en la direccion /etc/group if grep -q ${grupoid} /etc/group then #echo "GrupoID =${grupoid}" #echo "Shell =${shell}" #Se comprueba el nombre(f1) (existe) el usuaruo en /etc/passwd if grep -q ${user} /etc/passwd then echo "--->Username existe =${user}<---" else #echo "Username no existe =${user}" #echo "Directorio =${home}" #Creacion del usaurio con el shell #-c comenetario campos GECOS #-p contraseรฑa cifrada #-d home-dir DIR_PERSONAL #-s sell consola de acceso a la nueva cuenta #-u UID identificador de la nueva cuenta #-g identificador de grupo useradd -c "${info}" -p "${password}" -d "${home}${user}" -s "${shell}" "${user}" -g "${grupoid}" if [ $? -eq $SUCCESS ]; then #echo "Grupo [${nombreGrupo}] agregado correctamente..." echo "--->Usuario creado USER= ${user} PASSWORD= ${password}<---" echo "[${user}:${password}:${userid}:${grupoid}:${info}:${home}${user}:${shell}]" else echo "Usuario no creado" #echo "Grupo [${nombreGrupo}] No se pudo agregar..." fi #echo "Usuario creado USER= ${user} PASSWORD= ${password}" fi #echo "Usuario repetido USER= ${user} PASSWORD= ${<PASSWORD>}" else echo "No existe el grupo" echo "Debe crear grupo ${grupoid} antes de ingresar el usuario ${user}" fi } while IFS=: read -r f1 f2 f3 f4 f5 f6 f7 do #Argumentos de entrada f1:f2:f3:f4:f5:f6:f7 ingresarUsuario "\${f1}" "\${f2}" "\${f3}" "\${f4}" "\${f5}" "\${f6}" "\${f7}" done < ${file} exit 0 <file_sep>/gestion_archivos/code.c #include <stdio.h> #include <string.h> #define TAM_NOMBRE 100 #define TAM_LECTURA 100 #define MAXIMA_LONGITUD_CADENA 1000 FILE *abrir_Archivo_solo_Lectura(char *nombre_arch){ FILE *ptrArchivo; ptrArchivo = fopen(nombre_arch, "r"); if( ptrArchivo == NULL ){ // con r Abre un archivo para lectura. printf("---> El archivo -> %s <- NO pudo abrirse (uso de r).\n", nombre_arch); } else{ printf("---> Archivo -> %s <- Abierto (uso de r).\n", nombre_arch); } return ptrArchivo; } void cerrar_archivo(FILE *ptrArchivo, char *nombre_arch){ fclose(ptrArchivo); printf("----> Archivo -> %s <- Cerrado Correctamente.\n", nombre_arch); } int existe_archivo(char *nombre_arch){ FILE *ptrArchivo; int existe = 0; // Con r abre un archivo para lectura. ptrArchivo = fopen(nombre_arch, "r"); if( ptrArchivo != NULL ){ existe = 1; cerrar_archivo(ptrArchivo, nombre_arch); } return existe; } int comparar(const void *a, const void *b){ const char *cp1 = a, *cp2 = b; for (; toupper(*cp1) == toupper(*cp2); cp1++, cp2++) if (*cp1 == '\0') return 0; return ((toupper(*cp1) < toupper(*cp2)) ? -1 : +1); } FILE *abrir_Archivo_lectura_escritura(char *nombre_arch){ FILE *ptrArchivo; ptrArchivo = fopen(nombre_arch, "r+"); if( ptrArchivo == NULL ){ // con r+ Abre un archivo para actualizaciรณn (lectura y escritura). printf("---> El archivo -> %s <- NO pudo abrirse (uso de r+).\n", nombre_arch); } else{ printf("---> Archivo -> %s <- Abierto (uso de r+).\n", nombre_arch); } return ptrArchivo; } // Implementaciรณn del mรฉtodo de la burbuja en C, para arreglos de cadenas void burbuja(char arreglo[][MAXIMA_LONGITUD_CADENA], int longitud) { // รštil para hacer intercambio de cadenas char temporal[MAXIMA_LONGITUD_CADENA]; int x, indiceActual; for (x = 0; x < longitud; x++) { for (indiceActual = 0; indiceActual < longitud - 1; indiceActual++) { int indiceSiguienteElemento = indiceActual + 1; // Si la cadena es mayor que la siguiente (alfabeticamente) entonces intercambiamos if (strcmp(arreglo[indiceActual], arreglo[indiceSiguienteElemento]) > 0) { // Movemos la cadena actual a la temporal memcpy(temporal, arreglo[indiceActual], MAXIMA_LONGITUD_CADENA); // Movemos al actual el siguiente elemento memcpy(arreglo[indiceActual], arreglo[indiceSiguienteElemento], MAXIMA_LONGITUD_CADENA); // Y en el siguiente elemento, lo que habรญa antes en el actual pero ahora estรก en temporal memcpy(arreglo[indiceSiguienteElemento], temporal, MAXIMA_LONGITUD_CADENA); } } } // No hay necesidad de devolver nada, pues modificamos al arreglo de manera interna } int crear_archivo(char *nombre_arch){ int creado = 0; FILE *ptrArchivo; ptrArchivo = fopen(nombre_arch, "w"); if( ptrArchivo == NULL ){ // con w crea un archivo para escritura. Si el archivo ya existe, descarta el contenido actual. printf("----> El archivo -> %s <- no pudo crearse (abrir; uso de w).\n", nombre_arch); } else{ creado = 1; printf("----> Archivo -> %s <- Creado (abierto; uso de w).\n", nombre_arch); cerrar_archivo(ptrArchivo, nombre_arch); } return creado; } FILE *abrir_Archivo_escritura(char *nombre_arch){ FILE *ptrArchivo; ptrArchivo = fopen(nombre_arch, "w+"); if( ptrArchivo == NULL ){ // con r+ Abre un archivo para actualizaciรณn (lectura y escritura). printf("---> El archivo -> %s <- NO pudo abrirse (uso de w+).\n", nombre_arch); } else{ printf("---> Archivo -> %s <- Abierto (uso de w+).\n", nombre_arch); } return ptrArchivo; } int main(int argc, char const *argv[]){ // FILE es una estructura /* ptrCF apuntado al archivo Open apuntador que si no puede abrir el programa se cierra*/ FILE *ptrCf = NULL; FILE *ptrCd = NULL; char nom_archivo[TAM_NOMBRE]; char nom_archivod[TAM_NOMBRE]; int existe_arch = 0; char cadena[TAM_LECTURA]; char cadena1[TAM_LECTURA]; char cadena2[TAM_LECTURA]; char separadores[]=" \n\t"; char *puntero; int palabras=0; //VERIFICACION DE UN ARCHIVO EXISTENTE do{ printf("\tIntroduzca el Nombre del Archivo de Entrada: "); gets(nom_archivo); existe_arch = existe_archivo(nom_archivo); if(existe_arch){ printf("---------------------------------------------------------------\n"); printf("\tEl archivo -> %s <-EXISTE.\n", nom_archivo); printf("---------------------------------------------------------------\n"); }else{ printf("---------------------------------------------------------------\n"); printf("\tEl archivo -> %s <- NO EXISTE.\n", nom_archivo); printf("---------------------------------------------------------------\n"); } }while(!existe_arch); //ABRIR ARCHIVO ptrCf = abrir_Archivo_solo_Lectura(nom_archivo); if(ptrCf == NULL){ printf("****************************************************************\n"); printf("\tEl archivo -> %s <- NO pudo Abrirse.\n", nom_archivo); printf("****************************************************************\n"); } else{ printf("****************************************************************\n"); printf("\tArchivo -> %s <- Abierto Correctamente.\n", nom_archivo); printf("****************************************************************\n"); while(!feof(ptrCf)){ fgets(cadena,TAM_LECTURA,ptrCf); printf("%s",cadena); } printf("---------------------------------------------------------------------------\n"); printf("\t---> LECTURA TERMINADA <---\n"); printf("---------------------------------------------------------------------------\n"); cerrar_archivo(ptrCf, nom_archivo); } //NUMERO PALABRAS PALABRAS printf("****************************************************************\n"); printf("\tPalabras separadas\n"); printf("****************************************************************\n"); ptrCf = abrir_Archivo_solo_Lectura(nom_archivo); //setear la cadena con el valor 0=\0 es vacio memset(cadena1,0,TAM_LECTURA); while(!feof(ptrCf)){ fgets(cadena1,TAM_LECTURA,ptrCf); /*strtok=token particionar la cadena por separadores*/ puntero=strtok(cadena1,separadores); palabras++; strcpy(cadena1,puntero); printf("%s\n",cadena1); while((puntero=strtok(NULL,separadores))!=NULL){ palabras++; strcpy(cadena1,puntero); printf("%s\n",cadena1); } } cerrar_archivo(ptrCf, nom_archivo); //GUARADAR PALABRAS EN ARREGLO int contador=0; char texto[palabras][MAXIMA_LONGITUD_CADENA]; char buffer[MAXIMA_LONGITUD_CADENA]; char pd[MAXIMA_LONGITUD_CADENA]; //LLENAR VECTOR DE PALABRAS ptrCf = abrir_Archivo_lectura_escritura(nom_archivo); /*while(fgets(buffer,MAXIMA_LONGITUD_CADENA,ptrCf)){ strtok(buffer,"\n"); memcpy(texto[contador],buffer,MAXIMA_LONGITUD_CADENA); contador++; } */ while(!feof(ptrCf)){ fgets(cadena1,TAM_LECTURA,ptrCf); /*strtok=token particionar la cadena por separadores*/ puntero=strtok(cadena1,separadores); strcpy(cadena1,puntero); printf("%s\n",cadena1); strcpy(memcpy(texto[contador],buffer,MAXIMA_LONGITUD_CADENA),cadena1); //memcpy(texto[contador],buffer,MAXIMA_LONGITUD_CADENA); while((puntero=strtok(NULL,separadores))!=NULL){ //palabras++; strcpy(cadena1,puntero); printf("%s\n",cadena1); contador++; strcpy(memcpy(texto[contador],buffer,MAXIMA_LONGITUD_CADENA),cadena1); //memcpy(texto[contador],buffer,MAXIMA_LONGITUD_CADENA); } } //LEER ARCHIVO SALIDA printf("\tIntroduzca el Nombre del Archivo Destino: "); gets(nom_archivod); existe_arch = existe_archivo(nom_archivod); if(existe_arch){ printf("---------------------------------------------------------------\n"); printf("\tEl archivo -> %s <- YA EXISTE.\n", nom_archivod); printf("---------------------------------------------------------------\n"); } else{ printf("---------------------------------------------------------------\n"); printf("\tEl archivo -> %s <- NO EXISTE.\n", nom_archivod); printf("---------------------------------------------------------------\n"); } if(crear_archivo(nom_archivod)){ printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); printf("\tEl archivo -> %s <- Fue creado/modificado EXITOSAMENTE.\n", nom_archivod); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); } else{ printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); printf("\tEl archivo -> %s <- NO pudo crearse.\n", nom_archivod); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); } //Abrir FILE Destino ptrCd=abrir_Archivo_escritura(nom_archivod); //Cerrar Dile Entrada cerrar_archivo(ptrCf, nom_archivo); //Longitud del arreglo int longitud = sizeof(texto) / sizeof(texto[0]); /*// Imprimimos el arreglo antes de ordenarlo, solo para ilustrar printf("---Imprimiendo arreglo sin ordenar---\n");*/ int i; /*for (i = 0; i < longitud; i++){ printf("%s\n", texto[i]); }*/ /*printf("\t\t\t%d\n",longitud); printf("\t\t\t%d\n",palabras); longuitud y palabras es el mismo numero*/ //Metodo de ordenamiento qsort((void*)texto,longitud,sizeof(texto[0]),comparar); for (i =0; i < longitud; i++){ printf("%s\n", texto[i]); fputs(texto[i],ptrCd); fputs("\n",ptrCd); } //Cerrar archivo de salida cerrar_archivo(ptrCd, nom_archivod); //Abrir archivo para solo lectura de salida ptrCd = abrir_Archivo_solo_Lectura(nom_archivod); while(!feof(ptrCd)){ fgets(cadena2,TAM_LECTURA,ptrCd); printf("%s",cadena2); } cerrar_archivo(ptrCd, nom_archivod); // Lo ordenamos //burbuja(texto, longitud); // Volvemos a imprimir //printf("---Imprimiendo arreglo ordenado---\n"); //for (i = 0; i < longitud; i++){ // printf("%s\n", texto[i]); //} printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); printf("\tFin del programa"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); return 0; } <file_sep>/Examen/ejercicio2.c #include <stdio.h> int main(){ char arrayChar[5]; int bd=0; char letra='a'; do{ arrayChar[bd]=letra; letra++; bd++; }while(letra<='e'); /*int i; for(i=0;i<5;i++){ printf("%c\n",arrayChar[i]); }*/ char *punteroChar; punteroChar=&arrayChar[0]; char *punteroCharDos; punteroCharDos=&arrayChar[0]; printf("\nArray primer valor: %c",arrayChar[0]); printf("\nPrimer elemento del punteroChar: %c",*punteroChar); printf("\nPrimer elemento del pubteroCharDos: %c",*punteroCharDos); printf("\nQuinto elemento del array: %c",arrayChar[4]); printf("\nQuinto elemento del punteroChar: %c",*(punteroChar+4)); printf("\nQuinto elemento del punteroCharDos: %c",*(punteroCharDos+4)); int i; printf("\n11.-PunteroCharDos "); for (i = 0; i < 5; ++i){ printf("\nLetra: %c", *(punteroCharDos+i)); } printf("\n12.-PunteroCharDos "); for (i = 0; i < 5; ++i){ printf("\nLetra: %c", *(punteroCharDos+i)); } /*printf("\n-PunteroChar "); for (i = 0; i < 5; ++i){ printf("\nLetra: %c", *(punteroChar+i)); }*/ return 0; } <file_sep>/Banco/main.c #include "banco.h" int main(){ int eleccion; int tam_banco; tam_banco=validarRango(1,LIMITE_PAISES,"Introduce el nรบmero de paises: "); Banco banco[tam_banco]; introducirPaises(banco, tam_banco); mostrarLongitudes(banco,tam_banco); saltoLinea(); instrucciones(); printf("\n Elija una opcion: "); scanf("%d",&eleccion); while(eleccion != SALIR){ switch(eleccion){ case ALTA: printf(" --- Opcion alta ---\n"); if(hayVacioTodaEstructura(banco,tam_banco)==true){ char nombre_pais[20]; //PEDIRNOMBREPAIS strcpy(nombre_pais,nombrePais(tam_banco,banco)); //Obtener indice int id_pais = getIndicePais(nombre_pais, banco, tam_banco); //Obtener indice cliente vacio int cliente= indiceVacioPaisEspecifico(id_pais, banco); if(cliente != -1){ char nombre_cliente[20]; char sexo; double saldo; strcpy(nombre_cliente,nombreCliente()); printf("\nIntroduce el Sexo: "); scanf("%s",&sexo); printf("\nIntroduce el Sueldo: "); scanf("%lf",&saldo); //llenar datos strcpy(banco[id_pais].clientes[cliente].nombre,nombre_cliente); banco[id_pais].clientes[cliente].sexo=sexo; banco[id_pais].clientes[cliente].saldo=saldo; banco[id_pais].clientes[cliente].ocupado=true; }else{ printf("No existe indice vacio en el pais %s",banco[id_pais].nombrePais); } }else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta completamente llena.\n"); printf("---------------------------------------------------------------------\n"); } break; case BAJA: printf(" --- Opciรณn baja ---\n"); if(estaTodoVacioEstructura(banco, tam_banco)==false){ char nombre_pais[20]; //PEDIRNOMBREPAIS strcpy(nombre_pais,nombrePais(tam_banco,banco)); //Obtener indice int pais = getIndicePais(nombre_pais, banco, tam_banco); //Obtener indice cliente int cliente = validarRango(0, getTotalClientes(banco,pais)-1, "\tIntroduce el indice del cliente: "); if(getIsOcupadoCliente(banco,pais,cliente)==true){ printf("\t--> Cliente %s dado de baja.",banco[pais].clientes[cliente].nombre); eliminarCliente(banco,pais,cliente); }else{ printf("\tEl cliente %i del pais %s no tiene datos.",cliente,banco[pais].nombrePais); } }else{ printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } break; case MOSTRAR_TODO: printf(" --- Opciรณn mostrar todo ---\n"); imprimirTodo(banco,tam_banco); break; case MOSTRAR_ESPECIFICO: printf(" --- Opciรณn mostrar especifico ---\n"); if(estaTodoVacioEstructura(banco, tam_banco)==false){ char nombre_pais[20]; //PEDIRNOMBREPAIS strcpy(nombre_pais,nombrePais(tam_banco,banco)); int pais= getIndicePais(nombre_pais, banco, tam_banco); int cliente = validarRango(0, getTotalClientes(banco,pais)-1, "\tIntroduce el indice del cliente: "); if(getIsOcupadoCliente(banco,pais,cliente)==true){ imprimirEspecifico(banco,pais,cliente); }else{ printf("\tEl cliente %i del pais %s no tiene datos.",cliente,banco[pais].nombrePais); } }else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } break; case MOSTRAR_OCUPADOS: printf(" --- Opciรณn mostrar solo ocupados ---\n"); imprimirSoloOcupados(banco, tam_banco); break; case ABONAR: printf(" --- Opciรณn abonar ---\n"); if(estaTodoVacioEstructura(banco, tam_banco)==false){ char nombre_pais[20]; //PEDIRNOMBREPAIS strcpy(nombre_pais,nombrePais(tam_banco,banco)); int pais = getIndicePais(nombre_pais, banco, tam_banco); int cliente = validarRango(0, getTotalClientes(banco,pais)-1, "\tIntroduce el indice del cliente: "); if(getIsOcupadoCliente(banco,pais,cliente)==true){ double cuanto; printf("\tIntroduce cuanto ingresarรกs a tรบ cuenta: "); scanf("%lf",&cuanto); abonarSaldoCliente(banco, pais,cliente, cuanto); }else{ printf("\tEl cliente %i del pais %s no tiene datos.",cliente,banco[pais].nombrePais); } }else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } break; case RETIRAR: printf(" --- Opciรณn retirar ---\n"); if(estaTodoVacioEstructura(banco, tam_banco)==false){ char nombre_pais[20]; //PEDIRNOMBREPAIS strcpy(nombre_pais,nombrePais(tam_banco,banco)); int pais = getIndicePais(nombre_pais, banco, tam_banco); int cliente = validarRango(0, getTotalClientes(banco,pais)-1, "\tIntroduce el indice del cliente: "); if(getIsOcupadoCliente(banco,pais,cliente)==true){ double cuanto; printf("\tIntroduce cuanto retirarรกs de tรบ cuenta: "); scanf("%lf",&cuanto); retirarSaldoCliente(banco, pais, cliente, cuanto); }else{ printf("\tEl cliente %i del pais %s no tiene datos.",cliente,banco[pais].nombrePais); } }else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } break; case BUSCAR_ID_VACIO_ESTRUCTURA: printf(" --- Opciรณn buscar id vacio en toda estructura ---\n"); if(hayVacioTodaEstructura(banco, tam_banco)==true){ Indices temp; temp = indiceVacioTodaEstructura(banco, tam_banco); printf("---------------------------------------------------------------------\n"); printf("\tEl pais [%d] %s tiene el cliente [%d] vacio\n",temp.pais, banco[temp.pais].nombrePais, temp.cliente); printf("---------------------------------------------------------------------\n"); }else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta completamente llena.\n"); printf("---------------------------------------------------------------------\n"); } break; case ESTA_LLENA_ESTRUCTURA: printf(" --- Opciรณn esta llena toda la estructura ---\n"); if(estaTodoLlenoEstructura(banco, tam_banco)==true) { printf("---------------------------------------------------------------------\n"); printf("\ttrue, la estructura esta toda llena.\n"); printf("---------------------------------------------------------------------\n"); }else { printf("---------------------------------------------------------------------\n"); printf("\tfalse, la estructura no esta toda llena.\n"); printf("---------------------------------------------------------------------\n"); } break; case ESTA_VACIA_ESTRUCTURA: printf(" --- Opciรณn esta vacia toda la estructura ---\n"); if(estaTodoVacioEstructura(banco, tam_banco)==false){ printf("---------------------------------------------------------------------\n"); printf("\ttrue, la estructura esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); }else { printf("---------------------------------------------------------------------\n"); printf("\tfalse, la estructura no esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } break; case IMPRIMIR_NOM_PAISES: printf(" --- Opciรณn imprimir nombre de paises ---\n"); imprimirPaises(banco, tam_banco); break; case ACTUALIZAR: printf(" --- Opciรณn actualizar ---\n"); if(estaTodoVacioEstructura(banco, tam_banco)==false){ char nombre_pais[20]; //PEDIRNOMBREPAIS strcpy(nombre_pais,nombrePais(tam_banco,banco)); int pais = getIndicePais(nombre_pais, banco, tam_banco); int cliente = validarRango(0, getTotalClientes(banco,pais)-1, "\tIntroduce el indice del cliente: "); if(getIsOcupadoCliente(banco,pais,cliente)==true){ instrucciones_actualizar(); printf(" Elija una opciรณn: "); scanf("%d",&eleccion); while(eleccion != SALIR_ACTUALIZAR) { switch (eleccion) { case ACTUALIZAR_NOMBRE: printf(" --- Opciรณn actualizar nombre ---\n"); char nuevoNombre[20]; strcpy(nuevoNombre,nombreCliente()); cambiarNombreCliente(banco,pais,cliente,nuevoNombre); printf("-----------------------------------------------------------------\n"); printCliente(banco, pais,cliente); printf("-----------------------------------------------------------------\n"); break; case ACTUALIZAR_SEXO: printf(" --- Opciรณn actualizar sexo ---\n"); char nuevoSexo; printf("Introduce el nuevo Sexo: "); fflush(stdin); scanf("%s",&nuevoSexo); cambiarSexoCliente(banco,pais,cliente,nuevoSexo); printf("-----------------------------------------------------------------\n"); printCliente(banco, pais,cliente); printf("-----------------------------------------------------------------\n"); break; case ACTUALIZAR_MOSTRAR_MENU: instrucciones_actualizar(); break; default: printf("******************************************\n"); printf(" --- Opciรณn Desconocida ---\n"); printf("******************************************\n"); instrucciones_actualizar(); } printf(" Elija una opciรณn: "); scanf("%d",&eleccion); } instrucciones(); }else{ printf("\tEl cliente %i del pais %s no tiene datos.",cliente,banco[pais].nombrePais); } }else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } break; case MOSTRAR_LONGITUDES: printf(" --- Opciรณn mostrar longitudes ---\n"); printf("---------------------------------------------------------------------\n"); mostrarLongitudes(banco,tam_banco); printf("---------------------------------------------------------------------\n"); break; case MOSTRAR_MENU_PRIN: instrucciones(); break; default: printf("******************************************\n"); printf(" --- Opciรณn Desconocida ---\n"); printf("******************************************\n"); instrucciones(); } instrucciones(); printf(" Elija una opciรณn: "); scanf("%d",&eleccion); } printf("--- Fin de la Ejecuciรณn del Sistema ---\n"); return 0; } <file_sep>/Banco/banco.c #include "banco.h" void instrucciones(){ printf("\n-------------------------------"); printf("---- Menu ----\n"); printf(" 0 Mostrar menu.\n"); printf(" 1 Dar de alta Cliente.\n"); printf(" 2 Dar de baja Cliente.\n"); printf(" 3 Mostrar todos los clientes.\n"); printf(" 4 Mostrar cliente en especifico.\n"); printf(" 5 Mostrar solo clientes dados de alta.\n"); printf(" 6 Abonar saldo a cliente.\n"); printf(" 7 Retirar saldo de cliente.\n"); printf(" 8 Buscar indice vacio en toda la estructura.\n"); printf(" 9 Mostrar si esta toda llena la estructura.\n"); printf(" 10 Mostrar si esta toda vacia la estructura.\n"); printf(" 11 Mostrar nombre de paises.\n"); printf(" 12 Mostrar longitudes.\n"); printf(" 13 Actualizar datos de cliente especifico.\n"); printf(" 14 Salir.\n"); printf("-------------------------------"); } void saltoLinea(){ printf("\n"); } int validarRango(int inicio, int fin, char *mensaje){ printf("%s",mensaje); int numero; scanf("%d",&numero); while(numero < inicio || numero > fin){ if(numero < inicio || numero > fin){ printf("\t\tNo esta dentro del Rango...\n"); printf("\t\t\t--> El rango va de %d a % d\n",inicio,fin); } puts(mensaje); scanf("%d",&numero); } return numero; } bool estaNombreRepetido(int tam_banco, char *nombrePais, Banco banco[]){ bool se_encuentra; int i; for(i = 0; i < tam_banco ; i++){ //Se comparan las cadenas para saber si son las mismas if( strcasecmp(banco[i].nombrePais,nombrePais) == 0 ){ se_encuentra = true; break; }else{ se_encuentra = false; } } return se_encuentra; } char *nombrePaisR(int tam_banco, Banco banco[]){ bool bandera; char nombrePais[20]; char* cadena = malloc(20); do{ printf("\nIntroduce el nombre del Paรญs\t"); memset(nombrePais,'\0',20); scanf("%s",nombrePais); bandera=estaNombreRepetido(tam_banco, nombrePais, banco); if(bandera==true){ printf("\t\tEl nombre %s ya se encuentra registrado...\n",nombrePais); printf("\t\t\t--> Intenta de nuevo.\n"); } }while(bandera==true); strcpy(cadena,nombrePais); return cadena; } char *nombrePais(int tam_banco, Banco banco[]){ char nombrePais[20]; char* cadena = malloc(20); bool bandera; do{ printf("\nIntroduce el nombre del Paรญs\t"); memset(nombrePais,'\0',20); scanf("%s",nombrePais); bandera=estaNombreRepetido(tam_banco, nombrePais, banco); if(bandera==false){ printf("\t\tEl nombre %s no se encuentra registrado...\n",nombrePais); printf("\t\t\t--> Intenta de nuevo.\n"); } }while(bandera==false); strcpy(cadena,nombrePais); return cadena; } void introducirPaises(Banco banco[], int tam_banco){ int i,tam_cliente; for(i = 0; i < tam_banco; i++){ strcpy(banco[i].nombrePais,nombrePaisR(tam_banco,banco)); tam_cliente=validarRango(1, LIMITE_CLIENTES, "\tIntroduce el total de clientes\t"); banco[i].clientes[tam_cliente]; banco[i].num_clientes=tam_cliente; } } void mostrarLongitudes(Banco banco[],int tam_banco){ int i; for(i=0;i<tam_banco;i++){ printf("--> Del Pais %s ------existen %d clientes.\n",banco[i].nombrePais,banco[i].num_clientes); } } bool getIsOcupadoCliente(Banco banco[],int indice_pais,int index){ bool ocupado=false; if(banco[indice_pais].clientes[index].ocupado != true){ ocupado=false; }else{ ocupado=true; } return ocupado; } int getTotalClientes(Banco banco[], int posicion){ return banco[posicion].num_clientes; } bool isTodoOcupado(Banco banco[], int indice_pais){ bool todo_ocupado = false; int contador = 0,i; for(i = 0; i < getTotalClientes(banco, indice_pais) ; i++){ if(getIsOcupadoCliente(banco,indice_pais,i)){ contador++; } } if(contador == getTotalClientes(banco,indice_pais)){ todo_ocupado = true; } return todo_ocupado; } bool hayVacioTodaEstructura(Banco banco[], int tam_banco){ bool hayLugar = false; int i; for(i=0;i<tam_banco;i++){ bool ocupado=isTodoOcupado(banco,i); if (ocupado==false) { hayLugar = true; } } return hayLugar; } int getIndicePais(char *nombrePais, Banco banco[], int tam_banco){ int indexPais; int i; for(i = 0; i < tam_banco; i++){ if(strcasecmp(banco[i].nombrePais,nombrePais)){ indexPais = i; break; } } return indexPais; } int indiceVacio(Banco banco[], int pais){ int index_vacio=-1; int i; for(i = 0; i < getTotalClientes(banco,pais) ; i++){ if(getIsOcupadoCliente(banco,pais,i)==false){ index_vacio = i; break; } } return index_vacio; } int indiceVacioPaisEspecifico(int pais, Banco banco[]){ int index_vacio=-1; index_vacio=indiceVacio(banco, pais); return index_vacio; } char *nombreCliente(){ char nombreCliente[20]; char* cadena = malloc(20); printf("\nIntroduce el nombre del cliente\t"); memset(nombreCliente,'\0',20); scanf("%s",nombreCliente); strcpy(cadena,nombreCliente); return cadena; } void eliminarCliente(Banco banco[],int pais,int index){ strcpy(banco[pais].clientes[index].nombre," "); banco[pais].clientes[index].sexo=' '; banco[pais].clientes[index].saldo=0.0; banco[pais].clientes[index].ocupado=false; } bool existeEspacioOcupado(Banco banco[], int pais){ bool existeOcupado = false; int i; for(i = 0; i < getTotalClientes(banco, pais); i++){ if(getIsOcupadoCliente(banco,pais,i)==true){ existeOcupado = true; break; } } return existeOcupado; } bool estaTodoVacioEstructura(Banco banco[], int tam_banco){ bool all_vacio = true; int i; for (i=0; i<tam_banco;i++) { if (existeEspacioOcupado(banco,i)==true) { all_vacio = false; break; } } return all_vacio; } void imprimirTodo(Banco banco[], int tam_banco){ int i; for(i = 0; i < tam_banco; i++){ int j; for(j=0;j<getTotalClientes(banco, i);j++){ printf("----------------------------------------------------------------------------------------------------------------"); printf("\n\t---->Del pais %s",banco[i].nombrePais); printf("\n\t\tCliente[%i]",j); printf("\n\t\t\tNombre: %s",banco[i].clientes[j].nombre); printf("\n\t\t\tSexo: %c",banco[i].clientes[j].sexo); printf("\n\t\t\tSaldo: %lf",banco[i].clientes[j].saldo); } } printf("----------------------------------------------------------------------------------------------------------------"); } void imprimirEspecifico(Banco banco[],int pais,int cliente){ printf("----------------------------------------------------------------------------------------------------------------"); printf("\n\t---->Del pais %s: ",banco[pais].nombrePais); printf("\n\t\t\tNombre: %s",banco[pais].clientes[cliente].nombre); printf("\n\t\t\tSexo: %c",banco[pais].clientes[cliente].sexo); printf("\n\t\t\tSaldo: %lf",banco[pais].clientes[cliente].saldo); printf("----------------------------------------------------------------------------------------------------------------"); } bool printSoloOcupados(Banco banco[],int pais){ bool imprimio = false; if(existeEspacioOcupado(banco, pais)==true){ imprimio = true; printf("----------------------------------------------------------------------------------------------------------------"); printf("\tDel pais [%s] los clientes disponibles son:",banco[pais].nombrePais); int i; for(i = 0; i < getTotalClientes(banco,pais); i++){ if(getIsOcupadoCliente(banco,pais,i)){ printf("El cliente %d es: ",i); printf("\n\t\t\tNombre: %s",banco[pais].clientes[i].nombre); printf("\n\t\t\tSexo: %c",banco[pais].clientes[i].sexo); printf("\n\t\t\tSaldo: %lf",banco[pais].clientes[i].saldo); } } printf("----------------------------------------------------------------------------------------------------------------"); } return imprimio; } void imprimirSoloOcupados(Banco banco[], int tam_banco){ int contador = 0; int i; for(i = 0; i < tam_banco; i++){ if(printSoloOcupados(banco,i)) contador++; } if(contador == 0){ printf("\t\t ---> No existen clientes que mostrar..."); } } bool tieneDatos(Banco banco[], int pais, int indice){ bool tiene_Datos=false; if(strcasecmp(banco[pais].clientes[indice].nombre," ")==0 || banco[pais].clientes[indice].sexo==' '){ tiene_Datos=false; }else{ tiene_Datos=true; } return tiene_Datos; } void abonarSaldo(Banco banco[], int pais, int indice ,double cuanto){ if(tieneDatos(banco, pais,indice)==true) { if(cuanto > 0.0){ banco[pais].clientes[indice].saldo=banco[pais].clientes[indice].saldo+cuanto; } else{ printf("\tImposible, no puedes abonar saldos negativos o nada."); } } } void abonarSaldoCliente(Banco banco[], int pais, int index, double cuanto){ abonarSaldo(banco,pais,index,cuanto); } bool tieneSaldo(Banco banco[], int pais, int indice){ bool tiene_Saldo=false; if(banco[pais].clientes[indice].saldo > 0.0){ tiene_Saldo=true; }else{ tiene_Saldo=false; } return tiene_Saldo; } void retirarSaldo(Banco banco[], int pais, int indice,double cuanto){ if(tieneDatos(banco, pais,indice)==true) { if(cuanto > 0.0){ if(tieneSaldo(banco, pais, indice)==true){ if(banco[pais].clientes[indice].saldo >= cuanto){ banco[pais].clientes[indice].saldo= banco[pais].clientes[indice].saldo-cuanto; }else{ printf("\tImposible, tรบ saldo es insuficiente para retirar %f",cuanto); } } else{ printf("\tImposible, no hay saldo."); } } else{ printf("\tImposible, no puedes retirar saldos negativos o nada."); } } } void retirarSaldoCliente(Banco banco[], int pais, int index, double cuanto){ retirarSaldo(banco, pais, index, cuanto); } Indices indiceVacioTodaEstructura(Banco banco[],int tam_banco) { Indices temp;//new Indices(); temp.pais=-1; temp.cliente=-1; int i; for(i = 0; i < tam_banco; i++) { int indice; indice = indiceVacio(banco, i); if(indice != -1) { temp.pais = i; temp.cliente = indice; break; } } return temp; } bool existeEspacioVacio(Banco banco[], int pais){ bool existeVacio = false; int i; for(i = 0; i < banco[pais].num_clientes ; i++){ if(getIsOcupadoCliente(banco,pais, i)==true){ existeVacio = true; break; } } return existeVacio; } bool estaTodoLlenoEstructura(Banco banco[], int tam_banco){ bool all_lleno = true; int i; for (i=0;i<tam_banco;i++) { if (existeEspacioVacio(banco,i)==true) { all_lleno = false; break; } } return all_lleno; } void imprimirPaises(Banco banco[], int tam_banco){ printf("---------------------------------------------------------------------\n"); printf("\tLos paises son: \n"); int i; for(i = 0; i < tam_banco; i++){ printf("\t---->Paรญs [%s] ",banco[i].nombrePais); } printf("---------------------------------------------------------------------\n"); } void instrucciones_actualizar(){ printf("\n-------------------------------"); printf("---- Menรบ Actualizar ----\n"); printf(" 0 Mostrar menรบ.\n"); printf(" 1 Actualizar Nombre.\n"); printf(" 2 Actualizar Sexo.\n"); printf(" 3 Regresar a mรฉnu principal.\n"); printf("-------------------------------"); } void setTodosDatos(Banco banco[],int pais, int indice){ strcpy(banco[pais].clientes[indice].nombre, " "); banco[pais].clientes[indice].sexo = ' '; banco[pais].clientes[indice].saldo = 0.0; banco[pais].clientes[indice].ocupado = false; } void setOcupado(Banco banco[], int pais, int indice) { if(tieneDatos(banco, pais,indice)==false){ setTodosDatos(banco, pais, indice); } else{ banco[pais].clientes[indice].ocupado = true; } } void cambiarNombre(Banco banco[], int pais, int indice, char nuevoNombre[20]){ /*Si primer cadena > a segunda resultado es mayor a 0 Si primer cadena > a segunda resultado es menor a 0 Si cadenas iguales resultado 0*/ if(strcasecmp(nuevoNombre," ")>0){ strcpy(banco[pais].clientes[indice].nombre,nuevoNombre); } setOcupado(banco, pais, indice); } void cambiarNombreCliente(Banco banco[], int pais, int index, char nuevoNombre[20]){ cambiarNombre(banco,pais, index,nuevoNombre); } void printCliente(Banco banco[], int pais,int index){ printf("-->Nombre: %s\n",banco[pais].clientes[index].nombre); printf("-->Sexo: %c\n",banco[pais].clientes[index].sexo); printf("-->Saldo: %f\n",banco[pais].clientes[index].saldo); } void cambiarSexo(Banco banco[], int pais, int indice, char sexo){ if(sexo == 'M' || sexo == 'F'){ banco[pais].clientes[indice].sexo = sexo; } setOcupado(banco, pais, indice); } void cambiarSexoCliente(Banco banco[], int pais, int index, char nuevoSexo){ cambiarSexo(banco, pais, index, nuevoSexo); } <file_sep>/POSIX_Threads/version_1/README.md #Creacion de hilos en lenguaje C POSIX <file_sep>/Examen/ejercicio1.c #include <stdio.h> int main(){ char x; char *p; char y; char *puntero; x='x'; p=&x; //printf("\nDireccion de memoria: %p",&x); printf("\nEL contenido del puntero p es: %c",*p); p++; printf("\nEL contenido del puntero p+1 es: %c",*p); p+=2; printf("\nEL contenido del puntero p+2 es: %c",*p); y='y'; puntero=&y; printf("\nEL contenido del puntero puntero es: %c\n",*puntero); return 0; } <file_sep>/POSIX_Threads/version_1/main.c #include "scheduler.h" void reproducir_musica(void); void abrir_youtube(void); void escribir_texto_word(void); void descargar_archivo(void); void subiendo_archivo(void); void compilando_programa(void); void ejecutando_programa(void); void usando_terminal(void); int main(int argc, char const *argv[]){ //Creacion de llamadas al hilo pthread_t h1; pthread_t h2; pthread_t h3; pthread_t h4; pthread_t h5; pthread_t h6; pthread_t h7; pthread_t h8; pthread_t h9; process p1 = {1, UN_SEGUNDO, "Proceso_1", reproducir_musica, ACTIVO}; //<-- process p2 = {1, DOS_SEGUNDOS, "Proceso_1", abrir_youtube, NO_ACTIVO}; process p3 = {3, TRES_SEGUNDOS, "Proceso_2", escribir_texto_word, ACTIVO}; //<-- process p4 = {4, TRES_SEGUNDOS, "Proceso_3", descargar_archivo, ACTIVO}; //<-- process p5 = {3, TRES_SEGUNDOS, "Proceso_4", subiendo_archivo, ACTIVO}; process p6 = {4, TRES_SEGUNDOS, "Proceso_5", compilando_programa, NO_ACTIVO}; process p7 = {0, TRES_SEGUNDOS, "Proceso_6", ejecutando_programa, ACTIVO}; //<-- process p8 = {2, CUATRO_SEGUNDOS, "Proceso_7", usando_terminal, ACTIVO}; //<-- process p9 = {5, CUATRO_SEGUNDOS, "Proceso_8", usando_terminal, NO_ACTIVO}; //<-- //Crear hilo pthread_create(&h1,NULL,(void *)crear_Proceso,&p1); pthread_create(&h2,NULL,(void *)crear_Proceso,&p2); pthread_create(&h3,NULL,(void *)crear_Proceso,&p3); pthread_create(&h4,NULL,(void *)crear_Proceso,&p4); pthread_create(&h5,NULL,(void *)crear_Proceso,&p5); pthread_create(&h6,NULL,(void *)crear_Proceso,&p6); pthread_create(&h7,NULL,(void *)crear_Proceso,&p7); pthread_create(&h8,NULL,(void *)crear_Proceso,&p8); pthread_create(&h9,NULL,(void *)crear_Proceso,&p9); //Ejecutar hilo pthread_join(h1,NULL); pthread_join(h2,NULL); pthread_join(h3,NULL); pthread_join(h4,NULL); pthread_join(h5,NULL); pthread_join(h6,NULL); pthread_join(h7,NULL); pthread_join(h8,NULL); pthread_join(h9,NULL); array_procesos *array = crear_ArrayProcesos(); agregar_Proceso(array, p1); agregar_Proceso(array, p2); agregar_Proceso(array, p3); agregar_Proceso(array, p4); agregar_Proceso(array, p5); agregar_Proceso(array, p6); agregar_Proceso(array, p7); agregar_Proceso(array, p8); agregar_Proceso(array, p9); ejecutar_Procesos(array); free(array); /*free(p1); free(p2); free(p3); free(p4); free(p5); free(p6); free(p7); free(p8); free(p9);*/ return 0; } void reproducir_musica(void){ printf("Reproduciendo Mรบsica\n"); } void abrir_youtube(void){ printf("Usando Youtube\n"); } void escribir_texto_word(void){ printf("Escribiendo Texto en Word\n"); } void descargar_archivo(void){ printf("Descargando Archivo\n"); } void subiendo_archivo(void){ printf("Subiendo Archivo\n"); } void compilando_programa(void){ printf("Compilando programa\n"); } void ejecutando_programa(void){ printf("Ejecutando programa\n"); } void usando_terminal(void){ printf("Usando la terminal\n"); } <file_sep>/Scheduler/main.c #include "scheduler.h" int main(){ //Datos iniciales int num_proc=num_procesos(); int time_ejec=quantum(); //Lenado de las estrcturas de procesos Proceso *proc; Proceso vproc[num_proc]; llenar_estructura(vproc,proc,num_proc); //Tabla de procesos entrada imprimir(vproc,num_proc); //Ejecucion multiprogramacion (Round Robin) printf("\t\t EJECUCION DE PROCESOS\n"); printf("Nombre del proceso |\tTiempo\t|\tEstado\t|\n"); round_robin(vproc,time_ejec,num_proc); return 0; } <file_sep>/Scheduler/scheduler.h #ifndef __scheduler #define __scheduler #include <stdio.h> #include <stdlib.h> //Para usar variables tipo boolean #include <string.h> #include <stdbool.h> #define TAM_TEXTO 50 typedef struct { char nombre[TAM_TEXTO]; int tiempo; char estado[TAM_TEXTO]; }Proceso; int num_procesos(); int quantum(); Proceso *llenar_proceso(char *nombre, int tiempo); void imprimir(Proceso vproc[], int num_proc); void agregar(Proceso vproc[],Proceso *proc,int posicion); void llenar_estructura(Proceso vproc[],Proceso *proc,int num_proc); bool vector_finalizado(Proceso vproc[],int num_proc); void imprimir_posicion(Proceso vproc[], int posicion); void round_robin(Proceso vproc[], int time_ejec,int num_proc); #endif <file_sep>/Sys_Banco/Banco_Sys.c #include <stdbool.h> #include <stdio.h> #include <string.h> #include <stdlib.h> //#include <malloc.h> #define MOSTRAR_MENU_PRIN 0 #define LIMITE_PAISES 5 #define LIMITE_CLIENTES 10 #define ALTA 1 #define BAJA 2 #define MOSTRAR_TODO 3 #define MOSTRAR_ESPECIFICO 4 #define MOSTRAR_OCUPADOS 5 #define ABONAR 6 #define RETIRAR 7 #define BUSCAR_ID_VACIO_ESTRUCTURA 8 #define ESTA_LLENA_ESTRUCTURA 9 #define ESTA_VACIA_ESTRUCTURA 10 #define IMPRIMIR_NOM_PAISES 11 #define MOSTRAR_LONGITUDES 12 #define ACTUALIZAR 13 #define SALIR 14 #define ACTUALIZAR_MOSTRAR_MENU 0 #define ACTUALIZAR_NOMBRE 1 #define ACTUALIZAR_SEXO 2 #define SALIR_ACTUALIZAR 3 typedef struct { char nombre[20]; char sexo; double saldo; bool ocupado; }Cliente; typedef struct { char nombrePais[20]; int num_clientes; Cliente clientes[]; }Banco; void instrucciones(){ printf("\n-------------------------------"); printf("---- Menu ----\n"); printf(" 0 Mostrar menu.\n"); printf(" 1 Dar de alta Cliente.\n"); printf(" 2 Dar de baja Cliente.\n"); printf(" 3 Mostrar todos los clientes.\n"); printf(" 4 Mostrar cliente en especifico.\n"); printf(" 5 Mostrar solo clientes dados de alta.\n"); printf(" 6 Abonar saldo a cliente.\n"); printf(" 7 Retirar saldo de cliente.\n"); printf(" 8 Buscar indice vacio en toda la estructura.\n"); printf(" 9 Mostrar si esta toda llena la estructura.\n"); printf(" 10 Mostrar si esta toda vacia la estructura.\n"); printf(" 11 Mostrar nombre de paises.\n"); printf(" 12 Mostrar longitudes.\n"); printf(" 13 Actualizar datos de cliente especifico.\n"); printf(" 14 Salir.\n"); printf("-------------------------------"); } void saltoLinea(){ printf("\n"); } int validarRango(int inicio, int fin, char mensaje[100]){ puts(mensaje); int numero; scanf("%d",&numero); while(numero < inicio || numero > fin){ if(numero < inicio || numero > fin){ printf("\t\tNo esta dentro del Rango...\n"); printf("\t\t\t--> El rango va de %d a % d\n",inicio,fin); } puts(mensaje); scanf("%d",&numero); } return numero; } bool estaNombreRepetido(int inicio, char nombrePais[20], Banco banco[]){ bool se_encuentra = false; int i; for(i = inicio; i > 0; i--){ if(strcasecmp(banco[i-1].nombrePais,nombrePais)==0){ se_encuentra = true; //break; } } return se_encuentra; } void introducirPaises(Banco banco[], int tam_banco){ int i; int tam_cliente; for(i = 0; i < tam_banco; i++){ printf("Introduce el nombre del Paรญs [%d] ",i); char *mensaje;//="Introduce el nombre del Paรญs [%d]",i; char nombrePais[20]; fflush(stdin); fgets(nombrePais,20,stdin); int inicio=i; while(estaNombreRepetido(inicio, nombrePais, banco)){//mientras exista if(estaNombreRepetido(inicio, nombrePais, banco)){ printf("\t\tEl nombre %s ya se encuentra registrado...\n",nombrePais); printf("\t\t\t--> Intenta de nuevo.\n"); } printf("Introduce el nombre del Paรญs [%d] ",i); fflush(stdin); fgets(nombrePais,20,stdin); } mensaje= "\tIntroduce el total de clientes del pais %s : ",nombrePais; strcpy(banco[i].nombrePais,nombrePais); tam_cliente=validarRango(1, LIMITE_CLIENTES, mensaje); banco[i].clientes[tam_cliente]; banco[i].num_clientes=tam_cliente; } } int getTotalClientes(Banco banco[], int posicion){ return banco[posicion].num_clientes; } bool getIsOcupadoCliente(Banco banco[],int indice_pais,int index){ bool ocupado=false; if(banco[indice_pais].clientes[index].ocupado != true){ ocupado=false; }else{ ocupado=true; } return ocupado; } bool isTodoOcupado(Banco banco[], int indice_pais){ bool todo_ocupado = false; int contador = 0; int i; for(i = 0; i < getTotalClientes(banco, indice_pais) ; i++){ if(getIsOcupadoCliente(banco,indice_pais,i)){ contador++; } } if(contador ==getTotalClientes(banco,indice_pais)){ todo_ocupado = true; } return todo_ocupado; } bool hayVacioTodaEstructura(Banco banco[], int tam_banco){ bool hayLugar = false; //for(Banco item : banco) { int j; for(j=0;j<tam_banco;j++){ //if(banco[i].existeEspacioVacio()) { // funciona tambiรฉn. if (isTodoOcupado(banco,j)==false) { hayLugar = true; // break; } } return hayLugar; } void mostrarLongitudes(Banco banco[],int tam_banco){ int i; for(i=0;i<tam_banco;i++){ printf("--> Del Pais %s ------existen %d clientes.\n",banco[i].nombrePais,banco[i].num_clientes); } } int getIndicePais(char nombrePais[20], Banco banco[], int tam_banco){ int indexPais = -1; int i; for(i = 0; i < tam_banco; i++){ // if(strcasecmp(banco[i].nombrePais,nombrePais)){ indexPais = i; // } //if(banco[i].getNombrePais().equalsIgnoreCase(nombrePais)){ // break; //} } return indexPais; } int indiceVacio(Banco banco[], int pais){ int index_vacio = -1; int i; for(i = 0; i < getTotalClientes(banco,pais) ; i++){ if(getIsOcupadoCliente(banco,pais,i)==false){ index_vacio = i; break; } } return index_vacio; } int indiceVacioPaisEspecifico(int pais, Banco banco[]){ int index_vacio; index_vacio=indiceVacio(banco, pais); return index_vacio; } bool existeEspacioOcupado(Banco banco[], int pais){ bool existeOcupado = false; int i; for(i = 0; i < getTotalClientes(banco, pais); i++){ if(getIsOcupadoCliente(banco,pais,i)==true){ existeOcupado = true; break; } } return existeOcupado; } bool estaTodoVacioEstructura(Banco banco[], int tam_banco){ bool all_vacio = true; int i; for (i=0; i<tam_banco;i++) { if (existeEspacioOcupado(banco,i)==true) { all_vacio = false; break; } } return all_vacio; } void eliminarCliente(Banco banco[],int pais,int index){ strcpy(banco[pais].clientes[index].nombre," "); banco[pais].clientes[index].sexo=' '; banco[pais].clientes[index].saldo=0.0; banco[pais].clientes[index].ocupado=false; } void imprimirTodo(Banco banco[], int tam_banco){ int i; for(i = 0; i < tam_banco; i++){ int j; for(j=0;j<getTotalClientes(banco, i);j++){ printf("----------------------------------------------------------------------------------------------------------------"); printf("\n\t---->Del pais %s",banco[i].nombrePais); printf("\n\t\tCliente[%i]",j); printf("\n\t\t\tNombre: %s",banco[i].clientes[j].nombre); printf("\n\t\t\tSexo: %c",banco[i].clientes[j].sexo); printf("\n\t\t\tSaldo: %s",banco[i].clientes[j].saldo); } } printf("----------------------------------------------------------------------------------------------------------------"); } void imprimirEspecifico(Banco banco[],int pais,int cliente){ printf("----------------------------------------------------------------------------------------------------------------"); printf("\n\t---->Del pais %s: ",banco[pais].nombrePais); printf("\n\t\t\tNombre: %s",banco[pais].clientes[cliente].nombre); printf("\n\t\t\tSexo: %c",banco[pais].clientes[cliente].sexo); printf("\n\t\t\tSaldo: %s",banco[pais].clientes[cliente].saldo); printf("----------------------------------------------------------------------------------------------------------------"); } bool printSoloOcupados(Banco banco[],int pais){ bool imprimio = false; if(existeEspacioOcupado(banco, pais)==true){ imprimio = true; printf("----------------------------------------------------------------------------------------------------------------"); printf("\tDel pais [%s] los clientes disponibles son:",banco[pais].nombrePais); int i; for(i = 0; i < getTotalClientes(banco,pais); i++){ if(getIsOcupadoCliente(banco,pais,i)){ printf("El cliente %d es: ",i); printf("\n\t\t\tNombre: %s",banco[pais].clientes[i].nombre); printf("\n\t\t\tSexo: %c",banco[pais].clientes[i].sexo); printf("\n\t\t\tSaldo: %s",banco[pais].clientes[i].saldo); } } printf("----------------------------------------------------------------------------------------------------------------"); } return imprimio; } void imprimirSoloOcupados(Banco banco[], int tam_banco){ int contador = 0; int i; for(i = 0; i < tam_banco; i++){ if(printSoloOcupados(banco,i)) contador++; } if(contador == 0){ printf("\t\t ---> No existen clientes que mostrar..."); } } bool tieneDatos(Banco banco[], int pais, int indice){ bool tiene_Datos=false; if(strcasecmp(banco[pais].clientes[indice].nombre," ")==0 || banco[pais].clientes[indice].sexo==' '){ tiene_Datos=false; }else{ tiene_Datos=true; } return tiene_Datos; } void abonarSaldo(Banco banco[], int pais, int indice ,double cuanto){ if(tieneDatos(banco, pais,indice)==true) { if(cuanto > 0.0){ banco[pais].clientes[indice].saldo=banco[pais].clientes[indice].saldo+cuanto; } else{ printf("\tImposible, no puedes abonar saldos negativos o nada."); } } } void abonarSaldoCliente(Banco banco[], int pais, int index, double cuanto){ abonarSaldo(banco,pais,index,cuanto); } bool tieneSaldo(Banco banco[], int pais, int indice){ bool tiene_Saldo=false; if(banco[pais].clientes[indice].saldo > 0.0){ tiene_Saldo=true; }else{ tiene_Saldo=false; } return tiene_Saldo; } void retirarSaldo(Banco banco[], int pais, int indice,double cuanto){ if(tieneDatos(banco, pais,indice)==true) { if(cuanto > 0.0){ if(tieneSaldo(banco, pais, indice)==true){ if(banco[pais].clientes[indice].saldo >= cuanto){ banco[pais].clientes[indice].saldo= banco[pais].clientes[indice].saldo-cuanto; }else{ printf("\tImposible, tรบ saldo es insuficiente para retirar %f",cuanto); } } else{ printf("\tImposible, no hay saldo."); } } else{ printf("\tImposible, no puedes retirar saldos negativos o nada."); } } } void retirarSaldoCliente(Banco banco[], int pais, int index, double cuanto){ retirarSaldo(banco, pais, index, cuanto); } typedef struct { int pais; int cliente; }Indices; Indices indiceVacioTodaEstructura(Banco banco[],int tam_banco) { Indices temp;//new Indices(); temp.pais=-1; temp.cliente=-1; int i; for(i = 0; i < tam_banco; i++) { int indice; indice = indiceVacio(banco, i); if(indice != -1) { temp.pais = i; temp.cliente = indice; break; } } return temp; } bool existeEspacioVacio(Banco banco[], int pais){ bool existeVacio = false; int i; for(i = 0; i < banco[pais].num_clientes ; i++){ if(getIsOcupadoCliente(banco,pais, i)==true){ existeVacio = true; break; } } return existeVacio; } bool estaTodoLlenoEstructura(Banco banco[], int tam_banco){ bool all_lleno = true; int i; for (i=0;i<tam_banco;i++) { if (existeEspacioVacio(banco,i)==true) { all_lleno = false; break; } } return all_lleno; } void imprimirPaises(Banco banco[], int tam_banco){ printf("---------------------------------------------------------------------\n"); printf("\tLos paises son: \n"); int i; for(i = 0; i < tam_banco; i++){ printf("\t---->Paรญs [%s] ",banco[i].nombrePais); } printf("---------------------------------------------------------------------\n"); } void instrucciones_actualizar(){ printf("\n-------------------------------"); printf("---- Menรบ Actualizar ----\n"); printf(" 0 Mostrar menรบ.\n"); printf(" 1 Actualizar Nombre.\n"); printf(" 2 Actualizar Sexo.\n"); printf(" 3 Regresar a mรฉnu principal.\n"); printf("-------------------------------"); } void setTodosDatos(Banco banco[],int pais, int indice){ strcpy(banco[pais].clientes[indice].nombre, " "); banco[pais].clientes[indice].sexo = ' '; banco[pais].clientes[indice].saldo = 0.0; banco[pais].clientes[indice].ocupado = false; } void setOcupado(Banco banco[], int pais, int indice) { if(tieneDatos(banco, pais,indice)==false){ setTodosDatos(banco, pais, indice); } else{ banco[pais].clientes[indice].ocupado = true; } } void cambiarNombre(Banco banco[], int pais, int indice, char nuevoNombre[20]){ /*Si primer cadena > a segunda resultado es mayor a 0 Si primer cadena > a segunda resultado es menor a 0 Si cadenas iguales resultado 0*/ if(strcasecmp(nuevoNombre," ")>0){ strcpy(banco[pais].clientes[indice].nombre,nuevoNombre); } setOcupado(banco, pais, indice); } void cambiarNombreCliente(Banco banco[], int pais, int index, char nuevoNombre[20]){ cambiarNombre(banco,pais, index,nuevoNombre); } void printCliente(Banco banco[], int pais,int index){ printf("-->Nombre: %s\n",banco[pais].clientes[index].nombre); printf("-->Sexo: %c\n",banco[pais].clientes[index].sexo); printf("-->Saldo: %f\n",banco[pais].clientes[index].saldo); } void cambiarSexo(Banco banco[], int pais, int indice, char sexo){ if(sexo == 'M' || sexo == 'F'){ banco[pais].clientes[indice].sexo = sexo; } setOcupado(banco, pais, indice); } void cambiarSexoCliente(Banco banco[], int pais, int index, char nuevoSexo){ cambiarSexo(banco, pais, index, nuevoSexo); } int main(){ int eleccion; int tam_banco; tam_banco=validarRango(1,LIMITE_PAISES,"Introduce el nรบmero de paises: "); Banco banco[tam_banco]; introducirPaises(banco, tam_banco); //int l;for(l=0;l<tam_banco;l++){ puts(banco[l].nombrePais); } //Revision de llenado nombrePais mostrarLongitudes(banco,tam_banco); saltoLinea(); instrucciones(); printf("\n Elija una opcion: "); scanf("%d",&eleccion); while(eleccion != SALIR){ switch(eleccion){ case ALTA: /*printf(" "); int op=1; do{*/ printf(" --- Opcion alta ---\n"); if(hayVacioTodaEstructura(banco, tam_banco)==true){ char nombre_pais[20]; //PEDIRNOMBREPAIS // printf("\tIntroduce el nombre del pais: "); //fflush(stdin); //gets(nombre_pais); //bool seEncuentraNombre(char nombrePais[20], Banco banco[], int tam_banco){ bool se_encuentra = 0; do{ printf("\tIntroduce el nombre del pais: "); fflush(stdin); //gets(nombre_pais); fgets(nombre_pais,20,stdin); int i; for (i=0;i<tam_banco;i++) { if(strcasecmp(banco[i].nombrePais,nombre_pais)==0){ //printf("%s\n",banco[i].nombrePais); se_encuentra = true; } } if(se_encuentra==false){ printf("\t\tEl nombre %s no se encuentra registrado...\n",nombre_pais); printf("\t\t\t--> Intenta de nuevo.\n"); } }while(se_encuentra==false); int id_pais; id_pais = getIndicePais(nombre_pais, banco, tam_banco); //printf("%d id pais\n ",id_pais);//verificar indice int cliente; cliente= indiceVacioPaisEspecifico(id_pais, banco); printf("%d ",cliente);//verificar indice if(cliente != -1){ char nombre_cliente[20]; char sexo; double saldo; printf("Introduce nombre del cliente: "); fflush(stdin); fgets(nombre_cliente,20,stdin); printf("\nIntroduce el Sexo: "); fflush(stdin); scanf("%c",&sexo); printf("\nIntroduce el Sueldo: "); scanf("%d",&saldo); //llenar datos strcpy(banco[id_pais].clientes[cliente].nombre,nombre_cliente); banco[id_pais].clientes[cliente].sexo=sexo; banco[id_pais].clientes[cliente].saldo=saldo; banco[id_pais].clientes[cliente].ocupado=true; } else printf("No existe indice vacio en el pais %s",banco[id_pais].nombrePais); } else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta completamente llena.\n"); printf("---------------------------------------------------------------------\n"); //op=2; } /*if(op==1){ printf("\n\t Desea dar de alta a otro cliente"); printf("\n\t1.-Si\t2.-No\t"); scanf("%d",&op); } }while(op==1); */ break; case BAJA: printf(" --- Opciรณn baja ---\n"); if(estaTodoVacioEstructura(banco, tam_banco)==false){ char nombre_pais[20]; //PEDIRNOMBREPAIS bool se_encuentra = 0; do{ printf("\tIntroduce el nombre del pais: "); fflush(stdin); //gets(nombre_pais); fgets(nombre_pais,20,stdin); int i; for (i=0;i<tam_banco;i++) { if(strcasecmp(banco[i].nombrePais,nombre_pais)==0){ //printf("%s\n",banco[i].nombrePais); se_encuentra = true; } } if(se_encuentra==false){ printf("\t\tEl nombre %s no se encuentra registrado...\n",nombre_pais); printf("\t\t\t--> Intenta de nuevo.\n"); } }while(se_encuentra==false); int pais; pais = getIndicePais(nombre_pais, banco, tam_banco); int cliente; cliente =validarRango(0, getTotalClientes(banco,pais)-1, "\tIntroduce el indice del cliente: "); if(getIsOcupadoCliente(banco,pais,cliente)==true){ printf("\t--> Cliente %s dado de baja.",banco[pais].clientes[cliente].nombre); eliminarCliente(banco,pais,cliente); } else printf("\tEl cliente %i del pais %s no tiene datos.",cliente,banco[pais].nombrePais); } else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } break; case MOSTRAR_TODO: printf(" --- Opciรณn mostrar todo ---\n"); imprimirTodo(banco,tam_banco); break; case MOSTRAR_ESPECIFICO: printf(" --- Opciรณn mostrar especifico ---\n"); if(estaTodoVacioEstructura(banco, tam_banco)==false){ char nombre_pais[20]; //PEDIRNOMBREPAIS bool se_encuentra = 0; do{ printf("\tIntroduce el nombre del pais: "); fflush(stdin); //gets(nombre_pais); fgets(nombre_pais,20,stdin); int i; for (i=0;i<tam_banco;i++) { if(strcasecmp(banco[i].nombrePais,nombre_pais)==0){ //printf("%s\n",banco[i].nombrePais); se_encuentra = true; } } if(se_encuentra==false){ printf("\t\tEl nombre %s no se encuentra registrado...\n",nombre_pais); printf("\t\t\t--> Intenta de nuevo.\n"); } }while(se_encuentra==false); int pais; pais= getIndicePais(nombre_pais, banco, tam_banco); int cliente; cliente = validarRango(0, getTotalClientes(banco,pais)-1, "\tIntroduce el indice del cliente: "); if(getIsOcupadoCliente(banco,pais,cliente)==true){ imprimirEspecifico(banco,pais,cliente); } else printf("\tEl cliente %i del pais %s no tiene datos.",cliente,banco[pais].nombrePais); } else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } break; case MOSTRAR_OCUPADOS: printf(" --- Opciรณn mostrar solo ocupados ---\n"); imprimirSoloOcupados(banco, tam_banco); break; case ABONAR: printf(" --- Opciรณn abonar ---\n"); if(estaTodoVacioEstructura(banco, tam_banco)==false){ char nombre_pais[20]; //PEDIRNOMBREPAIS bool se_encuentra = 0; do{ printf("\tIntroduce el nombre del pais: "); fflush(stdin); //gets(nombre_pais); fgets(nombre_pais,20,stdin); int i; for (i=0;i<tam_banco;i++) { if(strcasecmp(banco[i].nombrePais,nombre_pais)==0){ //printf("%s\n",banco[i].nombrePais); se_encuentra = true; } } if(se_encuentra==false){ printf("\t\tEl nombre %s no se encuentra registrado...\n",nombre_pais); printf("\t\t\t--> Intenta de nuevo.\n"); } }while(se_encuentra==false); int pais; pais = getIndicePais(nombre_pais, banco, tam_banco); int cliente; cliente = validarRango(0, getTotalClientes(banco,pais)-1, "\tIntroduce el indice del cliente: "); if(getIsOcupadoCliente(banco,pais,cliente)==true){ double cuanto; printf("\tIntroduce cuanto ingresarรกs a tรบ cuenta: "); scanf("%f",&cuanto); abonarSaldoCliente(banco, pais,cliente, cuanto); } else{ printf("\tEl cliente %i del pais %s no tiene datos.",cliente,banco[pais].nombrePais); } } else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } break; case RETIRAR: printf(" --- Opciรณn retirar ---\n"); if(estaTodoVacioEstructura(banco, tam_banco)==false){ char nombre_pais[20]; //PEDIRNOMBREPAIS bool se_encuentra = 0; do{ printf("\tIntroduce el nombre del pais: "); fflush(stdin); //gets(nombre_pais); fgets(nombre_pais,20,stdin); int i; for (i=0;i<tam_banco;i++) { if(strcasecmp(banco[i].nombrePais,nombre_pais)==0){ //printf("%s\n",banco[i].nombrePais); se_encuentra = true; } } if(se_encuentra==false){ printf("\t\tEl nombre %s no se encuentra registrado...\n",nombre_pais); printf("\t\t\t--> Intenta de nuevo.\n"); } }while(se_encuentra==false); int pais; pais = getIndicePais(nombre_pais, banco, tam_banco); int cliente; cliente = validarRango(0, getTotalClientes(banco,pais)-1, "\tIntroduce el indice del cliente: "); if(getIsOcupadoCliente(banco,pais,cliente)==true){ double cuanto; printf("\tIntroduce cuanto retirarรกs de tรบ cuenta: "); scanf("%d",&cuanto); retirarSaldoCliente(banco, pais, cliente, cuanto); } else printf("\tEl cliente %i del pais %s no tiene datos.",cliente,banco[pais].nombrePais); } else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } break; case BUSCAR_ID_VACIO_ESTRUCTURA: printf(" --- Opciรณn buscar id vacio en toda estructura ---\n"); if(hayVacioTodaEstructura(banco, tam_banco)==true){ Indices temp; temp = indiceVacioTodaEstructura(banco, tam_banco); printf("---------------------------------------------------------------------\n"); printf("\tEl pais [%d] %s tiene el cliente [%d] vacio\n",temp.pais, banco[temp.pais].nombrePais, temp.cliente); printf("---------------------------------------------------------------------\n"); } else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta completamente llena.\n"); printf("---------------------------------------------------------------------\n"); } break; case ESTA_LLENA_ESTRUCTURA: printf(" --- Opciรณn esta llena toda la estructura ---\n"); if(estaTodoLlenoEstructura(banco, tam_banco)==true) { printf("---------------------------------------------------------------------\n"); printf("\ttrue, la estructura esta toda llena.\n"); printf("---------------------------------------------------------------------\n"); } else { printf("---------------------------------------------------------------------\n"); printf("\tfalse, la estructura no esta toda llena.\n"); printf("---------------------------------------------------------------------\n"); } break; case ESTA_VACIA_ESTRUCTURA: printf(" --- Opciรณn esta vacia toda la estructura ---\n"); if(estaTodoVacioEstructura(banco, tam_banco)==false){ printf("---------------------------------------------------------------------\n"); printf("\ttrue, la estructura esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } else { printf("---------------------------------------------------------------------\n"); printf("\tfalse, la estructura no esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } break; case IMPRIMIR_NOM_PAISES: printf(" --- Opciรณn imprimir nombre de paises ---\n"); imprimirPaises(banco, tam_banco); break; case ACTUALIZAR: printf(" --- Opciรณn actualizar ---\n"); if(estaTodoVacioEstructura(banco, tam_banco)==false){ char nombre_pais[20]; //PEDIRNOMBREPAIS bool se_encuentra = 0; do{ printf("\tIntroduce el nombre del pais: "); fflush(stdin); //gets(nombre_pais); fgets(nombre_pais,20,stdin); int i; for (i=0;i<tam_banco;i++) { if(strcasecmp(banco[i].nombrePais,nombre_pais)==0){ //printf("%s\n",banco[i].nombrePais); se_encuentra = true; } } if(se_encuentra==false){ printf("\t\tEl nombre %s no se encuentra registrado...\n",nombre_pais); printf("\t\t\t--> Intenta de nuevo.\n"); } }while(se_encuentra==false); int pais; pais = getIndicePais(nombre_pais, banco, tam_banco); int cliente; cliente = validarRango(0, getTotalClientes(banco,pais)-1, "\tIntroduce el indice del cliente: "); if(getIsOcupadoCliente(banco,pais,cliente)==true){ instrucciones_actualizar(); printf(" Elija una opciรณn: "); scanf("%d",&eleccion); while(eleccion != SALIR_ACTUALIZAR) { switch (eleccion) { case ACTUALIZAR_NOMBRE: printf(" --- Opciรณn actualizar nombre ---\n"); char nuevoNombre[20]; printf("Introduce nuevo nombre del cliente: "); fflush(stdin); fgets(nuevoNombre,20,stdin); cambiarNombreCliente(banco,pais,cliente,nuevoNombre); printf("-----------------------------------------------------------------\n"); printCliente(banco, pais,cliente); printf("-----------------------------------------------------------------\n"); break; case ACTUALIZAR_SEXO: printf(" --- Opciรณn actualizar sexo ---\n"); char nuevoSexo; printf("Introduce el nuevo Sexo: "); fflush(stdin); scanf("%c",nuevoSexo); cambiarSexoCliente(banco,pais,cliente,nuevoSexo); printf("-----------------------------------------------------------------\n"); printCliente(banco, pais,cliente); printf("-----------------------------------------------------------------\n"); break; case ACTUALIZAR_MOSTRAR_MENU: instrucciones_actualizar(); break; default: printf("******************************************\n"); printf(" --- Opciรณn Desconocida ---\n"); printf("******************************************\n"); instrucciones_actualizar(); } printf(" Elija una opciรณn: "); scanf("%d",&eleccion); } instrucciones(); } else{ printf("\tEl cliente %i del pais %s no tiene datos.",cliente,banco[pais].nombrePais); } } else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } break; case MOSTRAR_LONGITUDES: printf(" --- Opciรณn mostrar longitudes ---\n"); printf("---------------------------------------------------------------------\n"); mostrarLongitudes(banco,tam_banco); printf("---------------------------------------------------------------------\n"); break; case MOSTRAR_MENU_PRIN: instrucciones(); break; default: printf("******************************************\n"); printf(" --- Opciรณn Desconocida ---\n"); printf("******************************************\n"); instrucciones(); } printf(" Elija una opciรณn: "); scanf("%d",&eleccion); } printf("--- Fin de la Ejecuciรณn del Sistema ---\n"); return 0; } <file_sep>/Banco/banco.h #ifndef __banco #define __banco #include <stdbool.h> #include <stdio.h> #include <string.h> #include <stdlib.h> //#include <malloc.h> #define MOSTRAR_MENU_PRIN 0 #define LIMITE_PAISES 5 #define LIMITE_CLIENTES 10 #define ALTA 1 #define BAJA 2 #define MOSTRAR_TODO 3 #define MOSTRAR_ESPECIFICO 4 #define MOSTRAR_OCUPADOS 5 #define ABONAR 6 #define RETIRAR 7 #define BUSCAR_ID_VACIO_ESTRUCTURA 8 #define ESTA_LLENA_ESTRUCTURA 9 #define ESTA_VACIA_ESTRUCTURA 10 #define IMPRIMIR_NOM_PAISES 11 #define MOSTRAR_LONGITUDES 12 #define ACTUALIZAR 13 #define SALIR 14 #define ACTUALIZAR_MOSTRAR_MENU 0 #define ACTUALIZAR_NOMBRE 1 #define ACTUALIZAR_SEXO 2 #define SALIR_ACTUALIZAR 3 typedef struct { char nombre[20]; char sexo; double saldo; bool ocupado; }Cliente; typedef struct { char nombrePais[20]; int num_clientes; Cliente clientes[]; }Banco; typedef struct { int pais; int cliente; }Indices; void instrucciones(); void saltoLinea(); int validarRango(int inicio, int fin, char *mensaje); bool estaNombreRepetido(int tam_banco, char *nombrePais, Banco banco[]); char *nombrePaisR(int tam_banco, Banco banco[]); char *nombrePais(int tam_banco, Banco banco[]); void introducirPaises(Banco banco[], int tam_banco); void mostrarLongitudes(Banco banco[],int tam_banco); bool getIsOcupadoCliente(Banco banco[],int indice_pais,int index); int getTotalClientes(Banco banco[], int posicion); bool isTodoOcupado(Banco banco[], int indice_pais); bool hayVacioTodaEstructura(Banco banco[], int tam_banco); int getIndicePais(char *nombrePais, Banco banco[], int tam_banco); int indiceVacio(Banco banco[], int pais); int indiceVacioPaisEspecifico(int pais, Banco banco[]); char *nombreCliente(); void eliminarCliente(Banco banco[],int pais,int index); bool existeEspacioOcupado(Banco banco[], int pais); bool estaTodoVacioEstructura(Banco banco[], int tam_banco); void imprimirTodo(Banco banco[], int tam_banco); void imprimirEspecifico(Banco banco[],int pais,int cliente); bool printSoloOcupados(Banco banco[],int pais); void imprimirSoloOcupados(Banco banco[], int tam_banco); bool tieneDatos(Banco banco[], int pais, int indice); void abonarSaldo(Banco banco[], int pais, int indice ,double cuanto); void abonarSaldoCliente(Banco banco[], int pais, int index, double cuanto); bool tieneSaldo(Banco banco[], int pais, int indice); void retirarSaldo(Banco banco[], int pais, int indice,double cuanto); void retirarSaldoCliente(Banco banco[], int pais, int index, double cuanto); Indices indiceVacioTodaEstructura(Banco banco[],int tam_banco); bool existeEspacioVacio(Banco banco[], int pais); bool estaTodoLlenoEstructura(Banco banco[], int tam_banco); void imprimirPaises(Banco banco[], int tam_banco); void instrucciones_actualizar(); void setTodosDatos(Banco banco[],int pais, int indice); void setOcupado(Banco banco[], int pais, int indice); void cambiarNombre(Banco banco[], int pais, int indice, char nuevoNombre[20]); void cambiarNombreCliente(Banco banco[], int pais, int index, char nuevoNombre[20]); void printCliente(Banco banco[], int pais,int index); void cambiarSexo(Banco banco[], int pais, int indice, char sexo); void cambiarSexoCliente(Banco banco[], int pais, int index, char nuevoSexo); #endif <file_sep>/Banco/Makefile all: gcc -g -c -Wall main.c -o main.o gcc -g -c -Wall banco.c -o banco.o gcc -g -Wall main.o banco.o -o application clean: rm *.o rm application
e7dbcc8219e944473ea37fb136767cd61b840df7
[ "Markdown", "C", "Makefile", "Shell" ]
17
C
EmanuelLP/Jose_Emanuel_Lopez_Paez_IC_602_Taller_SO
a24d14a58f61405230487962ea5539214a15a9dc
dd5a2ea89037eef1626770401ceb5af1cc37f325
refs/heads/master
<file_sep>๏ปฟusing System; using System.Collections; using System.Configuration; using System.Data; using System.Text; using System.IO; using System.Xml; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.Services; using it.itryframework.managers.mail; using System.Text.RegularExpressions; using it.aquest.baseobjects; public partial class Ajax : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static string getContentSection(string lang, string type, string view ) { Page page = new System.Web.UI.Page(); Control c = (Control)page.LoadControl("~/ascx/" + type + "/" + view + ".ascx"); //((ContentUserControl)c).Lang = lang; if (c.GetType().GetInterface("IUserControl") != null) { ((IUserControl)c).load(); } page.Controls.Add(c); StringWriter writer = new System.IO.StringWriter(); HttpContext.Current.Server.Execute(page, writer, false); return _cleanUselessHiddenFields(writer.ToString()); } //public static string getLavori(string lang, string work, int workIndex, string nextWork, int nextWorkIndex) [WebMethod] public static string getLavori(string work, int workIndex, string nextWork, int nextWorkIndex) { Page page = new System.Web.UI.Page(); string pathWork = "~/ascx/projects/" + work + ".ascx"; Control c = (Control)page.LoadControl(pathWork); ((IWorkUserControl)c).Index = workIndex; ((IWorkUserControl)c).View = work; ((IWorkUserControl)c).load(); page.Controls.AddAt(0, c); // viene caricato il secondo work solo e solo se il parametro nextWork รจ valorizzato // se รจ vuoto, non carica if (!string.IsNullOrEmpty(nextWork)) { string pathNextWork = "~/ascx/projects/" + nextWork + ".ascx"; Control nextC = (Control)page.LoadControl(pathNextWork); ((IWorkUserControl)nextC).Index = nextWorkIndex; ((IWorkUserControl)nextC).View = nextWork; ((IWorkUserControl)nextC).load(); page.Controls.AddAt(1, nextC); } StringWriter writer = new System.IO.StringWriter(); HttpContext.Current.Server.Execute(page, writer, false); return _cleanUselessHiddenFields(writer.ToString()); } [WebMethod] public static string inviaForm(string company, string person, string telephone, string email, string message) { int esito = 0; System.Text.StringBuilder s = new System.Text.StringBuilder(); s.Append("E' stata inviata una richiesta informazioni dal sito Aquest"); s.Append("<br><br>Company: <b>" + company + "</b>"); s.Append("<br><br>Person: <b>" + person + "</b>"); s.Append("<br><br>Telephone: <b>" + telephone + "</b>"); s.Append("<br><br>Email: <a href=mailto:" + email + "><b>" + email + "</b></a>"); s.Append("<br><br>Messaggio:<br>" + message); MailManager mailMng = new MailManager("localhost"); try { //mailMng.send("<EMAIL>", "<EMAIL>", new string[] { "<EMAIL>" }, "Richiesta informazioni sito Aquest", s.ToString()); mailMng.send("<EMAIL>", "<EMAIL>", new string[] { "<EMAIL>", "<EMAIL>"}, "Richiesta informazioni sito Aquest", s.ToString()); esito = 1; } catch { } return esito.ToString(); } private static string _cleanUselessHiddenFields(string inputString) { string regex = @"<input type=""hidden"" name=""__VIEWSTATE"" id=""__VIEWSTATE"" value=""(.*)"" />"; string regex2 = @"<input type=""hidden"" name=""__EVENTVALIDATION"" id=""__EVENTVALIDATION"" value=""(.*)"" />"; string valueToReturn = Regex.Replace(inputString, regex, ""); valueToReturn = Regex.Replace(valueToReturn, regex2, ""); return valueToReturn; } private static string _getCodLang(string codLingua) { string codLang = "it-IT"; if (codLingua.Equals("en")) codLang = "en-US"; else if (codLingua.Equals("de")) codLang = "de-DE"; return codLang; } private static void _setCulture(string codLang) { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(codLang); System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(codLang); } } <file_sep>๏ปฟusing System; using System.Data; using System.Text; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; /// <summary> /// Mail di notifica errore /// </summary> public class MailErrore : MailGenerica { private Exception _e; public MailErrore() { } public MailErrore(Exception e) { _e = e; _from = "<EMAIL>"; _to = "<EMAIL>"; _subject = "[lanordica-extraflame.it] errore"; _body = getBody(); } public MailErrore(string soggetto) { _e = null; _from = "<EMAIL>"; _to = "<EMAIL>"; _subject = soggetto; _body = getBody(); } public MailErrore(Exception e, string soggetto) { _e = e; _from = "<EMAIL>"; _to = "<EMAIL>"; _subject = soggetto; _body = getBody(); } private string getBody() { StringBuilder body = new StringBuilder(); body.Append("Errore aquest.it<br><br>"); if (_e != null) { body.Append(_e.ToString()); } return body.ToString(); } } <file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// IUserControl /// </summary> public interface IUserControl { void load(); }<file_sep>๏ปฟusing System; using System.IO; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Net; public class Logger { private string _logFilePath; public string logFilePath { get { return _logFilePath; } set { _logFilePath = value; } } public Logger(string path) { logFilePath = path; } public void log(Exception ex, string msg) { StreamWriter f = null; //try //{ f = (!File.Exists(logFilePath)) ? File.CreateText(logFilePath) : File.AppendText(logFilePath); if (ex != null) { f.WriteLine("-------------------------------------"); f.WriteLine("Exception: " + Environment.NewLine + ex.Message + Environment.NewLine + "Stack trace: " + Environment.NewLine + ex.StackTrace); if (ex.InnerException != null) f.WriteLine("Inner exception: " + Environment.NewLine + ex.InnerException.Message); } if (!string.IsNullOrEmpty(msg)) f.WriteLine(msg); //} //catch (Exception ex1) //{ //EventLog.WriteEntry("RunnerService", ex1.Message + Environment.NewLine + ex1.StackTrace, EventLogEntryType.Error, 1); //} //finally //{ if (f != null) { f.Close(); f.Dispose(); } //} } }<file_sep>๏ปฟusing System; using System.Data; using System.Text; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; /// <summary> /// Mail generica /// </summary> public class MailGenerica { protected string _from; public string from { get { return _from; } } protected string _to; public string to { get { return _to; } } protected string _subject; public string subject { get { return _subject; } } protected string[] _bcc; public string[] bcc { get { return _bcc; } } protected string _body; public string body { get { return _body; } } public MailGenerica() { } public MailGenerica(string from, string to, string[] bcc, string subject, string body) { _from = from; _to = to; _subject = subject; _bcc = bcc; _body = body; } } <file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { public string Lang { get; set; } public string View { get; set; } public string Type { get; set; } protected void Page_Load(object sender, EventArgs e) { } protected override void OnInit(EventArgs e) { base.OnInit(e); Lang = String.IsNullOrEmpty(Request.QueryString["lang"]) ? "it" : Request.QueryString["lang"]; View = String.IsNullOrEmpty(Request.QueryString["view"]) ? "home" : Request.QueryString["view"]; Type = String.IsNullOrEmpty(Request.QueryString["type"]) ? "pages" : Request.QueryString["type"]; Control c = (Control)LoadControl("~/ascx/" + Type + "/" + View + ".ascx"); if (c.GetType().GetInterface("IUserControl") != null) { ((IUserControl)c).load(); } phPage.Controls.Add(c); string js = "<script>var lang='" + Lang + "', view = '" + View + "';</script>"; litJs.Text = js; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); } }<file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net; using System.IO; using it.aquest.baseobjects; using System.Text; public partial class Homepage : ContentUserControl, IUserControl { protected void Page_Load(object sender, EventArgs e) { } public void load() { } }<file_sep>๏ปฟ(function () { module.exports.name = 'router'; // --- --- --- --- // module obj // --- --- --- --- var router = {}; // --- --- --- --- // START private vars and functions declaration // --- --- --- --- var _humanize = function (s) { var arr, humanized, word, _i, _len; humanized = ""; if (s.charAt(0) === '/') { s = s.slice(1); } arr = s.split('-'); if (s.length > 0) { if (arr.length > 0) { _len = arr.length; for (_i = 0; _i < _len; _i++) { word = arr[_i]; //humanized += _capitalize(word); humanized += word; } } else { //humanized = _capitalize(s); humanized = s; } } else { //humanized = "Homepage"; humanized = "homepage"; } return humanized; }; var _capitalize = function (s) { return s.charAt(0).toUpperCase() + s.slice(1); }; // --- --- --- --- // END private vars and functions declaration // --- --- --- --- // --- --- --- --- // START exported functions // --- --- --- --- router.route = function (url) { if (typeof url === 'undefined') { url = ""; } return _humanize(url); }; // --- --- --- --- // END exported functions // --- --- --- --- // --- --- --- --- // exports module obj // --- --- --- --- module.exports = router; }());<file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descrizione di riepilogo per IWorkUserControl /// </summary> public interface IWorkUserControl { int Index { get; set; } string View { get; set; } void load(); }<file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Web; using System.Web.UI.HtmlControls; using System.Web.UI; using System.Web.UI.WebControls; namespace it.aquest.baseobjects { public class BasePage : System.Web.UI.Page { private string m_codLingua; public string CodLingua { get { return m_codLingua; } } private string m_page; public string Pagina { get { return m_page; } set { m_page = value; } } public BasePage() { } protected override void InitializeCulture() { HttpCookie ckLinguaSito = new HttpCookie("lingua_sito"); if (!string.IsNullOrEmpty(Request["lang"])) { if (Request["lang"].Equals("it", StringComparison.InvariantCultureIgnoreCase) || Request["lang"].Equals("en", StringComparison.InvariantCultureIgnoreCase)) { m_codLingua = Request["lang"].ToLower(); ckLinguaSito.Value = m_codLingua; Response.Cookies.Add(ckLinguaSito); } } string codLang = "it-IT"; if (m_codLingua.Equals("en")) codLang = "en-US"; System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(codLang); System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(codLang); base.InitializeCulture(); /* HttpCookie ckLinguaSito = Request.Cookies["lingua_sito"]; if (ckLinguaSito == null) { ckLinguaSito = new HttpCookie("lingua_sito"); ckLinguaSito.Value = "IT"; m_codLingua = "it"; } else { m_codLingua = ckLinguaSito.Value; //ckLinguaSito.Value = "IT"; } Response.Cookies.Add(ckLinguaSito); if (!string.IsNullOrEmpty(Request["lang"])) { if (Request["lang"].Equals("it", StringComparison.InvariantCultureIgnoreCase) || Request["lang"].Equals("en", StringComparison.InvariantCultureIgnoreCase)) { m_codLingua = Request["lang"].ToLower(); ckLinguaSito.Value = m_codLingua; Response.Cookies.Add(ckLinguaSito); } } string codLang = "it-IT"; if (m_codLingua.Equals("en")) codLang = "en-US"; System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(codLang); System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(codLang); base.InitializeCulture(); */ } protected override void OnInit(EventArgs e) { base.OnInit(e); Pagina = Request.QueryString["view"]; //Pagina = Pagina.Trim().Length == 0 ? "home" : Pagina; Pagina = Pagina == null || (Pagina != null && Pagina.Trim().Length == 0) ? "home" : Pagina; if (!IsPostBack) { if (Request.QueryString["ref"] != null && Request.QueryString["ref"].ToString().Length > 0) { _initializeAqRef(Request.QueryString["ref"]); } } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); } protected string getSessionLingua() { return ""; } protected void setTitle(string title) { Page.Title = title; } protected void setDescription(string testo) { if (string.IsNullOrEmpty(testo)) return; string shorDesc = (testo.Length > 200 ? testo.Substring(0, 200) : testo); HtmlMeta description = new HtmlMeta(); description.Name = "Description"; description.Content = shorDesc; Page.Header.Controls.Add(description); } public void setRegisterJs(string fileName) { HtmlGenericControl js = new HtmlGenericControl("script"); js.Attributes.Add("type", "text/javascript"); js.Attributes.Add("language", "javascript"); js.Attributes.Add("src", "/js/" + fileName); Page.Header.Controls.Add(js); } private void _initializeAqRef(string val) { DateTime ora = DateTime.Now; Response.Cookies["aqref"].Value = val; Response.Cookies["aqref"].Expires = ora.AddMonths(1); } } }<file_sep>๏ปฟ(function () { module.exports.name = 'config'; // --- --- --- --- // module obj // --- --- --- --- var config = { ROUTE_BY_URL: true, MAX_CACHE_LENGTH: 5, // -1 cache illimitata HAS_INFO: false, PRELOAD: true, MOBILE_THRESHOLD: 767, TABLET_THRESHOLD: 1025, POLLING_TIMER: 100, STANDARD_ANIM_TIMING: 100, SCROLL_EVENT_HANDLERS: 'mousewheel touchmove wheel', CLICK_EVENT_HANDLERS: 'click touchend' }; // --- --- --- --- // exports module obj // --- --- --- --- module.exports = config; }()); <file_sep>๏ปฟusing System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; //using it.aquest.managers; namespace it.aquest.baseobjects { public class ContentUserControl : BaseUserControl { //public string Brand { get; set; } //public string Season { get; set; } //public string Year { get; set; } public ContentUserControl() { } protected override void OnInit(EventArgs e) { base.OnInit(e); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); } } }<file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descrizione di riepilogo per InitializeCulture /// </summary> public class UrlMapper { public UrlMapper() { // // TODO: aggiungere qui la logica del costruttore // } public string map(string langCode, string page) { string valueToReturn = ""; if (langCode.ToLower().Equals("it")) { switch (page) { case "home": valueToReturn = "/en"; break; case "gruppo": valueToReturn = "/en/group"; break; case "dovesiamo": valueToReturn = "/en/where"; break; case "servizi": valueToReturn = "/en/services"; break; case "etica": valueToReturn = "/en/ethics"; break; case "contatti": valueToReturn = "/en/contact"; break; } } else { switch (page) { case "home": valueToReturn = "/"; break; case "en/group": case "group": valueToReturn = "/gruppo"; break; case "en/where": case "where": valueToReturn = "/dovesiamo"; break; case "en/services": case "services": valueToReturn = "/servizi"; break; case "en/ethics": case "ethics": valueToReturn = "/etica"; break; case "en/contact": case "contact": valueToReturn = "/contatti"; break; } } return valueToReturn; } }<file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Web; using System.Web.UI.HtmlControls; namespace it.aquest.baseobjects { public class BaseUserControl : System.Web.UI.UserControl { public BaseUserControl() { } protected override void OnInit(EventArgs e) { base.OnInit(e); //if (Session[it.brugi.costanti.cosGenerali.ADMIN] == null) //{ // if (!Page.IsCallback) // { // Response.Redirect("~/backoffice/login.aspx", true); // } // else // { // string script = string.Format("http://{0}/backoffice/login.aspx", Request.ServerVariables["SERVER_NAME"]); // base.ClientScript.RegisterClientScriptBlock(typeof(string), "redirect", script, true); // } //} } protected override void OnLoad(EventArgs e) { base.OnLoad(e); } protected string getSessionLingua() { return ""; } protected void setRegisterCss(string path) { HtmlLink css = new HtmlLink(); css.Attributes.Add("rel", "stylesheet"); css.Attributes.Add("type", "text/css"); css.Href= path; Page.Header.Controls.Add(css); } protected void setRegisterJs(string path) { HtmlGenericControl js = new HtmlGenericControl(); js.TagName = "script"; js.Attributes.Add("type", "text/javascript"); js.Attributes.Add("language", "javascript"); js.Attributes.Add("src", path); Page.Header.Controls.Add(js); } } }<file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for Elem /// </summary> public class Elem : System.Collections.IComparer, IComparable { #region properties private string _title; public string title { get { return _title; } set { _title = value; } } private string _abstractText; public string abstractText { get { return _abstractText; } set { _abstractText = value; } } private string _id; public string id { get { return _id; } set { _id = value; } } private string _type; public string type { get { return _type; } set { _type = value; } } private string _allegato; public string allegato { get { return _allegato; } set { _allegato = value; } } private string _data; public string data { get { return _data; } set { _data = value; } } private string _dataid; public string dataid { get { return _dataid; } set { _dataid = value; } } #endregion public Elem() { // // TODO: Add constructor logic here // } public int Compare(object x, object y) { return _compare(x, y); } public int CompareTo(object y) { return _compare(this, y); } private int _compare(object x, object y) { Elem xElem = (Elem)x, yElem = (Elem)y; int valueToReturn = 0, xData = Convert.ToInt32(xElem.dataid), yData = Convert.ToInt32(yElem.dataid); if (xData < yData) { valueToReturn = -1; } else { if (xData > yData) { valueToReturn = 1; } } return valueToReturn; } }<file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Web; using System.Web.UI.WebControls; using System.Data; using System.Xml; using System.Text; using Newtonsoft.Json.Linq; using System.Text.RegularExpressions; using System.Security.Cryptography; namespace it.aquest { public class Utils { public string toUrl(string inputString) { string s = String.Empty; if (!String.IsNullOrEmpty(inputString)) { s = inputString.Trim().ToLower(); s = Regex.Replace(s, " - ", "-"); s = Regex.Replace(s, "ร ", "a"); s = Regex.Replace(s, "รข", "a"); s = Regex.Replace(s, "รจ", "e"); s = Regex.Replace(s, "รฌ", "i"); s = Regex.Replace(s, "รฒ", "o"); s = Regex.Replace(s, "รน", "u"); s = Regex.Replace(s, "รฉ", "e"); s = Regex.Replace(s, "รณ", "o"); s = Regex.Replace(s, "รถ", "o"); s = Regex.Replace(s, "รต", "o"); s = Regex.Replace(s, "รผ", "u"); s = Regex.Replace(s, "รค", "a"); s = Regex.Replace(s, "รœ", "u"); s = Regex.Replace(s, "รฑ", "n"); s = Regex.Replace(s, "รง", "c"); s = Regex.Replace(s, "!", ""); s = Regex.Replace(s, "ยฎ", ""); s = Regex.Replace(s, "โ„ข", ""); s = Regex.Replace(s, ",", "-"); s = Regex.Replace(s, @"([@ยฐ""./&()โ€™+*โ€รธร˜<>=$:?ยฃ ])", "-"); s = Regex.Replace(s, @"(-&-|' | '|')", "-"); s = Regex.Replace(s, @"(---|--)", "-"); s = Regex.Replace(s, "--", "-"); if (s.StartsWith("-")) { s = s.Substring(1, s.Length - 1); } if (s.EndsWith("-")) { s = s.Substring(0, s.Length - 1); } } else { s = inputString; } return s; } public static string generateRandomString(int len) { char[] cr = "123456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUWXYZ".ToCharArray(); string result = string.Empty; Random r = new Random(); for (int i = 0; i < len; i++) { result += cr[r.Next(0, cr.Length - 1)].ToString(); } return result; } public static void insertStartupJsOnPageReady(string testo) { System.Web.UI.Page currentPage = (System.Web.UI.Page)HttpContext.Current.Handler; string randString = generateRandomString(5); if (!currentPage.ClientScript.IsClientScriptBlockRegistered(randString)) { string tmp = "<script type=\"text/javascript\">\n $(function() { \n " + testo + " \n });</script>"; currentPage.ClientScript.RegisterStartupScript (currentPage.GetType(), randString, tmp); } } public static void insertStartupJavascript(string testo) { System.Web.UI.Page currentPage = (System.Web.UI.Page)HttpContext.Current.Handler; string randString = generateRandomString(5); if (!currentPage.ClientScript.IsClientScriptBlockRegistered(randString)) { currentPage.ClientScript.RegisterStartupScript (currentPage.GetType(), randString, "<script type=\"text/javascript\">\n " + testo + " \n</script>"); } } public static string Abbreviate(string sIn, int len) { string newString = Regex.Replace(sIn, @"<[^>]*>", " "); int lastSpace = 0; newString = newString.Replace("\r", "").Replace("\n", "").Replace("\'", "'"); if (newString.Length > len) { newString = newString.Substring(0, len - 2); if (newString.Contains(" ")) { lastSpace = newString.LastIndexOf(' '); } else { lastSpace = newString.Length; } newString = newString.Substring(0, lastSpace) + " ..."; } return newString; } public static string stripLastCharOfString(string sIn) { return stripNCharsFromEndOfString(sIn, 1); } public static string stripNCharsFromEndOfString(string sIn, int n) { if (sIn != null && sIn.Length > 0) { sIn = sIn.Substring(0, sIn.Length - n); } return sIn; } public static DateTime UnixTimeStampToDateTime(double unixTimeStamp) { // Unix timestamp is seconds past epoch System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime(); return dtDateTime; } public static string GetMessageDateDiffFromNow(DateTime d) { string valueToReturn = ""; TimeSpan span = (DateTime.Now - d); if (span.Days > 0) { valueToReturn += span.Days.ToString() + " day"; if (span.Days > 1) { valueToReturn += "s"; } valueToReturn += " ago"; } else { if (span.Hours > 0) { valueToReturn += span.Hours.ToString() + " hour"; if (span.Hours > 1) { valueToReturn += "s"; } valueToReturn += " ago"; } else { valueToReturn += span.Minutes.ToString() + " min ago"; } } return valueToReturn; } /// <summary> /// see http://pigeoncms.codeplex.com/SourceControl/latest#projects/PigeonCms.Core/Helpers/Utility.cs /// useful crypt decript methods using AES (modified) /// </summary> public class Encryption { const string SKIP_KEY = "nn"; public static string Decrypt(string textToDecrypt, string key) { byte[] encryptedData = Convert.FromBase64String(textToDecrypt); if (key == SKIP_KEY) { return Encoding.UTF8.GetString(encryptedData); } else { RijndaelManaged rijndaelCipher = new RijndaelManaged(); //AES rijndaelCipher.Mode = CipherMode.CBC; rijndaelCipher.Padding = PaddingMode.PKCS7; rijndaelCipher.KeySize = 0x80; rijndaelCipher.BlockSize = 0x80; //byte[] encryptedData = Convert.FromBase64String(textToDecrypt); byte[] pwdBytes = Encoding.UTF8.GetBytes(key); byte[] keyBytes = new byte[0x10]; int len = pwdBytes.Length; if (len > keyBytes.Length) { len = keyBytes.Length; } Array.Copy(pwdBytes, keyBytes, len); rijndaelCipher.Key = keyBytes; rijndaelCipher.IV = keyBytes; byte[] plainText = rijndaelCipher.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length); return Encoding.UTF8.GetString(plainText); } } public static string Encrypt(string textToEncrypt, string key) { byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt); if (key == SKIP_KEY) { return Convert.ToBase64String(plainText); } else { RijndaelManaged rijndaelCipher = new RijndaelManaged(); rijndaelCipher.Mode = CipherMode.CBC; rijndaelCipher.Padding = PaddingMode.PKCS7; rijndaelCipher.KeySize = 0x80; rijndaelCipher.BlockSize = 0x80; byte[] pwdBytes = Encoding.UTF8.GetBytes(key); byte[] keyBytes = new byte[0x10]; int len = pwdBytes.Length; if (len > keyBytes.Length) { len = keyBytes.Length; } Array.Copy(pwdBytes, keyBytes, len); rijndaelCipher.Key = keyBytes; rijndaelCipher.IV = keyBytes; ICryptoTransform transform = rijndaelCipher.CreateEncryptor(); //byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt); return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length)); } } } } } <file_sep>// ------------------------------------------------------ // // // TOKI by Aquest // v. 1.1.0 // Authors: <NAME>, <NAME> // // 24/10/2014 // // Libreries and Tools used: // - Node.js with Browserify Modules // - Util node.js code modules // - Builded with Grunt.js / Gulp.js // - LoDash.js // - Velocity.js // - Events Emitter // - Jquery // - Masonry, Modernizr // ------------------------------------------------------ // "use strict"; // --- --- --- --- // START TOKI declaration // --- --- --- --- var TOKI = TOKI || {}; var is_chromeWin = (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) && (navigator.userAgent.indexOf("Mac OS X") == -1); global._ = require('lodash'); global.util = require('util'); global.TOKI = TOKI; // --- --- --- --- // START jQuery plugins require // --- --- --- --- require('./vendor/velocity.min.js'); require('./vendor/velocity.ui.min.js'); // --- --- --- --- // START TOKI fields declarations // --- --- --- --- TOKI.inView = true; TOKI.CurrentModule = null; TOKI.isInsideDetail = false; TOKI.isAjax = false; TOKI.Events = []; var TokiEmitter = require("./app/components/toki-emitter.js"); TOKI.emitter = new TokiEmitter(); TOKI.emitter.setMaxListeners(0); // listeners illimitati // --- --- --- --- // START require components // --- --- --- --- TOKI.config = require("./app/components/config.js"); TOKI.screen = require("./app/components/screen.js"); TOKI.router = require("./app/components/router.js"); TOKI.cache = require("./app/components/cache.js"); // --- --- --- --- // START require views // --- --- --- --- TOKI.baseview = require("./app/views/base-view.js"); TOKI.homepage = require("./app/views/homepage.js"); // --- --- --- --- // START require regions // --- --- --- --- /* TOKI.loader = require('./app/regions/loader.js'); TOKI.nav = require('./app/regions/nav.js'); TOKI.hyperlinks = require('./app/regions/hyperlinks.js'); TOKI.content = require('./app/regions/content.js'); TOKI.body = require('./app/regions/body.js'); */ // --- --- --- --- // START adding regions // --- --- --- --- TOKI.init_shared_regions = function() { /* TOKI.hyperlinks.init(); TOKI.body.init(); TOKI.nav.init(); TOKI.content.init(); TOKI.loader.init(); */ TOKI.init(); }; // --- --- --- --- // START project's heart // --- --- --- --- TOKI.init = function (url) { // router if (typeof url === 'undefined') { //TOKI.isAjax = false; url = TOKI.config.ROUTE_BY_URL ? location.href : $("body").data("page"); } var splittedUrl = url.split('/'); var urlTokenCount = splittedUrl.length; var page = splittedUrl[urlTokenCount - 1].split('?')[0]; // setto prev e current module TOKI.CurrentModule = TOKI.router.route(page); // chiamo init di ogni modulo TOKI[TOKI.CurrentModule].init(TOKI.isAjax); // es. Toki[About].init(true); TOKI.emitter.emit('TOKI:init'); _.delay(function(){ TOKI.emitter.emit(TOKI.CurrentModule + ":ready"); },1000); }; // --- --- --- --- --- --- // START emitting dom and window events // --- --- --- --- --- --- $(document).on('ready', function(e){ TOKI.emitter.emit('TOKI:document:ready', e); }); $(window).on('orientationchange', function(e){ TOKI.emitter.emit('TOKI:window:orientationchange', e); }); $(window).on('resize', function(e){ TOKI.emitter.emit('TOKI:window:resize', e); }); $(window).on(TOKI.config.SCROLL_EVENT_HANDLERS, function (e) { TOKI.emitter.emit('TOKI:window:scroll', e); }); // --- --- --- --- // FIRST START ON DOCUMENT READY // --- --- --- --- TOKI.init_shared_regions(); // --- --- --- --- // RECALL TOKI INIT ON AJAX CALL // --- --- --- --- TOKI.emitter.on("layout:content:contentFilled", function(href) { TOKI.init(href); });
380c24cbdc33e642af087449135a5ab79e3a5fda
[ "JavaScript", "C#" ]
17
C#
nod2007/mayn
83db1b4efec63bf4fd1134444f830468ff29a89f
776741f32beccb3b458e43c52fc26c22c88704be
refs/heads/master
<file_sep>package net.blf2.service.impl; import net.blf2.dao.IUserDao; import net.blf2.entity.UserInfo; import net.blf2.service.IUserService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * Created by blf2 on 17-2-4. */ @Service("UserService") public class UserService implements IUserService { @Resource private IUserDao userDao; public IUserDao getUserDao() { return userDao; } public void setUserDao(IUserDao userDao) { this.userDao = userDao; } public UserInfo findUserInfoByUserId(String userId) { return userDao.queryUserInfoById(userId); } public List<UserInfo> findAllUserInfos() { return userDao.queryUserInfoAll(); } public boolean registerUserInfo(UserInfo userInfo) { try { userDao.insertUserInfo(userInfo); }catch (Exception ex){ return false; } return true; } public boolean updateUserInfo(UserInfo userInfo) { try { userDao.updateUserInfo(userInfo); }catch (Exception ex){ return false; } return true; } //TODO:delete all infomation of user infomation public boolean deleteUserInfoByUserId(String userId) { return false; } public boolean checkLoginInfo(String userNum, String userPswd) { return false; } public boolean checkUserPhoneHasExist(String userPhone) { return userDao.queryUserIdByUserPhone(userPhone) != null; } public boolean checkUserNumHasExist(String userNum) { return userDao.queryUserIdByUserNum(userNum) != null; } } <file_sep>CREATE DATABASE collector DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; use collector; create table UserInfo( userId varchar(100) primary key, userNum varchar(20) not null, userPswd varchar(20), userPhone varchar(20), userGrade varchar(30) not null, userRoleId varchar(100) not null, userNote varchar(512) ); create table ClassInfo( classId varchar(100) primary key, majorName varchar(30) not null, classGrade varchar(10) not null, classNum varchar(10) not null, monitorId varchar(100) not null, classNote varchar(512) ); create table UserRoleInfo( roleId varchar(100) primary key, roleName varchar(30) not null, roleRule varchar(512), roleNote varchar(512) ); <file_sep>package net.blf2.util; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.util.Map; import java.util.Properties; /** * Created by blf2 on 17-1-8. */ public class Consts { private static Properties properties; static{ properties = new Properties(); try { properties.load(Consts.class.getClassLoader().getResourceAsStream("consts.properties")); }catch (Exception ex) { ex.printStackTrace(); } } public static int CONNECTIONS_PER_HOST = properties.getProperty("CONNECTIONS_PER_HOST") != null ? Integer.parseInt(properties.getProperty("CONNECTIONS_PER_HOST")) : 50; public static int THREADS_ALLOWED_TO_BLOCK_FOR_CONNECTION_MULTIPLIER = properties.getProperty("THREADS_ALLOWED_TO_BLOCK_FOR_CONNECTION_MULTIPLIER") != null ? Integer.parseInt(properties.getProperty("THREADS_ALLOWED_TO_BLOCK_FOR_CONNECTION_MULTIPLIER")) : 50; public static int CONNECT_TIMEOUT = properties.getProperty("CONNECT_TIMEOUT") != null ? Integer.parseInt(properties.getProperty("CONNECT_TIMEOUT")) : 60000; public static int MAX_WAIT_TIME = properties.getProperty("MAX_WAIT_TIME") != null ? Integer.parseInt(properties.getProperty("MAX_WAIT_TIME")) : 120000; public static String MONGODB_HOST = properties.getProperty("MONGODB_HOST") != null ? properties.getProperty("MONGODB_HOST") : "127.0.0.1"; public static int SOCKET_TIME_OUT = properties.getProperty("SOCKET_TIME_OUT") != null ? Integer.parseInt(properties.getProperty("SOCKET_TIME_OUT")) : 5000; public static int MONGODB_PORT = properties.getProperty("MONGODB_PORT") != null ? Integer.parseInt(properties.getProperty("MONGODB_PORT")) : 27017; public static boolean SOCKET_KEEP_ALIVE = properties.getProperty("SOCKET_KEEP_ALIVE") != null ? Boolean.parseBoolean(properties.getProperty("SOCKET_KEEP_ALIVE")) : false; public static String MONGO_DATABASE_NAME = properties.getProperty("MONGO_DATABASE_NAME") != null ? properties.getProperty("MONGO_DATABASE_NAME") : "app"; public static String MONGO_COLLECTION_FOR_CLASS = properties.getProperty("MONGO_COLLECTION_FOR_CLASS") != null ? properties.getProperty("MONGO_COLLECTION_FOR_CLASS") : "app_data"; public static String MONGO_PRIMARY_KEY_NAME = properties.getProperty("MONGO_PRIMARY_KEY_NAME") != null ? properties.getProperty("MONGO_PRIMARY_KEY_NAME") : "objectId"; } <file_sep>CONNECTIONS_PER_HOST=50 THREADS_ALLOWED_TO_BLOCK_FOR_CONNECTION_MULTIPLIER=50 CONNECT_TIMEOUT=60000 MAX_WAIT_TIME=120000 MONGODB_HOST=127.0.0.1 MONGODB_PORT=27017 SOCKET_TIME_OUT=5000 SOCKET_KEEP_ALIVE=false MONGO_DATABASE_NAME=app MONGO_COLLECTION_FOR_CLASS=app_data MONGO_PRIMARY_KEY_NAME=objectId
a4e7450e5c9ab0312597678482ebd1f6e4fcbe75
[ "Java", "SQL", "INI" ]
4
Java
469656392/Collector
2c8506b1715d3f5bb781469732435165d18289fc
74ca635302c0dc4c617d2317f94b19f389818132
refs/heads/master
<file_sep>const dynamoose = require('dynamoose'); const Schema = dynamoose.Schema; module.exports = new Schema({ SearchTerm: { type: String, hashKey: true }, StatName: { type: String, rangeKey: true, index: true }, Tweets: { type: 'list', list: [{ type: 'map', map: { hashtags: { type: [String] }, has_media: { type: Boolean, default: false }, parent_tweet_id: { type: String }, is_replied: { type: Boolean, default: false }, url: { type: String }, is_reply_to: { type: Boolean, default: false }, video_url: { type: String }, replies: { type: Number }, screen_name: { type: String }, user_id: { type: String }, img_urls: { type: [String] }, html: { type: String }, links: { type: [String] }, reply_to_users: { type: [String] }, id: { type: String }, text: { type: String }, timestamp_epochs: { type: Number }, retweets: { type: Number }, username: { type: String }, timestamp: { type: String }, likes: { type: Number } } }] }}, { useDocumentTypes: true, throughput: {read: 15, write: 5} } );<file_sep>class TweetDTO { constructor(rawTweetObj) { this.screen_name = rawTweetObj.screen_name; this.username = rawTweetObj.username; this.html = rawTweetObj.html; this.url = rawTweetObj.url; this.time = rawTweetObj.time.format('LLLL'); this.timestamp = rawTweetObj.timestamp+'Z'; this.likes = rawTweetObj.likes; this.replies = rawTweetObj.replies; this.retweets = rawTweetObj.retweets; this.avatar_img = rawTweetObj.avatar_img; return this; } } module.exports = TweetDTO;<file_sep>class UserDTO { constructor(rawTweetObj) { this.screen_name = rawTweetObj.screen_name; this.username = rawTweetObj.username; this.tweet_time = rawTweetObj.time.format('LLLL'); this.avatar_img = rawTweetObj.avatar_img; return this; } } module.exports = UserDTO;
d13d4a4477257c96b5e8a860de60235430bc2dd4
[ "JavaScript" ]
3
JavaScript
haseebelahi/hashtag-analyzer-api
cc0720a27e601855e2ef4cc13673eec0a77d752c
2634073eaebc232aebc8d9bd02171db128ac2032
refs/heads/master
<file_sep>class Picture < ApplicationRecord #picture belongs to event and user relation belongs_to :imageable, polymorphic: true mount_uploader :picture, PictureUploader #picture resize validation validate :picture_size private # Validates the size of an uploaded picture. def picture_size if picture.size > 5.megabytes errors.add(:picture, "should be less than 5MB") end end end<file_sep>class Event < ApplicationRecord belongs_to :creator, foreign_key: 'user_id', class_name: 'User' #realtion of event attending has_many :event_attendings, :foreign_key => :attended_event_id has_many :attendees, :through => :event_attendings, :source => :event_attendee #realtion of hasmany picture has_many :pictures, as: :imageable accepts_nested_attributes_for :pictures mount_uploader :picture, PictureUploader #validation default_scope -> { order(created_at: :desc) } validates :user_id, presence: true validates :title, presence: true, length: { maximum: 50 } validates :description, length: { maximum: 1000 } validates :location, presence: true, length: { maximum: 50 } #where query for find date and time wise event record scope :upcoming, -> { where("date >= ?", Time.now).order('date ASC') } scope :past, -> { where("date < ?", Time.now).order('date DESC') } end <file_sep>class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update ,:destroy] #show all user def index @user = User.find_by(params[:id]) @users = User.all if params[:user_id].present? @events = Event.where(user_id: params[:user_id]) else @events = Event.where(user_id: current_user.id) end end #update user def update if @user.update_attributes(user_params) flash[:success] = "Profile updated" redirect_to @user else render :edit end end # Use callbacks to share common setup or constraints between actions. private def set_user @user = User.find(params[:id]) end def user_params params.require(:user).permit(:name, :email,:phone_number,:gender,:date_of_birth,:password, :password_confirmation,:current_password,:role,pictures_attributes: :picture) end end <file_sep> class RegistrationsController < Devise::RegistrationsController def new build_resource self.resource.pictures.build end private def sign_up_params params.require(:user).permit(:email,:name,:phone_number,:gender,:date_of_birth,:password, :password_confirmation,:current_password,:role,pictures_attributes: [:picture]) end def account_update_params params.require(:user).permit(:email,:name,:phone_number,:gender,:date_of_birth,:password, :password_confirmation,:current_password,:role,pictures_attributes: [:picture]) end end<file_sep>class EventAttendee < ApplicationRecord belongs_to :attendee, :class_name => "User" belongs_to :event, :class_name => "Event" validates :attendee_id, presence: true validates :event_id, presence: true end <file_sep>class EventPolicy < ApplicationPolicy def new is_admin? end def show? is_admin? || is_user? end def create? is_admin? end def update? is_admin? end def edit? is_admin? end def destroy? is_admin? end def index? is_user? end end <file_sep>class Role < ApplicationRecord has_and_belongs_to_many :users, :join_table => :users_roles #add role for user for authorization belongs_to :resource,:polymorphic => true,:optional => true #validation for rolify validates :resource_type,:inclusion => { :in => Rolify.resource_types },:allow_nil => true scopify end <file_sep>class EventController < ApplicationController before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy,:index] #new event render def new @event = Event.new @event.pictures.build end #attndeing method for user def attend @event = Event.find_by(id: params[:id]) @event.attendees << current_user redirect_to current_user end #show all event def index @upcoming_events= Event.upcoming.all @past_events = Event.past.all if params[:user_id].present? @events = Event.where(user_id: params[:user_id]) else @events = Event.where(user_id: current_user.id) end authorize @events end #craete new event and save def create @event = current_user.events.build(event_params) authorize @event if @event.save! @event.attendees << current_user flash[:success] = "Event created successfully...!!!!!!!!!!" redirect_to current_user else flash[:notice] = "Event is not crrated plase fill the vaule...!!!!!!!!!!" redirect_to root_url end end #destory event def destroy @event = Event.find_by(params[:event_id]) if @event.destroy authorize @event flash[:success] = "Event Deleted" redirect_back(fallback_location: root_url) else flash[:notice] = "event is not deteled plzz try again!!!!" redirect_to root_path end end #update event def update @event = Event.find(params[:id]) authorize @event [email protected](event_params) redirect_back(fallback_location: root_url) else render :edit end end #private method for event params private def event_params params.require(:event).permit(:date, :location, :title, :description, :user_id , pictures_attributes: :picture) end end<file_sep>Rails.application.routes.draw do get 'picture/new' devise_for :users, :controllers => { registrations: 'registrations' } root 'static_pages#home' get '/about', to:'static_pages#about' get '/contact', to:'static_pages#contact' get '/news', to:'static_pages#news' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :users, only: [:index, :show, :edit, :update ,:destroy] get 'event/new' post 'event/create' get 'event/index' get 'event/show' get 'event/update' get 'event/destroy' resources :event do post 'attend' ,on: :member end #resources :event_attendees, only: [:create, :destroy] end <file_sep>class User < ApplicationRecord #rolify add role rolify after_create :assign_default_role #relation for attend event has_many :events, foreign_key: 'user_id', class_name: 'Event' ,dependent: :destroy has_many :event_attendings, :foreign_key => :event_attendee_id has_many :attended_events, :through => :event_attendings #relation for picture uploder has_many :pictures, as: :imageable accepts_nested_attributes_for :pictures #Include default devise modules. devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable #validtion for user signin from validates :name, presence: true #validates :phone_number, presence: true #validates :gender, presence: { message: "must be selected" } #validates :dob, presence: { message: "(Date of Birth) must be entered" } end #when user singup then assign role def assign_default_role if self.roles.blank? self.add_role(:user) else self.add_role(:admin) end end def upcoming_events self.attended_events.upcoming end def past_events self.attended_events.past end end <file_sep>module PictureHelper end <file_sep>module EventHelper end <file_sep>class PictureController < ApplicationController before_action :load_imagable #picture craete for event and user profile picture def create @picture [email protected](picture_params) if @picture.save redirect_to [@imageable, :pictures], notice: 'Comment created' else render :new end end #render picture from def new @picture = @imageable.pictures.new end #show picture def show @picture = Picture.find(params[:id]) @imageable = User.find(params[:user_id]) @imageable = Event.find(params[:event_id]) end #private method for picture params and load images private def picture_params params.require(:picture).permit(:picture) end def load_imagable resource, id = request.path.split('/')[1,2] @imagable = resource.singularize.classify.constantize.find(id) end end
44f34cdcdebc687c1587044cee2342b3b402e2ed
[ "Ruby" ]
13
Ruby
neha912/Event-Mangement-App
cbdcd88b487822a12df4354c5be1ed49d2662156
006aadcff71202f0ac81e834cf8aef20b8588e45
refs/heads/master
<file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "gl_context.h" static const EGLint _display_attribs[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE }; static const EGLint _context_attribs[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_CONTEXT_MAJOR_VERSION_KHR, 3, EGL_CONTEXT_MINOR_VERSION_KHR, 1, EGL_NONE }; static EGLContext _context = EGL_NO_CONTEXT; static EGLSurface _surface = EGL_NO_SURFACE; static EGLDisplay _display = EGL_NO_DISPLAY; // ------------------------------------------------------------------------------------------------- void gl_context_create(struct ANativeWindow *window) { EGLint num_configs; EGLConfig *configs; EGLint r, g, b; EGLConfig selected_config; size_t i; if (window == NULL) return; _display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(_display, 0, 0); // Get a config eglChooseConfig(_display, _display_attribs, NULL, 0, &num_configs); configs = (EGLConfig *) malloc(num_configs * sizeof(EGLConfig)); eglChooseConfig(_display, _display_attribs, configs, num_configs, &num_configs); for (i = 0; i < num_configs; i++) { if (eglGetConfigAttrib(_display, configs[i], EGL_RED_SIZE, &r) && eglGetConfigAttrib(_display, configs[i], EGL_GREEN_SIZE, &g) && eglGetConfigAttrib(_display, configs[i], EGL_BLUE_SIZE, &b) && r == 8 && g == 8 && b == 8) { selected_config = configs[i]; break; } } if (i == num_configs) { LOGE("Default config loaded"); selected_config = configs[0]; } free(configs); EGLint format; eglGetConfigAttrib(_display, selected_config, EGL_NATIVE_VISUAL_ID, &format); _surface = eglCreateWindowSurface ( _display, selected_config, window, NULL ); _context = eglCreateContext(_display, selected_config, NULL, _context_attribs); // Load OpenGl functions gl_functions_load(); if (eglMakeCurrent(_display, _surface, _surface, _context) == EGL_FALSE) { LOGE("Unable to make current"); } // Check init OK GLenum infos[] = {GL_VENDOR, GL_RENDERER, GL_VERSION, GL_EXTENSIONS}; for (i = 0; i < 4; i++) { const GLubyte *info = glGetString(infos[i]); LOGD("OpenGL info : %s", info); } eglMakeCurrent(_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } void gl_context_init_computing(struct compute_data *data) { gl_computing_init(data); } void gl_context_update_computing(struct compute_data *data) { gl_computing_update(data); } void gl_context_perform_computing(struct compute_data *data) { gl_computing_compute(data); } void gl_context_destroy_computing(struct compute_data *data) { gl_computing_destroy(data); } void gl_context_init_frame(struct display_data *data) { rendering_init(data); } void gl_context_update_frame(struct display_data *data) { rendering_update(data); } void gl_context_clear_frame(struct display_data *data) { rendering_clear(data); } void gl_context_resize_frame(struct display_data *data) { GLsizei w; GLsizei h; eglQuerySurface(_display, _surface, EGL_WIDTH, &(w)); eglQuerySurface(_display, _surface, EGL_HEIGHT, &(h)); rendering_resize(data, w, h); } void gl_context_draw_frame(struct display_data *data) { rendering_draw(data); eglSwapBuffers(_display, _surface); } void gl_context_destroy_frame(struct display_data *data) { rendering_destroy(data); } void gl_context_bind() { if (eglGetCurrentContext() != _context) { if (eglMakeCurrent(_display, _surface, _surface, _context) == EGL_FALSE) { LOGE("Unable to bind the current EGL context"); } } } void gl_context_unbind() { eglMakeCurrent(_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } void gl_context_destroy() { if (_display != EGL_NO_DISPLAY) { if (eglMakeCurrent(_display, _surface, _surface, _context) == EGL_FALSE) { LOGE("Unable to make current for destroying"); return; } if (_context != EGL_NO_CONTEXT) { eglDestroyContext(_display, _context); } if (_surface != EGL_NO_SURFACE) { eglDestroySurface(_display, _surface); } eglTerminate(_display); } _display = EGL_NO_DISPLAY; _context = EGL_NO_CONTEXT; _surface = EGL_NO_SURFACE; }<file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "global.h" void checkCLError(const char *message, const cl_int error_id) { switch (error_id) { case CL_SUCCESS: LOGD("%s : CL_SUCCESS", message); break; case CL_INVALID_DEVICE: LOGE("%s : CL_INVALID_DEVICE", message); break; case CL_INVALID_VALUE: LOGE("%s : CL_INVALID_VALUE", message); break; case CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR: LOGE("%s : CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR", message); break; case CL_INVALID_OPERATION: LOGE("%s : CL_INVALID_OPERATION", message); break; case CL_OUT_OF_RESOURCES: LOGE("%s : CL_OUT_OF_RESOURCES", message); break; case CL_INVALID_CONTEXT: LOGE("%s : CL_INVALID_CONTEXT", message); break; case CL_OUT_OF_HOST_MEMORY: LOGE("%s : CL_OUT_OF_HOST_MEMORY", message); break; case CL_INVALID_PROGRAM: LOGE("%s : CL_INVALID_PROGRAM", message); break; case CL_INVALID_BINARY: LOGE("%s : CL_INVALID_BINARY", message); break; case CL_INVALID_BUILD_OPTIONS: LOGE("%s : CL_INVALID_BUILD_OPTIONS", message); break; case CL_BUILD_PROGRAM_FAILURE: LOGE("%s : CL_BUILD_PROGRAM_FAILURE", message); break; case CL_COMPILER_NOT_AVAILABLE: LOGE("%s : CL_COMPILER_NOT_AVAILABLE", message); break; case CL_INVALID_BUFFER_SIZE: LOGE("%s : CL_INVALID_BUFFER_SIZE", message); break; case CL_MEM_OBJECT_ALLOCATION_FAILURE: LOGE("%s : CL_MEM_OBJECT_ALLOCATION_FAILURE", message); break; case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR: LOGE("%s : CL_INVALID_IMAGE_FORMAT_DESCRIPTOR", message); break; case CL_INVALID_IMAGE_DESCRIPTOR: LOGE("%s : CL_INVALID_IMAGE_DESCRIPTOR", message); break; case CL_INVALID_IMAGE_SIZE: LOGE("%s : CL_INVALID_IMAGE_SIZE", message); break; case CL_INVALID_HOST_PTR: LOGE("%s : CL_INVALID_HOST_PTR", message); break; case CL_IMAGE_FORMAT_NOT_SUPPORTED: LOGE("%s : CL_IMAGE_FORMAT_NOT_SUPPORTED", message); break; default: LOGE("%s : unknown error", message); break; } } void checkGLError(const char *message) { GLenum err = glGetError(); switch (err) { case GL_NO_ERROR: LOGI("%s OK", message); break; case GL_INVALID_ENUM: LOGE("%s GL error : INVALID ENUM", message); break; case GL_INVALID_VALUE: LOGE("%s GL error : INVALID VALUE", message); break; case GL_INVALID_OPERATION: LOGE("%s GL error : INVALID OPERATION", message); break; case GL_INVALID_FRAMEBUFFER_OPERATION: LOGE("%s GL error : INVALID FRAMEBUFFER OPERATION", message); break; case GL_OUT_OF_MEMORY: LOGE("%s GL error : OUT OF MEMORY", message); break; } } void checkFrameBufferCompleteness(const char *message) { GLenum err = glCheckFramebufferStatus(GL_FRAMEBUFFER); switch (err) { case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: LOGE("%s framebuffer incomplete : GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT", message); break; #ifdef __ANDROID case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: LOGE("%s framebuffer incomplete : GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS", message); break; #endif case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: LOGE("%s framebuffer incomplete : GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT", message); break; case GL_FRAMEBUFFER_UNSUPPORTED: LOGE("%s framebuffer incomplete : GL_FRAMEBUFFER_UNSUPPORTED", message); break; case GL_FRAMEBUFFER_COMPLETE: LOGD("%s framebuffer complete", message); break; } }<file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #ifndef OPENINGS_GL_THREAD_H #define OPENINGS_GL_THREAD_H #include <pthread.h> #include <unistd.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <errno.h> #include <omp.h> #include <EGL/egl.h> #include <EGL/eglext.h> #include <android/native_window.h> #include "cl_context/cl_context.h" #include "global/global.h" #include "gl/gl_context.h" #include "model/model.h" #include "rendering/rendering.h" #include "gl_computing/gl_computing.h" #define GL_THREAD_SLEEP_TIME 10000 // 10 ms #define GL_THREAD_RENDER_CLEAR_REQUEST 0b00000001 #define GL_THREAD_RENDER_UPDATE_REQUEST 0b00000010 #define GL_THREAD_RENDER_RESIZE_REQUEST 0b00000100 #define GL_THREAD_COMPUTE_UPDATE_REQUEST 0b00001000 #define GL_THREAD_COMPUTE_PERFORM_REQUEST 0b00010000 __BEGIN_DECLS extern void gl_thread_set_flag(uint8_t flag); extern void gl_thread_start(struct ANativeWindow *window); extern void gl_thread_stop(); __END_DECLS #endif // OPENINGS_GL_THREAD_H <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #ifndef OPENINGS_RENDERING_H #define OPENINGS_RENDERING_H #include <stdint.h> #include <stdlib.h> #include <string.h> #include <GLES3/gl3.h> #include "global/global.h" #include "gl/gl_31_functions.h" #include "gl/shader.h" #include "model/model.h" __BEGIN_DECLS extern void rendering_init(struct display_data *data); extern void rendering_resize(struct display_data *data, GLsizei w, GLsizei h); extern void rendering_update(struct display_data *data); extern void rendering_clear(struct display_data *data); extern void rendering_draw(struct display_data *data); extern void rendering_destroy(struct display_data *data); __END_DECLS #endif // OPENINGS_RENDERING_H <file_sep># Created by <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_ARM_NEON := true ifeq ($(TARGET_ARCH_ABI),armeabi-v7a) LOCAL_CFLAGS := -mfloat-abi=softfp -mfpu=neon endif LOCAL_MODULE := native_interface LOCAL_C_INCLUDES += $(LOCAL_PATH)/ \ $(LOCAL_PATH)/application/ \ $(LOCAL_PATH)/CL/ \ $(LOCAL_PATH)/computing/ \ $(LOCAL_PATH)/gl/ \ $(LOCAL_PATH)/global/ \ $(LOCAL_PATH)/model/ \ $(LOCAL_PATH)/rendering/ \ $(LOCAL_PATH)/tango/ LOCAL_SRC_FILES := $(subst $(LOCAL_PATH)/,,$(wildcard $(LOCAL_PATH)/*.c)) \ $(subst $(LOCAL_PATH)/,,$(wildcard $(LOCAL_PATH)/application/*.c)) \ $(subst $(LOCAL_PATH)/,,$(wildcard $(LOCAL_PATH)/computing/*.c)) \ $(subst $(LOCAL_PATH)/,,$(wildcard $(LOCAL_PATH)/gl/*.c)) \ $(subst $(LOCAL_PATH)/,,$(wildcard $(LOCAL_PATH)/global/*.c)) \ $(subst $(LOCAL_PATH)/,,$(wildcard $(LOCAL_PATH)/model/*.c)) \ $(subst $(LOCAL_PATH)/,,$(wildcard $(LOCAL_PATH)/rendering/*.c)) \ $(subst $(LOCAL_PATH)/,,$(wildcard $(LOCAL_PATH)/tango/*.c)) LOCAL_LDLIBS := -lGLESv3 \ -lEGL \ -llog \ -lc \ -lm \ -landroid \ -fopenmp \ -lOpenCL \ -L$(LOCAL_PATH)/../JNILibs include $(BUILD_SHARED_LIBRARY)<file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #ifndef OPENINGS_GLOBAL_H #define OPENINGS_GLOBAL_H #ifndef _REENTRANT # define _REENTRANT #endif #ifndef CL_TARGET_OPENCL_VERSION # define CL_TARGET_OPENCL_VERSION 220 #endif #include <CL/opencl.h> #include <pthread.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <android/log.h> #include <GLES3/gl3.h> #include "CL/opencl.h" // --------------------------------------------------------------------------------------------- #define LOG_TAG "native-activity" /** * Different constants related to the depth and color camera (width, height, resolutions, ...) */ #define COLOR_CAMERA_WIDTH 1920 #define COLOR_CAMERA_HEIGHT 1080 #define COLOR_CAMERA_RESOLUTION (COLOR_CAMERA_WIDTH * COLOR_CAMERA_HEIGHT) #define COLOR_CAMERA_IMAGE_SIZE (COLOR_CAMERA_RESOLUTION * 3) /** * OpenGL offsets */ #define BUFFER_OFFSET(offset) ((char*)NULL + (offset)) #define BUFFER_SIZE(size) ((GLsizeiptr)((char*)NULL + size)) /** * Useful functions */ #define NOT_ZERO(P) (((P)[0] + (P)[1] + (P)[2]) != 0.0f) #define CLAMP(x, a, b) (x < a ? a : (x > b ? b : x)) #define SWAP_POINTERS(p1, p2) swap_pointers((void**)p1, (void**)p2) /** * Helper functions to generate an Android log */ # define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)) # define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)) # define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)) # define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)) #define DEBUG_GL #ifdef DEBUG_GL #define __glcall__(P) P; checkGLError(#P) #else #define __glcall__(P) P #endif // --------------------------------------------------------------------------------------------- __BEGIN_DECLS /** * * @param message * @param error_id */ extern void checkCLError(const char *message, const cl_int error_id); /** * Check the last OpenGL error and displays the associated message * @param message Any message we want to associate with the error checking. */ extern void checkGLError(const char *message); /** * Check the last OpenGl framebuffer status and displays the associated message. * @param message Any message we want to associate with the framebuffer checking. */ extern void checkFrameBufferCompleteness(const char *message); /** * Perform a swap between two pointers . The swap is performed atomically so it can be used * to swap data between different threads. * @param p1 * @param p2 */ static inline void swap_pointers(void **p1, void **p2) { void *tmp; // = *p1; #pragma omp atomic read tmp = *p1; #pragma omp atomic capture { *p1 = *p2; *p2 = tmp; } } __END_DECLS #endif // OPENINGS_GLOBAL_H <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #ifndef OPENINGS_GL_CONTEXT_H #define OPENINGS_GL_CONTEXT_H #include <stdint.h> #include <stdlib.h> #include <android/native_window.h> #include <EGL/egl.h> #include <EGL/eglext.h> #include "gl_computing/gl_computing.h" #include "gl/gl_31_functions.h" #include "global/global.h" #include "model/model.h" #include "rendering/rendering.h" __BEGIN_DECLS extern void gl_context_create(struct ANativeWindow *window); extern void gl_context_bind(); extern void gl_context_unbind(); #if (USE_OPENCL == 0) extern void gl_context_init_computing(struct compute_data *data); extern void gl_context_update_computing(struct compute_data *data); extern void gl_context_perform_computing(struct compute_data *data); extern void gl_context_destroy_computing(struct compute_data *data); #endif extern void gl_context_init_frame(struct display_data *data); extern void gl_context_update_frame(struct display_data *data); extern void gl_context_clear_frame(struct display_data *data); extern void gl_context_resize_frame(struct display_data *data); extern void gl_context_draw_frame(struct display_data *data); extern void gl_context_destroy_frame(struct display_data *data); extern void gl_context_destroy(); __END_DECLS #endif // OPENINGS_GL_CONTEXT_H <file_sep>/* * Copyright (c) 2018. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package limsi.fr.openings; import android.content.Context; import android.hardware.Camera; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.io.IOException; public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback { private Camera _camera; private SurfaceHolder _holder; public CameraSurfaceView(Context context, Camera camera) { super(context); _camera = camera; _holder = getHolder(); _holder.addCallback(this); } @Override public void onPreviewFrame(byte[] img, Camera camera) { nativeSetImage(img, camera.getParameters().getPreviewSize().width, camera.getParameters().getPreviewSize().height); } @Override public void surfaceCreated(SurfaceHolder holder) { Log.d("CameraSurfaceView", "Surface created"); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.d("CameraSurfaceView", "Surface changed"); if (holder.getSurface() == null) { return; } try { _camera.stopPreview(); } catch (Exception e) { } try { _camera.setPreviewDisplay(holder); _camera.setPreviewCallback(this); _camera.startPreview(); } catch (IOException e) { Log.e("CameraSurfaceView", e.getMessage()); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { } private static native void nativeSetImage(byte img[], int width, int height); } <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "cl_grayscale.h" static struct compute_info _info; static GLuint _output_texture_id; static float _input_image[3][COLOR_CAMERA_RESOLUTION]; static float _output_image[4 * COLOR_CAMERA_RESOLUTION]; static cl_program _program; static cl_mem _input_red_image_id; static cl_mem _input_green_image_id; static cl_mem _input_blue_image_id; static cl_mem _output_image_id; static cl_image_format _input_format = { .image_channel_order = CL_R, .image_channel_data_type = CL_FLOAT }; static cl_image_desc _input_description = { .image_type = CL_MEM_OBJECT_IMAGE2D, .image_width = COLOR_CAMERA_WIDTH, .image_height = COLOR_CAMERA_HEIGHT, .image_array_size = 0, .image_row_pitch = 0, .image_slice_pitch = 0, .num_mip_levels = 0, .num_samples = 0, .buffer = NULL }; static cl_image_format _output_format = { .image_channel_order = CL_RGBA, .image_channel_data_type = CL_FLOAT }; static cl_image_desc _output_description = { .image_type = CL_MEM_OBJECT_IMAGE2D, .image_width = COLOR_CAMERA_WIDTH, .image_height = COLOR_CAMERA_HEIGHT, .image_array_size = 0, .image_row_pitch = 0, .image_slice_pitch = 0, .num_mip_levels = 0, .num_samples = 0, .buffer = NULL }; void grayscale_init(struct compute_info *info, const GLuint output_texture) { memset(_input_image[0], 0, COLOR_CAMERA_RESOLUTION * sizeof(float)); memset(_input_image[1], 0, COLOR_CAMERA_RESOLUTION * sizeof(float)); memset(_input_image[2], 0, COLOR_CAMERA_RESOLUTION * sizeof(float)); memcpy(&_info, info, sizeof(struct compute_info)); _output_texture_id = output_texture; _program = kernel_create_program(_info.context, &(_info.device_id), grayscale_kernel_source); _input_red_image_id = clCreateImage ( _info.context, CL_MEM_READ_ONLY, &_input_format, &_input_description, NULL, NULL ); _input_green_image_id = clCreateImage ( _info.context, CL_MEM_READ_ONLY, &_input_format, &_input_description, NULL, NULL ); _input_blue_image_id = clCreateImage ( _info.context, CL_MEM_READ_ONLY, &_input_format, &_input_description, NULL, NULL ); _output_image_id = clCreateFromGLTexture ( _info.context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, _output_texture_id, NULL ); } void grayscale_set_input_image(const float *img) { size_t i; size_t index = 0; for (i = 0; i < COLOR_CAMERA_RESOLUTION; i++) { _input_image[0][i] = img[index++]; _input_image[1][i] = img[index++]; _input_image[2][i] = img[index++]; } // Update CL objects cl_int err; size_t img_index[3] = {0, 0, 0}; size_t img_region[3] = {COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT, 1}; err = clEnqueueWriteImage ( _info.command_queue, _input_red_image_id, CL_FALSE, img_index, img_region, 0, 0, _input_image[0], NULL, 0, NULL ); err = clEnqueueWriteImage ( _info.command_queue, _input_green_image_id, CL_FALSE, img_index, img_region, 0, 0, _input_image[1], NULL, 0, NULL ); err = clEnqueueWriteImage ( _info.command_queue, _input_blue_image_id, CL_FALSE, img_index, img_region, 0, 0, _input_image[2], NULL, 0, NULL ); // Wait for all commands to finish err = clEnqueueBarrierWithWaitList ( _info.command_queue, 0, NULL, NULL ); } void grayscale_compute() { cl_int err; const size_t img_origin[3] = {0, 0, 0}; const size_t img_region[3] = {COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT, 1}; cl_kernel kernel = clCreateKernel(_program, "img_grayscale", NULL); err = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *) &_input_red_image_id); err = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *) &_input_green_image_id); err = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *) &_input_blue_image_id); err = clSetKernelArg(kernel, 3, sizeof(cl_mem), (void *) &_output_image_id); // Dispatch the computing size_t global_item_size[2] = {COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT}; size_t local_item_size[2] = {960, 1}; clEnqueueAcquireGLObjects(_info.command_queue, 1, &(_output_image_id), 0, 0, NULL); err = clEnqueueNDRangeKernel ( _info.command_queue, kernel, 2, NULL, global_item_size, local_item_size, NULL, 0, NULL ); clFinish(_info.command_queue); clEnqueueReleaseGLObjects(_info.command_queue, 1, &_output_image_id, 0, 0, NULL); } void grayscale_destroy() { clReleaseMemObject(_input_red_image_id); clReleaseMemObject(_input_green_image_id); clReleaseMemObject(_input_blue_image_id); clReleaseMemObject(_output_image_id); clReleaseProgram(_program); }<file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #ifndef OPENINGS_GL_FUNCTIONS_H #define OPENINGS_GL_FUNCTIONS_H /** * @brief Manual loading of the OpenGL 3.1 features, that are not included in the Android NDK * libGLESv3.so. Use it as a complement. */ #include <EGL/egl.h> #include <GLES3/gl3.h> #ifndef APIENTRY #define APIENTRY #endif #ifndef APIENTRYP #define APIENTRYP APIENTRY * #endif #ifndef GLAPIENTRY #define GLAPIENTRY APIENTRY #endif #ifndef GL_ES_VERSION_3_1 #define GL_ES_VERSION_3_1 1 #endif #define GL_COMPUTE_SHADER 0x91B9 #define GL_MAX_COMPUTE_UNIFORM_BLOCKS 0x91BB #define GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS 0x91BC #define GL_MAX_COMPUTE_IMAGE_UNIFORMS 0x91BD #define GL_MAX_COMPUTE_SHARED_MEMORY_SIZE 0x8262 #define GL_MAX_COMPUTE_UNIFORM_COMPONENTS 0x8263 #define GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS 0x8264 #define GL_MAX_COMPUTE_ATOMIC_COUNTERS 0x8265 #define GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS 0x8266 #define GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS 0x90EB #define GL_MAX_COMPUTE_WORK_GROUP_COUNT 0x91BE #define GL_MAX_COMPUTE_WORK_GROUP_SIZE 0x91BF #define GL_COMPUTE_WORK_GROUP_SIZE 0x8267 #define GL_DISPATCH_INDIRECT_BUFFER 0x90EE #define GL_DISPATCH_INDIRECT_BUFFER_BINDING 0x90EF #define GL_COMPUTE_SHADER_BIT 0x00000020 #define GL_DRAW_INDIRECT_BUFFER 0x8F3F #define GL_DRAW_INDIRECT_BUFFER_BINDING 0x8F43 #define GL_MAX_UNIFORM_LOCATIONS 0x826E #define GL_FRAMEBUFFER_DEFAULT_WIDTH 0x9310 #define GL_FRAMEBUFFER_DEFAULT_HEIGHT 0x9311 #define GL_FRAMEBUFFER_DEFAULT_SAMPLES 0x9313 #define GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS 0x9314 #define GL_MAX_FRAMEBUFFER_WIDTH 0x9315 #define GL_MAX_FRAMEBUFFER_HEIGHT 0x9316 #define GL_MAX_FRAMEBUFFER_SAMPLES 0x9318 #define GL_UNIFORM 0x92E1 #define GL_UNIFORM_BLOCK 0x92E2 #define GL_PROGRAM_INPUT 0x92E3 #define GL_PROGRAM_OUTPUT 0x92E4 #define GL_BUFFER_VARIABLE 0x92E5 #define GL_SHADER_STORAGE_BLOCK 0x92E6 #define GL_ATOMIC_COUNTER_BUFFER 0x92C0 #define GL_TRANSFORM_FEEDBACK_VARYING 0x92F4 #define GL_ACTIVE_RESOURCES 0x92F5 #define GL_MAX_NAME_LENGTH 0x92F6 #define GL_MAX_NUM_ACTIVE_VARIABLES 0x92F7 #define GL_NAME_LENGTH 0x92F9 #define GL_TYPE 0x92FA #define GL_ARRAY_SIZE 0x92FB #define GL_OFFSET 0x92FC #define GL_BLOCK_INDEX 0x92FD #define GL_ARRAY_STRIDE 0x92FE #define GL_MATRIX_STRIDE 0x92FF #define GL_IS_ROW_MAJOR 0x9300 #define GL_ATOMIC_COUNTER_BUFFER_INDEX 0x9301 #define GL_BUFFER_BINDING 0x9302 #define GL_BUFFER_DATA_SIZE 0x9303 #define GL_NUM_ACTIVE_VARIABLES 0x9304 #define GL_ACTIVE_VARIABLES 0x9305 #define GL_REFERENCED_BY_VERTEX_SHADER 0x9306 #define GL_REFERENCED_BY_FRAGMENT_SHADER 0x930A #define GL_REFERENCED_BY_COMPUTE_SHADER 0x930B #define GL_TOP_LEVEL_ARRAY_SIZE 0x930C #define GL_TOP_LEVEL_ARRAY_STRIDE 0x930D #define GL_LOCATION 0x930E #define GL_VERTEX_SHADER_BIT 0x00000001 #define GL_FRAGMENT_SHADER_BIT 0x00000002 #define GL_ALL_SHADER_BITS 0xFFFFFFFF #define GL_PROGRAM_SEPARABLE 0x8258 #define GL_ACTIVE_PROGRAM 0x8259 #define GL_PROGRAM_PIPELINE_BINDING 0x825A #define GL_ATOMIC_COUNTER_BUFFER_BINDING 0x92C1 #define GL_ATOMIC_COUNTER_BUFFER_START 0x92C2 #define GL_ATOMIC_COUNTER_BUFFER_SIZE 0x92C3 #define GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS 0x92CC #define GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS 0x92D0 #define GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS 0x92D1 #define GL_MAX_VERTEX_ATOMIC_COUNTERS 0x92D2 #define GL_MAX_FRAGMENT_ATOMIC_COUNTERS 0x92D6 #define GL_MAX_COMBINED_ATOMIC_COUNTERS 0x92D7 #define GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE 0x92D8 #define GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS 0x92DC #define GL_ACTIVE_ATOMIC_COUNTER_BUFFERS 0x92D9 #define GL_UNSIGNED_INT_ATOMIC_COUNTER 0x92DB #define GL_MAX_IMAGE_UNITS 0x8F38 #define GL_MAX_VERTEX_IMAGE_UNIFORMS 0x90CA #define GL_MAX_FRAGMENT_IMAGE_UNIFORMS 0x90CE #define GL_MAX_COMBINED_IMAGE_UNIFORMS 0x90CF #define GL_IMAGE_BINDING_NAME 0x8F3A #define GL_IMAGE_BINDING_LEVEL 0x8F3B #define GL_IMAGE_BINDING_LAYERED 0x8F3C #define GL_IMAGE_BINDING_LAYER 0x8F3D #define GL_IMAGE_BINDING_ACCESS 0x8F3E #define GL_IMAGE_BINDING_FORMAT 0x906E #define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 #define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 #define GL_UNIFORM_BARRIER_BIT 0x00000004 #define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 #define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 #define GL_COMMAND_BARRIER_BIT 0x00000040 #define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 #define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 #define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 #define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 #define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 #define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 #define GL_ALL_BARRIER_BITS 0xFFFFFFFF #define GL_IMAGE_2D 0x904D #define GL_IMAGE_3D 0x904E #define GL_IMAGE_CUBE 0x9050 #define GL_IMAGE_2D_ARRAY 0x9053 #define GL_INT_IMAGE_2D 0x9058 #define GL_INT_IMAGE_3D 0x9059 #define GL_INT_IMAGE_CUBE 0x905B #define GL_INT_IMAGE_2D_ARRAY 0x905E #define GL_UNSIGNED_INT_IMAGE_2D 0x9063 #define GL_UNSIGNED_INT_IMAGE_3D 0x9064 #define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 #define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 #define GL_IMAGE_FORMAT_COMPATIBILITY_TYPE 0x90C7 #define GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE 0x90C8 #define GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS 0x90C9 #define GL_READ_ONLY 0x88B8 #define GL_WRITE_ONLY 0x88B9 #define GL_READ_WRITE 0x88BA #define GL_SHADER_STORAGE_BUFFER 0x90D2 #define GL_SHADER_STORAGE_BUFFER_BINDING 0x90D3 #define GL_SHADER_STORAGE_BUFFER_START 0x90D4 #define GL_SHADER_STORAGE_BUFFER_SIZE 0x90D5 #define GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS 0x90D6 #define GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS 0x90DA #define GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS 0x90DB #define GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS 0x90DC #define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS 0x90DD #define GL_MAX_SHADER_STORAGE_BLOCK_SIZE 0x90DE #define GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT 0x90DF #define GL_SHADER_STORAGE_BARRIER_BIT 0x00002000 #define GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES 0x8F39 #define GL_DEPTH_STENCIL_TEXTURE_MODE 0x90EA #define GL_STENCIL_INDEX 0x1901 #define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5E #define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5F #define GL_SAMPLE_POSITION 0x8E50 #define GL_SAMPLE_MASK 0x8E51 #define GL_SAMPLE_MASK_VALUE 0x8E52 #define GL_TEXTURE_2D_MULTISAMPLE 0x9100 #define GL_MAX_SAMPLE_MASK_WORDS 0x8E59 #define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E #define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F #define GL_MAX_INTEGER_SAMPLES 0x9110 #define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104 #define GL_TEXTURE_SAMPLES 0x9106 #define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107 #define GL_TEXTURE_WIDTH 0x1000 #define GL_TEXTURE_HEIGHT 0x1001 #define GL_TEXTURE_DEPTH 0x8071 #define GL_TEXTURE_INTERNAL_FORMAT 0x1003 #define GL_TEXTURE_RED_SIZE 0x805C #define GL_TEXTURE_GREEN_SIZE 0x805D #define GL_TEXTURE_BLUE_SIZE 0x805E #define GL_TEXTURE_ALPHA_SIZE 0x805F #define GL_TEXTURE_DEPTH_SIZE 0x884A #define GL_TEXTURE_STENCIL_SIZE 0x88F1 #define GL_TEXTURE_SHARED_SIZE 0x8C3F #define GL_TEXTURE_RED_TYPE 0x8C10 #define GL_TEXTURE_GREEN_TYPE 0x8C11 #define GL_TEXTURE_BLUE_TYPE 0x8C12 #define GL_TEXTURE_ALPHA_TYPE 0x8C13 #define GL_TEXTURE_DEPTH_TYPE 0x8C16 #define GL_TEXTURE_COMPRESSED 0x86A1 #define GL_SAMPLER_2D_MULTISAMPLE 0x9108 #define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 #define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A #define GL_VERTEX_ATTRIB_BINDING 0x82D4 #define GL_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D5 #define GL_VERTEX_BINDING_DIVISOR 0x82D6 #define GL_VERTEX_BINDING_OFFSET 0x82D7 #define GL_VERTEX_BINDING_STRIDE 0x82D8 #define GL_VERTEX_BINDING_BUFFER 0x8F4F #define GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D9 #define GL_MAX_VERTEX_ATTRIB_BINDINGS 0x82DA #define GL_MAX_VERTEX_ATTRIB_STRIDE 0x82E5 // OpenGL functions names #define glDispatchCompute __glDispatchCompute #define glDispatchComputeIndirect __glDispatchComputeIndirect #define glDrawArraysIndirect __glDrawArraysIndirect #define glDrawElementsIndirect __glDrawElementsIndirect #define glFramebufferParameteri __glFramebufferParameteri #define glGetFramebufferParameteri __glGetFramebufferParameteri #define glGetProgramInterface __glGetProgramInterface #define glGetProgramSourceIndex __glGetProgramSourceIndex #define glGetProgramResourceName __glGetProgramResourceName #define glGetProgramResourceiv __glGetProgramResourceiv #define glGetProgramResourceLocation __glGetProgramResourceLocation #define glUseProgramStages __glUseProgramStages #define glActiveShaderProgram __glActiveShaderProgram #define glCreateSHaderProgram __glCreateSHaderProgram #define glBindProgramPipeline __glBindProgramPipeline #define glDeleteProgramPipeline __glDeleteProgramPipeline #define glGenProgramPipeline __glGenProgramPipeline #define glIsProgramPipeline __glIsProgramPipeline #define glGetProgramPipelineiv __glGetProgramPipelineiv #define glProgramUniform1i __glProgramUniform1i #define glProgramUniform2i __glProgramUniform2i #define glProgramUniform3i __glProgramUniform3i #define glProgramUniform4i __glProgramUniform4i #define glProgramUniform1ui __glProgramUniform1ui #define glProgramUniform2ui __glProgramUniform2ui #define glProgramUniform3ui __glProgramUniform3ui #define glProgramUniform4ui __glProgramUniform4ui #define glProgramUniform1f __glProgramUniform1f #define glProgramUniform2f __glProgramUniform2f #define glProgramUniform3f __glProgramUniform3f #define glProgramUniform4f __glProgramUniform4f #define glProgramUniform1iv __glProgramUniform1iv #define glProgramUniform2iv __glProgramUniform2iv #define glProgramUniform3iv __glProgramUniform3iv #define glProgramUniform4iv __glProgramUniform4iv #define glProgramUniform1uiv __glProgramUniform1uiv #define glProgramUniform2uiv __glProgramUniform2uiv #define glProgramUniform3uiv __glProgramUniform3uiv #define glProgramUniform4uiv __glProgramUniform4uiv #define glProgramUniform1fv __glProgramUniform1fv #define glProgramUniform2fv __glProgramUniform2fv #define glProgramUniform3fv __glProgramUniform3fv #define glProgramUniform4fv __glProgramUniform4fv #define glProgramUniformMatrix2fv __glProgramUniformMatrix2fv #define glProgramUniformMatrix3fv __glProgramUniformMatrix3fv #define glProgramUniformMatrix4fv __glProgramUniformMatrix4fv #define glProgramUniformMatrix2x3fv __glProgramUniformMatrix2x3fv #define glProgramUniformMatrix3x2fv __glProgramUniformMatrix3x2fv #define glProgramUniformMatrix2x4fv __glProgramUniformMatrix2x4fv #define glProgramUniformMatrix4x2fv __glProgramUniformMatrix4x2fv #define glProgramUniformMatrix3x4fv __glProgramUniformMatrix3x4fv #define glProgramUniformMatrix4x3fv __glProgramUniformMatrix4x3fv #define glValidateProgramPipeline __glValidateProgramPipeline #define glGetProgramPipelineInfoLog __glGetProgramPipelineInfoLog #define glBindImageTexture __glBindImageTexture #define glGetBooleani_v __glGetBooleani_v #define glMemoryBarrier __glMemoryBarrier #define glMemoryBarrierByRegion __glMemoryBarrierByRegion #define glTexStorage2DMultiSample __glTexStorage2DMultiSample #define glGetMultisamplefv __glGetMultisamplefv #define glSampleMaski __glSampleMaski #define glGetTexLevelParameteriv __glGetTexLevelParameteriv #define glGetTexLevelParameterfv __glGetTexLevelParameterfv #define glBindVertexBuffer __glBindVertexBuffer #define glVertexAttribFormat __glVertexAttribFormat #define glVertexAttribIFormatProc __glVertexAttribIFormatProc #define glVertexAttribBinding __glVertexAttribBinding #define glVertexBindingDivisor __glVertexBindingDivisor // ------------------------------------------------------------------------------------------------- __BEGIN_DECLS typedef void (GL_APIENTRYP PFNGLDISPATCHCOMPUTEPROC) ( GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z ); typedef void (GL_APIENTRYP PFNGLDISPATCHCOMPUTEINDIRECTPROC)(GLintptr indirect); typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINDIRECTPROC)(GLenum mode, const void *indirect); typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINDIRECTPROC) ( GLenum mode, GLenum type, const void *indirect ); typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERPARAMETERIPROC) ( GLenum target, GLenum pname, GLint param ); typedef void (GL_APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVPROC) ( GLenum target, GLenum pname, GLint *params ); typedef void (GL_APIENTRYP PFNGLGETPROGRAMINTERFACEIVPROC) ( GLuint program, GLenum programInterface, GLenum pname, GLint *params ); typedef GLuint (GL_APIENTRYP PFNGLGETPROGRAMRESOURCEINDEXPROC) ( GLuint program, GLenum programInterface, const GLchar *name ); typedef void (GL_APIENTRYP PFNGLGETPROGRAMRESOURCENAMEPROC) ( GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name ); typedef void (GL_APIENTRYP PFNGLGETPROGRAMRESOURCEIVPROC) ( GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLint *params); typedef GLint (GL_APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONPROC) ( GLuint program, GLenum programInterface, const GLchar *name ); typedef void (GL_APIENTRYP PFNGLUSEPROGRAMSTAGESPROC) ( GLuint pipeline, GLbitfield stages, GLuint program ); typedef void (GL_APIENTRYP PFNGLACTIVESHADERPROGRAMPROC)(GLuint pipeline, GLuint program); typedef GLuint (GL_APIENTRYP PFNGLCREATESHADERPROGRAMVPROC) ( GLenum type, GLsizei count, const GLchar *const *strings ); typedef void (GL_APIENTRYP PFNGLBINDPROGRAMPIPELINEPROC)(GLuint pipeline); typedef void (GL_APIENTRYP PFNGLDELETEPROGRAMPIPELINESPROC)(GLsizei n, const GLuint *pipelines); typedef void (GL_APIENTRYP PFNGLGENPROGRAMPIPELINESPROC)(GLsizei n, GLuint *pipelines); typedef GLboolean (GL_APIENTRYP PFNGLISPROGRAMPIPELINEPROC)(GLuint pipeline); typedef void (GL_APIENTRYP PFNGLGETPROGRAMPIPELINEIVPROC) ( GLuint pipeline, GLenum pname, GLint *params ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1IPROC) ( GLuint program, GLint location, GLint v0 ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2IPROC) ( GLuint program, GLint location, GLint v0, GLint v1 ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3IPROC) ( GLuint program, GLint location, GLint v0, GLint v1, GLint v2 ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4IPROC) ( GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3 ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1UIPROC) ( GLuint program, GLint location, GLuint v0 ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2UIPROC) ( GLuint program, GLint location, GLuint v0, GLuint v1 ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3UIPROC) ( GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2 ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4UIPROC) ( GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3 ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1FPROC) ( GLuint program, GLint location, GLfloat v0 ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2FPROC) ( GLuint program, GLint location, GLfloat v0, GLfloat v1 ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3FPROC) ( GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2 ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4FPROC) ( GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3 ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1IVPROC) ( GLuint program, GLint location, GLsizei count, const GLint *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2IVPROC) ( GLuint program, GLint location, GLsizei count, const GLint *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3IVPROC) ( GLuint program, GLint location, GLsizei count, const GLint *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4IVPROC) ( GLuint program, GLint location, GLsizei count, const GLint *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1UIVPROC) ( GLuint program, GLint location, GLsizei count, const GLuint *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3UIVPROC) ( GLuint program, GLint location, GLsizei count, const GLuint *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4UIVPROC) ( GLuint program, GLint location, GLsizei count, const GLuint *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1FVPROC) ( GLuint program, GLint location, GLsizei count, const GLfloat *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2FVPROC) ( GLuint program, GLint location, GLsizei count, const GLfloat *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3FVPROC) ( GLuint program, GLint location, GLsizei count, const GLfloat *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4FVPROC) ( GLuint program, GLint location, GLsizei count, const GLfloat *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVPROC) ( GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVPROC) ( GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVPROC) ( GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC) ( GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC) ( GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC) ( GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC) ( GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC) ( GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value ); typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC) ( GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value ); typedef void (GL_APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEPROC)(GLuint pipeline); typedef void (GL_APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGPROC) ( GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog ); typedef void (GL_APIENTRYP PFNGLBINDIMAGETEXTUREPROC) ( GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format ); typedef void (GL_APIENTRYP PFNGLGETBOOLEANI_VPROC)(GLenum target, GLuint index, GLboolean *data); typedef void (GL_APIENTRYP PFNGLMEMORYBARRIERPROC)(GLbitfield barriers); typedef void (GL_APIENTRYP PFNGLMEMORYBARRIERBYREGIONPROC)(GLbitfield barriers); typedef void (GL_APIENTRYP PFNGLTEXSTORAGE2DMULTISAMPLEPROC) ( GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations ); typedef void (GL_APIENTRYP PFNGLGETMULTISAMPLEFVPROC)(GLenum pname, GLuint index, GLfloat *val); typedef void (GL_APIENTRYP PFNGLSAMPLEMASKIPROC)(GLuint maskNumber, GLbitfield mask); typedef void (GL_APIENTRYP PFNGLGETTEXLEVELPARAMETERIVPROC) ( GLenum target, GLint level, GLenum pname, GLint *params ); typedef void (GL_APIENTRYP PFNGLGETTEXLEVELPARAMETERFVPROC) ( GLenum target, GLint level, GLenum pname, GLfloat *params ); typedef void (GL_APIENTRYP PFNGLBINDVERTEXBUFFERPROC) ( GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride ); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBFORMATPROC) ( GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset ); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBIFORMATPROC) ( GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset ); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBBINDINGPROC)(GLuint attribindex, GLuint bindingindex); typedef void (GL_APIENTRYP PFNGLVERTEXBINDINGDIVISORPROC)(GLuint bindingindex, GLuint divisor); // ------------------------------------------------------------------------------------------------- /** * Loads the OpenGLES 3.1 function pointers */ extern void gl_functions_load(); extern PFNGLDISPATCHCOMPUTEPROC __glDispatchCompute; extern PFNGLDISPATCHCOMPUTEINDIRECTPROC __glDispatchComputeIndirect; extern PFNGLDRAWARRAYSINDIRECTPROC __glDrawArraysIndirect; extern PFNGLDRAWELEMENTSINDIRECTPROC __glDrawElementsIndirect; extern PFNGLFRAMEBUFFERPARAMETERIPROC __glFramebufferParameteri; extern PFNGLGETFRAMEBUFFERPARAMETERIVPROC __glGetFramebufferParameteri; extern PFNGLGETPROGRAMINTERFACEIVPROC __glGetProgramInterface; extern PFNGLGETPROGRAMRESOURCEINDEXPROC __glGetProgramSourceIndex; extern PFNGLGETPROGRAMRESOURCENAMEPROC __glGetProgramResourceName; extern PFNGLGETPROGRAMRESOURCEIVPROC __glGetProgramResourceiv; extern PFNGLGETPROGRAMRESOURCELOCATIONPROC __glGetProgramResourceLocation; extern PFNGLUSEPROGRAMSTAGESPROC __glUseProgramStages; extern PFNGLACTIVESHADERPROGRAMPROC __glActiveShaderProgram; extern PFNGLCREATESHADERPROGRAMVPROC __glCreateShaderProgram; extern PFNGLBINDPROGRAMPIPELINEPROC __glBindProgramPipeline; extern PFNGLDELETEPROGRAMPIPELINESPROC __glDeleteProgramPipeline; extern PFNGLGENPROGRAMPIPELINESPROC __glGenProgramPipeline; extern PFNGLISPROGRAMPIPELINEPROC __glIsProgramPipeline; extern PFNGLGETPROGRAMPIPELINEIVPROC __glGetProgramPipelineiv; extern PFNGLPROGRAMUNIFORM1IPROC __glProgramUniform1i; extern PFNGLPROGRAMUNIFORM2IPROC __glProgramUniform2i; extern PFNGLPROGRAMUNIFORM3IPROC __glProgramUniform3i; extern PFNGLPROGRAMUNIFORM4IPROC __glProgramUniform4i; extern PFNGLPROGRAMUNIFORM1UIPROC __glProgramUniform1ui; extern PFNGLPROGRAMUNIFORM2UIPROC __glProgramUniform2ui; extern PFNGLPROGRAMUNIFORM3UIPROC __glProgramUniform3ui; extern PFNGLPROGRAMUNIFORM4UIPROC __glProgramUniform4ui; extern PFNGLPROGRAMUNIFORM1FPROC __glProgramUniform1f; extern PFNGLPROGRAMUNIFORM2FPROC __glProgramUniform2f; extern PFNGLPROGRAMUNIFORM3FPROC __glProgramUniform3f; extern PFNGLPROGRAMUNIFORM4FPROC __glProgramUniform4f; extern PFNGLPROGRAMUNIFORM1IVPROC __glProgramUniform1iv; extern PFNGLPROGRAMUNIFORM2IVPROC __glProgramUniform2iv; extern PFNGLPROGRAMUNIFORM3IVPROC __glProgramUniform3iv; extern PFNGLPROGRAMUNIFORM4IVPROC __glProgramUniform4iv; extern PFNGLPROGRAMUNIFORM1UIVPROC __glProgramUniform1uiv; extern PFNGLPROGRAMUNIFORM2UIVPROC __glProgramUniform2uiv; extern PFNGLPROGRAMUNIFORM3UIVPROC __glProgramUniform3uiv; extern PFNGLPROGRAMUNIFORM4UIVPROC __glProgramUniform4uiv; extern PFNGLPROGRAMUNIFORM1FVPROC __glProgramUniform1fv; extern PFNGLPROGRAMUNIFORM2FVPROC __glProgramUniform2fv; extern PFNGLPROGRAMUNIFORM3FVPROC __glProgramUniform3fv; extern PFNGLPROGRAMUNIFORM4FVPROC __glProgramUniform4fv; extern PFNGLPROGRAMUNIFORMMATRIX2FVPROC __glProgramUniformMatrix2fv; extern PFNGLPROGRAMUNIFORMMATRIX3FVPROC __glProgramUniformMatrix3fv; extern PFNGLPROGRAMUNIFORMMATRIX4FVPROC __glProgramUniformMatrix4fv; extern PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC __glProgramUniformMatrix2x3fv; extern PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC __glProgramUniformMatrix3x2fv; extern PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC __glProgramUniformMatrix2x4fv; extern PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC __glProgramUniformMatrix4x2fv; extern PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC __glProgramUniformMatrix3x4fv; extern PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC __glProgramUniformMatrix4x3fv; extern PFNGLVALIDATEPROGRAMPIPELINEPROC __glValidateProgramPipeline; extern PFNGLGETPROGRAMPIPELINEINFOLOGPROC __glGetProgramPipelineInfoLog; extern PFNGLBINDIMAGETEXTUREPROC __glBindImageTexture; extern PFNGLGETBOOLEANI_VPROC __glGetBooleani_v; extern PFNGLMEMORYBARRIERPROC __glMemoryBarrier; extern PFNGLMEMORYBARRIERBYREGIONPROC __glMemoryBarrierByRegion; extern PFNGLTEXSTORAGE2DMULTISAMPLEPROC __glTexStorage2DMultiSample; extern PFNGLGETMULTISAMPLEFVPROC __glGetMultisamplefv; extern PFNGLSAMPLEMASKIPROC __glSampleMaski; extern PFNGLGETTEXLEVELPARAMETERIVPROC __glGetTexLevelParameteriv; extern PFNGLGETTEXLEVELPARAMETERFVPROC __glGetTexLevelParameterfv; extern PFNGLBINDVERTEXBUFFERPROC __glBindVertexBuffer; extern PFNGLVERTEXATTRIBFORMATPROC __glVertexAttribFormat; extern PFNGLVERTEXATTRIBIFORMATPROC __glVertexAttribIFormatProc; extern PFNGLVERTEXATTRIBBINDINGPROC __glVertexAttribBinding; extern PFNGLVERTEXBINDINGDIVISORPROC __glVertexBindingDivisor; __END_DECLS #endif // OPENINGS_GL_31_FUNCTIONS_H <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "gl_thread.h" static struct compute_data _compute_data; static struct compute_data *_compute_data_ptr; static struct display_data _display_data; static struct display_data *_display_data_ptr; static pthread_t _gl_thread; static uint8_t _status; static uint8_t _stopped; // ----------------------------------------------------------------------------------------- static void *__gl_thread_main_loop(void *); static inline uint8_t __gl_thread__read_status() { uint8_t res; #pragma omp atomic capture { res = _status; _status = 0u; }; return res; } // ----------------------------------------------------------------------------------------- void gl_thread_set_flag(uint8_t flag) { #pragma omp atomic update _status |= flag; } void gl_thread_start(struct ANativeWindow *window) { _compute_data_ptr = &_compute_data; _display_data_ptr = &_display_data; #pragma omp atomic write _stopped = 0u; gl_context_create(window); if (pthread_create(&_gl_thread, NULL, &__gl_thread_main_loop, NULL)) { LOGE("Problem initializing the GL thread : %s", strerror(errno)); } } void gl_thread_stop() { #pragma omp atomic write _stopped = 1u; while (!(pthread_join(_gl_thread, NULL))) { LOGD("Stopping thread"); } gl_context_destroy(); } // ----------------------------------------------------------------------------------------- static void *__gl_thread_main_loop(void *context) { uint8_t status; uint8_t stopped; gl_context_bind(); gl_context_init_frame(_display_data_ptr); #if(USE_OPENCL == 0) gl_context_init_computing(_compute_data_ptr); #else cl_context_init_computing(_compute_data_ptr); #endif do { // Perform computings status = __gl_thread__read_status(); model_get_compute_data(&_compute_data_ptr); #if (USE_OPENCL == 0) if (status & GL_THREAD_COMPUTE_UPDATE_REQUEST) gl_context_update_computing(_compute_data_ptr); if (status & GL_THREAD_COMPUTE_PERFORM_REQUEST) gl_context_perform_computing(_compute_data_ptr); #else if (status & GL_THREAD_COMPUTE_UPDATE_REQUEST) cl_context_update_computing(_compute_data_ptr); if (status & GL_THREAD_COMPUTE_PERFORM_REQUEST) cl_context_perform_computing(_compute_data_ptr); #endif // Perform drawings model_get_display_data(&_display_data_ptr); if (status & GL_THREAD_RENDER_CLEAR_REQUEST) gl_context_clear_frame(_display_data_ptr); if (status & GL_THREAD_RENDER_RESIZE_REQUEST) gl_context_resize_frame(_display_data_ptr); if (status & GL_THREAD_RENDER_UPDATE_REQUEST) gl_context_update_frame(_display_data_ptr); gl_context_draw_frame(_display_data_ptr); usleep(GL_THREAD_SLEEP_TIME); #pragma omp atomic read stopped = _stopped; } while (!stopped); #if (USE_OPENCL == 0) gl_context_destroy_computing(_compute_data_ptr); #else cl_context_destroy_computing(_compute_data_ptr); #endif gl_context_destroy_frame(_display_data_ptr); gl_context_unbind(); return NULL; }<file_sep>/* * Created by <NAME> on 4/27/18 8:38 AM. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package limsi.fr.openings; import android.app.Activity; import android.hardware.Camera; import android.os.Bundle; import android.widget.FrameLayout; /** * A basic activity that creates an UI with a NativeSurfaceView object and wraps all its * lifecycle ti native methods. */ public class MainActivity extends Activity { private Camera _camera; private CameraSurfaceView _cameraSurfaceView; private FrameLayout _cameraLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); _camera = Camera.open(); _cameraSurfaceView = new CameraSurfaceView(this, _camera); _cameraLayout = findViewById(R.id.camera_frame_layout); _cameraLayout.addView(_cameraSurfaceView); nativeOnCreate(); } @Override protected void onStart() { super.onStart(); nativeOnStart(); } @Override protected void onResume() { super.onResume(); nativeOnResume(); } @Override protected void onPause() { super.onPause(); nativeOnPause(); } @Override protected void onStop() { super.onStop(); nativeOnStop(); } @Override protected void onDestroy() { super.onDestroy(); nativeOnDestroy(); } /* * Native methods for all the activity's lifecycle */ private static native void nativeOnCreate(); private static native void nativeOnStart(); private static native void nativeOnResume(); private static native void nativeOnPause(); private static native void nativeOnStop(); private static native void nativeOnDestroy(); } <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "application.h" void application_create() { model_init(); } void application_init_window(struct ANativeWindow *window) { gl_thread_start(window); } void application_term_window() { gl_thread_stop(); } void application_destroy() { model_destroy(); } void application_pause() { } void application_resume() { } void application_start() { } void application_stop() { } void application_redraw_needed() { } void application_window_resized(int32_t width, int32_t height) { gl_thread_set_flag(GL_THREAD_RENDER_RESIZE_REQUEST); } <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define LINE_MAX_LENGTH 512 int main(int argc, char **argv) { char line[512]; FILE *file; size_t nb_read; printf("/*\n" " * Created by <NAME>\n" " *\n" " * This program is free software: you can redistribute it and/or modify\n" " * it under the terms of the GNU General Public License as published by\n" " * the Free Software Foundation, either version 3 of the License, or\n" " * (at your option) any later version.\n" " *\n" " * This program is distributed in the hope that it will be useful,\n" " * but WITHOUT ANY WARRANTY; without even the implied warranty of\n" " * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" " * GNU General Public License for more details.\n" " *\n" " * You should have received a copy of the GNU General Public License\n" " */\n\n"); printf("#ifndef __KERNEL_SOURCES_H\n" "#define __KERNEL_SOURCES_H\n\n"); for (int i = 1; i < argc; i++) { char filename[LINE_MAX_LENGTH]; char *tmp; sprintf(filename, "%s.cl", argv[i]); file = fopen(filename, "r"); printf("static const char *%s_source = \n", argv[i]); printf("\t{\n"); while (fgets(&line, LINE_MAX_LENGTH, file)) { tmp = strstr(line, "\n"); if (tmp != NULL) strncpy(tmp, "\0", 2); printf("\t\t\"%s\\n\"\n", line); } printf("\t};\n\n"); } printf("#endif // __KERNEL_SOURCES_H\n"); return 0; }<file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "conv3x3_f.h" static GLuint _conv3x3_f_compute_program_id; static GLuint _conv3x3_f_red_texture_id; static GLuint _conv3x3_f_green_texture_id; static GLuint _conv3x3_f_blue_texture_id; static GLuint _conv3x3_f_red_kernel_ubo_id; static GLuint _conv3x3_f_green_kernel_ubo_id; static GLuint _conv3x3_f_blue_kernel_ubo_id; void conv3x3_f_init() { // Image textures allocation glGenTextures(1, &_conv3x3_f_red_texture_id); glGenTextures(1, &_conv3x3_f_green_texture_id); glGenTextures(1, &_conv3x3_f_blue_texture_id); glBindTexture(GL_TEXTURE_2D, _conv3x3_f_red_texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT); glBindTexture(GL_TEXTURE_2D, _conv3x3_f_green_texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT); glBindTexture(GL_TEXTURE_2D, _conv3x3_f_blue_texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT); glBindTexture(GL_TEXTURE_2D, 0); // Kernels buffer allocation glGenBuffers(1, &_conv3x3_f_red_kernel_ubo_id); glGenBuffers(1, &_conv3x3_f_green_kernel_ubo_id); glGenBuffers(1, &_conv3x3_f_blue_kernel_ubo_id); glBindBuffer(GL_UNIFORM_BUFFER, _conv3x3_f_red_kernel_ubo_id); glBufferData ( GL_UNIFORM_BUFFER, (GLsizeiptr) (3 * 3 * sizeof(GLfloat)), NULL, GL_DYNAMIC_DRAW ); glBindBuffer(GL_UNIFORM_BUFFER, _conv3x3_f_green_kernel_ubo_id); glBufferData ( GL_UNIFORM_BUFFER, (GLsizeiptr) (3 * 3 * sizeof(GLfloat)), NULL, GL_DYNAMIC_DRAW ); glBindBuffer(GL_UNIFORM_BUFFER, _conv3x3_f_blue_kernel_ubo_id); glBufferData ( GL_UNIFORM_BUFFER, (GLsizeiptr) (3 * 3 * sizeof(GLfloat)), NULL, GL_DYNAMIC_DRAW ); glBindBuffer(GL_UNIFORM_BUFFER, 0); // Compute program creation _conv3x3_f_compute_program_id = shader_create_compute_program(CONV3X3_source); glUseProgram(_conv3x3_f_compute_program_id); glBindBufferBase(GL_UNIFORM_BUFFER, 0, _conv3x3_f_red_kernel_ubo_id); glBindBufferBase(GL_UNIFORM_BUFFER, 1, _conv3x3_f_green_kernel_ubo_id); glBindBufferBase(GL_UNIFORM_BUFFER, 2, _conv3x3_f_blue_kernel_ubo_id); glBindImageTexture(3, _conv3x3_f_red_texture_id, 0, GL_FALSE, 0, GL_READ_ONLY, GL_R32F); glBindImageTexture(4, _conv3x3_f_green_texture_id, 0, GL_FALSE, 0, GL_READ_ONLY, GL_R32F); glBindImageTexture(5, _conv3x3_f_blue_texture_id, 0, GL_FALSE, 0, GL_READ_ONLY, GL_R32F); glUseProgram(0); } void conv3x3_f_set_kernels(const float *kernels) { glBindBuffer(GL_UNIFORM_BUFFER, _conv3x3_f_red_kernel_ubo_id); glBufferSubData(GL_UNIFORM_BUFFER, 0, (GLsizeiptr) (3 * 3 * sizeof(GLfloat)), kernels); glBindBuffer(GL_UNIFORM_BUFFER, _conv3x3_f_green_kernel_ubo_id); glBufferSubData(GL_UNIFORM_BUFFER, 0, (GLsizeiptr) (3 * 3 * sizeof(GLfloat)), kernels + 9); glBindBuffer(GL_UNIFORM_BUFFER, _conv3x3_f_blue_kernel_ubo_id); glBufferSubData(GL_UNIFORM_BUFFER, 0, (GLsizeiptr) (3 * 3 * sizeof(GLfloat)), kernels + 18); glBindBuffer(GL_UNIFORM_BUFFER, 0); } void conv3x3_f_attach_rendering_texture(const GLuint tex) { glUseProgram(_conv3x3_f_compute_program_id); glBindImageTexture(6, tex, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F); glUseProgram(0); } void conv3x3_f_update(const float *red, const float *green, const float *blue) { glBindTexture(GL_TEXTURE_2D, _conv3x3_f_red_texture_id); glTexSubImage2D ( GL_TEXTURE_2D, 0, 0, 0, COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT, GL_RED, GL_FLOAT, red ); glBindTexture(GL_TEXTURE_2D, _conv3x3_f_green_texture_id); glTexSubImage2D ( GL_TEXTURE_2D, 0, 0, 0, COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT, GL_RED, GL_FLOAT, green ); glBindTexture(GL_TEXTURE_2D, _conv3x3_f_blue_texture_id); glTexSubImage2D ( GL_TEXTURE_2D, 0, 0, 0, COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT, GL_RED, GL_FLOAT, blue ); glMemoryBarrier(GL_TEXTURE_UPDATE_BARRIER_BIT); } void conv3x3_f_perform_compute() { glUseProgram(_conv3x3_f_compute_program_id); glDispatchCompute(COLOR_CAMERA_WIDTH, 2, 1); glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT); glUseProgram(0); } void conv3x3_f_destroy() { glDeleteBuffers(1, &_conv3x3_f_red_kernel_ubo_id); glDeleteBuffers(1, &_conv3x3_f_green_kernel_ubo_id); glDeleteBuffers(1, &_conv3x3_f_blue_kernel_ubo_id); glDeleteTextures(1, &_conv3x3_f_red_texture_id); glDeleteTextures(1, &_conv3x3_f_green_texture_id); glDeleteTextures(1, &_conv3x3_f_blue_texture_id); glDeleteProgram(_conv3x3_f_compute_program_id); }<file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "kernel.h" cl_program kernel_create_program ( cl_context context, cl_device_id *device, const char *source ) { cl_program res = NULL; cl_int err; cl_build_status status; char *info_log; size_t log_len; res = clCreateProgramWithSource ( context, 1, (const char **) &source, NULL, &err ); checkCLError("Creating cl program", err); if (err != CL_SUCCESS) { return NULL; } err = clBuildProgram(res, 1, device, NULL, NULL, NULL); err = clGetProgramBuildInfo ( res, *device, CL_PROGRAM_BUILD_STATUS, sizeof(cl_program_build_info), &status, &log_len ); if (status != CL_SUCCESS) { LOGE("OpenCL program building failed"); err = clGetProgramBuildInfo ( res, *device, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_len ); info_log = (char *) malloc(log_len); clGetProgramBuildInfo ( res, *device, CL_PROGRAM_BUILD_LOG, log_len, info_log, NULL ); LOGE("%s", info_log); free(info_log); clReleaseProgram(res); res = NULL; } return res; }<file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #ifndef OPENINGS_APPLICATION_H #define OPENINGS_APPLICATION_H /** * @brief Contains all the functions that handle the Android activity lifecycle. */ #include <stdlib.h> #include <string.h> #include <stdint.h> #include <omp.h> #include "global/global.h" #include "gl/gl_thread.h" #include "rendering/rendering.h" #include "gl_computing/gl_computing.h" __BEGIN_DECLS extern void application_create(); extern void application_init_window(struct ANativeWindow *window); extern void application_term_window(); extern void application_destroy(); extern void application_pause(); extern void application_resume(); extern void application_start(); extern void application_stop(); extern void application_redraw_needed(); extern void application_window_resized(int32_t width, int32_t height); __END_DECLS #endif // OPENINGS_APPLICATION_H <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <errno.h> #include <jni.h> #include <android/native_window.h> #include <android/native_window_jni.h> #include "global.h" #include "application.h" /** * This file contains the definition of all the native functions declared in the Java files. * These wrappers dispatch the Java calls into the associated native calls. */ __BEGIN_DECLS static struct compute_data _compute_data; static struct compute_data *_compute_data_ptr = &_compute_data; static void conversions_convert_YUV_to_RGB ( float *img, const uint8_t *yuv, const size_t width, const size_t height ); JNIEXPORT void JNICALL Java_limsi_fr_openings_MainActivity_nativeOnCreate(JNIEnv *env, jobject obj) { application_create(); } JNIEXPORT void JNICALL Java_limsi_fr_openings_MainActivity_nativeOnStart(JNIEnv *env, jobject obj) { application_start(); } JNIEXPORT void JNICALL Java_limsi_fr_openings_MainActivity_nativeOnResume(JNIEnv *env, jobject obj) { application_resume(); } JNIEXPORT void JNICALL Java_limsi_fr_openings_MainActivity_nativeOnPause(JNIEnv *env, jobject obj) { application_pause(); } JNIEXPORT void JNICALL Java_limsi_fr_openings_MainActivity_nativeOnStop(JNIEnv *env, jobject obj) { application_stop(); } JNIEXPORT void JNICALL Java_limsi_fr_openings_MainActivity_nativeOnDestroy(JNIEnv *env, jobject obj) { application_destroy(); } JNIEXPORT void JNICALL Java_limsi_fr_openings_NativeSurfaceView_nativeCreateSurface ( JNIEnv *env, jobject obj, jobject surface ) { struct ANativeWindow *window = ANativeWindow_fromSurface(env, surface); application_init_window(window); ANativeWindow_release(window); } JNIEXPORT void JNICALL Java_limsi_fr_openings_NativeSurfaceView_nativeResizeSurface ( JNIEnv *env, jobject obj, jobject surface, jint format, jint width, jint height ) { application_window_resized((int32_t) width, (int32_t) height); } JNIEXPORT void JNICALL Java_limsi_fr_openings_NativeSurfaceView_nativeDrawSurface ( JNIEnv *env, jobject obj, jobject surface ) { application_redraw_needed(); } JNIEXPORT void JNICALL Java_limsi_fr_openings_NativeSurfaceView_nativeDestroySurface ( JNIEnv *env, jobject obj, jobject surface ) { application_term_window(); } static uint8_t _img[COLOR_CAMERA_IMAGE_SIZE]; JNIEXPORT void JNICALL Java_limsi_fr_openings_CameraSurfaceView_nativeSetImage ( JNIEnv *env, jobject obj, jbyteArray img, jint width, jint height ) { jbyte *ptr = (*env)->GetByteArrayElements(env, img, NULL); jsize length = (*env)->GetArrayLength(env, img); conversions_convert_YUV_to_RGB(_compute_data_ptr->input_image, (uint8_t *) ptr, COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT); (*env)->ReleaseByteArrayElements(env, img, ptr, 0); model_set_compute_data(&_compute_data_ptr); gl_thread_set_flag(GL_THREAD_COMPUTE_UPDATE_REQUEST); gl_thread_set_flag(GL_THREAD_COMPUTE_PERFORM_REQUEST); gl_thread_set_flag(GL_THREAD_RENDER_UPDATE_REQUEST); } static void conversions_convert_YUV_to_RGB ( float *img, const uint8_t *yuv, const size_t width, const size_t height ) { const size_t frameSize = width * height; size_t a = 0; int y, u, v, r, g, b; size_t i, j; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { y = (0xff & ((int32_t) yuv[i * width + j])); v = (0xff & ((int32_t) yuv[frameSize + (i >> 1) * width + (j & ~1) + 0])); u = (0xff & ((int32_t) yuv[frameSize + (i >> 1) * width + (j & ~1) + 1])); y = y < 16 ? 16 : y; r = y + (int32_t) (1.370705f * (v - 128.)); g = y - (int32_t) (0.698001f * (v - 128.)) - (int32_t) (0.337633 * (u - 128.)); b = y + (int32_t) (1.732446f * (u - 128.)); r = r < 0 ? 0 : (r > 255 ? 255 : r); g = g < 0 ? 0 : (g > 255 ? 255 : g); b = b < 0 ? 0 : (b > 255 ? 255 : b); a = 3 * (i * width + j); img[a] = ((float) r / 255.0f); img[a + 1] = ((float) g / 255.0f); img[a + 2] = ((float) b / 255.0f); } } } __END_DECLS <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "layer3x3x64_f.h" static GLuint _layer3x3x64_f_compute_program_id; static GLuint _layer3x3x64_f_red_texture_id; static GLuint _layer3x3x64_f_green_texture_id; static GLuint _layer3x3x64_f_blue_texture_id; static GLuint _layer3x3x64_f_output_textures[64]; static GLuint _layer3x3x64_f_kernel_ubo_id; void layer3x3x64_f_init() { size_t i; glGenTextures(64, _layer3x3x64_f_output_textures); for (i = 0; i < 64; i++) { glBindTexture(GL_TEXTURE_2D, _layer3x3x64_f_output_textures[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT); } glBindTexture(GL_TEXTURE_2D, 0); // Image textures allocation glGenTextures(1, &_layer3x3x64_f_red_texture_id); glGenTextures(1, &_layer3x3x64_f_green_texture_id); glGenTextures(1, &_layer3x3x64_f_blue_texture_id); glBindTexture(GL_TEXTURE_2D, _layer3x3x64_f_red_texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT); glBindTexture(GL_TEXTURE_2D, _layer3x3x64_f_green_texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT); glBindTexture(GL_TEXTURE_2D, _layer3x3x64_f_blue_texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT); glBindTexture(GL_TEXTURE_2D, 0); // Kernels buffer allocation glGenBuffers(1, &_layer3x3x64_f_kernel_ubo_id); glBindBuffer(GL_UNIFORM_BUFFER, _layer3x3x64_f_kernel_ubo_id); glBufferData ( GL_UNIFORM_BUFFER, (GLsizeiptr) (9 * 3 * sizeof(GLfloat)), NULL, GL_DYNAMIC_COPY ); glBindBuffer(GL_UNIFORM_BUFFER, 0); } void layer3x3x64_f_update(const float *red, const float *green, const float *blue) { } void layer3x3x64_f_perform_compute() { } void layer3x3x64_f_destroy() { }<file_sep>/* * Created by <NAME> on 4/27/18 8:38 AM. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ package limsi.fr.openings; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; /** * This is an implementation of a custom SurfaceView class that is used by a native code. * An EGL context is created with native code and is used to draw in the SurfaceView. In the * Java code only initialize the SurfaceView and set callbacks. A native rendering thread is * implemented. */ public class NativeSurfaceView extends SurfaceView implements SurfaceHolder.Callback { private final SurfaceHolder _holder; /** * Basic constructor * * @param context * @param attributes */ public NativeSurfaceView(Context context, AttributeSet attributes) { super(context, attributes); _holder = getHolder(); _holder.addCallback(this); setWillNotDraw(true); // Important to not draw the SurfaceView here !! } /** * Called when the surface is created, and calls nativeCreateSurface in order to initialize * the OpenGLES rendering context. * * @param surfaceHolder */ @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { synchronized (_holder) { nativeCreateSurface(_holder.getSurface()); } Log.d("NativeSurfaceView", "Surface created"); } /** * Called when the surface is resized, and calls nativeResizeSurface to update the OpenGLES * context * * @param surfaceHolder * @param format * @param width * @param height */ @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) { synchronized (_holder) { nativeResizeSurface(_holder.getSurface(), format, width, height); } } /** * Called when the surface is destroyed and calls nativeDestroySurface that will destroy the * created the OpenGLES context * * @param surfaceHolder */ @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { synchronized (_holder) { nativeDestroySurface(_holder.getSurface()); } } /* * Native methods for the NativeSurfaceView handling */ private static native void nativeCreateSurface(final Surface surface); private static native void nativeResizeSurface(final Surface surface, int format, int width, int height); // private static native void nativeDrawSurface(final Surface surface); private static native void nativeDestroySurface(final Surface surface); } <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "gl_computing.h" GLuint _output_texture_id; static float _red_input[COLOR_CAMERA_RESOLUTION]; static float _green_input[COLOR_CAMERA_RESOLUTION]; static float _blue_input[COLOR_CAMERA_RESOLUTION]; // static const float __kernel[] = // { // 1.0f / 16.0f, 1.0f / 8.0f, 1.0f / 16.0f, // 1.0f / 8.0f, 1.0f / 4.0f, 1.0f / 8.0f, // 1.0f / 16.0f, 1.0f / 8.0f, 1.0f / 16.0f // }; static const float __kernels[] = { 0.0f, -1.0f, 0.0f, -1.0f, 4.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, -1.0f, 4.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, -1.0f, 4.0f, -1.0f, 0.0f, -1.0f, 0.0f, }; // ------------------------------------------------------------------------------------------ static void __print_compute_shader_descr(); // ------------------------------------------------------------------------------------------ void gl_computing_init(void *data) { __print_compute_shader_descr(); glEnable(GL_TEXTURE_2D); glGenTextures(1, &_output_texture_id); glBindTexture(GL_TEXTURE_2D, _output_texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA32F, COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT); glBindTexture(GL_TEXTURE_2D, 0); conv3x3_f_init(); conv3x3_f_set_kernels(__kernels); conv3x3_f_attach_rendering_texture(_output_texture_id); } void gl_computing_update(void *data) { struct compute_data *data_ = (struct compute_data *) data; size_t i; size_t index = 0; for (i = 0; i < COLOR_CAMERA_RESOLUTION; i++) { _red_input[i] = data_->input_image[index++]; _green_input[i] = data_->input_image[index++]; _blue_input[i] = data_->input_image[index++]; } conv3x3_f_update(_red_input, _green_input, _blue_input); } void gl_computing_compute(void *data) { conv3x3_f_perform_compute(); } void gl_computing_destroy(void *data) { conv3x3_f_destroy(); } // ------------------------------------------------------------------------------------------ static void __print_compute_shader_descr() { GLint workgroup_count[3]; GLint workgroup_size[3]; GLint workgroup_invocations; GLint max_uniform_bock_size; GLint uniform_offset_alignment; glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 0, &workgroup_count[0]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 1, &workgroup_count[1]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 2, &workgroup_count[2]); LOGD("Taille maximale des workgroups:\n\tx:%u\n\ty:%u\n\tz:%u\n", workgroup_size[0], workgroup_size[1], workgroup_size[2]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 0, &workgroup_size[0]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 1, &workgroup_size[1]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 2, &workgroup_size[2]); LOGD("Nombre maximal d'invocations locales:\n\tx:%u\n\ty:%u\n\tz:%u\n", workgroup_size[0], workgroup_size[1], workgroup_size[2]); glGetIntegerv(GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS, &workgroup_invocations); LOGD("Nombre maximum d'invocations de workgroups:\n\t%u\n", workgroup_invocations); glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &max_uniform_bock_size); LOGD("Taille maximale des UBO : %d", max_uniform_bock_size); glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uniform_offset_alignment); LOGD("Offset d'alignement : %d", uniform_offset_alignment); }<file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "model.h" static struct compute_data _compute_data; static struct compute_data *_compute_data_ptr; static struct display_data _display_data; static struct display_data *_display_data_ptr; void model_init() { _compute_data_ptr = &_compute_data; _display_data_ptr = &_display_data; } void model_get_compute_data(struct compute_data **data) { SWAP_POINTERS(&_compute_data_ptr, data); } void model_set_compute_data(struct compute_data **data) { SWAP_POINTERS(&_compute_data_ptr, data); } void model_get_display_data(struct display_data **data) { SWAP_POINTERS(&_display_data_ptr, data); } void model_set_display_data(struct display_data **data) { SWAP_POINTERS(&_display_data_ptr, data); } void model_destroy() { }<file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "cl_computing.h" GLuint _output_texture_id; // --------------------------------------------------------------------------------------------- static void __matrix_add(struct compute_info *info, const float *X, const float *Y, float *Z); // --------------------------------------------------------------------------------------------- void cl_computing_init(struct compute_info *info, void *data) { // Initialize OpenGL objects glEnable(GL_TEXTURE_2D); glGenTextures(1, &_output_texture_id); glBindTexture(GL_TEXTURE_2D, _output_texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexStorage2D ( GL_TEXTURE_2D, 1, GL_RGBA32F, COLOR_CAMERA_WIDTH, COLOR_CAMERA_HEIGHT ); glBindTexture(GL_TEXTURE_2D, 0); grayscale_init(info, _output_texture_id); } void cl_computing_update(struct compute_info *info, void *data) { struct compute_data *data_ = (struct compute_data *) data; grayscale_set_input_image(data_->input_image); } void cl_computing_compute(struct compute_info *info, void *data) { grayscale_compute(); } void cl_computing_destroy(struct compute_info *info, void *data) { grayscale_destroy(); glDeleteTextures(1, &_output_texture_id); }<file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "gl_31_functions.h" PFNGLDISPATCHCOMPUTEPROC __glDispatchCompute = NULL; PFNGLDISPATCHCOMPUTEINDIRECTPROC __glDispatchComputeIndirect = NULL; PFNGLDRAWARRAYSINDIRECTPROC __glDrawArraysIndirect = NULL; PFNGLDRAWELEMENTSINDIRECTPROC __glDrawElementsIndirect = NULL; PFNGLFRAMEBUFFERPARAMETERIPROC __glFramebufferParameteri = NULL; PFNGLGETFRAMEBUFFERPARAMETERIVPROC __glGetFramebufferParameteri = NULL; PFNGLGETPROGRAMINTERFACEIVPROC __glGetProgramInterface = NULL; PFNGLGETPROGRAMRESOURCEINDEXPROC __glGetProgramSourceIndex = NULL; PFNGLGETPROGRAMRESOURCENAMEPROC __glGetProgramResourceName = NULL; PFNGLGETPROGRAMRESOURCEIVPROC __glGetProgramResourceiv = NULL; PFNGLGETPROGRAMRESOURCELOCATIONPROC __glGetProgramResourceLocation = NULL; PFNGLUSEPROGRAMSTAGESPROC __glUseProgramStages = NULL; PFNGLACTIVESHADERPROGRAMPROC __glActiveShaderProgram = NULL; PFNGLCREATESHADERPROGRAMVPROC __glCreateShaderProgram = NULL; PFNGLBINDPROGRAMPIPELINEPROC __glBindProgramPipeline = NULL; PFNGLDELETEPROGRAMPIPELINESPROC __glDeleteProgramPipeline = NULL; PFNGLGENPROGRAMPIPELINESPROC __glGenProgramPipeline = NULL; PFNGLISPROGRAMPIPELINEPROC __glIsProgramPipeline = NULL; PFNGLGETPROGRAMPIPELINEIVPROC __glGetProgramPipelineiv = NULL; PFNGLPROGRAMUNIFORM1IPROC __glProgramUniform1i = NULL; PFNGLPROGRAMUNIFORM2IPROC __glProgramUniform2i = NULL; PFNGLPROGRAMUNIFORM3IPROC __glProgramUniform3i = NULL; PFNGLPROGRAMUNIFORM4IPROC __glProgramUniform4i = NULL; PFNGLPROGRAMUNIFORM1UIPROC __glProgramUniform1ui = NULL; PFNGLPROGRAMUNIFORM2UIPROC __glProgramUniform2ui = NULL; PFNGLPROGRAMUNIFORM3UIPROC __glProgramUniform3ui = NULL; PFNGLPROGRAMUNIFORM4UIPROC __glProgramUniform4ui = NULL; PFNGLPROGRAMUNIFORM1FPROC __glProgramUniform1f = NULL; PFNGLPROGRAMUNIFORM2FPROC __glProgramUniform2f = NULL; PFNGLPROGRAMUNIFORM3FPROC __glProgramUniform3f = NULL; PFNGLPROGRAMUNIFORM4FPROC __glProgramUniform4f = NULL; PFNGLPROGRAMUNIFORM1IVPROC __glProgramUniform1iv = NULL; PFNGLPROGRAMUNIFORM2IVPROC __glProgramUniform2iv = NULL; PFNGLPROGRAMUNIFORM3IVPROC __glProgramUniform3iv = NULL; PFNGLPROGRAMUNIFORM4IVPROC __glProgramUniform4iv = NULL; PFNGLPROGRAMUNIFORM1UIVPROC __glProgramUniform1uiv = NULL; PFNGLPROGRAMUNIFORM2UIVPROC __glProgramUniform2uiv = NULL; PFNGLPROGRAMUNIFORM3UIVPROC __glProgramUniform3uiv = NULL; PFNGLPROGRAMUNIFORM4UIVPROC __glProgramUniform4uiv = NULL; PFNGLPROGRAMUNIFORM1FVPROC __glProgramUniform1fv = NULL; PFNGLPROGRAMUNIFORM2FVPROC __glProgramUniform2fv = NULL; PFNGLPROGRAMUNIFORM3FVPROC __glProgramUniform3fv = NULL; PFNGLPROGRAMUNIFORM4FVPROC __glProgramUniform4fv = NULL; PFNGLPROGRAMUNIFORMMATRIX2FVPROC __glProgramUniformMatrix2fv = NULL; PFNGLPROGRAMUNIFORMMATRIX3FVPROC __glProgramUniformMatrix3fv = NULL; PFNGLPROGRAMUNIFORMMATRIX4FVPROC __glProgramUniformMatrix4fv = NULL; PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC __glProgramUniformMatrix2x3fv = NULL; PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC __glProgramUniformMatrix3x2fv = NULL; PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC __glProgramUniformMatrix2x4fv = NULL; PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC __glProgramUniformMatrix4x2fv = NULL; PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC __glProgramUniformMatrix3x4fv = NULL; PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC __glProgramUniformMatrix4x3fv = NULL; PFNGLVALIDATEPROGRAMPIPELINEPROC __glValidateProgramPipeline = NULL; PFNGLGETPROGRAMPIPELINEINFOLOGPROC __glGetProgramPipelineInfoLog = NULL; PFNGLBINDIMAGETEXTUREPROC __glBindImageTexture = NULL; PFNGLGETBOOLEANI_VPROC __glGetBooleani_v = NULL; PFNGLMEMORYBARRIERPROC __glMemoryBarrier = NULL; PFNGLMEMORYBARRIERBYREGIONPROC __glMemoryBarrierByRegion = NULL; PFNGLTEXSTORAGE2DMULTISAMPLEPROC __glTexStorage2DMultiSample = NULL; PFNGLGETMULTISAMPLEFVPROC __glGetMultisamplefv = NULL; PFNGLSAMPLEMASKIPROC __glSampleMaski = NULL; PFNGLGETTEXLEVELPARAMETERIVPROC __glGetTexLevelParameteriv = NULL; PFNGLGETTEXLEVELPARAMETERFVPROC __glGetTexLevelParameterfv = NULL; PFNGLBINDVERTEXBUFFERPROC __glBindVertexBuffer = NULL; PFNGLVERTEXATTRIBFORMATPROC __glVertexAttribFormat = NULL; PFNGLVERTEXATTRIBIFORMATPROC __glVertexAttribIFormatProc = NULL; PFNGLVERTEXATTRIBBINDINGPROC __glVertexAttribBinding = NULL; PFNGLVERTEXBINDINGDIVISORPROC __glVertexBindingDivisor = NULL; void gl_functions_load() { __glDispatchCompute = (PFNGLDISPATCHCOMPUTEPROC) eglGetProcAddress("glDispatchCompute"); __glDispatchComputeIndirect = (PFNGLDISPATCHCOMPUTEINDIRECTPROC) eglGetProcAddress("glDispatchComputeIndirect"); __glDrawArraysIndirect = (PFNGLDRAWARRAYSINDIRECTPROC) eglGetProcAddress("glDrawArraysIndirect"); __glDrawElementsIndirect = (PFNGLDRAWELEMENTSINDIRECTPROC) eglGetProcAddress("glDrawElementsIndirect"); __glFramebufferParameteri = (PFNGLFRAMEBUFFERPARAMETERIPROC) eglGetProcAddress("glFramebufferParameteri"); __glGetFramebufferParameteri = (PFNGLGETFRAMEBUFFERPARAMETERIVPROC) eglGetProcAddress("glGetFramebufferParameteri"); __glGetProgramInterface = (PFNGLGETPROGRAMINTERFACEIVPROC) eglGetProcAddress("glGetProgramInterface"); __glGetProgramSourceIndex = (PFNGLGETPROGRAMRESOURCEINDEXPROC) eglGetProcAddress("glGetProgramSourceIndex"); __glGetProgramResourceName = (PFNGLGETPROGRAMRESOURCENAMEPROC) eglGetProcAddress("glGetProgramResourceName"); __glGetProgramResourceiv = (PFNGLGETPROGRAMRESOURCEIVPROC) eglGetProcAddress("glGetProgramResourceiv"); __glGetProgramResourceLocation = (PFNGLGETPROGRAMRESOURCELOCATIONPROC) eglGetProcAddress("glGetProgramResourceLocation"); __glUseProgramStages = (PFNGLUSEPROGRAMSTAGESPROC) eglGetProcAddress("glUseProgramStages"); __glActiveShaderProgram = (PFNGLACTIVESHADERPROGRAMPROC) eglGetProcAddress("glActiveShaderProgram"); __glCreateShaderProgram = (PFNGLCREATESHADERPROGRAMVPROC) eglGetProcAddress("glCreateShaderProgram"); __glBindProgramPipeline = (PFNGLBINDPROGRAMPIPELINEPROC) eglGetProcAddress("glBindProgramPipeline"); __glDeleteProgramPipeline = (PFNGLDELETEPROGRAMPIPELINESPROC) eglGetProcAddress("glDeleteProgramPipeline"); __glGenProgramPipeline = (PFNGLGENPROGRAMPIPELINESPROC) eglGetProcAddress("glGenProgramPipeline"); __glIsProgramPipeline = (PFNGLISPROGRAMPIPELINEPROC) eglGetProcAddress("glIsProgramPipeline"); __glGetProgramPipelineiv = (PFNGLGETPROGRAMPIPELINEIVPROC) eglGetProcAddress("glGetProgramPipelineiv"); __glProgramUniform1i = (PFNGLPROGRAMUNIFORM1IPROC) eglGetProcAddress("glProgramUniform1i"); __glProgramUniform2i = (PFNGLPROGRAMUNIFORM2IPROC) eglGetProcAddress("glProgramUniform2i"); __glProgramUniform3i = (PFNGLPROGRAMUNIFORM3IPROC) eglGetProcAddress("glProgramUniform3i"); __glProgramUniform4i = (PFNGLPROGRAMUNIFORM4IPROC) eglGetProcAddress("glProgramUniform4i"); __glProgramUniform1ui = (PFNGLPROGRAMUNIFORM1UIPROC) eglGetProcAddress("glProgramUniform1ui"); __glProgramUniform2ui = (PFNGLPROGRAMUNIFORM2UIPROC) eglGetProcAddress("glProgramUniform2ui"); __glProgramUniform3ui = (PFNGLPROGRAMUNIFORM3UIPROC) eglGetProcAddress("glProgramUniform3ui"); __glProgramUniform4ui = (PFNGLPROGRAMUNIFORM4UIPROC) eglGetProcAddress("glProgramUniform4ui"); __glProgramUniform1f = (PFNGLPROGRAMUNIFORM1FPROC) eglGetProcAddress("glProgramUniform1f"); __glProgramUniform2f = (PFNGLPROGRAMUNIFORM2FPROC) eglGetProcAddress("glProgramUniform2f"); __glProgramUniform3f = (PFNGLPROGRAMUNIFORM3FPROC) eglGetProcAddress("glProgramUniform3f"); __glProgramUniform4f = (PFNGLPROGRAMUNIFORM4FPROC) eglGetProcAddress("glProgramUniform4f"); __glProgramUniform1iv = (PFNGLPROGRAMUNIFORM1IVPROC) eglGetProcAddress("glProgramUniform1iv"); __glProgramUniform2iv = (PFNGLPROGRAMUNIFORM2IVPROC) eglGetProcAddress("glProgramUniform2iv"); __glProgramUniform3iv = (PFNGLPROGRAMUNIFORM3IVPROC) eglGetProcAddress("glProgramUniform3iv"); __glProgramUniform4iv = (PFNGLPROGRAMUNIFORM4IVPROC) eglGetProcAddress("glProgramUniform4iv"); __glProgramUniform1uiv = (PFNGLPROGRAMUNIFORM1UIVPROC) eglGetProcAddress("glProgramUniform1uiv"); __glProgramUniform2uiv = (PFNGLPROGRAMUNIFORM2UIVPROC) eglGetProcAddress("glProgramUniform2uiv"); __glProgramUniform3uiv = (PFNGLPROGRAMUNIFORM3UIVPROC) eglGetProcAddress("glProgramUniform3uiv"); __glProgramUniform4uiv = (PFNGLPROGRAMUNIFORM4UIVPROC) eglGetProcAddress("glProgramUniform4uiv"); __glProgramUniform1fv = (PFNGLPROGRAMUNIFORM1FVPROC) eglGetProcAddress("glProgramUniform1fv"); __glProgramUniform2fv = (PFNGLPROGRAMUNIFORM2FVPROC) eglGetProcAddress("glProgramUniform2fv"); __glProgramUniform3fv = (PFNGLPROGRAMUNIFORM3FVPROC) eglGetProcAddress("glProgramUniform3fv"); __glProgramUniform4fv = (PFNGLPROGRAMUNIFORM4FVPROC) eglGetProcAddress("glProgramUniform4fv"); __glProgramUniformMatrix2fv = (PFNGLPROGRAMUNIFORMMATRIX2FVPROC) eglGetProcAddress("glProgramUniformMatrix2fv"); __glProgramUniformMatrix3fv = (PFNGLPROGRAMUNIFORMMATRIX3FVPROC) eglGetProcAddress("glProgramUniformMatrix3fv"); __glProgramUniformMatrix4fv = (PFNGLPROGRAMUNIFORMMATRIX4FVPROC) eglGetProcAddress("glProgramUniformMatrix4fv"); __glProgramUniformMatrix2x3fv = (PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC) eglGetProcAddress("glProgramUniformMatrix2x3fv"); __glProgramUniformMatrix3x2fv = (PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC) eglGetProcAddress("glProgramUniformMatrix3x2fv"); __glProgramUniformMatrix2x4fv = (PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC) eglGetProcAddress("glProgramUniformMatrix2x4fv"); __glProgramUniformMatrix4x2fv = (PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC) eglGetProcAddress("glProgramUniformMatrix4x2fv"); __glProgramUniformMatrix3x4fv = (PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC) eglGetProcAddress("glProgramUniformMatrix3x4fv"); __glProgramUniformMatrix4x3fv = (PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC) eglGetProcAddress("glProgramUniformMatrix4x3fv"); __glValidateProgramPipeline = (PFNGLVALIDATEPROGRAMPIPELINEPROC) eglGetProcAddress("glValidateProgramPipeline"); __glGetProgramPipelineInfoLog = (PFNGLGETPROGRAMPIPELINEINFOLOGPROC) eglGetProcAddress("glGetProgramPipelineInfoLog"); __glBindImageTexture = (PFNGLBINDIMAGETEXTUREPROC) eglGetProcAddress("glBindImageTexture"); __glGetBooleani_v = (PFNGLGETBOOLEANI_VPROC) eglGetProcAddress("glGetBooleani_v"); __glMemoryBarrier = (PFNGLMEMORYBARRIERPROC) eglGetProcAddress("glMemoryBarrier"); __glMemoryBarrierByRegion = (PFNGLMEMORYBARRIERBYREGIONPROC) eglGetProcAddress("glMemoryBarrierByRegion"); __glTexStorage2DMultiSample = (PFNGLTEXSTORAGE2DMULTISAMPLEPROC) eglGetProcAddress("glTexStorage2DMultiSample"); __glGetMultisamplefv = (PFNGLGETMULTISAMPLEFVPROC) eglGetProcAddress("glGetMultisamplefv"); __glSampleMaski = (PFNGLSAMPLEMASKIPROC) eglGetProcAddress("glSampleMaski"); __glGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC) eglGetProcAddress("glGetTexLevelParameteriv"); __glGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC) eglGetProcAddress("glGetTexLevelParameterfv"); __glBindVertexBuffer = (PFNGLBINDVERTEXBUFFERPROC) eglGetProcAddress("glBindVertexBuffer"); __glVertexAttribFormat = (PFNGLVERTEXATTRIBFORMATPROC) eglGetProcAddress("glVertexAttribFormat"); __glVertexAttribIFormatProc = (PFNGLVERTEXATTRIBIFORMATPROC) eglGetProcAddress("glVertexAttribIFormatPro"); __glVertexAttribBinding = (PFNGLVERTEXATTRIBBINDINGPROC) eglGetProcAddress("glVertexAttribBinding"); __glVertexBindingDivisor = (PFNGLVERTEXBINDINGDIVISORPROC) eglGetProcAddress("glVertexBindingDivisor"); }<file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #ifndef OPENINGS_COMPUTING_H #define OPENINGS_COMPUTING_H #include <stdint.h> #include <omp.h> #include <arm_neon.h> #include <GLES3/gl3.h> #include "gl_computing/conv3x3_f.h" #include "global/global.h" #include "gl/gl_31_functions.h" #include "gl/shader.h" #include "gl/shader_sources.h" #include "model/model.h" __BEGIN_DECLS extern void gl_computing_init(void *data); extern void gl_computing_update(void *data); extern void gl_computing_compute(void *data); extern void gl_computing_destroy(void *data); __END_DECLS #endif // OPENINGS_COMPUTING_H <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #ifndef __KERNEL_SOURCES_H #define __KERNEL_SOURCES_H static const char *grayscale_kernel_source = { "/*\n" " * Created by <NAME>\n" " *\n" " * This program is free software: you can redistribute it and/or modify\n" " * it under the terms of the GNU General Public License as published by\n" " * the Free Software Foundation, either version 3 of the License, or\n" " * (at your option) any later version.\n" " *\n" " * This program is distributed in the hope that it will be useful,\n" " * but WITHOUT ANY WARRANTY; without even the implied warranty of\n" " * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" " * GNU General Public License for more details.\n" " *\n" " * You should have received a copy of the GNU General Public License\n" " */\n" "\n" "__constant sampler_t _sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_NEAREST;\n" "\n" "__kernel void img_grayscale\n" " (\n" " __read_only image2d_t input_red_image,\n" " __read_only image2d_t input_green_image,\n" " __read_only image2d_t input_blue_image,\n" " __write_only image2d_t output_image\n" " )\n" "{\n" " size_t j = get_global_id(1);\n" " size_t i = get_global_id(0);\n" " float4 red = read_imagef(input_red_image, (int2)(i,j));\n" " float4 green = read_imagef(input_green_image, (int2)(i,j));\n" " float4 blue = read_imagef(input_blue_image, (int2)(i,j));\n" " \n" " float val = (red.x + green.x + blue.x) / 3.0f;\n" " \n" " write_imagef(output_image, (int2)(i,j), (float4)(val, val, val, 1.0f));\n" "}\n" }; #endif // __KERNEL_SOURCES_H <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "shader.h" GLuint shader_createProgram(const char *vtxSrc, const char *fragSrc) { GLuint vtxShader = 0; GLuint fragShader = 0; GLuint program = 0; GLint linked = GL_FALSE; vtxShader = shader_createShader(GL_VERTEX_SHADER, vtxSrc); if (!vtxShader) goto exit; fragShader = shader_createShader(GL_FRAGMENT_SHADER, fragSrc); if (!fragShader) goto exit; program = glCreateProgram(); if (!program) { //checkGlError("glCreateProgram"); goto exit; } glAttachShader(program, vtxShader); glAttachShader(program, fragShader); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &linked); if (!linked) { LOGE("Could not link program"); GLint infoLogLen = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLen); if (infoLogLen) { GLchar *infoLog = (GLchar *) malloc(infoLogLen); if (infoLog) { glGetProgramInfoLog(program, infoLogLen, NULL, infoLog); LOGE("Could not link program:\n%s\n", infoLog); free(infoLog); } } glDeleteProgram(program); program = 0; } exit: glDeleteShader(vtxShader); glDeleteShader(fragShader); return program; } GLuint shader_create_compute_program(const char *kernel) { GLuint program_id = 0; GLuint compute_shader = 0; GLint linked = GL_FALSE; compute_shader = shader_createShader(GL_COMPUTE_SHADER, kernel); if (!compute_shader) goto exit; program_id = glCreateProgram(); if (!program_id) goto exit; glAttachShader(program_id, compute_shader); glLinkProgram(program_id); glGetProgramiv(program_id, GL_LINK_STATUS, &linked); if (!linked) { LOGE("Could not link compute program"); GLint infoLogLen = 0; glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &infoLogLen); if (infoLogLen) { GLchar *infoLog = (GLchar *) malloc((size_t) infoLogLen); if (infoLog) { glGetProgramInfoLog(program_id, infoLogLen, NULL, infoLog); LOGE("Could not link compute program:\n%s\n", infoLog); free(infoLog); } } glDeleteProgram(program_id); program_id = 0; } exit: glDeleteShader(compute_shader); return program_id; } GLuint shader_createShader(GLenum shaderType, const char *src) { GLuint shader = glCreateShader(shaderType); if (!shader) { LOGE("Problem shader"); return 0; } glShaderSource(shader, 1, &src, NULL); GLint compiled = GL_FALSE; glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLint infoLogLen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLen); if (infoLogLen > 0) { GLchar *infoLog = (GLchar *) malloc(infoLogLen); if (infoLog) { glGetShaderInfoLog(shader, infoLogLen, NULL, infoLog); LOGE ( "Could not compile %s shader:\n%s\n", shaderType == GL_VERTEX_SHADER ? "vertex" : (shaderType == GL_FRAGMENT_SHADER ? "fragment" : "compute"), infoLog ); free(infoLog); } } glDeleteShader(shader); return 0; } return shader; } <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #ifndef __SHADER_SOURCES_H #define __SHADER_SOURCES_H #include <GLES3/gl31.h> static const GLchar *CONV3X3_source = { "/*\n" " * Created by <NAME>\n" " *\n" " * This program is free software: you can redistribute it and/or modify\n" " * it under the terms of the GNU General Public License as published by\n" " * the Free Software Foundation, either version 3 of the License, or\n" " * (at your option) any later version.\n" " *\n" " * This program is distributed in the hope that it will be useful,\n" " * but WITHOUT ANY WARRANTY; without even the implied warranty of\n" " * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" " * GNU General Public License for more details.\n" " *\n" " * You should have received a copy of the GNU General Public License\n" " */\n" "\n" "#version 310 es\n" "\n" "precision highp float;\n" "\n" "layout(local_size_x = 1, local_size_y = 540, local_size_z = 1) in;\n" "\n" "// --------------------------------------------------------------------------------------------\n" "// ----------------------------------- Kernels ------------------------------------------------\n" "// --------------------------------------------------------------------------------------------\n" "\n" "layout(std140, binding = 0) uniform RED_KERNEL\n" "{\n" " float red_kernel[9];\n" "};\n" "\n" "layout(std140, binding = 1) uniform GREEN_KERNEL\n" "{\n" " float green_kernel[9];\n" "};\n" "\n" "layout(std140, binding = 2) uniform BLUE_KERNEL\n" "{\n" " float blue_kernel[9];\n" "};\n" "\n" "// --------------------------------------------------------------------------------------------\n" "// -------------------------------- Input images ----------------------------------------------\n" "// --------------------------------------------------------------------------------------------\n" "\n" "layout(r32f, binding = 3) readonly uniform highp image2D _red_input;\n" "layout(r32f, binding = 4) readonly uniform highp image2D _green_input;\n" "layout(r32f, binding = 5) readonly uniform highp image2D _blue_input;\n" "\n" "// --------------------------------------------------------------------------------------------\n" "// -------------------------------- Output image ----------------------------------------------\n" "// --------------------------------------------------------------------------------------------\n" "\n" "layout(rgba32f, binding = 6) writeonly uniform highp image2D _output;\n" "\n" "// -------------------------------------------------------------------------------------------\n" "\n" "void main()\n" "{\n" " uint i = gl_WorkGroupID.x * gl_WorkGroupSize.x + gl_LocalInvocationID.x;\n" " uint j = gl_WorkGroupID.y * gl_WorkGroupSize.y + gl_LocalInvocationID.y;\n" "\n" " float val_r;\n" " float val_g;\n" " float val_b;\n" "\n" " val_r = imageLoad(_red_input, ivec2(i - 1u, j - 1u)).r * red_kernel[0]\n" " + imageLoad(_red_input, ivec2(i - 1u, j )).r * red_kernel[1]\n" " + imageLoad(_red_input, ivec2(i - 1u, j + 1u)).r * red_kernel[2]\n" " + imageLoad(_red_input, ivec2(i , j - 1u)).r * red_kernel[3]\n" " + imageLoad(_red_input, ivec2(i , j )).r * red_kernel[4]\n" " + imageLoad(_red_input, ivec2(i , j + 1u)).r * red_kernel[5]\n" " + imageLoad(_red_input, ivec2(i + 1u, j - 1u)).r * red_kernel[6]\n" " + imageLoad(_red_input, ivec2(i + 1u, j )).r * red_kernel[7]\n" " + imageLoad(_red_input, ivec2(i + 1u, j + 1u)).r * red_kernel[8];\n" "\n" " val_g = imageLoad(_green_input, ivec2(i - 1u, j - 1u)).r * green_kernel[0]\n" " + imageLoad(_green_input, ivec2(i - 1u, j )).r * green_kernel[1]\n" " + imageLoad(_green_input, ivec2(i - 1u, j + 1u)).r * green_kernel[2]\n" " + imageLoad(_green_input, ivec2(i , j - 1u)).r * green_kernel[3]\n" " + imageLoad(_green_input, ivec2(i , j )).r * green_kernel[4]\n" " + imageLoad(_green_input, ivec2(i , j + 1u)).r * green_kernel[5]\n" " + imageLoad(_green_input, ivec2(i + 1u, j - 1u)).r * green_kernel[6]\n" " + imageLoad(_green_input, ivec2(i + 1u, j )).r * green_kernel[7]\n" " + imageLoad(_green_input, ivec2(i + 1u, j + 1u)).r * green_kernel[8];\n" "\n" " val_b = imageLoad(_blue_input, ivec2(i - 1u, j - 1u)).r * blue_kernel[0]\n" " + imageLoad(_blue_input, ivec2(i - 1u, j )).r * blue_kernel[1]\n" " + imageLoad(_blue_input, ivec2(i - 1u, j + 1u)).r * blue_kernel[2]\n" " + imageLoad(_blue_input, ivec2(i , j - 1u)).r * blue_kernel[3]\n" " + imageLoad(_blue_input, ivec2(i , j )).r * blue_kernel[4]\n" " + imageLoad(_blue_input, ivec2(i , j + 1u)).r * blue_kernel[5]\n" " + imageLoad(_blue_input, ivec2(i + 1u, j - 1u)).r * blue_kernel[6]\n" " + imageLoad(_blue_input, ivec2(i + 1u, j )).r * blue_kernel[7]\n" " + imageLoad(_blue_input, ivec2(i + 1u, j + 1u)).r * blue_kernel[8];\n" "\n" " imageStore(_output, ivec2(i, j), vec4(val_r, val_g, val_b, 1.0f));\n" "}\n" }; static const GLchar *GRAYSCALE_source = { "/*\n" " * Created by <NAME>\n" " *\n" " * This program is free software: you can redistribute it and/or modify\n" " * it under the terms of the GNU General Public License as published by\n" " * the Free Software Foundation, either version 3 of the License, or\n" " * (at your option) any later version.\n" " *\n" " * This program is distributed in the hope that it will be useful,\n" " * but WITHOUT ANY WARRANTY; without even the implied warranty of\n" " * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" " * GNU General Public License for more details.\n" " *\n" " * You should have received a copy of the GNU General Public License\n" " */\n" "\n" "#version 310 es\n" "\n" "precision lowp float;\n" "\n" "layout(local_size_x = 1, local_size_y = 540, local_size_z = 1) in;\n" "\n" "// --------------------------------------------------------------------------------------------\n" "// -------------------------------- Input images ----------------------------------------------\n" "// --------------------------------------------------------------------------------------------\n" "\n" "layout(r32f, binding = 0) readonly uniform highp image2D _red_input;\n" "layout(r32f, binding = 1) readonly uniform highp image2D _green_input;\n" "layout(r32f, binding = 2) readonly uniform highp image2D _blue_input;\n" "\n" "// --------------------------------------------------------------------------------------------\n" "// -------------------------------- Output image ----------------------------------------------\n" "// --------------------------------------------------------------------------------------------\n" "\n" "layout(rgba32f, binding = 3) writeonly highp uniform image2D _output;\n" "\n" "// -------------------------------------------------------------------------------------------\n" "\n" "void main()\n" "{\n" " uint i = gl_WorkGroupID.x;\n" " uint j = gl_WorkGroupID.y * gl_WorkGroupSize.y + gl_LocalInvocationID.y;\n" "\n" " float r, g, b;\n" " float val;\n" "\n" " r = imageLoad(_red_input, ivec2(i, j)).r;\n" " g = imageLoad(_green_input, ivec2(i, j)).r;\n" " b = imageLoad(_blue_input, ivec2(i, j)).r;\n" "\n" " val = (r + g + b) / 3.0f;\n" "\n" " imageStore(_output, ivec2(i, j), vec4(val, val, val, 1.0f));\n" "}\n" }; static const GLchar *MATRIX_SAXPY_source = { "/*\n" " * Created by <NAME>\n" " *\n" " * This program is free software: you can redistribute it and/or modify\n" " * it under the terms of the GNU General Public License as published by\n" " * the Free Software Foundation, either version 3 of the License, or\n" " * (at your option) any later version.\n" " *\n" " * This program is distributed in the hope that it will be useful,\n" " * but WITHOUT ANY WARRANTY; without even the implied warranty of\n" " * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" " * GNU General Public License for more details.\n" " *\n" " * You should have received a copy of the GNU General Public License\n" " */\n" "\n" "#version 310 es\n" "\n" "layout(local_size_x = 1024, local_size_y = 1, local_size_z = 1) in;\n" "\n" "layout(std430, binding = 0) readonly buffer A_buffer\n" "{\n" " float data[];\n" "} A;\n" "\n" "layout(std430, binding = 1) readonly buffer X_buffer\n" "{\n" " float data[];\n" "} X;\n" "\n" "layout(std430, binding = 2) readonly buffer Y_buffer\n" "{\n" " float data[];\n" "} Y;\n" "\n" "layout(std430, binding = 3) buffer Z_buffer\n" "{\n" " float data[];\n" "} Z;\n" "\n" "void main()\n" "{\n" " uint i = gl_WorkGroupID.x;\n" " uint j = gl_LocalInvocationID.x;\n" " uint num_cols = gl_NumWorkGroups.x;\n" "\n" " uint Z_index = i * num_cols + j;\n" " uint A_index = i * num_cols;\n" "\n" " Z.data[Z_index] = 0.0f;\n" "\n" " for(uint id = A_index; id < (A_index + num_cols); id++)\n" " {\n" " Z.data[Z_index] += A.data[id] * X.data[id];\n" " }\n" " Z.data[Z_index] += Y.data[Z_index];\n" "}\n" }; static const GLchar *SAXPY_source = { "/*\n" " * Created by <NAME>\n" " *\n" " * This program is free software: you can redistribute it and/or modify\n" " * it under the terms of the GNU General Public License as published by\n" " * the Free Software Foundation, either version 3 of the License, or\n" " * (at your option) any later version.\n" " *\n" " * This program is distributed in the hope that it will be useful,\n" " * but WITHOUT ANY WARRANTY; without even the implied warranty of\n" " * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" " * GNU General Public License for more details.\n" " *\n" " * You should have received a copy of the GNU General Public License\n" " */\n" "\n" "#version 310 es\n" "\n" "// Performs a single SAXPY operation\n" "\n" "layout(local_size_x = 1280) in;\n" "\n" "layout(std430, binding = 0) readonly buffer X_buffer\n" "{\n" " float elements[];\n" "} X;\n" "\n" "layout(std430, binding = 1) readonly buffer Y_buffer\n" "{\n" " float elements[];\n" "} Y;\n" "\n" "layout(std430, binding = 2) writeonly buffer Z_buffer\n" "{\n" " float elements[];\n" "} Z;\n" "\n" "uniform float SAXPY_A;\n" "\n" "void main()\n" "{\n" " Z.elements[gl_GlobalInvocationID.x]\n" " = SAXPY_A * X.elements[gl_GlobalInvocationID.x] + Y.elements[gl_GlobalInvocationID.x];\n" "}\n" }; #endif // __SHADER_SOURCES_H <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #ifndef OPENINGS_LAYER3X3X32_F_H #define OPENINGS_LAYER3X3X32_F_H #include <stdint.h> #include <GLES3/gl3.h> #include "global/global.h" #include "gl/gl_31_functions.h" #include "gl/shader.h" #include "gl/shader_sources.h" __BEGIN_DECLS extern void layer3x3x64_f_init(); extern void layer3x3x64_f_update(const float *red, const float *green, const float *blue); extern void layer3x3x64_f_perform_compute(); extern void layer3x3x64_f_destroy(); __END_DECLS #endif // OPENINGS_LAYER3X3X32_F_H <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "rendering.h" static const GLchar _vertex_shader_source[] = "#version 310 es\n" "precision mediump float;\n" "layout(location = 0) in vec3 _position;\n" "layout(location = 1) in vec2 _texcoords;\n" "out vec2 uv;\n" "void main(){\n" "gl_Position = vec4(_position.y, -_position.x, _position.z, 1.0);\n" "uv = vec2(_texcoords);\n" "}\n"; static const GLchar _fragment_shader_source[] = "#version 310 es\n" "precision mediump float;\n" "precision mediump sampler2D;\n" "in vec2 uv;\n" "uniform sampler2D tex;\n" "layout(location = 0) out vec4 out_color;\n" "void main(){\n" "out_color = texture(tex, uv);\n" "}\n"; static const GLfloat _positions[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f }; static const GLfloat _texcoords[] = { 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f }; static GLuint _program; static GLuint _positions_vbo; static GLuint _texcoords_vbo; extern GLuint _output_texture_id; // ---------------------------------------------------------------------------------------- void rendering_init(struct display_data *data) { glEnable(GL_TEXTURE_2D); glClearColor(1.0f, 0.0f, 0.0f, 1.0f); _program = shader_createProgram(_vertex_shader_source, _fragment_shader_source); glGenBuffers(1, &_positions_vbo); glGenBuffers(1, &_texcoords_vbo); glBindBuffer(GL_ARRAY_BUFFER, _positions_vbo); glBufferData(GL_ARRAY_BUFFER, 18 * sizeof(float), _positions, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, _texcoords_vbo); glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(float), _texcoords, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } void rendering_resize(struct display_data *data, GLsizei w, GLsizei h) { glViewport(0, 0, w, h); } void rendering_update(struct display_data *data) { } void rendering_clear(struct display_data *data) { } void rendering_draw(struct display_data *data) { glClear(GL_COLOR_BUFFER_BIT); glUseProgram(_program); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, _output_texture_id); glBindBuffer(GL_ARRAY_BUFFER, _positions_vbo); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, _texcoords_vbo); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); glDrawArrays(GL_TRIANGLES, 0, 6); glUseProgram(0); glFlush(); } void rendering_destroy(struct display_data *data) { }<file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #ifndef OPENINGS_MODEL_H #define OPENINGS_MODEL_H #include <GLES3/gl3.h> #include"global/global.h" #if (USE_OPENCL == 1) struct compute_info { cl_platform_id platform_id; cl_device_id device_id; cl_context context; cl_command_queue command_queue; }; #endif struct compute_data { float input_image[COLOR_CAMERA_IMAGE_SIZE]; }; struct display_data { // uint8_t output_image[COLOR_CAMERA_IMAGE_SIZE]; GLuint _output_id; }; __BEGIN_DECLS extern void model_init(); extern void model_get_compute_data(struct compute_data **data); extern void model_set_compute_data(struct compute_data **data); extern void model_get_display_data(struct display_data **data); extern void model_set_display_data(struct display_data **data); extern void model_destroy(); __END_DECLS #endif // OPENINGS_MODEL_H <file_sep>/* * Created by <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ #include "cl_context.h" static struct compute_info _info; void cl_context_init_computing(struct compute_data *data) { cl_int err; cl_uint num_platforms; cl_uint num_devices; _info.platform_id = NULL; err = clGetPlatformIDs(1, &(_info.platform_id), &num_platforms); checkCLError("getPlatformIDs", err); if (err != CL_SUCCESS) { return; } err = clGetDeviceIDs(_info.platform_id, CL_DEVICE_TYPE_GPU, 1, &(_info.device_id), &num_devices); checkCLError("getDevicesIDs", err); if (err != CL_SUCCESS) { return; } LOGD("There are : %d devices available", num_devices); cl_context_properties props[] = { CL_GL_CONTEXT_KHR, (cl_context_properties) eglGetCurrentContext(), CL_EGL_DISPLAY_KHR, (cl_context_properties) eglGetCurrentDisplay(), CL_CONTEXT_PLATFORM, (cl_context_properties) _info.platform_id, CL_NONE }; _info.context = clCreateContextFromType(props, CL_DEVICE_TYPE_GPU, NULL, NULL, &err); checkCLError("Creating an OpenCL context", err); if (err != CL_SUCCESS) { return; } _info.command_queue = clCreateCommandQueueWithProperties(_info.context, _info.device_id, NULL, &err); checkCLError("Creating command queue", err); if (err != CL_SUCCESS) { return; } LOGD("Context created"); cl_computing_init(&_info, data); } void cl_context_update_computing(struct compute_data *data) { cl_computing_update(&_info, data); } void cl_context_perform_computing(struct compute_data *data) { cl_computing_compute(&_info, data); } void cl_context_destroy_computing(struct compute_data *data) { cl_computing_destroy(&_info, data); clReleaseCommandQueue(_info.command_queue); clReleaseContext(_info.context); clReleaseDevice(_info.device_id); }<file_sep># Created by <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License cmake_minimum_required(VERSION 3.6) set(CMAKE_C_STANDARD 11) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DUSE_OPENCL=1") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c11 -O3 -fopenmp") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}") ## -------------------------------------------------------------------------------------------- ## --------------------- List all include files ----------------------------------------------- ## -------------------------------------------------------------------------------------------- include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/ ${CMAKE_CURRENT_SOURCE_DIR}/application ${CMAKE_CURRENT_SOURCE_DIR}/CL ${CMAKE_CURRENT_SOURCE_DIR}/cl_computing ${CMAKE_CURRENT_SOURCE_DIR}/cl_context ${CMAKE_CURRENT_SOURCE_DIR}/gl ${CMAKE_CURRENT_SOURCE_DIR}/gl_computing ${CMAKE_CURRENT_SOURCE_DIR}/global ${CMAKE_CURRENT_SOURCE_DIR}/model ${CMAKE_CURRENT_SOURCE_DIR}/rendering ) ## -------------------------------------------------------------------------------------------- ## ---------------------- List all src files -------------------------------------------------- ## -------------------------------------------------------------------------------------------- set( APPLICATION_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/application/application.c ) set( CL_CONTEXT_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/cl_context/cl_context.c ${CMAKE_CURRENT_SOURCE_DIR}/cl_context/kernel.c ) set( CL_COMPUTING_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/cl_computing/cl_computing.c ${CMAKE_CURRENT_SOURCE_DIR}/cl_computing/cl_grayscale.c ) set( GL_COMPUTING_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/gl_computing/gl_computing.c ${CMAKE_CURRENT_SOURCE_DIR}/gl_computing/conv3x3_f.c ${CMAKE_CURRENT_SOURCE_DIR}/gl_computing/grayscale_f.c ${CMAKE_CURRENT_SOURCE_DIR}/gl_computing/layer3x3x64_f.c ) set( GL_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/gl/gl_31_functions.c ${CMAKE_CURRENT_SOURCE_DIR}/gl/gl_context.c ${CMAKE_CURRENT_SOURCE_DIR}/gl/gl_thread.c ${CMAKE_CURRENT_SOURCE_DIR}/gl/shader.c ) set( GLOBAL_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/global/global.c ) set( MODEL_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/model/model.c ) set( RENDERING_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/rendering/rendering.c ) set( SRC_FILES ${CMAKE_CURRENT_SOURCE_DIR}/native_interface.c ${APPLICATION_SRCS} ${CL_CONTEXT_SRCS} ${CL_COMPUTING_SRCS} ${GL_COMPUTING_SRCS} ${GL_SRCS} ${GLOBAL_SRCS} ${MODEL_SRCS} ${RENDERING_SRCS} ) ## -------------------------------------------------------------------------------------------- ## ---------------------------- List libraries ------------------------------------------------ ## -------------------------------------------------------------------------------------------- add_library( OpenCL SHARED IMPORTED ) set_target_properties( OpenCL PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/../jniLibs/libOpenCL.so ) ## -------------------------------------------------------------------------------------------- ## --------------------------------- Build ---------------------------------------------------- ## -------------------------------------------------------------------------------------------- add_library(native_interface SHARED ${SRC_FILES}) target_link_libraries( native_interface OpenCL android EGL GLESv3 log m )
a9f545fdfd0be90a1084c218fe7341abfdf133e1
[ "Java", "C", "Makefile", "CMake" ]
33
C
aarnaud1/Openings
869f35d36d847af639fdab8cbcb7f0c7ea0f7922
f6ef8bd48771ab7c93555103f436e2c80d6e9ab7
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Post; use App\Like; use Auth; use Illuminate\Http\Request; use Illuminate\Database\QueryException; class PostController extends Controller { public function gotoDashboard() { $posts = Post::orderBy('created_at', 'desc')->get(); return view('dashboard', ['posts' => $posts]); } public function likePost(Request $request) { // TODO : find like, create new like, fill the fields, add number of likes $post = Post::find($request['postId']); $user = Auth::user(); $user_id = $user->id; // ** find liked post $like = $user->likes()->where('post_id',$post->id)->first(); if($like){ // ? : if liked by the user already // todo : unlike it if($like->is_liked){ $like->delete(); return response()->json(['msg'=>'success unliked'], 200); } } else{ // ? if post is not liked $like = new Like(); $like->post_id = $post->id; $like->user_id = $user->id; $like->is_liked = 1; $like->save(); return response()->json(['msg' => 'success liked'], 200); } } public function createPost(Request $request) { $post = new Post(); $post->body = $request['body']; // ? get the current user and save the relation post if ($request->user()->posts()->save($post)) { return redirect()->route('dashboard'); } } public function deletePost($post_id) { if (Auth::user() != $post->user) { // ? protecting route from other users return redirect()->back(); } $post = Post::where('id', $post_id)->first(); $post->delete(); return redirect('dashboard'); } public function editPost(Request $request) { $post = Post::find($request['postId']); $post->body = $request['body']; $post->update(); return response()->json(['message' => 'post edited'], 200); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('/x', function () { return view('x'); }); Route::get('/first', function () { return view('first'); }); Route::get('/signup', function () { return view('signup'); }); Route::get('/dashboard', [ 'uses' => 'PostController@gotoDashboard', 'as' => 'dashboard', ]); Route::get('/profile', [ 'uses' => 'UserController@profile', 'as' => 'profile', ]); Route::get('/profilepic/{filename}', [ 'uses' => 'UserController@getProfilePic', 'as' => 'profile.pic', ]); Route::get('/logout', [ 'uses' => 'UserController@logout', 'as' => 'logout', ]); Route::post('/createUser', [ 'uses' => 'UserController@postSignup', 'as' => 'create', // ? name of route ]); Route::post('/editProfile', [ 'uses' => 'UserController@editProfile', 'as' => 'profile.edit', // ? name of route ]); Route::post('/saveProfilePic', [ 'uses' => 'UserController@saveProfilePic', 'as' => 'profile.pic.save', // ? name of route ]); Route::post('/loginUser', [ 'uses' => 'UserController@postLogin', 'as' => 'login', // ? name of route ]); Route::post('/createpost', [ 'uses' => 'PostController@createPost', 'as' => 'post.create', // ? name of route ]); Route::post('/editpost', [ 'uses' => "PostController@editPost", 'as' => 'editpost', ]); Route::get('/deletepost/{post_id}', [ 'uses' => 'PostController@deletePost', 'as' => 'post.delete', ]); Route::post('/like', [ 'uses' => "PostController@likePost", 'as' => 'like', ]); <file_sep><?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\User; use Auth; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Storage; // use Illuminate\Support\Facades\Validator; class UserController extends Controller { public function profile() { return view('profile', ['user' => Auth::user()]); } public function getProfilePic($filename) { $file = Storage::disk('local')->get($filename); return new Response($file, 200); } public function saveProfilePic(Request $request) { $file = $request->file('profilepic'); $filename = Auth::user()->username. '.jpg'; if ($file) { Storage::disk('local')->put($filename, File::get($file)); return redirect('profile'); } } public function editProfile(Request $request) { $user = Auth::user(); $user->username = $request['username']; $user->email = $request['email']; $user->update(); return redirect('profile'); } public function postSignup(Request $request) { $request->validate([ 'email' => 'required|email|unique:users', // ** users is the table name 'password' => '<PASSWORD>', 'username' => 'required|unique:users', ]); $email = $request['email']; $password = <PASSWORD>($request['password']); $username = $request['username']; $user = new User(); $user->email = $email; $user->password = $<PASSWORD>; $user->username = $username; $user->save(); Auth::login($user); return redirect()->route('dashboard'); } public function postLogin(Request $request) { if (Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) { return redirect()->route('dashboard'); } else { return redirect()->back(); } } public function logout() { Auth::logout(); return redirect('/first'); } }
f7591d33d50be499fe18205ef22903b464874f04
[ "PHP" ]
3
PHP
shiki-boy/lsapp
81577f3d0f92cf279c39e5e895ae08c9670af08e
b49545eb2a43480ba3fc5d320bdde9e5d124e9cb
refs/heads/master
<repo_name>chinhnk/TIES437-01<file_sep>/TIES437-service/src/main/java/ties437/service/entities/City.java package ties437.service.entities; import org.json.simple.JSONObject; import ties437.service.commons.OntologyConstants; /** * Created by chinhnk on 4/3/2017. */ public class City extends Entity{ public static final String TYPE_URI = OntologyConstants.PREFIX_CB + "City"; private String name; private double latitude; private double longitude; public City(String uri) { super(uri); } public City(String uri, String name, double latitude, double longitude) { super(uri); this.name = name; this.latitude = latitude; this.longitude = longitude; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } @Override public String toString() { return "City{" + "uri=" + uri + ", name='" + name + '\'' + ", latitude=" + latitude + ", longitude=" + longitude + '}'; } public JSONObject toJSON() { JSONObject obj = new JSONObject(); obj.put("uri", this.uri); obj.put("name", this.name); obj.put("latitude", this.latitude); obj.put("longitude", this.longitude); return obj; } } <file_sep>/TIES437-service/src/main/java/ties437/service/entities/Entity.java package ties437.service.entities; /** * Created by chinhnk on 4/3/2017. */ public class Entity { protected String uri; // private List<Literal> public Entity(String uri) { this.uri = uri; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Entity)) return false; Entity entity = (Entity) o; return getUri().equals(entity.getUri()); } @Override public int hashCode() { return getUri().hashCode(); } } <file_sep>/TIES437-service/src/main/java/ties437/service/servlets/CityServlet.java package ties437.service.servlets; import org.apache.jena.rdf.model.Model; import org.json.simple.JSONArray; import ties437.service.commons.RdfUtils; import ties437.service.dao.CityDAO; import ties437.service.entities.City; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.List; /** * Created by chinhnk on 1/4/2016. */ @WebServlet("/city") @MultipartConfig public class CityServlet extends HttpServlet { public static final String PATH = "/city"; public static final String RDF_FILE_RELATIVE_URL = "/resources/rdf/cottage-booking-data.rdf"; private Model model; @Override public void init(ServletConfig config) throws ServletException { super.init(config); ServletContext context = config.getServletContext(); String fullPath = context.getRealPath(RDF_FILE_RELATIVE_URL); // load data from rdf file this.model = RdfUtils.getModelFromRDF(fullPath); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONArray cityArray = new JSONArray(); List<City> cityList = CityDAO.getAll(this.model); for (City city : cityList) { cityArray.add(city.toJSON()); } response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); writer.print(cityArray); } } <file_sep>/TIES437-service/src/main/java/ties437/service/entities/Cottage.java package ties437.service.entities; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import ties437.service.commons.OntologyConstants; import java.util.ArrayList; import java.util.List; /** * Created by chinhnk on 4/3/2017. */ public class Cottage extends Entity { public static final String TYPE_URI = OntologyConstants.PREFIX_CB + "Cottage"; private String name; private double latitude; private double longitude; private double distanceToLake; private String imageURL; private List<Bedroom> bedroomList = new ArrayList<Bedroom>(); private List<Booking> bookingList = new ArrayList<Booking>(); public Cottage(String uri) { super(uri); } public Cottage(String uri, String name, double latitude, double longitude, double distanceToLake, String imageURL, List<Bedroom> bedroomList, List<Booking> bookingList) { super(uri); this.name = name; this.latitude = latitude; this.longitude = longitude; this.distanceToLake = distanceToLake; this.imageURL = imageURL; this.bedroomList = bedroomList; this.bookingList = bookingList; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public List<Bedroom> getBedroomList() { return bedroomList; } public void setBedroomList(List<Bedroom> bedroomList) { this.bedroomList = bedroomList; } public double getDistanceToLake() { return distanceToLake; } public void setDistanceToLake(double distanceToLake) { this.distanceToLake = distanceToLake; } public String getImageURL() { return imageURL; } public void setImageURL(String imageURL) { this.imageURL = imageURL; } public List<Booking> getBookingList() { return bookingList; } public void setBookingList(List<Booking> bookingList) { this.bookingList = bookingList; } @Override public String toString() { return "Cottage{" + "uri=" + uri + ", name='" + name + '\'' + ", latitude=" + latitude + ", longitude=" + longitude + ", distanceToLake=" + distanceToLake + ", imageURL='" + imageURL + '\'' + ", bedroomList=" + bedroomList + ", bookingList=" + bookingList + '}'; } public JSONObject toJSON() { JSONObject obj = new JSONObject(); obj.put("uri", this.uri); obj.put("name", this.name); obj.put("latitude", this.latitude); obj.put("longitude", this.longitude); obj.put("distanceToLake", this.distanceToLake); obj.put("imageURL", this.imageURL); JSONArray bedroomJsonArray = new JSONArray(); for (Bedroom bedroom : this.bedroomList) { bedroomJsonArray.add(bedroom.toJSON()); } obj.put("bedroomList", bedroomJsonArray); JSONArray bookingJsonArray = new JSONArray(); for (Booking booking : this.bookingList) { bookingJsonArray.add(booking.toJSON()); } obj.put("bookingList", bookingJsonArray); return obj; } } <file_sep>/TIES437-service/src/main/resources/application.properties server.port = 8083 rdg.file.path = task2/rdg.rdf<file_sep>/TIES437-service/src/main/java/ties437/service/servlets/BookingServlet.java package ties437.service.servlets; import org.apache.jena.rdf.model.Model; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import ties437.service.commons.Constants; import ties437.service.commons.RdfUtils; import ties437.service.commons.Utils; import ties437.service.dao.CityDAO; import ties437.service.dao.CottageDAO; import ties437.service.entities.Bedroom; import ties437.service.entities.Booking; import ties437.service.entities.City; import ties437.service.entities.Cottage; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Created by chinhnk on 1/4/2016. */ @WebServlet("/booking") @MultipartConfig public class BookingServlet extends HttpServlet { public static final String PATH = "/booking"; public static final String P_BOOKER_NAME = "bookerName"; public static final String P_MIN_BEDROOM_COUNT = "minBedroomCount"; public static final String P_MIN_TOTAL_PLACE_COUNT = "minTotalPlaceCount"; public static final String P_MAX_DISTANCE_TO_LAKE = "maxDistanceToLake"; public static final String P_CITY = "city"; public static final String P_MAX_DISTANCE = "maxDistance"; public static final String P_START_DATE_STRING = "startDateString"; public static final String P_DURATION_DAY = "durationDay"; public static final String P_FLEX_DAY = "flexDay"; public static final String RDF_FILE_RELATIVE_URL = "/resources/rdf/cottage-booking-data.rdf"; private Model model; @Override public void init(ServletConfig config) throws ServletException { super.init(config); ServletContext context = config.getServletContext(); String fullPath = context.getRealPath(RDF_FILE_RELATIVE_URL); // load data from rdf file this.model = RdfUtils.getModelFromRDF(fullPath); } /** * required amount of places (people); * required amount of bedrooms; * max distance of a cottage from a lake (meters); * city (next to which cottage is located) and a max distance to that city from a cottage; * required amount of days; * starting day of a booking (dd.mm.yyyy) and max possible shift of it (+/- n days). * <p> * name of the booker; * booking number; * address of the cottage; * image of the cottage (URL of the image in the web); * actual amount of places in the cottage; * actual amount of bedrooms in the cottage; * actual distance to the lake (meters); * nearest city and a distance to it from the cottage; * booking period. */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String bookerName = request.getParameter(P_BOOKER_NAME); int minBedroomCount = Integer.parseInt(request.getParameter(P_MIN_BEDROOM_COUNT)); int minTotalPlaceCount = Integer.parseInt(request.getParameter(P_MIN_TOTAL_PLACE_COUNT)); double maxDistanceToLake = Double.parseDouble(request.getParameter(P_MAX_DISTANCE_TO_LAKE)); City city = CityDAO.getByURI(model, request.getParameter(P_CITY)); double maxDistance = Double.parseDouble(request.getParameter(P_MAX_DISTANCE)); String startDateString = request.getParameter(P_START_DATE_STRING); SimpleDateFormat formatter = new SimpleDateFormat(Constants.DATE_FORMAT_JS); Date startDate = null; try { startDate = formatter.parse(startDateString); } catch (ParseException e) { e.printStackTrace(); } int durationDay = Integer.parseInt(request.getParameter(P_DURATION_DAY)); int flexDay = Integer.parseInt(request.getParameter(P_FLEX_DAY)); JSONArray eligibleResponseArray = new JSONArray(); List<Cottage> allCottageList = CottageDAO.getAll(this.model); for (Cottage cottage : allCottageList) { JSONObject eligibleResponse = getEligible(cottage, minBedroomCount, minTotalPlaceCount, maxDistanceToLake, city, maxDistance, startDate, durationDay, flexDay); if (eligibleResponse != null) { eligibleResponse.put("bookerName", bookerName); System.out.println(eligibleResponse.toJSONString().replace("\\/", "/")); eligibleResponseArray.add(eligibleResponse); } } response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); writer.print(eligibleResponseArray.toJSONString().replace("\\/", "/")); } public static void main(String[] args) throws Exception { // String dataSourcePath = "D:\\Future Data\\WISE\\Spring 2017\\TIES437 Everything to Everything Interfaces\\TIES437-01\\web\\resources\\rdf\\cottage-booking-data.rdf"; // Model model = RdfUtils.getModelFromRDF(dataSourcePath); // // String bookerName = "Pekka"; // // int minBedroomCount = 2; // int minTotalPlaceCount = 4; // double maxDistanceToLake = 200.0; // // City city = CityDAO.getByURI(model, OntologyConstants.PREFIX_CBD + "Helsinki"); // double maxDistance = 7.0; String startDateString = "07-08-2017"; SimpleDateFormat formatter = new SimpleDateFormat(Constants.DATE_FORMAT_JS); Date startDate = formatter.parse(startDateString); System.out.println(startDate); // int durationDay = 5; // int flexDay = 2; // // List<Cottage> allCottageList = CottageDAO.getAll(model); // for (Cottage cottage : allCottageList) { // JSONObject eligibleResponse = getEligible(cottage, minBedroomCount, minTotalPlaceCount, // maxDistanceToLake, city, maxDistance, startDate, durationDay, flexDay); // if (eligibleResponse != null) { // eligibleResponse.put("bookerName", bookerName); // System.out.println(eligibleResponse.toJSONString().replace("\\/", "/")); // } // } // // // Shit has // String queryString1 = "PREFIX cb: <http://users.jyu.fi/~chnguyen/TIES437/cottage-booking.owl#>\n" + // "PREFIX cbd: <http://localhost:8080/resources/rdf/cottage-booking-data.rdf#>\n" + // "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n" + // "\n" + // "SELECT ?cottage\n" + // " (COUNT(DISTINCT ?bedroom) AS ?bedroomCount)\n" + // " (SUM(?placeCount) AS ?totalPlaceCount)\n" + // " ?distanceToLake\n" + // "WHERE {\n" + // " ?cottage a cb:Cottage .\n" + // " ?cottage cb:hasBedroom ?bedroom .\n" + // " ?bedroom cb:hasPlaceCount ?placeCount .\n" + // " ?cottage cb:hasDistanceToLake ?distanceToLake .\n" + // " ?booking a cb:Booking .\n" + // " FILTER NOT EXISTS {?booking cb:hasCottage ?cottage} .\n" + // "}\n" + // "GROUP BY ?cottage ?distanceToLake\n" + // "HAVING (\n" + // " ?bedroomCount >= " + minBedroomCount + "\n" + // " &&\n" + // " ?totalPlaceCount >= " + minTotalPlaceCount + "\n" + // " &&\n" + // " ?distanceToLake <= " + maxDistanceToLake + "\n" + // ")"; // // String queryString = // "SELECT *\n" + // "WHERE {\n" + // " ?s a <" + Bedroom.TYPE_URI + "> .\n" + // " ?s ?p ?o .\n" + // "}\n"; // // String queryString2 = "PREFIX cb: <http://users.jyu.fi/~chnguyen/TIES437/cottage-booking.owl#>\n" + // "PREFIX cbd: <http://localhost:8080/resources/rdf/cottage-booking-data.rdf#>\n" + // "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n" + // "\n" + // "SELECT ?cottage\n" + // " (COUNT(DISTINCT ?bedroom) AS ?bedroomCount)\n" + // " (SUM(?placeCount) AS ?totalPlaceCount)\n" + // " ?distanceToLake\n" + // " ?booking\n" + // " ?bookedStartDate\n" + // "WHERE {\n" + // " ?cottage a cb:Cottage .\n" + // // " ?cottage cb:hasBedroom ?bedroom .\n" + // " ?bedroom cb:hasPlaceCount ?placeCount .\n" + // // " ?cottage cb:hasDistanceToLake ?distanceToLake .\n" + // // " ?booking a cb:Booking .\n" + // " ?booking cb:hasCottage ?cottage .\n" + // " ?booking cb:hasStartDate ?bookedStartDate .\n" + // " ?booking cb:hasEndDate ?bookedEndDate .\n" + // " FILTER (\n" + // " ?bookedStartDate < \"2017-07-08T12:00:00+02:00\"^^xsd:dateTime\n" + // " ||\n" + // " ?bookedEndDate > \"2017-07-02T12:00:00+02:00\"^^xsd:dateTime\n" + // " ) .\n" + // "}\n" + // "GROUP BY ?cottage ?distanceToLake ?booking ?bookedStartDate"; // cb:hasEndDate "2017-07-07T12:00:00+02:00"^^xsd:dateTime ; // cb:hasStartDate "2017-07-01T12:00:00+02:00"^^xsd:dateTime . // BookingServlet.runQuery(model, queryString); // BookingServlet.runQuery(model, queryString1); // BookingServlet.runQuery(model, queryString2); } private static JSONObject getEligible(Cottage cottage, int minBedroomCount, int minTotalPlaceCount, double maxDistanceToLake, City city, double maxDistance, final Date startDate, int durationDay, int flexDay) { // check bedroomCount if (cottage.getBedroomList().size() < minBedroomCount) { return null; } // check totalPlaceCount int totalPlaceCount = 0; for (Bedroom bedroom : cottage.getBedroomList()) { totalPlaceCount += bedroom.getPlaceCount(); } if (totalPlaceCount < minTotalPlaceCount) { return null; } // check distanceToLake if (cottage.getDistanceToLake() > maxDistanceToLake) { return null; } // check distance double distance = Utils.distanceFromCoords( city.getLatitude(), city.getLongitude(), cottage.getLatitude(), cottage.getLongitude()); if (distance > maxDistance) { return null; } // check date List<Date> possibleStartDateList = new ArrayList<Date>(); if (!cottage.getBookingList().isEmpty()) { for (Booking booking : cottage.getBookingList()) { Date bookedStartDate = booking.getStartDate(); Date bookedEndDate = booking.getEndDate(); for (int i = -flexDay; i <= flexDay; i++) { Date possibleStartDate = Utils.addDays(startDate, i); Date possibleEndDate = Utils.addDays(possibleStartDate, durationDay); if (!(((possibleStartDate.compareTo(bookedStartDate) >= 0) && (possibleStartDate.compareTo(bookedEndDate) <= 0)) || ((possibleEndDate.compareTo(bookedStartDate) >= 0) && (possibleEndDate.compareTo(bookedEndDate) <= 0)))) { if (!possibleStartDateList.contains(possibleStartDate)) { possibleStartDateList.add(possibleStartDate); } } } if (possibleStartDateList.isEmpty()) { return null; } } } else { for (int i = -flexDay; i <= flexDay; i++) { Date possibleStartDate = Utils.addDays(startDate, i); possibleStartDateList.add(possibleStartDate); } } Collections.sort(possibleStartDateList, new Comparator<Date>() { public int compare(Date o1, Date o2) { return Long.compare(Utils.getDateDiff(startDate, o1), Utils.getDateDiff(startDate, o2)); } }); JSONObject obj = new JSONObject(); DecimalFormat df = new DecimalFormat("#.##"); obj.put("address", cottage.getName()); obj.put("imageURL", cottage.getImageURL()); obj.put("bedroomCount", cottage.getBedroomList().size()); obj.put("totalPlaceCount", totalPlaceCount); obj.put("distanceToLake", df.format(cottage.getDistanceToLake())); obj.put("city", city.getName()); obj.put("distance", df.format(distance)); JSONArray possibleStartDateJsonArray = new JSONArray(); SimpleDateFormat formatter = new SimpleDateFormat(Constants.DATE_FORMAT_JS); for (Date date : possibleStartDateList) { possibleStartDateJsonArray.add(formatter.format(date)); } obj.put("possibleStartDateList", possibleStartDateJsonArray); return obj; } } <file_sep>/TIES437-service/src/main/java/ties437/service/commons/RdfUtils.java package ties437.service.commons; import org.apache.jena.query.*; import org.apache.jena.rdf.model.*; import org.apache.jena.reasoner.Derivation; import org.apache.jena.reasoner.Reasoner; import org.apache.jena.reasoner.rulesys.GenericRuleReasoner; import org.apache.jena.reasoner.rulesys.Rule; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; /** * Created by chinhnk on 4/3/2017. */ public class RdfUtils { public static final String KEYWORD_SELECT = "SELECT"; public static final String KEYWORD_CONSTRUCT = "CONSTRUCT"; public static final String KEYWORD_DESCRIBE = "DESCRIBE"; public static final String KEYWORD_ASK = "ASK"; public static final String RDFA_API_LINK = "http://rdf-translator.appspot.com/convert/rdfa/xml/"; public static void main(String[] args) throws Exception { // String fileURL = "http%3A%2F%2Fusers.jyu.fi%2F~chnguyen%2FTIES452%2Ffinal%2Ffinal.xhtml"; Model model = RdfUtils.getModelFromRDF("D:\\Future Data\\WISE\\Spring 2017\\TIES437 Everything to Everything Interfaces\\TIES437-01\\web\\resources\\rdf\\cottage-booking-data.rdf"); // required amount of places (people); // required amount of bedrooms; // max distance of a cottage from a lake (meters); // city (next to which cottage is located) and a max distance to that city from a cottage; // required amount of days; // starting day of a booking (dd.mm.yyyy) and max possible shift of it (+/- n days). // name of the booker; // booking number; // address of the cottage; // image of the cottage (URL of the image in the web); // actual amount of places in the cottage; // actual amount of bedrooms in the cottage; // actual distance to the lake (meters); // nearest city and a distance to it from the cottage; // booking period. String queryString = "PREFIX cb: <http://users.jyu.fi/~chnguyen/TIES437/cottage-booking.owl#>\n" + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n" + "\n" + "SELECT *\n" + "WHERE {\n" + " <http://localhost:8080/resources/rdf/cottage-booking-data.rdf#Susiraja_82_1> ?p ?o .\n" + "}\n"; RdfUtils.runQuery(model, queryString); } public static Model getModelFromRDFa(String fileURL) throws IOException { URL url = new URL(RDFA_API_LINK + fileURL); System.out.println("GET RDFa URL:"); System.out.println(RDFA_API_LINK + fileURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String modelText = ""; String line; while ((line = br.readLine()) != null) { modelText += line + "\n"; } ByteArrayInputStream stream = new ByteArrayInputStream(modelText.getBytes()); Model model = ModelFactory.createDefaultModel(); model.read(stream, null); conn.disconnect(); model.write(System.out, Constants.RDF_LANG); return model; } public static Model getModelFromRDF(String fileURL) { Model model = ModelFactory.createDefaultModel(); try { model.read(new FileInputStream(fileURL), null, Constants.RDF_LANG); } catch (FileNotFoundException e) { e.printStackTrace(); } return model; } public static InfModel applyRules(Model model, String ruleSrc) throws IOException { PrintWriter writer = new PrintWriter("temp.rules", "UTF-8"); writer.println(ruleSrc); writer.close(); List<Rule> rules = Rule.rulesFromURL("temp.rules"); System.out.println(rules.size() + " rule(s)."); Reasoner reasoner = new GenericRuleReasoner(rules); reasoner.setDerivationLogging(true); InfModel infModel = ModelFactory.createInfModel(reasoner, model); PrintWriter out = new PrintWriter(System.out); for (StmtIterator i = infModel.listStatements(); i.hasNext(); ) { Statement s = i.nextStatement(); for (Iterator id = infModel.getDerivation(s); id.hasNext(); ) { System.out.println("Statement is " + s); Derivation derivation = (Derivation) id.next(); derivation.printTrace(out, true); } } out.flush(); return infModel; } public static String runQuery(Model model, String queryString) { String result = ""; Dataset dataset = DatasetFactory.create(model); Query query = QueryFactory.create(queryString); QueryExecution queryExecution = QueryExecutionFactory.create(query, dataset); if (Pattern.compile(Pattern.quote(KEYWORD_SELECT), Pattern.CASE_INSENSITIVE).matcher(queryString).find()) { ResultSet resultSet = queryExecution.execSelect(); String resultHead = ""; String resultBody = ""; boolean passFirstRow = false; while (resultSet.hasNext()) { QuerySolution row = resultSet.next(); Iterator<String> varNamesIterator = row.varNames(); while (varNamesIterator.hasNext()) { String varName = varNamesIterator.next(); if (!passFirstRow) { resultHead += varName + "\t"; } resultBody += row.get(varName).toString() + "\t"; } passFirstRow = true; resultBody += "\n"; } result = resultHead + "\n" + resultBody; } else if (Pattern.compile(Pattern.quote(KEYWORD_ASK), Pattern.CASE_INSENSITIVE).matcher(queryString).find()) { boolean answer = queryExecution.execAsk(); result = (answer) ? "Yes !!!" : "No..."; } else if (Pattern.compile(Pattern.quote(KEYWORD_CONSTRUCT), Pattern.CASE_INSENSITIVE).matcher(queryString).find()) { Model resultModel = queryExecution.execConstruct(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); resultModel.write(outputStream, Constants.RDF_LANG); result = outputStream.toString(); } else if (Pattern.compile(Pattern.quote(KEYWORD_DESCRIBE), Pattern.CASE_INSENSITIVE).matcher(queryString).find()) { Model resultModel = queryExecution.execDescribe(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); resultModel.write(outputStream, Constants.RDF_LANG); result = outputStream.toString(); } System.out.println(result); return result; } } <file_sep>/TIES437-service/src/main/java/ties437/service/entities/Booking.java package ties437.service.entities; import org.json.simple.JSONObject; import ties437.service.commons.OntologyConstants; import java.util.Date; /** * Created by chinhnk on 4/3/2017. */ public class Booking extends Entity { public static final String TYPE_URI = OntologyConstants.PREFIX_CB + "Booking"; private String bookerName; private Date startDate; private Date endDate; public Booking(String uri) { super(uri); } public Booking(String uri, String bookerName, Date startDate, Date endDate) { super(uri); this.bookerName = bookerName; this.startDate = startDate; this.endDate = endDate; } public String getBookerName() { return bookerName; } public void setBookerName(String bookerName) { this.bookerName = bookerName; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } @Override public String toString() { return "Booking{" + "uri=" + uri + ", bookerName='" + bookerName + '\'' + ", startDate=" + startDate + ", endDate=" + endDate + '}'; } public JSONObject toJSON() { JSONObject obj = new JSONObject(); obj.put("uri", this.uri); obj.put("bookerName", this.bookerName); obj.put("startDate", this.startDate.toString()); obj.put("endDate", this.endDate.toString()); return obj; } } <file_sep>/TIES437-mediator/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>TIES437</groupId> <artifactId>TIES437-mediator</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>TIES437</groupId> <artifactId>TIES437</artifactId> <version>1.0-SNAPSHOT</version> </parent> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <!-- SSWAP - START --> <!--https://mvnrepository.com/artifact/org.antlr/antlr-runtime--> <dependency> <groupId>org.antlr</groupId> <artifactId>antlr-runtime</artifactId> <version>3.2</version> </dependency> <!-- https://mvnrepository.com/artifact/aopalliance/aopalliance --> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.hp.hpl.jena/arq --> <dependency> <groupId>com.hp.hpl.jena</groupId> <artifactId>arq</artifactId> <version>2.8.7</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec --> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient --> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency> <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache-core --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.4.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.hibernate/ejb3-persistence --> <dependency> <groupId>org.hibernate</groupId> <artifactId>ejb3-persistence</artifactId> <version>1.0.2.GA</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.guava/guava --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>15.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.inject/guice --> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> <version>3.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.inject.extensions/guice-assistedinject --> <dependency> <groupId>com.google.inject.extensions</groupId> <artifactId>guice-assistedinject</artifactId> <version>3.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.inject.extensions/guice-jmx --> <dependency> <groupId>com.google.inject.extensions</groupId> <artifactId>guice-jmx</artifactId> <version>3.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.inject.extensions/guice-multibindings --> <dependency> <groupId>com.google.inject.extensions</groupId> <artifactId>guice-multibindings</artifactId> <version>3.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.inject.extensions/guice-throwingproviders --> <dependency> <groupId>com.google.inject.extensions</groupId> <artifactId>guice-throwingproviders</artifactId> <version>3.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.ibm.icu/icu4j --> <dependency> <groupId>com.ibm.icu</groupId> <artifactId>icu4j</artifactId> <version>3.4.4</version> </dependency> <!-- https://mvnrepository.com/artifact/com.hp.hpl.jena/iri --> <dependency> <groupId>com.hp.hpl.jena</groupId> <artifactId>iri</artifactId> <version>0.8</version> </dependency> <!-- https://mvnrepository.com/artifact/org.javassist/javassist --> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.14.0-GA</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.inject/javax.inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api --> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.hp.hpl.jena/jena --> <dependency> <groupId>com.hp.hpl.jena</groupId> <artifactId>jena</artifactId> <version>2.6.4</version> </dependency> <!-- https://mvnrepository.com/artifact/org.jgrapht/jgrapht-jdk1.5 --> <dependency> <groupId>org.jgrapht</groupId> <artifactId>jgrapht-jdk1.5</artifactId> <version>0.7.3</version> </dependency> <!-- https://mvnrepository.com/artifact/com.martiansoftware/jsap --> <dependency> <groupId>com.martiansoftware</groupId> <artifactId>jsap</artifactId> <version>2.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.json/json --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20140107</version> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.13</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-core --> <dependency> <groupId>org.apache.lucene</groupId> <artifactId>lucene-core</artifactId> <version>2.3.1</version> </dependency> <!--https://mvnrepository.com/artifact/org.openrdf.sesame/sesame--> <dependency> <groupId>org.openrdf.sesame</groupId> <artifactId>sesame</artifactId> <version>2.7.7</version> </dependency> <!-- https://mvnrepository.com/artifact/com.sun.xml/relaxngDatatype --> <dependency> <groupId>com.sun.xml</groupId> <artifactId>relaxngDatatype</artifactId> <version>1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.hp.hpl.jena/sdb --> <dependency> <groupId>com.hp.hpl.jena</groupId> <artifactId>sdb</artifactId> <version>1.3.3</version> </dependency> <!-- https://mvnrepository.com/artifact/stax/stax-api --> <dependency> <groupId>stax</groupId> <artifactId>stax-api</artifactId> <version>1.0.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.codehaus.woodstox/wstx-asl --> <dependency> <groupId>org.codehaus.woodstox</groupId> <artifactId>wstx-asl</artifactId> <version>3.2.9</version> </dependency> <!-- https://mvnrepository.com/artifact/xerces/xercesImpl --> <dependency> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> <version>2.7.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.sun.msv.datatype.xsd/xsdlib --> <dependency> <groupId>com.sun.msv.datatype.xsd</groupId> <artifactId>xsdlib</artifactId> <version>20060615</version> </dependency> <!-- aterm-java-1.6 --> <dependency> <groupId>aterm-java-1.6</groupId> <artifactId>aterm-java-1.6</artifactId> <scope>system</scope> <version>1.0</version> <systemPath>${basedir}\lib\aterm-java-1.6.jar</systemPath> </dependency> <!-- sswap --> <dependency> <groupId>sswap</groupId> <artifactId>sswap</artifactId> <scope>system</scope> <version>1.0</version> <systemPath>${basedir}\lib\sswap.jar</systemPath> </dependency> <!-- empire-0.8.3 --> <dependency> <groupId>empire-0.8.3</groupId> <artifactId>empire-0.8.3</artifactId> <scope>system</scope> <version>0.8.3</version> <systemPath>${basedir}\lib\empire-0.8.3.jar</systemPath> </dependency> <!-- empire-test-0.8.3 --> <dependency> <groupId>empire-test-0.8.3</groupId> <artifactId>empire-test-0.8.3</artifactId> <scope>system</scope> <version>0.8.3</version> <systemPath>${basedir}\lib\empire-test-0.8.3.jar</systemPath> </dependency> <!-- empire-jena-0.8.3 --> <dependency> <groupId>empire-jena-0.8.3</groupId> <artifactId>empire-jena-0.8.3</artifactId> <scope>system</scope> <version>0.8.3</version> <systemPath>${basedir}\lib\empire-jena-0.8.3.jar</systemPath> </dependency> <!-- empire-sesame-0.8.3 --> <dependency> <groupId>empire-sesame-0.8.3</groupId> <artifactId>empire-sesame-0.8.3</artifactId> <scope>system</scope> <version>0.8.3</version> <systemPath>${basedir}\lib\empire-sesame-0.8.3.jar</systemPath> </dependency> <!-- empire-sesame-test-0.8.3 --> <dependency> <groupId>empire-sesame-test-0.8.3</groupId> <artifactId>empire-sesame-test-0.8.3</artifactId> <scope>system</scope> <version>0.8.3</version> <systemPath>${basedir}\lib\empire-sesame-test-0.8.3.jar</systemPath> </dependency> <!-- empire-sesame-test-0.8.3 --> <dependency> <groupId>cp-common-fourstore-0.3.1</groupId> <artifactId>cp-common-fourstore-0.3.1</artifactId> <scope>system</scope> <version>0.3.1</version> <systemPath>${basedir}\lib\cp-common-fourstore-0.3.1.jar</systemPath> </dependency> <!-- cp-common-openrdf-2.0.1 --> <dependency> <groupId>cp-common-openrdf-2.0.1</groupId> <artifactId>cp-common-openrdf-2.0.1</artifactId> <scope>system</scope> <version>2.0.1</version> <systemPath>${basedir}\lib\cp-common-openrdf-2.0.1.jar</systemPath> </dependency> <!-- cp-common-utils-3.1.1.jar --> <dependency> <groupId>cp-common-utils-3.1.1</groupId> <artifactId>cp-common-utils-3.1.1</artifactId> <scope>system</scope> <version>3.1.1</version> <systemPath>${basedir}\lib\cp-common-utils-3.1.1.jar</systemPath> </dependency> <!-- cp-common-utils-1.1.jar --> <dependency> <groupId>cp-common-utils-1.1</groupId> <artifactId>cp-common-utils-1.1</artifactId> <scope>system</scope> <version>1.1</version> <systemPath>${basedir}\lib\cp-common-utils-1.1.jar</systemPath> </dependency> <!-- cp-common-utils-2.3.jar --> <dependency> <groupId>cp-common-utils-2.3</groupId> <artifactId>cp-common-utils-2.3</artifactId> <scope>system</scope> <version>2.3</version> <systemPath>${basedir}\lib\cp-common-utils-2.3.jar</systemPath> </dependency> <!-- cp-common-utils-2.4.1.1.jar --> <dependency> <groupId>cp-common-utils-2.4.1.1</groupId> <artifactId>cp-common-utils-2.4.1.1</artifactId> <scope>system</scope> <version>2.4.1.1</version> <systemPath>${basedir}\lib\cp-common-utils-2.4.1.1.jar</systemPath> </dependency> <!-- cp-common-utils-2.5.0.jar --> <dependency> <groupId>cp-common-utils-2.5.0</groupId> <artifactId>cp-common-utils-2.5.0</artifactId> <scope>system</scope> <version>2.5.0</version> <systemPath>${basedir}\lib\cp-common-utils-2.5.0.jar</systemPath> </dependency> <!-- cp-common-utils-3.0.jar --> <dependency> <groupId>cp-common-utils-3.0</groupId> <artifactId>cp-common-utils-3.0</artifactId> <scope>system</scope> <version>3.0</version> <systemPath>${basedir}\lib\cp-common-utils-3.0.jar</systemPath> </dependency> <!-- openrdf-sesame-2.7.7.jar --> <dependency> <groupId>openrdf-sesame-2.7.7</groupId> <artifactId>openrdf-sesame-2.7.7</artifactId> <scope>system</scope> <version>2.7.7</version> <systemPath>${basedir}\lib\openrdf-sesame-2.7.7.jar</systemPath> </dependency> <!-- owlapi and pellet since there is no specified version in the jars --> <!-- owlapi-bin.jar --> <dependency> <groupId>owlapi</groupId> <artifactId>owlapi</artifactId> <scope>system</scope> <version>3.2.4</version> <systemPath>${basedir}\lib\owlapi-bin.jar</systemPath> </dependency> <!-- pellet-cli.jar --> <dependency> <groupId>pellet-cli</groupId> <artifactId>pellet-cli</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-cli.jar</systemPath> </dependency> <!-- pellet-core.jar --> <dependency> <groupId>pellet-core</groupId> <artifactId>pellet-core</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-core.jar</systemPath> </dependency> <!--pellet-datatypes.jar--> <dependency> <groupId>pellet-datatypes</groupId> <artifactId>pellet-datatypes</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-datatypes.jar</systemPath> </dependency> <!--pellet-dig.jar--> <dependency> <groupId>pellet-dig</groupId> <artifactId>pellet-dig</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-dig.jar</systemPath> </dependency> <!--pellet-el.jar--> <dependency> <groupId>pellet-el</groupId> <artifactId>pellet-el</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-el.jar</systemPath> </dependency> <!--pellet-explanation.jar--> <dependency> <groupId>pellet-explanation</groupId> <artifactId>pellet-explanation</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-explanation.jar</systemPath> </dependency> <!--pellet-jena.jar--> <dependency> <groupId>pellet-jena</groupId> <artifactId>pellet-jena</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-jena.jar</systemPath> </dependency> <!--pellet-modularity.jar--> <dependency> <groupId>pellet-modularity</groupId> <artifactId>pellet-modularity</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-modularity.jar</systemPath> </dependency> <!--pellet-owlapi.jar--> <dependency> <groupId>pellet-owlapi</groupId> <artifactId>pellet-owlapi</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-owlapi.jar</systemPath> </dependency> <!--pellet-owlapiv3.jar--> <dependency> <groupId>pellet-owlapiv3</groupId> <artifactId>pellet-owlapiv3</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-owlapiv3.jar</systemPath> </dependency> <!--pellet-pellint.jar--> <dependency> <groupId>pellet-pellint</groupId> <artifactId>pellet-pellint</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-pellint.jar</systemPath> </dependency> <!--pellet-query.jar--> <dependency> <groupId>pellet-query</groupId> <artifactId>pellet-query</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-query.jar</systemPath> </dependency> <!--pellet-rules.jar--> <dependency> <groupId>pellet-rules</groupId> <artifactId>pellet-rules</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-rules.jar</systemPath> </dependency> <!--pellet-test.jar--> <dependency> <groupId>pellet-test</groupId> <artifactId>pellet-test</artifactId> <scope>system</scope> <systemPath>${basedir}\lib\pellet-test.jar</systemPath> </dependency> <!-- SSWAP - END --> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>mvnrepository</id> <url>https://mvnrepository.com/repos</url> </repository> </repositories> </project><file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>TIES437</groupId> <artifactId>TIES437</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <modules> <module>TIES437-ui</module> <module>TIES437-service</module> <module>TIES437-mediator</module> </modules> <properties> <java.version>1.8</java.version> <spring.version>4.3.0.RELEASE</spring.version> <springboot.version>1.3.3.RELEASE</springboot.version> <logback.version>1.1.6</logback.version> <maven.resource.version>2.6</maven.resource.version> <maven.compiler.version>3.5.1</maven.compiler.version> <jackson.version>2.5.3</jackson.version> <javax.servlet.api.version>3.1.0</javax.servlet.api.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>${springboot.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> <!-- JSON --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${javax.servlet.api.version}</version> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.jena/jena-core --> <dependency> <groupId>org.apache.jena</groupId> <artifactId>jena-core</artifactId> <version>3.0.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.jena/jena-arq --> <dependency> <groupId>org.apache.jena</groupId> <artifactId>jena-arq</artifactId> <version>3.0.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.7</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.xml.rpc</groupId> <artifactId>javax.xml.rpc-api</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-servlet</artifactId> <version>9.3.10.v20160621</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>${springboot.version}</version> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven.compiler.version}</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project><file_sep>/TIES437-mediator/src/main/java/ties437/mediator/Application.java package ties437.mediator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; /** * Created by V.Tsybulko on 17.04.2017. */ @SpringBootApplication @ComponentScan(basePackages = {"ties437.mediator"}) public class Application extends SpringBootServletInitializer { final static Logger logger = LoggerFactory.getLogger(Application.class); @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } public static void main(String[] args) { SpringApplication.run(Application.class, args); logger.info("Mediator started!"); } }
ba7ff17abb73a1b9b56ecbb60ab5a51ac4c75ef4
[ "Java", "Maven POM", "INI" ]
11
Java
chinhnk/TIES437-01
f11c03d9cfb179cb7086b4f5c7ba46a0bde2c6d4
a5122ed6756d8515437ecba7dd50b438aea3816e
refs/heads/master
<file_sep>#' @title DDT Data Set #' #' @description A data set collected by the US forces from the Tennessee River and its tributaries #' #' @format a list with 6 variables, which are: #' \describe{ #' \item{MILE}{ the mile of the river at which the fish was taken} #' \item{LENGTH}{ the length of the wish} #' \item{WEIGHT}{ the weight of the fish} #' \item{DDT}{ the DDT concentration in the fish} #' \item{RIVER}{ the river from which the fish was sampled} #' \item{SPECIES}{ the species of fish} #' } "ddt" <file_sep>#' Shiny Plotting Function #' #' @param plotType the type of plot to be made #' @param mile whether or not to include the MILE variable #' @param length whether or not to include the LENGTH variable #' @param weight whether or not to include the WEIGHT variable #' @param ddt whether or not to include the DDT variable #' @param FCM whether or not to include the FCM River #' @param LCM whether or not to include the LCM River #' @param SCM whether or not to include the SCM River #' @param TRM whether or not to include the TRM River #' @param catfish whether or not to include the CCATFISH Species #' @param buffalo whether or not to include the SMBUFFALO Species #' @param bass whether or not to includ ethe LMBASS Species #' @param pcaType whether to use the covariance or correlation matrix for PCA #' @param col variable to use to differentiate points in scatterplot #' #' @return a plot of data #' @export #' #' @examples plotter("scatterplot",length=FALSE,buffalo=FALSE) plotter=function(plotType="screeplot",mile=TRUE,length=TRUE,weight=TRUE,ddt=TRUE, FCM=TRUE,LCM=TRUE,SCM=TRUE,TRM=TRUE, catfish=TRUE,buffalo=TRUE,bass=TRUE, pcaType="covariance",col="RIVER"){ # Exit if not enough data is being used to conduct analysis. # For inadequate PCA variables if (mile+length+weight+ddt<2){ stop("At least quantiative variables must be input.") } # Simplify descriptions of plots if needed. if (plotType=="scatterplot (1st two variables)"){ plotType="scatterplot" } if (plotType=="boxplot (1st variable)"){ plotType="boxplot" } if (plotType=="connected dot plot (1st two variables)"){ plotType="connected" } # Determine what will be needed from the constructor. if (pcaType=="covariance"){ cor=FALSE } else { cor=TRUE } # Create the inf object. infObj=const(plotType,cor,mile,length,weight,ddt,FCM,LCM,SCM,TRM,catfish, buffalo,bass,swap) # Plotting function for inf objects plot.inf=function(obj,type="scatterplot",col="RIVER", prop=FALSE,cumProp=FALSE,eig=FALSE,screeVar=FALSE){ if (plotType=="scatterplot"){ dat=obj$dat lab=c(length=2) if (colnames(dat)[1]=="MILE"){ lab[1]="Mile" } if (colnames(dat)[2]=="MILE"){ lab[2]="Mile" } if (colnames(dat)[1]=="LENGTH"){ lab[1]="Length" } if (colnames(dat)[2]=="LENGTH"){ lab[2]="Length" } if (colnames(dat)[1]=="WEIGHT"){ lab[1]="Weight" } if (colnames(dat)[2]=="WEIGHT"){ lab[2]="Weight" } if (colnames(dat)[1]=="DDT"){ lab[1]="DDT Level" } if (colnames(dat)[2]=="DDT"){ lab[2]="DDT Level" } library(ggplot2) # Create a ggplot object. cn=colnames(dat) if (col=="RIVER"){ if (lab[1]=="Mile"){ if (lab[2]=="Length"){ g=ggplot(dat,aes(x=MILE,y=LENGTH,col=RIVER)) } } if (lab[1]=="Mile"){ if (lab[2]=="Weight"){ g=ggplot(dat,aes(x=MILE,y=WEIGHT,col=RIVER)) } } if (lab[1]=="Mile"){ if (lab[2]=="DDT Level"){ g=ggplot(dat,aes(x=MILE,y=DDT,col=RIVER)) } } if (lab[1]=="Length"){ if (lab[2]=="Mile"){ g=ggplot(dat,aes(x=LENGTH,y=MILE,col=RIVER)) } } if (lab[1]=="Length"){ if (lab[2]=="Weight"){ g=ggplot(dat,aes(x=LENGTH,y=WEIGHT,col=RIVER)) } } if (lab[1]=="Length"){ if (lab[2]=="DDT Level"){ g=ggplot(dat,aes(x=LENGTH,y=DDT,col=RIVER)) } } if (lab[1]=="Weight"){ if (lab[2]=="Mile"){ g=ggplot(dat,aes(x=WEIGHT,y=MILE,col=RIVER)) } } if (lab[1]=="Weight"){ if (lab[2]=="Length"){ g=ggplot(dat,aes(x=WEIGHT,y=LENGTH,col=RIVER)) } } if (lab[1]=="Weight"){ if (lab[2]=="DDT Level"){ g=ggplot(dat,aes(x=WEIGHT,y=DDT,col=RIVER)) } } if (lab[1]=="DDT Level"){ if (lab[2]=="Mile"){ g=ggplot(dat,aes(x=DDT,y=MILE,col=RIVER)) } } if (lab[1]=="DDT Level"){ if (lab[2]=="Length"){ g=ggplot(dat,aes(x=DDT,y=LENGTH,col=RIVER)) } } if (lab[1]=="DDT Level"){ if (lab[2]=="Weight"){ g=ggplot(dat,aes(x=DDT,y=WEIGHT,col=RIVER)) } } } if (col=="SPECIES"){ if (lab[1]=="Mile"){ if (lab[2]=="Length"){ g=ggplot(dat,aes(x=MILE,y=LENGTH,col=SPECIES)) } } if (lab[1]=="Mile"){ if (lab[2]=="Weight"){ g=ggplot(dat,aes(x=MILE,y=WEIGHT,col=SPECIES)) } } if (lab[1]=="Mile"){ if (lab[2]=="DDT Level"){ g=ggplot(dat,aes(x=MILE,y=DDT,col=SPECIES)) } } if (lab[1]=="Length"){ if (lab[2]=="Mile"){ g=ggplot(dat,aes(x=LENGTH,y=MILE,col=SPECIES)) } } if (lab[1]=="Length"){ if (lab[2]=="Weight"){ g=ggplot(dat,aes(x=LENGTH,y=WEIGHT,col=SPECIES)) } } if (lab[1]=="Length"){ if (lab[2]=="DDT Level"){ g=ggplot(dat,aes(x=LENGTH,y=DDT,col=SPECIES)) } } if (lab[1]=="Weight"){ if (lab[2]=="Mile"){ g=ggplot(dat,aes(x=WEIGHT,y=MILE,col=SPECIES)) } } if (lab[1]=="Weight"){ if (lab[2]=="Length"){ g=ggplot(dat,aes(x=WEIGHT,y=LENGTH,col=SPECIES)) } } if (lab[1]=="Weight"){ if (lab[2]=="DDT Level"){ g=ggplot(dat,aes(x=WEIGHT,y=DDT,col=SPECIES)) } } if (lab[1]=="DDT Level"){ if (lab[2]=="Mile"){ g=ggplot(dat,aes(x=DDT,y=MILE,col=SPECIES)) } } if (lab[1]=="DDT Level"){ if (lab[2]=="Length"){ g=ggplot(dat,aes(x=DDT,y=LENGTH,col=SPECIES)) } } if (lab[1]=="DDT Level"){ if (lab[2]=="Weight"){ g=ggplot(dat,aes(x=DDT,y=WEIGHT,col=SPECIES)) } } } g=g+coord_equal() if (plotType=="scatterplot"){ sg=g+geom_point()+ggtitle("Scatterplot of DDT Data") } } if (plotType=="screeplot"){ pc=obj$pc len=length(pc$sdev)+1 screeplot(pc,xlim=c(0,len),ylim=c(0,max(pc$sdev)^2+1000), main="Principal Components of DDT Data") } if (plotType=="biplot"){ pc=obj$pc biplot(pc,main="Biplot of DDT Data") } if (plotType=="boxplot"){ if (mile==TRUE){ b=dat$MILE lab="Mile" } else if (length==TRUE){ b=dat$LENGTH lab="Length" } else if (weight==TRUE){ b=dat$WEIGHT lab="Weight" } else if (ddt==TRUE){ b=dat$DDT lab="DDT Concentration" } boxplot(b,main=substitute(paste("Boxplot of ",lab))) } if (plotType=="scatterplot"){ sg } } plot.inf(infObj,type=plotType,col=col,prop=prop, cumProp=cumProp,eig=eig,screeVar=screeVar) } <file_sep>library(shinydashboard) library(shinyWidgets) ui <- dashboardPage( dashboardHeader(title="Analysis of DDT Data",titleWidth=500), dashboardSidebar(disable=TRUE), dashboardBody( fluidRow( box(plotOutput("plot1",height=500)), # Box 1: Quantitative Variable Restrictions box( status="warning", solidHeader=TRUE, collapsible=TRUE, width=3, background="red", title="Quantitative Variables", prettySwitch("mile","Include Mile?",TRUE), prettySwitch("length","Include Length?",TRUE), prettySwitch("weight","Include Weight?",TRUE), prettySwitch("ddt","Include DDT Level?",TRUE) ), # Box 2: Qualitative Variable Restrictions box( status="warning", solidHeader=TRUE, collapsible=TRUE, width=3, background="blue", title="Qualitative Variable Limitations", prettySwitch("FCM","Include the FCM River?",TRUE), prettySwitch("LCM","Include the LCM River?",TRUE), prettySwitch("SCM","Include the SCM River?",TRUE), prettySwitch("TRM","Include the TRM River?",TRUE), prettySwitch("catfish","Include CCatfish?",TRUE), prettySwitch("buffalo","Include SMBuffalo?",TRUE), prettySwitch("bass","Include LMBass?",TRUE) ), # Box 3: Type of Output Plot box( status="warning", solidHeader=TRUE, collapsible=TRUE, width=3, background="orange", title="Type of Plot", selectInput("plotType","Type of Output", list("scatterplot (1st two variables)","screeplot","biplot", "boxplot (1st variable)"), "screeplot") ), # Box 4: Plot Settings box( status="warning", solidHeader=TRUE, collapsible=TRUE, width=3, background="purple", title="PCA Settings", selectInput("pcaType","Type of Matrix for PCA",list("covariance","correlation"),"covariance"), selectInput("col","Color Data by?",list("RIVER","SPECIES"),"RIVER") ) ) ) ) <file_sep>library(shinydashboard) library(shinyWidgets) library(Project2AndrewMitchell) #' Shiny Server Function #' #' @param input the input of the function #' @param output the output of the function #' #' @return a shiny server #' @export #' #' @examples server() server<-function(input,output){ output$plot1<-renderPlot({ plotter(plotType=input$plotType, mile=input$mile,length=input$length,weight=input$weight,ddt=input$ddt, FCM=input$FCM,LCM=input$LCM,SCM=input$SCM,TRM=input$TRM, catfish=input$catfish,buffalo=input$buffalo,bass=input$bass, pcaType=input$pcaType,col=input$col) }) } <file_sep>#' Constructor Function #' #' @param plotType the type of plot to be made #' @param cor whether or not to use the correlation matrix for PCA #' @param mile whether or not to include the mile variable #' @param length whether or not to include the length variable #' @param weight whether or not to include the weight variable #' @param ddt whether or not to include the DDT variable #' @param FCM whether or not to include the FCM River #' @param LCM whether or not to include the LCM River #' @param SCM whether or not to include the SCM River #' @param TRM whether or not to include the TRM River #' @param catfish whether or not to include the CCATFISH species #' @param buffalo whether or not to include the SMBUFFALO species #' @param bass whether or not to include the LMBASS species #' #' @return #' @export #' #' @examples const=function(plotType="scatterplot",cor=FALSE,mile=TRUE,length=TRUE,weight=TRUE,ddt=TRUE, FCM=TRUE,LCM=TRUE,SCM=TRUE,TRM=TRUE, catfish=TRUE,buffalo=TRUE,bass=TRUE,swap=FALSE){ # Create the DDT data set. x=Project2AndrewMitchell::ddt # Remove subsets of the data if need be. # Rivers not to be included if (FCM==FALSE){ x=subset(x,RIVER!="FCM") } if (LCM==FALSE){ x=subset(x,RIVER!="LCM") } if (SCM==FALSE){ x=subset(x,RIVER!="SCM") } if (TRM==FALSE){ x=subset(x,RIVER!="TRM") } # Species to not be used if (catfish==FALSE){ x=subset(x,SPECIES!="CCATFISH") } if (buffalo==FALSE){ x=subset(x,SPECIES!="SMBUFFALO") } if (bass==FALSE){ x=subset(x,SPECIES!="LMBASS") } # Remove quantitative variables if need be. if (ddt==FALSE){ x=x[,-4] } if (weight==FALSE){ x=x[,-3] } if (length==FALSE){ x=x[,-2] } if (mile==FALSE){ x=x[,-1] } # Conduct PCA on the data. xPC=x # Remove the quantitative variables from the data. rem=c() for (i in 1:ncol(xPC)){ c=ncol(xPC)+1-i if (class(xPC[1,c])=="factor"){ rem[i]=c } } if (length(rem)>=1){ for (i in 1:length(rem)){ xPC=xPC[,-rem[i]] } } # Conduct PCA. pc=princomp(xPC,cor=cor) # Find the eigenvalues and eigenvectors for the chosen matrix. # Covariance matrix if (cor==FALSE){ ei=eigen(cov(xPC)) } # Correlation matrix else { ei=eigen(cor(xPC)) } # Store the values and vectors. eiVal=ei$values eiVec=ei$vectors obj=list(dat=x,pc=pc,eiVal=eiVal,eiVec=eiVec) class(obj)="inf" obj } <file_sep>--- title: "AndrewMitchellProject2" author: "<NAME>" output: rmarkdown::html_vignette: toc: yes vignette: > %\VignetteIndexEntry{AndrewMitchellProject2} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(AndrewMitchellProject2) ``` # DDT Data Set The DDT data set within this package details observations taken on fish in areas in and in tributaries of the Tennessee River, where researchers were measuring the concentration of DDT present in each fish. The following measurements were taken on each fish: * Mile - the mile of the river at which the fish was caught to be examined * Length - the length of the fish * Weight - the weight of the fish * DDT - the concentration of DDT measured within the fish * River - the section of the river in which the fish was caught * Species - the species of the fish This data set is the basis of the functions within this package. # plotter() function The plotter() function takes in a variety of variables designed to function alongside the Shiny server included in the package. The function can create the following types of plots. * Scatterplots of two variables * Biplots of principal components of data * Boxplots of one variable * Screeplots of principal components of data Transformations for the data are done with in the const() function, which releases a constructed object of type inf, which contains the following: * The original data set, possibly rearranged or with parts removed (i.e. certain variables or subsets of the data that have a particular value for a given variable) * A principal component object created for a specified subset of the data or the entire data set * The eigenvalues of the covariance or correlation matrix for the quantitative variables from the data * The eigenvectors corresponding to the above eigenvalues Each of these portions of the returned data are used in the creation of the plots being studied. ## Scatterplot Scatterplots can be created by the plotter() function for any combination of two of the quantitative variables in the DDT data set. In addition, the data within the plot can be color-coded to indicate either the river from which they were taken or the species of fish depending on the user's choice. The scatterplot indicates a significant difference in fish concentrations between the Tennessee River and its tributaries, with the fish the furthest distances nearly all coming from this river. ## Biplot Biplots plot the most significant two principal components of the data set, i.e. those corresponding to the largest eigenvalues. The individual data are plotted, and arrows are placed on the plot for each variable being used in PCA with a magnitude and direction. Arrows pointing to the right have a positive correlation with the first principal component, and pointing up have a positive correlation with the second principal component. The opposite can be said for arrows pointing to the left and downward respectively. An arrow with a larger magnitude in a particular direction indicates a stronger correlation, no matter whether positive or negative. The principal components of the data are defined as follows, where $\{y_i\}_{i=1}^p$ are the principal components (with $p$ being the number of variables being used), and $\{e_i\}_{i=1}^p$ are the eigenvectors of whichever matrix is being used: $$ \begin{eqnarray} y_1&=&e_{11}x_1+e_{12}x_2+...+e_{1p}x_p\\ y_2&=&e_{21}x_1+e_{22}x_2+...+e_{2p}x_p\\ \vdots\\ y_p&=&e_{p1}x_1+e_{p2}x_2+...+e_{pp}x_p \end{eqnarray} $$ From this construction, one can see how since the largest eigenvalue has large effect on the principal component variance, the variable whose influence matches the first principal component would have the largest effect overall. ## Boxplot Boxplots are used primarily as an indication of spread of data or comparison between sets of data. The lines on the box on a boxplot indicate the quartiles of the data, and the end of the "whiskers" indicate the last data point before the others are considered outliers (typically defined in this situation by not within 1.5 times the interquartile range of the data from the middle 50% of data). Boxplots also indicate the median, which can be a useful indicator of centrality due to its resistance to outliers. ## Screeplot The screeplot shows the variances of the principal components in the order of importance of the components. The most common use of the screeplot is to determine at which point to cut off which principal components are being examined: only those who have significant impact on the data will be used. The plot does not give any exact numbers to calculate, but researchers use the change in slopes of lines connecting the components' variances to make subjective decisions. Such decisions can alleviate some of the challenges that arise when dealing with vast numbers of variables. # Shiny Server The server in this package is comprised of the server.R and ui.R files. These files together provide the following options for the user of the server: * Removal of quantitative variables (up to the point where they can still be used) * Removal of data of a particular species or a particular river * Changing the method by which PCA is carried out (i.e. correlation or covariance matrix) * Determining which variables will be used in plots * Determining what plot will be produced at any given time
cc00c074d0413384363bce8cae26842d1f0d3ce3
[ "R", "RMarkdown" ]
6
R
ajmitchell715/AndrewMitchellProject2
923b45ab1648628315a0a8a7e6b8bb35127d29bf
a80d57427cfecb32f1750ab4d28bf86587d781e6
refs/heads/master
<repo_name>RotcivOcnarb/Arqdesis-Aula15<file_sep>/app/src/main/java/br/usjt/arqdesis/cliente/ListaClientesActivity.java package br.usjt.arqdesis.cliente; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; public class ListaClientesActivity extends Activity { public static final String ID = "br.usjt.arqdesis.cliente.id"; ArrayList<String> lista; Activity atividade; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lista_clientes); atividade = this; Intent intent = getIntent(); String chave = intent.getStringExtra(MainActivity.CHAVE); lista = buscaClientes(chave); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lista); ListView listView = (ListView) findViewById(R.id.listview); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ public void onItemClick(AdapterView<?> parent, View view, int position, long id){ Intent intent = new Intent(atividade, DetalheClienteActivity.class); intent.putExtra(ID, ListaDados.getInstance().getIdOf(lista.get(position))); startActivity(intent); } }); } public ArrayList<String> buscaClientes(String chave){ ArrayList<String> lista = ListaDados.getInstance().getLista(); if(chave == null || chave.length() == 0){ return lista; } else{ ArrayList<String> subLista = new ArrayList<String>(); for(String nome : lista){ if(nome.toUpperCase().contains(chave.toUpperCase())){ subLista.add(nome); } } return subLista; } } } <file_sep>/app/src/main/java/br/usjt/arqdesis/cliente/DetalheClienteActivity.java package br.usjt.arqdesis.cliente; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class DetalheClienteActivity extends Activity { int position; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detalhe_cliente); TextView nome = (TextView) findViewById(R.id.nome_selecionado); Intent intent = getIntent(); position = intent.getIntExtra(ListaClientesActivity.ID, -1); nome.setText( ListaDados.getInstance().getLista().get(position) ); } boolean editing = false; public void editarNome(View view){ editing = !editing; if(editing){ Button botao = (Button) findViewById(R.id.botao_editar); botao.setText("Salvar"); EditText nome = (EditText) findViewById(R.id.nome_selecionado); nome.setEnabled(true); } else{ Button botao = (Button) findViewById(R.id.botao_editar); botao.setText("Editar"); EditText nome = (EditText) findViewById(R.id.nome_selecionado); ListaDados.getInstance().getLista().set(position, nome.getText().toString()); nome.setEnabled(false); } } public void excluirCliente(View view){ AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("Excluir"); alertDialog.setMessage("Deseja mesmo excluir " + ListaDados.getInstance().getLista().get(position) + "?"); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "SIM", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); ListaDados.getInstance().getLista().remove(position); Intent intent = new Intent(DetalheClienteActivity.this, MainActivity.class); startActivity(intent); } }); alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "NรƒO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } }
54009ff833cf57436fb513d98f11fcd5fe1e96b1
[ "Java" ]
2
Java
RotcivOcnarb/Arqdesis-Aula15
dec02ccfc20ca62aa7daf32fb170e02ad66b71cc
1d05415ed26f4e5711743a3b2a4fac28b6fa07db
refs/heads/master
<repo_name>ryancharris/dev-affirmations<file_sep>/index.js const axios = require("axios"); require("dotenv").config(); const addTweet = tweetId => { // Make HTTP request to hit AWS Lambda function axios({ data: { id: tweetId }, method: "post", url: process.env.LAMBDA_ADDRESS, headers: { "x-api-key": process.env.LAMBDA_KEY } }) .then(res => { console.log("Adding tweet to database..."); return res; }) .catch(err => { console.log(err); }) .then(res => { console.log("Tweet added ๐Ÿ™Œ"); console.log(res.data); }); }; module.exports = { addTweet }; <file_sep>/README.md A CLI tool used for interacting with a positive reinforcement Slackbot.
6780d958ab0d590998058ef99029c72f5cea437b
[ "JavaScript", "Markdown" ]
2
JavaScript
ryancharris/dev-affirmations
1ec55ea704252e769804dd78feaae9f94a2a8240
6d6e22640daa89454b41669fb00994608995cdfb
refs/heads/master
<file_sep>๏ปฟnamespace DynamicTeDD.Tests.test.data.SkeletonTheDynamicContextAction { using System; using Microsoft.CSharp; using NUnit.Framework; [TestFixture] public class SampleTests { [Test] public void FirstTestWithDynamic() { dynamic myModelingClayInstance = new object(); Assert.IsTrue(myModelingClayInstance.Portnaouaq()); string temp = "satchm{caret}o"; } } } <file_sep>// // -------------------------------------------------------------------------------------------------------------------- // // <copyright file="SkeletonTheDynamicContextAction.cs" company=""> // // Copyright 2014 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // </copyright> // // -------------------------------------------------------------------------------------------------------------------- namespace DynamicTeDD { using System; using JetBrains.Application.Progress; using JetBrains.ProjectModel; using JetBrains.ReSharper.Feature.Services.Bulbs; using JetBrains.ReSharper.Feature.Services.CSharp.Bulbs; using JetBrains.ReSharper.Feature.Services.LinqTools; using JetBrains.ReSharper.Intentions.Extensibility; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.Tree; using JetBrains.TextControl; using JetBrains.Util; [ContextAction(Name = "SkeletonTheDynamic", Description = "Replaces the dynamic instance with a non-dynamic skeleton type instance.", Group = "C#")] public class SkeletonTheDynamicAction : ContextActionBase, IContextAction { private readonly ICSharpContextActionDataProvider provider; private ILiteralExpression stringLiteral; public SkeletonTheDynamicAction(ICSharpContextActionDataProvider provider) { this.provider = provider; } public override bool IsAvailable(IUserDataHolder cache) { var literal = this.provider.GetSelectedElement<ILiteralExpression>(true, true); if (literal != null && literal.IsConstantValue() && literal.ConstantValue.IsString()) { var s = literal.ConstantValue.Value as string; if (!string.IsNullOrEmpty(s)) { this.stringLiteral = literal; return true; } } return false; } protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { CSharpElementFactory factory = CSharpElementFactory.GetInstance(this.provider.PsiModule); var stringValue = this.stringLiteral.ConstantValue.Value as string; if (stringValue == null) return null; var chars = stringValue.ToCharArray(); Array.Reverse(chars); ICSharpExpression newExpr = factory.CreateExpressionAsIs("\"" + new string(chars) + "\""); this.stringLiteral.ReplaceBy(newExpr); return null; } public override string Text { get { return "Skeleton the dynamic"; } } } // [ContextAction(Description = "My skeleton the dynamic context action does ...", // Group = "C#", // Name = "My skeleton the dynamic Context Action")] // public sealed class SkeletonTheDynamicContextAction : IContextAction // { // private readonly ICSharpContextActionDataProvider _provider; // private IBulbAction[] _items; // /// <summary> // /// For languages other than C# any inheritor of <see cref="IContextActionDataProvider"/> can // /// be injected in this constructor. // /// </summary> // public SkeletonTheDynamicContextAction(ICSharpContextActionDataProvider provider) // { // _provider = provider; // } // public void CreateBulbItems(BulbMenu menu) // { // // Basically // foreach (var item in Items) // { // // use other extension methods on BulbMenu to arrange menu items. // menu.ArrangeContextAction(item); // } // } // public bool IsAvailable(IUserDataHolder cache) // { // // Availability code may be optimized but for most cases can be as simple as follow: // return Items.Length > 0; // } // private IBulbAction[] Items // { // get // { // if (_items == null) // { // _items = new IBulbAction[] // { // new MyBulbItem(_provider) // }; // } // return _items; // } // } // } // public class MyBulbItem : BulbActionBase // { // private readonly ICSharpContextActionDataProvider _provider; // public MyBulbItem(ICSharpContextActionDataProvider provider) // { // _provider = provider; // } // public override string Text // { // get // { // // text returned here will be displayed on the context action // return "Skeleton the dynamic Context action text"; // } // } // protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) // { // // put transacted steps here // // use 'provider' field to get currently selected element // return textControl => // { // // put post-transaction steps here // // if there are none, you can replace this with 'return null' // }; // } // } } <file_sep>DynamicTeDD =================== DynamicTeDD is a R# plugin that makes your .NET TDD workflow more fluent than ever. Indeed, with DynamicTeDD: 1. You start writing a test with a temporary (*'modeling clay'*) dynamic variable subject (dynamic types supporting the on-the-fly addition of any method/property) - __RED, but without breaking the IDE build, nor leaving the test scope__ 2. Once your test is fully written (including the __[NFluent Check](http://www.n-fluent.net)__), you *Alt-Enter* within the test method scope, and the plugin proposes you to replace your dynamic variable with a classical and non-dynamic skeleton class instance - still __RED__ 3. You fill the skeleton with code providing the behavior specified by the test - __GREEN__ and then __REFACTOR__ Disclaimer: ----------- DynamicTeDD is only at the beginning and not even an alpha version today. To be followed then... - - - This workflow is directly inspired by the one imagined by __[<NAME>](https://twitter.com/rhwy)__ and exposed during an __[french ALT.NET meetup](http://www.meetup.com/altnetfr/events/153888012/)__, but also in his __[Dynamic TDD](http://www.codedistillers.com/rui/2013/12/23/dynamic-tdd/)__ post. <file_sep>Notes for contributors ====================== <NAME> - January 3rd, 2014 - - - How to setup your dev environment --------------------------------- 1. Download and install the R# __SDK__ for the version(s) you target: http://confluence.jetbrains.com/display/NETCOM/ReSharper+8+Plugin+Development - - - Some usefull links ------------------ * [R# plugin development documentation](http://confluence.jetbrains.com/display/NETCOM/ReSharper+8+Plugin+Development) * [Download previous R# SDK](http://resharper-support.jetbrains.com/entries/21206508-Where-can-I-download-an-old-previous-ReSharper-version-) * [Ultimate guide to speeding up R# & Visual Studio](http://confluence.jetbrains.com/display/NETCOM/Ultimate+Guide+to+Speeding+Up+ReSharper+(and+Visual+Studio)) <file_sep>using System.Reflection; using JetBrains.ActionManagement; using JetBrains.Application.PluginSupport; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DynamicTeDD")] [assembly: AssemblyDescription("A ReSharper plug-in to make your TDD more fluent via dynamic usage. 1/ You start defining your contract using a dynamic 'modeling clay' instance from within a test (compiling RED) 2/ The plugin replace your dynamic instance with a non-dynamic skeleton code (RED) 3/ You implement the dynamic skeleton code to make your test pass (GREEN)")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("<NAME>, from <NAME>'s original idea")] [assembly: AssemblyProduct("DynamicTeDD")] [assembly: AssemblyCopyright("Copyright ยฉ <NAME>, from <NAME>'s original idea, 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ActionsXml("DynamicTeDD.Actions.xml")] // The following information is displayed by ReSharper in the Plugins dialog [assembly: PluginTitle("DynamicTeDD")] [assembly: PluginDescription("A ReSharper plug-in to make your TDD more fluent via dynamic usage. 1/ You start defining your contract using a dynamic 'modeling clay' instance from within a test (compiling RED) 2/ The plugin replace your dynamic instance with a non-dynamic skeleton code (RED) 3/ You implement the dynamic skeleton code to make your test pass (GREEN)")] [assembly: PluginVendor("<NAME>, from <NAME>'s original idea")] <file_sep>// // -------------------------------------------------------------------------------------------------------------------- // // <copyright file="AboutAction.cs" company=""> // // Copyright 2014 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // </copyright> // // -------------------------------------------------------------------------------------------------------------------- namespace DynamicTeDD { using System.Windows.Forms; using JetBrains.ActionManagement; using JetBrains.Application.DataContext; [ActionHandler("DynamicTeDD.About")] public class AboutAction : IActionHandler { public bool Update(IDataContext context, ActionPresentation presentation, DelegateUpdate nextUpdate) { // return true or false to enable/disable this action return true; } public void Execute(IDataContext context, DelegateExecute nextExecute) { MessageBox.Show( "DynamicTeDD\nThomas PIERRAIN, from <NAME>'s original idea\n\nA ReSharper plug-in to make your TDD more fluent via dynamic usage. 1/ You start defining your contract using a dynamic 'modeling clay' instance from within a test (compiling RED) 2/ The plugin replace your dynamic instance with a non-dynamic skeleton code (RED) 3/ You implement the dynamic skeleton code to make your test pass (GREEN).", "About DynamicTeDD", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
c696a3fbbb135f6192ed74a376d9fdae2d0663d0
[ "Markdown", "C#" ]
6
C#
tpierrain/DynamicTeDD
2a3569c8a73dac1715e3933ae2de190fb00f47c0
a8ae31b40705d974f4ce3bb9af321a3c46e3fb03
refs/heads/master
<file_sep>import os import discord import time import random from discord.ext import commands from dotenv import load_dotenv from make_gif import make_gif print('Loading tokens...') load_dotenv("tokens.env") TOKEN = os.getenv('DISCORD_TOKEN') kill_pw = os.getenv('KILL_PW') #GUILD = os.getenv('DISCORD_GUILD') print('Building bot...') names = ["Simon", "Jamie", "James", "Alex", "Sam", "Elliott", "Jacob", "Will", "Ned", "Jake", "Chappers"] thinking = ["Hmmm let me think.", "This is an easy one.", "Now this is HLTV confirmed.", "Tricky one...", "Errrm.", "OK this one is close.", "Stupid question..."] class CustomClient(discord.Client): async def on_ready(self): print("{} has connected to Discord!".format(self.user)) for g in self.guilds: print("Connected to {}".format(g)) bot = commands.Bot(command_prefix='!') @bot.command(name='kill', help='Protected kill command. Shuts off bot.') async def kill(ctx, *, pw): await ctx.message.delete() if str(pw) == kill_pw: await ctx.send("Putting bot to sleep...") await bot.logout() else: await ctx.send("No permission to kill bot.") @bot.command(name='fak', help='Type !fak to fuck something.') async def fak(ctx, *, thing): await ctx.send("Fuck {}".format(thing)) @bot.command(name='who', help='Type !who is blank thing to decide who is a thing.') async def who(ctx, *, thing): await ctx.send(random.choice(thinking)) thing = thing.replace("?", "") #if thing[0:3] == "is ": # thing = thing[3:] time.sleep(1) await ctx.send("{} {}.".format(random.choice(names), thing), tts=True) #await ctx.message.delete() @bot.command(name='chaser', help='Who is the chaser?') async def chaser(ctx): voice_channel = ctx.author.voice.channel if ctx.author.voice is not None else None channel = None if voice_channel is not None: channel = voice_channel.name vc = await voice_channel.connect() vc.play(discord.FFmpegPCMAudio(source='chaser_walk_on.mp3')) while vc.is_playing(): time.sleep(1) await vc.disconnect() else: await ctx.send("{} is not in a channel.".format(str(ctx.author.name))) await ctx.message.delete() ''' Play error. Comment out for now. @bot.command(name='minceintro', help='Relaxing music.') async def minceintro(ctx): voice_channel = ctx.author.voice.channel if ctx.author.voice is not None else None channel = None if voice_channel is not None: channel = voice_channel.name vc = await voice_channel.connect() vc.play(discord.FFmpegPCMAudio(source='audio/minceintro.mp3')) while vc.is_playing(): time.sleep(1) await vc.disconnect() else: await ctx.send("{} is not in a channel.".format(str(ctx.author.name))) await ctx.message.delete() ''' @bot.command(name='goal', help='BBC WM Goal Horn') async def goal(ctx): voice_channel = ctx.author.voice.channel if ctx.author.voice is not None else None channel = None if voice_channel is not None: channel = voice_channel.name vc = await voice_channel.connect() vc.play(discord.FFmpegPCMAudio(source='WM_Goal.mp3')) while vc.is_playing(): time.sleep(1) await vc.disconnect() else: await ctx.send("{} is not in a channel.".format(str(ctx.author.name))) await ctx.message.delete() @bot.command(name='retard', help='m0e asks a question') async def retard(ctx): voice_channel = ctx.author.voice.channel if ctx.author.voice is not None else None channel = None if voice_channel is not None: channel = voice_channel.name vc = await voice_channel.connect() vc.play(discord.FFmpegPCMAudio(source='audio/retard_m0e.mp3')) while vc.is_playing(): time.sleep(1) await vc.disconnect() else: await ctx.send("{} is not in a channel.".format(str(ctx.author.name))) await ctx.message.delete() @bot.command(name='fuck', help='Steel finds out @tomi is still tweeting') async def fuck(ctx): voice_channel = ctx.author.voice.channel if ctx.author.voice is not None else None channel = None if voice_channel is not None: channel = voice_channel.name vc = await voice_channel.connect() vc.play(discord.FFmpegPCMAudio(source='audio/fuck.mp3')) while vc.is_playing(): time.sleep(1) await vc.disconnect() else: await ctx.send("{} is not in a channel.".format(str(ctx.author.name))) await ctx.message.delete() @bot.command(name='shitting', help='Steel has piles?') async def shitting(ctx): voice_channel = ctx.author.voice.channel if ctx.author.voice is not None else None channel = None if voice_channel is not None: channel = voice_channel.name vc = await voice_channel.connect() vc.play(discord.FFmpegPCMAudio(source='audio/shitting_me.mp3')) while vc.is_playing(): time.sleep(1) await vc.disconnect() else: await ctx.send("{} is not in a channel.".format(str(ctx.author.name))) await ctx.message.delete() @bot.command(name='defuse', help='For trolling only.') async def defuse(ctx): voice_channel = ctx.author.voice.channel if ctx.author.voice is not None else None channel = None if voice_channel is not None: channel = voice_channel.name vc = await voice_channel.connect() vc.play(discord.FFmpegPCMAudio(source='audio/defuse.mp3')) while vc.is_playing(): time.sleep(1) await vc.disconnect() else: await ctx.send("{} is not in a channel.".format(str(ctx.author.name))) await ctx.message.delete() @bot.command(name='idgi', help='I don\'t get it') async def idgi(ctx): channel = ctx.message.channel await channel.send(file=discord.File('idgi.jpg')) voice_channel = ctx.author.voice.channel if ctx.author.voice is not None else None channel = None if voice_channel is not None: channel = voice_channel.name vc = await voice_channel.connect() vc.play(discord.FFmpegPCMAudio(source='audio/idgi.mp3')) while vc.is_playing(): time.sleep(1) await vc.disconnect() await ctx.message.delete() @bot.command(name='qi', help='ALARM - !qi text') async def qi(ctx, *, text): channel = ctx.message.channel await ctx.message.delete() print(text) await channel.send(file=discord.File(make_gif(text))) voice_channel = ctx.author.voice.channel if ctx.author.voice is not None else None channel = None if voice_channel is not None: channel = voice_channel.name vc = await voice_channel.connect() vc.play(discord.FFmpegPCMAudio(source='audio/qi.mp3')) while vc.is_playing(): time.sleep(1) await vc.disconnect() print('Bot starting!') bot.run(TOKEN) #client = CustomClient() #client.run(TOKEN) <file_sep># OS modules import os import shutil # Image modules from PIL import ImageFont from PIL import Image from PIL import ImageDraw def make_gif(text): # create/delete our temp files folder if os.path.exists('frames'): shutil.rmtree('frames') os.mkdir('frames') # load in the background image img_background = Image.open('imgs/black_bg.png') img = Image.new("RGBA", img_background.size, (0, 0, 0, 255)) # set up colours and vars x = 10 y = 10 W = 500 H = 300 white = (255, 255, 255, 255) # load the font font_size = max(10,65-(max(0, len(text)-48)*4)) font_size = 65 font = ImageFont.truetype("RobotoR.ttf", font_size) text = text_wrap(text, font, W-50) text = "\n".join(text) draw = ImageDraw.Draw(img) # add text to each frame for N in range(0, 8): img.paste(img_background, (0, 0)) if (N % 2) == 0: w, h = draw.textsize(text, font=font) draw.multiline_text(((W - w) / 2, (H - h) / 2), text, fill="white", font=font, align="center") #draw.text((x, y), text, white, font=font) img.save("./frames/{}.png".format(str(N).zfill(3))) # output the result os.system('ffmpeg -framerate 2 -i frames/%03d.png -c:v ffv1 -r 8 -y -loop -1 out.avi') os.system('ffmpeg -y -i out.avi out.gif') # clean up shutil.rmtree('frames') return "out.gif" def text_wrap(text, font, max_width): """Wrap text base on specified width. This is to enable text of width more than the image width to be display nicely. @params: text: str text to wrap font: obj font of the text max_width: int width to split the text with @return lines: list[str] list of sub-strings """ lines = [] # If the text width is smaller than the image width, then no need to split # just add it to the line list and return if font.getsize(text)[0] <= max_width: lines.append(text) else: # split the line by spaces to get words words = text.split(' ') i = 0 # append every word to a line while its width is shorter than the image width while i < len(words): line = '' while i < len(words) and font.getsize(line + words[i])[0] <= max_width: line = line + words[i] + " " i += 1 if not line: line = words[i] i += 1 lines.append(line) return lines
d13f72d9a5c1510cefa1c9945e31df7e5d25c01d
[ "Python" ]
2
Python
jubjamie/SaltyBot
316a80af316b3edfb456ce39ae4486f02c69865b
22a7f72dd11ffcb2c27ab28411d03899456b7fae
refs/heads/master
<file_sep>include ':app' rootProject.name='ProyectoBJCS' <file_sep>package com.isc.proyectobjcs; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.widget.Button; import android.view.View; public class MenuPrinActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu_prin); }public void onClick(View v){ Intent resident=new Intent(this, ResidentActivity.class); startActivity(resident); finish(); } public void pantalla2(View v){ Intent silent=new Intent(this, SilentActivity.class); startActivity(silent); finish(); } public void pantalla3(View v){ Intent dead =new Intent(this, DeadActivity.class); startActivity(dead); finish(); } public void pantalla4(View v){ Intent outlast=new Intent(this, OutlastActivity.class); startActivity(outlast); finish(); } public void pantalla5(View v){ Intent evil=new Intent(this, EvilActivity.class); startActivity(evil); finish(); } public void pantalla6(View v){ Intent amnesia=new Intent(this, AmnesiaActivity.class); startActivity(amnesia); finish(); } public void pantalla7(View v){ Intent alien=new Intent(this, AlienActivity.class); startActivity(alien); finish(); } public void pantalla8(View v){ Intent acerca=new Intent(this, AcercaActivity.class); startActivity(acerca); finish(); } }
42250f3ddd5bf456259e8de3f9adb160507a67a0
[ "Java", "Gradle" ]
2
Gradle
johnwhick98/ProyectoBJCS
6990eaf2533733495896820f17d7fd0f5a8f42ca
82a204c74d5936bab8c550a24a89b6cdc6963b57
refs/heads/master
<file_sep>// ะŸะตั€ะฒะฐั ะทะฐะดะฐั‡ะฐ 'use strict' var Tc = parseFloat(prompt('ะ’ะฒะตะดะธั‚ะต ั‚ะตะผะฟะตั€ะฐั‚ัƒั€ัƒ ะฒ ะณั€ะฐะดัƒัะฐั… ะฆะตะปัŒัะธั')); function TempCel(Tc) { let Tf = (9 / 5) * Tc + 32; return Tf; } alert('ะขะตะผะฟะตั€ะฐั‚ัƒั€ะฐ ะฟะพ ั„ะฐั€ะธะฝะณะตะนั‚ัƒ - ' + TempCel(Tc) + ' ะณั€ะฐะดัƒัะพะฒ.'); // ะ’ั‚ะพั€ะฐั ะทะฐะดะฐั‡ะฐ let admin = NaN; let name = prompt('ะ’ะฒะตะดะธั‚ะต ะธะผั'); admin = name; alert('ะ˜ะผั ะฐะดะผะธะฝะฐ' + ' ' + admin) // ะขั€ะตั‚ัŒั ะทะฐะดะฐั‡ะฐ var a = 1000 + '108'; alert(a) // 1000108 // ะงะตั‚ะฒะตั€ั‚ะฐั ะ—ะฐะดะฐั‡ะฐ //ะกะฐะผะพัั‚ะพัั‚ะตะปัŒะฝะพ ั€ะฐะทะพะฑั€ะฐั‚ัŒัั ั ะฐั‚ั€ะธะฑัƒั‚ะฐะผะธ ั‚ะตะณะฐ script (async ะธ defer). //Defer: //ะกะบั€ะธะฟั‚ั‹ ั defer ะฝะธะบะพะณะดะฐ ะฝะต ะฑะปะพะบะธั€ัƒัŽั‚ ัั‚ั€ะฐะฝะธั†ัƒ. //ะกะบั€ะธะฟั‚ั‹ ั defer ะฒัะตะณะดะฐ ะฒั‹ะฟะพะปะฝััŽั‚ัั, ะบะพะณะดะฐ ะดะตั€ะตะฒะพ DOM ะณะพั‚ะพะฒะพ/ //ะžั‚ะปะพะถะตะฝะฝั‹ะต ั ะฟะพะผะพั‰ัŒัŽ defer ัะบั€ะธะฟั‚ั‹ ัะพั…ั€ะฐะฝััŽั‚ ะฟะพั€ัะดะพะบ ะพั‚ะฝะพัะธั‚ะตะปัŒะฝะพ ะดั€ัƒะณ ะดั€ัƒะณะฐ, ะบะฐะบ ะธ ะพะฑั‹ั‡ะฝั‹ะต ัะบั€ะธะฟั‚ั‹. ะŸะพัั‚ะพะผัƒ, ะตัะปะธ ัะฝะฐั‡ะฐะปะฐ ะทะฐะณั€ัƒะถะฐะตั‚ัั ะฑะพะปัŒัˆะพะน ัะบั€ะธะฟั‚, ะฐ ะทะฐั‚ะตะผ ะผะตะฝัŒัˆะตะณะพ ั€ะฐะทะผะตั€ะฐ, ั‚ะพ ะฟะพัะปะตะดะฝะธะน ะฑัƒะดะตั‚ ะถะดะฐั‚ัŒ. //Async //ะั‚ั€ะธะฑัƒั‚ async ะพะทะฝะฐั‡ะฐะตั‚, ั‡ั‚ะพ ัะบั€ะธะฟั‚ ะฐะฑัะพะปัŽั‚ะฝะพ ะฝะตะทะฐะฒะธัะธะผ: //ะกั‚ั€ะฐะฝะธั†ะฐ ะฝะต ะถะดั‘ั‚ ะฐัะธะฝั…ั€ะพะฝะฝั‹ั… ัะบั€ะธะฟั‚ะพะฒ, ัะพะดะตั€ะถะธะผะพะต ะพะฑั€ะฐะฑะฐั‚ั‹ะฒะฐะตั‚ัั ะธ ะพั‚ะพะฑั€ะฐะถะฐะตั‚ัั. //ะกะพะฑั‹ั‚ะธะต DOMContentLoaded ะธ ะฐัะธะฝั…ั€ะพะฝะฝั‹ะต ัะบั€ะธะฟั‚ั‹ ะฝะต ะถะดัƒั‚ ะดั€ัƒะณ ะดั€ัƒะณะฐ: //DOM ะผะพะถะตั‚ ะฟั€ะพะธะทะพะนั‚ะธ ะบะฐะบ ะดะพ ะฐัะธะฝั…ั€ะพะฝะฝะพะณะพ ัะบั€ะธะฟั‚ะฐ (ะตัะปะธ ะฐัะธะฝั…ั€ะพะฝะฝั‹ะน ัะบั€ะธะฟั‚ ะทะฐะฒะตั€ัˆะธั‚ ะทะฐะณั€ัƒะทะบัƒ ะฟะพัะปะต ั‚ะพะณะพ, ะบะฐะบ ัั‚ั€ะฐะฝะธั†ะฐ ะฑัƒะดะตั‚ ะณะพั‚ะพะฒะฐ),ั‚ะฐะบ ะธ ะฟะพัะปะต ะฐัะธะฝั…ั€ะพะฝะฝะพะณะพ ัะบั€ะธะฟั‚ะฐ (ะตัะปะธ ะพะฝ ะบะพั€ะพั‚ะบะธะน ะธะปะธ ัƒะถะต ัะพะดะตั€ะถะธั‚ัั ะฒ HTTP-ะบะตัˆะต) //ะžัั‚ะฐะปัŒะฝั‹ะต ัะบั€ะธะฟั‚ั‹ ะฝะต ะถะดัƒั‚ async, ะธ ัะบั€ะธะฟั‚ั‹ c async ะฝะต ะถะดัƒั‚ ะดั€ัƒะณะธะต ัะบั€ะธะฟั‚ั‹. //ะขะฐะบ ั‡ั‚ะพ ะตัะปะธ ัƒ ะฝะฐั ะตัั‚ัŒ ะฝะตัะบะพะปัŒะบะพ ัะบั€ะธะฟั‚ะพะฒ ั async, ะพะฝะธ ะผะพะณัƒั‚ ะฒั‹ะฟะพะปะฝัั‚ัŒัั ะฒ ะปัŽะฑะพะผ ะฟะพั€ัะดะบะต. ะขะพ, ั‡ั‚ะพ ะฟะตั€ะฒะพะต ะทะฐะณั€ัƒะทะธั‚ัั โ€“ ะทะฐะฟัƒัั‚ะธั‚ัั ะฒ ะฟะตั€ะฒัƒัŽ ะพั‡ะตั€ะตะดัŒ:
3fc63343da32da86e8e660c1e9079e7818d5985a
[ "JavaScript" ]
1
JavaScript
nsm23/JavaScrit
e416e17b2163f16b3d032acc58e8e96a44f5ae6f
2ca49f6c308c90f0f8c37f9dc9d4e2932a656177
refs/heads/main
<file_sep>package proj2 // CS 161 Project 2 // You MUST NOT change these default imports. ANY additional imports it will // break the autograder and everyone will be sad. import ( "github.com/cs161-staff/userlib" // The JSON library will be useful for serializing go structs. // See: https://cs161.org/assets/projects/2/docs/coding_tips/json.html. "encoding/json" // Likewise, useful for debugging, etc. "encoding/hex" // The Datastore requires UUIDs to store key-value entries. // See: https://cs161.org/assets/projects/2/docs/coding_tips/uuid.html. "github.com/google/uuid" // Useful for debug messages, or string manipulation for datastore keys. "strings" // Want to import errors. "errors" // Optional. You can remove the "_" there, but please do not touch // anything else within the import bracket. _ "strconv" // if you are looking for fmt, we don't give you fmt, but you can use userlib.DebugMsg. // see someUsefulThings() below: ) // This serves two purposes: // a) It shows you some useful primitives, and // b) it suppresses warnings for items not being imported. // Of course, this function can be deleted. func someUsefulThings() { // Creates a random UUID f := uuid.New() userlib.DebugMsg("UUID as string:%v", f.String()) // Example of writing over a byte of f f[0] = 10 userlib.DebugMsg("UUID as string:%v", f.String()) // takes a sequence of bytes and renders as hex h := hex.EncodeToString([]byte("fubar")) userlib.DebugMsg("The hex: %v", h) // Marshals data into a JSON representation // Will actually work with go structures as well d, _ := json.Marshal(f) userlib.DebugMsg("The json data: %v", string(d)) var g uuid.UUID json.Unmarshal(d, &g) userlib.DebugMsg("Unmashaled data %v", g.String()) // This creates an error type userlib.DebugMsg("Creation of error %v", errors.New(strings.ToTitle("This is an error"))) // And a random RSA key. In this case, ignoring the error // return value var pk userlib.PKEEncKey var sk userlib.PKEDecKey pk, sk, _ = userlib.PKEKeyGen() userlib.DebugMsg("Key is %v, %v", pk, sk) } // Helper function: Takes the first 16 bytes and converts it into the UUID type func bytesToUUID(data []byte) (ret uuid.UUID) { for x := range ret { ret[x] = data[x] } return } type Node struct { Username string User_invite_loc []byte //encrypted with the root/owner's public key Children []*Node } type LL_node struct { Data userlib.UUID HMAC_Data []byte Next userlib.UUID } type Tree struct { Root *Node } // User is the structure definition for a user record. type User struct { password string Username string Tree_sk userlib.PKEDecKey Secret_key userlib.PKEDecKey Signing_sk userlib.DSSignKey Files_key []byte //Files userlib.UUID // pointer to Hashmap of files: filename โ†’ accesstoken|HMAC(file_location) } type File struct { //Data []byte // End_pointer int //encrypted int len of file Head userlib.UUID Tail userlib.UUID Participants Tree File_ID []byte } type AccessToken struct { Enc_file_symm []byte Enc_file_id []byte Enc_file_owner []byte Enc_recipient []byte Signed_file_symm []byte Signed_file_id []byte Signed_file_owner []byte Signed_recipient []byte // Enc_keys []byte // Signed_keys []byte } func Find(slice []uuid.UUID, val uuid.UUID) (found bool) { for _, item := range slice { if item == val { return true } } return false } func Padding(msg []byte) (padded_msg []byte) { msg_len := len(msg) padding := 16 - msg_len%16 for i := 0; i < padding; i += 1 { msg = append(msg, byte(padding)) } return msg } func Unpad(ciphertext []byte) (unpadded_msg []byte) { padding := int(ciphertext[len(ciphertext)-1]) unpadded_msg = ciphertext[0 : len(ciphertext)-padding] return unpadded_msg } func CheckMult16(text []byte) (mult bool) { if len(text) > 16 { if len(text)%16 == 0 { return true } } return false } func CheckRange(text []byte) (mult bool) { if text[len(text)-1] > 16 || text[len(text)-1] < 1 { return false } return true } func TreeSearch(participants *Tree, username string) (node *Node) { queue := make([]*Node, 0) queue = append(queue, participants.Root) for len(queue) > 0 { next := queue[0] queue = queue[1:] if next.Username == username { return next } if len(next.Children) > 0 { for _, child := range next.Children { queue = append(queue, child) } } } return nil } func RetrieveHashmap(username string, files_key []byte) (files map[string]userlib.UUID, err error) { hash := userlib.Hash([]byte(username + "files")) slicehash := hash[:] enc_marshalled_files, _ := userlib.DatastoreGet(bytesToUUID(slicehash)) hash_HMAC := userlib.Hash([]byte(username + "files HMAC")) slicehash_HMAC := hash_HMAC[:] enc_marshalled_files_HMAC, _ := userlib.DatastoreGet(bytesToUUID(slicehash_HMAC)) HMAC_key, _ := userlib.HashKDF(files_key, []byte("HMAC files")) HMAC_calc, _ := userlib.HMACEval(HMAC_key[:16], enc_marshalled_files) if !userlib.HMACEqual(HMAC_calc, enc_marshalled_files_HMAC) { return nil, errors.New(strings.ToTitle("Files HMAC doesn't match.")) } dec_key, _ := userlib.HashKDF(files_key, []byte("encryption files")) if !CheckMult16(enc_marshalled_files) { return nil, errors.New(strings.ToTitle("File has been corrupted.")) } if !CheckMult16(enc_marshalled_files) { return nil, errors.New(strings.ToTitle("Linked list data has been corrupted in RevokeFile.")) } marshalled_files := userlib.SymDec(dec_key[:16], enc_marshalled_files) if !CheckRange(marshalled_files) { return nil, errors.New(strings.ToTitle("Linked list data is not correctly decrypted.")) } marshalled_files = Unpad(marshalled_files) json.Unmarshal(marshalled_files, &files) return files, nil } func SetHashmap(filename string, accessToken userlib.UUID, username string, files_key []byte) error { files, err := RetrieveHashmap(username, files_key) if err != nil { return err } files[filename] = accessToken files_marshalled, _ := json.Marshal(files) files_marshalled = Padding(files_marshalled) enc_key, _ := userlib.HashKDF(files_key, []byte("encryption files")) files_marshalled_enc := userlib.SymEnc(enc_key[:16], userlib.RandomBytes(16), files_marshalled) hash := userlib.Hash([]byte(username + "files")) slicehash := hash[:] userlib.DatastoreSet(bytesToUUID(slicehash), files_marshalled_enc) HMAC_key, _ := userlib.HashKDF(files_key, []byte("HMAC files")) files_marshalled_enc_HMAC, _ := userlib.HMACEval(HMAC_key[:16], files_marshalled_enc) hash_HMAC := userlib.Hash([]byte(username + "files HMAC")) slicehash_HMAC := hash_HMAC[:] userlib.DatastoreSet(bytesToUUID(slicehash_HMAC), files_marshalled_enc_HMAC) return nil } func RetrieveFile(owner_hash []byte, file_symm []byte, file_id []byte) (filedataptr *File, err error) { key_hash := userlib.Hash(append(file_id, owner_hash[:]...)) storageKey, _ := uuid.FromBytes(key_hash[:16]) dataJSON, ok := userlib.DatastoreGet(storageKey) if !ok { return nil, errors.New(strings.ToTitle("File not in Datastore!")) } file_symm_struct, _ := userlib.HashKDF(file_symm, []byte("encrypt struct")) file_symm_struct = file_symm_struct[:16] if !CheckMult16(dataJSON) { return nil, errors.New(strings.ToTitle("File has been corrupted in RetrieveFile.")) } dataJSON_dec := userlib.SymDec(file_symm_struct, dataJSON) if !CheckRange(dataJSON_dec) { return nil, errors.New(strings.ToTitle("Linked list data is not correctly decrypted.")) } dataJSON_dec = Unpad(dataJSON_dec) var filedata File filedataptr = &filedata json.Unmarshal(dataJSON_dec, filedataptr) hmac := []byte("HMAC") key_HMAC := append(hmac, owner_hash...) key_HMAC = append(file_id, key_HMAC...) key_hash_HMAC := userlib.Hash(key_HMAC) storageKey_HMAC, _ := uuid.FromBytes(key_hash_HMAC[:16]) filedata_HMAC, ok := userlib.DatastoreGet(storageKey_HMAC) if !ok { return nil, errors.New(strings.ToTitle("File HMAC not in Datastore!")) } file_symm_struct_HMAC, _ := userlib.HashKDF(file_symm, []byte("HMAC struct")) file_symm_struct_HMAC = file_symm_struct_HMAC[:16] filedata_HMAC_datastore, _ := userlib.HMACEval(file_symm_struct_HMAC, dataJSON) if !userlib.HMACEqual(filedata_HMAC, filedata_HMAC_datastore) { return nil, errors.New(strings.ToTitle("File HMACs don't match!")) } return filedataptr, nil } func RetrieveAccessToken(userdata *User, filename string) (file_symm []byte, file_id []byte, file_owner_hash []byte, owner []byte, err error) { files, err := RetrieveHashmap(userdata.Username, userdata.Files_key) if err != nil { return nil, nil, nil, nil, err } uuid_accessToken, ok := files[filename] if !ok { return nil, nil, nil, nil, errors.New(strings.ToTitle("Access token not in hashmap!")) } accessToken_marshaled, ok := userlib.DatastoreGet(uuid_accessToken) if !ok { return nil, nil, nil, nil, errors.New(strings.ToTitle("Access Token not in Datastore")) } secret_key := userdata.Secret_key var AT AccessToken _ = json.Unmarshal(accessToken_marshaled, &AT) file_symm, _ = userlib.PKEDec(secret_key, AT.Enc_file_symm) // invalid := []byte("This is an invalid accessToken.") // if string(file_symm) == string(invalid) { // return nil, nil, nil, nil, errors.New(strings.ToTitle("This user does not have a valid accessToken." + string(file_symm))) // } file_id, _ = userlib.PKEDec(secret_key, AT.Enc_file_id) owner, _ = userlib.PKEDec(secret_key, AT.Enc_file_owner) file_owner := userlib.Hash(owner) file_owner_hash = file_owner[:] return file_symm, file_id, file_owner_hash, owner, nil } func DatastoreFile(file_id []byte, owner_hash []byte, file_symm []byte, filedata *File) { //Storing encrypted file struct in datastore key_hash := userlib.Hash(append(file_id, owner_hash[:]...)) storageKey, _ := uuid.FromBytes(key_hash[:16]) jsonData, _ := json.Marshal(filedata) jsonData_enc := Padding(jsonData) iv := userlib.RandomBytes(16) file_symm_struct, _ := userlib.HashKDF(file_symm, []byte("encrypt struct")) file_symm_struct = file_symm_struct[:16] jsonData_enc = userlib.SymEnc(file_symm_struct, iv, jsonData_enc) userlib.DatastoreSet(storageKey, jsonData_enc) //Storing encrypted file struct HMAC in datastore hmac := []byte("HMAC") key_HMAC := append(hmac, owner_hash[:]...) key_HMAC = append(file_id, key_HMAC...) key_hash_HMAC := userlib.Hash(key_HMAC) storageKey_HMAC, _ := uuid.FromBytes(key_hash_HMAC[:16]) file_symm_struct_HMAC, _ := userlib.HashKDF(file_symm, []byte("HMAC struct")) file_symm_struct_HMAC = file_symm_struct_HMAC[:16] jsonData_enc_HMAC, _ := userlib.HMACEval(file_symm_struct_HMAC, jsonData_enc) //maybe don't use file_symm userlib.DatastoreSet(storageKey_HMAC, jsonData_enc_HMAC) } func DatastoreUser(userdata *User, pk userlib.PKEEncKey) { userbytes, _ := json.Marshal(userdata) pwd_bytes := []byte(userdata.password) //Storing encrypted user struct in datastore IV_enc := userlib.RandomBytes(16) userbytes = Padding(userbytes) pk_salt, _ := userlib.KeystoreGet(userdata.Username + "_salt") salt_marshalled, _ := json.Marshal(pk_salt) salt, _ := userlib.HMACEval(salt_marshalled[:16], []byte(userdata.Username)) userdata_enc := userlib.SymEnc(userlib.Argon2Key(pwd_bytes, salt, 32), IV_enc, userbytes) hash := userlib.Hash([]byte(userdata.Username)) slicehash := hash[:] userlib.DatastoreSet(bytesToUUID(slicehash), userdata_enc) //Storing HMAC of encrypted user struct in datastore userdata_HMAC, _ := userlib.HMACEval(userlib.Argon2Key(pwd_bytes, salt, 16), userdata_enc) hash_HMAC := userlib.Hash([]byte(userdata.Username + "HMAC")) slicehash_HMAC := hash_HMAC[:] userlib.DatastoreSet(bytesToUUID(slicehash_HMAC), userdata_HMAC) } // InitUser will be called a single time to initialize a new user. func InitUser(username string, password string) (userdataptr *User, err error) { var userdata User userdataptr = &userdata //TODO: This is a toy implementation. user_enckey := username + "_enckey" //Check if username already exists _, ok := userlib.KeystoreGet(user_enckey) if ok { return nil, errors.New(strings.ToTitle("Username already exists.")) } if len(username) <= 0 { return nil, errors.New(strings.ToTitle("Username length is not valid.")) } if len(password) <= 0 { return nil, errors.New(strings.ToTitle("Password length is not valid.")) } userdata.Username = username pwd_bytes := []byte(<PASSWORD>) public_key, secret_key, _ := userlib.PKEKeyGen() //TODO: Check keylen later if necessary - secret keys using keylen = 32, hmacs using keylen = 16 userlib.KeystoreSet(user_enckey, public_key) userdata.Secret_key = secret_key pk_salt, _, _ := userlib.PKEKeyGen() userlib.KeystoreSet(username+"_salt", pk_salt) salt_marshalled, _ := json.Marshal(pk_salt) salt, _ := userlib.HMACEval(salt_marshalled[:16], []byte(username)) Tree_pk, Tree_sk, _ := userlib.PKEKeyGen() userlib.KeystoreSet(username+"_treekey", Tree_pk) userdata.Tree_sk = Tree_sk signing_sk, signing_verk, _ := userlib.DSKeyGen() user_verkey := username + "_verkey" userlib.KeystoreSet(user_verkey, signing_verk) userdata.Signing_sk = signing_sk userdata.Files_key = userlib.RandomBytes(16) //initialize empty files hashmap and store in datastore files := make(map[string]userlib.UUID) files_marshalled, _ := json.Marshal(files) files_marshalled = Padding(files_marshalled) enc_key, _ := userlib.HashKDF(userdata.Files_key, []byte("encryption files")) files_marshalled_enc := userlib.SymEnc(enc_key[:16], userlib.RandomBytes(16), files_marshalled) hash := userlib.Hash([]byte(username + "files")) slicehash := hash[:] userlib.DatastoreSet(bytesToUUID(slicehash), files_marshalled_enc) HMAC_key, _ := userlib.HashKDF(userdata.Files_key, []byte("HMAC files")) files_marshalled_enc_HMAC, _ := userlib.HMACEval(HMAC_key[:16], files_marshalled_enc) hash_HMAC := userlib.Hash([]byte(username + "files HMAC")) slicehash_HMAC := hash_HMAC[:] userlib.DatastoreSet(bytesToUUID(slicehash_HMAC), files_marshalled_enc_HMAC) userbytes, _ := json.Marshal(userdata) //Storing encrypted user struct in datastore IV_enc := userlib.RandomBytes(16) userbytes = Padding(userbytes) userdata_enc := userlib.SymEnc(userlib.Argon2Key(pwd_bytes, salt, 32), IV_enc, userbytes) hash = userlib.Hash([]byte(username)) slicehash = hash[:] userlib.DatastoreSet(bytesToUUID(slicehash), userdata_enc) //Storing HMAC of encrypted user struct in datastore userdata_HMAC, _ := userlib.HMACEval(userlib.Argon2Key(pwd_bytes, salt, 16), userdata_enc) hash_HMAC = userlib.Hash([]byte(username + "HMAC")) slicehash_HMAC = hash_HMAC[:] userlib.DatastoreSet(bytesToUUID(slicehash_HMAC), userdata_HMAC) userdata.password = <PASSWORD> return &userdata, nil } // GetUser is documented at: // https://cs161.org/assets/projects/2/docs/client_api/getuser.html func GetUser(username string, password string) (userdataptr *User, err error) { var userdata User userdataptr = &userdata user_enckey := username + "_enckey" user_verkey := username + "_verkey" _, ok_enc := userlib.KeystoreGet(user_enckey) _, ok_sign := userlib.KeystoreGet(user_verkey) if ok_enc && ok_sign { hash := userlib.Hash([]byte(username)) slicehash := hash[:] user, ok := userlib.DatastoreGet(bytesToUUID(slicehash)) if !ok { return nil, errors.New(strings.ToTitle("Username does not exist.")) } hash_HMAC := userlib.Hash([]byte(username + "HMAC")) slicehash_HMAC := hash_HMAC[:] user_HMAC_datastore, _ := userlib.DatastoreGet(bytesToUUID(slicehash_HMAC)) pk_salt, _ := userlib.KeystoreGet(username + "_salt") salt_marshalled, _ := json.Marshal(pk_salt) salt, _ := userlib.HMACEval(salt_marshalled[:16], []byte(username)) pwd_bytes := []byte(<PASSWORD>) user_HMAC, _ := userlib.HMACEval(userlib.Argon2Key(pwd_bytes, salt, 16), user) if !userlib.HMACEqual(user_HMAC, user_HMAC_datastore) { return nil, errors.New(strings.ToTitle("HMAC of user structs don't match.")) } if !CheckMult16(user) { return nil, errors.New(strings.ToTitle("User has been corrupted in GetUser.")) } user = userlib.SymDec(userlib.Argon2Key(pwd_bytes, salt, 32), user) if !CheckRange(user) { return nil, errors.New(strings.ToTitle("User data is not correctly decrypted.")) } user = Unpad(user) _ = json.Unmarshal(user, userdataptr) userdata.password = <PASSWORD> return userdataptr, nil } else { return nil, errors.New(strings.ToTitle("User has not been initialized.")) } } // StoreFile is documented at: // https://cs161.org/assets/projects/2/docs/client_api/storefile.html func (userdata *User) StoreFile(filename string, data []byte) (err error) { // file_symm: HMAC data, encrypt data, HMAC file struct, encrypt file struct var filedata File data = Padding(data) // case where file exists and someone else may be owner and we are overwriting files, err := RetrieveHashmap(userdata.Username, userdata.Files_key) if err != nil { return err } _, ok := files[filename] if ok { file_symm, file_id, file_owner_hash, _, err1 := RetrieveAccessToken(userdata, filename) if err1 != nil { return err1 } filedata, _ := RetrieveFile(file_owner_hash, file_symm, file_id) var data_node LL_node iv := userlib.RandomBytes(16) file_symm_data, _ := userlib.HashKDF(file_symm, []byte("encrypt data")) file_symm_data = file_symm_data[:16] location := uuid.New() enc_d := userlib.SymEnc(file_symm_data, iv, data) userlib.DatastoreSet(location, enc_d) data_node.Data = location file_symm_data_HMAC, _ := userlib.HashKDF(file_symm, []byte("HMAC data")) file_symm_data_HMAC = file_symm_data_HMAC[:16] data_node.HMAC_Data, _ = userlib.HMACEval(file_symm_data_HMAC, enc_d) data_node.Next = uuid.Nil random := userlib.RandomBytes(16) data_loc := bytesToUUID(random) data_node_marshal, _ := json.Marshal(data_node) userlib.DatastoreSet(data_loc, data_node_marshal) head, _ := userlib.DatastoreGet(filedata.Head) var linked_list LL_node json.Unmarshal(head, &linked_list) loc := filedata.Head for linked_list.Next != uuid.Nil { ll_data, _ := userlib.DatastoreGet(linked_list.Data) calc_HMAC, _ := userlib.HMACEval(file_symm_data_HMAC, ll_data) if string(calc_HMAC) != string(linked_list.HMAC_Data) { return errors.New(strings.ToTitle("File contents have been corrupted.")) } next, _ := userlib.DatastoreGet(linked_list.Next) json.Unmarshal(next, &linked_list) userlib.DatastoreDelete(loc) loc = linked_list.Next } userlib.DatastoreDelete(loc) filedata.Head = data_loc filedata.Tail = data_loc DatastoreFile(file_id, file_owner_hash, file_symm, filedata) return } file_symm := userlib.RandomBytes(16) var data_node LL_node //needs to go onto datastore iv := userlib.RandomBytes(16) file_symm_data, _ := userlib.HashKDF(file_symm, []byte("encrypt data")) file_symm_data = file_symm_data[:16] location := uuid.New() enc_d := userlib.SymEnc(file_symm_data, iv, data) userlib.DatastoreSet(location, enc_d) data_node.Data = location file_symm_data_HMAC, _ := userlib.HashKDF(file_symm, []byte("HMAC data")) file_symm_data_HMAC = file_symm_data_HMAC[:16] data_node.HMAC_Data, _ = userlib.HMACEval(file_symm_data_HMAC, enc_d) data_node.Next = uuid.Nil data_loc := uuid.New() data_node_marshal, _ := json.Marshal(data_node) userlib.DatastoreSet(data_loc, data_node_marshal) filedata.Head = data_loc filedata.Tail = data_loc pk, _ := userlib.KeystoreGet(userdata.Username + "_enckey") file_id := userlib.RandomBytes(16) filedata.File_ID = file_id owner_hash := userlib.Hash([]byte(userdata.Username)) signing_sk := userdata.Signing_sk // user_hash := userlib.Hash(append([]byte(userdata.Username), []byte("accessToken")...)) // key_hash := userlib.Hash(append(file_id, user_hash[:]...)) accessToken := uuid.New() encrypted_file_symm, _ := userlib.PKEEnc(pk, file_symm) encrypted_file_id, _ := userlib.PKEEnc(pk, file_id) encrypted_file_owner, _ := userlib.PKEEnc(pk, []byte(userdata.Username)) signed_enc_file_symm, _ := userlib.DSSign(signing_sk, encrypted_file_symm) signed_enc_file_id, _ := userlib.DSSign(signing_sk, encrypted_file_id) signed_enc_file_owner, _ := userlib.DSSign(signing_sk, encrypted_file_owner) var encrypted_AT_struct AccessToken encrypted_AT_struct.Enc_file_symm = encrypted_file_symm encrypted_AT_struct.Enc_file_id = encrypted_file_id encrypted_AT_struct.Enc_file_owner = encrypted_file_owner encrypted_AT_struct.Signed_file_symm = signed_enc_file_symm encrypted_AT_struct.Signed_file_id = signed_enc_file_id encrypted_AT_struct.Signed_file_owner = signed_enc_file_owner encrypted_AT_marshaled, _ := json.Marshal(encrypted_AT_struct) userlib.DatastoreSet(accessToken, encrypted_AT_marshaled) // Encrypting file with Tree_pk Tree_pk, _ := userlib.KeystoreGet(userdata.Username + "_treekey") SetHashmap(filename, accessToken, userdata.Username, userdata.Files_key) //userdata.Files[filename] = accessToken invite_AT, _ := json.Marshal(accessToken) invite_AT_enc, _ := userlib.PKEEnc(Tree_pk, invite_AT) var usernode Node usernodeptr := &usernode usernode.Username = userdata.Username usernode.User_invite_loc = invite_AT_enc usernode.Children = nil var participants Tree participants.Root = usernodeptr filedata.Participants = participants DatastoreFile(file_id, owner_hash[:], file_symm, &filedata) DatastoreUser(userdata, pk) return } //AppendFile is documented at: //https://cs161.org/assets/projects/2/docs/client_api/appendfile.html func (userdata *User) AppendFile(filename string, data []byte) (err error) { if data == nil || len(data) < 1 { return errors.New(strings.ToTitle("No data to append.")) } file_symm, file_id, file_owner_hash, _, err := RetrieveAccessToken(userdata, filename) if err != nil { return err } filedata, err := RetrieveFile(file_owner_hash, file_symm, file_id) if err != nil { return err } participants := filedata.Participants if TreeSearch(&participants, userdata.Username) == nil { return errors.New(strings.ToTitle("User does not have access to this file.")) } // Create new node for new Data and place in Datstore at data_loc var data_node LL_node iv := userlib.RandomBytes(16) data = Padding(data) file_symm_data, _ := userlib.HashKDF(file_symm, []byte("encrypt data")) file_symm_data = file_symm_data[:16] file_symm_data_HMAC, _ := userlib.HashKDF(file_symm, []byte("HMAC data")) file_symm_data_HMAC = file_symm_data_HMAC[:16] location := uuid.New() enc_d := userlib.SymEnc(file_symm_data, iv, data) userlib.DatastoreSet(location, enc_d) data_node.Data = location data_node.HMAC_Data, _ = userlib.HMACEval(file_symm_data_HMAC, enc_d) data_node.Next = uuid.Nil random := userlib.RandomBytes(16) data_loc := bytesToUUID(random) data_node_marshal, _ := json.Marshal(data_node) userlib.DatastoreSet(data_loc, data_node_marshal) /////////////////// //old tail Next should point to new data node tail, _ := userlib.DatastoreGet(filedata.Tail) var tail_ll LL_node json.Unmarshal(tail, &tail_ll) tail_ll.Next = data_loc tail_marshal, _ := json.Marshal(tail_ll) userlib.DatastoreSet(filedata.Tail, tail_marshal) ////////////// filedata.Tail = data_loc DatastoreFile(file_id, file_owner_hash, file_symm, filedata) return nil } // LoadFile is documented at: // https://cs161.org/assets/projects/2/docs/client_api/loadfile.html func (userdata *User) LoadFile(filename string) (dataBytes []byte, err error) { file_symm, file_id, file_owner_hash, _, err := RetrieveAccessToken(userdata, filename) if err != nil { return nil, err } filedata, err := RetrieveFile(file_owner_hash, file_symm, file_id) if err != nil { return nil, err } participants := filedata.Participants if TreeSearch(&participants, userdata.Username) == nil { return nil, errors.New(strings.ToTitle("User does not have access to this file.")) } file_id_str := string(file_id) if file_id_str != string(filedata.File_ID) { return nil, errors.New(strings.ToTitle("Did not retrieve the correct file (wrong file id).")) } head, _ := userlib.DatastoreGet(filedata.Head) var linked_list LL_node json.Unmarshal(head, &linked_list) dataBytes = []byte{} file_symm_data, _ := userlib.HashKDF(file_symm, []byte("encrypt data")) file_symm_data = file_symm_data[:16] file_symm_data_HMAC, _ := userlib.HashKDF(file_symm, []byte("HMAC data")) file_symm_data_HMAC = file_symm_data_HMAC[:16] visited := []uuid.UUID{filedata.Head} found := Find(visited, linked_list.Next) curr_uuid := filedata.Head for linked_list.Next != uuid.Nil && !found { ll_data, _ := userlib.DatastoreGet(linked_list.Data) calc_HMAC, _ := userlib.HMACEval(file_symm_data_HMAC, ll_data) if string(calc_HMAC) != string(linked_list.HMAC_Data) { return nil, errors.New(strings.ToTitle("File contents have been corrupted.")) } if !CheckMult16(ll_data) { return nil, errors.New(strings.ToTitle("Linked list data has been corrupted in LoadFile.")) } data := userlib.SymDec(file_symm_data, ll_data) if !CheckRange(data) { return nil, errors.New(strings.ToTitle("Linked list data is not correctly decrypted.")) } data = Unpad(data) dataBytes = append(dataBytes, data...) // checking for loops and proper termination and advancing to the next node visited = append(visited, linked_list.Next) next, _ := userlib.DatastoreGet(linked_list.Next) curr_uuid = linked_list.Next json.Unmarshal(next, &linked_list) found = Find(visited, linked_list.Next) } if !found { if curr_uuid != filedata.Tail { return nil, errors.New(strings.ToTitle("Did not complete going through the data.")) } ll_data, _ := userlib.DatastoreGet(linked_list.Data) calc_HMAC, _ := userlib.HMACEval(file_symm_data_HMAC, ll_data) if string(calc_HMAC) != string(linked_list.HMAC_Data) { return nil, errors.New(strings.ToTitle("File contents have been corrupted.")) } if !CheckMult16(ll_data) { return nil, errors.New(strings.ToTitle("Linked list data has been corrupted in LoadFile.")) } data := userlib.SymDec(file_symm_data, ll_data) if !CheckRange(data) { return nil, errors.New(strings.ToTitle("Linked list data is not correctly decrypted.")) } data = Unpad(data) dataBytes = append(dataBytes, data...) } else { return nil, errors.New(strings.ToTitle("Cycle detected in data.")) } return dataBytes, nil } // ShareFile is documented at: // https://cs161.org/assets/projects/2/docs/client_api/sharefile.html func (userdata *User) ShareFile(filename string, recipient string) ( accessToken uuid.UUID, err error) { file_symm, file_id, file_owner_hash, owner, err := RetrieveAccessToken(userdata, filename) if err != nil { return uuid.Nil, err } filedata, err := RetrieveFile(file_owner_hash, file_symm, file_id) if err != nil { return uuid.Nil, err } participants := filedata.Participants if TreeSearch(&participants, userdata.Username) == nil { return uuid.Nil, errors.New(strings.ToTitle("This user does not have access to the file.")) } if TreeSearch(&participants, recipient) != nil { return uuid.Nil, errors.New(strings.ToTitle("This recipient already has access to the file.")) } recipient_pk, ok := userlib.KeystoreGet(recipient + "_enckey") if !ok { return uuid.Nil, errors.New(strings.ToTitle("Recipient username is incorrect.")) } signing_sk := userdata.Signing_sk encrypted_file_symm, _ := userlib.PKEEnc(recipient_pk, file_symm) encrypted_file_id, _ := userlib.PKEEnc(recipient_pk, file_id) encrypted_file_owner, _ := userlib.PKEEnc(recipient_pk, owner) encrypted_recipient, _ := userlib.PKEEnc(recipient_pk, []byte(recipient)) signed_enc_file_symm, _ := userlib.DSSign(signing_sk, encrypted_file_symm) signed_enc_file_id, _ := userlib.DSSign(signing_sk, encrypted_file_id) signed_enc_file_owner, _ := userlib.DSSign(signing_sk, encrypted_file_owner) signed_recipient, _ := userlib.DSSign(signing_sk, encrypted_recipient) var encrypted_AT_struct AccessToken encrypted_AT_struct.Enc_file_symm = encrypted_file_symm encrypted_AT_struct.Enc_file_id = encrypted_file_id encrypted_AT_struct.Enc_file_owner = encrypted_file_owner encrypted_AT_struct.Enc_recipient = encrypted_recipient encrypted_AT_struct.Signed_file_symm = signed_enc_file_symm encrypted_AT_struct.Signed_file_id = signed_enc_file_id encrypted_AT_struct.Signed_file_owner = signed_enc_file_owner encrypted_AT_struct.Signed_recipient = signed_recipient encrypted_AT_marshaled, _ := json.Marshal(encrypted_AT_struct) accessToken = uuid.New() userlib.DatastoreSet(accessToken, encrypted_AT_marshaled) Tree_pk, _ := userlib.KeystoreGet(string(owner) + "_treekey") invite_AT, _ := json.Marshal(accessToken) invite_AT_enc, _ := userlib.PKEEnc(Tree_pk, invite_AT) var usernode Node usernode.Username = recipient usernode.User_invite_loc = invite_AT_enc usernode.Children = nil // set this user to be child of sender sender_node := TreeSearch(&participants, userdata.Username) if sender_node == nil { return uuid.Nil, errors.New(strings.ToTitle("Sender does not have access to the file.")) } sender_node.Children = append(sender_node.Children, &usernode) DatastoreFile(file_id, file_owner_hash, file_symm, filedata) return accessToken, nil } // ReceiveFile is documented at: // https://cs161.org/assets/projects/2/docs/client_api/receivefile.html func (userdata *User) ReceiveFile(filename string, sender string, accessToken uuid.UUID) error { files, err := RetrieveHashmap(userdata.Username, userdata.Files_key) if err != nil { return err } _, ok := files[filename] if ok { // share after revoke puts access token exactly where it was before making, this method useless _, _, _, _, err := RetrieveAccessToken(userdata, filename) if err == nil { return errors.New(strings.ToTitle("This user already has a file with filename:" + filename)) } } accessToken_enc, _ := userlib.DatastoreGet(accessToken) var AT AccessToken _ = json.Unmarshal(accessToken_enc, &AT) sender_verkey, _ := userlib.KeystoreGet(sender + "_verkey") err = userlib.DSVerify(sender_verkey, AT.Enc_file_symm, AT.Signed_file_symm) if err != nil { return err } err = userlib.DSVerify(sender_verkey, AT.Enc_file_id, AT.Signed_file_id) if err != nil { return err } err = userlib.DSVerify(sender_verkey, AT.Enc_file_owner, AT.Signed_file_owner) if err != nil { return err } err = userlib.DSVerify(sender_verkey, AT.Enc_recipient, AT.Signed_recipient) if err != nil { return err } recipient_sk := userdata.Secret_key intended_recipient, _ := userlib.PKEDec(recipient_sk, AT.Enc_recipient) if string(intended_recipient) != userdata.Username { return errors.New(strings.ToTitle("This user is not the intended recipient.")) } SetHashmap(filename, accessToken, userdata.Username, userdata.Files_key) return nil } // RevokeFile is documented at: // https://cs161.org/assets/projects/2/docs/client_api/revokefile.html func (userdata *User) RevokeFile(filename string, targetUsername string) (err error) { file_symm, file_id, file_owner_hash, owner, err := RetrieveAccessToken(userdata, filename) if err != nil { return err } filedata, err := RetrieveFile(file_owner_hash, file_symm, file_id) if err != nil { return err } if targetUsername == userdata.Username { return errors.New(strings.ToTitle("Owner cannot revoke from themself.")) } participants := filedata.Participants if (participants.Root).Username != userdata.Username { return errors.New(strings.ToTitle("User does not have revoke access.")) } targetNode := TreeSearch(&participants, targetUsername) if targetNode == nil { return errors.New(strings.ToTitle("Target does not currently have access to this file.")) } Tree_sk := userdata.Tree_sk // go through pariticipants and replace file_symm file_symm_new := userlib.RandomBytes(16) //affected by file_symm: encryption of data, HMAC of data, encryption of filestruct, HMAC of filestruct head, _ := userlib.DatastoreGet(filedata.Head) var linked_list LL_node json.Unmarshal(head, &linked_list) file_symm_data, _ := userlib.HashKDF(file_symm, []byte("encrypt data")) file_symm_data = file_symm_data[:16] file_symm_data_HMAC, _ := userlib.HashKDF(file_symm, []byte("HMAC data")) file_symm_data_HMAC = file_symm_data_HMAC[:16] file_symm_new_data, _ := userlib.HashKDF(file_symm_new, []byte("encrypt data")) file_symm_new_data = file_symm_new_data[:16] file_symm_new_data_HMAC, _ := userlib.HashKDF(file_symm_new, []byte("HMAC data")) file_symm_new_data_HMAC = file_symm_new_data_HMAC[:16] location := filedata.Head for linked_list.Next != uuid.Nil { ll_data, _ := userlib.DatastoreGet(linked_list.Data) calc_HMAC, _ := userlib.HMACEval(file_symm_data_HMAC, ll_data) if string(calc_HMAC) != string(linked_list.HMAC_Data) { return errors.New(strings.ToTitle("File contents have been corrupted in revoke.")) } if !CheckMult16(ll_data) { return errors.New(strings.ToTitle("Linked list data has been corrupted in RevokeFile.")) } data := userlib.SymDec(file_symm_data, ll_data) iv := userlib.RandomBytes(16) data = userlib.SymEnc(file_symm_new_data, iv, data) data_HMAC, _ := userlib.HMACEval(file_symm_new_data_HMAC, data) location_data := uuid.New() userlib.DatastoreSet(location_data, data) linked_list.Data = location_data linked_list.HMAC_Data = data_HMAC ll_marshalled, _ := json.Marshal(linked_list) userlib.DatastoreSet(location, ll_marshalled) next, _ := userlib.DatastoreGet(linked_list.Next) location = linked_list.Next json.Unmarshal(next, &linked_list) } ll_data, _ := userlib.DatastoreGet(linked_list.Data) calc_HMAC, _ := userlib.HMACEval(file_symm_data_HMAC, ll_data) if string(calc_HMAC) != string(linked_list.HMAC_Data) { return errors.New(strings.ToTitle("File contents have been corrupted in revoke end.")) } if !CheckMult16(ll_data) { return errors.New(strings.ToTitle("Linked list data has been corrupted in RevokeFile.")) } data := userlib.SymDec(file_symm_data, ll_data) iv := userlib.RandomBytes(16) data = userlib.SymEnc(file_symm_new_data, iv, data) data_HMAC, _ := userlib.HMACEval(file_symm_new_data_HMAC, data) location_data := uuid.New() userlib.DatastoreSet(location_data, data) linked_list.Data = location_data linked_list.HMAC_Data = data_HMAC ll_marshalled, _ := json.Marshal(linked_list) userlib.DatastoreSet(location, ll_marshalled) // for the for subtree of target user, change accessTokens to garbage invalid := []byte("This is an invalid accessToken.") updateAccessTokens(targetNode, invalid, userlib.RandomBytes(16), userlib.RandomBytes(10), Tree_sk, true) // remove subtree for this node in participants (probably create this helper) removeSubtree(&participants, targetNode.Username) updateAccessTokens(participants.Root, file_symm_new, file_id, owner, Tree_sk, false) DatastoreFile(file_id, file_owner_hash, file_symm_new, filedata) return } // iterates through node and all it's children and updates their accessTokens with given udpate_val // encrypts the update_val according to who the node belongs to func updateAccessTokens(node *Node, file_symm []byte, file_id []byte, file_owner []byte, owner_sk userlib.PKEDecKey, delete bool) (err error) { if node == nil { return nil } node_pk, _ := userlib.KeystoreGet(node.Username + "_enckey") encrypted_file_symm, _ := userlib.PKEEnc(node_pk, file_symm) encrypted_file_id, _ := userlib.PKEEnc(node_pk, file_id) encrypted_file_owner, _ := userlib.PKEEnc(node_pk, file_owner) signed_enc_file_symm := userlib.RandomBytes(256) signed_enc_file_id := userlib.RandomBytes(256) signed_enc_file_owner := userlib.RandomBytes(256) var encrypted_AT_struct AccessToken encrypted_AT_struct.Enc_file_symm = encrypted_file_symm encrypted_AT_struct.Enc_file_id = encrypted_file_id encrypted_AT_struct.Enc_file_owner = encrypted_file_owner encrypted_AT_struct.Signed_file_symm = signed_enc_file_symm encrypted_AT_struct.Signed_file_id = signed_enc_file_id encrypted_AT_struct.Signed_file_owner = signed_enc_file_owner encrypted_AT_marshaled, _ := json.Marshal(encrypted_AT_struct) AT, _ := userlib.PKEDec(owner_sk, node.User_invite_loc) var AT_uuid uuid.UUID json.Unmarshal(AT, &AT_uuid) userlib.DatastoreSet(AT_uuid, encrypted_AT_marshaled) if delete { userlib.DatastoreDelete(AT_uuid) _, ok := userlib.DatastoreGet(AT_uuid) if ok { return errors.New(strings.ToTitle("AT_uuid was not deleted from datastore.")) } } for _, child := range node.Children { updateAccessTokens(child, file_symm, file_id, file_owner, owner_sk, delete) } return nil } func removeSubtree(participants *Tree, targetUser string) (found bool) { queue := make([]*Node, 0) queue = append(queue, participants.Root) for len(queue) > 0 { next := queue[0] queue = queue[1:] if len(next.Children) > 0 { for idx, child := range next.Children { if child.Username == targetUser { if len(next.Children) == 1 { next.Children = nil } else { next.Children = append(next.Children[:idx], next.Children[idx+1:]...) } return true } queue = append(queue, child) } } } return false } <file_sep>package proj2 // You MUST NOT change these default imports. ANY additional imports it will // break the autograder and everyone will be sad. import ( _ "encoding/hex" _ "errors" "reflect" _ "strconv" _ "strings" "testing" "github.com/cs161-staff/userlib" "github.com/google/uuid" _ "github.com/google/uuid" ) func clear() { // Wipes the storage so one test does not affect another userlib.DatastoreClear() userlib.KeystoreClear() } func TestInit(t *testing.T) { clear() t.Log("Initialization test") // You can set this to false! userlib.SetDebugStatus(true) u, err := InitUser("alice", "fubar") if err != nil { // t.Error says the test fails t.Error("Failed to initialize user", err) return } // t.Log() only produces output if you run with "go test -v" t.Log("Got user", u) // If you want to comment the line above, // write _ = u here to make the compiler happy // You probably want many more tests here. u, err = InitUser("alice", "pingpong") if err == nil { // t.Error says the test fails t.Error("Failed to recognize a taken username", err) return } u, err = InitUser("Alice", "pingpong") if err != nil { // t.Error says the test fails t.Error("Failed to be case sensitive to usernames", err) return } u, err = InitUser("AliCe", "pingpong") if err != nil { // t.Error says the test fails t.Error("Failed to be case sensitive to usernames", err) return } u, err = InitUser("", "pingpong") if err == nil { // t.Error says the test fails t.Error("Failed to recognize an invalid empty username", err) return } u, err = InitUser("bob", "<PASSWORD>ong") if err != nil { // t.Error says the test fails t.Error("Failed to successfully create new user", err) return } } func TestGet(t *testing.T) { clear() t.Log("GetUser test") // You can set this to false! userlib.SetDebugStatus(true) _, err := InitUser("alice", "fubar") if err != nil { // t.Error says the test fails t.Error("Failed to initialize user", err) return } _, e := GetUser("alice", "fubar") if e != nil { t.Error("Failed to get user", e) return } _, e = GetUser("alice", "kkkk") if e == nil { t.Error("Failed to recognize wrong password.", e) return } _, e = GetUser("alicea", "fubar") if e == nil { t.Error("Failed to recognize wrong username.", e) return } _, e = GetUser("alisce", "kkkk") if e == nil { t.Error("Failed to recognize wrong username and password.", e) return } } func TestGetUserErrors(t *testing.T) { clear() _, err := InitUser("alice", "fubar") if err != nil { // t.Error says the test fails t.Error("Failed to initialize user", err) return } _, e := GetUser("alice", "fubar") if e != nil { t.Error("Failed to get user", e) return } // tamper with datastore // datastore := userlib.DatastoreGetMap() hash := userlib.Hash([]byte("alice")) slicehash := hash[:] garbage := userlib.RandomBytes(64) uuid_hash, _ := uuid.FromBytes(slicehash[:16]) userlib.DatastoreSet(uuid_hash, garbage) _, e = GetUser("alice", "fubar") if e == nil { t.Error("Failed to recognize user can't be retrieved.", e) return } ////////////// clear() _, err = InitUser("alice", "fubar") if err != nil { // t.Error says the test fails t.Error("Failed to initialize user", err) return } _, e = GetUser("alice", "fubar") if e != nil { t.Error("Failed to get user", e) return } // tamper with datastore // datastore := userlib.DatastoreGetMap() hash = userlib.Hash([]byte("alice" + "HMAC")) slicehash = hash[:] garbage = userlib.RandomBytes(64) uuid_hash, _ = uuid.FromBytes(slicehash[:16]) userlib.DatastoreSet(uuid_hash, garbage) _, e = GetUser("alice", "fubar") if e == nil { t.Error("Failed to recognize user can't be retrieved.", e) return } } func TestRetrieveHashmapErrors(t *testing.T) { clear() u, err := InitUser("alice", "fubar") if err != nil { // t.Error says the test fails t.Error("Failed to initialize user", err) return } v := []byte("Test storage") e := u.StoreFile("file1", v) if e != nil { t.Error("Failed to store file", e) return } hash := userlib.Hash([]byte("alice" + "files")) slicehash := hash[:] garbage := userlib.RandomBytes(64) uuid_hash, _ := uuid.FromBytes(slicehash[:16]) userlib.DatastoreSet(uuid_hash, garbage) v = []byte("Test overwriting with storage") e = u.StoreFile("file1", v) if e == nil { t.Error("Failed to store file", e) return } ////////////// clear() u, err = InitUser("alice", "fubar") if err != nil { // t.Error says the test fails t.Error("Failed to initialize user", err) return } v = []byte("Test storage") e = u.StoreFile("file1", v) if e != nil { t.Error("Failed to store file", e) return } hash = userlib.Hash([]byte("alice" + "files HMAC")) slicehash = hash[:] garbage = userlib.RandomBytes(64) uuid_hash, _ = uuid.FromBytes(slicehash[:16]) userlib.DatastoreSet(uuid_hash, garbage) v = []byte("Test overwriting with storage") e = u.StoreFile("file1", v) if e == nil { t.Error("Failed to store file", e) return } } func TestMultipleUserSessions(t *testing.T) { clear() _, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } alice1, err := GetUser("alice", "fubar") if err != nil { t.Error("Failed to get user", err) return } alice2, err := GetUser("alice", "fubar") if err != nil { t.Error("Failed to get user", err) return } if !reflect.DeepEqual(alice1, alice2) { t.Error("Alice1 and Alice2 don't point to the same thing", alice1, alice2) return } // alice1 creates a file v := []byte("This is a test") err1 := alice1.StoreFile("file1", v) if err1 != nil { t.Error("Alice1 failed to store.", err1) return } v2, err2 := alice1.LoadFile("file1") if err2 != nil { t.Error("Alice1 failed to download", err2) return } // alice2 can load the file v2, err2 = alice2.LoadFile("file1") if err2 != nil { t.Error("Alice2 failed to download", err2) return } if !reflect.DeepEqual(v, v2) { t.Error("Alice2's downloaded file is not the same", v, v2) return } // alice2 appends to the file err = alice2.AppendFile("file1", []byte("Appending to file.")) if err != nil { t.Error("Alice2 failed to append", err) } // alice1 can load the appended file v1, err1 := alice1.LoadFile("file1") if err1 != nil { t.Error("Alice1 failed to download", err1) return } expected_v := []byte("This is a testAppending to file.") if !reflect.DeepEqual(expected_v, v1) { t.Error("Alice1's downloaded file is not the same", expected_v, v1) return } // alice1 shares file to bob bob, _ := InitUser("bob", "<PASSWORD>") accessToken, err := alice1.ShareFile("file1", "bob") if err != nil { t.Error("Alice1 failed to share file1 with bob", err) return } err = bob.ReceiveFile("file1", "alice", accessToken) if err != nil { t.Error("Bob failed to receive file1 from Alice", err) return } // bob appends to file err = bob.AppendFile("file1", []byte("Bob appending here.")) if err != nil { t.Error("Bob failed to append to file1", err) return } bob_v, err1 := bob.LoadFile("file1") if err1 != nil { t.Error("Bob failed to download", err1) return } expected_v = []byte("This is a testAppending to file.Bob appending here.") if !reflect.DeepEqual(expected_v, bob_v) { t.Error("Bob's downloaded file is not the same", expected_v, bob_v) return } // alice1 and alice 2 can load the appended file alice1_v, err1 := alice1.LoadFile("file1") if err1 != nil { t.Error("Alice1 failed to download", err1) return } if !reflect.DeepEqual(expected_v, alice1_v) { t.Error("Alice1's downloaded file is not the same", expected_v, alice1_v) return } alice2_v, err1 := alice2.LoadFile("file1") if err1 != nil { t.Error("Alice2 failed to download", err1) return } if !reflect.DeepEqual(expected_v, alice2_v) { t.Error("Alice2's downloaded file is not the same", expected_v, alice2_v) return } } func TestMultipleUserSessions_2(t *testing.T) { clear() _, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } alice1, err := GetUser("alice", "fubar") if err != nil { t.Error("Failed to get user", err) return } alice2, err := GetUser("alice", "fbar") if err == nil { t.Error("Failed to recognize wrong password second session", err) return } alice2, err = GetUser("alice", "fubar") if err != nil { t.Error("Failed to get user", err) return } v := []byte("This is my file") alice1.StoreFile("file1", v) _, err = InitUser("bob", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } bob1, err := GetUser("bob", "fubar") if err != nil { t.Error("Failed to get user", err) return } bob2, err := GetUser("bob", "fubar") if err != nil { t.Error("Failed to get user", err) return } accessToken, err := alice2.ShareFile("file1", "bob") if err != nil { t.Error("Alice2 failed to share file1 with bob", err) return } err = bob1.ReceiveFile("file1", "alice", accessToken) if err != nil { t.Error("Bob1 failed to reeive from Alice2", err) return } bob_v := []byte("Bob2 appending") err = bob2.AppendFile("file1", bob_v) if err != nil { t.Error("Bob2 failed to append to file1", err) return } bob_v = []byte("Bob1 appending") err = bob1.AppendFile("file1", bob_v) if err != nil { t.Error("Bob1 failed to append to file1", err) return } alice_v := []byte("Alice1 appending") err = alice1.AppendFile("file1", alice_v) if err != nil { t.Error("Alice1 failed to append to file1", err) return } alice_v = []byte("Alice2 appending") err = alice2.AppendFile("file1", alice_v) if err != nil { t.Error("Alice2 failed to append to file1", err) return } data_bob1, err := bob1.LoadFile("file1") if err != nil { t.Error("Bob1 failed to load file1", err) return } expected_v := []byte("This is my fileBob2 appendingBob1 appendingAlice1 appendingAlice2 appending") if !reflect.DeepEqual(data_bob1, expected_v) { t.Error("files are not equal", data_bob1, expected_v) return } data_alice2, err := alice2.LoadFile("file1") if err != nil { t.Error("Alice2 failed to load file1", err) return } if !reflect.DeepEqual(data_alice2, expected_v) { t.Error("files are not equal", data_alice2, expected_v) return } //alice1 revoke from bob2 err = alice1.RevokeFile("file1", "bob") if err != nil { t.Error("Alice1 failed to revoke from Bob.", err) return } _, err = alice2.LoadFile("file1") if err != nil { t.Error("Alice2 failed to load file1", err) return } } func TestStorage(t *testing.T) { clear() u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } v := []byte("This is a test") err1 := u.StoreFile("file1", v) if err1 != nil { t.Error("Failed to store.", err1) return } v2, err2 := u.LoadFile("file1") if err2 != nil { t.Error("Failed to upload and download", err2) return } if !reflect.DeepEqual(v, v2) { t.Error("Downloaded file is not the same", v, v2) return } u1, _ := InitUser("bob", "<PASSWORD>") _, err3 := u1.LoadFile("file1") if err3 == nil { t.Error("Did not detect invalid load.", err3) return } _, err4 := u.LoadFile("file2") if err4 == nil { t.Error("Did not detect file DNE.", err4) return } v3 := []byte("This better overwrite") err5 := u.StoreFile("file1", v3) if err5 != nil { t.Error("Failed to overwrite.", err5) return } v4, err5 := u.LoadFile("file1") if err5 != nil { t.Error("Failed to upload and download", err5) return } if !reflect.DeepEqual(v3, v4) { t.Error("Downloaded file is not the same", v3, v4) return } } func TestInvalidFile(t *testing.T) { clear() u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } _, err2 := u.LoadFile("this file does not exist") if err2 == nil { t.Error("Downloaded a ninexistent file", err2) return } } func TestAppend(t *testing.T) { clear() u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } v := []byte("This is a test") u.StoreFile("file1", v) stored_v, _ := u.LoadFile("file1") if !reflect.DeepEqual(v, stored_v) { t.Error("not matching: ", string(stored_v)) return } err1 := u.AppendFile("file1", []byte(" appended data")) if err1 != nil { t.Error("Failed to append", err1) return } expected := []byte("This is a test appended data") loaded, err2 := u.LoadFile("file1") if err2 != nil { t.Error("Failed to load appended file", err2) return } if !reflect.DeepEqual(expected, loaded) { t.Error("Failed to correctly append ", string(loaded)) return } } func TestAppend_NonOwners(t *testing.T) { clear() u, err := InitUser("alice", "<PASSWORD>") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } u3, err3 := InitUser("charlie", "foobar") if err3 != nil { t.Error("Failed to initialize bob", err3) return } v := []byte("This is a test") u.StoreFile("file1", v) accessToken, err := u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the a file", err) return } err = u2.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } err = u2.AppendFile("file2", []byte("Appending this data.")) if err != nil { t.Error("Failed to allow non-owner to append", err) return } v2, err := u2.LoadFile("file2") if err != nil { t.Error("Bob failed to download the file after non-owner appended", err) return } expected_v := []byte("This is a testAppending this data.") if !reflect.DeepEqual(expected_v, v2) { t.Error("The file bob loaded after appending is incorrect.", expected_v, v2) return } alice_v, err := u.LoadFile("file1") if err != nil { t.Error("Alice failed to download the file after non-owner appended", err) return } if !reflect.DeepEqual(expected_v, alice_v) { t.Error("The file alice loaded after bob (non-owner) appended is incorrect.", expected_v, alice_v) return } accessToken, err = u2.ShareFile("file2", "charlie") if err != nil { t.Error("Failed to share the a file", err) return } err = u3.ReceiveFile("file3", "bob", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } err = u3.AppendFile("file3", []byte("Appending more data.")) if err != nil { t.Error("Failed to allow non-owner (charlie) to append", err) return } err = u3.AppendFile("file3", []byte("AND more data.")) if err != nil { t.Error("Failed to allow non-owner (charlie) to append", err) return } err = u.AppendFile("file1", []byte("AND even more data.")) if err != nil { t.Error("Failed to allow owner Alice to append", err) return } expected_v = []byte("This is a testAppending this data.Appending more data.AND more data.AND even more data.") v3, err := u3.LoadFile("file3") if err != nil { t.Error("Failed to download the file after sharing", err) return } if !reflect.DeepEqual(expected_v, v3) { t.Error("Shared file is not the same", v, v3) return } v2, err = u2.LoadFile("file2") if err != nil { t.Error("Bob failed to download the file after charlie appended", err) return } if !reflect.DeepEqual(expected_v, v2) { t.Error("Bob's shared file is not the same", v, v2) return } v1, err := u.LoadFile("file1") if err != nil { t.Error("Alice failed to download the file after charlie appended", err) return } if !reflect.DeepEqual(expected_v, v1) { t.Error("Alice's shared file is not the same", v, v1) return } } func TestShare(t *testing.T) { clear() u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } v := []byte("This is a test") u.StoreFile("file1", v) var v2 []byte var accessToken uuid.UUID v, err = u.LoadFile("file1") if err != nil { t.Error("Failed to download the file from alice", err) return } accessToken, err = u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the a file", err) return } err = u2.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } v2, err = u2.LoadFile("file2") if err != nil { t.Error("Failed to download the file after sharing", err) return } if !reflect.DeepEqual(v, v2) { t.Error("Shared file is not the same", v, v2) return } } func TestOverwrite(t *testing.T) { clear() // alice stores alice, err := InitUser("alice", "<PASSWORD>") if err != nil { t.Error("Failed to initialize alice", err) return } bob, err2 := InitUser("bob", "<PASSWORD>") if err2 != nil { t.Error("Failed to initialize bob", err2) return } v := []byte("This is a test") alice.StoreFile("file1", v) var accessToken uuid.UUID // alice loads v, err = alice.LoadFile("file1") if err != nil { t.Error("Failed to download the file from alice", err) return } // overwrite v = []byte("This is overwriting") alice.StoreFile("file1", v) // alice loads -- check correctly overwritten var v2 []byte v2, err = alice.LoadFile("file1") if err != nil { t.Error("Failed to download the file from alice after overwrite", err) return } if !reflect.DeepEqual(v, v2) { t.Error("overwritten file is not the same", v, v2) return } // alice share with Bob accessToken, err = alice.ShareFile("file1", "bob") if err != nil { t.Error("Alice failed to share file with bob", err) return } err = bob.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Bob failed to receive the share message", err) return } // bob storess v = []byte("Bob is overwriting") bob.StoreFile("file2", v) // alice load -- check correctly overwritten v2, err = alice.LoadFile("file1") if err != nil { t.Error("Failed to download the file from alice after bob overwrites", err) return } if !reflect.DeepEqual(v, v2) { t.Error("Shared file is not the same", v, v2) return } // bob load -- check correctly overwritten v2, err = bob.LoadFile("file2") if err != nil { t.Error("Failed to download the file from bob after he overwrites", err) return } if !reflect.DeepEqual(v, v2) { t.Error("Shared file is not the same", v, v2) return } } func TestRevoke_1(t *testing.T) { clear() u, err := InitUser("alice", "<PASSWORD>") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } v := []byte("This is a test") u.StoreFile("file1", v) var v2 []byte var accessToken uuid.UUID v, err = u.LoadFile("file1") if err != nil { t.Error("Failed to download the file from alice", err) return } accessToken, err = u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the a file", err) return } err = u2.ReceiveFile("file1", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } v2, err = u2.LoadFile("file1") if err != nil { t.Error("Failed to download the file after sharing", err) return } if !reflect.DeepEqual(v, v2) { t.Error("Shared file is not the same", v, v2) return } v, err = u.LoadFile("file1") if err != nil { t.Error("Failed to download the file from alice after share", err) return } err = u.RevokeFile("file1", "bob") if err != nil { t.Error("Failed to revoke access from bob", err) return } v, err = u.LoadFile("file1") if err != nil { t.Error("Failed to download the file from alice after revoke", err) return } v2, err = u2.LoadFile("file1") if err == nil { t.Error("Bob still has access after revocation", err) return } } func TestRevoke_2(t *testing.T) { //alice shares with bob & charlie, revoke from charlie, bob should still be able to load clear() // initalize users u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } u3, err3 := InitUser("charlie", "foobar") if err3 != nil { t.Error("Failed to initialize bob", err3) return } ///////////////// //alice create file v := []byte("This is a test") u.StoreFile("file1", v) var v2 []byte var accessToken uuid.UUID v, err = u.LoadFile("file1") if err != nil { t.Error("Failed to download the file from alice", err) return } ////////////////// // alice shares with bob accessToken, err = u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the a file", err) return } err = u2.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } v2, err = u2.LoadFile("file2") if err != nil { t.Error("Failed to download the file after sharing", err) return } if !reflect.DeepEqual(v, v2) { t.Error("Shared file is not the same", v, v2) return } /////////////////// // alice shares with charlie accessToken, err = u.ShareFile("file1", "charlie") if err != nil { t.Error("Failed to share the a file", err) return } err = u3.ReceiveFile("file3", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } v3, err := u3.LoadFile("file3") if err != nil { t.Error("Failed to download the file after sharing", err) return } if !reflect.DeepEqual(v, v3) { t.Error("Shared file is not the same", v, v3) return } ////////////////// v, err = u.LoadFile("file1") if err != nil { t.Error("Failed to download the file from alice after share", err) return } // Alice revokes from Bob err = u.RevokeFile("file1", "bob") if err != nil { t.Error("Failed to revoke access from bob", err) return } //////////// v, err = u.LoadFile("file1") if err != nil { t.Error("Failed to download the file from alice after revoke", err) return } v3, err = u3.LoadFile("file3") if err != nil { t.Error("Failed to download the file from charlie after alice revoked bob", err) return } v2, err = u2.LoadFile("file2") if err == nil { t.Error("Bob still has access after revocation", err) return } } func TestRevoke_3(t *testing.T) { //alice shares with bob, bob shares with charlie, revoke from bob - neither should be able to load clear() // initalize users u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } u3, err3 := InitUser("charlie", "foobar") if err3 != nil { t.Error("Failed to initialize bob", err3) return } ///////////////// //alice create file v := []byte("This is a test") u.StoreFile("file1", v) ////////////////// // alice shares with bob accessToken, err := u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the a file", err) return } err = u2.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } /////////////////// // bob shares with charlie accessToken, err = u2.ShareFile("file2", "charlie") if err != nil { t.Error("Failed to share the a file", err) return } err = u3.ReceiveFile("file3", "bob", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } v3, err := u3.LoadFile("file3") if err != nil { t.Error("Failed to download the file after sharing", err) return } if !reflect.DeepEqual(v, v3) { t.Error("Shared file is not the same", v, v3) return } ////////////////// v, err = u.LoadFile("file1") if err != nil { t.Error("Failed to download the file from alice after share", err) return } // Alice revokes from Bob err = u.RevokeFile("file1", "bob") if err != nil { t.Error("Failed to revoke access from bob", err) return } //////////// v, err = u.LoadFile("file1") if err != nil { t.Error("Failed to download the file from alice after revoke", err) return } v3, err = u3.LoadFile("file3") if err == nil { t.Error("Charlie still has access after revocation", err) return } _, err = u2.LoadFile("file2") if err == nil { t.Error("Bob still has access after revocation", err) return } } func TestRevoke_4(t *testing.T) { // test error check: share when user does not have acces to file clear() // initalize users u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } u3, err3 := InitUser("charlie", "foobar") if err3 != nil { t.Error("Failed to initialize bob", err3) return } ///////////////// //alice create file v := []byte("This is a test") u.StoreFile("file1", v) ////////////////// // bob shares with charlie _, err = u2.ShareFile("file1", "charlie") if err == nil { t.Error("Failed to recognize that Bob does not have access to file and cannot share the file", err) return } // Alice revokes from Bob w/o sharing with Bob err = u.RevokeFile("file1", "bob") if err == nil { t.Error("Failed to recognize alice cannot revoke from bob", err) return } //////////// // test error check: alice share Bob, bob share charlie, but he cannot revoke charlie accessToken, err := u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the file", err) return } err = u2.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } accessToken, err = u2.ShareFile("file2", "charlie") if err != nil { t.Error("Failed to allow participant (not owner) to share the file", err) return } err = u3.ReceiveFile("file3", "bob", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } err = u2.RevokeFile("file1", "charlie") if err == nil { t.Error("Failed to recognize bob (who is not the owner) cannot revoke from charlie", err) return } } func TestRevoke_5(t *testing.T) { clear() // initalize users u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } ///////////////// //alice create file v := []byte("This is a test") u.StoreFile("file1", v) ////////////////// // alice shares with bob accessToken, err := u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the a file", err) return } err = u2.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } //alice revokes from bob err = u.RevokeFile("file1", "bob") if err != nil { t.Error("Failed to revoke from bob", err) return } //bob attempts to load _, err = u2.LoadFile("file2") if err == nil { t.Error("Failed to correctly revoke from Bob.", err) return } //bob attempts to receive err = u2.ReceiveFile("file2", "alice", accessToken) if err == nil { t.Error("Bob was able to receive after being revoked", err) return } //bob tries to append err = u2.AppendFile("file2", []byte("this should not be appended")) if err == nil { t.Error("Bob was able to append after being revoked", err) return } //alice loads to make sure bob didn't append alice_v, err := u.LoadFile("file1") if err != nil { t.Error("Alice failed to correctly load.", err) return } if !reflect.DeepEqual(v, alice_v) { t.Error("Shared file is not the same", v, alice_v) return } //bob attempts to share _, err3 := InitUser("charlie", "foobar") if err3 != nil { t.Error("Failed to initialize charlie", err3) return } accessToken, err = u2.ShareFile("file2", "charlie") if err == nil { t.Error("Bob was able to share after being revoked", err) return } //bob attempts to revoke err = u2.RevokeFile("file2", "alice") if err == nil { t.Error("Bob was able to revoke from alice after being revoked", err) return } bob_new_v := []byte("Bob's file") err = u2.StoreFile("file2", bob_new_v) if err == nil { t.Error("Bob was able to overwrite after being revoked", err) return } } func TestShareReceiveOrder(t *testing.T) { clear() // initalize users u, err := InitUser("alice", "<PASSWORD>") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } ///////////////// //alice create file v := []byte("This is a test") u.StoreFile("file1", v) ////////////////// // alice shares with bob accessToken, err := u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the a file", err) return } err = u2.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } //bob tries to receive again err = u2.ReceiveFile("file2", "alice", accessToken) if err == nil { t.Error("Bob was able to receive twice", err) return } //bob tries to receive same file under a different name err = u2.ReceiveFile("file4", "alice", accessToken) if err != nil { t.Error("Bob was not able to same file under different name", err) return } //alice tries to receive her own file err = u.ReceiveFile("file1", "alice", accessToken) if err == nil { t.Error("Alice was able to receive her own file under same name", err) return } err = u.ReceiveFile("file2", "alice", accessToken) if err == nil { t.Error("Alice was able to receive her own file under different name", err) return } err = u.ReceiveFile("file3", "bob", accessToken) if err == nil { t.Error("Alice was able to receive her own file from bob as sender", err) return } //Charlie tries to receive accessToken intended for bob u3, err3 := InitUser("charlie", "foobar") if err3 != nil { t.Error("Failed to initialize charlie", err3) return } err = u3.ReceiveFile("file3", "alice", accessToken) if err == nil { t.Error("Charlie was able to receive intended for Bob.", err) return } //bob tries to share with alice accessToken, err = u2.ShareFile("file2", "alice") if err == nil { t.Error("Bob was able to share alice's file with alice", err) return } } func TestRevokeShare(t *testing.T) { // test error check: share, revoke, reshare clear() // initalize users u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } ///////////////// //alice create file v := []byte("This is a test") u.StoreFile("file1", v) ////////////////// // alice shares with bob accessToken, err := u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the a file", err) return } err = u2.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } bob_v, err := u2.LoadFile("file2") if err != nil { t.Error("Bob failed to load after receiving from Alice", err) return } if !reflect.DeepEqual(v, bob_v) { t.Error("Shared file is not the same", v, bob_v) return } /////////////////// // Alice revokes from Bob err = u.RevokeFile("file1", "bob") if err != nil { t.Error("Failed to revoke access from bob", err) return } bob_v, err = u2.LoadFile("file2") if err == nil { t.Error("Failed to correctly revoke from Bob.", err) return } //////////// // alice shares with bob accessToken, err = u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the a file", err) return } err = u2.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } bob_v, err = u2.LoadFile("file2") if err != nil { t.Error("Failed to reshare to Bob.", err) return } /////////////////// } func TestRevokeShare_2(t *testing.T) { // test error check: share, revoke, reshare clear() // initalize users u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } u3, err3 := InitUser("charlie", "foobar") if err3 != nil { t.Error("Failed to initialize bob", err3) return } ///////////////// //alice create file v := []byte("This is a test") u.StoreFile("file1", v) ////////////////// // alice shares with bob accessToken, err := u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the a file", err) return } err = u2.ReceiveFile("file1", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } // alice shares with charlie accessToken, err = u.ShareFile("file1", "charlie") if err != nil { t.Error("Failed to share the a file", err) return } err = u3.ReceiveFile("file1", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } charlie_v, err := u3.LoadFile("file1") if err != nil { t.Error("Charlie failed to load after receiving from Alice", err) return } if !reflect.DeepEqual(v, charlie_v) { t.Error("Shared file is not the same", v, charlie_v) return } /////////////////// // Alice revokes from Bob err = u.RevokeFile("file1", "bob") if err != nil { t.Error("Failed to revoke access from bob", err) return } _, err = u2.LoadFile("file1") if err == nil { t.Error("Failed to correctly revoke from Bob.", err) return } //////////// // charlie shares with bob accessToken, err = u3.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the a file", err) return } err = u2.ReceiveFile("file1", "charlie", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } bob_v, err := u2.LoadFile("file1") if err != nil { t.Error("Failed to reshare to Bob.", err) return } if !reflect.DeepEqual(v, bob_v) { t.Error("Shared file is not the same", v, bob_v) return } /////////////////// } func TestRevokeAppend(t *testing.T) { // test error check: share, revoke, reshare clear() // initalize users u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } ///////////////// //alice create file v := []byte("This is a test") u.StoreFile("file1", v) ////////////////// // alice shares with bob accessToken, err := u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the a file", err) return } err = u2.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } // Bob append err = u2.AppendFile("file2", []byte("Appending to file.")) if err != nil { t.Error("Bob failed to append", err) } // Alice revokes from Bob err = u.RevokeFile("file1", "bob") if err != nil { t.Error("Failed to revoke access from bob", err) return } _, err = u2.LoadFile("file2") if err == nil { t.Error("Failed to correctly revoke from Bob.", err) return } //////////// // Alice load and the appended data should still be there v1, err := u.LoadFile("file1") if err != nil { t.Error("Failed to correctly load after revoking Bob.", err) return } expected_v := []byte("This is a testAppending to file.") if !reflect.DeepEqual(expected_v, v1) { t.Error("Shared file is not the same", expected_v, v1) return } } func TestRevokeStore(t *testing.T) { // test error check: share, revoke, reshare clear() // initalize users u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } ///////////////// //alice create file v := []byte("This is a test") u.StoreFile("file1", v) ////////////////// // alice shares with bob accessToken, err := u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the a file", err) return } err = u2.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Failed to receive the share message", err) return } // Bob append err = u2.AppendFile("file2", []byte("Appending to file.")) if err != nil { t.Error("Bob failed to append", err) } // Alice revokes from Bob err = u.RevokeFile("file1", "bob") if err != nil { t.Error("Failed to revoke access from bob", err) return } _, err = u2.LoadFile("file2") if err == nil { t.Error("Failed to correctly revoke from Bob.", err) return } //////////// err = u2.StoreFile("file2", []byte("Bob trying to overwrite without access")) if err == nil { t.Error("Failed to correctly revoke from Bob. He's still storing!", err) return } } func TestRevokeMultChildren(t *testing.T) { clear() // initalize users u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } u3, err := InitUser("charlie", "fubar") if err != nil { t.Error("Failed to initialize charlie", err) return } u4, err2 := InitUser("david", "foobar") if err2 != nil { t.Error("Failed to initialize david", err2) return } u5, err := InitUser("eric", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u6, err2 := InitUser("fred", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } u7, err2 := InitUser("greg", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } //alice create file v := []byte("This is a test") u.StoreFile("file1", v) ////////////////// //alice shares with bob & charlie // alice shares with bob accessToken, err := u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the file with bob", err) return } err = u2.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Bob failed to receive the share message", err) return } accessToken, err = u.ShareFile("file1", "charlie") if err != nil { t.Error("Failed to share the file with charlie", err) return } err = u3.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Charlie failed to receive the share message", err) return } //Bob shares with greg accessToken, err = u2.ShareFile("file2", "greg") if err != nil { t.Error("Bob failed to share the file with greg", err) return } err = u7.ReceiveFile("file1", "bob", accessToken) if err != nil { t.Error("Greg failed to receive the share message", err) return } //Charlie shares with david & eric accessToken, err = u3.ShareFile("file2", "david") if err != nil { t.Error("Charlie failed to share the file with david", err) return } err = u4.ReceiveFile("file1", "charlie", accessToken) if err != nil { t.Error("David failed to receive the share message", err) return } accessToken, err = u3.ShareFile("file2", "eric") if err != nil { t.Error("Charlie failed to share the file with eric", err) return } err = u5.ReceiveFile("file1", "charlie", accessToken) if err != nil { t.Error("Eric failed to receive the share message", err) return } //Eric shares with fred accessToken, err = u5.ShareFile("file1", "fred") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u6.ReceiveFile("file1", "eric", accessToken) if err != nil { t.Error("Fred failed to receive the share message", err) return } //Alice revokes from charlie err = u.RevokeFile("file1", "charlie") if err != nil { t.Error("Alice failed to revoke from charlie", err) return } //Check that only alice, bob, greg can load _, err = u.LoadFile("file1") if err != nil { t.Error("Alice failed to load", err) return } _, err = u2.LoadFile("file2") if err != nil { t.Error("Bob failed to load", err) return } _, err = u3.LoadFile("file2") if err == nil { t.Error("Charlie still has access", err) return } _, err = u4.LoadFile("file1") if err == nil { t.Error("David still has access", err) return } _, err = u5.LoadFile("file1") if err == nil { t.Error("Eric still has access", err) return } _, err = u6.LoadFile("file1") if err == nil { t.Error("Fred still has access", err) return } _, err = u7.LoadFile("file1") if err != nil { t.Error("Greg failed to load", err) return } } func TestShareALot(t *testing.T) { clear() // initalize users u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } u3, err := InitUser("charlie", "fubar") if err != nil { t.Error("Failed to initialize charlie", err) return } u4, err2 := InitUser("david", "foobar") if err2 != nil { t.Error("Failed to initialize david", err2) return } u5, err := InitUser("eric", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u6, err2 := InitUser("fred", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } u7, err2 := InitUser("greg", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } u8, err2 := InitUser("harry", "foobar") if err2 != nil { t.Error("Failed to initialize harry", err2) return } u9, err2 := InitUser("izzy", "foobar") if err2 != nil { t.Error("Failed to initialize izzy", err2) return } u10, err2 := InitUser("john", "foobar") if err2 != nil { t.Error("Failed to initialize john", err2) return } u11, err2 := InitUser("kevin", "foobar") if err2 != nil { t.Error("Failed to initialize kevin", err2) return } u12, err2 := InitUser("lisa", "foobar") if err2 != nil { t.Error("Failed to initialize lisa", err2) return } u13, err2 := InitUser("monica", "foobar") if err2 != nil { t.Error("Failed to initialize monica", err2) return } u14, err2 := InitUser("nancy", "foobar") if err2 != nil { t.Error("Failed to initialize nancy", err2) return } u15, err2 := InitUser("olaf", "foobar") if err2 != nil { t.Error("Failed to initialize olaf", err2) return } u16, err2 := InitUser("pat", "foobar") if err2 != nil { t.Error("Failed to initialize pat", err2) return } //alice create file v := []byte("This is a test") u.StoreFile("file1", v) ////////////////// //alice shares with bob & charlie // alice shares with bob accessToken, err := u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the file with bob", err) return } err = u2.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Bob failed to receive the share message", err) return } accessToken, err = u.ShareFile("file1", "charlie") if err != nil { t.Error("Failed to share the file with charlie", err) return } err = u3.ReceiveFile("file2", "alice", accessToken) if err != nil { t.Error("Charlie failed to receive the share message", err) return } //Bob shares with greg accessToken, err = u2.ShareFile("file2", "greg") if err != nil { t.Error("Bob failed to share the file with greg", err) return } err = u7.ReceiveFile("file1", "bob", accessToken) if err != nil { t.Error("Greg failed to receive the share message", err) return } //Charlie shares with david & eric accessToken, err = u3.ShareFile("file2", "david") if err != nil { t.Error("Charlie failed to share the file with david", err) return } err = u4.ReceiveFile("file1", "charlie", accessToken) if err != nil { t.Error("David failed to receive the share message", err) return } accessToken, err = u3.ShareFile("file2", "eric") if err != nil { t.Error("Charlie failed to share the file with eric", err) return } err = u5.ReceiveFile("file1", "charlie", accessToken) if err != nil { t.Error("Eric failed to receive the share message", err) return } //Eric shares with fred accessToken, err = u5.ShareFile("file1", "fred") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u6.ReceiveFile("file1", "eric", accessToken) if err != nil { t.Error("Fred failed to receive the share message", err) return } accessToken, err = u5.ShareFile("file1", "harry") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u8.ReceiveFile("file1", "eric", accessToken) if err != nil { t.Error("harry failed to receive the share message", err) return } accessToken, err = u5.ShareFile("file1", "izzy") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u9.ReceiveFile("file1", "eric", accessToken) if err != nil { t.Error("izzy failed to receive the share message", err) return } accessToken, err = u5.ShareFile("file1", "john") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u10.ReceiveFile("file1", "eric", accessToken) if err != nil { t.Error("john failed to receive the share message", err) return } accessToken, err = u5.ShareFile("file1", "kevin") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u11.ReceiveFile("file1", "eric", accessToken) if err != nil { t.Error("kevin failed to receive the share message", err) return } accessToken, err = u5.ShareFile("file1", "lisa") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u12.ReceiveFile("file1", "eric", accessToken) if err != nil { t.Error("lisa failed to receive the share message", err) return } accessToken, err = u5.ShareFile("file1", "monica") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u13.ReceiveFile("file1", "eric", accessToken) if err != nil { t.Error("monica failed to receive the share message", err) return } accessToken, err = u5.ShareFile("file1", "nancy") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u14.ReceiveFile("file1", "eric", accessToken) if err != nil { t.Error("nancy failed to receive the share message", err) return } accessToken, err = u5.ShareFile("file1", "olaf") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u15.ReceiveFile("file1", "eric", accessToken) if err != nil { t.Error("olaf failed to receive the share message", err) return } accessToken, err = u5.ShareFile("file1", "pat") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u16.ReceiveFile("file1", "eric", accessToken) if err != nil { t.Error("pat failed to receive the share message", err) return } } func TestShareTreeSearch(t *testing.T) { clear() // initalize users u, err := InitUser("alice", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } u3, err := InitUser("charlie", "fubar") if err != nil { t.Error("Failed to initialize charlie", err) return } u4, err2 := InitUser("david", "foobar") if err2 != nil { t.Error("Failed to initialize david", err2) return } u5, err := InitUser("eric", "fubar") if err != nil { t.Error("Failed to initialize user", err) return } u6, err2 := InitUser("fred", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } u7, err2 := InitUser("greg", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } u8, err2 := InitUser("harry", "foobar") if err2 != nil { t.Error("Failed to initialize harry", err2) return } u9, err2 := InitUser("izzy", "foobar") if err2 != nil { t.Error("Failed to initialize izzy", err2) return } u10, err2 := InitUser("john", "foobar") if err2 != nil { t.Error("Failed to initialize john", err2) return } _, err2 = InitUser("kevin", "foobar") if err2 != nil { t.Error("Failed to initialize kevin", err2) return } //alice create file v := []byte("This is a test") u.StoreFile("file1", v) ////////////////// //alice shares with bob & charlie // alice shares with bob accessToken, err := u.ShareFile("file1", "bob") if err != nil { t.Error("Failed to share the file with bob", err) return } err = u2.ReceiveFile("file1", "alice", accessToken) if err != nil { t.Error("Bob failed to receive the share message", err) return } accessToken, err = u2.ShareFile("file1", "charlie") if err != nil { t.Error("Failed to share the file with charlie", err) return } err = u3.ReceiveFile("file1", "bob", accessToken) if err != nil { t.Error("Charlie failed to receive the share message", err) return } //Bob shares with greg accessToken, err = u3.ShareFile("file1", "david") if err != nil { t.Error("Bob failed to share the file with greg", err) return } err = u4.ReceiveFile("file1", "charlie", accessToken) if err != nil { t.Error("Greg failed to receive the share message", err) return } accessToken, err = u4.ShareFile("file1", "eric") if err != nil { t.Error("Charlie failed to share the file with david", err) return } err = u5.ReceiveFile("file1", "david", accessToken) if err != nil { t.Error("David failed to receive the share message", err) return } accessToken, err = u5.ShareFile("file1", "fred") if err != nil { t.Error("Charlie failed to share the file with eric", err) return } err = u6.ReceiveFile("file1", "eric", accessToken) if err != nil { t.Error("Eric failed to receive the share message", err) return } accessToken, err = u6.ShareFile("file1", "greg") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u7.ReceiveFile("file1", "fred", accessToken) if err != nil { t.Error("Fred failed to receive the share message", err) return } accessToken, err = u7.ShareFile("file1", "harry") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u8.ReceiveFile("file1", "greg", accessToken) if err != nil { t.Error("harry failed to receive the share message", err) return } accessToken, err = u8.ShareFile("file1", "izzy") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u9.ReceiveFile("file1", "harry", accessToken) if err != nil { t.Error("izzy failed to receive the share message", err) return } accessToken, err = u9.ShareFile("file1", "john") if err != nil { t.Error("Eric failed to share the file with eric", err) return } err = u10.ReceiveFile("file1", "izzy", accessToken) if err != nil { t.Error("john failed to receive the share message", err) return } err = u.RevokeFile("file1", "john") if err != nil { t.Error("Failed to revoke from john", err) return } err = u.RevokeFile("file1", "kevin") if err == nil { t.Error("Should have errored") return } } func TestRetrieveAccessTokenError(t *testing.T) { clear() u, err := InitUser("alice", "foobar") if err != nil { t.Error("Failed to initialize bob", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } //alice share with bob v := []byte("Alice's file") err = u.StoreFile("file1", v) if err != nil { t.Error("Failed to store", err) return } accessToken, _ := u.ShareFile("file1", "bob") //bob receive accessToken u2.ReceiveFile("file1", "alice", accessToken) //delete the accessToken from datastore userlib.DatastoreDelete(accessToken) //expect error when bob tries to load _, err = u2.LoadFile("file1") if err == nil { t.Error("Did not recognize accessToken is missing from datastores", err) return } } func TestAppendError(t *testing.T) { clear() u, err := InitUser("alice", "foobar") if err != nil { t.Error("Failed to initialize alice", err) return } v := []byte("Alice's file") err = u.StoreFile("file1", v) if err != nil { t.Error("Failed to store", err) return } err = u.AppendFile("file1", []byte("")) if err == nil { t.Error("Failed to recognize no bytes to append", err) return } u2, err := InitUser("bob", "foobar") if err != nil { t.Error("Failed to initialize bob", err) return } err = u2.AppendFile("file1", []byte("bob can't do this")) if err == nil { t.Error("Failed to recognize bob can't append", err) return } //Alice appends a bunch of stuff serially u.AppendFile("file1", []byte("Append1")) u.AppendFile("file1", []byte("Append2")) u.AppendFile("file1", []byte("Append3")) u.AppendFile("file1", []byte("Append4")) u.AppendFile("file1", []byte("Append5")) u.AppendFile("file1", []byte("Append6")) u.AppendFile("file1", []byte("Append7")) u.AppendFile("file1", []byte("Append8")) u.AppendFile("file1", []byte("Append9")) u.AppendFile("file1", []byte("Append10")) u.AppendFile("file1", []byte("Append11")) u.AppendFile("file1", []byte("Append12")) v1, err := u.LoadFile("file1") if err != nil { t.Error("Failed to load after multiple appends", err) return } expected_v := []byte("Alice's fileAppend1Append2Append3Append4Append5Append6" + "Append7Append8Append9Append10Append11Append12") if !reflect.DeepEqual(expected_v, v1) { t.Error("appended file is not correc", expected_v, v1) return } accessToken, err := u.ShareFile("file1", "bob") if err != nil { t.Error("Alice failed to share the file with bob", err) return } err = u2.ReceiveFile("file1", "alice", accessToken) if err != nil { t.Error("bob failed to receive the share message", err) return } err = u2.StoreFile("file1", []byte("Overwriting everything")) if err != nil { t.Error("bob failed to overwrite", err) return } v2, err := u.LoadFile("file1") if err != nil { t.Error("Alice failed to load after bob overwrite", err) return } expected_v = []byte("Overwriting everything") if !reflect.DeepEqual(expected_v, v2) { t.Error("overwritten file is not correct", expected_v, v2) return } u2.AppendFile("file1", []byte("Append1")) u.AppendFile("file1", []byte("Append2")) u2.AppendFile("file1", []byte("Append3")) u.AppendFile("file1", []byte("Append4")) u2.AppendFile("file1", []byte("Append5")) u.AppendFile("file1", []byte("Append6")) u2.AppendFile("file1", []byte("Append7")) u.AppendFile("file1", []byte("Append8")) u2.AppendFile("file1", []byte("Append9")) u.AppendFile("file1", []byte("Append10")) u2.AppendFile("file1", []byte("Append11")) u.AppendFile("file1", []byte("Append12")) v2, err = u.LoadFile("file1") if err != nil { t.Error("Alice failed to load after bob appends a lot", err) return } expected_v = []byte("Overwriting everythingAppend1Append2Append3Append4Append5Append6" + "Append7Append8Append9Append10Append11Append12") if !reflect.DeepEqual(expected_v, v2) { t.Error("appended file is not correct", string(expected_v), string(v2)) return } } func TestLoadErrorCorruptedHash(t *testing.T) { clear() userlib.SetDebugStatus(true) u, err := InitUser("alice", "foobar") if err != nil { t.Error("Failed to initialize alice", err) return } ds := userlib.DatastoreGetMap() ds_orig := make(map[uuid.UUID][]byte) for k, v := range ds { ds_orig[k] = v } v := []byte("Alice's file") err = u.StoreFile("file1", v) if err != nil { t.Error("Failed to store", err) return } ds = userlib.DatastoreGetMap() ds_orig2 := make(map[uuid.UUID][]byte) for k, v := range ds { ds_orig2[k] = v } diff := []uuid.UUID{} for k, _ := range ds_orig2 { if _, ok := ds_orig[k]; !ok { diff = append(diff, k) } } var file1HMACuuid uuid.UUID file1HMACuuid = uuid.Nil for i := 0; i < len(diff); i++ { elem := diff[i] element, _ := userlib.DatastoreGet(elem) if len(element) == 64 { file1HMACuuid = elem } } userlib.DatastoreSet(file1HMACuuid, userlib.RandomBytes(64)) _, err = u.LoadFile("file1") if err == nil { t.Error("Failed to detect corrupted file struct", err) return } } func TestFuzzDatastore(t *testing.T) { clear() userlib.SetDebugStatus(true) //// Initialize and edit datastore u, err := InitUser("alice", "foobar") if err != nil { t.Error("Failed to initialize alice", err) return } ds := userlib.DatastoreGetMap() ds_orig := make(map[uuid.UUID][]byte) for k, v := range ds { ds_orig[k] = v // userlib.DebugMsg(strconv.Itoa(len(v))) } //////// Get node 1 v := []byte("Alice's file") err = u.StoreFile("file1", v) if err != nil { t.Error("Failed to store", err) return } ds = userlib.DatastoreGetMap() ds_orig2 := make(map[uuid.UUID][]byte) for k, v := range ds { ds_orig2[k] = v } diff := []uuid.UUID{} for k, _ := range ds_orig2 { if _, ok := ds_orig[k]; !ok { diff = append(diff, k) } } for i := 0; i < len(diff); i++ { elem := diff[i] element, _ := userlib.DatastoreGet(elem) // corrupt userlib.DatastoreSet(elem, []byte("Corrupting elem")) // check loadfile fails _, err = u.LoadFile("file1") if err == nil { t.Error("Failed to detect corruption. i = ", i, err) return } //truncate length := int(len(element) / 2) data := element[:length] userlib.DatastoreSet(elem, data) // check laodfile fails _, err = u.LoadFile("file1") if err == nil { t.Error("Failed to detect corruption. i = ", i, err) return } //clear userlib.DatastoreSet(elem, []byte("")) _, err = u.LoadFile("file1") if err == nil { t.Error("Failed to detect corruption. i = ", i, err) return } //replace original value userlib.DatastoreSet(elem, element) } ///////////////// err = u.AppendFile("file1", []byte("Appending data 1")) if err != nil { t.Error("Failed to append 1", err) return } ds = userlib.DatastoreGetMap() ds_orig3 := make(map[uuid.UUID][]byte) for k, v := range ds { ds_orig3[k] = v } diff = []uuid.UUID{} for k, _ := range ds_orig3 { if _, ok := ds_orig2[k]; !ok { diff = append(diff, k) } } for i := 0; i < len(diff); i++ { elem := diff[i] element, _ := userlib.DatastoreGet(elem) // corrupt userlib.DatastoreSet(elem, []byte("Corrupting elem")) // check loadfile fails _, err = u.LoadFile("file1") if err == nil { t.Error("Failed to detect corruption. i = ", i, err) return } //truncate length := int(len(element) / 2) data := element[:length] userlib.DatastoreSet(elem, data) // check laodfile fails _, err = u.LoadFile("file1") if err == nil { t.Error("Failed to detect corruption. i = ", i, err) return } //clear userlib.DatastoreSet(elem, []byte("")) _, err = u.LoadFile("file1") if err == nil { t.Error("Failed to detect corruption. i = ", i, err) return } //replace original value userlib.DatastoreSet(elem, element) } /////////////// err = u.AppendFile("file1", []byte("Appending data 2")) if err != nil { t.Error("Failed to append 2", err) return } ds = userlib.DatastoreGetMap() ds_orig4 := make(map[uuid.UUID][]byte) for k, v := range ds { ds_orig4[k] = v } diff = []uuid.UUID{} for k, _ := range ds_orig4 { if _, ok := ds_orig3[k]; !ok { diff = append(diff, k) } } for i := 0; i < len(diff); i++ { elem := diff[i] element, _ := userlib.DatastoreGet(elem) // corrupt userlib.DatastoreSet(elem, []byte("Corrupting elem")) // check loadfile fails _, err = u.LoadFile("file1") if err == nil { t.Error("Failed to detect corruption. i = ", i, err) return } //truncate length := int(len(element) / 2) data := element[:length] userlib.DatastoreSet(elem, data) // check laodfile fails _, err = u.LoadFile("file1") if err == nil { t.Error("Failed to detect corruption. i = ", i, err) return } //clear userlib.DatastoreSet(elem, []byte("")) _, err = u.LoadFile("file1") if err == nil { t.Error("Failed to detect corruption. i = ", i, err) return } //replace original value userlib.DatastoreSet(elem, element) } u2, err2 := InitUser("bob", "fubar") if err2 != nil { t.Error("Failed to initialize alice", err2) return } accessToken, err2 := u.ShareFile("file1", "bob") if err2 != nil { t.Error("Failed to share with bob", err2) return } ds = userlib.DatastoreGetMap() ds_orig5 := make(map[uuid.UUID][]byte) for k, v := range ds { ds_orig4[k] = v } diff = []uuid.UUID{} for k, _ := range ds_orig5 { if _, ok := ds_orig4[k]; !ok { diff = append(diff, k) } } for i := 0; i < len(diff); i++ { elem := diff[i] element, _ := userlib.DatastoreGet(elem) // corrupt userlib.DatastoreSet(elem, []byte("Corrupting elem")) // check receivefile fails err2 = u2.ReceiveFile("file1", "alice", accessToken) if err2 == nil { t.Error("Failed to receive from alice", err2) return } //truncate length := int(len(element) / 2) data := element[:length] userlib.DatastoreSet(elem, data) // check laodfile fails err2 = u2.ReceiveFile("file1", "alice", accessToken) if err2 == nil { t.Error("Failed to receive from alice", err2) return } //clear userlib.DatastoreSet(elem, []byte("")) // check laodfile fails err2 = u2.ReceiveFile("file1", "alice", accessToken) if err2 == nil { t.Error("Failed to receive from alice", err2) return } //replace original value userlib.DatastoreSet(elem, element) } } func TestSwapDatastore(t *testing.T) { clear() userlib.SetDebugStatus(true) //// Initialize and edit datastore u, err := InitUser("alice", "foobar") if err != nil { t.Error("Failed to initialize alice", err) return } ds := userlib.DatastoreGetMap() ds_orig := make(map[uuid.UUID][]byte) for k, v := range ds { ds_orig[k] = v } //////// Get node 1 v := []byte("Alice's file") err = u.StoreFile("file1", v) if err != nil { t.Error("Failed to store", err) return } ds = userlib.DatastoreGetMap() ds_orig2 := make(map[uuid.UUID][]byte) for k, v := range ds { ds_orig2[k] = v } diff := []uuid.UUID{} for k, _ := range ds_orig2 { if _, ok := ds_orig[k]; !ok { diff = append(diff, k) } } for i := 0; i < len(diff)-1; i += 1 { elem1 := diff[i] element1, _ := userlib.DatastoreGet(elem1) elem2 := diff[i+1] element2, _ := userlib.DatastoreGet(elem2) userlib.DatastoreSet(elem1, element2) userlib.DatastoreSet(elem2, element1) _, err = u.LoadFile("file1") if err == nil { t.Error("Failed to recognize datastore swap", err) return } userlib.DatastoreSet(elem1, element1) userlib.DatastoreSet(elem2, element2) } } // initialize alice and bob // create file --> obtain diff which will have file related stuff // corrupt, share, revoke error in a for loop func TestRevokeDataErrors(t *testing.T) { clear() userlib.SetDebugStatus(true) //// Initialize and edit datastore u, err := InitUser("alice", "foobar") if err != nil { t.Error("Failed to initialize alice", err) return } u2, err2 := InitUser("bob", "foobar") if err2 != nil { t.Error("Failed to initialize bob", err2) return } ds := userlib.DatastoreGetMap() ds_orig := make(map[uuid.UUID][]byte) for k, v := range ds { ds_orig[k] = v // userlib.DebugMsg(strconv.Itoa(len(v))) } //////// Get node 1 v := []byte("Alice's file") err = u.StoreFile("file1", v) if err != nil { t.Error("Failed to store", err) return } u.AppendFile("file1", []byte("More data")) ds = userlib.DatastoreGetMap() ds_orig2 := make(map[uuid.UUID][]byte) for k, v := range ds { ds_orig2[k] = v } diff_file := []uuid.UUID{} for k, _ := range ds_orig2 { if _, ok := ds_orig[k]; !ok { diff_file = append(diff_file, k) } } accessToken, _ := u.ShareFile("file1", "bob") u2.ReceiveFile("file1", "alice", accessToken) for i := 0; i < len(diff_file); i++ { elem := diff_file[i] element, _ := userlib.DatastoreGet(elem) // corrupt userlib.DatastoreSet(elem, []byte("Corrupting elem")) // check loadfile fails err = u.RevokeFile("file1", "bob") if err == nil { t.Error("Failed to detect corruption. i = ", i, err) return } //truncate length := int(len(element) / 2) data := element[:length] userlib.DatastoreSet(elem, data) // check laodfile fails err = u.RevokeFile("file1", "bob") if err == nil { t.Error("Failed to detect corruption. i = ", i, err) return } //clear userlib.DatastoreSet(elem, []byte("")) err = u.RevokeFile("file1", "bob") if err == nil { t.Error("Failed to detect corruption. i = ", i, err) return } //replace original value userlib.DatastoreSet(elem, element) } } func TestAppendEfficiency(t *testing.T) { clear() userlib.SetDebugStatus(true) //// Initialize and edit datastore u, err := InitUser("alice", "foobar") if err != nil { t.Error("Failed to initialize alice", err) return } v := []byte("Alice's file") err = u.StoreFile("file1", v) if err != nil { t.Error("Failed to store", err) return } v1 := []byte("Alice's fileAlice's fileAlice's fileAlice's fileAlice's fileAlice's fileAlice's fileAlice's fileAlice's fileAlice's fileAlice's file") err = u.StoreFile("file2", v1) if err != nil { t.Error("Failed to store", err) return } //Check that append doesn't scale with size of file userlib.DatastoreResetBandwidth() u.AppendFile("file1", []byte("More data.")) b1 := userlib.DatastoreGetBandwidth() userlib.DatastoreResetBandwidth() u.AppendFile("file2", []byte("More data.")) b2 := userlib.DatastoreGetBandwidth() difference := b1 - b2 if difference < 0 { if -1*difference > 50 { t.Error("Not an efficient append", b1, b2) return } } else { if difference > 50 { t.Error("Not an efficient append", difference) return } } // Check that append doesn't scale with number of appends userlib.DatastoreResetBandwidth() u.StoreFile("file1", []byte("Orig data")) for i := 0; i < 50; i++ { u.AppendFile("file1", []byte("append")) } b1 = userlib.DatastoreGetBandwidth() userlib.DatastoreResetBandwidth() for i := 50; i < 100; i++ { u.AppendFile("file1", []byte("append")) } b2 = userlib.DatastoreGetBandwidth() difference = b1 - b2 if difference < 0 { if -1*difference > 5000 { t.Error("Not an efficient append num appends", b1, b2) return } } else { if difference > 5000 { t.Error("Not an efficient append num appends", b1, b2) return } } //AppendFile cannot scale with the number of previous appends (from piazza) u.StoreFile("file1", []byte("A")) u.StoreFile("file2", []byte("A")) for i := 0; i < 50; i++ { u.AppendFile("file1", []byte("append")) } userlib.DatastoreResetBandwidth() u.AppendFile("file1", []byte("B")) b1 = userlib.DatastoreGetBandwidth() userlib.DatastoreResetBandwidth() u.AppendFile("file2", []byte("B")) b2 = userlib.DatastoreGetBandwidth() difference = b1 - b2 if difference < 0 { if -1*difference > 50 { t.Error("Not an efficient append prev appends", b1, b2) return } } else { if difference > 50 { t.Error("Not an efficient append prev appends", b1, b2) return } } //AppendFile cannot scale with the size of the previous append (from piazza) u.StoreFile("file1", []byte("A")) u.StoreFile("file2", []byte("A")) u.AppendFile("file1", []byte("appendappendappendappendappendappendappendappendappend"+ "appendappendappendappendappendappendappendappendappend"+"appendappendappendappendappendappendappendappendappend"+ "appendappendappendappendappendappendappendappendappend"+"appendappendappendappendappendappendappendappendappend")) userlib.DatastoreResetBandwidth() u.AppendFile("file1", []byte("B")) b1 = userlib.DatastoreGetBandwidth() userlib.DatastoreResetBandwidth() u.AppendFile("file2", []byte("B")) b2 = userlib.DatastoreGetBandwidth() difference = b1 - b2 if difference < 0 { if -1*difference > 50 { t.Error("Not an efficient append size prev appends", b1, b2) return } } else { if difference > 50 { t.Error("Not an efficient append size prev appends", b1, b2) return } } } func TestNilUser(t *testing.T) { clear() _, err := InitUser("", "hello") if err == nil { t.Error("Didn't catch that we can't have empty username", err) return } _, err = InitUser("alice", "") if err == nil { t.Error("Didn't catch that we can't have empty password", err) return } } func TestEmptyFilename(t *testing.T) { clear() alice, err := InitUser("alice", "hello") if err != nil { t.Error("Can't create user alice", err) return } bob, err := InitUser("bob", "hello") if err != nil { t.Error("Can't create user bob ", err) return } v := []byte("Storing to an empty file name") err = alice.StoreFile("", v) if err != nil { t.Error("failed to store with an empty filename", err) return } _, err = alice.LoadFile("") if err != nil { t.Error("failed to load with an empty filename", err) return } accessToken, err := alice.ShareFile("", "bob") if err != nil { t.Error("failed to share with an empty filename", err) return } err = bob.ReceiveFile("", "alice", accessToken) if err != nil { t.Error("failed to receive with an empty filename", err) return } bob_v := []byte("Bob's appending to an empty filename!") err = bob.AppendFile("", bob_v) if err != nil { t.Error("failed to append with an empty filename", err) return } err = alice.RevokeFile("", "bob") if err != nil { t.Error("failed to revoke bob from an empty filename", err) return } } func TestShareRevoke(t *testing.T) { clear() alice, err := InitUser("alice", "hello") if err != nil { t.Error("Can't create user alice", err) return } bob, err := InitUser("bob", "hello") if err != nil { t.Error("Can't create user bob ", err) return } v := []byte("Storing to an empty file name") err = alice.StoreFile("", v) if err != nil { t.Error("failed to store with an empty filename", err) return } _, err = alice.ShareFile("", "bob") if err != nil { t.Error("failed to share with an empty filename", err) return } err = alice.RevokeFile("", "bob") if err != nil { t.Error("failed to revoke bob from an empty filename", err) return } _, err = bob.LoadFile("") if err == nil { t.Error("did not correctly revoke from bob", err) return } } func TestRevokeAttack(t *testing.T) { clear() alice, err := InitUser("alice", "hello") if err != nil { t.Error("Can't create user alice", err) return } bob, err := InitUser("bob", "hello") if err != nil { t.Error("Can't create user bob ", err) return } v := []byte("Storing to an empty file name") err = alice.StoreFile("", v) if err != nil { t.Error("failed to store with an empty filename", err) return } accessToken, err := alice.ShareFile("", "bob") if err != nil { t.Error("failed to share with an empty filename", err) return } err = bob.ReceiveFile("", "alice", accessToken) if err != nil { t.Error("did not correctly revoke from bob", err) return } _, err = bob.LoadFile("") if err != nil { t.Error("Bob failed to load file", err) return } err = alice.RevokeFile("", "bob") if err != nil { t.Error("failed to revoke bob from an empty filename", err) return } err = bob.ReceiveFile("", "alice", accessToken) if err == nil { t.Error("did not correctly revoke from bob", err) return } } func TestDifUsersSameFile(t *testing.T) { clear() alice, err := InitUser("alice", "hello") if err != nil { t.Error("Can't create user alice", err) return } bob, err := InitUser("bob", "hello") if err != nil { t.Error("Can't create user bob ", err) return } v := []byte("Storing to an empty file name") err = alice.StoreFile("", v) if err != nil { t.Error("failed to store with an empty filename", err) return } err = bob.StoreFile("", v) if err != nil { t.Error("failed to store with an empty filename", err) return } } func TestNonExistentUsers(t *testing.T) { clear() _, err := GetUser("alice", "i totally exist") if err == nil { t.Error("Failed to recognize Alice is not a real user to get.", err) return } v := []byte("dummy data") InitUser("dummy", "hello") charlie, _ := InitUser("charlie", "fubar") // existent user share with non-existent err = charlie.StoreFile("file2", v) if err != nil { t.Error("Failed to store file for Charlie.", err) return } _, err = charlie.ShareFile("file2", "alice") if err == nil { t.Error("Failed to recognize Charlie cannot share with Alice who DNE.", err) return } // non-existent receive from existent accessToken, _ := charlie.ShareFile("file2", "dummy") err = charlie.ReceiveFile("file2", "alice", accessToken) if err == nil { t.Error("Failed to recognize Alice DNE so can't receive from Charlie.", err) return } // existent tries to revoke from non-existent err = charlie.RevokeFile("file2", "bob") if err == nil { t.Error("Failed to recognize Charlie cannot revoke from Bob because Bob DNE.", err) return } }
681c9f89a780b61ae9bbceb22dd313d1651fbfc0
[ "Go" ]
2
Go
vainaviv/project2-starter-code
d0fa7175b43cb80671f333cc0e321c029baa937d
5a5f80b249c70836f680e0cd46c50dfdd79ee8df
refs/heads/master
<file_sep>const fs = require('fs'); const path = require('path'); const config= require('./config'); const moment = require('moment'); function ensureDir(p) { if(!fs.existsSync(p)){ fs.mkdirSync(p); } } function getAssetRelativePath(absolutePath, assetPath='/assets', replaceSplit = true){ let targetPath = absolutePath.replace(path.join(config.baseDir, assetPath), ""); if(targetPath && replaceSplit){ targetPath = targetPath.replace(/\\/g, "/"); } return targetPath; } const formatDate = (value, formatStr = 1) => { if(!value){ return ''; } let date = moment(value); let targetFormatStr = formatStr; if(targetFormatStr === 1){ targetFormatStr = 'YYYY-MM-DD HH:mm:ss' }else if(targetFormatStr === 2){ targetFormatStr = 'YYYY-MM-DD' }else if(targetFormatStr === 3){ targetFormatStr = 'YYYYMMDDHHmmss' } if (date.isValid()) { return date.format(targetFormatStr); } return ''; }; module.exports = { ensureDir, getAssetRelativePath, formatDate, }<file_sep>const puppeteer = require('puppeteer'); const browserPromise = puppeteer.launch(); module.exports = { port: 8080, baseDir : __dirname, getBrowserInstance: ()=> browserPromise, resCode: { suc: 200, err: 400, }, defaultDevice: 'iPhone 6', }<file_sep>const path = require('path'); const fs = require('fs'); const utils = require('./utils'); const stringRandom = require('string-random'); const config = require('./config'); const puppeteer = require('puppeteer'); const devices = require('puppeteer/DeviceDescriptors'); const Koa = require('koa'); const app = new Koa(); const serve = require('koa-static'); const cors = require('koa2-cors'); const bodyParser = require('koa-bodyparser'); const Router = require('koa-router'); const assetsDir = path.join(config.baseDir, `assets`); utils.ensureDir(assetsDir); app.use(cors()); app.use(serve('assets')); app.use(bodyParser()); const router = new Router(); router.all('/', async(ctx, next)=>{ ctx.response.type = 'html'; ctx.body = fs.createReadStream('index.html'); }) // can do things: // 1.ๅฏไปฅ็”จchannelๅŒบๅˆ†ไธๅŒไบงๅ“ // 2.ๅฏไปฅๆ”ฏๆŒ่‡ชๅฎšไน‰ๅฐบๅฏธใ€dpi // 3.ๅฏไปฅๆ”ฏๆŒๆˆชๅ–ๆŒ‡ๅฎšๅŒบๅŸŸ router.all('/poster', async(ctx, next)=>{ const startDate = Date.now(); try{ let req = ctx.request.body || {}; req.channel=1800; if(ctx.request.method!='POST'){ let urlParams = ctx.request.search; if(urlParams.startsWith("?")){ urlParams=urlParams.substr(1); } urlParams.split('&').forEach(item=>{ let index = item.indexOf("="); if(index<=0){ return; } req[item.substr(0, index)] = item.substr(index+1); }) } req.device = req.device || config.defaultDevice; const targetDevice = devices[req.device]; let errMsg = ''; if(!req.channel){ errMsg = 'channelๅ‚ๆ•ฐไธ่ƒฝไธบ็ฉบ๏ผ'; }else if(!req.url){ errMsg = 'urlๅ‚ๆ•ฐไธ่ƒฝไธบ็ฉบ๏ผ'; }else if(!targetDevice){ errMsg = 'deviceๅ‚ๆ•ฐไธๅˆๆณ•๏ผ'; } if(errMsg){ ctx.status = 200; ctx.body = { code: config.resCode.err, msg: errMsg, } return; } // prepare work const targetDir = path.join(config.baseDir, `assets/${req.channel}`); utils.ensureDir(targetDir); const targetFileName = stringRandom(6)+"_"+utils.formatDate(Date.now(),3)+".png"; const targetFilePath = path.join(targetDir, targetFileName); // ๅ•ไพ‹๏ผšๅ…จๅฑ€็ปดๆŒไธ€ไธชbrowserๅฎžไพ‹ const browser = await config.getBrowserInstance(); // ๅฏไผ˜ๅŒ–๏ผš็ปดๆŠคไธ€ไธชpagePool๏ผŒ็ฑปไผผ็บฟ็จ‹ๆฑ ๏ผŒๅ‡ๅฐ‘ๆถˆ่€— const page = await browser.newPage(); await page.emulate(targetDevice); await page.goto(req.url, {waitUntil: "networkidle0"}); // ๅฏไผ˜ๅŒ–๏ผšๆตทๆŠฅhtmlๆ”พๅœจ้กน็›ฎๅ†…๏ผŒๆœฌๅœฐๅŠ ่ฝฝๆ›ดๅฟซ await page.screenshot({path: targetFilePath, fullPage: false}); page.close(); let posterUrl = utils.getAssetRelativePath(targetFilePath); const endDate = Date.now(); ctx.status = 200; ctx.body = { code: config.resCode.suc, msg: '็”ŸๆˆๆตทๆŠฅๆˆๅŠŸ๏ผ', timespan: (endDate-startDate)+'ms', data: { posterUrl, }, } }catch(e){ const endDate = Date.now(); ctx.status = 200; ctx.body = { code: config.resCode.err, msg: '็”ŸๆˆๆตทๆŠฅๅคฑ่ดฅ๏ผ', timespan: (endDate-startDate)+'ms', data: { error: e.toString(), }, } } }); router.all('/health', async(ctx, next)=>{ ctx.body = 'ok'; }); app.use(router.routes()).use(router.allowedMethods()); const server = app.listen(config.port, function (){ const host = server.address().address; const port = server.address().port; console.log('app start listening at http://%s:%s', host, port); });<file_sep># puppeteer-poster puppeteer็”ŸๆˆๆตทๆŠฅ
17ac61946b6f74d241ad71ec06323137d86214e7
[ "JavaScript", "Markdown" ]
4
JavaScript
Thyiad/puppeteer-poster
39f642f88a596f29d7a9b406563f9f0b150d7228
082c799b60cb563524fea57fad8adf31f77dc88c
refs/heads/master
<file_sep>package com.lusheng.bookcrossing.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.lusheng.bookcrossing.dao.BaseDao; import com.lusheng.bookcrossing.model.PointsChangeRecord; import com.lusheng.bookcrossing.service.PointsChangeRecordService; @Service("pointsChangeRecordService") public class PointsChangeRecordServiceImpl extends BaseServiceImpl<PointsChangeRecord> implements PointsChangeRecordService{ @Resource(name="pointsChangeRecordDao") @Override public void setDao(BaseDao<PointsChangeRecord> dao) { super.setDao(dao); } @Override public List<PointsChangeRecord> getPointsChangeRecordsByUidHasPage( Integer uid, int pageNum, int pageSize) { String hql="from PointsChangeRecord p where p.user.uid =? order by p.time desc"; return this.findEntityHasPageByHQL(hql, (pageNum-1)*pageSize, pageSize, uid); } @Override public int getPointsChangeRecordsCountByUid(Integer uid) { String hql="select count(*) from PointsChangeRecord p where p.user.uid =?"; return (int)(long) this.uniqueResult(hql, uid); } } <file_sep>package com.lusheng.bookcrossing.dao.impl; import org.springframework.stereotype.Repository; import com.lusheng.bookcrossing.model.User; @Repository("userDao") public class UserDaoImpl extends BaseDaoImpl<User>{ } <file_sep>package com.lusheng.bookcrossing.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.lusheng.bookcrossing.dao.BaseDao; import com.lusheng.bookcrossing.model.DriftRecord; import com.lusheng.bookcrossing.service.DriftRecordService; @Service("driftRecordService") public class DriftRecordServiceImpl extends BaseServiceImpl<DriftRecord> implements DriftRecordService { @Resource(name = "driftRecordDao") @Override public void setDao(BaseDao<DriftRecord> dao) { super.setDao(dao); } @Override public DriftRecord getDriftingRecordByBid(Integer bid) { String hql = "from DriftRecord d where d.book.bid=? and d.status=?"; List<DriftRecord> driftRecords = this.findEntityByHQL(hql, bid, DriftRecord.DRIFTING_STATUS); if (driftRecords == null || driftRecords.size() == 0) { return null; } return driftRecords.get(0); } @Override public DriftRecord getLastDriftedRecordByBid(Integer bid) { String hql = "from DriftRecord d where d.book.bid=? and d.status=? order by d.startTime desc"; List<DriftRecord> driftRecords = this.findEntityByHQL(hql, bid, DriftRecord.DRIFTED_STATUS); if (driftRecords == null || driftRecords.size() == 0) { return null; } return driftRecords.get(0); } @Override public List<DriftRecord> getDriftRecordsByBidHasPage(Integer bid, int pageNum, int pageSize) { String hql = "from DriftRecord d where d.book.bid=?"; return this.findEntityHasPageByHQL(hql, (pageNum - 1) * pageSize, pageSize, bid); } @Override public int getDriftRecordsCountByBid(Integer bid) { String hql = "select count(*) from DriftRecord d where d.book.bid=?"; return (int) (long) this.uniqueResult(hql, bid); } @Override public List<DriftRecord> getDriftRecordsByUidHasPageHasPage(Integer uid, int pageNum, int pageSize) { String hql="from DriftRecord d where d.preUser.uid=? or d.nextUser.uid=?"; return this.findEntityHasPageByHQL(hql, (pageNum - 1) * pageSize, pageSize, uid,uid); } @Override public int getDriftRecordsCountByUid(Integer uid) { String hql = "select count(*) from DriftRecord d where d.preUser.uid=? or d.nextUser.uid=?"; return (int) (long) this.uniqueResult(hql, uid,uid); } } <file_sep>package com.lusheng.bookcrossing.dao.impl; import org.springframework.stereotype.Repository; import com.lusheng.bookcrossing.model.Review; @Repository("reviewDao") public class ReviewDaoImpl extends BaseDaoImpl<Review>{ } <file_sep>package com.lusheng.bookcrossing.dao.impl; import org.springframework.stereotype.Repository; import com.lusheng.bookcrossing.model.DriftRecord; @Repository("driftRecordDao") public class DriftRecordDaoImpl extends BaseDaoImpl<DriftRecord>{ } <file_sep>package com.lusheng.bookcrossing.uitls; import java.util.LinkedHashMap; import java.util.Map; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class JsonUtils { private static final String FLAG_KEY = "flag"; private static final String DATA_KEY = "data"; public static final String ERROR_CODE_KEY = "errorCode"; public static final String ERROR_STR_KEY = "errorStr"; private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); public static String getSuccessMsg(Object data) { Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put(FLAG_KEY, true); if (data != null) { map.put(DATA_KEY, data); } return gson.toJson(map); } public static String getErrorMsg(int errorCode, String errorStr) { Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put(FLAG_KEY, false); map.put(ERROR_CODE_KEY, errorCode); map.put(ERROR_STR_KEY, errorStr); return gson.toJson(map); } public static String getServerBugErrorMsg(){ return getErrorMsg(Config.SERVER_BUG_ERROR_CODE, Config.SERVER_BUG_ERROR_STR); } } <file_sep>package com.lusheng.bookcrossing.dao.impl; import org.springframework.stereotype.Repository; import com.lusheng.bookcrossing.model.Book; @Repository("bookDao") public class BookDaoImpl extends BaseDaoImpl<Book>{ } <file_sep>package com.lusheng.bookcrossing.uitls; import java.util.UUID; public class UUIDUtils { public static String randomUUID(){ return UUID.randomUUID().toString().replace("-", ""); } } <file_sep>package com.lusheng.bookcrossing.action.manager; public interface IManagerAction { String BASE_PATH = "manager"; String ERROR = "error"; String SUCCESS = "success"; String SUCCESS_CODE = "1"; String ERROR_CODE = "0"; } <file_sep>package com.lusheng.bookcrossing.action.mobile; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.lusheng.bookcrossing.model.Book; import com.lusheng.bookcrossing.model.DriftRecord; import com.lusheng.bookcrossing.model.User; import com.lusheng.bookcrossing.service.BookService; import com.lusheng.bookcrossing.service.DriftRecordService; import com.lusheng.bookcrossing.uitls.Config; import com.lusheng.bookcrossing.uitls.JsonUtils; import com.lusheng.bookcrossing.uitls.ParameterUtils; @Controller @RequestMapping("mobile") public class DriftRecordAction { @Autowired private BookService bookService; @Autowired private DriftRecordService driftRecordService; @ResponseBody @RequestMapping("/lookDriftRecordByBid") public String lookDriftRecordByBid(HttpServletRequest request){ Integer bid=ParameterUtils.getIntNoCareException(request, "bid", -1); int pageNum=ParameterUtils.getIntNoCareException(request, "pageNum", 1); int pageSize=ParameterUtils.getIntNoCareException(request, "pageSize", 10); if(bid==-1){ return JsonUtils.getErrorMsg(Config.INVALID_PRAMETERS_ERROR_CODE, "bidๆ ผๅผไธๅฏน"); } Book book=bookService.getEntity(bid); if(book==null){ return JsonUtils.getErrorMsg(Config.OTHER_ERROR_CODE, "ไธๅญ˜ๅœจๆญคๆผ‚ไนฆ"); } int count=driftRecordService.getDriftRecordsCountByBid(bid); pageSize=pageSize==0?10:pageSize; int pageCount=(count-1)/pageSize+1; List<DriftRecord> driftRecords=driftRecordService.getDriftRecordsByBidHasPage(bid, pageNum, pageSize); Map<String,Object> map=new LinkedHashMap<String, Object>(); map.put("pageNum", pageNum); map.put("pageCount", pageCount); map.put("driftRecords", wrapDriftRecords(driftRecords)); return JsonUtils.getSuccessMsg(map); } @ResponseBody @RequestMapping("/lookMyDriftRecord") public String lookMyDriftRecord(HttpServletRequest request){ Integer uid=(Integer) request.getAttribute("uid"); int pageNum=ParameterUtils.getIntNoCareException(request, "pageNum", 1); int pageSize=ParameterUtils.getIntNoCareException(request, "pageSize", 10); int count=driftRecordService.getDriftRecordsCountByUid(uid); pageSize=pageSize==0?10:pageSize; int pageCount=(count-1)/pageSize+1; List<DriftRecord> driftRecords=driftRecordService.getDriftRecordsByUidHasPageHasPage(uid, pageNum, pageSize); Map<String,Object> map=new LinkedHashMap<String, Object>(); map.put("pageNum", pageNum); map.put("pageCount", pageCount); map.put("driftRecords", wrapDriftRecords(driftRecords)); return JsonUtils.getSuccessMsg(map); } private List<DriftRecordWrapper> wrapDriftRecords(List<DriftRecord> driftRecords){ List<DriftRecordWrapper> driftRecordWrappers=new ArrayList<DriftRecordAction.DriftRecordWrapper>(); for(DriftRecord driftRecord:driftRecords){ driftRecordWrappers.add(new DriftRecordWrapper(driftRecord)); } return driftRecordWrappers; } private static class DriftRecordWrapper extends DriftRecord{ public Integer preUid; public String preUsername; public Integer nextUid; public String nextUsername; public Integer bid; public String bookname; public DriftRecordWrapper(DriftRecord driftRecord){ setDrid(driftRecord.getDrid()); setStartTime(driftRecord.getStartTime()); setEndTime(driftRecord.getEndTime()); setStatus(driftRecord.getStatus()); User preUser=driftRecord.getPreUser(); if(preUser!=null){ preUid=preUser.getUid(); preUsername=preUser.getUsername(); } User nextUser=driftRecord.getNextUser(); if(nextUser!=null){ nextUid=nextUser.getUid(); nextUsername=nextUser.getUsername(); } Book book = driftRecord.getBook(); if(book!=null){ bid = book.getBid(); bookname=book.getBookname(); } } } } <file_sep>package com.lusheng.bookcrossing.model; import java.util.ArrayList; import java.util.List; public class Category { private Integer cid; private String cname; private Category parent; private List<Category> subCategories=new ArrayList<Category>(); public List<Category> getSubCategories() { return subCategories; } public void setSubCategories(List<Category> subCategories) { this.subCategories = subCategories; } public Integer getCid() { return cid; } public void setCid(Integer cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public Category getParent() { return parent; } public void setParent(Category parent) { this.parent = parent; } @Override public String toString() { return "Category [cid=" + cid + ", cname=" + cname + ", parent=" + parent + "]"; } } <file_sep>package com.lusheng.bookcrossing.action.manager; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.lusheng.bookcrossing.model.Manager; import com.lusheng.bookcrossing.service.ManagerService; import com.lusheng.bookcrossing.uitls.ParameterUtils; import com.lusheng.bookcrossing.uitls.TextUtils; @RequestMapping("manager") @Controller public class ManagePersonInfoAction implements IManagerAction{ @Autowired private ManagerService managerService; @RequestMapping("/login") public String login(HttpServletRequest request) { String accountNumber = ParameterUtils.getTrimString(request, "accountNumber"); String password = ParameterUtils.getTrimString(request, "password"); if (TextUtils.isEmpty(accountNumber)) { request.setAttribute(ERROR, "่ดฆๅทไธ่ƒฝไธบ็ฉบ"); return "forward:/manager/login.jsp"; } if (TextUtils.isEmpty(password)) { request.setAttribute(ERROR, "ๅฏ†็ ไธ่ƒฝไธบ็ฉบ"); return "forward:/manager/login.jsp"; } Manager manager = managerService.login(accountNumber, password); if (manager != null) { request.getSession().setAttribute("manager", manager); return BASE_PATH + "/home"; } else { request.setAttribute(ERROR, "่ดฆๅทๆˆ–ๅฏ†็ ไธๆญฃ็กฎ"); return "forward:/manager/login.jsp"; } } @RequestMapping("/home") public String goHome() { return BASE_PATH + "/home"; } @RequestMapping("/logout") public String logout(HttpSession session) { session.invalidate(); return "redirect:/manager/login.jsp"; } @RequestMapping(value = "/changePassword", method = RequestMethod.GET) public String goChangePassword() { return BASE_PATH + "/changePassword"; } @RequestMapping(value = "/changePassword", method = RequestMethod.POST) public String changePassword(HttpServletRequest request) { String oldPwd = ParameterUtils.getTrimString(request, "oldPwd"); String newPwd = ParameterUtils.getTrimString(request, "newPwd"); if (TextUtils.isEmpty(oldPwd)) { request.setAttribute(ERROR, "ๅŽŸๅง‹ๅฏ†็ ไธ่ƒฝไธบ็ฉบ"); return BASE_PATH + "/changePassword"; } if (TextUtils.isEmpty(newPwd)) { request.setAttribute(ERROR, "ๆ–ฐๅฏ†็ ไธ่ƒฝไธบ็ฉบ"); return BASE_PATH + "/changePassword"; } Manager manager = (Manager) request.getSession() .getAttribute("manager"); if (!TextUtils.equals(manager.getPassword(), oldPwd)) { request.setAttribute(ERROR, "ๅŽŸๅง‹ๅฏ†็ ้”™่ฏฏ"); return BASE_PATH + "/changePassword"; } if (TextUtils.equals(oldPwd, newPwd)) { request.setAttribute(ERROR, "ๆ–ฐๅฏ†็ ไธ่ƒฝไธŽๅŽŸๅง‹ๅฏ†็ ็›ธๅŒ"); return BASE_PATH + "/changePassword"; } try { managerService.changePassword(manager.getMid(), newPwd); request.setAttribute(SUCCESS, "ๅฏ†็ ไฟฎๆ”นๆˆๅŠŸ"); manager.setPassword(newPwd); } catch (Exception e) { request.setAttribute(ERROR, "ๅฏ†็ ไฟฎๆ”นๅคฑ่ดฅ"); } return BASE_PATH + "/changePassword"; } } <file_sep>package com.lusheng.bookcrossing.dao.impl; import org.springframework.stereotype.Repository; import com.lusheng.bookcrossing.model.PointsChangeRecord; @Repository("pointsChangeRecordDao") public class PointsChangeRecordDaoImpl extends BaseDaoImpl<PointsChangeRecord>{ } <file_sep>package com.lusheng.bookcrossing.service; import java.util.List; import com.lusheng.bookcrossing.model.Review; public interface ReviewService extends BaseService<Review>{ List<Review> getReviewsByBid(Integer bid); List<Review> getReviewsByUidHasPage(Integer uid,int pageNum,int pageSize); int getReviewsCountByUid(Integer uid); void deleteReviewByRid(Integer rid); void praiseReview(Integer rid,Integer uid); void trampleReview(Integer rid,Integer uid); } <file_sep>package com.lusheng.bookcrossing.service; import com.lusheng.bookcrossing.model.PraiseTrampleRecord; public interface PraiseTrampleRecordService extends BaseService<PraiseTrampleRecord>{ PraiseTrampleRecord getPraiseTrampleRecordByUidAndRid(Integer uid,Integer rid); } <file_sep>package com.lusheng.bookcrossing.dao.impl; import org.springframework.stereotype.Repository; import com.lusheng.bookcrossing.model.PraiseTrampleRecord; @Repository("praiseTrampleRecordDao") public class PraiseTrampleRecordDaoImpl extends BaseDaoImpl<PraiseTrampleRecord>{ } <file_sep>package com.lusheng.bookcrossing.action.manager; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.lusheng.bookcrossing.model.Book; import com.lusheng.bookcrossing.model.Category; import com.lusheng.bookcrossing.model.User; import com.lusheng.bookcrossing.service.BookService; import com.lusheng.bookcrossing.service.CategoryService; import com.lusheng.bookcrossing.uitls.ParameterUtils; import com.lusheng.bookcrossing.uitls.TextUtils; import com.lusheng.bookcrossing.uitls.UUIDUtils; @RequestMapping("manager") @Controller public class ManageBookAction implements IManagerAction{ private static final int PAGE_SIZE = 5; @Autowired private BookService bookService; @Autowired private CategoryService categoryService; @RequestMapping("/shareBook") public void shareBook(HttpServletRequest request){ Book book; User user=new User(); user.setUid(22); String imagePath="/file/image/avatar/test.jpg"; for(int i=0;i<100;i++){ book=new Book(); book.setAuthor("ไฝœ่€…"+i); book.setBookcrossingId(UUIDUtils.randomUUID()); book.setBookname("ไนฆๅ"+i); book.setShareUser(user); book.setImagePath(imagePath); book.setPress("ๅ‡บ็‰ˆ็คพ"+i); book.setPublishTime(new Date(System.currentTimeMillis()-i*1000*60*60*24)); book.setShareTime(new Date(System.currentTimeMillis()-i*1000000)); book.setStatus(Book.NO_AUDIT); bookService.saveEntity(book); } } @RequestMapping("/auditBook") public String auditBook(HttpServletRequest request){ int status=ParameterUtils.getIntNoCareException(request, "status", Book.NO_AUDIT); int pageNum=ParameterUtils.getIntNoCareException(request, "pageNum", 1); List<Book> books=bookService.getBooksByStatusHasPage(status, pageNum, PAGE_SIZE); int bookCount=bookService.getBookCountByStatus(status); int pageCount=(bookCount-1)/PAGE_SIZE+1; request.setAttribute("status", status); request.setAttribute("books", books); request.setAttribute("pageNum", pageNum); request.setAttribute("pageCount", pageCount); if(status==Book.NO_AUDIT){ List<Category> categories = categoryService.getFirstLevelCategories(); request.setAttribute("categories", categories); } return BASE_PATH+"/auditBook"; } @RequestMapping("/auditPass") public void auditPass(HttpServletRequest request,PrintWriter out){ int bid; int cid; try { bid=ParameterUtils.getInt(request, "bid"); cid=ParameterUtils.getInt(request, "cid"); } catch (Exception e) { out.write(ERROR_CODE); out.flush(); return; } try { bookService.auditPass(bid, cid); out.write(SUCCESS_CODE); } catch (Exception e) { out.write(ERROR_CODE); } out.flush(); } @RequestMapping("/auditNoPass") public void auditNoPass(HttpServletRequest request,PrintWriter out){ String nopassReason=ParameterUtils.getTrimString(request, "nopassReason"); int bid; try { bid=ParameterUtils.getInt(request, "bid"); } catch (Exception e) { out.write(ERROR_CODE); out.flush(); return; } try { bookService.auditNoPass(bid, nopassReason); out.write(SUCCESS_CODE); } catch (Exception e) { out.write(ERROR_CODE); } out.flush(); } @RequestMapping("/changeCategory") public void changeCategory(HttpServletRequest request,PrintWriter out){ int bid; int cid; try { bid=ParameterUtils.getInt(request, "bid"); cid=ParameterUtils.getInt(request, "cid"); } catch (Exception e) { out.write(ERROR_CODE); out.flush(); return; } try { bookService.changeCategory(bid, cid); out.write(SUCCESS_CODE); } catch (Exception e) { out.write(ERROR_CODE); } out.flush(); } @RequestMapping("/searchBook") public String searchBook(HttpServletRequest request){ String searchContent=ParameterUtils.getTrimString(request, "searchContent"); int searchFieldCode=ParameterUtils.getIntNoCareException(request, "searchFieldCode", Book.SEARCH_BOOKCROSSINGID_FIELD_CODE); int searchType=ParameterUtils.getIntNoCareException(request, "searchType", Book.ACCURATE_SEARCH_TPYE); int pageNum=ParameterUtils.getIntNoCareException(request, "pageNum", 1); List<Book> books=new ArrayList<Book>(); int pageCount = 0; if(!TextUtils.isEmpty(searchContent)){ if(searchFieldCode==Book.SEARCH_BOOKCROSSINGID_FIELD_CODE){ Book book=bookService.getPassAuditBookByBookcrossingId(searchContent); if(book!=null){ books.add(book); if(books.size()==1){ pageCount=1; } } }else if(searchFieldCode==Book.SEARCH_BOOKNAME_FIELD_CODE){ books.addAll(bookService.getPassAuditBooksByNameHasPage(searchContent, searchType, pageNum, PAGE_SIZE)); pageCount=(bookService.getPassAuditBooksCountByName(searchContent, searchType)-1)/PAGE_SIZE+1; } } request.setAttribute("searchContent", searchContent); request.setAttribute("searchFieldCode", searchFieldCode); request.setAttribute("searchType", searchType); request.setAttribute("pageNum", pageNum); request.setAttribute("books", books); request.setAttribute("pageCount", pageCount); return BASE_PATH+"/searchBook"; } @RequestMapping("/listBook") public String listBook(HttpServletRequest request){ int pid=ParameterUtils.getIntNoCareException(request, "pid", -1); int cid=ParameterUtils.getIntNoCareException(request, "cid", -1); int pageNum=ParameterUtils.getIntNoCareException(request, "pageNum", 1); List<Category> categories=categoryService.getFirstLevelCategories(); List<Category> subCategories = null; List<Book> books = null; int pageCount = 0; if(pid!=-1&&cid!=-1){ subCategories=categoryService.getSecondLevelCategories(pid); books=bookService.getPassAuditBooksByCategoryHasPage(cid, pageNum, PAGE_SIZE); pageCount=(bookService.getPassAuditBooksCountByCategory(cid)-1)/PAGE_SIZE+1; } request.setAttribute("pid", pid); request.setAttribute("cid", cid); request.setAttribute("pageNum", pageNum); request.setAttribute("categories", categories); request.setAttribute("subCategories", subCategories); request.setAttribute("books", books); request.setAttribute("pageCount", pageCount); return BASE_PATH+"/listBook"; } @RequestMapping("/bookInfo") public String bookInfo(HttpServletRequest request){ int bid=ParameterUtils.getIntNoCareException(request, "bid", 0); Book book=bookService.getEntity(bid); List<Category> categories=categoryService.getFirstLevelCategories(); request.setAttribute("book", book); request.setAttribute("categories", categories); return BASE_PATH+"/bookInfo"; } } <file_sep>package com.lusheng.bookcrossing.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.lusheng.bookcrossing.dao.BaseDao; import com.lusheng.bookcrossing.model.PraiseTrampleRecord; import com.lusheng.bookcrossing.model.Review; import com.lusheng.bookcrossing.model.User; import com.lusheng.bookcrossing.service.ReviewService; import com.lusheng.bookcrossing.service.UserService; @Service("reviewService") public class ReviewServiceImpl extends BaseServiceImpl<Review> implements ReviewService{ @Autowired private UserService userService; @Resource(name="praiseTrampleRecordDao") private BaseDao<PraiseTrampleRecord> praiseTrampleRecordDao; @Resource(name="reviewDao") @Override public void setDao(BaseDao<Review> dao) { super.setDao(dao); } @Override public List<Review> getReviewsByBid(Integer bid) { String hql="from Review r where r.book.bid=?"; return this.findEntityByHQL(hql, bid); } @Override public List<Review> getReviewsByUidHasPage(Integer uid, int pageNum, int pageSize) { String hql="from Review r where r.user.uid=? order by r.time desc"; return this.findEntityHasPageByHQL(hql, (pageNum-1)*pageSize, pageSize, uid); } @Override public int getReviewsCountByUid(Integer uid) { String hql="select count(*) from Review r where r.user.uid=?"; return (int)(long) this.uniqueResult(hql, uid); } @Override public void deleteReviewByRid(Integer rid) { String hql1="delete from PraiseTrampleRecord p where p.review.rid=?"; this.batchEntityByHQL(hql1, rid); String hql2="delete from Review r where r.rid=?"; this.batchEntityByHQL(hql2, rid); } @Override public void praiseReview(Integer rid, Integer uid) { Review review=this.getEntity(rid); if(review==null){ return; } review.setPraiseNum(review.getPraiseNum()+1); if(review.getPraiseNum()==10){ userService.changePointsByUid(review.getUser().getUid(), 20,"ๅฏนไบŽๆผ‚ไนฆ"+review.getBook().getBookname()+"็š„ไนฆ่ฏ„ๅพ—ๅˆฐ10ไธช่ตž"); } PraiseTrampleRecord praiseTrampleRecord=new PraiseTrampleRecord(); praiseTrampleRecord.setReview(review); User user=new User(); user.setUid(uid); praiseTrampleRecord.setUser(user); praiseTrampleRecord.setType(PraiseTrampleRecord.PRAISE_TYPE); praiseTrampleRecordDao.saveEntity(praiseTrampleRecord); } @Override public void trampleReview(Integer rid, Integer uid) { Review review=this.getEntity(rid); if(review==null){ return; } review.setTrampleNum(review.getTrampleNum()+1); if(review.getTrampleNum()==10){ userService.changePointsByUid(review.getUser().getUid(), -20,"ๅฏนไบŽๆผ‚ไนฆ"+review.getBook().getBookname()+"็š„ไนฆ่ฏ„ๅพ—ๅˆฐ10ไธช่ธฉ"); } PraiseTrampleRecord praiseTrampleRecord=new PraiseTrampleRecord(); praiseTrampleRecord.setReview(review); User user=new User(); user.setUid(uid); praiseTrampleRecord.setUser(user); praiseTrampleRecord.setType(PraiseTrampleRecord.TRAMPLE_TYPE); praiseTrampleRecordDao.saveEntity(praiseTrampleRecord); } } <file_sep># bookcrossing ๆฏ•ไธš่ฎพ่ฎก
0a17bb02ad7fa3c410648a38be7675b3a1c40f2f
[ "Markdown", "Java" ]
19
Java
wosilusheng/bookcrossing
08eda403b5852e70ed09204490d9e3e33e38fb0b
ad1d30177b52a8c59c5d3bb162faa8a2d3d9e2be
refs/heads/master
<repo_name>Asplomer/FPSMobile<file_sep>/FPSmobileS/Assets/Scripts/Extras/Follower2.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class Follower2 : MonoBehaviour { public float speed = 1.8f; public Transform Target; public float timerBomber =3.0f; public float timer; public GameObject bomb; // Use this for initialization void Start () { timer = 0.0f; } // Update is called once per frame void Update () { if (timer != 0.0f) { timer = timer + Time.deltaTime; } // Debug.Log (timer); Vector3 pos1 = this.transform.position; Vector3 pos2 = Target.position; Vector3 dir = pos2 - pos1; dir.y = 0.0f; dir.Normalize (); transform.rotation = Quaternion.LookRotation (dir); pos1 += speed * Time.deltaTime * transform.forward; transform.position = pos1; if (pos1.x + 3.0f > pos2.x && timer >= 0.0f) { Instantiate (bomb, transform.position, transform.rotation); timer -= timerBomber; } } } <file_sep>/FPSmobileS/Assets/Scripts/Extras/CameraFollower.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFollower : MonoBehaviour { public Transform Target; // Use this for initialization void Start () { } // Update is called once per frame void Update () { Vector3 posPlayer= Target.position; transform.position = posPlayer; posPlayer.Normalize (); transform.rotation = Quaternion.LookRotation (Target.forward); } } <file_sep>/FPSmobileS/Assets/Scripts/FoeScriptA.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class FoeScriptA : MonoBehaviour { public int EnemyHealth; //i need a way to check for an impact with a spell or player void Start () { } // Update is called once per frame void Update () { if (EnemyHealth <= 0) { gameObject.GetComponent<Spawner> ().foeCount--; Destroy (gameObject); } //Debug.Log(EnemyHealth); } } <file_sep>/FPSmobileS/Assets/Scripts/PlayerShoot.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class PlayerShoot : MonoBehaviour { public GameObject bulletPrefab; public Transform bulletSpawn; // Use this for initialization void Update () { /* if (!isLocalPlayer) { return; }*/ var x = Input.GetAxis ("Horizontal") * Time.deltaTime * 150.0f; var z = Input.GetAxis ("Vertical") * Time.deltaTime * 3.0f; transform.Rotate (0, x, 0); transform.Rotate (0, 0, z); if (Input.GetKey ("Fire1")) { Fire (); } } // Update is called once per frame void Fire () { var bullet = (GameObject)Instantiate( bulletPrefab, bulletSpawn.position, bulletSpawn.rotation); bullet.GetComponent<Rigidbody> ().velocity = bullet.transform.forward * 6; Destroy (bullet, 2.0f); } }<file_sep>/FPSmobileS/Assets/Scripts/Extras/MyShip.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class MyShip : MonoBehaviour { public float Accel = 1.0f; public float RotSpeed = 5.0f; Vector3 speed = Vector3.zero; // Use this for initialization void Start () { } // Update is called once per frame void Update () { Vector3 pos = this.transform.position; if (Input.GetKey (KeyCode.RightArrow)) { this.transform.rotation *= Quaternion.AngleAxis (-RotSpeed * Time.deltaTime, Vector3.forward); } if (Input.GetKey (KeyCode.LeftArrow)) { this.transform.rotation *= Quaternion.AngleAxis (RotSpeed * Time.deltaTime, Vector3.forward); } if (Input.GetKey (KeyCode.UpArrow)) { speed += this.transform.up * Accel * Time.deltaTime; } pos += speed * Time.deltaTime; this.transform.position = pos; } } <file_sep>/FPSmobileS/Assets/Scripts/OnHitBehaviour.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class OnHitBehaviour : MonoBehaviour { private float duration; public float lifetime; // Use this for initialization void Start () { duration = 0.0f; } // Update is called once per frame void Update () { duration = duration + Time.deltaTime; if (duration >= lifetime) { Destroy (gameObject); } } } <file_sep>/FPSmobileS/Assets/Scripts/BombExplosion.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class BombExplosion : MonoBehaviour { private float duration; public float lifetime; public GameObject player; private bool notHit; Vector3 vec ; Vector3 bomb ; // Use this for initialization void Start () { duration = 0.0f; notHit = true; vec= player.transform.position; bomb = this.transform.position; } void OnTriggerEnter(Collider collider){ if (collider.tag == "Player" || notHit) { //collider.gameObject.GetComponent<PlayerHealth> ().Health -= 1; notHit = false; } } // Update is called once per frame void Update () { duration = duration + Time.deltaTime; if (duration >= lifetime) { Destroy (gameObject); } } } <file_sep>/FPSmobileS/Assets/Scripts/Spawner.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawner : MonoBehaviour { public int foeCount; public int MaxFoe; public float timer; private Vector3 SpawnArea; void Start () { foeCount = 2; MaxFoe = 2; // Random.InitState(); } public void Spawn(GameObject Creature, Vector3 Area){ Instantiate (Creature, this.transform.position, this.transform.rotation); foeCount++; } // Update is called once per frame void Update () {/* if(foeCount !=MaxFoe){ SpawnArea = Random.insideUnitSphere; transform.position.Set (SpawnArea.x, 0.0f, SpawnArea.z); }*/ } } <file_sep>/FPSmobileS/Assets/Scripts/ShootCasting.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class ShootCasting : MonoBehaviour { public GameObject bulletPrefab; public GameObject bulletPrefab2; public Transform tipWandF; public Transform tipWandR; public Transform tipWandL; // Update is called once per frame void Update () { if (Input.GetButtonDown("Fire1")) { SimpleSpell(); } if (Input.GetButtonDown("Fire2")){ SpreadSpell(); } } void SimpleSpell(){ Instantiate(bulletPrefab, tipWandF.position, tipWandF.rotation); } void SpreadSpell(){ Instantiate(bulletPrefab2, tipWandF.position, tipWandF.rotation); Instantiate(bulletPrefab2, tipWandL.position, tipWandL.rotation); Instantiate(bulletPrefab2, tipWandR.position, tipWandR.rotation); } /* void SimpleSpell(){ Instantiate(bulletPrefab, tipWandF.position, tipWandF.rotation); } */ }<file_sep>/FPSmobileS/Assets/Scripts/PlayerHealth.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerHealth : MonoBehaviour { public int Health; private float iframes; private bool hit; //i need a way to check for an impact with a spell or player void Start () { iframes = 0f; hit = false; } void OnTriggerEnter(Collider collider){ if ((collider.tag == "Enemy")&& !hit) { Health--; hit = true; } if ((collider.tag == "EBullet")&& !hit) { Health-=3; hit = true; } } // Update is called once per frame void Update () { if (iframes >= 1.0f && hit) { hit = false; iframes = 0.0f; } if (iframes != 1.0f && hit) { iframes = iframes + Time.deltaTime; } Debug.Log(iframes); if (Health <= 0) { Destroy (gameObject); UnityEngine.SceneManagement.SceneManager.LoadScene ("TitleScreen"); } // Debug.Log(Health); } } <file_sep>/FPSmobileS/Assets/Scripts/bomb.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class bomb : MonoBehaviour { public float boltSpeed; private float duration; public float lifetimeBullet; public GameObject onHit; void Start(){ duration = 0.0f; } void OnTriggerEnter(Collider collider){ if ((collider.tag == "Floor" || collider.tag == "Player")) { Instantiate (onHit, transform.position, transform.rotation); Destroy (gameObject); } } void Update () { if(this.tag =="EBullet"){ transform.Translate(Vector3.down* boltSpeed); } duration = duration + Time.deltaTime; if (duration >= lifetimeBullet) { Destroy (gameObject); } } } <file_sep>/FPSmobileS/Assets/Scripts/HealthBar.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class HealthBar : MonoBehaviour { public GameObject Bar1; public GameObject Bar2; public GameObject Bar3; public GameObject Bar4; public GameObject Bar5; public GameObject player; void Update () { if((player.gameObject.GetComponent<PlayerHealth>().Health) <= 8) Destroy (Bar1); if((player.gameObject.GetComponent<PlayerHealth>().Health) <= 6) Destroy (Bar2); if((player.gameObject.GetComponent<PlayerHealth>().Health) <= 4) Destroy (Bar3); if((player.gameObject.GetComponent<PlayerHealth>().Health) <= 2) Destroy (Bar4); if((player.gameObject.GetComponent<PlayerHealth>().Health) <= 0) Destroy (Bar5); } }
8744b7ad7f0270f6db12054720f9446ca1470595
[ "C#" ]
12
C#
Asplomer/FPSMobile
c760a7ed45a30f218b167733505509847344ae2f
f7d239a48b69c506a68493681a736d6ed72d6cda
refs/heads/master
<repo_name>RoolApps/YetAnotherFindPair<file_sep>/gridcontroller.cpp #include "gridcontroller.h" /*ctor*/ GridController::GridController(Item object) : IQmlComponentController(object){ } /*dtor*/ GridController::~GridController(){ clear(); } /*private*/ bool GridController::checkIfSolved(){ for(int row = 0; row < c_gridArray2d.size(); row++){ for(int col = 0; col < c_gridArray2d.at(row).size(); col++){ if (c_gridArray2d.at(row).at(col)->canRotate()) { return false; } } } return true; } void GridController::clear(){ for(int row = 0; row < c_gridArray2d.size(); row++){ for(int col = 0; col < c_gridArray2d.at(row).size(); col++){ CellController * cell = c_gridArray2d.at(row).at(col); if(cell->type() != Game::CellType::Transparent) { disconnect(cell, SIGNAL(cellClicked(CellController*)), this, SLOT(cellClicked(CellController*))); disconnect(cell, SIGNAL(cellRotationStopped(CellController*)), this, SLOT(cellRotationStopped(CellController*))); } } } c_hints.clear(); for(GridArray2d::iterator array = c_gridArray2d.begin(); array != c_gridArray2d.end(); ++array){ for(GridArray::iterator it = array->begin(); it != array->end(); ++it){ delete *it; *it = nullptr; } array->clear(); } c_gridArray2d.clear(); while(!c_qmlObject->childItems().empty()){ Item item = c_qmlObject->childItems().takeFirst(); delete item; item = nullptr; } } CellController * GridController::createCellController(int size) const{ Item cell = Game::createQmlObject("CppCell"); cell->setParent(c_qmlObject); cell->setParentItem(c_qmlObject); cell->setWidth(size); cell->setHeight(size); return new CellController(cell); } CellController * GridController::atIndex(Index index){ return c_gridArray2d.at(index.r).at(index.c); } int GridController::calculateCellSize() const { int rows = read(qmlObject(), "rows").toInt(); int columns = read(qmlObject(), "columns").toInt(); int spacing = read(qmlObject(), "spacing").toInt(); int width = read(qobject_cast<Item>(qmlObject()->parent()), "width").toInt() - (spacing * columns); int height = read(qobject_cast<Item>(qmlObject()->parent()), "height").toInt() - (spacing * rows); int size = qMin(width / columns, height / rows); return size - (size * .2); } /*public*/ void GridController::loadLevel(Level &level, bool shuffle){ clear(); c_hints = level.hints(); write(c_qmlObject, "rows", level.rows()); write(c_qmlObject, "columns", level.columns()); this->rows = level.rows(); this->columns = level.columns(); this->difficulty = level.difficulty(); if(shuffle) level.shuffle(); int cellSize = calculateCellSize(); for(int row = 0; row < level.rows(); row++){ GridArray gridArray; for(int col = 0; col < level.columns(); col++){ int type = level.hints().at(row * level.columns() + col).toInt(); CellController *cellController = createCellController(cellSize); cellController->setType(static_cast<Game::CellType>(type)); if (type == Game::CellType::Transparent) { cellController->setCanRotate(false); } else { connect(cellController, SIGNAL(cellClicked(CellController*)), this, SLOT(cellClicked(CellController*))); connect(cellController, SIGNAL(cellRotationStopped(CellController*)), this, SLOT(cellRotationStopped(CellController*))); } gridArray.append(cellController); } c_gridArray2d.append(gridArray); } levelReady(); } Index GridController::getIndex(CellController * controller) { for(int row = 0; row < c_gridArray2d.size(); row++){ for(int col = 0; col < c_gridArray2d.at(row).size(); col++){ CellController * cell = c_gridArray2d.at(row).at(col); if(cell == controller) { return Index(row, col); } } } return Index(); } /*private slot*/ void GridController::cellClicked(CellController * controller) { if (firstCell != NULL && secondCell != NULL) { return; } if (firstCell == controller || secondCell == controller) { return; } if (!controller->canRotate()) { return; } emit makeMoveSound(); if (firstCell == NULL) { firstCell = controller; } else { secondCell = controller; } controller->rotate(); } void GridController::cellRotationStopped(CellController * controller) { if (firstCell == NULL || secondCell == NULL) { return; } if (secondCell != controller) { return; } if(firstCell->type() == secondCell->type()) { firstCell->setCanRotate(false); secondCell->setCanRotate(false); } else { firstCell->rotate(); secondCell->rotate(); } if(checkIfSolved()) { firstCell = NULL; secondCell = NULL; emit solved(); return; } moveCells(); } void GridController::shiftCells(GridArray * cells, int chunkSize) { Index * indices = new Index[cells->size()]; GridArray * newCells = new GridArray(); int itemsProcessed = 0; int chunksProcessed = 0; int offset = randomBool() ? 1 : -1; for(int cellIndex=0;cellIndex<cells->size();cellIndex++) { int sourceCellIndex = cellIndex + offset; if (sourceCellIndex == chunksProcessed * chunkSize - 1) { sourceCellIndex = (chunksProcessed + 1) * chunkSize - 1; } if (sourceCellIndex == (chunksProcessed + 1) * chunkSize) { sourceCellIndex = chunksProcessed * chunkSize; } indices[cellIndex] = getIndex(cells->at(sourceCellIndex)); newCells->append(cells->at(sourceCellIndex)); itemsProcessed++; if(itemsProcessed==chunkSize) { chunksProcessed++; itemsProcessed=0; offset = randomBool() ? 1 : -1; } } GridArray * movedCells = new GridArray(); for(int cellIndex=0;cellIndex<cells->size();cellIndex++) { QMetaObject::Connection * connection = new QMetaObject::Connection(); *connection = QObject::connect(cells->at(cellIndex), &CellController::cellMovementStopped, [movedCells, cells, newCells, indices, connection, this](CellController * controller) { QObject::disconnect(*connection); delete connection; movedCells->append(controller); if(std::equal(cells->begin(), cells->end(), movedCells->begin())) { delete indices; delete newCells; delete cells; delete movedCells; this->firstCell = NULL; this->secondCell = NULL; } }); Index index = indices[cellIndex]; c_gridArray2d[index.r][index.c] = cells->at(cellIndex); cells->at(cellIndex)->setPosition(newCells->at(cellIndex)->getPosition()); } } void GridController::moveCells() { bool moveRow = randomBool(); int length = moveRow ? this->columns : this->rows; QVector<int> vector = QVector<int>(); int vectorLength = moveRow ? this->rows : this->columns; for(int i=0;i<vectorLength;i++) { vector.append(i); } std::random_shuffle(vector.begin(), vector.end()); GridArray * cells = new GridArray(); for(int move=0;move<this->difficulty;move++) { for(int cell=0;cell<length;cell++) { if(moveRow) { cells->append(c_gridArray2d.at(vector.at(move)).at(cell)); } else { cells->append(c_gridArray2d.at(cell).at(vector.at(move))); } } } shiftCells(cells, length); } /*public virtual*/ void GridController::info() const{ return IQmlComponentController::info(); } <file_sep>/main.cpp #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QQmlEngine> #include <QSettings> #include "QtAdMob/QtAdMobBanner.h" #include "QtAdMob/QtAdMobInterstitial.h" #include "game.h" #include "level.h" #include "settings.h" #include "gameplane.h" #include "gameresult.h" QString appPath; int main(int argc, char *argv[]){ QGuiApplication app(argc, argv); appPath = app.applicationDirPath(); app.setOrganizationName(GAME_ORGANIZATION); app.setApplicationName(GAME_NAME); QmlAdMobBanner::DeclareQML(); QmlAdMobInterstitial::DeclareQML(); qmlRegisterType<Game>("CppItems", 0, 1, "Game"); qmlRegisterType<GamePlane>("CppItems", 0, 1, "GamePlane"); qmlRegisterType<Level>("CppItems", 0, 1, "Level"); qmlRegisterType<GameResult>("CppItems", 0, 1, "GameResult"); QQmlApplicationEngine engine; Game::setEngine(&engine); Settings settings; engine.rootContext()->setContextProperty("applicationPath", appPath); engine.rootContext()->setContextProperty("applicationSettings", &settings); engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); } <file_sep>/gameresult.cpp #include "gameresult.h" /*ctor*/ GameResult::GameResult(QObject *parent) : QObject(parent), c_levelId(0), c_moves(0){ } /*public*/ int GameResult::levelId() const{ return c_levelId; } void GameResult::setLevelId(int id){ if(c_levelId != id){ c_levelId = id; emit levelIdChanged(); } } int GameResult::moves() const{ return c_moves; } void GameResult::setMoves(int moves){ if(c_moves != moves){ c_moves = moves; emit movesChanged(); } } QString GameResult::time() const{ return c_time; } void GameResult::setTime(QString time){ if(c_time != time){ c_time = time; emit timeChanged(); } } <file_sep>/settings.cpp #include "settings.h" /*ctor*/ Settings::Settings(QObject *parent) : QSettings("app.ini", QSettings::IniFormat, parent){ if(!contains("settingsInitialized")){ setValue("settingsInitialized", true); // Levels beginWriteArray("levels"); for(int id = 0; id < GAME_LEVELS_COUNT; id++){ setArrayIndex(id); setValue("id", id); setValue("open", false); } endArray(); setValue("levels/1/open", true); // Sound beginGroup("sound"); setValue("backgroundMusic", true); setValue("slideEffectSound", true); endGroup(); // Timer setValue("timer", false); } } /*public INVOKABLE*/ void Settings::print() const{ dbg << "SETTINGS:"; dbg << value("settingsInitialized").toBool(); dbg << value("levels/size"); } int Settings::levelId(int id) const{ QString val = QString("levels/%1/id").arg(++id); return value(val).toInt(); } bool Settings::levelOpened(int id) const{ QString val = QString("levels/%1/open").arg(++id); return value(val).toBool(); } void Settings::setLevelOpened(int id, bool state){ QString target = QString("levels/%1/open").arg(++id); setValue(target, state); emit levelStateChanged(id, state); } int Settings::levelsCount() const{ return value("levels/size").toInt(); } bool Settings::backgroundMusic() const{ return value("sound/backgroundMusic").toBool(); } void Settings::setBackgroundMusic(bool state){ setValue("sound/backgroundMusic", state); emit backgroundMusicStateChanged(state); } bool Settings::slideEffectSound() const{ return value("sound/slideEffectSound").toBool(); } void Settings::setSlideEffectSound(bool state){ setValue("sound/slideEffectSound", state); emit slideEffectSoundStateChanged(state); } bool Settings::timer() const{ return value("timer").toBool(); } void Settings::setTimer(bool state){ setValue("timer", state); emit timerStateChanged(state); } <file_sep>/cellcontroller.h #ifndef CELLCONTROLLER_H #define CELLCONTROLLER_H #include "game.h" #include "iqmlcomponentcontroller.h" #include <QPoint> class CellController : public QObject, public IQmlComponentController{ Q_OBJECT private: bool c_canRotate = true; Game::CellType c_type; bool flipped(); public: explicit CellController(Item = nullptr); public: bool canRotate(); Game::CellType type() const; void setType(Game::CellType); void moveLeft(int); void moveRight(int); void moveUp(int); void moveDown(int); QPoint getPosition(); void setPosition(QPoint); void rotate(); void setCanRotate(bool); public: virtual void info() const; private slots: void onAnimationStopped(); void onClicked(); void onRotationStopped(); signals: void cellClicked(CellController *); void cellRotationStopped(CellController *); void cellMovementStopped(CellController *); }; #endif // CELLCONTROLLER_H <file_sep>/gridcontroller.h #ifndef GRIDCONTROLLER_H #define GRIDCONTROLLER_H #include <QObject> #include <QScreen> #include <QGuiApplication> #include "game.h" #include "utils.h" #include "level.h" #include "cellcontroller.h" class GridController : public QObject, public IQmlComponentController{ Q_OBJECT private: typedef QVector<CellController *> GridArray; typedef QVector<GridArray> GridArray2d; int difficulty; int columns; int rows; private: GridArray2d c_gridArray2d; QVariantList c_hints; CellController * firstCell = NULL; CellController * secondCell = NULL; public: GridController(Item = nullptr); ~GridController(); private: void clear(); bool checkIfSolved(); Index cellIndex(Game::CellType) const; CellController * createCellController(int = 100) const; CellController * atIndex(Index); int calculateCellSize() const; Index getIndex(CellController *); void moveCells(); void shiftCells(GridArray * cells, int chunkSize); private slots: void cellClicked(CellController *); void cellRotationStopped(CellController * controller); public: void loadLevel(Level &, bool = false); public: virtual void info() const; signals: void levelReady(); void solved(); void makeMoveSound(); }; #endif // GRIDCONTROLLER_H <file_sep>/gameplane.cpp #include "gameplane.h" #include <QTime> #include "settings.h" extern QString appPath; /*ctor*/ GamePlane::GamePlane(QQuickItem *parent) : QQuickItem(parent), c_movesCounter(0), c_foregroundGridController(nullptr), c_foregroundGrid(nullptr), c_backgroundGrid(nullptr), c_currentLevel(nullptr){ c_tickTimer.setInterval(1000); connect(&c_tickTimer, SIGNAL(timeout()), this, SLOT(timerTick())); c_tickTimer.start(); } GamePlane::~GamePlane(){ delete c_foregroundGridController; } /*private*/ void GamePlane::makeSoundEffect(){ c_movesCounter++; emit soundEffect(); } QQuickItem * GamePlane::foregroundGrid() const{ return c_foregroundGrid; } QQuickItem * GamePlane::backgroundGrid() const{ return c_backgroundGrid; } void GamePlane::setForegroundGrid(QQuickItem *grid){ delete c_foregroundGridController; c_foregroundGrid = grid; c_foregroundGrid->setParent(this); c_foregroundGrid->setParentItem(this); c_foregroundGridController = new GridController(c_foregroundGrid); connect(c_foregroundGridController, &GridController::solved, this, &GamePlane::openNewLevel); connect(c_foregroundGridController, &GridController::makeMoveSound, this, &GamePlane::makeSoundEffect); if(c_backgroundGrid != nullptr) { connect(c_foregroundGrid, SIGNAL(heightChanged()), this, SLOT(foregroundGridHeightChanged())); } } void GamePlane::foregroundGridHeightChanged() { if(c_foregroundGrid!=nullptr) { c_backgroundGrid->setHeight(c_foregroundGrid->height() + c_magicNumber); c_backgroundGrid->setWidth(c_foregroundGrid->width() + c_magicNumber); } } void GamePlane::setBackgroundGrid(QQuickItem * grid){ c_backgroundGrid = grid; c_backgroundGrid->setParent(this); c_backgroundGrid->setParentItem(this); if(c_foregroundGrid != nullptr) { foregroundGridHeightChanged(); connect(c_foregroundGrid, SIGNAL(heightChanged()), this, SLOT(foregroundGridHeightChanged())); } } /*public Q_INVOKABLE*/ void GamePlane::restartLevel(){ loadLevel(c_currentLevel); } QVariantList GamePlane::generateHints(int rows, int columns) { int types = rows * columns / 2; const QMetaObject *metaObject = qt_getEnumMetaObject(Game::CellType()); const char *name = qt_getEnumName(Game::CellType()); QMetaEnum cellType = metaObject->enumerator(metaObject->indexOfEnumerator(name)); int length = cellType.keyCount(); QVector<int> vector = QVector<int>(); for(int i=0;i<length;i++) { if((int)Game::CellType::Transparent != i) { vector.append(i); } } std::random_shuffle(vector.begin(), vector.end()); QVariantList hints = QVariantList(); for(int i=0;i<types;i++) { hints.append(QVariant(vector.at(i))); hints.append(QVariant(vector.at(i))); } if (types * 2 != rows * columns) { hints.append(QVariant((int)Game::CellType::Transparent)); } std::random_shuffle(hints.begin(), hints.end()); return hints; } void GamePlane::loadLevel(Level *level){ if(c_currentLevel != nullptr) { } c_currentLevel = level; c_movesCounter = 0; if(c_foregroundGrid) { Level foregroundLevel(*level); QVariantList foregroundHints = generateHints(level->rows(), level->columns()); foregroundLevel.setHints(foregroundHints); c_foregroundGridController->loadLevel(foregroundLevel, true); foregroundGridHeightChanged(); c_timer.start(); secondsElapsed = -1; timerTick(); } } void GamePlane::timerTick() { secondsElapsed++; QTime time = QTime(0, secondsElapsed / 60, secondsElapsed % 60); emit secondTick(time.toString("mm:ss")); } /*public slots*/ void GamePlane::openNewLevel(){ Settings settings; int newLevelId = c_currentLevel->levelId() + 1; if(newLevelId < settings.levelsCount()) settings.setLevelOpened(newLevelId, true); GameResult result; result.setLevelId(newLevelId); result.setMoves(c_movesCounter); result.setTime(QTime::fromMSecsSinceStartOfDay(c_timer.elapsed()).toString("mm:ss")); emit newLevelOpened(&result); } <file_sep>/gameplane.h #ifndef GAMEPLANE_H #define GAMEPLANE_H #include <QQuickItem> #include <QQmlProperty> #include <QSoundEffect> #include <QElapsedTimer> #include <QTimer> #include "game.h" #include "level.h" #include "gridcontroller.h" #include "gameresult.h" class GamePlane : public QQuickItem { Q_OBJECT Q_PROPERTY(QQuickItem * foregroundGrid READ foregroundGrid WRITE setForegroundGrid) Q_PROPERTY(QQuickItem * backgroundGrid READ backgroundGrid WRITE setBackgroundGrid) private: int c_magicNumber = 50; int c_movesCounter; int secondsElapsed = 0; QElapsedTimer c_timer; QTimer c_tickTimer; GridController *c_foregroundGridController; QQuickItem *c_foregroundGrid; QQuickItem *c_backgroundGrid; Level *c_currentLevel; public: explicit GamePlane(QQuickItem * = 0); ~GamePlane(); private: void makeSoundEffect(); QVariantList generateHints(int, int); private slots: void foregroundGridHeightChanged(); void timerTick(); public: Q_INVOKABLE void restartLevel(); Q_INVOKABLE void loadLevel(Level *); public: QQuickItem * backgroundGrid() const; QQuickItem * foregroundGrid() const; void setForegroundGrid(QQuickItem *); void setBackgroundGrid(QQuickItem *); signals: void newLevelOpened(GameResult *result); void soundEffect(); void secondTick(QString); public slots: void openNewLevel(); }; #endif // GAMEPLANE_H <file_sep>/level.cpp #include "level.h" #include <ctime> /*ctor*/ Level::Level(QObject *parent) : QObject(parent), c_levelId(0), c_rows(0), c_columns(0), c_difficulty(0){ srand(time(NULL)); } Level::Level(Level const &level) : QObject(nullptr){ *this = level; } Level & Level::operator=(Level const &level){ if(this == &level) return *this; c_levelId = level.c_levelId; c_rows = level.c_rows; c_columns = level.c_columns; c_difficulty = level.c_difficulty; c_hints = level.c_hints; return *this; } /*public*/ int Level::levelId() const{ return c_levelId; } void Level::setLevelId(int id){ if(c_levelId != id){ c_levelId = id; emit levelIdChanged(); } } int Level::rows() const{ return c_rows; } void Level::setRows(int rows){ if(c_rows != rows){ c_rows = rows; emit rowsChanged(); } } int Level::columns() const{ return c_columns; } void Level::setColumns(int columns){ if(c_columns != columns){ c_columns = columns; emit columnsChanged(); } } int Level::difficulty() const{ return c_difficulty; } void Level::setDifficulty(int difficulty){ if(c_difficulty != difficulty){ c_difficulty = difficulty; emit difficultyChanged(); } } QList<QVariant> Level::hints() const{ return c_hints; } void Level::setHints(QList<QVariant> &list){ if(c_hints != list){ c_hints = list; emit hintsChanged(); } } void Level::shuffle(){ // Index previousStep; // for(int steps = 0; steps < static_cast<int>(c_difficulty * 10);){ // int row = empty / c_columns; // int col = empty % c_columns; // Index indexes[] = {Index(0, -1), Index(0, 1), Index(-1, 0), Index(1, 0)}; // Index step = indexes[rand() % (sizeof(indexes) / sizeof(*indexes))]; // if( (step == indexes[Game::Left] && previousStep == indexes[Game::Right]) || // (step == indexes[Game::Right] && previousStep == indexes[Game::Left]) || // (step == indexes[Game::Up] && previousStep == indexes[Game::Down]) || // (step == indexes[Game::Down] && previousStep == indexes[Game::Up])) continue; // Index move(row + step.r, col + step.c); // if(move.isValid(c_rows, c_columns)){ // previousStep = step; // int index = move.r * c_columns + move.c; // std::swap(c_hints[empty], c_hints[index]); // empty = index; // steps++; // } // } } <file_sep>/iqmlcomponentcontroller.cpp #include "iqmlcomponentcontroller.h" /*ctor*/ IQmlComponentController::IQmlComponentController(Item object) : c_qmlObject(object){ } /*public*/ Item IQmlComponentController::qmlObject() const{ return c_qmlObject; } void IQmlComponentController::setQmlObject(Item object){ if(c_qmlObject != object){ c_qmlObject = object; } } QVariant IQmlComponentController::read(Item item, QString property) const{ return QQmlProperty::read(item, property); } void IQmlComponentController::write(Item item, QString property, QVariant value){ QQmlProperty::write(item, property, value); } /*public virtual*/ void IQmlComponentController::info() const{ dbg << "INFO:" << c_qmlObject; dbg << "Parent INFO" << c_qmlObject->parent(); dbg << "ParentItem INFO" << c_qmlObject->parentItem(); dbg << "Childrens count: " << c_qmlObject->children().length() << "childItems count:" << c_qmlObject->childItems().size(); dbg << "Childrens: " << c_qmlObject->children(); dbg << "ChildItems: " << c_qmlObject->childItems(); dbg << " --------------------- "; } <file_sep>/iqmlcomponentcontroller.h #ifndef IQMLCOMPONENTCONTROLLER_H #define IQMLCOMPONENTCONTROLLER_H #include <QQuickItem> #include <QQmlProperty> #include "game.h" typedef QQuickItem * Item; class IQmlComponentController{ protected: Item c_qmlObject; public: explicit IQmlComponentController(Item = nullptr); public: Item qmlObject() const; void setQmlObject(Item); QVariant read(Item, QString) const; void write(Item, QString, QVariant); public: virtual void info() const; }; #endif // IQMLCOMPONENTCONTROLLER_H <file_sep>/level.h #ifndef LEVEL_H #define LEVEL_H #include <QQuickItem> #include "game.h" /* * 0 - Empty * 1 - Red triangle * 2 - Red rectangle * 3 - Red circle */ class Level : public QObject{ Q_OBJECT Q_PROPERTY(int levelId READ levelId WRITE setLevelId NOTIFY levelIdChanged) Q_PROPERTY(int rows READ rows WRITE setRows NOTIFY rowsChanged) Q_PROPERTY(int columns READ columns WRITE setColumns NOTIFY columnsChanged) Q_PROPERTY(int difficulty READ difficulty WRITE setDifficulty NOTIFY difficultyChanged) Q_PROPERTY(QVariantList hints READ hints WRITE setHints NOTIFY hintsChanged) private: int c_levelId; int c_rows; int c_columns; int c_difficulty; QVariantList c_hints; public: Level(QObject * = nullptr); Level(Level const &); Level & operator=(Level const &); public: int levelId() const; void setLevelId(int); int rows() const; void setRows(int); int columns() const; void setColumns(int); int difficulty() const; void setDifficulty(int); QVariantList hints() const; void setHints(QVariantList &); void shuffle(); signals: void levelIdChanged(); void rowsChanged(); void columnsChanged(); void difficultyChanged(); void hintsChanged(); public slots: }; #endif // LEVEL_H <file_sep>/cellcontroller.cpp #include "cellcontroller.h" extern QString appPath; /*ctor*/ CellController::CellController(Item object) : IQmlComponentController(object) { connect(c_qmlObject, SIGNAL(animationStopped()), this, SLOT(onAnimationStopped())); connect(c_qmlObject, SIGNAL(clicked()), this, SLOT(onClicked())); connect(c_qmlObject, SIGNAL(rotationStopped()), this, SLOT(onRotationStopped())); } /*public*/ bool CellController::canRotate() { return c_canRotate; } void CellController::setCanRotate(bool canRotate) { c_canRotate = canRotate; } bool CellController::flipped() { return read(c_qmlObject, "flipped").toBool(); } Game::CellType CellController::type() const { return c_type; } void CellController::setType(Game::CellType type) { write(c_qmlObject, "source", Game::fullImagePath(type)); write(c_qmlObject, "frontSource", Game::fullFrontImagePath(type)); c_type = type; } QPoint CellController::getPosition() { return QPoint(read(c_qmlObject, "x").toInt(), read(c_qmlObject, "y").toInt()); } void CellController::setPosition(QPoint point) { write(c_qmlObject, "x", point.x()); write(c_qmlObject, "y", point.y()); } /*public virtual*/ void CellController::info() const { return IQmlComponentController::info(); } /*private slots*/ void CellController::onAnimationStopped() { cellMovementStopped(this); } void CellController::onRotationStopped() { if(flipped()) { cellRotationStopped(this); } } void CellController::rotate() { write(c_qmlObject, "flipped", !flipped()); } void CellController::onClicked() { cellClicked(this); } <file_sep>/game.cpp #include "game.h" QQmlEngine * Game::c_engine = nullptr; /*ctor*/ Game::Game(QObject *parent) : QObject(parent){ } /*public*/ QQmlEngine * Game::engine(){ return Game::c_engine; } void Game::setEngine(QQmlEngine *engine){ if(Game::c_engine != engine){ Game::c_engine = engine; } } QQuickItem * Game::createQmlObject(QString const name){ QQmlComponent component(Game::engine(), QUrl("qrc:/qml/Cpp/" + name + ".qml")); QQuickItem * qmlComponent = qobject_cast<QQuickItem *>(component.create()); return qmlComponent; } QString Game::cellTypeAsString(CellType type){ QString stype = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("CellType")).valueToKey(type); return stype; } QString Game::fullImagePath(CellType type){ if (type == Game::CellType::Transparent) { return QString("qrc:/assets/svg/Icons/_Transparent.svg"); } else { return QString("qrc:/assets/svg/Icons/" + cellTypeAsString(type) + ".svg"); } } QString Game::fullFrontImagePath(CellType type){ if (type == Game::CellType::Transparent) { return QString("qrc:/assets/svg/Icons/_Transparent.svg"); } else { return QString("qrc:/assets/svg/Icons/_Hidden.svg"); } } <file_sep>/game.h #ifndef GAME_H #define GAME_H #include <QObject> #include <QQuickItem> #include <QQmlEngine> #include "utils.h" #define GAME_ORGANIZATION "ROOL APPS" #define GAME_NAME "Yet Another Find Pair" #define GAME_LEVELS_COUNT 35 class Game : public QObject { Q_OBJECT Q_PROPERTY(QQmlEngine * engine READ engine WRITE setEngine) public: enum MoveDirection {Left, Right, Up, Down}; enum CellType { Transparent, Bug, Flower, Pepper, Apple, Ball, Bird, Bagel, Cactus, Cat, Cloud, Cup, Cupcake, Diamond, Eye, Feather, Icecream, Leaf, Mushroom, Peach, Pizza, Plant, Soda, Sun, Tree, Turtle, Umbrella, Candle, Candy, Glasses, Bulb, Medusa, Pawprint, Shell, Strawberry, Bear }; Q_ENUM(MoveDirection) Q_ENUM(CellType) private: static QQmlEngine *c_engine; public: Game(QObject * = 0); public: static QQmlEngine * engine(); static void setEngine(QQmlEngine *); static QQuickItem * createQmlObject(QString const); static QString cellTypeAsString(CellType); static QString fullImagePath(CellType); static QString fullFrontImagePath(CellType); signals: public slots: }; #endif // GAMELOGIC_H <file_sep>/Utils.js function percent(p, value){ return (value * p) / 100; } <file_sep>/settings.h #ifndef SETTINGS_H #define SETTINGS_H #include <QObject> #include <QSettings> #include "game.h" class Settings : public QSettings{ Q_OBJECT public: explicit Settings(QObject * = nullptr); public: Q_INVOKABLE void print() const; Q_INVOKABLE int levelId(int) const; Q_INVOKABLE bool levelOpened(int) const; Q_INVOKABLE void setLevelOpened(int, bool); Q_INVOKABLE int levelsCount() const; Q_INVOKABLE bool backgroundMusic() const; Q_INVOKABLE void setBackgroundMusic(bool); Q_INVOKABLE bool slideEffectSound() const; Q_INVOKABLE void setSlideEffectSound(bool); Q_INVOKABLE bool timer() const; Q_INVOKABLE void setTimer(bool); signals: void levelStateChanged(int, bool); void backgroundMusicStateChanged(bool); void slideEffectSoundStateChanged(bool); void timerStateChanged(bool); }; #endif // SETTINGS_H <file_sep>/utils.h #ifndef UTILS_H #define UTILS_H #include <QDebug> #include <QRandomGenerator> #define dbg qDebug() struct Index { int r; int c; Index(int row = -1, int col = -1) : r(row), c(col) {} bool operator==(Index other){ return r == other.r && c == other.c; } bool operator!=(Index other){ return !(*this == other); } bool isValid(int maxRow, int maxCol){ return r >= 0 && r < maxRow && c >= 0 && c < maxCol; } void print(){ qDebug() << "row:" << r << ", col:" << c; } }; inline bool randomBool() { return QRandomGenerator::global()->generate() % 2 == 0; } #endif // UTILS_H <file_sep>/gameresult.h #ifndef GAMERESULT_H #define GAMERESULT_H #include "game.h" class GameResult : public QObject { Q_OBJECT Q_PROPERTY(int levelId READ levelId WRITE setLevelId NOTIFY levelIdChanged) Q_PROPERTY(int moves READ moves WRITE setMoves NOTIFY movesChanged) Q_PROPERTY(QString time READ time WRITE setTime NOTIFY timeChanged) private: int c_levelId; int c_moves; QString c_time; public: explicit GameResult(QObject *parent = nullptr); public: int levelId() const; void setLevelId(int); int moves() const; void setMoves(int); QString time() const; void setTime(QString); signals: void levelIdChanged(); void movesChanged(); void timeChanged(); public slots: }; #endif // GAMERESULT_H
1bf952fb6d764052d9375be74b17c2d8c4fc06c4
[ "JavaScript", "C", "C++" ]
19
C++
RoolApps/YetAnotherFindPair
1caa6e9bd3d75048a8f3bfcbdc624514a4b2e053
dc781e6f34bff3bde7bcd6f9d9796159567ac9ac
refs/heads/master
<file_sep># Simple Electron Chat App This is just a demo of a basic chat app using Electron and React. The server is included and must be run using Node.js ## Tiny features * You provide a username to enter a chat room. Server endpoint is configurable. * Supports Markdown. * List of connected users. * Informs connection and disconnection events. * Informs when someone is typing. * Supports multiple instances * Message notification. ## To Use To clone and run this repository you'll need [Git](https://git-scm.com) and [Node.js](https://nodejs.org/en/download/) (which comes with [npm](http://npmjs.com)) installed on your computer. From your command line: ```bash # Clone this repository git clone https://github.com/demian85/electron-chat-app-demo.git # Go into the repository cd electron-chat-app-demo # Install dependencies npm install # Run local server npm run server # Run the app npm start ``` If you want to test the app using multiple instances, remember you should only have one instance of the chat server running! ## Create distributable package ``` npm install -g electron-packager cd electron-chat-app-demo electron-packager . --asar ``` You will now have a folder for your platform and you can run the app by executing `electron-chat-app-demo` Learn more about Electron and its API in the [documentation](http://electron.atom.io/docs/latest). <file_sep>/* eslint-env browser, node */ /* global React */ const notifier = require('node-notifier'); const marked = require('marked'); const mainWindow = require('electron').remote.getGlobal('mainWindow'); let typing = false; let typingTimer; var currentUser; document.addEventListener('DOMContentLoaded', function onLoad() { const app = React.createElement(App); ReactDOM.render(app, document.body); }); class App extends React.Component { constructor(props) { super(props); this.state = { username: '', url: '', users: [], messages: [], status: '' }; this.onLogin = this.onLogin.bind(this); this.onInput = this.onInput.bind(this); this.onSend = this.onSend.bind(this); } initSocket(url) { this.setState({ status: 'Connecting...' }); const socket = io.connect(url); socket.on('connect', () => { this.appendMessage(`Connected to server ${this.state.url}`); this.setState({ status: '' }); }); socket.on('message', data => { this.appendMessage(`__${data.username}:__ ${data.text}`); if (data.username != currentUser) { notifier.notify({ 'title': 'Electron Chat DEMO (' + currentUser + ')', 'message': `${data.username}: ${data.text}`, wait: true }, function (err, noData) { console.log('waited'); }).on('click', function () { console.log('Clicked'); mainWindow.show(); mainWindow.focus(); }); } }); socket.on('login', data => { this.appendMessage(`${data.username} has logged in.`); this.setState({ users: data.users }); if (data.username != currentUser) { notifier.notify({ 'title': 'Electron Chat DEMO (' + currentUser + ')', 'message': `${data.username} has logged in.`, wait: true }, function (err, noData) { console.log('Waited'); console.log(err, noData); }).on('click', function () { console.log('Clicked'); }); } }); socket.on('typing', data => { this.setState({ status: `${data.username} is typing...` }); }); socket.on('stop-typing', () => { this.setState({ status: '' }); }); socket.on('logout', data => { this.appendMessage(`${data.username} disconnected.`); this.setState({ users: data.users }); if (data.username != currentUser) { notifier.notify({ 'title': 'Electron Chat DEMO (' + currentUser + ')', 'message': `${data.username} disconnected.` }).on('click', function () { mainWindow.show(); mainWindow.focus(); }); } }); this.socket = socket; } appendMessage(message) { this.setState((prev, props) => { const messages = prev.messages; messages.push(message); return { messages }; }); } onLogin(url, username) { this.setState({ url, username }); this.initSocket(url); this.socket.emit('login', { username }); this.refs.inputBar.focus(); } onInput(text) { const username = this.state.username; if (!typing) { typing = true; this.socket.emit('typing', { username }); } if (typingTimer) { clearTimeout(typingTimer); typingTimer = null; } typingTimer = setTimeout(() => { typing = false; this.socket.emit('stop-typing', { username }); }, 1000); } onSend(text) { const username = this.state.username; this.socket.emit('message', { username, text }); } componentDidMount() { this.refs.loginBox.focus(); } render() { return React.createElement( 'main', null, React.createElement(LoginBox, { ref: 'loginBox', url: 'http://chat.triplez.cn:3010', onLogin: this.onLogin }), React.createElement( 'div', { className: 'content' }, React.createElement(UserList, { users: this.state.users }), React.createElement(ChatArea, { messages: this.state.messages, status: this.state.status }) ), React.createElement(InputBar, { ref: 'inputBar', onInput: this.onInput, onSend: this.onSend }) ); } } class LoginBox extends React.Component { constructor(props) { super(props); this.onKeyDown = this.onKeyDown.bind(this); } focus() { this.refs.username.focus(); } onKeyDown(e) { if (e.keyCode === 13) { const value = this.refs.username.value.trim(); const url = this.refs.url.value.trim(); if (value) { this.props.onLogin(url, value); this.refs.root.classList.add('hidden'); } currentUser = value; document.title = 'Electron Chat DEMO (' + value + ')'; } } render() { return React.createElement( 'div', { id: 'login-box', ref: 'root' }, React.createElement( 'div', null, React.createElement( 'h2', null, 'Login' ), React.createElement('input', { type: 'url', id: 'server-url', ref: 'url', value: this.props.url }), React.createElement('input', { type: 'text', placeholder: 'enter username', id: 'username', ref: 'username', onKeyDown: this.onKeyDown, autofocus: true }) ) ); } } class UserList extends React.Component { render() { const opts = { sanitize: true }; const users = this.props.users.map(user => React.createElement('li', { dangerouslySetInnerHTML: { __html: marked(user, opts) } })); return React.createElement( 'aside', null, React.createElement( 'h3', null, 'Connected Users' ), React.createElement( 'ul', { id: 'users' }, users ), React.createElement( 'div', { id: 'user-stats' }, users.length, ' users online.' ) ); } } class ChatArea extends React.Component { render() { const opts = { sanitize: true }; const text = this.props.messages.map(msg => `${marked(msg, opts)}\n`).join(''); return React.createElement( 'div', { id: 'chat' }, React.createElement('div', { id: 'chat-text', dangerouslySetInnerHTML: { __html: text } }), React.createElement( 'div', { id: 'chat-status-msg' }, this.props.status ) ); } } class InputBar extends React.Component { constructor(props) { super(props); this.onKeyDown = this.onKeyDown.bind(this); this.onInput = this.onInput.bind(this); this.onClick = this.onClick.bind(this); } onKeyDown(e) { if (e.keyCode === 13) { this.send(); } } onInput() { const value = this.refs.input.value.trim(); this.props.onInput(value); } onClick() { this.send(); } send() { const value = this.refs.input.value.trim(); if (value) { this.props.onSend(value); this.refs.input.value = ''; // Should I mutate state instead? } } focus() { this.refs.input.focus(); } render() { return React.createElement( 'div', { className: 'input' }, React.createElement('input', { type: 'text', id: 'text-input', ref: 'input', placeholder: 'say something...', onInput: this.onInput, onKeyDown: this.onKeyDown }), React.createElement( 'a', { id: 'send-btn', className: 'waves-effect waves-light btn', onClick: this.onClick }, 'Send' ) ); } }<file_sep>/* eslint-env browser, node */ /* global React */ const notifier = require('node-notifier'); const marked = require('marked'); const mainWindow = require('electron').remote.getGlobal('mainWindow'); let typing = false; let typingTimer; var currentUser; document.addEventListener('DOMContentLoaded', function onLoad() { const app = React.createElement(App); ReactDOM.render(app, document.body); }); class App extends React.Component { constructor(props) { super(props); this.state = { username: '', url: '', users: [], messages: [], status: '', }; this.onLogin = this.onLogin.bind(this); this.onInput = this.onInput.bind(this); this.onSend = this.onSend.bind(this); } initSocket(url) { this.setState({status: 'Connecting...'}); const socket = io.connect(url); socket.on('connect', () => { this.appendMessage(`Connected to server ${this.state.url}`); this.setState({status: ''}); }); socket.on('message', (data) => { this.appendMessage(`__${data.username}:__ ${data.text}`); if (data.username != currentUser) { notifier.notify({ 'title': 'Electron Chat DEMO (' + currentUser + ')', 'message': `${data.username}: ${data.text}`, wait: true, }, function (err, noData) { console.log('waited'); }).on('click', function () { console.log('Clicked'); mainWindow.show(); mainWindow.focus(); }); } }); socket.on('login', (data) => { this.appendMessage(`${data.username} has logged in.`); this.setState({users: data.users}); if (data.username != currentUser) { notifier.notify({ 'title': 'Electron Chat DEMO (' + currentUser + ')', 'message': `${data.username} has logged in.`, wait: true, }, function (err, noData) { console.log('Waited'); console.log(err, noData); }).on('click', function () { console.log('Clicked'); }); } }); socket.on('typing', (data) => { this.setState({status: `${data.username} is typing...`}); }); socket.on('stop-typing', () => { this.setState({status: ''}); }); socket.on('logout', (data) => { this.appendMessage(`${data.username} disconnected.`); this.setState({users: data.users}); if (data.username != currentUser) { notifier.notify({ 'title': 'Electron Chat DEMO (' + currentUser + ')', 'message': `${data.username} disconnected.`, }).on('click', function () { mainWindow.show(); mainWindow.focus(); }); } }); this.socket = socket; } appendMessage(message) { this.setState((prev, props) => { const messages = prev.messages; messages.push(message); return { messages }; }); } onLogin(url, username) { this.setState({url, username}); this.initSocket(url); this.socket.emit('login', { username }); this.refs.inputBar.focus(); } onInput(text) { const username = this.state.username; if (!typing) { typing = true; this.socket.emit('typing', { username }); } if (typingTimer) { clearTimeout(typingTimer); typingTimer = null; } typingTimer = setTimeout(() => { typing = false; this.socket.emit('stop-typing', { username }); }, 1000); } onSend(text) { const username = this.state.username; this.socket.emit('message', { username, text }); } componentDidMount() { this.refs.loginBox.focus(); } render() { return ( <main> <LoginBox ref="loginBox" url="http://chat.triplez.cn:3010" onLogin={this.onLogin} /> <div className="content"> <UserList users={this.state.users} /> <ChatArea messages={this.state.messages} status={this.state.status} /> </div> <InputBar ref="inputBar" onInput={this.onInput} onSend={this.onSend} /> </main> ); } } class LoginBox extends React.Component { constructor(props) { super(props); this.onKeyDown = this.onKeyDown.bind(this); } focus() { this.refs.username.focus(); } onKeyDown(e) { if (e.keyCode === 13) { const value = this.refs.username.value.trim(); const url = this.refs.url.value.trim(); if (value) { this.props.onLogin(url, value); this.refs.root.classList.add('hidden'); } currentUser = value; document.title = 'Electron Chat DEMO (' + value + ')'; } } render() { return ( <div id="login-box" ref="root"> <div> <h2>Login</h2> <input type="url" id="server-url" ref="url" value={this.props.url} /> <input type="text" placeholder="enter username" id="username" ref="username" onKeyDown={this.onKeyDown} autofocus /> </div> </div> ); } } class UserList extends React.Component { render() { const opts = { sanitize: true }; const users = this.props.users.map(user => <li dangerouslySetInnerHTML={{__html: marked(user, opts)}}></li>) return ( <aside> <h3>Connected Users</h3> <ul id="users">{users}</ul> <div id="user-stats">{users.length} users online.</div> </aside> ); } } class ChatArea extends React.Component { render() { const opts = { sanitize: true }; const text = this.props.messages.map(msg => `${marked(msg, opts)}\n`).join(''); return ( <div id="chat"> <div id="chat-text" dangerouslySetInnerHTML={{__html: text}}></div> <div id="chat-status-msg">{this.props.status}</div> </div> ); } } class InputBar extends React.Component { constructor(props) { super(props); this.onKeyDown = this.onKeyDown.bind(this); this.onInput = this.onInput.bind(this); this.onClick = this.onClick.bind(this); } onKeyDown(e) { if (e.keyCode === 13) { this.send(); } } onInput() { const value = this.refs.input.value.trim(); this.props.onInput(value); } onClick() { this.send(); } send() { const value = this.refs.input.value.trim(); if (value) { this.props.onSend(value); this.refs.input.value = ''; // Should I mutate state instead? } } focus() { this.refs.input.focus(); } render() { return ( <div className="input"> <input type="text" id="text-input" ref="input" placeholder="say something..." onInput={this.onInput} onKeyDown={this.onKeyDown} /> <a id="send-btn" className="waves-effect waves-light btn" onClick={this.onClick}>Send</a> </div> ); } } <file_sep>module.exports = { "extends": "airbnb", "rules": { "no-use-before-define": 0, "prefer-arrow-callback": 0, "func-names": 0, "no-console": 0, "react/no-string-refs": 0, "react/no-multi-comp": 0 }, "globals": { "io": true, "React": true, "ReactDOM": true, "mainWindow": true, } };
9d8602ddab4ceaa2f148dfe09d0c3c3c3a899a08
[ "Markdown", "JavaScript" ]
4
Markdown
Triple-Z/Eletron_Chat_DEMO
9140da2314bffebd40f43cf54d5c93b3aa215299
c0093ea2cc6bb0dfb0bf5938ed49cdd876a89e97
refs/heads/master
<file_sep>DataPostTimeSchema = Dry::Validation.Form(ApplicationSchema) do DATE_REGEX = /\A([0-2][\d]):([0-5][\d])\s([0-3][\d])\.([0-1][\d])\z/ configure do def is_date?(value) !DATE_REGEX.match(value).nil? end def auto_date?(value) %w(end beginning).any? { |d| d == value } end end required(:value) { filled? & (is_date? | auto_date?) } end <file_sep>GC::Profiler.enable if Rails.env.production? <file_sep>RSpec.configure do |config| config.include ActiveJob::TestHelper, type: :job ActiveJob::Base.queue_adapter = :test end <file_sep>require 'rails_helper' RSpec.describe TimeData, type: :model do subject { FactoryGirl.build(:time_data) } it { should validate_presence_of(:value) } it { should validate_uniqueness_of(:value) } end <file_sep>RSpec.configure do |config| config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec\/api/ config.include ActiveModelSerializers::Test::Schema, file_path: /spec\/controllers\/api/ end <file_sep>module Constraints class ApiConstraint ACCEPT_BASE = 'application/vnd.apisvc.v'.freeze attr_reader :version attr_reader :default def initialize(options) @version = options.fetch(:version) @default = options.fetch(:default) end def matches?(request) acc = accept(request) if acc&.include?(ACCEPT_BASE) acc.include?("#{ACCEPT_BASE}#{@version}") else default end end private def accept(request) request.headers['Accept'] end end end <file_sep>require 'rails_helper' RSpec.describe TimeHelpers do describe '#prepare_time_value' do it 'returns with end of day' do date = described_class.prepare_time_value('end') expect(date.zone).to eq('UTC') expect(date.hour).to eq(23) expect(date.min).to eq(59) end it 'returns with beginning of the day' do date = described_class.prepare_time_value('beginning') expect(date.zone).to eq('UTC') expect(date.hour).to eq(0) expect(date.min).to eq(0) end it 'returns parsed date' do date = described_class.prepare_time_value('10:33 11.11') expect(date.zone).to eq('UTC') expect(date.hour).to eq(10) expect(date.min).to eq(33) expect(date.day).to eq(11) expect(date.month).to eq(11) end it 'returns nil' do date = described_class.prepare_time_value('44:33 11.11') expect(date).to be_nil end end describe '#time_zone_by_offset' do it 'returns Moscow' do expect(described_class.time_zone_by_offset(3)).to eq('Europe/Athens') end it 'returns UTC' do expect(described_class.time_zone_by_offset(0)).to eq('Atlantic/Azores') end it 'returns UTC' do expect(described_class.time_zone_by_offset(5)).to eq('Asia/Yekaterinburg') end end end <file_sep>require 'shoulda-matchers' module ShouldaMatchersFixDeprecation def matches?(controller) @controller = controller ensure_action_and_verb_present! parameters_double_registry.register Doublespeak.with_doubles_activated do context.__send__(verb, action, params: request_params) end unpermitted_parameter_names.empty? end end Shoulda::Matchers::ActionController::PermitMatcher.send(:include, ShouldaMatchersFixDeprecation) Shoulda::Matchers.configure do |config| config.integrate do |with| with.test_framework :rspec # Choose one or more libraries: # with.library :active_record # with.library :active_model # with.library :action_controller # Or, choose the following (which implies all of the above): with.library :rails end end <file_sep>ifndef SERVER SERVER = production endif migrate: bundle exec rails db:create db:migrate seed: bundle exec rails db:seed doc_v1: rails api:v1:schema <file_sep>class TimeDataSerializer < ApplicationSerializer cache key: 'time_data', expires_in: 3.hours attributes :value end <file_sep>require 'rails_helper' RSpec.describe 'Data V1', type: :request do describe 'v1 GET /data' do it 'returns http success' do build(:time_data) get '/data', params: {}, headers: { 'accept' => 'application/vnd.apisvc.v1' }, as: :json expect(response).to have_http_status(200) end it 'fallback by default' do build(:time_data) get '/data', params: {}, as: :json expect(response).to have_http_status(200) end end describe 'v2 GET /data' do it 'returns 404' do build(:time_data) expect do get '/data', params: {}, headers: { 'accept' => 'application/vnd.apisvc.v2' }, as: :json end.to raise_exception(ActionController::RoutingError) end end describe 'v0 GET /data' do it 'returns 404' do build(:time_data) expect do get '/data', params: {}, headers: { 'accept' => 'application/vnd.apisvc.v0' }, as: :json end.to raise_exception(ActionController::RoutingError) end end end <file_sep>require 'rails_helper' RSpec.describe LocationUpdateJob, type: :job do let(:valid_location_attributes) do { type: 'location', name: 'eee', latitude: 55.000, longitude: 44.0000, timezone: '-03:00' } end let(:invalid_location_attributes) do { name: 'eee', latitude: 'dfdd', longitude: 'dfdd', timezone: 444 } end it 'with enqueued job' do expect do LocationUpdateJob.perform_later(DataPostLocationSchema.call(valid_location_attributes).output) end.to have_enqueued_job end it 'with success job' do expect do LocationUpdateJob.perform_now(DataPostLocationSchema.call(valid_location_attributes).output) end.to change(LocationData, :count).by(1) end it 'with failed job' do expect do LocationUpdateJob.perform_now(DataPostLocationSchema.call(invalid_location_attributes).output) end.not_to change(LocationData, :count) end end <file_sep>DataPostSchema = Dry::Validation.Form(ApplicationSchema) do configure do def location_or_time?(value) %w(location time).any? { |lt| lt == value } end end required(:type) { filled? & str? & location_or_time? } end <file_sep>## ApiSvc Ruby Backend ### ะะฐะฟะธัะฐั‚ัŒ ัะตั€ะฒะธั ั API. ะกะตั€ะฒะธั ะดะพะปะถะตะฝ ะธะผะตั‚ัŒ ะพะดะธะฝ endpoint ะธ ะฟั€ะตะดะพัั‚ะฐะฒะปัั‚ัŒ ะฒะพะทะผะพะถะฝะพัั‚ัŒ ะฒะตั€ัะธะพะฝะธั€ะพะฒะฐะฝะธั (ะฒะตั€ัะธั ัƒะบะฐะทั‹ะฒะฐะตั‚ัั ะฒ header'e ะทะฐะฟั€ะพัะฐ). Url endpoint'a - '/data'. ### ะ’ะตั€ัะธะพะฝะธั€ะพะฒะฐะฝะธะต ะŸะตั€ะตะดะฐั‡ะฐ ะฒะตั€ัะธะธ ะพััƒั‰ะตัั‚ะฒะปัะตั‚ัั ะฟั€ะธ ะฟะพะผะพั‰ะธ ะทะฐะณะพะปะพะฒะบะฐ `Accept`, ะฝะฐะฟั€ะธะผะตั€: `application/vnd.apisvc.v1` ะ’ ัะปัƒั‡ะฐะต ะพั‚ััƒั‚ัั‚ะฒะธั ะทะฐะณะพะปะพะฒะบะฐ ะธัะฟะพะปัŒะทัƒะตั‚ัั ะฒะตั€ัะธั ะฟะพ-ัƒะผะพะปั‡ะฐะฝะธัŽ. ### ะŸั€ะฐะฒะธะปะฐ ะœะตั‚ะพะด | ะŸัƒั‚ัŒ | ะขะธะฟ (ะฟะฐั€ะฐะผะตั‚ั€ `type`) | ะžะฑัะทะฐั‚ะตะปัŒะฝั‹ะต ะฟะฐั€ะฐะผะตั‚ั€ั‹ | ะ”ะพะฟ. ะฟะฐั€ะฐะผะตั‚ั€ั‹ | :----------------|:------------------|:-------| :-------------------- | :----------- | `POST` | `/data` | location | latitude `double`, longitude `double`, name `string` | timezone `-04:00` | `POST` | `/data` | time | value `15:30 11.09` UTC, `end`, `beginning` | - | `GET` | `/data` | - | - | timezone `string` | ### Setup # Install gems $ bundle install # Setup DB $ make migrate # Seed into DB $ make seed # Run project! $ bin/rails s ### Dependencies: - Ruby 2.3+ - Rails 5.0 - PostgreSQL - Memcached - Puma #### Few words about: - This project is a little API app. #### Post ะทะฐะฟั€ะพั: ะžะฑัะทะฐั‚ะตะปัŒะฝั‹ะน ะฟะฐั€ะฐะผะตั‚ั€ - type. ะœะพะถะตั‚ ะฟั€ะธะฝะธะผะฐั‚ัŒ ะดะฒะฐ ะทะฝะฐั‡ะตะฝะธั: - 'time' - 'location'. ##### ะ•ัะปะธ ะฟะฐั€ะฐะผะตั‚ั€ 'time', ะพะฑัะทะฐั‚ะตะปัŒะฝั‹ะน ะฟะฐั€ะฐะผะตั‚ั€: - 'value' (datetime) ะบะพั‚ะพั€ั‹ะน ะผะพะถะตั‚ ะฟั€ะธะฝะธะผะฐั‚ัŒ ะทะฝะฐั‡ะตะฝะธั ะฒ ั„ะพั€ะผะฐั‚ะต: - 'hour:minutes day.month' (19:25 13.11) - 'end' (ะบะพะฝะตั† ั‚ะตะบัƒั‰ะตะณะพ ะดะฝั 23:59) - 'beginning' (ะฝะฐั‡ะฐะปะพ ั‚ะตะบัƒั‰ะตะณะพ ะดะฝั 00:00) ##### ะ’ ัะปัƒั‡ะฐะต 'location', ะพะฑัะทะฐั‚ะตะปัŒะฝั‹ ั‚ั€ะธ ะฟะฐั€ะฐะผะตั‚ั€ะฐ: - 'latitude' (double, 4 ะทะฝ ะฟะพัะปะต ั‚ะพั‡ะบะธ) - 'longitude' (double) - 'name' (string) - ะฝะตะพะฑัะทะฐั‚ะตะปัŒะฝั‹ะน 'timezone' (ะฒะธะดะฐ '-04:00') ะŸะพะปัƒั‡ะตะฝะฝั‹ะต ะดะฐะฝะฝั‹ะต ัะพั…ั€ะฐะฝััŽั‚ัั ะฒ ะฑะด. ะ’ั€ะตะผั ะพั‚ะดะตะปัŒะฝะพ, ะปะพะบะฐั†ะธะธ ะพั‚ะดะตะปัŒะฝะพ. #### Get ะทะฐะฟั€ะพั: ะ•ะดะธะฝัั‚ะฒะตะฝะฝั‹ะน query ะฟะฐั€ะฐะผะตั‚ั€ 'timezone' ะดะพะปะถะตะฝ ัƒะบะฐะทั‹ะฒะฐั‚ัŒ ะฝะฐ 'name' ะพะดะฝะพะณะพ ะธะท ั…ั€ะฐะฝะธะผั‹ั… 'location'. Endpoint ะดะพะปะถะตะฝ ะฒะพะทะฒั€ะฐั‰ะฐั‚ัŒ ัะฟะธัะพะบ ั…ั€ะฐะฝะธะผั‹ั… 'time' ะดะปั ัƒะบะฐะทะฐะฝะฝะพะน timezone. ะ’ ัะปัƒั‡ะฐะต ะพั‚ััƒั‚ัั‚ะฒะธั query ะฟะฐั€ะฐะผะตั‚ั€ะฐ, ะปะธะฑะพ ะฟัƒัั‚ะพะณะพ ะฟะพะปั 'timezone' ะดะปั ัƒะบะฐะทะฐะฝะฝะพะณะพ 'location', ะฒะพะทะฒั€ะฐั‰ะฐั‚ัŒ ะฒ utc. ะ˜ัะฟะพะปัŒะทะพะฒะฐั‚ัŒ JSON API ั„ะพั€ะผะฐั‚ ะพั‚ะฒะตั‚ะพะฒ. ะ”ะพะฑะฐะฒะธั‚ัŒ ะพัˆะธะฑะบะธ ะฟะพ ัะฒะพะตะผัƒ ัƒัะผะพั‚ั€ะตะฝะธัŽ. ะŸะพะบั€ั‹ั‚ัŒ ะบะพะด ั‚ะตัั‚ะฐะผะธ. ะฃะบะฐะทะฐั‚ัŒ ะธัะฟะพะปัŒะทัƒะตะผัƒัŽ database ะธ web server. ะกะตั€ะฒะธั ะดะพะปะถะตะฝ ะฑั‹ั‚ัŒ ั€ะฐััั‡ะธั‚ะฐะฝ ะฝะฐ ัั€ะตะดะฝะต-ะฒั‹ัะพะบัƒัŽ ะฝะฐะณั€ัƒะทะบัƒ. Copyright (c) 2016 <NAME> MIT License <file_sep>module ErrorHandler extend ActiveSupport::Concern included do rescue_from ActiveRecord::RecordNotFound, with: :error rescue_from Exception, with: :error rescue_from ActionController::RoutingError, with: :error end def raise_not_found raise ActionController::RoutingError, "No route matches #{params[:unmatched_route]}" end private def error(e) return if performed? fetch_exception(e) error_from_response(e) end def error_from_response(e) self.response_body = nil message = Rails.env.development? || Rails.env.test? ? "#{e&.class.name} : #{e&.message}" : e&.message error_info = { error: @rescue_response, message: message } unless Rails.env.production? Rails.logger.error e e&.backtrace[0, 10].each { |l| Rails.logger.error l } end error_info[:trace] = e&.backtrace[0, 10] if Rails.env.development? render json: error_info.to_json, status: @status_code end def fetch_exception(e) @status_code = ActionDispatch::ExceptionWrapper.new(request.env, e).status_code @rescue_response = ActionDispatch::ExceptionWrapper.rescue_responses[e&.class.name] end end <file_sep>ActiveModelSerializers.config.adapter = :json_api ActiveModelSerializers.config.schema_path = 'spec/support/schemas' <file_sep>source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '5.0.0.1' # Use postgresql as the database for Active Record gem 'pg', '~> 0.18' # Use Puma as the app server gem 'puma' # API gem 'active_model_serializers', github: 'rails-api/active_model_serializers' # gem 'foreman', require: false # Validate gem 'dry-validation', '~> 0.10.0' # JSON gem 'oj' gem 'oj_mimic_json' # Logs gem 'lograge' # Protection gem 'rack-protection' gem 'rack-attack' gem 'rack-cors' gem 'rack-timeout', require: 'rack/timeout/base' # Cache gem 'dalli' group :development, :test do gem 'ruby-debug-ide' gem 'debase' gem 'factory_girl_rails', '~> 4.5' gem 'rubocop', require: false gem 'brakeman', require: false # Call 'byebug' anywhere in the code to stop execution and get a debugger console # gem 'byebug' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' gem 'spring-commands-rspec' gem 'coveralls' gem 'rspec-rails', '~> 3.5.0' end gem 'json_schema' group :development do gem 'listen', '~> 3.0.5' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring-watcher-listen', '~> 2.0.0' end group :test do gem 'database_cleaner' gem 'shoulda-matchers', '3.1.1', require: false gem 'rails-controller-testing', require: false end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] <file_sep>class LocationData < ApplicationRecord validates :name, uniqueness: true, presence: true validates :latitude, presence: true, numericality: true validates :longitude, presence: true, numericality: true end <file_sep>-- -- PostgreSQL database dump -- -- Dumped from database version 9.5.4 -- Dumped by pg_dump version 9.5.4 SET statement_timeout = 0; SET lock_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SET check_function_bodies = false; SET client_min_messages = warning; SET row_security = off; -- -- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: - -- CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog; -- -- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: - -- COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language'; SET search_path = public, pg_catalog; SET default_tablespace = ''; SET default_with_oids = false; -- -- Name: ar_internal_metadata; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE ar_internal_metadata ( key character varying NOT NULL, value character varying, created_at timestamp without time zone NOT NULL, updated_at timestamp without time zone NOT NULL ); -- -- Name: location_data; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE location_data ( id integer NOT NULL, latitude numeric(30,4) NOT NULL, longitude numeric(30,10) NOT NULL, name character varying DEFAULT ''::character varying NOT NULL, timezone character varying DEFAULT 'Etc/UTC'::character varying ); -- -- Name: location_data_id_seq; Type: SEQUENCE; Schema: public; Owner: - -- CREATE SEQUENCE location_data_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; -- -- Name: location_data_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - -- ALTER SEQUENCE location_data_id_seq OWNED BY location_data.id; -- -- Name: schema_migrations; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE schema_migrations ( version character varying NOT NULL ); -- -- Name: time_data; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE time_data ( id integer NOT NULL, value timestamp without time zone NOT NULL ); -- -- Name: time_data_id_seq; Type: SEQUENCE; Schema: public; Owner: - -- CREATE SEQUENCE time_data_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; -- -- Name: time_data_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - -- ALTER SEQUENCE time_data_id_seq OWNED BY time_data.id; -- -- Name: id; Type: DEFAULT; Schema: public; Owner: - -- ALTER TABLE ONLY location_data ALTER COLUMN id SET DEFAULT nextval('location_data_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: - -- ALTER TABLE ONLY time_data ALTER COLUMN id SET DEFAULT nextval('time_data_id_seq'::regclass); -- -- Name: ar_internal_metadata_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY ar_internal_metadata ADD CONSTRAINT ar_internal_metadata_pkey PRIMARY KEY (key); -- -- Name: location_data_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY location_data ADD CONSTRAINT location_data_pkey PRIMARY KEY (id); -- -- Name: schema_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY schema_migrations ADD CONSTRAINT schema_migrations_pkey PRIMARY KEY (version); -- -- Name: time_data_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY time_data ADD CONSTRAINT time_data_pkey PRIMARY KEY (id); -- -- Name: index_location_data_on_name; Type: INDEX; Schema: public; Owner: - -- CREATE UNIQUE INDEX index_location_data_on_name ON location_data USING btree (name); -- -- Name: index_time_data_on_value; Type: INDEX; Schema: public; Owner: - -- CREATE UNIQUE INDEX index_time_data_on_value ON time_data USING btree (value); -- -- PostgreSQL database dump complete -- SET search_path TO "$user", public; INSERT INTO schema_migrations (version) VALUES ('20160921191155'), ('20160921191157'); <file_sep>DataGetSchema = Dry::Validation.Form(ApplicationSchema) do optional(:timezone).maybe(:str?) end <file_sep>class WelcomeController < ActionController::API def index render body: 'Welcome to the roots!' end end <file_sep>DataPostLocationSchema = Dry::Validation.Form(ApplicationSchema) do required(:latitude).filled(:float?) required(:longitude).filled(:float?) required(:name).maybe(:str?) optional(:timezone).maybe(:str?) end <file_sep>class TimeData < ApplicationRecord validates :value, uniqueness: true, presence: true end <file_sep>Rails.application.config.middleware.insert 0, Rack::Attack if Rails.env.production? Rails.application.config.middleware.insert_before Rack::Runtime, Rack::Timeout Rack::Timeout.timeout = 10 # seconds end Rails.application.config.middleware.insert_after Rack::Cors, Rack::Protection, except: [:remote_token, :session_hijacking] <file_sep>module TimeHelpers def self.prepare_time_value(value) case value when 'end' Time.zone.now.end_of_day when 'beginning' Time.zone.now.beginning_of_day else begin Time.zone.strptime(value, '%H:%M %d.%m') rescue => _e nil end end end def self.time_zone_by_offset(offset) ActiveSupport::TimeZone.all.detect do |zone| t = Time.current.in_time_zone(zone) (t.utc_offset / 3600) == offset end&.tzinfo&.name || 'Etc/UTC' end end <file_sep>TimeData.create((1..20).map { |_| { value: Time.current.utc } }) LocationData.create(latitude: 55.0000, longitude: 44.0000, name: 'test', timezone: 'Asia/Yekaterinburg') <file_sep>require 'rails_helper' RSpec.describe Api::V1::DataController, type: :controller do include_context 'api_v1' include ActiveJob::TestHelper let(:valid_post_attributes) do { type: 'location' } end let(:invalid_post_attributes) do { type: 'eee' } end let(:valid_location_attributes) do { type: 'location', name: 'eee', latitude: 55.000, longitude: 44.0000, timezone: '-03:00' } end let(:valid_time_attributes) do { type: 'time', value: '19:24 11.11' } end let(:valid_time_end_attributes) do { type: 'time', value: 'end' } end let(:valid_time_beginning_attributes) do { type: 'time', value: 'beginning' } end let(:invalid_time_attributes) do { type: 'time', value: '19:24 11.aa' } end let(:invalid_location_attributes) do { type: 'location', name: 'eee', latitude: 'dfdd', longitude: 'dfdd', timezone: 444 } end let(:valid_attributes) do { timezone: 'some' } end let(:invalid_attributes) do { timezone: 444 } end let(:valid_session) { {} } describe 'GET #index' do it 'assigns all times as @times within timezone' do create(:location_data, name: 'some', timezone: 'Europe/Moscow') time_data = create(:time_data) get :index, params: valid_attributes, session: valid_session expect(response).to have_http_status(:success) expect(assigns(:times)).to eq([time_data]) expect(assigns(:location)).to be_a(LocationData) assert_response_schema('data/get.json') expect(JSON.parse(response.body)['data'][0]['attributes']['value']).to include('.000+03:00') end it 'assigns all times as @times with utc' do time_data = create(:time_data) get :index, params: valid_attributes, session: valid_session expect(response).to have_http_status(:success) expect(assigns(:times)).to eq([time_data]) expect(assigns(:location)).to be_nil assert_response_schema('data/get.json') expect(JSON.parse(response.body)['data'][0]['attributes']['value']).to include('.000Z') end it 'returns empty array' do get :index, params: invalid_attributes, session: valid_session expect(response).to have_http_status(:success) expect(assigns(:times)).to eq([]) assert_response_schema('data/get.json') end end describe 'POST #create' do context 'time' do context 'with valid params' do it 'creates a new TimeData' do expect do post :create, params: valid_time_attributes, session: valid_session end.to change(TimeData, :count).by(1) expect(response).to have_http_status(200) assert_response_schema('data/post.json') end it 'creates a new TimeData for end of the day' do expect do post :create, params: valid_time_end_attributes, session: valid_session end.to change(TimeData, :count).by(1) expect(response).to have_http_status(200) assert_response_schema('data/post.json') end it 'creates a new TimeData for beginning of the day' do expect do post :create, params: valid_time_beginning_attributes, session: valid_session end.to change(TimeData, :count).by(1) expect(response).to have_http_status(200) assert_response_schema('data/post.json') end it 'assigns a newly created time_data as @time_data' do post :create, params: valid_time_attributes, session: valid_session expect(response).to have_http_status(200) expect(assigns(:time_data)).to be_a(TimeData) expect(assigns(:time_data)).to be_persisted expect(assigns(:time_data).value.time_zone.name).to eq('UTC') assert_response_schema('data/post.json') end end context 'with invalid params' do it 'unsaved time_data as @time_data' do post :create, params: invalid_time_attributes, session: valid_session expect(response).to have_http_status(422) expect(assigns(:time_data)).to be_a(TimeData) expect(JSON.parse(response.body)['errors'].keys).to eq(['value']) assert_response_schema('data/error.json') end it 'error 422 on invalid hours format' do post :create, params: { type: 'time', value: '55:24 11.11' }, session: valid_session expect(response).to have_http_status(422) expect(assigns(:time_data)).to be_a(TimeData) expect(JSON.parse(response.body)['errors'].keys).to eq(['value']) assert_response_schema('data/error.json') end it 'error 422 on invalid month format' do post :create, params: { type: 'time', value: '15:24 11.15' }, session: valid_session expect(response).to have_http_status(422) expect(assigns(:time_data)).to be_a(TimeData) expect(JSON.parse(response.body)['errors'].keys).to eq(['value']) assert_response_schema('data/error.json') end it 'error 422 on valid but wrong time format' do post :create, params: { type: 'time', value: '25:24 11.11' }, session: valid_session expect(response).to have_http_status(422) expect(assigns(:time_data)).to be_a(TimeData) expect(JSON.parse(response.body)['errors'].keys).to eq(['value']) assert_response_schema('data/error.json') end end end context 'location' do context 'with valid params' do it 'creates a new LocationData' do expect do post :create, params: valid_location_attributes, session: valid_session end.to have_enqueued_job(LocationUpdateJob) expect(response).to have_http_status(200) assert_response_schema('data/post.json') end end context 'with invalid params' do it 'unsaved time_data as @time_data' do post :create, params: invalid_location_attributes, session: valid_session expect(response).to have_http_status(422) expect(JSON.parse(response.body)['errors'].keys).to eq(%w(latitude longitude)) assert_response_schema('data/error.json') end end end context 'with valid type params' do it 'creates a new TimeData' do post :create, params: valid_post_attributes, session: valid_session expect(response).to have_http_status(422) assert_response_schema('data/error.json') expect(JSON.parse(response.body)['errors'].keys).not_to include('type') end end context 'with invalid type params' do it 'assigns a newly created but unsaved post as @post' do post :create, params: invalid_post_attributes, session: valid_session expect(response).to have_http_status(422) expect(JSON.parse(response.body)['errors'].keys).to include('type') assert_response_schema('data/error.json') end end end end <file_sep>require 'spec_helper' RSpec.shared_context 'api_v1' do # let(:schema_url_prefix) { '/data' } before :each do request.headers.merge!('Accept' => 'application/vnd.apisvc.v1') end end <file_sep>class LocationUpdateJob < ApplicationJob queue_as :default def perform(data) LocationData.where(name: data[:name]).first_or_initialize.tap do |location| data[:timezone] = TimeHelpers.time_zone_by_offset(data[:timezone].to_i) location.attributes = data location.save end end end <file_sep>RSpec.configure do |config| config.use_transactional_fixtures = false config.before(:example) do DatabaseCleaner.strategy = if RSpec.current_example.metadata[:js] :truncation else :transaction end ActiveRecord::Base.connection.increment_open_transactions if ActiveRecord::Base.connection.open_transactions < 0 DatabaseCleaner.start unless RSpec.current_example.metadata[:nodb] end config.before(:example, type: :feature) do # :rack_test driver's Rack app under test shares database connection # with the specs, so we can use transaction strategy for speed. driver_shares_db_connection_with_specs = Capybara.current_driver == :rack_test DatabaseCleaner.strategy = if driver_shares_db_connection_with_specs :transaction else # Non-:rack_test driver is probably a driver for a JavaScript browser # with a Rack app under test that does *not* share a database # connection with the specs, so we must use truncation strategy. :truncation end end config.after(:example) do DatabaseCleaner.clean unless RSpec.current_example.metadata[:nodb] end end <file_sep>class CreateTableTimeData < ActiveRecord::Migration[5.0] def up create_table :time_data do |t| t.datetime :value, null: false end add_index :time_data, :value, unique: true end def down drop_table :time_data end end <file_sep>FactoryGirl.define do factory :time_data do value Time.zone.parse('2015-08-27T12:09:36Z') end end <file_sep>module Api module V1 class DataController < ApplicationController before_action :set_location, only: [:index] def index if index_params.success? Time.use_zone(@location&.timezone || 'Etc/UTC') do @times = TimeData.all render json: @times end else render json: { errors: index_params.messages }, status: :unprocessable_entity end end def create render json: { errors: type_params.messages }, status: :unprocessable_entity unless type_params.success? case type_params.output[:type] when 'time' post_time when 'location' post_location end end private def post_time render json: { errors: time_params.messages }, status: :unprocessable_entity unless time_params.success? data = time_params.output data[:value] = TimeHelpers.prepare_time_value(data[:value]) @time_data = TimeData.new(data) if @time_data.save render json: { success: true }, status: :ok else render json: { errors: @time_data.errors }, status: :unprocessable_entity end end def post_location if location_params.success? LocationUpdateJob.perform_later(location_params.output) render json: { success: true }, status: :ok else render json: { errors: location_params.messages }, status: :unprocessable_entity end end def set_location @location = LocationData.find_by(name: index_params.output[:timezone]) end def type_params DataPostSchema.call(params.as_json) end def time_params DataPostTimeSchema.call(params.as_json) end def location_params DataPostLocationSchema.call(params.as_json) end def index_params DataGetSchema.call(params.as_json) end end end end <file_sep>require 'rails_helper' RSpec.describe Api::ApplicationController, type: :controller do end <file_sep>FactoryGirl.define do sequence :name do |n| "some#{n}" end factory :location_data do name { generate(:name) } latitude 6.00000 longitude 57.000000 timezone 'Etc/UTC' end end <file_sep>class LocationDataSerializer < ApplicationSerializer cache key: 'location_data', expires_in: 3.hours attributes :time_zone, :name, :latitude, :longitude end <file_sep>class CreateTableLocationData < ActiveRecord::Migration[5.0] def up create_table :location_data do |t| t.decimal :latitude, precision: 30, scale: 4, null: false t.decimal :longitude, precision: 30, scale: 10, null: false t.string :name, null: false, default: '' t.string :timezone, default: 'Etc/UTC' end add_index :location_data, :name, unique: true end def down drop_table :location_data end end <file_sep>require 'rails_helper' RSpec.describe LocationData, type: :model do subject { FactoryGirl.build(:location_data) } it { should validate_presence_of(:name) } it { should validate_presence_of(:latitude) } it { should validate_presence_of(:longitude) } it { should validate_numericality_of(:longitude) } it { should validate_numericality_of(:latitude) } it { should validate_uniqueness_of(:name) } end <file_sep>Rails.application.routes.draw do root 'welcome#index' def data_version(version, default = false, &routes) api_constraint = Constraints::ApiConstraint.new(version: version, default: default) scope(module: "v#{version}", constraints: api_constraint, &routes) end scope :data, module: 'api', constraints: { format: 'json' } do data_version(1, true) do get '/', to: 'data#index', as: :data post '/', to: 'data#create' end end end
b6bde341a7fe48a98c591c0899996cbab937acd7
[ "Makefile", "SQL", "Ruby", "Markdown" ]
39
Ruby
merqlove/apisvc
2cefabf09942c03eddb46401c3329b9fedd8f6ad
978040ffd0da37571488d039bd864e4f0eb5244e
refs/heads/master
<file_sep>source 'https://rubygems.org' gem 'rails', '4.0.1' gem 'pg', '0.17.1' # Json builder gem 'jbuilder', '~> 1.2' # JavaScript gem 'coffee-rails', '~> 4.0.0' gem 'jquery-rails', '3.1.0' gem 'jquery-ui-rails', '4.1.1' gem 'angularjs-rails', '1.2.14' # CSS gem 'sass-rails', '~> 4.0.0' gem 'compass-rails', '~> 1.1.3' gem 'bootstrap-sass', '~> 3.2.0.0' gem 'uglifier', '~> 2.5.3' # Icons FontAwesome gem 'font-awesome-rails', '~> 4.1.0.0' # Slim gem 'slim', :git => 'git://github.com/brennancheung/slim.git', :branch => 'angularjs_support' gem 'slim-rails', '2.1.0' <file_sep>namespace :db do desc 'add categories' task add_categories: :environment do unless Api::Category.find_by_name('Category 1') category = Api::Category.new( name: 'Category 1', count: 0 ) category.save puts '---> added category Category 1' end unless Api::Category.find_by_name('Category 2') category = Api::Category.new( name: 'Category 2', count: 0 ) category.save puts '---> added category Category 2' end unless Api::Category.find_by_name('Category 3') category = Api::Category.new( name: 'Category 3', count: 0 ) category.save puts '---> added category Category 3' end end end <file_sep>json.array!(@api_questions) do |api_question| json.extract! api_question, :id, :status, :title, :body, :comments_count, :category_id end <file_sep>json.extract! @api_category, :id, :name, :count, :created_at, :updated_at <file_sep>class Api::CommentsController < ApplicationController before_action :set_api_comment, only: [:show, :edit, :update, :destroy] def index @api_comments = Api::Comment.where(question_id: params[:question_id]) end def create @api_comment = Api::Comment.new(api_comment_params) if @api_comment.save render json: { comment: @api_comment }, status: :created else render json: @api_comment.errors, status: :unprocessable_entity end end def update if @api_comment.update(api_comment_params) respond_to json { head :no_content } else respond_to json { render json: @api_comment.errors, status: :unprocessable_entity } end end def destroy @api_comment.destroy respond_to json { head :no_content } end private def set_api_comment @api_comment = Api::Comment.find(params[:id]) end def api_comment_params params.require(:comment).permit(:body, :question_id) end end <file_sep>namespace :db do desc 'add questions' task add_questions: :environment do category = Api::Category.first puts "---> take first category '#{category.name}'" # Create question for first category quest = Api::Question.where(title: "Question 1") unless quest.any? question = Api::Question.new( category_id: category.id, status: 'open', title: 'Question 1', body: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem, repudiandae.', comments_count: 0 ) question.save puts "---> added question for #{category.name}" end quest = Api::Question.where(title: "Question 2") unless quest.any? question = Api::Question.new( category_id: category.id, status: 'ballot', title: 'Question 2', body: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem, repudiandae.', comments_count: 0 ) question.save puts "---> added question for #{category.name}" end quest = Api::Question.where(title: "Question 3") unless quest.any? question = Api::Question.new( category_id: category.id, status: 'close', title: 'Question 3', body: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem, repudiandae.', comments_count: 0 ) question.save puts "---> added question for #{category.name}" end end end <file_sep>namespace :db do desc 'delete custom added data' task delete_data: :environment do Api::Category.delete_all Api::Question.delete_all Api::Comment.delete_all puts '---> deleted all data' end end <file_sep>class Api::QuestionsController < ApplicationController before_action :set_api_question, only: [:show, :edit, :update, :status, :destroy] def index @api_questions = Api::Question.where(category_id: params[:category_id]) end def create @api_question = Api::Question.new(api_question_params) if @api_question.save respond_to json { render action: 'show', status: :created, location: @api_question } else respond_to json { render json: @api_question.errors, status: :unprocessable_entity } end end def update if @api_question.update(api_question_params) respond_to json { head :no_content } else respond_to json { render json: @api_question.errors, status: :unprocessable_entity } end end def status if @api_question.update(status_params) render json: { status: @api_question.status }, status: :created else render json: @api_question.errors, status: :unprocessable_entity end end def destroy @api_question.destroy respond_to json { head :no_content } end private def set_api_question @api_question = Api::Question.find(params[:id]) end def api_question_params params.require(:question).permit(:status, :title, :body, :comments_count, :category_id) end def status_params params.permit(:status) end end <file_sep>Question &amp; Answer =============== "Question &amp; Answer" with Ruby on Rails 4, AngularJS, PostgreSQL. For populate the database run next two rake tasks: ``` rake db:add_categories rake db:add_questions ``` For delete all fakes data from database run next task: ``` rake db:delete_data ``` <file_sep>RorAngularQuestions::Application.routes.draw do namespace :api do resources :categories do resources :questions do member do put :status end resources :comments end end end root 'main#index' match '*path' => 'main#index', via: [:get, :post] end <file_sep>json.array!(@api_comments) do |api_comment| json.extract! api_comment, :id, :body, :question_id end <file_sep>class Api::CategoriesController < ApplicationController before_action :set_api_category, only: [:show, :edit, :update, :destroy] def index @api_categories = Api::Category.all.order("id ASC") end def create @api_category = Api::Category.new(api_category_params) if @api_category.save respond_to json { render action: 'show', status: :created, location: @api_category } else respond_to json { render json: @api_category.errors, status: :unprocessable_entity } end end def update if @api_category.update(api_category_params) respond_to json { head :no_content } else respond_to json { render json: @api_category.errors, status: :unprocessable_entity } end end def destroy @api_category.destroy respond_to json { head :no_content } end private def set_api_category @api_category = Api::Category.find(params[:id]) end def api_category_params params.require(:api_category).permit(:name, :count) end end <file_sep>json.array!(@api_categories) do |api_category| json.extract! api_category, :id, :name, :count end <file_sep>json.extract! @api_comment, :id, :body, :question_id, :created_at, :updated_at <file_sep># register .slim for assets pipeline Rails.application.assets.register_mime_type 'text/html', '.html' Rails.application.assets.register_engine '.slim', Slim::Template
fbb32e5e508f84c6945a579a9d950e24e18dcfa8
[ "Markdown", "Ruby" ]
15
Ruby
sashasydorenko/question-answer
e1106cf1b2f70762ce7f0cbc629d7ec272310f05
afd71f0e2263ddccac7ec84df2a1f47355281518
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Sun Jul 12 12:49:53 2020 @author: Itay """ # pyinstaller --onefile -w CC_GUI_Final.py import tkinter as tk import tkinter.ttk as ttk from PIL import Image,ImageTk import numpy as np import time import pickle # SARSA L Parameters alpha=0.1 gamma=0.4 lam=0.4 epsilon=0 #State Life Expectancy deterioration rate EDrop=0.99999 #Life expectency (episodes*assumed mean rolls per episode) lifeExpectencey=100000*20 #State deletion threshold maxStatesStored=100000 # [Nearby, Far, Abroad] diceReset=[3,4,2] diceDict={0:"Nearby",1:"Far",2:"Abroad"} dicColorDict={0:"blue",1:"green",2:"red"} #[Safe Return, Mask, Exposure] NearbyDie=[3,2,1] FarDie=[2,2,2] AbroadDie=[1,2,3] diceStats=np.array([NearbyDie,FarDie,AbroadDie]) #Score required to win goal=10 roundRewardNone=-1 roundRewardLost=-2 winReward=10 loseReward=-5 reachGoalReward=3 # [green left, yellow left, red left, brains, shotguns, green footsteps, # yellow footsteps, red footsteps, current score, maximal opponent score] stateReset=[diceReset[0],diceReset[1],diceReset[2],0,0,0,0,0,0,0] global keepPlaying keepPlaying=1 global new_width,new_height,ratio new_height=560 new_width=800 ratio=1 root=tk.Tk() root.geometry("800x560") root.title("COVID Clash") def newGame(): global keepPlaying keepPlaying=1 ########## Window Resize Function ########## def resizeWindow(event): global new_width,new_height,ratio new_width = root.winfo_width() new_height = root.winfo_height() if new_width/800>new_height/560: new_width=int(800*new_height/560) else: new_height=int(560*new_width/800) ratio=new_width/800 canvas.config(width=new_width,height=new_height) ##### image = bgImgOrigin.resize((new_width, new_height)) global bgPhoto bgPhoto = ImageTk.PhotoImage(image) canvas.itemconfig(background,image=bgPhoto) ##### scale=0.6*ratio resizeSize=(int(logoImgOrigin.size[0]*scale),int(logoImgOrigin.size[1]*scale)) image = logoImgOrigin.resize(resizeSize) global logoPhoto,logo logoPhoto = ImageTk.PhotoImage(image) canvas.delete(logo) logo=canvas.create_image(int(0.5*new_width),0,anchor="n",image=logoPhoto) ##### global P1ScoreText,P2ScoreText canvas.delete(P1ScoreText) canvas.delete(P2ScoreText) P1ScoreText=canvas.create_text(int(1/3*new_width),0.18*new_height,anchor="n",text=P1ScoreInput,font=("Arial",int(38*ratio),"bold"),justify=tk.CENTER) P2ScoreText=canvas.create_text(int(2/3*new_width),0.18*new_height,anchor="n",text=P2ScoreInput,font=("Arial",int(38*ratio),"bold"),justify=tk.CENTER) global dice,diceImages # canvas.delete(diceFrame) canvas.delete(dice[0]) canvas.delete(dice[1]) canvas.delete(dice[2]) # diceFrameWidth=ratio*500 # diceFrameHeight=ratio*160 # diceFrame=canvas.create_rectangle(int(new_width*0.5-diceFrameWidth/2),int(new_height*0.55-diceFrameHeight/2),int(new_width*0.5+diceFrameWidth/2),int(new_height*0.55+diceFrameHeight/2),outline="#fffac3",width=4) diceSize=int(140*ratio) blankDie=blankOrigin.resize((diceSize,diceSize)) blueExposure=blueExposureOrigin.resize((diceSize,diceSize)) blueMask=blueMaskOrigin.resize((diceSize,diceSize)) blueSafe=blueSafeOrigin.resize((diceSize,diceSize)) greenExposure=greenExposureOrigin.resize((diceSize,diceSize)) greenMask=greenMaskOrigin.resize((diceSize,diceSize)) greenSafe=greenSafeOrigin.resize((diceSize,diceSize)) redExposure=redExposureOrigin.resize((diceSize,diceSize)) redMask=redMaskOrigin.resize((diceSize,diceSize)) redSafe=redSafeOrigin.resize((diceSize,diceSize)) diceImages=list() blueImages=list() blueImages.append(ImageTk.PhotoImage(blankDie)) blueImages.append(ImageTk.PhotoImage(blueExposure)) blueImages.append(ImageTk.PhotoImage(blueMask)) blueImages.append(ImageTk.PhotoImage(blueSafe)) diceImages.append(blueImages) greenImages=list() greenImages.append(ImageTk.PhotoImage(blankDie)) greenImages.append(ImageTk.PhotoImage(greenExposure)) greenImages.append(ImageTk.PhotoImage(greenMask)) greenImages.append(ImageTk.PhotoImage(greenSafe)) diceImages.append(greenImages) redImages=list() redImages.append(ImageTk.PhotoImage(blankDie)) redImages.append(ImageTk.PhotoImage(redExposure)) redImages.append(ImageTk.PhotoImage(redMask)) redImages.append(ImageTk.PhotoImage(redSafe)) diceImages.append(redImages) for i in range(3): dice[i]=canvas.create_image(int(new_width*0.4-160*ratio+i*160*ratio),int(new_height*0.55),anchor="center",image=diceImages[diceColor[i]][diceState[i]]) ##################################################### continueButton.config(font=("Arial",int(20*ratio),"bold")) continueButton.place(x=int(new_width*0.4+270*ratio),y=int(new_height*0.55-70*ratio),anchor="nw",width=int(140*ratio),height=int(70*ratio)) stopButton.config(font=("Arial",int(20*ratio),"bold")) stopButton.place(x=int(new_width*0.4+270*ratio),y=int(new_height*0.55),anchor="nw",width=int(140*ratio),height=int(70*ratio)) ##################################################### global RemDiceTitle,nearDiceText,farDiceText,abroadDiceText,curStateTitle,safeTripText,exposureText canvas.delete(RemDiceTitle) canvas.delete(nearDiceText) canvas.delete(farDiceText) canvas.delete(abroadDiceText) canvas.delete(curStateTitle) canvas.delete(safeTripText) canvas.delete(exposureText) RemDiceTitle=canvas.create_text(int(new_width*0.28),int(new_height*0.75),anchor="center",text="Remaining Dice",font=("Arial",int(14*ratio),"bold")) nearDiceText=canvas.create_text(int(new_width*0.18),int(new_height*0.82),anchor="center",text=nearDiceInput,font=("Arial",int(14*ratio),"bold"),justify=tk.CENTER,fill="blue") farDiceText=canvas.create_text(int(new_width*0.28),int(new_height*0.82),anchor="center",text=farDiceInput,font=("Arial",int(14*ratio),"bold"),justify=tk.CENTER,fill="green") abroadDiceText=canvas.create_text(int(new_width*0.38),int(new_height*0.82),anchor="center",text=abroadDiceInput,font=("Arial",int(14*ratio),"bold"),justify=tk.CENTER,fill="red") curStateTitle=canvas.create_text(int(new_width*0.72),int(new_height*0.75),anchor="center",text="Current Status",font=("Arial",int(14*ratio),"bold")) safeTripText=canvas.create_text(int(new_width*0.64),int(new_height*0.82),anchor="center",text=safeTripInput,font=("Arial",int(14*ratio),"bold"),justify=tk.CENTER,fill="maroon1") exposureText=canvas.create_text(int(new_width*0.80),int(new_height*0.82),anchor="center",text=exposureInput,font=("Arial",int(14*ratio),"bold"),justify=tk.CENTER,fill="maroon1") ##################################################### global copyrightText canvas.delete(copyrightText) copyrightText=canvas.create_text(int(new_width*0.005),int(new_height*0.995),anchor="sw",text="Created by <NAME>",font=("Arial",int(12*ratio),"italic")) ##################################################### victoryRateBar.place(relx=0.5,rely=0.90,width=int(400*ratio),height=int(15*ratio),anchor="center") global victoryRateText canvas.delete(victoryRateText) victoryRateText=canvas.create_text(int(new_width*0.5),int(new_height*0.94),text=victoryRateTextInput,font=("Arial",int(12*ratio),"bold"),anchor="center") #################################################### helpButton.config(font=("Arial",int(15*ratio),"bold")) helpButton.place(x=new_width*0.995,y=new_height*0.995,anchor="se",width=int(ratio*40),height=int(ratio*40)) #################################################### try: global helpCanvas,S,tabControl,aboutText,rulesText,exitButton S.configure('TNotebook.Tab', font=('Arial',int(15*ratio),'bold')) helpCanvas.config(width=new_width*0.87,height=new_height*0.81) helpCanvas.place(x=new_width*0.5,y=new_height*0.15,anchor="n") tabControl.place(relx=0.5,rely=0.5,anchor="center",width=new_width*0.86,height=new_height*0.8) aboutText.config(font=("Arial",int(12*ratio))) aboutText.pack(expand=True,fill="both") # aboutText.config(state="disabled") rulesText.config(font=("Arial",int(11*ratio))) rulesText.pack(expand=True,fill="both") rulesText.tag_add("steps",2.0,6.0) rulesText.tag_configure("steps",font=("Arial",int(11*ratio),"italic bold")) # rulesText.config(state="disabled") exitButton.config(font=("Arial",int(ratio*13))) exitButton.place(relx=0.5,rely=0.98,anchor="s",width=30*ratio,height=30*ratio) except: 1 #################################################### try: global winnerText,endGameFrame,winnerLabel,newGameButton,endGameButton endGameFrame.config(highlightthickness=int(5*ratio)) endGameFrame.place(relx=0.5,rely=0.6,width=0.4*new_width,height=0.4*new_height,anchor="center") winnerLabel.config(font=("Arial",int(23*ratio),"bold")) winnerLabel.place(relx=0.5,rely=0.1,anchor="n") newGameButton.config(font=("Arial",int(17*ratio))) newGameButton.place(relx=0.5,rely=0.9,anchor="se",width=0.45*0.4*new_width,height=0.3*0.4*new_height) endGameButton.config(font=("Arial",int(17*ratio))) endGameButton.place(relx=0.5,rely=0.9,anchor="sw",width=0.45*0.4*new_width,height=0.3*0.4*new_height) except: 1 ########## Game Functions ########## def loadParameters(): with open("data/SARSA.dat","rb") as filehandle: [stateLabels1,stateLabels2,SE1,SE2,Q1,Q2,E1,E2]=pickle.load(filehandle) try: with open('data/stats.dat', 'rb') as filehandle: stats=pickle.load(filehandle) except: stats=np.zeros((2)) return stateLabels1,stateLabels2,Q1,Q2,SE1,SE2,E1,E2,stats def saveParameters(): with open('data/SARSA.dat',"wb") as filehandle: pickle.dump([stateLabels1,stateLabels2,SE1,SE2,Q1,Q2,E1,E2],filehandle) # with open('data/stateLabels1.dat', 'w') as filehandle: # for listitem in stateLabels1: # for seclistitem in listitem: # filehandle.write('%s,' % seclistitem) # filehandle.write('\n') # with open('data/stateLabels2.dat', 'w') as filehandle: # for listitem in stateLabels2: # for seclistitem in listitem: # filehandle.write('%s,' % seclistitem) # filehandle.write('\n') # with open('data/SE1.dat', 'w') as filehandle: # for listitem in SE1: # filehandle.write('%s' % listitem) # filehandle.write('\n') # with open('data/SE2.dat', 'w') as filehandle: # for listitem in SE2: # filehandle.write('%s' % listitem) # filehandle.write('\n') # with open('data/Q1.dat', 'w') as filehandle: # for listitem in Q1: # for seclistitem in listitem: # filehandle.write('%s,' % seclistitem) # filehandle.write('\n') # with open('data/Q2.dat', 'w') as filehandle: # for listitem in Q2: # for seclistitem in listitem: # filehandle.write('%s,' % seclistitem) # filehandle.write('\n') # with open('data/E1.dat', 'w') as filehandle: # for listitem in E1: # for seclistitem in listitem: # filehandle.write('%s,' % seclistitem) # filehandle.write('\n') # with open('data/E2.dat', 'w') as filehandle: # for listitem in E2: # for seclistitem in listitem: # filehandle.write('%s,' % seclistitem) # filehandle.write('\n') # return 0 def decide(state,stateLabels,Q): if (sum(state[0:3])==0) & (sum(state[5:8])==0): action=0 elif state[4]>=3: action=0 else: try: currentStateLabel=stateLabels.index(state) print(Q[currentStateLabel]) if Q[currentStateLabel][0]==Q[currentStateLabel][1]: prob=[0.5,0.5] else: greedyAction=np.where(Q[currentStateLabel]==max(Q[currentStateLabel]))[0][0] prob=[((1-greedyAction)*(1-epsilon)+greedyAction*epsilon),((1-greedyAction)*epsilon+greedyAction*(1-epsilon))] except: prob=[0.5,0.5] action=np.random.choice([0,1],p=prob) return action def rollDice(state): global dice,diceImages,canvas global diceState,diceColor currentDice=state[5:8] state[5:8]=[0,0,0] diceNeeded=3-sum(currentDice) diceAvailable=sum(state[0:3]) for i in range(min([diceNeeded,diceAvailable])): newDie=np.random.choice(range(3),p=np.array(state[0:3])/sum(np.array(state[0:3]))) currentDice[newDie]=currentDice[newDie]+1 state[newDie]=state[newDie]-1 counter=-1 for i in range(3): for j in range(currentDice[i]): counter=counter+1 newRoll=np.random.choice(range(3),p=diceStats[i]/6) if newRoll==2: diceState[counter]=2 diceColor[counter]=i canvas.itemconfig(dice[counter],image=diceImages[diceColor[counter]][diceState[counter]]) state[5+i]=state[5+i]+1 elif newRoll==0: diceState[counter]=3 diceColor[counter]=i canvas.itemconfig(dice[counter],image=diceImages[diceColor[counter]][diceState[counter]]) state[3+newRoll]=state[3+newRoll]+1 else: diceState[counter]=1 diceColor[counter]=i canvas.itemconfig(dice[counter],image=diceImages[diceColor[counter]][diceState[counter]]) state[3+newRoll]=state[3+newRoll]+1 global nearDiceText,farDiceText,abroadDiceText,safeTripText,exposureText global nearDiceInput,farDiceInput,farDiceInput,abroadDiceInput,safeTripInput,exposureInput nearDiceInput="Nearby\n"+str(state[0]) canvas.itemconfig(nearDiceText,text=nearDiceInput) farDiceInput="Far\n"+str(state[1]) canvas.itemconfig(farDiceText,text=farDiceInput) abroadDiceInput="Abroad\n"+str(state[2]) canvas.itemconfig(abroadDiceText,text=abroadDiceInput) safeTripInput="Safe Trips\n"+str(state[3]) canvas.itemconfig(safeTripText,text=safeTripInput) exposureInput="Exposures\n"+str(state[4]) canvas.itemconfig(exposureText,text=exposureInput) canvas.update() return state def PCTurn(statePC): global statePCOld global Q1 global Q2 global E1 global E2 global SE1 global SE2 global stateLabels1 global stateLabels2 action=1 if PC=="P1": time.sleep(0.7) while action==1: # stateOld=statePC.copy() # actionOld=action statePCOld=statePC.copy() statePC=rollDice(statePC.copy()) print(statePC) action=decide(statePC.copy(),stateLabels1,Q1) if statePC[4]<3: Q1,E1,SE1,stateLabels1=stateExistance(statePC.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(statePC.copy(),statePCOld.copy(),1,1,Q1,E1,SE1,stateLabels1,0) time.sleep(2) if PC=="P2": time.sleep(0.7) while action==1: # stateOld=statePC.copy() # actionOld=action statePCOld=statePC.copy() statePC=rollDice(statePC.copy()) print(statePC) action=decide(statePC.copy(),stateLabels2,Q2) if statePC[4]<3: Q2,E2,SE2,stateLabels2=stateExistance(statePC.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(statePC.copy(),statePCOld.copy(),1,1,Q2,E2,SE2,stateLabels2,0) time.sleep(2) return statePC def scoreUpdate(state,otherState): if state[4]<3: state[-2]=state[-2]+state[3] state=[diceReset[0],diceReset[1],diceReset[2],0,0,0,0,0,state[-2],state[-1]] otherState[-1]=state[-2] else: state=[diceReset[0],diceReset[1],diceReset[2],0,0,0,0,0,max([state[-2]-1,0]),state[-1]] otherState[-1]=state[-2] state=[diceReset[0],diceReset[1],diceReset[2],0,0,0,0,0,state[-2],state[-1]] return state,otherState def scoreBoardUpdate(): global P1ScoreText,P2ScoreText,P1ScoreInput,P2ScoreInput,canvas if PC=="P1": P1ScoreInput="PC\n"+str(statePC[8]) P2ScoreInput="USER\n"+str(stateUser[8]) else: P2ScoreInput="PC\n"+str(statePC[8]) P1ScoreInput="USER\n"+str(stateUser[8]) canvas.itemconfig(P1ScoreText,text=P1ScoreInput) canvas.itemconfig(P2ScoreText,text=P2ScoreInput) def recalcQ(state,stateOld,action,actionOld,Q,E,SE,stateLabels,reward): if (state[0:3]==diceReset) & (state[8]<goal): currentStateLabel=stateLabels.index(state) Q[currentStateLabel]=Q[currentStateLabel]*0 if stateOld[0:3]==diceReset: oldStateLabel=stateLabels.index(stateOld) Q[oldStateLabel]=Q[oldStateLabel]*0 return Q,E,SE currentStateLabel=stateLabels.index(state) oldStateLabel=stateLabels.index(stateOld) delta=reward+gamma*Q[currentStateLabel][action]-Q[oldStateLabel][actionOld] E[oldStateLabel][actionOld]=E[oldStateLabel][actionOld]+1 print(reward,"+",gamma*Q[currentStateLabel][action],"-",Q[oldStateLabel][actionOld],"=",delta) print(E[oldStateLabel][actionOld]) Q=Q+alpha*delta*E E=gamma*lam*E SE[oldStateLabel]=SE[oldStateLabel]+1 SE=EDrop*SE return Q,E,SE def stateExistance(state,Q,E,SE,stateLabels): if state not in stateLabels: stateLabels.append(state) Q=np.append(Q,np.zeros((1,2)),axis=0) SE=np.append(SE,[1],axis=0) E=np.append(E,np.zeros((1,2)),axis=0) return Q,E,SE,stateLabels def endGamePanel(): global winnerText,endGameFrame,winnerLabel,newGameButton,endGameButton endGameFrame=tk.Frame(canvas,highlightbackground="red", highlightthickness=int(5*ratio)) endGameFrame.place(relx=0.5,rely=0.6,width=0.4*new_width,height=0.4*new_height,anchor="center") winnerLabel=tk.Label(endGameFrame,text=winnerText,font=("Arial",int(23*ratio),"bold")) winnerLabel.place(relx=0.5,rely=0.1,anchor="n") newGameButton=tk.Button(endGameFrame,text="New Game",font=("Arial",int(17*ratio)),command=newGameButtonCommand) newGameButton.place(relx=0.5,rely=0.9,anchor="se",width=0.45*0.4*new_width,height=0.3*0.4*new_height) endGameButton=tk.Button(endGameFrame,text="Quit",font=("Arial",int(17*ratio)),command=endGameButtonCommand) endGameButton.place(relx=0.5,rely=0.9,anchor="sw",width=0.45*0.4*new_width,height=0.3*0.4*new_height) def newGameButtonCommand(): canvas.destroy() newGame() def endGameButtonCommand(): root.destroy() def resetRemDiceState(): global RemDiceTitle,nearDiceText,farDiceText,abroadDiceText,curStateTitle,safeTripText,exposureText global nearDiceInput,farDiceInput,farDiceInput,abroadDiceInput,safeTripInput,exposureInput nearDiceInput="Nearby\n"+str(stateReset[0]) canvas.itemconfig(nearDiceText,text=nearDiceInput) farDiceInput="Far\n"+str(stateReset[1]) canvas.itemconfig(farDiceText,text=farDiceInput) abroadDiceInput="Abroad\n"+str(stateReset[2]) canvas.itemconfig(abroadDiceText,text=abroadDiceInput) safeTripInput="Safe Trips\n"+str(stateReset[3]) canvas.itemconfig(safeTripText,text=safeTripInput) exposureInput="Exposures\n"+str(stateReset[4]) canvas.itemconfig(exposureText,text=exposureInput) ##################################### keepPlaying=0 #Choose who starts PC=np.random.choice(["P1","P2"]) global winnerText winnerText="" print(PC) global stateUser global stats global statePC stateUser=stateReset.copy() statePC=stateReset.copy() if PC=="P1": currentState=statePC.copy() else: currentState=stateUser.copy() global statePCOld global stateUserOld global Q1 global Q2 global E1 global E2 global SE1 global SE2 global stateLabels1 global stateLabels2 stateUserOld=stateUser.copy() statePCOld=statePC.copy() stateLabels1,stateLabels2,Q1,Q2,SE1,SE2,E1,E2,stats = loadParameters() ################################################ global new_width,new_height,ratio ################################################ bgImgOrigin=Image.open(r"data/bg.png") bgImg=ImageTk.PhotoImage(bgImgOrigin) global canvas canvas=tk.Canvas(root,width=new_width,height=new_height) canvas.place(relx=0.5,rely=0.5,anchor="center") canvas.update() background=canvas.create_image(0,0,anchor="nw",image=bgImg) ############################################### logoImgOrigin=Image.open("data/Logo.png") scale=0.6*new_width/800 resizeSize=(int(logoImgOrigin.size[0]*scale),int(logoImgOrigin.size[1]*scale)) logoImg=logoImgOrigin.resize(resizeSize, Image.ANTIALIAS) logoImg=ImageTk.PhotoImage(logoImg) global logo logo=canvas.create_image(int(0.5*new_width),0,anchor="n",image=logoImg) ############################################## global P1ScoreText,P2ScoreText,P1ScoreInput,P2ScoreInput if PC=="P1": P1ScoreInput="PC\n"+str(statePC[8]) P2ScoreInput="USER\n"+str(stateUser[8]) else: P2ScoreInput="PC\n"+str(statePC[8]) P1ScoreInput="USER\n"+str(stateUser[8]) P1ScoreText=canvas.create_text(int(1/3*new_width),0.18*new_height,anchor="n",text=P1ScoreInput,font=("Arial",int(38*ratio),"bold"),justify=tk.CENTER) P2ScoreText=canvas.create_text(int(2/3*new_width),0.18*new_height,anchor="n",text=P2ScoreInput,font=("Arial",int(38*ratio),"bold"),justify=tk.CENTER) ############################################## global dice,diceImages blankOrigin=Image.open("data/blank.png") blueExposureOrigin=Image.open("data/Exposure_Blue.png") blueMaskOrigin=Image.open("data/Mask_Blue.png") blueSafeOrigin=Image.open("data/ReturnSafely_Blue.png") greenExposureOrigin=Image.open("data/Exposure_Green.png") greenMaskOrigin=Image.open("data/Mask_Green.png") greenSafeOrigin=Image.open("data/ReturnSafely_Green.png") redExposureOrigin=Image.open("data/Exposure_Red.png") redMaskOrigin=Image.open("data/Mask_Red.png") redSafeOrigin=Image.open("data/ReturnSafely_Red.png") diceSize=int(140*ratio) blankDie=blankOrigin.resize((diceSize,diceSize)) blueExposure=blueExposureOrigin.resize((diceSize,diceSize)) blueMask=blueMaskOrigin.resize((diceSize,diceSize)) blueSafe=blueSafeOrigin.resize((diceSize,diceSize)) greenExposure=greenExposureOrigin.resize((diceSize,diceSize)) greenMask=greenMaskOrigin.resize((diceSize,diceSize)) greenSafe=greenSafeOrigin.resize((diceSize,diceSize)) redExposure=redExposureOrigin.resize((diceSize,diceSize)) redMask=redMaskOrigin.resize((diceSize,diceSize)) redSafe=redSafeOrigin.resize((diceSize,diceSize)) diceImages=list() blueImages=list() blueImages.append(ImageTk.PhotoImage(blankDie)) blueImages.append(ImageTk.PhotoImage(blueExposure)) blueImages.append(ImageTk.PhotoImage(blueMask)) blueImages.append(ImageTk.PhotoImage(blueSafe)) diceImages.append(blueImages) greenImages=list() greenImages.append(ImageTk.PhotoImage(blankDie)) greenImages.append(ImageTk.PhotoImage(greenExposure)) greenImages.append(ImageTk.PhotoImage(greenMask)) greenImages.append(ImageTk.PhotoImage(greenSafe)) diceImages.append(greenImages) redImages=list() redImages.append(ImageTk.PhotoImage(blankDie)) redImages.append(ImageTk.PhotoImage(redExposure)) redImages.append(ImageTk.PhotoImage(redMask)) redImages.append(ImageTk.PhotoImage(redSafe)) diceImages.append(redImages) global diceState,diceColor diceState={0:0,1:0,2:0} diceColor={0:0,1:0,2:0} dice=list() dice.append(canvas.create_image(int(new_width*0.4-160*ratio),int(new_height*0.55),anchor="center",image=diceImages[diceColor[0]][diceState[0]])) dice.append(canvas.create_image(int(new_width*0.4),int(new_height*0.55),anchor="center",image=diceImages[diceColor[1]][diceState[1]])) dice.append(canvas.create_image(int(new_width*0.4+160*ratio),int(new_height*0.55),anchor="center",image=diceImages[diceColor[2]][diceState[2]])) ############################################## global RemDiceTitle,nearDiceText,farDiceText,abroadDiceText,curStateTitle,safeTripText,exposureText global nearDiceInput,farDiceInput,farDiceInput,abroadDiceInput,safeTripInput,exposureInput RemDiceTitle=canvas.create_text(int(new_width*0.28),int(new_height*0.75),anchor="center",text="Remaining Dice",font=("Arial",int(14*ratio),"bold")) nearDiceInput="Nearby\n"+str(stateReset[0]) ##### Fix Later ##### nearDiceText=canvas.create_text(int(new_width*0.18),int(new_height*0.82),anchor="center",text=nearDiceInput,font=("Arial",int(14*ratio),"bold"),justify=tk.CENTER,fill="blue") farDiceInput="Far\n"+str(stateReset[1]) ##### Fix Later ##### farDiceText=canvas.create_text(int(new_width*0.28),int(new_height*0.82),anchor="center",text=farDiceInput,font=("Arial",int(14*ratio),"bold"),justify=tk.CENTER,fill="green") abroadDiceInput="Abroad\n"+str(stateReset[2]) ##### Fix Later ##### abroadDiceText=canvas.create_text(int(new_width*0.38),int(new_height*0.82),anchor="center",text=abroadDiceInput,font=("Arial",int(14*ratio),"bold"),justify=tk.CENTER,fill="red") curStateTitle=canvas.create_text(int(new_width*0.72),int(new_height*0.75),anchor="center",text="Current Status",font=("Arial",int(14*ratio),"bold")) safeTripInput="Safe Trips\n"+str(stateReset[3]) safeTripText=canvas.create_text(int(new_width*0.64),int(new_height*0.82),anchor="center",text=safeTripInput,font=("Arial",int(14*ratio),"bold"),justify=tk.CENTER,fill="maroon1") exposureInput="Exposures\n"+str(stateReset[4]) exposureText=canvas.create_text(int(new_width*0.80),int(new_height*0.82),anchor="center",text=exposureInput,font=("Arial",int(14*ratio),"bold"),justify=tk.CENTER,fill="maroon1") ############################################## global copyrightText copyrightText=canvas.create_text(int(new_width*0.005),int(new_height*0.995),anchor="sw",text="Created by <NAME>",font=("Arial",int(12*ratio),"italic")) ############################################## global S S=ttk.Style() S.theme_use("clam") S.configure("red.Horizontal.TProgressbar", foreground='black', background='#fffac3')#("red.Horizontal.TProgressbar", foreground="#fffac3") victoryRateBar=ttk.Progressbar(canvas,style="red.Horizontal.TProgressbar",length=100) victoryRateBar.place(relx=0.5,rely=0.9,width=int(400*ratio),height=int(15*ratio),anchor="center") if stats[0]==0: victoryRateBar["value"]=0 victoryRateTextInput="You have won "+str(100)+"% of "+str(0)+" games" else: victoryRateBar["value"]=stats[1]/stats[0]*100 victoryRateBar.update() victoryRateTextInput="You have won "+str(round(stats[1]/stats[0]*100,1))+"% of "+str(int(stats[0]))+" games" global victoryRateText victoryRateText=canvas.create_text(int(new_width*0.5),int(new_height*0.94),text=victoryRateTextInput,font=("Arial",int(12*ratio),"bold"),anchor="center") ############################################## def continueButtonCommand(): global stateUserOld,statePC,stateUser global Q1,Q2,E1,E2,SE1,SE2,stateLabels1,stateLabels2 stateUserOld=stateUser.copy() stateUser=rollDice(stateUser.copy()) stopButton["state"]="normal" if stateUser[4]>=3: continueButton["state"]="disable" else: if PC=="P1": Q2,E2,SE2,stateLabels2=stateExistance(stateUser.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(stateUser.copy(),stateUserOld.copy(),1,1,Q2,E2,SE2,stateLabels2,0) else: Q1,E1,SE1,stateLabels1=stateExistance(stateUser.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(stateUser.copy(),stateUserOld.copy(),1,1,Q1,E1,SE1,stateLabels1,0) return 0 def stopButtonCommand(): global stats global Q1,Q2,E1,E2,SE1,SE2,stateLabels1,stateLabels2 global statePC,statePCOld,stateUser,stateUserOld global diceState,diceColor global winnerText continueButton["state"]="disable" stopButton["state"]="disable" diceState={0:0,1:0,2:0} diceColor={0:0,1:0,2:0} for i in range(3): canvas.itemconfig(dice[i],image=diceImages[diceColor[i]][diceState[i]]) if (stateUser[4]<3) & (stateUser[3]>0): rewardUser=min([2,stateUser[3]]) elif (stateUser[4]<3) | (stateUser[-2]==0): rewardUser=roundRewardNone else: rewardUser=roundRewardLost if PC=="P1": Q2,E2,SE2,stateLabels2=stateExistance(stateUser.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(stateUser.copy(),stateUserOld.copy(),0,1,Q2,E2,SE2,stateLabels2,rewardUser) else: Q1,E1,SE1,stateLabels1=stateExistance(stateUser.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(stateUser.copy(),stateUserOld.copy(),0,1,Q1,E1,SE1,stateLabels1,rewardUser) statUserOld=stateUser.copy() statePCOld=statePC.copy() stateUser,statePC=scoreUpdate(stateUser.copy(),statePC.copy()) scoreBoardUpdate() if (stateUser[8]>=goal) & (stateUser[8]>statePC[8]): if PC=="P1": print("Human Wins!") winnerText="HUMANITY\nWINS!" if PC=="P1": Q1,E1,SE1,stateLabels1=stateExistance(statePC.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(statePC.copy(),statePCOld.copy(),1,0,Q1,E1,SE1,stateLabels1,loseReward) Q2,E2,SE2,stateLabels2=stateExistance(stateUser.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(stateUser.copy(),stateUserOld.copy(),1,0,Q2,E2,SE2,stateLabels2,winReward) else: Q1,E1,SE1,stateLabels1=stateExistance(stateUser.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(stateUser.copy(),stateUserOld.copy(),1,0,Q1,E1,SE1,stateLabels1,winReward) Q2,E2,SE2,stateLabels2=stateExistance(statePC.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(statePC.copy(),statePCOld.copy(),1,0,Q2,E2,SE2,stateLabels2,loseReward) saveParameters() stats=stats+1 saveStats() endGamePanel() # diceSpaceFrame.destroy() # diceSpaceFrame = tk.Frame(canvasMainPage,height=140,width=400,bg="Black") # diceSpaceFrame.grid(row=1,column=0) # diceSpaceFrame.grid_propagate(0) # vicotryLabel = tk.Label(diceSpaceFrame,text="Human Wins!",bg="Black",fg="red") # vicotryLabel.place(relx=0.5, rely=0.5, anchor="c") # NewGameButton=tk.Button(diceSpaceFrame,text="New Game",padx=10,pady=5,command=newGameButtonCommand) # NewGameButton.place(relx=0.5,rely=0.3,anchor="c") return 0 elif (statePC[8]>=goal) & (statePC[8]>=stateUser[8]): if PC=="P1": print("Computer Wins!") winnerText="GAME OVER!\nComputer Wins!" if PC=="P1": Q1,E1,SE1,stateLabels1=stateExistance(statePC.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(statePC.copy(),statePCOld.copy(),1,0,Q1,E1,SE1,stateLabels1,winReward) Q2,E2,SE2,stateLabels2=stateExistance(stateUser.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(stateUser.copy(),stateUserOld.copy(),1,0,Q2,E2,SE2,stateLabels2,loseReward) else: Q1,E1,SE1,stateLabels1=stateExistance(stateUser.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(stateUser.copy(),stateUserOld.copy(),1,0,Q1,E1,SE1,stateLabels1,loseReward) Q2,E2,SE2,stateLabels2=stateExistance(statePC.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(statePC.copy(),statePCOld.copy(),1,0,Q2,E2,SE2,stateLabels2,winReward) saveParameters() stats[0]=stats[0]+1 saveStats() endGamePanel() # diceSpaceFrame.destroy() # diceSpaceFrame = tk.Frame(canvasMainPage,height=140,width=400,bg="Black") # diceSpaceFrame.grid(row=1,column=0) # diceSpaceFrame.grid_propagate(0) # vicotryLabel = tk.Label(diceSpaceFrame,text="Computer Wins!",bg="Black",fg="red") # vicotryLabel.place(relx=0.5, rely=0.5, anchor="c") # NewGameButton=tk.Button(diceSpaceFrame,text="New Game",padx=10,pady=5,command=newGameButtonCommand) # NewGameButton.place(relx=0.5,rely=0.3,anchor="c") return 0 else: if PC=="P1": Q1,E1,SE1,stateLabels1=stateExistance(statePC.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(statePC.copy(),statePCOld.copy(),1,0,Q1,E1,SE1,stateLabels1,0) Q2,E2,SE2,stateLabels2=stateExistance(stateUser.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(stateUser.copy(),stateUserOld.copy(),1,0,Q2,E2,SE2,stateLabels2,0) else: Q1,E1,SE1,stateLabels1=stateExistance(stateUser.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(stateUser.copy(),stateUserOld.copy(),1,0,Q1,E1,SE1,stateLabels1,0) Q2,E2,SE2,stateLabels2=stateExistance(statePC.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(statePC.copy(),statePCOld.copy(),1,0,Q2,E2,SE2,stateLabels2,0) time.sleep(0.2) statePC=PCTurn(statePC.copy()) if (statePC[4]<3) & (statePC[3]>0): rewardPC=min([2,statePC[3]]) elif (statePC[4]<3) | (statePC[-2]==0): rewardPC=roundRewardNone else: rewardPC=roundRewardLost if PC=="P2": Q2,E2,SE2,stateLabels2=stateExistance(statePC.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(statePC.copy(),statePCOld.copy(),0,1,Q2,E2,SE2,stateLabels2,rewardPC) else: Q1,E1,SE1,stateLabels1=stateExistance(statePC.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(statePC.copy(),statePCOld.copy(),0,1,Q1,E1,SE1,stateLabels1,rewardPC) stateUserOld=stateUser.copy() statePCOld=statePC.copy() statePC,stateUser=scoreUpdate(statePC.copy(),stateUser.copy()) scoreBoardUpdate() time.sleep(1) if (stateUser[8]>=goal) & (stateUser[8]>=statePC[8]): if PC=="P2": print("Human Wins!") winnerText="HUMANITY\nWINS!" if PC=="P1": Q1,E1,SE1,stateLabels1=stateExistance(statePC.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(statePC.copy(),statePCOld.copy(),1,0,Q1,E1,SE1,stateLabels1,loseReward) Q2,E2,SE2,stateLabels2=stateExistance(stateUser.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(stateUser.copy(),stateUserOld.copy(),1,0,Q2,E2,SE2,stateLabels2,winReward) else: Q1,E1,SE1,stateLabels1=stateExistance(stateUser.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(stateUser.copy(),stateUserOld.copy(),1,0,Q1,E1,SE1,stateLabels1,winReward) Q2,E2,SE2,stateLabels2=stateExistance(statePC.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(statePC.copy(),statePCOld.copy(),1,0,Q2,E2,SE2,stateLabels2,loseReward) saveParameters() stats=stats+1 saveStats() endGamePanel() # diceSpaceFrame.destroy() # diceSpaceFrame = tk.Frame(canvasMainPage,height=140,width=400,bg="Black") # diceSpaceFrame.grid(row=1,column=0) # diceSpaceFrame.grid_propagate(0) # vicotryLabel = tk.Label(diceSpaceFrame,text="Human Wins!",bg="Black",fg="red") # vicotryLabel.place(relx=0.5, rely=0.5, anchor="c") # NewGameButton=tk.Button(diceSpaceFrame,text="New Game",padx=10,pady=5,command=newGameButtonCommand) # NewGameButton.place(relx=0.5,rely=0.3,anchor="c") return 0 elif (statePC[8]>=goal) & (statePC[8]>stateUser[8]): if PC=="P2": winnerText="GAME OVER!\nComputer Wins!" time.sleep(1) if PC=="P1": Q1,E1,SE1,stateLabels1=stateExistance(statePC.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(statePC.copy(),statePCOld.copy(),1,0,Q1,E1,SE1,stateLabels1,winReward) Q2,E2,SE2,stateLabels2=stateExistance(stateUser.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(stateUser.copy(),stateUserOld.copy(),1,0,Q2,E2,SE2,stateLabels2,loseReward) else: Q1,E1,SE1,stateLabels1=stateExistance(stateUser.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(stateUser.copy(),stateUserOld.copy(),1,0,Q1,E1,SE1,stateLabels1,loseReward) Q2,E2,SE2,stateLabels2=stateExistance(statePC.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(statePC.copy(),statePCOld.copy(),1,0,Q2,E2,SE2,stateLabels2,winReward) saveParameters() stats[0]=stats[0]+1 saveStats() endGamePanel() # diceSpaceFrame.destroy() # diceSpaceFrame = tk.Frame(canvasMainPage,height=140,width=400,bg="Black") # diceSpaceFrame.grid(row=1,column=0) # diceSpaceFrame.grid_propagate(0) # vicotryLabel = tk.Label(diceSpaceFrame,text="Computer Wins!",bg="Black",fg="red") # vicotryLabel.place(relx=0.5, rely=0.5, anchor="c") # NewGameButton=tk.Button(diceSpaceFrame,text="New Game",padx=10,pady=5,command=newGameButtonCommand) # NewGameButton.place(relx=0.5,rely=0.3,anchor="c") return 0 else: if PC=="P1": Q1,E1,SE1,stateLabels1=stateExistance(statePC.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(statePC.copy(),statePCOld.copy(),1,0,Q1,E1,SE1,stateLabels1,0) Q2,E2,SE2,stateLabels2=stateExistance(stateUser.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(stateUser.copy(),stateUserOld.copy(),1,0,Q2,E2,SE2,stateLabels2,0) else: Q1,E1,SE1,stateLabels1=stateExistance(stateUser.copy(),Q1,E1,SE1,stateLabels1) Q1,E1,SE1=recalcQ(stateUser.copy(),stateUserOld.copy(),1,0,Q1,E1,SE1,stateLabels1,0) Q2,E2,SE2,stateLabels2=stateExistance(statePC.copy(),Q2,E2,SE2,stateLabels2) Q2,E2,SE2=recalcQ(statePC.copy(),statePCOld.copy(),1,0,Q2,E2,SE2,stateLabels2,0) continueButton["state"]="normal" time.sleep(0.7) diceState={0:0,1:0,2:0} diceColor={0:0,1:0,2:0} for i in range(3): canvas.itemconfig(dice[i],image=diceImages[diceColor[i]][diceState[i]]) resetRemDiceState() continueButton=tk.Button(canvas,text="Roll",font=("Arial",int(20*ratio),"bold"),fg="green",command=continueButtonCommand) continueButton.place(x=int(new_width*0.4+270*ratio),y=int(new_height*0.55-70*ratio),anchor="nw",width=int(140*ratio),height=int(70*ratio)) stopButton=tk.Button(canvas,text="End Turn",font=("Arial",int(20*ratio),"bold"),fg="red",command=stopButtonCommand) stopButton.place(x=int(new_width*0.4+270*ratio),y=int(new_height*0.55),anchor="nw",width=int(140*ratio),height=int(70*ratio)) stopButton["state"]="disable" ############################################## with open('data/text.dat', 'rb') as textFile: [aboutTextInput,rulesTextInput] = pickle.load(textFile) def helpButtonCommand(): global helpCanvas,tabControl,aboutText,rulesText,exitButton,S S.configure('TNotebook.Tab', font=('Arial',int(15*ratio),'bold')) helpCanvas=tk.Canvas(canvas,width=new_width*0.87,height=new_height*0.81,bg="#fffac3") helpCanvas.place(x=new_width*0.5,y=new_height*0.15,anchor="n") tabControl=ttk.Notebook(helpCanvas) aboutTab=ttk.Frame(tabControl) rulesTab=ttk.Frame(tabControl) tabControl.add(aboutTab,text="About the Game") tabControl.add(rulesTab,text="Game Rules") aboutText=tk.Text(aboutTab,wrap="word",font=("Arial",int(12*ratio))) aboutText.pack(expand=True,fill="both") aboutText.insert('insert',aboutTextInput) aboutText.config(state="disabled") rulesText=tk.Text(rulesTab,wrap="word",font=("Arial",int(11*ratio))) rulesText.pack(expand=True,fill="both") rulesText.insert('insert',rulesTextInput) rulesText.tag_add("steps",2.0,6.0) rulesText.tag_configure("steps",font=("Arial",int(11*ratio),"italic bold")) rulesText.config(state="disabled") tabControl.place(relx=0.5,rely=0.5,anchor="center",width=new_width*0.86,height=new_height*0.8) exitButton=tk.Button(helpCanvas,text="X",font=("Arial",int(ratio*13)),command=exitButtonCommand) exitButton.place(relx=0.5,rely=0.99,anchor="s",width=30*ratio,height=30*ratio) def exitButtonCommand(): global helpCanvas helpCanvas.destroy() helpButton=tk.Button(canvas,text="?",font=("Arial",15,"bold"),command=helpButtonCommand) helpButton.place(x=new_width*0.995,y=new_height*0.995,anchor="se",width=40*ratio,height=40*ratio) root.bind('<Configure>', resizeWindow) def player(): if PC=="P1": print("PC starts") stopButtonCommand() def saveStats(): with open('data/stats.dat', 'wb') as filehandle: pickle.dump(stats,filehandle) # with open('data/stats.dat', 'w') as filehandle: # for listitem in stats: # filehandle.write('%s\n' % listitem) root.after(1000,player) newGame() root.mainloop()<file_sep># CCGame This is a simple dice game you can play against a computer agent. The agent has been thoroughly trained via Reinforcement Learning, playing numerous games against himself, in order to learn to make the correct decision considering the complex game statistics. The agent will continue to learn (although slowly) as it plays against the user, from both his and the user's moves. You can play the game simply by downloading the Executable folder and running the .exe file in the folder. However, this will probably only work on a Windows OS. For other OS, You can try and run the Python file in the Code folder, although it has not been tested so I can't assure you that will work. If you wish to review the code, it is available in the Code folder. Note, however, that it was not originally meant to be published, but as part of learning Python, and therefore is a bit messy and not annotated. # Game Rules The players are mayors of cities facing COVID-19 and competing to keep their city the safest. The goal is to reach ten safety points or more and have the safest city. Each die roll represents citizens leaving their homes. The die roll may result in one of three options - return home after a SAFE TRIP (denoted by a house), a protected encounter where everyone was wearing MASKs (denoted by a mask), and an unprotected encounter which leads to EXPOSURE (denoted by a virus). The chance of EXPOSURE is higher depending on the proximity. Nearby trips (blue) are safer than Far trips (green) which are safer than trips Abroad (red). A turn is comprised of the following steps: 1. Pick three dice at random from the stack and roll them by clicking the Roll button. 2. If you have three (or more) EXPOSUREs, you have a local outbreak which ends your turn when you click the End Turn button. Otherwise, you may choose to end your turn here with the SAFE TRIPs you have collected so far by clicking the End Turn button (skipping the next steps) or continue by clicking the Roll button again. 3. MASKs are being rerolled, to continue their trip, while the rest accumulate. Additional dice are collected from the stack to a total of three (including the MASKs) or until there are no dice in the stock. Note: If there are no MASKs and no new dice, you must end your turn by clicking the End Turn button. 4. The (up to) three dice will be rolled and and then you will repeat steps 2-4. Once the turn had ended, unless you had a local outbreak, add the number of dice the resulted in SAFE TRIPs to your current score. If the turn ended in a local outbreak, and you have one or more safety points, your safety points are reduced by one. Either way, all the dice return to the stack. If at the end of a round, i.e., the end of the second player's turn, either player has ten or more safety points, the player with the most points wins the game. In the case of a tie, the first player wins the game.
837cd06d5564344216b9289cc7ad830d8577cb54
[ "Markdown", "Python" ]
2
Python
ItayGrinberg/CCGame
bf30eb9a6c2c6a15a5587518e535626a9fdebe42
b0153b261d7ceb8fd0f018409be64c96dbc214c0
refs/heads/master
<file_sep># This file was created by `documentation::extract_tests` on 2018-11-12 16:19:15. # Once present, this file will not be overwritten and changes will persist. # To recreate the default version of this file delete and rerun `extract_tests`. library(testthat) test_check("testextra")
ec5c251b78f8e96f50edc96f8fc84e71d33b75f0
[ "R" ]
1
R
cran/testextra
47aff786d69fec69ed4e2e78d702675fb1e37be9
7305d853cfa25e75a90e0fba1ba4ebe35c655b62
refs/heads/main
<file_sep>import { Component, OnInit } from '@angular/core'; import {SecurityService} from '../services/security.service' @Component({ selector: 'app-encoder-decoder', templateUrl: './encoder-decoder.component.html', styleUrls: ['./encoder-decoder.component.css'] }) export class EncoderDecoderComponent implements OnInit { constructor(private securityService:SecurityService) { } ngOnInit(): void { } word:string; encodedWord:string; decodedWord:string; errorMessage:string; loading; encoder(){ this.loading=true; this.securityService.encoder(this.word).subscribe((encodedWord)=>{ this.decodedWord = null; this.encodedWord=encodedWord.result; this.errorMessage=""; this.loading=false; }, (error) => {this.errorMessage = error.statusText}); } decoder(){ this.loading=true; this.securityService.decoder(this.word).subscribe((decodedWord)=>{ this.encodedWord = null; this.decodedWord=decodedWord.result; console.log(this.decodedWord) this.errorMessage=""; if(this.decodedWord == null){ this.errorMessage = "String can't be decoded" } this.loading=false; }, (error) => {this.errorMessage = error.statusText}); } } <file_sep>import { SymmetricComponent } from './symmetric/symmetric.component'; import { AsymmetricComponent } from './asymmetric/asymmetric.component'; import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { EncoderDecoderComponent } from './encoder-decoder/encoder-decoder.component'; import { HasherComponent } from './hasher/hasher.component'; import { MainComponent } from './main/main.component'; import { PasswordCrackerComponent } from './password-cracker/password-cracker.component'; const routes: Routes = [ {path:"encoder-decoder",component:EncoderDecoderComponent}, {path:"password-cracker",component:PasswordCrackerComponent}, {path:"hasher",component:HasherComponent}, {path:"symmetric",component:SymmetricComponent}, {path:"asymmetric",component:AsymmetricComponent}, {path:"",component:MainComponent}, {path:"**",component:MainComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { SecurityService } from 'src/app/services/security.service'; import { StorageService } from 'src/app/services/storage.service'; @Component({ selector: 'app-import-from', templateUrl: './import-from.component.html', styleUrls: ['./import-from.component.css'] }) export class ImportFromComponent implements OnInit { fingerprint = ''; submitted = false; success = false; errorMessage = ''; publicKey = ''; alreadyExists = false; constructor( private securityService: SecurityService, private storageService: StorageService ) { } ngOnInit(): void { } onSubmit(): void { this.submitted = true; this.securityService.importKey(this.fingerprint).subscribe( data => { this.publicKey=data.public; if(this.publicKey!='Bad Fingerprint') { this.storageService.importKey(this.fingerprint,this.publicKey); } }, error => this.errorMessage=error.message, ()=> {this.success=true; this.submitted=false} ) } checkFingerprint(fingerprint) { this.alreadyExists = this.storageService.publicKeyExists(fingerprint); } } <file_sep>import { SecurityService } from './../../services/security.service'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-symmetric-encryption', templateUrl: './symmetric-encryption.component.html', styleUrls: ['./symmetric-encryption.component.css'] }) export class SymmetricEncryptionComponent implements OnInit { message = ''; algorithms = [ '3DES', 'CAST5', 'BLOWFISH', 'AES', 'AES192', 'AES256', 'TWOFISH', 'CAMELLIA128', 'CAMELLIA192', 'CAMELLIA256' ] chosenAlgorithm = ''; passphrase; submitted = false; result; errorMessage; constructor( private securityService : SecurityService ) { } ngOnInit(): void { } encrypt() : void { this.submitted = true; this.securityService.symEncrypt(this.message,this.chosenAlgorithm,this.passphrase).subscribe( data => {this.submitted=false; this.result=data.result; this.passphrase=data.password.length ? data.password : this.passphrase}, error => {console.log(error); this.errorMessage=error.message}, ) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { SecurityService } from 'src/app/services/security.service'; import { StorageService } from 'src/app/services/storage.service'; @Component({ selector: 'app-import-own', templateUrl: './import-own.component.html', styleUrls: ['./import-own.component.css'] }) export class ImportOwnComponent implements OnInit { submitted = false; success = false; errorMessage = ''; publicKey = ''; fingerprint = ''; alreadyExists = false; constructor( private securityService: SecurityService, private storageService: StorageService ) { } ngOnInit(): void { } onSubmit(): void { this.submitted = true; this.securityService.importOwnKey(this.publicKey).subscribe( data => { this.fingerprint=data.fingerprint; if(this.fingerprint!='Bad Public Key') { this.storageService.importKey(this.fingerprint,this.publicKey); } }, error => this.errorMessage=error.message, ()=> {this.success=true; this.submitted=false} ) } } <file_sep># University Project for [Security Module] # Frontend # The tasks: ![alt text](./1.jpg) ![alt text](./2.jpg) <file_sep>import { SecurityService } from './../../services/security.service'; import { StorageService } from './../../services/storage.service'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-asymmetric-encryption', templateUrl: './asymmetric-encryption.component.html', styleUrls: ['./asymmetric-encryption.component.css'] }) export class AsymmetricEncryptionComponent implements OnInit { fingerprint; message = ''; submitted = false; success = false; errorMessage = ''; result = ''; constructor( private storageService: StorageService, private securityService: SecurityService ) { } ngOnInit(): void { } onSubmit(): void { this.submitted = true; this.securityService.asymEncrypt(this.message,this.storageService.getPublicKey(this.fingerprint)).subscribe( data => { this.result = data.result; }, error => {this.errorMessage = error.message}, () => {this.submitted= false; this.success = true;} ) } changeFingerprint(fingerprint): void { this.fingerprint = this.storageService.publicKeyExists(fingerprint) ? fingerprint : null; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { SecurityService } from '../services/security.service'; @Component({ selector: 'app-hasher', templateUrl: './hasher.component.html', styleUrls: ['./hasher.component.css'] }) export class HasherComponent implements OnInit { algorithms = ['md5', 'sha1', 'ripemd160', 'sha256', 'sha384', ]; constructor(private securityService:SecurityService) { } ngOnInit(): void { } word:string; hashedWord:string; errorMessage; loading; algorithm:string="Select Algorithm"; hasher(){ this.loading=true; this.securityService.hash(this.word,this.algorithm).subscribe((hashedWord)=>{ this.hashedWord=hashedWord.hash; this.loading=false; },error => {this.errorMessage = error.message},); } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { ImportFromComponent } from './import-from.component'; describe('ImportFromComponent', () => { let component: ImportFromComponent; let fixture: ComponentFixture<ImportFromComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ImportFromComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ImportFromComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>export const environment = { production: true, baseURL:"https://protect-messages.herokuapp.com/api/security/" }; <file_sep>import { Component, OnInit } from '@angular/core'; import { StorageService } from './../../services/storage.service'; import { SecurityService } from './../../services/security.service'; @Component({ selector: 'app-sign', templateUrl: './sign.component.html', styleUrls: ['./sign.component.css'] }) export class SignComponent implements OnInit { fingerprint; message = ''; passphrase = ''; submitted = false; success = false; errorMessage = ''; result = ''; constructor( private storageService: StorageService, private securityService: SecurityService ) { } ngOnInit(): void { } onSubmit(): void { this.submitted = true; this.securityService.sign(this.message,this.storageService.getPrivateKey(this.fingerprint),this.passphrase).subscribe( data => { this.result = data.result; }, error => {this.errorMessage = error.message}, () => {this.submitted= false; this.success = true;} ) } changeFingerprint(fingerprint): void { this.fingerprint = this.storageService.privateKeyExists(fingerprint) ? fingerprint : null; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { SecurityService } from '../services/security.service'; @Component({ selector: 'app-password-cracker', templateUrl: './password-cracker.component.html', styleUrls: ['./password-cracker.component.css'] }) export class PasswordCrackerComponent implements OnInit { types = ['dictionary', 'bruteforce', 'hybrid']; algorithms = ['md5', 'sha1', 'ripemd160', 'sha256', 'sha384', ]; constructor(private securityService:SecurityService) { } ngOnInit(): void { } algorithm:string="Select Algorithm"; password:string; crackedPassword:string; attackChoice:string="Select Attack Type"; notfound; errorMessage; loading=false; cracker(){ this.loading=true; this.notfound=false; this.securityService.cracker(this.password,this.attackChoice,this.algorithm).subscribe((crackedPassword)=>{ if(crackedPassword.password=="<PASSWORD>"){ this.notfound=true; } else{ this.notfound=false; this.crackedPassword=<PASSWORD>; } this.loading=false; },error => {this.errorMessage = error.message},); } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { MDBBootstrapModule } from 'angular-bootstrap-md'; import { ButtonsModule, WavesModule, CardsModule } from 'angular-bootstrap-md'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { EncoderDecoderComponent } from './encoder-decoder/encoder-decoder.component'; import { HasherComponent } from './hasher/hasher.component'; import { PasswordCrackerComponent } from './password-cracker/password-cracker.component'; import { MainComponent } from './main/main.component'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { BadgeModule, IconsModule } from 'angular-bootstrap-md'; import { SymmetricComponent } from './symmetric/symmetric.component'; import { AsymmetricComponent } from './asymmetric/asymmetric.component'; import { SymmetricEncryptionComponent } from './symmetric/symmetric-encryption/symmetric-encryption.component'; import { SymmetricDecryptionComponent } from './symmetric/symmetric-decryption/symmetric-decryption.component'; import { GenKeysComponent } from './asymmetric/gen-keys/gen-keys.component'; import { ListKeysComponent } from './asymmetric/list-keys/list-keys.component'; import { ImportKeysComponent } from './asymmetric/import-keys/import-keys.component'; import { AsymmetricEncryptionComponent } from './asymmetric/asymmetric-encryption/asymmetric-encryption.component'; import { AsymmetricDecryptionComponent } from './asymmetric/asymmetric-decryption/asymmetric-decryption.component'; import { SignComponent } from './asymmetric/sign/sign.component'; import { VerifyComponent } from './asymmetric/verify/verify.component'; import { ImportOwnComponent } from './asymmetric/import-own/import-own.component'; import { ImportFromComponent } from './asymmetric/import-keys/import-from/import-from.component'; @NgModule({ declarations: [ AppComponent, EncoderDecoderComponent, HasherComponent, PasswordCrackerComponent, MainComponent, SymmetricComponent, AsymmetricComponent, SymmetricEncryptionComponent, SymmetricDecryptionComponent, GenKeysComponent, ListKeysComponent, ImportKeysComponent, AsymmetricEncryptionComponent, AsymmetricDecryptionComponent, SignComponent, VerifyComponent, ImportOwnComponent, ImportFromComponent ], imports: [ BrowserModule, AppRoutingModule, MDBBootstrapModule.forRoot(), CardsModule, WavesModule, IconsModule, BadgeModule, ButtonsModule, FormsModule, HttpClientModule ], providers: [HttpClientModule], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class SecurityService { constructor(private http: HttpClient) { } routeEndpoint = ''; encoder(word:string): Observable<any> { this.routeEndpoint="base64encode"; return this.http.post<any>(environment.baseURL + this.routeEndpoint, {message:word}) } decoder(word:string): Observable<any> { this.routeEndpoint="base64decode"; return this.http.post<any>(environment.baseURL + this.routeEndpoint, {message:word}) } hash(word:string,algorithm:string): Observable<any>{ this.routeEndpoint="hash"; return this.http.post<any>(environment.baseURL + this.routeEndpoint, {message:word,algorithm:algorithm }); } cracker(hash:string,type:string,algorithm): Observable<any>{ this.routeEndpoint="crack/"+type; return this.http.post<any>(environment.baseURL + this.routeEndpoint, {message:hash,algorithm:algorithm }); } symEncrypt(message: string, algorithm: string, passphrase: string): Observable<any> { this.routeEndpoint = 'symetrique/chiffrer'; return this.http.post<any>(environment.baseURL+this.routeEndpoint,{message : message, algorithm: algorithm, password: <PASSWORD>}) } symDecrypt(message: string, passphrase: string): Observable<any> { this.routeEndpoint = 'symetrique/dechiffrer'; return this.http.post<any>(environment.baseURL+this.routeEndpoint,{encrypted : message, password: <PASSWORD>}); } genKeys(passphrase: string, algorithm: string): Observable<any> { this.routeEndpoint = 'asymetrique/genkeys'; return this.http.post<any>(environment.baseURL + this.routeEndpoint, {passphrase: passphrase, algorithm: algorithm}); } importKey(fingerprint: string): Observable<any> { this.routeEndpoint= 'asymetrique/import'; return this.http.get<any>(environment.baseURL+this.routeEndpoint+'?fingerprint='+fingerprint); } importOwnKey(publicKey: string): Observable<any> { this.routeEndpoint= 'asymetrique/import'; return this.http.post<any>(environment.baseURL+this.routeEndpoint,{public: publicKey}) } asymEncrypt(message: string, publicKey: string): Observable<any> { this.routeEndpoint = 'asymetrique/chiffrer'; return this.http.post<any>(environment.baseURL+this.routeEndpoint,{message: message, recipient_public_key_data: publicKey}); } asymDecrypt(message: string, privateKey: string, passphrase: string): Observable<any> { this.routeEndpoint = 'asymetrique/dechiffrer'; return this.http.post<any>(environment.baseURL+this.routeEndpoint,{encrypted: message, local_private_key_data: privateKey, passphrase: passphrase}) } sign(message: string, privateKey: string, passphrase: string,): Observable<any> { this.routeEndpoint= 'asymetrique/sign'; return this.http.post<any>(environment.baseURL+this.routeEndpoint,{message: message, passphrase: <PASSWORD>, local_private_key_data: privateKey}); } verify(encrypted: string, signer_public_key: string): Observable<any> { this.routeEndpoint = 'asymetrique/verify'; return this.http.post<any>(environment.baseURL+this.routeEndpoint,{encrypted,signer_public_key}); } } <file_sep>import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class StorageService { constructor() { } saveKeys(fingerprint: string, privateKey: string, publicKey: string): void { localStorage.setItem(fingerprint,JSON.stringify( { 'publicKey' : publicKey, 'privateKey' : privateKey } )); this.addFingerprint(fingerprint); } private addFingerprint(fingerprint: string) { const fingerprints = localStorage.getItem('fingerprints'); if (!fingerprints) { localStorage.setItem('fingerprints',JSON.stringify([fingerprint])); } else { const fingerprintsArray = JSON.parse(fingerprints); fingerprintsArray.push(fingerprint); localStorage.setItem('fingerprints', JSON.stringify(fingerprintsArray )); } } getKeys(fingerprint: string) { return JSON.parse(localStorage.getItem(fingerprint)); } getFingerPrints() { return JSON.parse(localStorage.getItem('fingerprints')); } importKey(fingerprint:string, publicKey: string) { if (localStorage.getItem(fingerprint)==null) { localStorage.setItem(fingerprint, JSON.stringify({'publicKey':publicKey})); this.addFingerprint(fingerprint); } else { localStorage.setItem(fingerprint, JSON.stringify({'publicKey':publicKey})); } } privateKeyExists(fingerprint: string): boolean { const keys = JSON.parse(localStorage.getItem(fingerprint)); return keys && keys.privateKey ; } publicKeyExists(fingerprint: string): boolean { const keys = JSON.parse(localStorage.getItem(fingerprint)); return keys && keys.publicKey ; } getPublicKey(fingerprint: string): string { const keys = JSON.parse(localStorage.getItem(fingerprint)); return keys.publicKey; } getPrivateKey(fingerprint: string): string { return (JSON.parse(localStorage.getItem(fingerprint))).privateKey; } } <file_sep>import { StorageService } from './../../services/storage.service'; import { SecurityService } from './../../services/security.service'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-gen-keys', templateUrl: './gen-keys.component.html', styleUrls: ['./gen-keys.component.css'] }) export class GenKeysComponent implements OnInit { passphrase = ''; algorithms = ['RSA','DSA']; chosenAlgorithm = ''; submitted = false; errorMessage; privateKey = ''; publicKey = ''; fingerPrint = ''; success = false; constructor( private securityService: SecurityService, private storageService: StorageService ) { } ngOnInit(): void { } onSubmit(): void { this.submitted = true; this.securityService.genKeys(this.passphrase, this.chosenAlgorithm).subscribe( data => { this.fingerPrint= data.fingerprint; this.publicKey = data.public; this.privateKey = data.secret; this.storageService.saveKeys(this.fingerPrint,this.privateKey,this.publicKey); }, error => this.errorMessage = error.message, () => {this.success = true ; this.submitted = false;} ) } } <file_sep>import { SecurityService } from './../../services/security.service'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-symmetric-decryption', templateUrl: './symmetric-decryption.component.html', styleUrls: ['./symmetric-decryption.component.css'] }) export class SymmetricDecryptionComponent implements OnInit { message = ''; passphrase = ''; algorithm = ''; submitted = false; result; errorMessage; constructor( private securityService: SecurityService ) { } ngOnInit(): void { } decrypt() : void { this.submitted = true; this.securityService.symDecrypt(this.message,this.passphrase).subscribe( data => {this.submitted=false; this.result=data.result;console.log(data); this.algorithm = data.algorithm}, error => {console.log(error); this.errorMessage=error.message}, ) } } <file_sep>import { StorageService } from './../../services/storage.service'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-list-keys', templateUrl: './list-keys.component.html', styleUrls: ['./list-keys.component.css'] }) export class ListKeysComponent implements OnInit { fingerprints : string[]; chosenFingerprint = ''; chosenPublicKey = ''; chosenPrivateKey = ''; constructor( private storageService: StorageService ) { } ngOnInit(): void { this.fingerprints = this.storageService.getFingerPrints(); } setKeyData(fingerprint: string): void { const data = this.storageService.getKeys(fingerprint); if (data) { this.chosenFingerprint=fingerprint; this.chosenPrivateKey=data.privateKey; this.chosenPublicKey=data.publicKey; } } }
98b26cd547dcd8a79c87577382a9374bb5bb2928
[ "Markdown", "TypeScript" ]
18
TypeScript
ZakariaNaaija/Pentbox-GUI-Frontend
c83324e7172689cd809089ea605a8a0a6b8fc7d2
8aeb7aa12d5ed6cdb5c03fae1175d3b54f51c9d5
refs/heads/master
<repo_name>Ghoris0127/cg<file_sep>/eindopdracht/interface.py from OpenGL.GL import * from OpenGL.GLUT import * import ctypes class Interface: def __init__(self, x, y, s_hor, s_ver, c, func): self.x = x self.y = y self.s_hor = s_hor self.s_ver = s_ver self.c = c self.func = func def check_pressed(self, button, x, y, window): if button == 0 and self.x - 0.5 * self.s_hor <= x <= self.x + 0.5 * self.s_hor and self.y - 0.5 * self.s_ver <= y <= self.y + 0.5 * self.s_ver: self.func(window) def draw(self): glBegin(GL_QUADS) glColor((1, 1, 1)) glVertex((self.x - 0.5 * self.s_hor, self.y - 0.5 * self.s_ver)) glVertex((self.x + 0.5 * self.s_hor, self.y - 0.5 * self.s_ver)) glVertex((self.x + 0.5 * self.s_hor, self.y + 0.5 * self.s_ver)) glVertex((self.x - 0.5 * self.s_hor, self.y + 0.5 * self.s_ver)) glColor(self.c) glVertex((self.x - 0.5 * self.s_hor + 2, self.y - 0.5 * self.s_ver + 2)) glVertex((self.x + 0.5 * self.s_hor - 2, self.y - 0.5 * self.s_ver + 2)) glVertex((self.x + 0.5 * self.s_hor - 2, self.y + 0.5 * self.s_ver - 2)) glVertex((self.x - 0.5 * self.s_hor + 2, self.y + 0.5 * self.s_ver - 2)) glEnd() <file_sep>/eindopdracht/lines.py from window import Window from shapes import Cube, Star, Curve from interface import Interface width = 1080 height = 720 def toggle_turning(window): for shape in window.shapes: if not isinstance(shape, Curve): shape.turning = not shape.turning l = Window(width, height) cube1 = Cube(0, 0, 0, 200, (1, 0, 0), True) l.add_shape(cube1) cube2 = Cube(0, -150, 0, 100, (0, 1, 0), True) l.add_shape(cube2) star = Star(350, 0, 0, 100, (1, 0, 1), True) l.add_shape(star) interface = Interface(50, 25, 100, 50, (0, 1, 1), toggle_turning) l.add_interface(interface) curve1 = Curve((100, 100), (100, 200), (200, 200), (0.5, 0, 0.5)) curve2 = Curve((100, 100), (100, 200), (0, 200), (0.5, 0, 0.5)) curve3 = Curve((100, 300), (100, 200), (0, 200), (0.5, 0, 0.5)) curve4 = Curve((100, 300), (100, 200), (200, 200), (0.5, 0, 0.5)) l.add_shape(curve1) l.add_shape(curve2) l.add_shape(curve3) l.add_shape(curve4) l.draw() #data for testing the matrix multiplier function. #matrix_one = [[4, 0, 3], [1, -1, 7], [-3, 3, 2]] #matrix_two = [[-2, 3, 1], [2, -3, -5], [4, 0, 7]] #print(mult_matrix_matrix(matrix_one, matrix_two)) <file_sep>/eindopdracht/window.py from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import math import random import time class Window: def __init__(self, sizeX, sizeY): self.sizeX = sizeX self.sizeY = sizeY self.shapes = [] self.interfaces = [] self.rotation = 45 self.old_time = time.time() self.iso = Isometric(self) glutInit() glutInitDisplayMode(GLUT_RGB) glutInitWindowSize(sizeX, sizeY) glutCreateWindow("Eindopdracht".encode("ascii")) glOrtho(0, sizeX, sizeY, 0, -1, 1) glutDisplayFunc(self.display) glutMouseFunc(self.mouse_func) #added timer func that will update after 2 seconds glutTimerFunc(50, self.update, 1) glutKeyboardFunc(self.end) def add_shape(self, shape): self.shapes.append(shape) def add_interface(self, interface): self.interfaces.append(interface) def update(self, value): new_time = time.time() dt = new_time - self.old_time self.old_time = new_time for shape in self.shapes: shape.update(dt) glutTimerFunc(50, self.update, 1) def display(self): glClear(GL_COLOR_BUFFER_BIT) for shape in self.shapes: shape.draw(self.iso) for interface in self.interfaces: interface.draw() glFlush() glutPostRedisplay() def mouse_func(self, button, state, x, y): if state == 1: for interface in self.interfaces: interface.check_pressed(button, x, y, self) def end(self, key, x, y): exit() def draw(self): glutMainLoop() #class to wrap the methods needed for isometric calculation class Isometric(): def __init__(self, window): self.window = window #method to multiply a matrix with a vector def mult_matrix_vector(self, matrix, vector): return_matrix = [0] * len(matrix) if len(matrix[0]) == len(vector): for i in range (0, len(matrix)): for j in range(0, len(vector)): return_matrix[i] += matrix[i][j] * vector[j] return return_matrix #method to multipy a matrix with a matrix def mult_matrix_matrix(self, matrix_one, matrix_two): return_matrix = [] for i in range (0, len(matrix_one)): return_matrix.append([]) for j in range (0, len(matrix_two[0])): return_matrix[i].append(0) if len(matrix_one[0]) == len(matrix_two): for h in range (0, len(matrix_one[0])): for i in range (0, len(matrix_one)): value = 0 for j in range(0, len(matrix_one[0])): value += matrix_one[i][j] * matrix_two[j][h] return_matrix[i][h] = value return return_matrix ''' in case of symmetry the rotational matrix that we need to implement is already used to create the view. with isometric you need to use 2 rotational matrixes. One for making the camera turn around the y axis and one around the x axis. we did the bonus excersize by multiplying our matrixes so that we only need to multiply the vector with one matrix.''' def isometricisize(self, coordinate_list, x, y, object_rotation): isometric_coordinates = [] alpha = math.asin(math.tan(math.radians(30))) beta = math.radians(object_rotation + self.window.rotation) projection_matrix_one = ((math.cos(beta), 0, -1 * math.sin(beta)), (0, 1, 0), (math.sin(beta), 0, math.cos(beta))) projection_matrix_two = ((1, 0, 0), (0, math.cos(alpha), math.sin(alpha)), (0, -1 * math.sin(alpha), math.cos(alpha))) combined_matrix = self.mult_matrix_matrix(projection_matrix_two, projection_matrix_one) for coordinate in coordinate_list: matrix_calc = self.mult_matrix_vector(combined_matrix, coordinate) isometric_coordinates.append((matrix_calc[0] + 0.5 * self.window.sizeX + x, matrix_calc[1] + 0.5 * self.window.sizeY + y)) return isometric_coordinates <file_sep>/eindopdracht/shapes.py from OpenGL.GL import * class Curve: def __init__(self, p1, p2, p3, c): self.p1 = p1 self.p2 = p2 self.p3 = p3 self.c = c def update(self, dt): pass def get_coordinates(self): return_list = [] for t in range(0, 10, 1): t *= 0.1 x_coor = (1 - t) ** 2 * self.p1[0] + 2 * (1 - t) * t * self.p2[0] + t ** 2 * self.p3[0] y_coor = (1 - t) ** 2 * self.p1[1] + 2 * (1 - t) * t * self.p2[1] + t ** 2 * self.p3[1] return_list.append((int(x_coor), int(y_coor))) return return_list def draw(self, perspective): glBegin(GL_LINE_STRIP) glColor(self.c) for coordinate in self.get_coordinates(): glVertex(coordinate) glEnd() class Star: vertices = [[0, -1, 0], [-0.95, -0.31, 0], [-0.59, 0.81, 0], [0.59, 0.81, 0], [0.95, -0.31, 0]] edges = ((0, 2), (2, 4), (4, 1), (1, 3), (3, 0)) def __init__(self, x, y, z, s, c, turning): self.x = x # x coordinate self.y = y # y coordinate self.z = z # z coordinate self.s = s # s (scale) self.c = c # c color (f, f, f) self.r = 0 self.turning = turning # Converts vertices to coordinates in the world def return_vertex_coordinates(self): return_coordinates = [] for vertex in self.vertices: new_x = vertex[0] * 0.5 * self.s new_y = vertex[1] * 0.5 * self.s new_z = vertex[2] * 0.5 * self.s return_coordinates.append((new_x, new_y, new_z)) return return_coordinates #returns the list with edgess def return_edges(self): return self.edges def update(self, dt): if self.turning: self.r -= 100 * dt def draw(self, perspective): #makes the isometric representation for an array of coordinates taking the current rotation into account isometric_coordinates = perspective.isometricisize(self.return_vertex_coordinates(), self.x, self.y, self.r) #draws lines between the calculated coordinates glBegin(GL_LINES) glColor(self.c) for edge in self.edges: glVertex(isometric_coordinates[edge[0]]) glVertex(isometric_coordinates[edge[1]]) #increases rotation for one glEnd() class Cube: # vertices related from the middle of the cube vertices = ((1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, -1), (1, -1, 1), (1, 1, 1), (-1, -1, 1), (-1, 1, 1)) # edges to show which vertex connects to which other vertex edges = ((0,1), (0,3), (0,4), (2,1), (2,3), (2,7), (6,3), (6,4), (6,7), (5,1), (5,4), (5,7)) surfaces = ((0,1,2,3), (3,2,7,6), (6,7,5,4), (4,5,1,0), (1,5,7,2), (4,0,3,6)) def __init__(self, x, y, z, s, c, turning): self.x = x # x coordinate self.y = y # y coordinate self.z = z # z coordinate self.s = s # s (scale) self.c = c # c color (f, f, f) self.r = 45 self.turning = turning # Converts vertices to coordinates in the world def return_vertex_coordinates(self): return_coordinates = [] for vertex in self.vertices: new_x = vertex[0] * 0.5 * self.s new_y = vertex[1] * 0.5 * self.s new_z = vertex[2] * 0.5 * self.s return_coordinates.append((new_x, new_y, new_z)) return return_coordinates #returns the list with edgess def return_edges(self): return self.edges def update(self, dt): if self.turning: self.r += 100 * dt def draw(self, perspective): #makes the isometric representation for an array of coordinates taking the current rotation into account isometric_coordinates = perspective.isometricisize(self.return_vertex_coordinates(), self.x, self.y, self.r) #draws lines between the calculated coordinates glBegin(GL_QUADS) glColor(self.c) for surface in self.surfaces: for vertex in surface: glVertex(isometric_coordinates[vertex]) glEnd() glBegin(GL_LINES) glColor((1, 1, 1)) for edge in self.edges: glVertex(isometric_coordinates[edge[0]]) glVertex(isometric_coordinates[edge[1]]) #increases rotation for one glEnd()
f40f4f67159419e0010f98936a1afa3f58fd3e17
[ "Python" ]
4
Python
Ghoris0127/cg
2e3c3ce60602ed15a5ee5833aa0dd083a9f152c5
163ec704fe086d96475e8fa388095648e75763b3
refs/heads/master
<file_sep>#ifndef INCLUDE_TOML_PARSER_HPP #define INCLUDE_TOML_PARSER_HPP #include <exception> #include <functional> #include <string_view> #include "parser.h" #include "constant.h" extern "C" { int toml__internal_on_section( toml__internal_t* s, const unsigned char* p, const unsigned char* endp); int toml__internal_on_field( toml__internal_t* s, const unsigned char* p, const unsigned char* endp); int toml__internal_on_value( toml__internal_t* s, const unsigned char* p, const unsigned char* endp); int toml__internal_on_after_value( toml__internal_t* s, const unsigned char* p, const unsigned char* endp); int toml__internal_on_entry_push( toml__internal_t* s, const unsigned char* p, const unsigned char* endp); int toml__internal_on_entry_pop( toml__internal_t* s, const unsigned char* p, const unsigned char* endp); } namespace llparse::toml { class parser; struct parser_setting_s { std::function<void (const parser& p, std::string_view chunk)> on_value; std::function<void (const parser& p)> on_after_value; // ๆ•ฐๆฎๅฎŒ็ป“ }; typedef struct parser_setting_s parser_setting_t; class parser { public: parser(const parser_setting_t& setting) noexcept; void parse(std::string_view str); void reset(); std::string field() const noexcept; std::uint8_t value_type() const noexcept; std::uint32_t value_array_index() const noexcept; private: toml__internal_t parser_; parser_setting_t setting_; std::vector<std::string> prefix_; std::string field_; std::vector<std::uint8_t> container_; std::vector<std::uint32_t> index_; // ๅ‰็ผ€ friend int ::toml__internal_on_section(toml__internal_t* s, const unsigned char* p, const unsigned char* endp); // ๅญ—ๆฎต friend int ::toml__internal_on_field(toml__internal_t* s, const unsigned char* p, const unsigned char* endp); // friend int ::toml__internal_on_after_field(toml__internal_t* s, const unsigned char* p, const unsigned char* endp); // ๆ•ฐๆฎ friend int ::toml__internal_on_value(toml__internal_t* s, const unsigned char* p, const unsigned char* endp); friend int ::toml__internal_on_after_value(toml__internal_t* s, const unsigned char* p, const unsigned char* endp); // ๅฑ‚็บง friend int ::toml__internal_on_entry_push(toml__internal_t* s, const unsigned char* p, const unsigned char* endp); friend int ::toml__internal_on_entry_pop(toml__internal_t* s, const unsigned char* p, const unsigned char* endp); }; class unknown_error: public std::exception { public: unknown_error(const char* where) : where_(where) { } const char* what() const noexcept; private: std::string where_; }; class unexpected_token: public std::exception { public: unexpected_token(char token, const char* where) : token_(token) , where_(where) { } const char* what() const noexcept; private: std::string where_; char token_; }; } #endif /* INCLUDE_TOML_PARSER_HPP */ <file_sep>.PHONY: all var clean install ENVIRON?=stage VERSION=1.0.2 CXX?=g++ AR?=ar NODE?=/data/server/node/bin/node CFLAGS?= -g -O0 CFLAGS+= -fPIC -std=c11 CXXFLAGS?= -g -O0 CXXFLAGS+= -fPIC -std=c++17 TESTORS_SOURCES := $(wildcard ./test/*.cpp) TARGETS := $(patsubst ./test/%.cpp,%,${TESTORS_SOURCES}) TESTORS := $(patsubst ./test/%.cpp,./${ENVIRON}/%.test,${TESTORS_SOURCES}) all: ${TESTORS} ./${ENVIRON}/liblltoml.a | ${ENVIRON} ${ENVIRON}: mkdir -p ./${ENVIRON} for name in ${TARGETS} ; \ do \ mkdir -p "./${ENVIRON}/$$name"; \ done SOURCES := $(wildcard $(foreach target,${TARGETS},./src/${target}/*.cpp)) DEFINES := $(foreach target,${TARGETS},./src/${target}/parser.mjs) PARSERS := $(foreach target,${TARGETS},./src/${target}/parser.c) OBJECTS := $(patsubst ./src/%.c,./${ENVIRON}/%.c.o, ${PARSERS}) $(patsubst ./src/%.cpp,./${ENVIRON}/%.cpp.o, ${SOURCES}) .PHONY: ${ENVIRON} var clean install var: @echo TESTORS = [${TESTORS}] @echo SOURCES = [${SOURCES}] @echo DEFINES = [${DEFINES}] @echo PARSERS = [${PARSERS}] @echo OBJECTS = [${OBJECTS}] clean: rm -rf ./${ENVIRON} install: mkdir -p /data/vendor/lltoml-${VERSION}/include/toml mkdir -p /data/vendor/lltoml-${VERSION}/lib cp ./src/toml/*.hpp /data/vendor/lltoml-${VERSION}/include/toml cp ./src/toml/*.h /data/vendor/lltoml-${VERSION}/include/toml cp ./${ENVIRON}/liblltoml.a /data/vendor/lltoml-${VERSION}/lib ./${ENVIRON}/%.c.o: ./src/%.c | ${ENVIRON} ${CXX} -x c ${CFLAGS} -c $^ -o $@ ./${ENVIRON}/%.cpp.o: ./src/%.cpp | ${ENVIRON} ${CXX} ${CXXFLAGS} -c $^ -o $@ ./src/%.c: ./src/%.mjs ${NODE} --experimental-modules $^ ./${ENVIRON}/%.test: ./test/%.cpp ${OBJECTS} | ${ENVIRON} ${CXX} ${CXXFLAGS} -o $@ $^ ./${ENVIRON}/liblltoml.a: ${OBJECTS} | ${ENVIRON} ${AR} rcs $@ $^ <file_sep>"use strict"; import llparse from 'llparse'; import { promises as fs } from 'fs'; import { dirname } from "path"; import { fileURLToPath } from "url"; const ERRORS = Object.fromEntries([ "ERROR_SUCCESS", "ERROR_UNEXPECTED_TOKEN", "ERROR_UNKNOWN_ERROR", ].map((v, i) => [v, i])); const VALUE_TYPES = Object.fromEntries([ "VALUE_TYPE_UNKNOWN", "VALUE_TYPE_BOOLEAN", "VALUE_TYPE_INTEGER", "VALUE_TYPE_HEX_INTEGER", "VALUE_TYPE_OCT_INTEGER", "VALUE_TYPE_BIN_INTEGER", "VALUE_TYPE_FLOAT", "VALUE_TYPE_INFINITY", "VALUE_TYPE_NAN", "VALUE_TYPE_DATE", "VALUE_TYPE_BASIC_STRING", "VALUE_TYPE_RAW_STRING", ].map((v, i) => [v, i])); const CONTAINER_TYPES = Object.fromEntries([ "CONTAINER_TYPE_TABLE", "CONTAINER_TYPE_ARRAY", "CONTAINER_TYPE_ARRAY_TABLE", ].map((v, i) => [v, i])); const parser = new llparse.LLParse("toml__internal"); function E(name, where) { if(ERRORS[name]) return parser.error(ERRORS[name], where); else throw new Error("undefined error '" + name + "'"); } // ๅฑžๆ€ง parser.property("i8", "value_type"); parser.property("i8", "container_type"); parser.property("i32", "array_index"); // ๅˆๅง‹ // ๅ‰็ผ€ const type_prefix = parser.node("before_prefix_table"); const before_prefix = parser.node("before_prefix"); const on_prefix_start = parser.invoke(parser.code.match("toml__internal_on_section"), before_prefix); const on_prefix = parser.span(parser.code.span("toml__internal_on_field")); const prefix_basic = parser.node("prefix_basic"); const prefix_quote = parser.node("prefix_quote"); const after_prefix = parser.node("after_prefix"); const after_prefix_next = parser.node("after_prefix_next"); const after_prefix_which = parser.node("after_prefix_which"); // ๅญ—ๆฎต const before_field = parser.node("before_field"); const on_before_field = parser.invoke(parser.code.update("value_type", VALUE_TYPES["VALUE_TYPE_UNKNOWN"]), before_field); // const on_field = parser.span(parser.code.span("toml__internal_on_field")); const on_field = on_prefix; const field_quote = parser.node("field_quote"); const field_basic = parser.node("field_basic"); const after_field = parser.node("after_field"); // const on_after_field = parser.invoke(parser.code.match("toml__internal_on_after_field"), after_field); const on_after_field = after_field; const after_field_next = parser.node("after_field_next"); const after_field_expect_equal = parser.node("after_field_expect_equal"); const after_field_expect_field = parser.node("after_field_expect_equal"); // ็ฌฆๅท const before_equal = parser.node("before_equal"); const equal = parser.node("equal"); const after_equal = parser.node("after_equal"); // ๅ€ผ const before_value = parser.node("before_value"); const on_before_value = parser.invoke(parser.code.update("value_type", VALUE_TYPES["VALUE_TYPE_UNKNOWN"]), before_value); const on_value = parser.span(parser.code.span("toml__internal_on_value")); // ๅ€ผ - ๆ— ๅˆ†้š”็ฌฆ const value_unknown = parser.node("value_unknown"); const value_boolean = parser.node("value_boolean"); const on_value_boolean = parser.invoke(parser.code.update("value_type", VALUE_TYPES["VALUE_TYPE_BOOLEAN"]), value_boolean); const value_integer = parser.node("value_integer"); const on_value_integer = parser.invoke(parser.code.update("value_type", VALUE_TYPES["VALUE_TYPE_INTEGER"]), value_integer); const value_hex_integer = parser.node("value_hex_integer"); const on_value_hex_integer = parser.invoke(parser.code.update("value_type", VALUE_TYPES["VALUE_TYPE_HEX_INTEGER"]), value_hex_integer); const value_oct_integer = parser.node("value_oct_integer"); const on_value_oct_integer = parser.invoke(parser.code.update("value_type", VALUE_TYPES["VALUE_TYPE_OCT_INTEGER"]), value_oct_integer); const value_bin_integer = parser.node("value_bin_integer"); const on_value_bin_integer = parser.invoke(parser.code.update("value_type", VALUE_TYPES["VALUE_TYPE_BIN_INTEGER"]), value_bin_integer); const value_float = parser.node("value_float") const on_value_float = parser.invoke(parser.code.update("value_type", VALUE_TYPES["VALUE_TYPE_FLOAT"]), value_float); const value_infinite = parser.node("value_infinite"); const on_value_infinite = parser.invoke(parser.code.update("value_type", VALUE_TYPES["VALUE_TYPE_INFINITY"]), value_infinite); const value_date = parser.node("value_date"); const before_value_date = parser.node("before_value_date"); const on_value_date = parser.invoke(parser.code.update("value_type", VALUE_TYPES["VALUE_TYPE_DATE"]), value_date); const after_value_date = parser.node("after_value_date"); // ๅ€ผ - ๆœ‰ๅˆ†้š”็ฌฆ const before_value_basic_string = parser.node("before_value_basic_string"); const on_before_value_basic_string = parser.invoke(parser.code.update("value_type", VALUE_TYPES["VALUE_TYPE_BASIC_STRING"]), before_value_basic_string); const value_basic_string = parser.node("value_basic_string"); const after_value_basic_string = parser.node("after_value_basic_string"); const value_multi_basic_string = parser.node("value_multi_basic_string"); const value_multi_basic_string_concat = parser.node("value_multi_basic_string"); const after_value_multi_basic_string = parser.node("after_value_multi_basic_string"); const before_value_raw_string = parser.node("before_value_raw_string"); const on_before_value_raw_string = parser.invoke(parser.code.update("value_type", VALUE_TYPES["VALUE_TYPE_RAW_STRING"]), before_value_raw_string); const value_raw_string = parser.node("value_raw_string"); const after_value_raw_string = parser.node("after_value_raw_string"); const value_multi_raw_string = parser.node("value_multi_raw_string"); const after_value_multi_raw_string = parser.node("after_value_multi_raw_string"); // ็ป“ๆŸ const after_value_expect_field = parser.node("after_value_expect_field"); const after_value_expect_value = parser.node("after_value_expect_value"); const on_after_value_which = parser.invoke(parser.code.load("container_type"), {2: after_value_expect_field, 1: after_value_expect_value, 0: after_value_expect_field}, E("ERROR_UNKNOWN_ERROR", "after_value")); const on_after_value = parser.invoke(parser.code.match("toml__internal_on_after_value"), on_after_value_which); // ๅฎนๅ™จ ๆ•ฐ็ป„ใ€่กจๆ ผ ๅฑ‚็บงๅ…ณ็ณปๅค„็† const on_cstart_array = parser.invoke(parser.code.update("container_type", CONTAINER_TYPES["CONTAINER_TYPE_ARRAY"]), parser.invoke(parser.code.match("toml__internal_on_entry_push"), on_before_value)); const on_cstart_table = parser.invoke(parser.code.update("container_type", CONTAINER_TYPES["CONTAINER_TYPE_TABLE"]), parser.invoke(parser.code.match("toml__internal_on_entry_push"), on_before_field)); const on_cstart_array_table = parser.invoke(parser.code.update("container_type", CONTAINER_TYPES["CONTAINER_TYPE_ARRAY_TABLE"]), parser.invoke(parser.code.match("toml__internal_on_entry_push"), on_before_field)); // const before_cfinish = parser.node("before_cfinish"); const on_cfinish = parser.invoke(parser.code.match("toml__internal_on_entry_pop"), on_after_value_which); // on_entry_pop ้œ€่ฆ็ปดๆŠค, ไธๅ†่ฐƒ็”จ on_after_value const on_cfinish_before_field = parser.invoke(parser.code.match("toml__internal_on_entry_pop"), on_before_field); // on_entry_pop ้œ€่ฆ็ปดๆŠค๏ผŒไธ‹ไธ€ไธช่Š‚้ฉฌไธŠๅผ€ๅง‹ // ๆณจ้‡Š const comment_expect_field = parser.node("begin_comment_expect_field"); const comment_expect_equal = parser.node("begin_comment_expect_equal"); const comment_expect_value = parser.node("begin_comment_expect_value"); // ๅ‰็ผ€ // -------------------------------------------------------------------------------- type_prefix .match("[[", on_prefix_start) .otherwise(on_prefix_start); before_prefix // .skipTo(comment_expect_field) .peek(["#", "]"], E("ERROR_UNEXPECTED_TOKEN", "before_prefix")) .match([" ", "\t"], before_prefix) .match('"', on_prefix.start(prefix_quote)) // on_prefix ๅฎž้™…ไธŠไธŽ on_field ๆ˜ฏๅŒไธ€ไธช SPAN , ๅŒบๅˆซๅœจ cstart ๅŽ็š„่ฝฌๆข่ฟ‡็จ‹ .otherwise(on_prefix.start(prefix_basic)); prefix_basic .peek(["#", "\r", "\n"], E("ERROR_UNEXPECTED_TOKEN", "prefix_basic")) .peek([".", " ", "\t", "]"], on_prefix.end(after_prefix)) .skipTo(prefix_basic); prefix_quote .peek("\"", on_prefix.end(after_prefix)) .skipTo(prefix_quote); after_prefix .match([" ", "\t", "\r", "\n"], after_prefix) .peek("]", after_prefix_which) .peek('.', on_prefix.start(after_prefix_next)) .otherwise(E("ERROR_UNEXPECTED_TOKEN", "after_prefix")); after_prefix_which .match("]]", on_cstart_array_table) .skipTo(on_cstart_table) after_prefix_next .skipTo(on_prefix.end(before_prefix)); // ๅญ—ๆฎต // -------------------------------------------------------------------------------- before_field // <-- after_field / after_value .match([" ", "\t", "\r", "\n"], before_field) .peek("#", comment_expect_field) .match("[", type_prefix) .match("\"", on_field.start(field_quote)) .otherwise(on_field.start(field_basic)); field_basic .peek([".", " ", "\t", "]", "=", "#", "\r", "\n"], on_field.end(on_after_field)) .skipTo(field_basic); field_quote .peek("\"", on_field.end(on_after_field)) .skipTo(field_quote); after_field .match(["\"", " ", "\t"], after_field_expect_equal) .peek(".", on_field.start(after_field_next)) // ๅญ็บง key ไธๆ”นๅ˜ๆ•ฐๆฎ็ฑปๅž‹ .match("]", after_field_expect_field) // .peek("#", comment_expect_equal) // ไธๅ…่ฎธๅ‡บ็Žฐๆญค็งๆƒ…ๅ†ต AAAA #CCCCC \n = BBBBB .otherwise( before_equal ); after_field_next .skipTo(on_field.end(before_field)) after_field_expect_equal .match([" ", "\t"], after_field_expect_equal) .otherwise(before_equal); after_field_expect_field .match([" ", "\t"], after_field_expect_field) .otherwise(on_before_field); // ๆณจๆ„้‡็ฝฎๆ•ฐๆฎ็ฑปๅž‹ // ็ฌฆๅท // -------------------------------------------------------------------------------- before_equal .peek(["\r", "\n"], E("ERROR_UNEXPECTED_TOKEN", "before_equal")) // ไธๅ…่ฎธๅ‡บ็Žฐๆญค็งๆƒ…ๅ†ต AAAA \n = BBBBB .match([" ", "\t"], before_equal) .peek("#", comment_expect_equal) .otherwise(equal); equal .match("=", after_equal) .otherwise(E("ERROR_UNEXPECTED_TOKEN", "equal")); after_equal .match([" ", "\t"], after_equal) .peek("#", comment_expect_value) .peek(["\r", "\n"], E("ERROR_UNEXPECTED_TOKEN", "after_equal")) .otherwise(before_value); // ๅ€ผ // -------------------------------------------------------------------------------- before_value .match([" ", "\t"], before_value) .peek(["\r", "\n"], E("ERROR_UNEXPECTED_TOKEN", "before_value")) // 0 ๆฏ”่พƒ็‰นๅˆซ๏ผˆ0x/0o/0b) .match("+", on_value.start(on_value_integer)) .peek(["-", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], on_value.start(on_value_integer)) .peek("t", on_value.start(on_value_boolean)) // true .peek("f", on_value.start(on_value_boolean)) // false .match("[", on_cstart_array) .match("{", on_cstart_table) // ๅพ…็กฎ่ฎคๆ˜ฏๅฆๆœชๅคš่กŒๆ–‡ๆœฌ .peek('"', on_before_value_basic_string) .peek("'", on_before_value_raw_string) .peek("#", comment_expect_value) .otherwise(on_value.start(value_unknown)) value_unknown .match(["-", ":"], on_value_date) .peek([",", "]", "}", " ", "\t", "#", "\r", "\n"], on_value.end(on_after_value)) .skipTo(value_unknown); value_boolean .match(["true", "false"], on_value.end(on_after_value)) .otherwise(E("ERROR_UNEXPECTED_TOKEN", "value_boolean")); value_integer .peek([",", "]", "}", " ", "\t", "#", "\r", "\n"], on_value.end(on_after_value)) .match("x", on_value_hex_integer) .match("o", on_value_oct_integer) .match("b", on_value_bin_integer) .match("+inf", on_value_infinite) .peek("-", before_value_date) .match("inf", on_value_infinite) .match("e-", on_value_float) .match("e+", on_value_float) .match("E-", on_value_float) .match("E+", on_value_float) .match(":", on_value_date) .match(".", on_value_float) .skipTo(value_integer); value_hex_integer .match(["_", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"], value_hex_integer) .otherwise(on_value.end(on_after_value)); value_oct_integer .match(["_", "0", "1", "2", "3", "4", "5", "6", "7"], value_hex_integer) .otherwise(on_value.end(on_after_value)); value_bin_integer .match(["_", "0", "1"], value_hex_integer) .otherwise(on_value.end(on_after_value)); value_infinite .otherwise(on_value.end(on_after_value)); value_float .peek([",", "]", "}", " ", "t", "#", "\r", "\n"], on_value.end(on_after_value)) .skipTo(value_float); before_value_date .match("-inf", on_value_infinite) .otherwise(value_date) value_date .peek(" ", after_value_date) // ๅฏ่ƒฝๆ˜ฏ็ป“ๆŸ็ฌฆๅท .peek([",", "]", "}", "\t", "#", "\r", "\n"], on_value.end(on_after_value)) .skipTo(value_date); after_value_date .match([" 0", " 1", " 2"], value_date) // ๅˆ็†็š„ไธ‰็งๅฝขๅผ .otherwise(on_value.end(on_after_value)); // ๅ…ถไป–ๅฝขๅผ็ป“ๆŸๅŒน้… // ๅ€ผ - ๅˆ†้š”็ฌฆ // ---------------------------------------------------------------------------------------------------- before_value_basic_string .match('"""', on_value.start(value_multi_basic_string)) // match at least .otherwise(on_value.start(value_basic_string)); // '"' value_basic_string .peek('"', on_value.end(after_value_basic_string)) .peek(["\r", "\n"], E("ERROR_UNEXPECTED_TOKEN", "value_basic_string")) .skipTo(value_basic_string); after_value_basic_string .match('"', on_after_value) .otherwise(E("ERROR_UNEXPECTED_TOKEN", "after_value_basic_string")); value_multi_basic_string .peek('"', on_value.end(after_value_multi_basic_string)) // ๆš‚ๅœ่งฃๆž๏ผŒไฝ†ๆœ‰ๅฏ่ƒฝๆขๅค .peek("\\", on_value.end(value_multi_basic_string_concat)) // ๅˆ†่กŒไนฆๅ†™้•ฟๆ–‡ๆœฌ .skipTo(value_multi_basic_string); value_multi_basic_string_concat // ็”จไบŽๅ•่กŒ้•ฟๆ–‡ๆœฌ .match("\\\r\n", on_value.start(value_multi_basic_string)) .match("\\\n", on_value.start(value_multi_basic_string)) .otherwise(on_value.start(value_multi_basic_string)) after_value_multi_basic_string .match('"""', on_after_value) .otherwise(on_value.start(value_multi_basic_string)); // ๆœชๅŒน้…็ป“ๆŸ็ฌฆ๏ผŒๆขๅค before_value_raw_string .match("'''", on_value.start(value_multi_raw_string)) .otherwise(on_value.start(value_raw_string)); value_raw_string .peek("'", on_value.end(after_value_raw_string)) .skipTo(value_raw_string); after_value_raw_string .match("'", on_after_value) .otherwise(E("ERROR_UNEXPECTED_TOKEN", "after_value_raw_string")); value_multi_raw_string .peek("'", on_value.end(after_value_multi_raw_string)) // ๆš‚ๅœ่งฃๆž๏ผŒไฝ†ๆœ‰ๅฏ่ƒฝๆขๅค .skipTo(value_multi_raw_string); after_value_multi_raw_string .match("'''", on_after_value) .otherwise(on_value.start(value_multi_raw_string)); // ๆœชๅŒน้…็ป“ๆŸ็ฌฆ๏ผŒๆขๅค after_value_expect_field .match([",", " ", "\t", "\r", "\n"], after_value_expect_field) // ไธๅ…่ฎธๅœจ value ๅŽ็ปง็ปญๅฎšไน‰ field ๅฟ…้กปๆข่กŒ .match(["}"/*, "]"*/], on_cfinish) // ๅฎนๅ™จ็ป“ๆŸ๏ผŒ้œ€่ฆๅ›žๅˆฐไธŠไธ€ๅฑ‚ .peek("]", E("ERROR_UNEXPECTED_TOKEN", "after_value")) .peek("#", comment_expect_field) .peek("[", on_cfinish_before_field) .otherwise(on_before_field); after_value_expect_value .match([",", " ", "\t", "\r", "\n"], after_value_expect_value) .match([/*"}",*/ "]"], on_cfinish) // ๅฎนๅ™จ็ป“ๆŸ๏ผŒ้œ€่ฆๅ›žๅˆฐไธŠไธ€ๅฑ‚ .peek("}", E("ERROR_UNEXPECTED_TOKEN", "after_value")) .peek("#", comment_expect_value) // .peek("[", on_cfinish_before_field) .otherwise(on_before_value); // ๆณจ้‡Š // ---------------------------------------------------------------------------------------------- comment_expect_field .match(["\r", "\n"], on_before_field) // .match("#", comment_expect_field) .skipTo(comment_expect_field); comment_expect_equal .match(["\r", "\n"], before_equal) // .match("#", comment_expect_equal) .skipTo(comment_expect_equal); comment_expect_value .match(["\r", "\n"], before_value) // .match("#", comment_expect_value) .skipTo(comment_expect_value); const __dirname = dirname(fileURLToPath(import.meta.url)); async function constant_header() { let header = "#ifndef TOML__INTERNAL_CONSTANT_H\n#define TOML__INTERNAL_CONSTANT_H\n\n#include <cstdint>\n\n"; header += "namespace llparse::toml {\n"; header += "\n\tenum error_t: std::uint8_t {\n"; for(let key in ERRORS) { header += "\t\t" + key.padEnd(16) + " = " + ERRORS[key] + ",\n"; } header += "\t};\n" header += "\n\tenum container_type_t: std::uint8_t {\n"; for(let key in CONTAINER_TYPES) { header += "\t\t" + key.padEnd(16) + " = " + CONTAINER_TYPES[key] + ",\n"; } header += "\t};\n"; header += "\n\tenum value_type_t: std::uint8_t {\n"; for(let key in VALUE_TYPES) { header += "\t\t" + key.padEnd(16) + " = " + VALUE_TYPES[key] + ",\n"; } header += "\t};\n"; header += "}\n#endif // TOML__INTERNAL_CONSTANT_H\n"; await fs.writeFile(__dirname + "/constant.h", header); } async function build() { const art = parser.build(before_field, {"c": { "header": "parser", }}); await fs.writeFile(__dirname + "/parser.h", art.header); await fs.writeFile(__dirname + "/parser.c", art.c); await constant_header(); console.log("parser source and constant header generated."); } build().catch((error) => { console.log(error); process.exit(-1); }); <file_sep>#include "toml.hpp" #include <cstdio> #include <string_view> #include "error.h" extern "C" { // ๅ‰็ผ€ // --------------------------------------------------------------------------------------------------------------------- int toml__internal_on_section(toml__internal_t* s, const unsigned char* p, const unsigned char* endp) { auto * self = static_cast<llparse::toml::parser*>(s->data); self->prefix_.resize(1); self->index_.resize(1); s->array_index = self->index_.back(); return 0; } // ๅญ—ๆฎต // --------------------------------------------------------------------------------------------------------------------- int toml__internal_on_field(toml__internal_t* s, const unsigned char* p, const unsigned char* endp) { auto * self = static_cast<llparse::toml::parser*>(s->data); if(endp > p) { self->field_.append((const char*)p, static_cast<std::size_t>(endp - p)); } return 0; } // ๆ•ฐๆฎ // --------------------------------------------------------------------------------------------------------------------- int toml__internal_on_value(toml__internal_t* s, const unsigned char* p, const unsigned char* endp) { const auto * self = static_cast<llparse::toml::parser*>(s->data); if(endp > p) { if(self->setting_.on_value) self->setting_.on_value(*self, {(const char*) p, static_cast<std::size_t>(endp - p)}); } return 0; } int toml__internal_on_after_value(toml__internal_t* s, const unsigned char* p, const unsigned char* endp) { auto * self = static_cast<llparse::toml::parser*>(s->data); if(self->setting_.on_after_value) self->setting_.on_after_value(*self); self->field_.clear(); if(s->container_type == llparse::toml::CONTAINER_TYPE_ARRAY) s->array_index = ++self->index_.back(); return 0; } // ๅฑ‚็บงๅ…ณ็ณป // --------------------------------------------------------------------------------------------------------------------- int toml__internal_on_entry_push(toml__internal_t* s, const unsigned char* p, const unsigned char* endp) { auto * self = static_cast<llparse::toml::parser*>(s->data); // std::cout << "> on_entry1: << " << self->prefix_ << "\n"; if(self->field_.empty()) self->field_.assign("#"); else if(s->container_type == (std::uint8_t) llparse::toml::CONTAINER_TYPE_ARRAY_TABLE) self->field_.append(".#"); self->prefix_.push_back(self->field_); self->field_.clear(); if(self->container_.back() == (std::uint8_t) llparse::toml::CONTAINER_TYPE_ARRAY) { if(s->container_type == (std::uint8_t) llparse::toml::CONTAINER_TYPE_TABLE) { s->container_type = (std::uint8_t) llparse::toml::CONTAINER_TYPE_ARRAY_TABLE; } } // ๅผ€ๅง‹ไธ€ไธช ARRAY ่Š‚ if(s->container_type == (std::uint8_t) llparse::toml::CONTAINER_TYPE_ARRAY) { self->index_.back() = s->array_index; s->array_index = 0; self->index_.push_back(s->array_index); } self->container_.push_back(s->container_type); return 0; } int toml__internal_on_entry_pop(toml__internal_t* s, const unsigned char* p, const unsigned char* endp) { auto * self = static_cast<llparse::toml::parser*>(s->data); self->prefix_.pop_back(); std::uint8_t ct = self->container_.back(); self->container_.pop_back(); s->container_type = self->container_.back(); // ็ป“ๆŸ็š„ไบ†ไธ€ไธช array ่Š‚ if(ct == llparse::toml::CONTAINER_TYPE_ARRAY) { self->index_.pop_back(); s->array_index = self->index_.back(); } if(s->container_type == llparse::toml::CONTAINER_TYPE_ARRAY || // ๆœฌ่Š‚็ป“ๆŸๅŽไธŠๅฑ‚ๆ˜ฏไธ€ไธช array ่Š‚ ct == llparse::toml::CONTAINER_TYPE_ARRAY_TABLE) { // ๆœฌ่Š‚ array_table ็ป“ๆŸ s->array_index = ++self->index_.back(); } return 0; } } // extern "C" namespace llparse::toml { parser::parser(const parser_setting_t& setting) noexcept : setting_(setting) { toml__internal_init(&parser_); parser_.data = this; parser_.container_type = llparse::toml::CONTAINER_TYPE_TABLE; parser_.array_index = 0; prefix_.push_back("$"); container_.push_back((std::uint8_t) parser_.container_type); index_.push_back((std::uint32_t) parser_.array_index); } void parser::parse(std::string_view str) { switch(toml__internal_execute(&parser_, str.data(), str.data() + str.size())) { case ERROR_SUCCESS: break; case ERROR_UNEXPECTED_TOKEN: throw unexpected_token(parser_.error_pos[0], parser_.reason); default: throw unknown_error(parser_.reason); } } void parser::reset() { toml__internal_init(&parser_); container_.resize(1); } std::string parser::field() const noexcept { std::string pre = prefix_[0]; for(int i=1;i<prefix_.size();++i) { pre.push_back('.'); pre.append(prefix_[i]); } if(field_.empty()) { if(parser_.container_type == CONTAINER_TYPE_ARRAY) { pre.push_back('.'); pre.push_back('#'); } }else{ pre.push_back('.'); pre.append(field_); } return pre; } std::uint8_t parser::value_type() const noexcept { return parser_.value_type; } std::uint32_t parser::value_array_index() const noexcept { return parser_.array_index; } const char* unknown_error::what() const noexcept { static char buffer[64]; std::sprintf(buffer, "TOML parse failed: unknown error @%s", where_.c_str()); return buffer; } const char* unexpected_token::what() const noexcept { static char buffer[96]; std::sprintf(buffer, "TOML parse failed: unexpected token (0x%02x => '%c') @%s", token_, token_, where_.c_str()); return buffer; } }<file_sep>#include "../src/toml/toml.hpp" #include <cstring> #include <iostream> #include <fstream> #include <memory> template <class T> void null_deleter(T* t) {} int main(int argc, char* argv[]) { std::string value; llparse::toml::parser p({ /*.on_value = */[&value] (const llparse::toml::parser& p, std::string_view chunk) { value.append(chunk); std::cout << "= on_value: " << p.field() << " #" << p.value_array_index() << " => (" << value << ")\n"; }, /* .on_after_value = */[&value] (const llparse::toml::parser& p) { // if(p.prefix() == ".a.b.e") exit(0); std::cout << "= on_after_value: " << p.field() << " #" << p.value_array_index() << " => [" << value << "]@" << (int)p.value_type() << "\n"; value.clear(); }, }); std::string flr; std::shared_ptr<std::istream> is; if(argc > 1) is.reset(new std::ifstream(argv[1])); else is.reset(&std::cin, null_deleter<std::istream>); while(!is->eof()) { std::getline(*is, flr); flr.append("\n"); p.parse(flr); }; return 0; } <file_sep>### ไป‹็ป ๅญฆไน ๅ’Œๆต‹่ฏ• [llparse](https://github.com/nodejs/llparse) / [llhttp](https://github.com/nodejs/llhttp) ็ผ–ๅ†™็š„ [toml](https://github.com/toml-lang/toml) ่งฃๆžๅ™จ; * `llparse` - ๅฏๆ–นไพฟ็š„็”จไบŽๆ–‡ๆœฌ็ฑปๅ่ฎฎ็š„ๅขž้‡่งฃๆžๅ™จ็”Ÿๆˆ(็›ฎๅ‰ๆ”ฏๆŒ็š„่ฝฌๆข็ญ‰ๅŠŸ่ƒฝๆ˜ฏ้…ๅˆ HTTP ๅ่ฎฎ่ฎพ่ฎก็š„, ๅฏ่ƒฝๆœ‰ๆ‰€ไธ่ถณ), ๅฏ็”Ÿๆˆๅฏนๅบ”ๅคดๆ–‡ไปถใ€ๆบๆ–‡ไปถๆˆ–ๅญ—่Š‚็ ; * `llhttp` - ไฝฟ็”จไธŠ่ฟฐ `llparse` ๅผ€ๅ‘็”Ÿๆˆ็š„ HTTP ่งฃๆžๅ™จ, ๆฎๅฎ˜ๆ–นไป‹็ปๆ•ˆ็Ž‡่พƒ [http_parser](https://github.com/nodejs/http-parser) ๆๅ‡ไธ€ๅ€ๆœ‰ไฝ™; ### ๅ่ฎฎ ๆœฌ้กน็›ฎไฝฟ็”จ MIT ๅ่ฎฎ
ec04f4891b3ed78b769f6f79549a1f273c4be7f5
[ "JavaScript", "Makefile", "C++", "Markdown" ]
6
C++
terrywh/lltoml
489b685bcfdbec07c0f4c1d875df11f4a0902633
3198ae0e1c2346d1351c7002962c5dc984b8c2ca
refs/heads/master
<repo_name>jmichaeln5/chris_g_page<file_sep>/javascript/basicslider.js var i = 0; //Starting Point var images = []; var time = 3300; // Image List images[0] = 'pic4.jpg' images[1] = 'pic1.jpg' images[2] = 'pic3.jpg' images[3] = 'pic2.jpg' // Change Image Func function changeImg(){ document.slide.src = images[i]; if (i < images.length - 1){ i ++; } else { i = 0; } setTimeout("changeImg()", time); } window.onload = changeImg;
9ffdacdaa56d3eec80b0c7c75433f96a11b2f162
[ "JavaScript" ]
1
JavaScript
jmichaeln5/chris_g_page
bee7710c9156b223e41bd36da12acb7bd864c822
34306a8b0501dcaeeb141f16d827d204afe0aeb0
refs/heads/master
<repo_name>hirvin-faria/jogo-adivinhacao<file_sep>/adivinhacao.c //for compile run `gcc advinhacao.c -o advinhacao.out/.exe` #include <stdio.h> #include <stdlib.h> #include <time.h> #define RETRIE_NUMBER 3 int main() { printf("************************************\n"); printf("* Bem vindo ao jogo de adivinhaรงรฃo *\n"); printf("* *\n"); printf("* ( ) *\n"); printf("* || *\n"); printf("* || *\n"); printf("* ___|""|__.._ *\n"); printf("* /____________\\ *\n"); printf("*jrei \\____________/~~~. *\n"); printf("*in www.asciiart.eu *\n"); printf("* *\n"); printf("************************************\n"); srand(time(0)); int secretnumber = rand() % 100; int kick; int retries = 1; double score = 1000; while (1) { printf("Tentativa %d\n", retries); printf("Qual รฉ seu chute?"); scanf("%d", &kick); printf("Seu chute foi %d\n", kick); if(kick < 0) { printf("Vocรช nรฃo pode chutar nรบmeros negativos\n"); continue; } if(kick == secretnumber) { printf("Parabรฉns! Vocรช acertou!\n"); break; } else if(kick > secretnumber) { printf("Seu chute foi maior do que o nรบmero secreto!\n"); } else { printf("Seu chute foi menor do que o nรบmero secreto!\n"); } retries++; double dawnscore = abs(kick - secretnumber) / 2.0; score = score - dawnscore; } printf("Fim de jogo.\n"); printf("Voce acertou em %d tentativas\n", retries); printf("Voce fez um total de %.1f pontos", score); }
64fc5a389d423cc2d0103b89a3b6eec657944a7f
[ "C" ]
1
C
hirvin-faria/jogo-adivinhacao
6eea91b0febc64830039c732b1b31739c981244f
501443f4d0436975c652e03748daf0a8547d406e
refs/heads/master
<repo_name>xseg18/Lab2<file_sep>/Parte 1/Heap.cs ๏ปฟusing System; namespace Parte_1 { public class Heap { internal Node[] Queue; int p; internal class Node { internal Node Right; internal Node Left; internal Node Parent; IHuffman.Node Key; internal IHuffman.Node Keys { get => Key; set => Key = value; } } Node root; internal Heap(int x) { Queue = new Node[x + 1]; p = 1; } internal void Add(IHuffman.Node value) { if(root == null) { root = new Node(); root.Keys = value; Queue[p] = root; p++; } else { Node add = new Node { Keys = value }; //hijo izquierdo if(p%2 == 0) { Queue[p / 2].Left = add; add.Parent = Queue[p / 2]; } else { Queue[p / 2].Right = add; add.Parent = Queue[p / 2]; } Queue[p] = add; Ordenar(p); p++; } } void Ordenar(int x) { if (Queue[x] != null) { if (Queue[x].Keys.Prio < Queue[x/2].Keys.Prio) { IHuffman.Node prov = Queue[x].Keys; Queue[x].Keys = Queue[x/2].Keys; Queue[x / 2].Keys = prov; if (x/2 != 1) { Ordenar(x / 2); } } } } void OrdenarRaiz(int x) { //hijo izquierdo y que hijo izquierdo sea menor que hijo derecho if (Queue[(x * 2) + 1] != null) { if (Queue[x * 2].Keys.Prio < Queue[x].Keys.Prio && Queue[(x * 2) + 1].Keys.Prio >= Queue[x * 2].Keys.Prio) { IHuffman.Node prov = Queue[x].Keys; Queue[x].Keys = Queue[x * 2].Keys; Queue[x * 2].Keys = prov; if ((x * 2) * 2 < p || ((x * 2) * 2) + 1 < p) { OrdenarRaiz(x * 2); } } else if (Queue[(x * 2) + 1].Keys.Prio < Queue[x].Keys.Prio) { IHuffman.Node prov = Queue[x].Keys; Queue[x].Keys = Queue[(x * 2) + 1].Keys; Queue[(x * 2) + 1].Keys = prov; if (((x * 2) + 1) * 2 < p || (((x * 2) + 1) * 2) + 1 < p) { OrdenarRaiz((x * 2) + 1); } } } else if(Queue[(x * 2) + 1] == null) { if (Queue[x * 2].Keys.Prio < Queue[x].Keys.Prio) { IHuffman.Node prov = Queue[x].Keys; Queue[x].Keys = Queue[x * 2].Keys; Queue[x * 2].Keys = prov; if ((x * 2) * 2 < p || ((x * 2) * 2) + 1 < p) { OrdenarRaiz(x * 2); } } } } internal IHuffman.Node Pop() { IHuffman.Node pop = root.Keys; if(Queue[2] != null) { Queue[1].Keys = Queue[p - 1].Keys; Queue[p - 1] = null; p--; if(p > 2) { OrdenarRaiz(1); } } else { p = 1; root = null; } return pop; } internal int Count() { return p - 1; } } } <file_sep>/Parte 2/Program.cs ๏ปฟusing System; using Parte_1; namespace Parte_2 { class Program { static void Main(string[] args) { IHuffman h = new ImplementationClass(); string prueba = h.Comprimir("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ullamcorper eros ut convallis placerat. Praesent tincidunt facilisis orci in aliquet. Sed convallis sapien erat, ac cursus felis tempus nec. Ut placerat tortor felis, sed accumsan velit elementum quis. Pellentesque finibus elit iaculis, luctus metus vitae, volutpat odio. Fusce feugiat quis lectus et dapibus. Nullam rutrum nisl massa, sed aliquet nisi faucibus non. Etiam eu ullamcorper metus. Sed vel leo aliquet, ullamcorper felis vitae, commodo velit. Phasellus aliquet condimentum convallis. Integer id ultrices magna. Mauris semper vitae odio non commodo."); string prueba2 = h.Descomprimir(prueba); } } } <file_sep>/Parte 1/Huffman.cs ๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace Parte_1 { public interface IHuffman { //nodo รกrbol internal class Node { int Priority; char Symbol; internal Node Left; internal Node Right; internal Node Parent; internal int Prio { get => Priority; set => Priority = value; } internal char Symb { get => Symbol; set => Symbol = value; } //recorrido para cรณdigo prefijo internal List<char> Recorrido(Node search, List<char> binary) { if(search != null) { if(search.Parent.Left == search) { if (search.Parent.Parent != null) { Recorrido(search.Parent, binary); } binary.Add('0'); } else { if (search.Parent.Parent != null) { Recorrido(search.Parent, binary); } binary.Add('1'); } return binary; } return null; } //encuentra el nodo a partir del caracter internal Node Find(char s, Node root) { if (root != null) { if (root.Symb == s) { return root; } else { Node found = Find(s, root.Left); if (found == null) { found = Find(s, root.Right); } return found; } } else { return null; } } } public string Comprimir(string compress); public string Descomprimir(string decompress); } public class ImplementationClass : IHuffman { string IHuffman.Comprimir(string compress) { //diccionario donde se guardan las frecuencias Dictionary<char, int> Leyenda = new Dictionary<char, int>(); for (int i = 0; i < compress.Length; i++) { if (!Leyenda.ContainsKey(compress[i])) { Leyenda.Add(compress[i], 0); } Leyenda[compress[i]]++; } //cola de prioridad Heap PrioHeap = new Heap(Leyenda.Count); foreach (KeyValuePair<char, int> symbol in Leyenda) { IHuffman.Node a = new IHuffman.Node { Symb = symbol.Key, Prio = symbol.Value }; PrioHeap.Add(a); } //รกrbol de cรณdigos prefijo IHuffman.Node Parent = new IHuffman.Node(); while (2 <= PrioHeap.Count()) { IHuffman.Node Left = PrioHeap.Pop(); IHuffman.Node Right = PrioHeap.Pop(); Parent = new IHuffman.Node { Prio = Left.Prio + Right.Prio, Left = Left, Right = Right }; Left.Parent = Parent; Right.Parent = Parent; PrioHeap.Add(Parent); } //cรณdigo binario de todo el รกrbol List<char> binary = new List<char>(); for (int i = 0; i < compress.Length; i++) { IHuffman.Node s = Parent.Find(compress[i], Parent); Parent.Recorrido(s, binary); } //string final String final = string.Empty; //Leyenda de letras foreach(var par in Leyenda) { final += par.Key + "[" + par.Value.ToString() + "]"; } //Final de metadata final += "!eNdยก"; //archivo comprimido string p = ""; for (int i = 0; i < binary.Count; i++) { p+= binary[i]; if(p.Length == 8) { final += Convert.ToChar(BinDec(Convert.ToInt32(p))); p = ""; } } if(p != "") { while (p.Length < 8) { p += '0'; } final += Convert.ToChar(BinDec(Convert.ToInt32(p))); } int x = final.Length; return final; } string IHuffman.Descomprimir(string decompress) { //encontrar metadata int pos = 0; string info = string.Empty; while (!info.Contains("!eNdยก")) { info += decompress[pos]; pos++; } //quitamos metadata decompress = decompress.Remove(0, pos); //quitamos separador info = info.Replace("!eNdยก", ""); //array de pares ordenados string[] par = info.Split(']'); //pares ordenados separados string[] frequencies = info.Split('[', ']'); //heap y contador de caracteres Heap PrioHeap = new Heap(par.Length); int charcount = 0; for (int i = 0; i < frequencies.Length - 1; i++) { IHuffman.Node a = new IHuffman.Node { Symb = Convert.ToChar(frequencies[i]), Prio = Convert.ToInt32(frequencies[i+1]) }; charcount += Convert.ToInt32(frequencies[i + 1]); PrioHeap.Add(a); i++; } //creaciรณn codigos prefijo IHuffman.Node Parent = new IHuffman.Node(); while (2 <= PrioHeap.Count()) { IHuffman.Node Left = PrioHeap.Pop(); IHuffman.Node Right = PrioHeap.Pop(); Parent = new IHuffman.Node { Prio = Left.Prio + Right.Prio, Left = Left, Right = Right }; Left.Parent = Parent; Right.Parent = Parent; PrioHeap.Add(Parent); } //diccionario cรณdigos prefijo Dictionary<char, string> Prefix = new Dictionary<char, string>(); for (int i = 0; i < par.Length - 1; i++) { IHuffman.Node found = Parent.Find(par[i][0], Parent); List<char> binary = new List<char>(); Parent.Recorrido(found, binary); string path = ""; for (int j = 0; j < binary.Count; j++) { path += binary[j]; } Prefix.Add(par[i][0], path); } //descompresiรณn de archivo string actualpath = ""; string final = ""; char[] deco = decompress.ToArray<char>(); //de caracteres a prefijos for (int i = 0; i < decompress.Length; i++) { actualpath += DecBin(decompress[i]); } //de prefijos a letras int cc = 0; while (charcount != cc) { foreach (var pars in Prefix) { if (actualpath.StartsWith(pars.Value)) { final += pars.Key; actualpath = actualpath.Substring(pars.Value.Length); break; } } cc++; } return final; } int BinDec(long binary) { int decim = 0; int digit = 0; const int div = 10; for (long i = binary, j = 0; i > 0; i /= div, j++) { digit = (int)i % div; if (digit != 1 && digit != 0) { return -1; } decim += digit * (int)Math.Pow(2, j); } return decim; } string DecBin(int decim) { long bin = 0; const int div = 2; long digit = 0; for (int i = decim % div, j = 0; decim > 0; decim /= div, i = decim % div, j++) { digit = i % div; bin += digit * (long)Math.Pow(10, j); } string Bin = bin.ToString(); while (Bin.Length < 8) { Bin = "0" + Bin; } return Bin; } } } <file_sep>/Controllers/HuffmanController.cs ๏ปฟusing Lab2.Models.Data; using Lab2.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using System.Text; using System.Threading.Tasks; using Parte_1; namespace Lab2.Controllers { [ApiController] [Route("api")] public class HuffmanController : Controller { [Route("compress/{name}")] [HttpPost] public ActionResult Compress([FromRoute] string name, IFormFile file) { try { if (file.Length > 0) { var fileBytes = (dynamic)null; var compressedBytes = (dynamic)null; using (var ms = new MemoryStream()) { file.CopyTo(ms); fileBytes = ms.ToArray(); } IHuffman h = new ImplementationClass(); compressedBytes = Encoding.UTF8.GetBytes(file.FileName + h.Comprimir(Encoding.UTF8.GetString(fileBytes))); double fileCount = Convert.ToDouble(Encoding.UTF8.GetByteCount(Encoding.UTF8.GetString(fileBytes))); double compressedCount = Convert.ToDouble(Encoding.UTF8.GetByteCount(Encoding.UTF8.GetString(compressedBytes))); var newCompression = new Compressions { originalName = file.FileName, compressedName = name + ".huff", path = Environment.CurrentDirectory, ratio = compressedCount / fileCount, factor = fileCount / compressedCount, percentage = Convert.ToString((compressedCount / fileCount) * 100) + "%" }; System.IO.File.WriteAllBytes(name + ".huff", compressedBytes); Singleton.Instance.Compressions.Add(newCompression); return Ok("Archivo comprimido en: " + Environment.CurrentDirectory); } else { return BadRequest(); } } catch (Exception) { return new StatusCodeResult(StatusCodes.Status500InternalServerError); } } [Route("decompress")] [HttpPost] public IActionResult Decompress(IFormFile file) { try { if (file.Length > 0) { var fileBytes = (dynamic)null; var compressedBytes = (dynamic)null; using (var ms = new MemoryStream()) { file.CopyTo(ms); fileBytes = ms.ToArray(); } IHuffman h = new ImplementationClass(); int found = Encoding.UTF8.GetString(fileBytes).IndexOf(".txt"); compressedBytes = Encoding.UTF8.GetBytes(h.Descomprimir(Encoding.UTF8.GetString(fileBytes).Substring(found + 4))); System.IO.File.WriteAllBytes(Encoding.UTF8.GetString(fileBytes).Substring(0, found + 4), compressedBytes); return Ok("Archivo descomprimido en : " + Environment.CurrentDirectory); } else { return BadRequest(); } } catch (Exception) { return new StatusCodeResult(StatusCodes.Status500InternalServerError); } } [Route("compressions")] [HttpGet] public ActionResult Compressions() { return Ok(JsonSerializer.Serialize(Singleton.Instance.Compressions)); } } } <file_sep>/Models/Data/Singleton.cs ๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Lab2.Models.Data { public class Singleton { private readonly static Singleton _instance = new Singleton(); public List<Compressions> Compressions { get; set; } private Singleton() { Compressions = new List<Compressions>(); } public static Singleton Instance { get { return _instance; } } } } <file_sep>/README.md El laboratorio 3 se encuentra en la branch "Lab3" <file_sep>/Models/Compressions.cs ๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Lab2.Models { public class Compressions { public string originalName { get; set; } public string compressedName { get; set; } public string path { get; set; } public double ratio { get; set; } public double factor { get; set; } public string percentage { get; set; } } }
6bdfc5b028b40a9b54cb95053ada04dbf08e7e9e
[ "Markdown", "C#" ]
7
C#
xseg18/Lab2
53a09452ebb2aed6de6d9b9087fb81a973c4d8e0
65685e5c3e6d5d282616ee75c680ad3bf4375538
refs/heads/main
<file_sep><?php namespace App\Actions\TicketType; use App\Models\Ticket_type; class UpdateTypeAction { public static function execute($inputs,$slug) { $type=Ticket_type::where('slug',$slug)->FiRSTOrFail(); $type->update([ 'name'=>$inputs->name ]); return $type; } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class User_permission extends Model { use HasFactory; protected $fillable=['user_name','role_name','permission_name','project_id']; /* public function users() { return $this->belongsTo('App\User'); } public function permissions() { return $this->belongsTo('App\Models\Permission'); } public function roles() { return $this->belongsTo('App\Models\Role'); } public function projects() { return $this->belongsTo('App\Models\Project'); }*/ } <file_sep><?php namespace App\Actions\Log; use App\Models\Project_activity; class ProjectActivityAction { public static function execute($user_name='',$action_type='',$project_id=null,$property=[]) { $proactivity=Project_activity::create([ 'user_name'=>$user_name, 'action_type'=>$action_type, 'project_id'=>$project_id ?? 0, 'property'=>$property ]); return true; } } <file_sep><?php namespace App\Actions\Project; use App\Models\Project; use Illuminate\Support\Facades\Auth; use App\User; use App\Actions\Log\ProjectActivityAction; class UpdateProjectAction { public static function execute($inputs,$id) { $project=Project::FindOrFail($id); $user=User::FindorFail(Auth::id()); $project->update([ 'title'=>$inputs->title, 'description'=>$inputs->description, 'team_id'=>$inputs->teamid ]); activity() ->causedBy($user) ->withProperties(['name' => $user->name,'email'=>$user->email,'role_id'=>$user->role_id,'project'=>$project]) ->useLog('Project_Log') ->log('Update_Project'); $project_activity=ProjectActivityAction::execute($user->name,'Update_Project',$project->id,$project); if($project_activity) { return $project; } } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Actions\Helper\Success; use App\Actions\Helper\Fail; use App\Http\Requests\TicketType\StoreTicketTypeRequest; use App\Http\Requests\TicketType\UpdateTicketTypeRequest; Use App\Actions\TicketType\DeleteTypeAction; Use App\Actions\TicketType\GetAllTicketTypeAction; Use App\Actions\TicketType\GetTypeDetails; Use App\Actions\TicketType\StoreNewTypeAction; Use App\Actions\TicketType\UpdateTypeAction; class TicketTypeController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $response=GetAllTicketTypeAction::execute(); if($response) { return Success::execute('Record(s) fetched successfully',$response,2000); } else { return Fail::execute('Record(s) can not be fetched',$response,3000); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(StoreTicketTypeRequest $request) { $response=StoreNewTypeAction::execute($request); if($response) { return Success::execute('Record Created',$response,2001); } else { return Fail::execute('Record can not be created',$response,3001); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($slug) { $response=GetTypeDetails::execute($slug); if($response) { return Success::execute('Record(s) fetched successfully',$response,2000); } else { return Fail::execute('Record(s) can not be fetched',$response,3000); } } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(UpdateTicketTypeRequest $request, $slug) { $response=UpdateTypeAction::execute($request,$slug); if($response) { return Success::execute('Record Updated',$response,2002); } else { return Fail::execute('Record can not be updated',$response,3002); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($slug) { $response=DeleteTypeAction::execute($slug); if($response) { return Success::execute('Record Deleted',$response,2003); } else { return Fail::execute('Record can not be deleted',$response,3003); } } } <file_sep><?php namespace App\Actions\TicketPriority; use App\Models\Ticket_priority; class UpdatePriorityAction { public static function execute($inputs,$slug) { $priority=Ticket_priority::where('slug',$slug)->FirstOrFail(); $priority->update([ 'name'=>$inputs->name ]); return $priority; } } <file_sep><?php namespace App\Actions\Project; use App\Models\Project; class GetProjectAction { public static function execute($id) { $project=Project::FindOrFail($id); return $project; } } <file_sep><?php namespace App\Actions\TicketPriority; use App\Models\Ticket_priority; class StoreNewPriorityAction { public static function execute($inputs) { $priority=Ticket_priority::create([ 'name'=>$inputs->name ]); return $priority; } } <file_sep><?php namespace App\Actions\User; use App\User; use Illuminate\Support\Facades\Auth; use Carbon\Carbon; class VerificationUserAction { public static function execute($mail) { $user=User::where('email',$mail)->first(); if($user!=null) { $user->email_verified_at=Carbon::now(); $user->save(); return $user; } } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Project extends Model { protected $fillable=['title','description','team_id']; public function teams() { return $this->belongsTo('App\Models\Team'); } public function boards() { return $this->hasMany('App\Models\Board'); } public function user_permissions() { return $this->hasMany('App\Models\User_permission'); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Spatie\Sluggable\HasSlug; use Spatie\Sluggable\SlugOptions; class Column extends Model { use HasSlug; protected $fillable=['title','board_id']; public function getSlugOptions(): SlugOptions { return SlugOptions::create() ->generateSlugsFrom('title') ->saveSlugsTo('slug') ->doNotGenerateSlugsOnUpdate(); } public function getRouteKeyName() { return 'slug'; } //relations public function boards() { return $this->belongsTo('App\Models\Board'); } public function tickets() { return $this->hasMany('App\Models\Ticket'); } } <file_sep><?php namespace App\Actions\Log; use App\Models\Activity_log; class GetAllActivityLogAction { public static function execute() { $logs=Activity_log::orderBy('id','DESC')->get(); return $logs; } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Spatie\Sluggable\HasSlug; use Spatie\Sluggable\SlugOptions; class Team extends Model { use HasSlug; protected $fillable=['name','description']; public function getSlugOptions(): SlugOptions { return SlugOptions::create() ->generateSlugsFrom('name') ->saveSlugsTo('slug') ->doNotGenerateSlugsOnUpdate(); } public function getRouteKeyName() { return 'slug'; } //relations public function users() { return $this->belongsToMany('App\User'); } public function projects() { return $this->hasMany('App\Models\Project'); } } <file_sep><?php namespace App\Actions\TicketPriority; use App\Models\Ticket_priority; class GetPriorityDetailAction { public static function execute($slug) { $priority=Ticket_priority::where('slug',$slug)->FirstOrFail(); return $priority; } } <file_sep><?php namespace App\Http\Middleware; use Closure; use Illuminate\Auth\Middleware\Authenticate as Middleware; use Illuminate\Support\Facades\Auth; use App\User; use App\Models\User_permission; use App\Models\Column; use App\Models\Ticket; use App\Models\Board; use Illuminate\Support\Str; class CheckSystemPermission extends Middleware { /** * Get the path the user should be redirected to when they are not authenticated. * * @param \Illuminate\Http\Request $request * @return string|null */ public function handle($request, Closure $next, ...$guards) { if (Auth::check()) { $userid=Auth::id(); $user=User::FindOrfail($userid); $Iflog = Str::contains($request->ActionType, 'logs'); $Ifteam = Str::contains($request->ActionType, 'teams'); $Ifuser = Str::contains($request->ActionType, 'users'); $Ifpermission = Str::contains($request->ActionType, 'permissions'); $Ifproject = Str::contains($request->ActionType, 'projects'); $Ifboard = Str::contains($request->ActionType, 'boards'); $Ifcolumn = Str::contains($request->ActionType, 'columns'); $Ifticket = Str::contains($request->ActionType, 'tickets'); $Ifstoreboard=Str::contains($request->ActionType, 'create boards'); $Ifstorecolumn=Str::contains($request->ActionType, 'create columns'); $Ifstoreticket=Str::contains($request->ActionType, 'create tickets'); if($user->role_id==1 || $user->role_id==2 || $user->role_id==3) { if($Iflog) { $permission=User_permission::where('user_name',$user->email)-> select('permission_name')->get(); foreach($permission as $x) { if($x['permission_name']==$request->ActionType) { return $next($request); } } } if($Ifteam) { $permission=User_permission::where('user_name',$user->email)-> select('permission_name')->get(); foreach($permission as $x) { if($x['permission_name']==$request->ActionType) { return $next($request); } } } if($Ifuser) { $permission=User_permission::where('user_name',$user->email)-> select('permission_name')->get(); foreach($permission as $x) { if($x['permission_name']==$request->ActionType) { return $next($request); } } } if($Ifpermission) { $permission=User_permission::where('user_name',$user->email)-> where('project_id',$request->project_id)-> select('permission_name')->get(); foreach($permission as $x) { if($x['permission_name']==$request->ActionType) { return $next($request); } } } if($Ifstoreboard) { $permission=User_permission::where('user_name',$user->email)-> where('project_id',$request->project_id)-> select('permission_name')->get(); foreach($permission as $x) { if($x['permission_name']==$request->ActionType) { return $next($request); } } } elseif($Ifstorecolumn) { $board=Board::where('id',$request->board_id)->FirstOrFail(); $permission=User_permission::where('user_name',$user->email)-> where('project_id',$board->project_id)-> select('permission_name')->get(); foreach($permission as $x) { if($x['permission_name']==$request->ActionType) { return $next($request); } } } elseif($Ifstoreticket) { $board=Board::where('id',$request->board_id)->FirstOrFail(); $permission=User_permission::where('user_name',$user->email)-> where('project_id',$board->project_id)-> select('permission_name')->get(); foreach($permission as $x) { if($x['permission_name']==$request->ActionType) { return $next($request); } }} elseif($Ifboard) { if($request->ActionType=='Can fetch columns') { $board=Board::where('id',$request->id)->FirstOrFail(); } $board=Board::where('slug',$request->slug)->FirstOrFail(); $permission=User_permission::where('user_name',$user->email)-> where('project_id',$board->project_id)-> select('permission_name')->get(); foreach($permission as $x) { if($x['permission_name']==$request->ActionType) { return $next($request); } } } elseif($Ifcolumn) { $column=Column::where('slug',$request->slug)->FirstOrFail(); $board=Board::FindOrFail($column->board_id); $permission=User_permission::where('user_name',$user->email)-> where('project_id',$board->project_id)-> select('permission_name')->get(); foreach($permission as $x) { if($x['permission_name']==$request->ActionType) { return $next($request); } } } elseif($Ifticket) { $ticket=Ticket::where('slug',$request->slug)->FirstOrFail(); $column=Column::FindOrFail($ticket->column_id); $board=Board::FindOrFail($column->board_id); $permission=User_permission::where('user_name',$user->email)-> where('project_id',$board->project_id)-> select('permission_name')->get(); foreach($permission as $x) { if($x['permission_name']==$request->ActionType) { return $next($request); } } } elseif($Ifproject) { $permission=User_permission::where('user_name',$user->email)-> where('project_id',$request->id)-> select('permission_name')->get(); foreach($permission as $x) { if($x['permission_name']==$request->ActionType) { return $next($request); } } } } } return response()->json(['error' => 'Not have Permissions'], 401); } } <file_sep><?php namespace App\Actions\Project; use App\Models\Board; class GetProjectBoardAction { public static function execute($id) { $board=Board::where('project_id',$id)->get(); return $board; } } <file_sep><?php namespace App\Actions\Board; use App\Models\Board; use App\User; use Illuminate\Support\Facades\Auth; use App\Actions\Log\ProjectActivityAction; class UpdateBoardsAction { public static function execute($inputs,$slug) { $board=Board::where('slug',$slug)->FirstOrFail(); $user=User::FindorFail(Auth::id()); $board->update([ 'title'=>$inputs->title, 'description'=>$inputs->description, 'project_id'=>$inputs->project_id ]); activity() ->causedBy($user) ->withProperties(['name' => $user->name,'email'=>$user->email,'role_id'=>$user->role_id,'Board'=>$board]) ->useLog('Board_Log') ->log('Update_Board'); $project_activity=ProjectActivityAction::execute($user->name,'Update_Board',$inputs->project_id,$board); if($project_activity) { return $board; } } } <file_sep><?php namespace App\Actions\User; use App\User; use App\Models\User_permission; class DeleteUserAction { public static function execute($userid) { $user=User::FindOrFail($userid); $user->teams()->detach(); $permissions=User_permission::where('user_name',$user->email); $permissions->delete(); $user->delete(); return true; } } <file_sep><?php namespace App\Actions\TeamUser; use App\Models\Team; use App\user; use App\Models\Team_User; class GetTeamUsetByid { public static function execute($teamid) { $team=Team::FindOrFail($teamid); $user=User::join('team_user','users.id','=','team_user.user_id') ->select('users.id','users.name','users.email')->where('team_user.team_id',$teamid) ->get(); return $user; } } <file_sep><?php namespace App\Actions\Team; use App\Models\Team; class GetTeamProjectsAction { public static function execute($slug) { $team=Team::where('slug',$slug)->FirstOrFail(); return $team->projects; } } <file_sep><?php namespace App\Actions\TicketPriority; use App\Models\Ticket_priority; class GetAllPriorityAction { public static function execute() { $priority=Ticket_priority::all(); return $priority; } } <file_sep><?php namespace App\Http\Controllers; use App\Actions\Helper\Fail; use App\Actions\Helper\Success; use Illuminate\Http\Request; use App\Http\Requests\Project\StoreNewProjectRequest; use App\Http\Requests\Project\UpdateProjectRequest; use App\Actions\Project\UpdateProjectAction; use App\Actions\Project\GetAllProjectAction; use App\Actions\Project\GetProjectAction; use App\Actions\Project\DeleteProjectAction; use App\Actions\Project\StoreNewProjectAction; use App\Actions\Project\GetProjectBoardAction; class ProjectController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $response=GetAllProjectAction::execute(); if($response) { return Success::execute('Record(s) fetched successfully',$response,2000); } else { return Fail::execute('Record(s) can not be fetched',$response,3000); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(StoreNewProjectRequest $request) { $response=StoreNewProjectAction::execute($request); if($response) { return Success::execute('Record Created',$response,2001); } else { return Fail::execute('Record can not be created',$response,3001); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $response=GetProjectAction::execute($id); if($response) { return Success::execute('Record(s) fetched successfully',$response,2000); } else { return Fail::execute('Record(s) can not be fetched',$response,3000); } } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(UpdateProjectRequest $request, $id) { $response=UpdateProjectAction::execute($request,$id); if($response) { return Success::execute('Record Updated',$response,2002); } else { return Fail::execute('Record can not be updated',$response,3002); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $response=DeleteProjectAction::execute($id); if($response) { return Success::execute('Record Deleted',$response,2003); } else { return Fail::execute('Record can not be deleted',$response,3003); } } public function GetProjectBoards($id) { $response=GetProjectBoardAction::execute($id); if($response) { return Success::execute('Record(s) fetched successfully',$response,2000); } else { return Fail::execute('Record(s) can not be fetched',$response,3000); } } } <file_sep><?php namespace App\Actions\User; use App\User; use Illuminate\Support\Facades\Auth; class GetUserProfile { public static function execute() { $userid=Auth::id(); $user_profile=User::findOrFail($userid); return $user_profile; } } <file_sep><?php namespace App\Actions\User; use App\User; use Illuminate\Support\Facades\Hash; use Spatie\Permission\Traits\HasRoles; use Illuminate\Support\Facades\Auth; use App\Models\User_permission; use App\Mail\EmailForQueuing; use Illuminate\Support\Facades\Mail; use App\Jobs\SendEmail; class StoreNewUserAction { use HasRoles; public static function execute($inputs) { $loguser=User::FindorFail(auth::id()); if($inputs->role_id==2) { User_permission::create(['user_name'=>$inputs->email,'role_name'=>'team_leader','permission_name'=>'Can create teams','project_id '=>'0']); User_permission::create(['user_name'=>$inputs->email,'role_name'=>'team_leader','permission_name'=>'Can update teams','project_id '=>'0']); User_permission::create(['user_name'=>$inputs->email,'role_name'=>'team_leader','permission_name'=>'Can delete teams','project_id '=>'0']); User_permission::create(['user_name'=>$inputs->email,'role_name'=>'owner','permission_name'=>'Can update users','project_id'=>'0']); } $user= User::create([ 'name' => $inputs['name'], 'email' => $inputs['email'], 'password' => <PASSWORD>($inputs['<PASSWORD>']), 'role_id'=>$inputs['role_id'] ]); $user->generateToken(); activity() ->causedBy($user) ->withProperties(['user' =>$loguser->email,'Register'=>$user]) ->useLog('UserLog') ->log('Register'); /* $email = new EmailForQueuing($user); Mail::to($user)->send($email); dispatch(new SendEmail($user));*/ return $user; } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Spatie\Sluggable\HasSlug; use Spatie\Sluggable\SlugOptions; class Board extends Model { use HasSlug; protected $fillable=['title','description','project_id']; public function getSlugOptions(): SlugOptions { return SlugOptions::create() ->generateSlugsFrom('title') ->saveSlugsTo('slug') ->doNotGenerateSlugsOnUpdate(); } public function getRouteKeyName() { return 'slug'; } //relations public function projects() { return $this->belongsTo('App\Models\Project'); } public function columns() { return $this->hasMany('App\Models\Column'); } } <file_sep><?php namespace App\Actions\TicketType; use App\Models\Ticket_type; class DeleteTypeAction { public static function execute($slug) { $type=Ticket_type::where('slug',$slug)->FiRSTOrFail(); $type->delete(); return true; } } <file_sep><?php use Illuminate\Database\Seeder; use App\User; use Illuminate\Support\Facades\Hash; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // Let's clear the users table first //User::truncate(); // DB::tabel('role_users')->truncate(); $admin=User::create([ 'name'=>'Owner', 'email'=>'<EMAIL>', 'password'=>Hash::make("<PASSWORD>"), 'role_id'=>'1' ]); $admin->generateToken(); } } <file_sep><?php namespace App\Actions\TeamUser; use App\Models\Team; use App\Models\Team_User; use Illuminate\Support\Facades\Auth; use App\User; class DeleteTeam { public static function execute($teamid) { $team=Team::FindOrFail($teamid); $user=User::FindorFail(Auth::id()); activity() ->causedBy($user) ->withProperties(['name' => $user->name,'email'=>$user->email,'role_id'=>$user->role_id,'team'=>$team]) ->useLog('Team_Log') ->log('Delete_Team'); $team->users()->detach(); $team->delete(); return true; } } <file_sep><?php namespace App\Actions\TicketType; use App\Models\Ticket_type; class GetTypeDetails { public static function execute($slug) { $type=Ticket_type::where('slug',$slug)->FiRSTOrFail(); return $type; } } <file_sep><?php namespace App\Actions\Column; use App\Models\Column; class GetAllColumnBoardAction { public static function execute($boaredid) { $Column=Column::where('board_id',$boaredid)->get(); return $Column; } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Http_log extends Model { use HasFactory; protected $fillable=['uri','method','request_body','response']; } <file_sep><?php use Illuminate\Database\Seeder; use App\Models\Team; class TeamTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $team=Team::create([ 'name'=>'No Team', 'description'=>'Self Project Without Team', 'slug'=>'no-team', ]); } } <file_sep><?php namespace App\Actions\TicketType; use App\Models\Ticket_type; class StoreNewTypeAction { public static function execute($inputs) { $type=Ticket_type::create([ 'name'=>$inputs->name ]); return $type; } } <file_sep><?php namespace App\Actions\Ticket; use App\Models\Ticket; use Illuminate\Support\Facades\Auth; use App\User; class ArchiveTicketAction { public static function execute($slug) { $ticket=Ticket::where('slug',$slug)->FirstOrFail(); $userid=Auth::id(); $user=User::FindOrFail($userid); if($ticket) { $ticket->is_archive=1; $ticket->save(); } return $ticket; } } <file_sep><?php namespace App\Actions\TeamUser; use App\Models\Team; use App\Models\Team_User; use Illuminate\Support\Facades\Auth; use App\User; class AddUserToTeam { public static function execute($input) { $team=Team::FindOrFail($input->team_id); $user=User::FindorFail(Auth::id()); $team->users()->sync($input->user_id); activity() ->causedBy($user) ->withProperties(['name' => $user->name,'email'=>$user->email,'role_id'=>$user->role_id,'team_user'=>$team->users()->get()]) ->useLog('TeamUser_Log') ->log('AddUser_Team'); return $team->users()->get(); } } <file_sep><?php namespace App\Actions\Team; use App\Models\Team; use Spatie\Activitylog\Models\Activity ; class GetAllTeamAction { public static function execute() { $team=Team::all(); return $team; } } <file_sep><?php namespace App\Actions\TicketPriority; use App\Models\Ticket_priority; class DeletePriorityAction { public static function execute($slug) { $priority=Ticket_priority::where('slug',$slug)->FirstOrFail(); $priority->delete(); return true; } } <file_sep><?php namespace App\Actions\Log; use App\Models\Http_log; class GetHttpLogAction { public static function execute() { $logs=Http_log::orderBy('created_at','DESC')->get(); return $logs; } } <file_sep><?php namespace App\Actions\Log; use App\Models\Project_activity; use App\Models\Project; class ProjectAllActivityAction { public static function execute($projectid) { $project=Project::FindOrFail($projectid); $activity=Project_activity::where('project_id',$projectid)->get(); return $activity; } } <file_sep><?php namespace App\Actions\Board; use App\Models\Board; class GetBoardDetailAction { public static function execute($slug) { $board=Board::where('slug',$slug)->FirstOrFail(); return $board; } } <file_sep><?php namespace App\Actions\Project; use App\Models\Project; use App\Models\User_permission; use Illuminate\Support\Facades\Auth; use App\User; use App\Models\Permission; use App\Actions\Log\ProjectActivityAction; class StoreNewProjectAction { public static function execute($inputs) { $userid=auth::id(); $user=User::FindOrFail($userid); $permission=Permission::all(); if($inputs->team_id==null) { $project=Project::create([ 'title'=>$inputs->title, 'description'=>$inputs->description, 'team_id'=>'1' ]); } else { $project=Project::create([ 'title'=>$inputs->title, 'description'=>$inputs->description, 'team_id'=>$inputs->team_id ]); } //create role permission for this project foreach($permission as $p) { $userpermission=User_permission::create(['user_name'=>$user->email,'role_name'=>'team_leader','permission_name'=>$p->name,'project_id'=>$project->id]); } activity() ->causedBy($user) ->withProperties(['name' => $user->name,'email'=>$user->email,'role_id'=>$user->role_id,'project'=>$project]) ->useLog('Project_Log') ->log('Store_Project'); $project_activity=ProjectActivityAction::execute($user->name,'Crete_New_Project',$project->id,$project); if($project_activity) { return $project; } } } <file_sep><?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Auth; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ //Auth::routes(['verify' => true]); Route::group(['middleware' => ['auth:api','HttpLog','cors']], function() { Route::post('userregister', 'UsersController@store')->middleware('check_owner'); Route::post('StoreProject', 'ProjectController@store')->middleware('check_owner'); Route::post('StoreType', 'TicketTypeController@store')->middleware('check_owner'); Route::post('StorePriority', 'TicketPriorityController@store')->middleware('check_owner'); Route::get('DeleteType/{slug}', 'TicketTypeController@destroy')->middleware('check_owner'); Route::get('DeletePriority/{slug}', 'TicketPriorityController@destroy')->middleware('check_owner'); Route::post('UpdateType/{slug}', 'TicketTypeController@update')->middleware('check_owner'); Route::post('UpdatePriority/{slug}', 'TicketPriorityController@update')->middleware('check_owner'); //**teams routes */ Route::get('GetTeams', 'TeamController@index')->middleware('check_owner'); Route::get('GetTeam/{slug}', 'TeamController@show')->middleware('check_owner'); Route::get('getusersteam/{teamid}', 'TeamUserController@show')->middleware('check_owner'); Route::get('GetTeamProject/{slug}', 'TeamController@GetTeamProject')->middleware('check_owner'); }); Route::group(['middleware' => ['auth:api','HttpLog','cors']], function() { Route::get('deleteBoard/{slug}', 'BoardController@destroy')->middleware('CheckSystemPermission'); Route::get('deleteColumn/{slug}', 'ColumnController@destroy')->middleware('CheckSystemPermission'); Route::get('DeleteProject/{id}', 'ProjectController@destroy')->middleware('CheckSystemPermission'); Route::get('DeleteTicket/{slug}', 'TicketController@destroy')->middleware('CheckSystemPermission'); //********************project*/ Route::get('GetAllProject', 'ProjectController@index'); Route::get('GetProjectBoards/{id}', 'ProjectController@GetProjectBoards')->middleware('CheckSystemPermission'); Route::get('GetProject/{id}', 'ProjectController@show')->middleware('CheckSystemPermission'); Route::post('UpdateProject/{id}', 'ProjectController@update')->middleware('CheckSystemPermission'); //******************board */ Route::post('StoreBoard', 'BoardController@store')->middleware('CheckSystemPermission'); Route::post('UpdateBoard/{slug}', 'BoardController@update')->middleware('CheckSystemPermission'); Route::get('GetBoardDetails/{slug}', 'BoardController@show')->middleware('CheckSystemPermission'); //****************column */ Route::get('GetColumnsBoard/{boaredid}', 'ColumnController@GetColumnsBoard')->middleware('CheckSystemPermission'); Route::post('StoreColumn', 'ColumnController@store')->middleware('CheckSystemPermission'); Route::get('GetColumn/{slug}', 'ColumnController@show')->middleware('CheckSystemPermission'); Route::post('UpdateColumn/{slug}', 'ColumnController@update')->middleware('CheckSystemPermission'); //**********************ticket */ Route::post('StoreTicket', 'TicketController@store')->middleware('CheckSystemPermission'); Route::get('GetTicket/{slug}', 'TicketController@show')->middleware('CheckSystemPermission'); Route::post('UpdateTicket/{slug}', 'TicketController@update')->middleware('CheckSystemPermission'); Route::get('GetAllTicket', 'TicketController@index'); Route::get('GetArchiveTicket', 'TicketController@GetArchiveTicket'); Route::get('ArchiveTicket/{slug}', 'TicketController@ArchiveTicket'); //************************************permissions+user */ Route::post('UpdatePermissions', 'UsersController@AddUserPermissions')->middleware('CheckSystemPermission'); Route::post('UpdateUserRole/{userid}','UsersController@UpdateUserRole')->middleware('CheckSystemPermission'); Route::get('DeleteUser/{userid}','UsersController@destroy')->middleware('CheckSystemPermission'); //************************team */ Route::post('UpdateTeam/{slug}', 'TeamController@update')->middleware('CheckSystemPermission'); Route::get('deleteTeam/{slug}', 'TeamController@destroy')->middleware('CheckSystemPermission'); Route::post('StoreNewTeam', 'TeamController@store')->middleware('CheckSystemPermission'); Route::post('UpdateUserTeam/{teamid}', 'TeamUserController@update')->middleware('CheckSystemPermission'); //*****************************log */ }); Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); }); Route::group(['middleware' => ['auth:api','cors']], function() { Route::get('GetUserProfilr','UsersController@GetUserProfile'); Route::get('GetHttlog', 'LogController@index')->middleware('CheckSystemPermission'); Route::get('GetAllActivitylog', 'LogController@GetActivities')->middleware('CheckSystemPermission'); Route::post('logout', 'Auth\LoginController@logout')->middleware('HttpLog'); }); Auth::routes(); Auth::routes(['verify' => true]); //**************************users routing Route::post('login', 'Auth\LoginController@login')->middleware(['HttpLog','cors']); Route::get('UserVirification/{email}','UsersController@VerificationUser')->middleware(['HttpLog','cors']);; Route::get('GetAllType', 'TicketTypeController@index')->middleware(['HttpLog','cors']); Route::get('GetType/{slug}', 'TicketTypeController@show')->middleware(['HttpLog','cors']); //********************************Ticket Priority */ Route::get('GetAllPriority', 'TicketPriorityController@index')->middleware(['HttpLog','cors']); Route::get('GetPriority/{slug}', 'TicketPriorityController@show')->middleware(['HttpLog','cors']); //*****************//*/ Route::get('ProjectActivityLog/{projectid}', 'LogController@GetProjectAllActivity')->middleware(['HttpLog','cors']); Route::post('ForgetPassword', 'Auth\ForgotPasswordController@sendResetLinkEmail')->middleware(['HttpLog','cors']); Route::post('ResetPassword', 'Auth\ResetPasswordController@reset')->middleware(['HttpLog','cors']); <file_sep><?php namespace App\Actions\Project; use App\Models\Project; use Illuminate\Support\Facades\Auth; use App\Models\User_permission; use App\User; class GetAllProjectAction { public static function execute() { $userid=Auth::id(); $user=User::FindOrFail($userid); $projectid=User_permission::where('user_name',$user->email)-> select('project_id')->distinct()->get(); $project=Project::whereIn('id',$projectid)->get(); return $project; } } <file_sep><?php namespace App\Actions\Ticket; use App\Models\Ticket; use Carbon\Carbon; class GetTicketDetailsAction { public static function execute($slug) { $datetimeNow=Carbon::now(); $ticket=Ticket::selectRaw('tickets.*,TIMESTAMPDIFF(SECOND,tickets.created_at,now()) as duration') ->where('slug',$slug)->get(); return $ticket; } } <file_sep><?php namespace App\Actions\Team; use App\Models\Team; use Illuminate\Support\Facades\Auth; use App\User; class UpdateTeamAction { public static function execute($inputs,$slug) { $team=Team::where('slug',$slug)->FirstOrFail(); $user=User::FindorFail(Auth::id()); $team->update([ 'name'=>$inputs->name, 'description'=>$inputs->description ]); activity() ->causedBy($user) ->withProperties(['name' => $user->name,'email'=>$user->email,'role_id'=>$user->role_id,'team'=>$team]) ->useLog('Team_Log') ->log('Update_Team'); return $team; } } <file_sep><?php namespace App\Actions\Board; use App\Models\Board; use Illuminate\Support\Facades\Auth; use App\User; use App\Actions\Log\ProjectActivityAction; class DeleteProjectBoardAction { public static function execute($slug) { $user=User::FindorFail(Auth::id()); $board=Board::where('slug',$slug)->FirstOrFail(); $column=$board->columns(); activity() ->causedBy($user) ->withProperties(['name' => $user->name,'email'=>$user->email,'role_id'=>$user->role_id,'Board'=>$board,'Column'=>$column]) ->useLog('Board_Log') ->log('Delete_Board'); $project_activity=ProjectActivityAction::execute($user->name,'Delete_Board',$board->project_id,$column); if($project_activity) { $column->delete(); $board->delete(); return true; } } } <file_sep><?php namespace App\Actions\User; use App\User; use Illuminate\Support\Facades\Auth; use App\Models\User_permission; use PhpParser\Node\Stmt\Return_; use App\Models\Role; class AdduseerPermission { public static function execute($inputs) { $userid=Auth::id(); $user=User::FindorFail($userid); $userto=User::where('email',$inputs->user_email)->FirstOrFail(); $roleto=Role::FindOrFail($userto->role_id); if($user->role_id==2 && strtoupper($roleto->name)=='OWNER') { return false; } $userpermission=User_permission::where('user_name',$inputs->user_email)-> where('project_id',$inputs->project_id); $userpermission->delete(); foreach($inputs->permission_name as $p) { $permissions=User_permission::create([ 'user_name'=>$inputs->user_email, 'role_name'=>$roleto->name, 'permission_name'=>$p, 'project_id'=>$inputs->project_id, ]); } //logout if ($userto) { $userto->api_token = null; $userto->save(); } return $permissions; } } <file_sep><?php namespace App\Actions\Column; use App\Models\Column; class GetColumnDetails { public static function execute($slug) { $Column=Column::where('slug',$slug)->FirstOrFail(); return $Column; } } <file_sep><?php namespace App\Http\Controllers; use App\Actions\User\GetUserProfile; use App\Actions\Helper\Fail; use App\Actions\Helper\Success; use App\Http\Requests\UserRole\UpdateUserRoleRequest; use App\Actions\User\AddUserRoleAction; use App\Actions\User\AdduseerPermission; use App\Actions\User\VerificationUserAction; use App\Actions\User\StoreNewUserAction; use App\Actions\User\DeleteUserAction; use App\Http\Requests\UserRole\StoreUserRequest; use App\Http\Requests\UserRole\StoreUserPernissionRequest; class UsersController extends Controller { public function GetUserProfile() { $response=GetUserProfile::execute(); if($response) { return Success::execute('Record(s) fetched successfully',$response,2000); } else { return Fail::execute('Record(s) can not be fetched',$response,3000); } } public function UpdateUserRole(UpdateUserRoleRequest $requset,$userid) { $response=AddUserRoleAction::execute($requset,$userid); if ($response) { return Success::execute('Record Updated',$response,2002); } else { return Fail::execute('Record can not be updated',$response,3002); } } public function VerificationUser($mail) { $response=VerificationUserAction::execute($mail); if($response) { //return Success::execute('User_Verified',$response); return redirect('https://testing.testhis.link/'); } else { return Fail::execute('User_Verified_error',$response); } } public function store(StoreUserRequest $request) { $response=StoreNewUserAction::execute($request); if($response) { return Success::execute('Record Created',$response,2001); } else { return Fail::execute('Record can not be created',$response,3001); } } public function AddUserPermissions(StoreUserPernissionRequest $request) { $response=AdduseerPermission::execute($request); if ($response) { return Success::execute('Record Updated',$response,2002); } else { return Fail::execute('Record can not be updated',$response,3002); } } public function destroy($userid) { $response=DeleteUserAction::execute($userid); if($response) { return Success::execute('Record Deleted',$response,2003); } else { return Fail::execute('Record can not be deleted',$response,3003); } } } <file_sep><?php namespace App\Actions\TicketType; use App\Models\Ticket_type; class GetAllTicketTypeAction { public static function execute() { $type=Ticket_type::all(); return $type; } } <file_sep><?php namespace App\Http\Middleware; use Closure; use Illuminate\Auth\Middleware\Authenticate as Middleware; use Illuminate\Support\Facades\Auth; use App\User; class CheckUserPermissions extends Middleware { /** * Get the path the user should be redirected to when they are not authenticated. * * @param \Illuminate\Http\Request $request * @return string|null */ public function handle($request, Closure $next, ...$guards) { if (Auth::check()) { $userid=Auth::id(); $user=User::FindOrfail($userid); if($user->role_id==1 || $user->role_id==2) { return $next($request); } } return response()->json(['error' => 'Not have Permissions'], 401); } } <file_sep><?php namespace App\Actions\Project; use App\Models\Project; use App\Models\Column; use App\Models\User_permission; use Illuminate\Support\Facades\Auth; use App\User; use App\Actions\Log\ProjectActivityAction; class DeleteProjectAction { public static function execute($id) { $project=Project::FindOrFail($id); $user=User::FindorFail(Auth::id()); $board=$project->boards(); $permission=User_permission::where('project_id',$id); activity() ->causedBy($user) ->withProperties(['name' => $user->name,'email'=>$user->email,'role_id'=>$user->role_id,'project'=>$project,'board'=>$board]) ->useLog('Project_Log') ->log('Delete_Project'); $project_activity=ProjectActivityAction::execute($user->name,'Delete_Project',$project->id,$project); if($project_activity) { foreach($board as $b) { $column=Column::where('board_id',$b->id); $column->delete(); } $board->delete(); $project->delete(); $permission->delete(); return true; } } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Project_activity extends Model { use HasFactory; protected $table='project_activity'; protected $fillable=['user_name','action_type','project_id','property']; protected $casts = [ 'property' => 'array' ]; } <file_sep><?php namespace App\Actions\Ticket; use App\Models\Ticket; use Illuminate\Support\Facades\Auth; class GetArchiveTicketAction { public static function execute() { $userid=Auth::id(); $ticket=Ticket::where('assign_id',$userid)-> where('is_archive','1')->get(); return $ticket; } } <file_sep><?php namespace App\Actions\Ticket; use App\Models\Ticket; class DeleteTicketAction { public static function execute($id) { $ticket=Ticket::where('slug',$id)->FirstOrFail(); $ticket->delete(); return true; } } <file_sep><?php namespace App\Actions\Ticket; use App\Models\Ticket; use Illuminate\Support\Facades\Auth; use App\User; use App\Actions\Log\ProjectActivityAction; use App\Models\Board; class StoreNewTicketAction { public static function execute($inputs) { $userid=Auth::id(); $user=User::FindOrFail($userid); $board=Board::FindOrFail($inputs->board_id); $ticket=Ticket::create([ 'title'=>$inputs->title, 'content'=>$inputs->content, 'reporter_id'=>$userid, 'assign_id'=>$inputs->assign_id, 'board_id'=>$inputs->board_id, 'type_id'=>$inputs->type_id, 'priority_id'=>$inputs->priority_id, 'column_id'=>$inputs->column_id, 'parent_id'=>$inputs->parent_id ]); activity() ->causedBy($user) ->withProperties(['user'=>$user->email,'ticket'=>$ticket]) ->useLog('Ticket_Log') ->log('Store_Ticket'); $project_activity=ProjectActivityAction::execute($user->name,'Create_Ticket',$board->project_id,$ticket); if($project_activity) { return $ticket; } } } <file_sep><?php namespace App\Actions\Ticket; use App\Models\Ticket; use Illuminate\Support\Facades\Auth; class GetAllTicketsAction { public static function execute() { $userid=Auth::id(); $ticket=Ticket::selectRaw('tickets.*,TIMESTAMPDIFF(SECOND,tickets.created_at,now()) as duration') ->where('assign_id',$userid)-> where('is_archive','0')->get(); return $ticket; } } <file_sep><?php namespace App\Actions\Column; use App\Models\Column; use Illuminate\Support\Facades\Auth; use App\User; use App\Actions\Log\ProjectActivityAction; use App\Models\Board; class DeleteColumnAction { public static function execute($slug) { $Column=Column::where('slug',$slug)->FirstOrFail(); $user=User::FindorFail(Auth::id()); $board=Board::FindorFail($Column->board_id); activity() ->causedBy($user) ->withProperties(['name' => $user->name,'email'=>$user->email,'role_id'=>$user->role_id,'Column'=>$Column]) ->useLog('Column_Log') ->log('Delete_Column'); $project_activity=ProjectActivityAction::execute($user->name,'Delete_Column',$board->project_id,$Column); if($project_activity) { $Column->delete(); return true; } } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Actions\Helper\Fail; use App\Actions\Helper\Success; use App\Actions\Log\GetHttpLogAction; use App\Actions\Log\GetAllActivityLogAction; use App\Actions\Log\GetActivityUserLogAction; use App\Actions\Log\ProjectAllActivityAction; class LogController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $response=GetHttpLogAction::execute(); if($response) { return Success::execute('Record(s) fetched successfully',$response,2000); } else { return Fail::execute('Record(s) can not be fetched',$response,3000); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function GetActivities() { $response=GetAllActivityLogAction::execute(); if($response) { return Success::execute('Record(s) fetched successfully',$response,2000); } else { return Fail::execute('Record(s) can not be fetched',$response,3000); } } public function GetProjectAllActivity($projectid) { $response=ProjectAllActivityAction::execute($projectid); if($response) { return Success::execute('Record(s) fetched successfully',$response,2000); } else { return Fail::execute('Record(s) can not be fetched',$response,3000); } } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php use Illuminate\Database\Seeder; use App\Models\Permission; use App\Models\User_permission; class PermissionTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Permission::create(['name'=>'Can create teams','guard_name'=>'web']); Permission::create(['name'=>'Can update teams','guard_name'=>'web']); Permission::create(['name'=>'Can delete teams','guard_name'=>'web']); Permission::create(['name'=>'Can fetch teams','guard_name'=>'web']); Permission::create(['name'=>'Can create boards','guard_name'=>'web']); Permission::create(['name'=>'Can update boards','guard_name'=>'web']); Permission::create(['name'=>'Can delete boards','guard_name'=>'web']); Permission::create(['name'=>'Can fetch boards','guard_name'=>'web']); Permission::create(['name'=>'Can create columns','guard_name'=>'web']); Permission::create(['name'=>'Can update columns','guard_name'=>'web']); Permission::create(['name'=>'Can delete columns','guard_name'=>'web']); Permission::create(['name'=>'Can fetch columns','guard_name'=>'web']); Permission::create(['name'=>'Can create tickets','guard_name'=>'web']); Permission::create(['name'=>'Can update tickets','guard_name'=>'web']); Permission::create(['name'=>'Can delete tickets','guard_name'=>'web']); Permission::create(['name'=>'Can fetch tickets','guard_name'=>'web']); Permission::create(['name'=>'Can create users','guard_name'=>'web']); Permission::create(['name'=>'Can update users','guard_name'=>'web']); Permission::create(['name'=>'Can delete users','guard_name'=>'web']); Permission::create(['name'=>'Can fetch users','guard_name'=>'web']); Permission::create(['name'=>'Can create roles','guard_name'=>'web']); Permission::create(['name'=>'Can update roles','guard_name'=>'web']); Permission::create(['name'=>'Can delete roles','guard_name'=>'web']); Permission::create(['name'=>'Can fetch roles','guard_name'=>'web']); Permission::create(['name'=>'Can create permissions','guard_name'=>'web']); Permission::create(['name'=>'Can update permissions','guard_name'=>'web']); Permission::create(['name'=>'Can delete permissions','guard_name'=>'web']); Permission::create(['name'=>'Can fetch system logs','guard_name'=>'web']); Permission::create(['name'=>'Can create projects','guard_name'=>'web']); Permission::create(['name'=>'Can update projects','guard_name'=>'web']); Permission::create(['name'=>'Can delete projects','guard_name'=>'web']); Permission::create(['name'=>'Can fetch projects','guard_name'=>'web']); //-***************************************************Owner permissions User_permission::create(['user_name'=>'<EMAIL>','role_name'=>'owner','permission_name'=>'Can create teams','project_id'=>'0']); User_permission::create(['user_name'=>'<EMAIL>','role_name'=>'owner','permission_name'=>'Can update teams','project_id'=>'0']); User_permission::create(['user_name'=>'<EMAIL>','role_name'=>'owner','permission_name'=>'Can delete teams','project_id'=>'0']); User_permission::create(['user_name'=>'<EMAIL>','role_name'=>'owner','permission_name'=>'Can update users','project_id'=>'0']); User_permission::create(['user_name'=>'<EMAIL>','role_name'=>'owner','permission_name'=>'Can fetch system logs','project_id'=>'0']); } } <file_sep><?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Auth\Notifications\VerifyEmail; class CustomVerifyEmailQueued extends VerifyEmail implements ShouldQueue { use Queueable; } <file_sep><?php namespace App\Actions\User; use App\Models\Role; use App\User; use App\Http\Requests\UserRole\UpdateUserRoleRequest; use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Hash; use App\Models\User_permission; use Illuminate\Support\Facades\Auth; class AddUserRoleAction { public static function execute($inputs,$userid) { $user=User::FindOrFail($userid); $loguser=User::FindorFail(auth::id()); $user->update([ 'name'=>$inputs->name, 'email'=>$inputs->email, 'role_id'=>$inputs->role_id, 'password' => <PASSWORD>($inputs->password), ] ); activity() ->causedBy($user) ->withProperties(['user' =>$loguser->email,'Register'=>$user]) ->useLog('UserLog') ->log('UpdateUser'); $permissions=User_permission::where('user_name',$inputs->email); $permissions->delete(); return $user; } }
d8d08873184c7d13b9735f8bab2a5dc21b9f590b
[ "PHP" ]
62
PHP
Mhdismaeel/EnableCors
f89059bf1204f59a31703b06af39e5de628dab47
33f77c37388fe8ada12da9439279b83a27660ff2
refs/heads/master
<repo_name>ichikawa0311/filter_plugins<file_sep>/dict_get.py from ansible.errors import AnsibleError class FilterModule(object): def dict_get(self, a_dict, a_key): if( not isinstance(a_dict,dict) ): raise AnsibleError('the parameter is not dict') if( not (a_key in a_dict.keys() ) ): raise AnsibleError("dict doesnt have a key "+a_key) return a_dict[a_key] def filters(self): return { # ๅทฆๅดใŒPlaybookๅ†…ใงไฝฟ็”จใ™ใ‚‹ใƒ•ใ‚ฃใƒซใ‚ฟใƒผๅใ€ๅณๅดใŒ็ดไป˜ใ‘ใ‚‹้–ขๆ•ฐๅใ€‚ 'dict_get': self.dict_get, } <file_sep>/README.md # filter_plugins ansibleใฎfilter_plugin็ฝฎใๅ ด ## filter_plugins ### dict_get get specified dict value. useful to specify key as variable. ``` "{{ some_dict | dict_get(some_key) }}" ``` # Features TBD # Requirement TBD * python 2.7.5 * ansible 2.10.7 # Installation TBD ## Usage TBD # Note TBD # Author * ichikawa # License [MIT license](https://en.wikipedia.org/wiki/MIT_License).
b476a23a65c8b1efd91272b49ad6cc591684e1f3
[ "Markdown", "Python" ]
2
Python
ichikawa0311/filter_plugins
8fdf213112389f9e8d5c3380e5da827732071c19
414a1535a78ab2b09ecf7e8184db47302e9b8a06
refs/heads/main
<file_sep># Import library PuLP as p import pulp as p # Set up a maximization problem and its variable # (I) Name the problem as "IceCream_maxProfit_Analysis" using objective of minimizing cost : profit = p.LpProblem('IceCream_maxProfit_Analysis', p.LpMaximize) # (II) Set up problem variables : # Box of vanilla ice-cream vanilla = p.LpVariable('vanilla', lowBound=0) # Box of strawberry ice-cream strawberry = p.LpVariable('strawberry', lowBound=0) # Create objective function : profit += (2*vanilla) + (3*strawberry) # Create constraints : # (I) Amount of daily fresh milk order profit += (0.5*vanilla) + (0.2*strawberry) <= 10 # (II) Number of doll for promoting in a day profit += vanilla + strawberry >= 30 # State problem print(profit) # Solve the problem profit.solve() # Result print('Result :\n--------------------------------------------------------') print('Maximum Profit :', p.value(profit.objective)) print('Optimal Number of Box(es) of Vanilla Ice-cream : ', p.value(vanilla)) print('Optimal Number of Box(es) of Strawberry Ice-cream : ', p.value(strawberry))
845bd1b6bbbbe017f2fa8c73efbc2e37bfa17f9f
[ "Python" ]
1
Python
Jirapawee-R/DataProg_HW5_640631114
3c71d7e2b55ae4a7d574cdf352bc8dd2d91345a3
f927e59448f4d4142dd1e509c2c2ceb3db1d03b8
refs/heads/master
<repo_name>AngelMsger/Bangumi-Visualizer<file_sep>/Dockerfile FROM node LABEL maintainer="<EMAIL>" COPY . /app WORKDIR /app RUN npm install --save CMD ["node", "bin/www"] <file_sep>/README.md # Bangumi-Visualizer [![Build Status](https://travis-ci.org/AngelMsger/Bangumi-Visualizer.svg?branch=master)](https://travis-ci.org/AngelMsger/Bangumi-Visualizer) ![](dist/img/ic_laoding_anim_01.png) ## Overview Bangumi-Visualizer is a visual frontend demo for data provided by [Bangumi-Provider](https://github.com/AngelMsger/Bangumi-Provider). Bangumi-Visualizer only support data in mongodb while multi storage backend is supported by Bangumi-Provider. [Demo](https://projects.angelmsger.com/bangumi) ![](dist/img/screenshot_0.png) ![](dist/img/screenshot_1.png) ![](dist/img/screenshot_2.png) ## Features ### Completely Split the Frontend and Backend Components. * Lightweight API Backend with Node.js & Express. * Implement [SPA](https://www.wikiwand.com/en/Single-page_application) Frontend Simply with Vue.js, Async Load Resource of Full Page. ### Data Visualization with Echarts. ## Usage 1. Make Sure Your Data Source(Data in MongoDB Provided by [Bangumi-Provider](https://github.com/AngelMsger/Bangumi-Provider)). 2. Update `conf.js` and Run `npm install && node bin/www` to Set up API Server. 3. Copy Files `dist/*` to Your Web Server(eg. Nginx) Root. 4. Update `apiPrefix` in `js/bangumi.js` to Your API Server URL. ## API Response Example ### Anime Information ``` curl https://api.angelmsger.com/bangumi/anime/season_id/21421 { "rating": { "count": 31896, "score": 9.8 }, "area": [ { "id": 2, "name": "ๆ—ฅๆœฌ" } ], "tags": [ { "id": 9, "name": "ๅฐ‘ๅฅณ" }, { "id": 122, "name": "้ญ”ๆณ•" }, { "id": 135, "name": "ๆผซๆ”น" } ], "top_matches": [ { "media_id": 3756, "similarity": 0.28640856945518733 }, { "media_id": 8892, "similarity": 0.19707309807208745 }, { "media_id": 8772, "similarity": 0.1422207767154259 }, { "media_id": 8932, "similarity": 0.11738195985814143 }, { "media_id": 8792, "similarity": 0.10697599425914822 }, { "media_id": 11712, "similarity": 0.10262114618086689 }, { "media_id": 33512, "similarity": 0.10059228641931872 }, { "media_id": 8992, "similarity": 0.09941438054869527 } ], "_id": "5aac7499635dc8f02da70665", "season_id": 21421, "alias": "ใ‚ซใƒผใƒ‰ใ‚ญใƒฃใƒ—ใ‚ฟใƒผใ•ใใ‚‰ ใ‚ฏใƒชใ‚ขใ‚ซใƒผใƒ‰็ทจ,็™พๅ˜ๅฐๆจฑ,้ญ”ๆณ•ๅฐ‘ๅฅณๆจฑ,้ญ”ๅกๅฐ‘ๅฅณๆจฑ๏ผš้€ๆ˜Ž็‰Œ็ฏ‡,้ญ”ๅกๅฐ‘ๅฅณๆจฑ,ๅฐๆจฑ", "cover_url": "http://i0.hdslb.com/bfs/bangumi/07245c4bf4acb03a5819762fea3210c656aba66c.jpg", "danmaku_count": 619362, "episodes": 11, "evaluate": "ๆจฑ้›†้ฝไบ†ไผš็ป™ไธ–้—ดๅธฆๆฅ็พ้šพ็š„โ€œๅบ“ๆด›็‰Œโ€๏ผŒๅนถ็”จ้ญ”ๆณ•็š„ๅŠ›้‡ๅฐ†ๅฎƒไปฌๅ˜ๆˆไบ†่‡ชๅทฑ็š„็‰Œใ€‚ๆจฑ่Šฑ็››ๅผ€็š„4ๆœˆ๏ผŒๅฐๆจฑๅ‡ๅ…ฅไบ†ๅˆไธญ1ๅนด็บงใ€‚่€ŒๅŽ๏ผŒๅฐๆจฑไธŽๆ›พ่ฟ”ๅ›ž้ฆ™ๆธฏ็š„ๅฐ็‹ผ้‡้€ข๏ผŒๅนถไธ€่ตทๅผ€ๅฟƒๅœฐๅŽปๅพ€ๅญฆๆ กใ€‚ๆŸไธชๅคœ้‡Œ๏ผŒๆ”ถ้›†็š„็‰Œๅ‡บ็Žฐไบ†ๅผ‚ๅธธโ€ฆโ€ฆ่€Œๅ‹ๆž็”บๆŽฅ่ฟžๅ‘็”Ÿๅฅ‡ๆ€ช็š„ไบ‹ใ€‚ๅฐๆจฑๅœจๆขฆไธญ้‡่ง็š„โ€œ้’ฅๅŒ™โ€็š„ๆŒ‡ๅผ•ไธ‹๏ผŒๅ†ๆฌกๅผ€ๅง‹ๆ”ถ้›†ๅก็‰‡ใ€‚่ฟ™ๆ—ถ๏ผŒ็ญ้‡Œ่ฝฌๆฅไธ€ไธชๅฅณๅญฉๅญโ€ฆโ€ฆ", "favorites": 2364534, "is_finish": true, "media_id": 8752, "pub_time": "2018-01-07T09:00:00.000Z", "title": "้ญ”ๅกๅฐ‘ๅฅณๆจฑ CLEAR CARD็ฏ‡", "last_long_reviews_cursor": "4294976682", "last_short_reviews_cursor": "73285027959490" } ``` ### Author Information ``` curl https://api.angelmsger.com/bangumi/author/mid/3346211 { "follow": [], "recommendation": [ 8892, 6463, 6434, 8772, 6425, 6301, 836, 8792 ], "reviews": [ { "review_id": 1721177, "content": "ๆฒก็œ‹่ฟ‡ๅŽŸไฝœ๏ผŒ็บฏๅŠจ็”ปๅ…š่กจ็คบๅ‰งๆƒ…่ฟ˜ๅฏไปฅใ€‚", "ctime": "2018-03-15T19:01:10.000Z", "mtime": "2018-03-15T19:01:10.000Z", "likes": 0, "score": 8, "media_id": 6339, "is_long": false, "last_ep_index": "12" }, { "review_id": 1721182, "content": "ไธ€ๅฃๆฐ”12้›†๏ผŒ็œŸ็š„ๆœ‰ๆฏ’๏ผ", "ctime": "2018-03-15T19:01:37.000Z", "mtime": "2018-03-15T19:01:37.000Z", "likes": 0, "score": 8, "media_id": 6311, "is_long": false, "last_ep_index": "12" }, { "review_id": 1721189, "content": "ไธ€ๅผ€ๅง‹่ฎพๅฎšๅพˆๆ–ฐ้ฒœ๏ผŒไฝ†็œ‹ไน…ไบ†ๅฐฑๆฒกๆœ‰้‚ฃไนˆๆƒŠ่‰ณไบ†ใ€‚", "ctime": "2018-03-15T19:02:59.000Z", "mtime": "2018-03-15T19:02:59.000Z", "likes": 0, "score": 8, "media_id": 3461, "is_long": false, "last_ep_index": "25" }, { "review_id": 1719102, "content": "ๅพˆๅ–œๆฌข่ฟ™็ง่ฝปๆพ็š„ๆ—ฅๅธธ๏ผŒๆœ‰ๆฒกๆœ‰WiFi๏ผ", "ctime": "2018-03-15T11:25:25.000Z", "mtime": "2018-03-15T11:25:25.000Z", "likes": 0, "score": 10, "media_id": 2580, "is_long": false, "last_ep_index": "12" }, { "review_id": 1725078, "content": "ๅญฆๅงๅ…š่กจ็คบๅพˆไธๆปกโ”(ยด-๏ฝ€)โ”Œใ€‚", "ctime": "2018-03-16T12:54:43.000Z", "mtime": "2018-03-16T12:54:43.000Z", "likes": 0, "score": 8, "media_id": 1512, "is_long": false, "last_ep_index": "0" }, { "review_id": 1719106, "content": "ๅ‹่ฐŠ็œŸ็š„ๆ˜ฏๅพˆ็่ดต็š„ไธœ่ฅฟ๏ผŒ่ฟ™้ƒจ็•ชๅพˆไผ˜็ง€ๅพˆๆ„Ÿไบบ๏ผŒ้ข็ ่ต›้ซ˜๏ผ", "ctime": "2018-03-15T11:26:51.000Z", "mtime": "2018-03-15T11:26:51.000Z", "likes": 0, "score": 10, "media_id": 835, "is_long": false }, { "review_id": 1719092, "content": "ไธ€้ƒจ่ขซๅŸ‹ๆฒก็š„ไผ˜็ง€ไฝœๅ“ใ€‚", "ctime": "2018-03-15T11:24:18.000Z", "mtime": "2018-03-15T11:24:18.000Z", "likes": 1, "score": 10, "media_id": 713, "is_long": false, "last_ep_index": "4" }, { "review_id": 1721165, "content": "ๆœŸๅพ…็ฌฌไธ‰ๅญฃ(โ— ยด๊’ณ` โ—)๏ผ", "ctime": "2018-03-15T18:58:21.000Z", "mtime": "2018-03-15T18:58:21.000Z", "likes": 1, "score": 10, "media_id": 6446, "is_long": false, "last_ep_index": "12" }, { "review_id": 1721901, "content": "OPEDๆ‰ฟ่ฝฝไบ†ๅ›žๅฟ†( ยดโ–ฝ` )ใ€‚", "ctime": "2018-03-15T21:21:06.000Z", "mtime": "2018-03-15T21:21:06.000Z", "likes": 0, "score": 10, "media_id": 425, "is_long": false, "last_ep_index": "4" }, { "review_id": 1721903, "content": "็‚ฎๅง่ต›้ซ˜ใƒพ(โ•นโ—กโ•น)๏พ‰~", "ctime": "2018-03-15T21:21:36.000Z", "mtime": "2018-03-15T21:21:36.000Z", "likes": 0, "score": 10, "media_id": 427, "is_long": false }, { "review_id": 1721883, "content": "ไธๆ˜ฏๅพˆๅธๅผ•ๆˆ‘๏ผˆ โ€™ - โ€™ * )ใ€‚", "ctime": "2018-03-15T21:18:09.000Z", "mtime": "2018-03-15T21:18:09.000Z", "likes": 0, "score": 6, "media_id": 3450, "is_long": false }, { "review_id": 1047291, "content": "ไฟกไปฐๅ•Š๏ผŒๅฟซ่ฆไบŒๅๅนดไบ†๏ผŒๆˆ‘็š„ๅคงๅญฆๆ—ถๅ…‰้ƒฝ่ฆ็ป“ๆŸไบ†๏ผŒๅฐๆจฑ็Ÿฅไธ–่ฟ˜ๆ˜ฏ้‚ฃไนˆๅนด่ฝป๏ผŒSakura่ต›้ซ˜*ูฉ(เน‘ยดโˆ€`เน‘)เธ‡*๏ผ", "ctime": "2018-01-10T22:27:29.000Z", "mtime": "2018-01-10T22:27:29.000Z", "likes": 1, "score": 10, "media_id": 8752, "is_long": false, "last_ep_index": "1" }, { "review_id": 1703840, "content": "ๅพˆไธ้”™็š„ๆ—ฅๅธธๆž็ฌ‘็•ชๅ‰ง๏ฝž( ยดโ–ฝ` )", "ctime": "2018-03-12T00:49:05.000Z", "mtime": "2018-03-12T00:49:05.000Z", "likes": 0, "score": 10, "media_id": 5069, "is_long": false, "last_ep_index": "1" }, { "review_id": 1721199, "content": "ๆ„Ÿ่ง‰ๅ’Œ็ฝชๆถ็Ž‹ๅ† ็›ธไผผ็š„่ฎพๅฎšๅพˆๅคš๏ผˆ โ€™ - โ€™ * )ใ€‚", "ctime": "2018-03-15T19:03:50.000Z", "mtime": "2018-03-15T19:03:50.000Z", "likes": 0, "score": 8, "media_id": 3494, "is_long": false, "last_ep_index": "12" }, { "review_id": 790871, "content": "ๅฏนๆˆ‘ๅฝฑๅ“ๆœ€ๆทฑ่ฟœ็š„ไฝœๅ“๏ผŒๅฐๆจฑๆ˜ฏๆˆ‘ๅ”ฏไธ€็š„ๅฅณ็ฅž๏ผ(หŠห˜ห‹*)", "ctime": "2017-12-18T20:19:14.000Z", "mtime": "2017-12-18T20:19:14.000Z", "likes": 0, "score": 10, "media_id": 3756, "is_long": false, "last_ep_index": "1" }, { "review_id": 1721207, "content": "ๅฎคๅ‹ๆŽจ่็š„๏ผŒ็ฅˆๅฆนๆˆ‘็š„ใ€‚", "ctime": "2018-03-15T19:05:26.000Z", "mtime": "2018-03-15T19:05:26.000Z", "likes": 0, "score": 10, "media_id": 1588, "is_long": false, "last_ep_index": "1" } ], "top_matches": [ { "mid": 40355388, "similarity": 0.48550148160528617 }, { "mid": 33071733, "similarity": 0.4811947284652843 }, { "mid": 8005102, "similarity": 0.4588097570922974 }, { "mid": 18288767, "similarity": 0.4542083633154889 }, { "mid": 2527584, "similarity": 0.450496738116172 }, { "mid": 19352249, "similarity": 0.4497567393745113 }, { "mid": 21806447, "similarity": 0.443463559968293 }, { "mid": 34545175, "similarity": 0.44296005140240013 } ], "_id": "5aac778a635dc8f02da91643", "mid": 3346211, "avatar_url": "http://i0.hdslb.com/bfs/face/6d848efd8e5cbab7369cb7005b6c3c9f94bb8e85.jpg", "uname": "ๅ…ฑไบซๅๅŒ่ฟ‡ๆปค็ฎ—ๆณ•", "last_analyze": "2018-03-19T14:54:22.063Z" } ``` ## ~~Need Help~~(Solved) ### Question: I use following code to query anime's archive in mongodb by its season_id: ``` db.archives.aggregate([ {$replaceRoot: { newRoot: { $mergeObjects: [ {date: '$date'}, {$arrayElemAt: [ {$filter:{ input: '$archives', cond: { $eq: ['$$this.season_id', 21729] } } }, 0] } ] } } } ]) ``` In Mongo Shell, it return result as following: ``` { "date": ISODate("2018-03-17T00:00:00Z"), "season_id": 21729, "favorites": 1169110, "danmaku_count": 88299, "reviews_count": 3731, "rating": { "count": 7831, "score": 9.7 } } ``` But with [Mongoose](http://mongoosejs.com/) in Node.js, the [same query](routes/app.js) return something different: ``` [{"date":"2018-03-17T00:00:00.000Z"}] ``` ~~I have no solution for this right now.~~ ## Solution: While mongoose support auto convert type of parameter to Number in top level by [the schema](db.js) you defined, you should do this manually in embedded query by yourself such as aggregate. The reason why you should do this I guess is that Mongoose don't support advanced query type correctness detection. ``` # this is ok(season_id will auto convert to in) db.collection.findOne({season_id: req.params.season_id}) # while this is error db.archives.aggregate([ {$replaceRoot: { ... {$filter:{ ... $eq: ['$$this.season_id', req.params.season_id] ... } ... } } ]) # fix error db.archives.aggregate([ {$replaceRoot: { ... {$filter:{ ... $eq: ['$$this.season_id', Number(req.params.season_id)] ... } ... } } ]) ``` # Quote 1. Always dependent data from [AngelMsger/Bangumi-Provider](https://github.com/AngelMsger/Bangumi-Provider). 2. Use [Vue-Material](https://github.com/vuematerial/vue-material) to design web pages. <file_sep>/routes/index.js const express = require('express'); const conf = require('../conf'); const db = require('../db'); const router = express.Router(); /* GET api listing. */ router.get('/anime/season_id/:season_id', function(req, res) { const seasonId = parseInt(req.params.season_id); if (seasonId) { const key = 'anime-season-id:' + seasonId; db.redis.get(key, function (error, value) { if (!error && value) { res.send(JSON.parse(value)); } else { db.animes.findOne({season_id: seasonId}, function (error, anime) { if (error === null) { res.send(anime); db.redis.set(key, JSON.stringify(anime), 'EX', conf.redisKVTTL); } }); } }); } }); router.get('/anime/media_id/:media_id', function(req, res) { const mediaId = parseInt(req.params.media_id); if (mediaId) { const key = 'anime-media-id:' + mediaId; db.redis.get(key, function (error, value) { if (!error && value) { res.send(JSON.parse(value)); } else { db.animes.findOne({media_id: mediaId}, function (error, anime) { if (error === null) { res.send(anime); db.redis.set(key, JSON.stringify(anime), 'EX', conf.redisKVTTL) } }); } }); } }); router.get('/author/mid/:mid', function (req, res) { const mId = parseInt(req.params.mid); if (mId) { const key = 'author-mid:' + mId; db.redis.get(key, function (error, value) { if (!error && value) { res.send(JSON.parse(value)); } else { db.authors.findOne({mid: mId}, function (error, author) { if (error === null) { res.send(author); db.redis.set(key, JSON.stringify(author), 'EX', conf.redisKVTTL) } }); } }); } }); router.get('/archive/season_id/:season_id', function (req, res) { const seasonId = parseInt(req.params.season_id); if (seasonId) { const key = 'archive-season-id:' + seasonId; db.redis.get(key, function (error, value) { if (!error && value) { res.send(JSON.parse(value)); } else { db.archives.aggregate([{ $replaceRoot: { newRoot: { $mergeObjects: [{ date: '$date' }, { $arrayElemAt: [{ $filter:{ input: '$archives', cond: { $eq: ['$$this.season_id', seasonId] } } }, 0] }] } } }], function (error, archives) { if (error === null) { res.send(archives); db.redis.set(key, JSON.stringify(archives), 'EX', conf.redisKVTTL); } }); } }); } }); module.exports = router; <file_sep>/conf.js const dbHost = process.env.DB_HOST || 'localhost'; const dbPort = process.env.DB_PORT || 27017; const dbDatabase = process.env.DB_DATABASE || 'bangumi'; const dbUsername = process.env.DB_USERNAME || 'bangumi'; const dbPassword = process.env.DB_PASSWORD || '<PASSWORD>'; const redisHost = process.env.REDIS_HOST || 'localhost'; const redisPort = process.env.REDIS_PORT || 6379; const redisDatabase = process.env.REDIS_DATABASE || 0; const redisMaxMemory = process.env.REDIS_MAXMEMORY || '1024mb'; const redisKVTTL = process.env.REDIS_KV_TTL || 43200; const dev = { root: '/', mongoUrl: 'mongodb://localhost/bangumi', redisUrl: 'redis://localhost/0', redisMaxMemory: '8192mb', redisKVTTL: 43200 }; prod = { root: '/bangumi', mongoUrl: 'mongodb://' + dbUsername + ':' + dbPassword + '@' + dbHost + ':' + dbPort + '/' + dbDatabase, redisUrl: 'redis://' + redisHost + ':' + redisPort + '/' + redisDatabase, redisMaxMemory: redisMaxMemory, redisKVTTL: redisKVTTL }; module.exports = prod; <file_sep>/dist/js/bangumi.js const conf = { apiPrefix: 'https://api.angelmsger.com/bangumi' }; conf.animeBySeasonIdURLPrefix = conf.apiPrefix + '/anime/season_id/'; conf.animeByMediaIdURLPrefix = conf.apiPrefix + '/anime/media_id/'; conf.authorByMidURLPrefix = conf.apiPrefix + '/author/mid/'; conf.archiveBySeasonIdURLPrefix = conf.apiPrefix + '/archive/season_id/'; function LineChartOption(title, xAxisData, seriesData) { this.title = { text: title }; this.xAxis = { data: xAxisData }; this.yAxis = { type: 'value' }; this.series = { type: 'line', data: seriesData }; } function PieChartOption(seriesData, title='็”จๆˆทๅๅฅฝ', seriesName='่ฏ„่ฎบ็•ชๅ‰งๆบๅธฆๆ ‡็ญพ') { this.title = { text: title, left: 'center', top: 20, textStyle: { color: '#000' } }; this.tooltip = { trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)" }; this.visualMap = { show: false, min: 0, max: 16, inRange: { colorLightness: [0, 1] } }; this.series = [ { name: seriesName, type: 'pie', radius : '55%', center: ['50%', '50%'], data: seriesData.sort(function (a, b) { return a.value - b.value; }), roseType: 'radius', label: { normal: { textStyle: { color: 'rgba(0, 0, 0, 0.3)' } } }, labelLine: { normal: { lineStyle: { color: 'rgba(0, 0, 0, 0.3)' }, smooth: 0.2, length: 10, length2: 20 } }, itemStyle: { normal: { color: '#c23531', shadowBlur: 200, shadowColor: 'rgba(0, 0, 0, 0.5)' } }, animationType: 'scale', animationEasing: 'elasticOut', animationDelay: function (idx) { return Math.random() * 200; } } ]; } Vue.use(VueMaterial.default); Vue.filter('filter_slice', function (value) { return value.length > 32 ? value.slice(0, 32) + '...' : value; }); let vm = new Vue({ el: '#app', data: { page: 0, menuVisible: false, season_id: '', anime: { success: false, alias: '', area: [], danmaku_count: 0, episodes: 0, evaluate: '', favorites: 0, is_finish: false, pub_time: null, rating: { count: 0, score: 0 }, tags: [], title: '', last_long_reviews_cursor: null, last_short_reviews_cursor: null, top_matches: [], archives: [] }, mid: '', author: { success: false, reviews: [], uname: '', follow: [], last_crawl: null, last_analyze: null, top_matches: [], recommendation: [] }, charts: { archivesToLoad: 0, archivesRenderFinished: false, reviewsToLoad: 0, tagsRenderFinished: false, } }, watch: { season_id: function () { if (this.season_id) { this.$http.get(conf.animeBySeasonIdURLPrefix + this.season_id).then(response => { let anime = response.body; if (anime && typeof anime !== 'string') { this.anime.success = true; this.anime.alias = anime.alias; this.anime.danmaku_count = anime.danmaku_count; this.anime.episodes = anime.episodes; this.anime.evaluate = anime.evaluate; this.anime.favorites = anime.favorites; this.anime.is_finish = anime.is_finish; this.anime.pub_time = moment(anime.pub_time).format('LL'); this.anime.rating = anime.rating; this.anime.title = anime.title; const that = this; while (this.anime.area.length > 0) this.anime.area.pop(); if (anime.area) { anime.area.forEach(function (area) { that.anime.area.push(area.name); }); } while (this.anime.tags.length > 0) this.anime.tags.pop(); if (anime.tags) { anime.tags.forEach(function (tag) { that.anime.tags.push(tag.name); }); } while (this.anime.top_matches.length > 0) this.anime.top_matches.pop(); if (anime.top_matches) { anime.top_matches.forEach(function (pair) { that.$http.get(conf.animeByMediaIdURLPrefix + pair.media_id).then(response => { let other = response.body; other.similarity = pair.similarity; that.anime.top_matches.push(other); }, response => { }); }); } while (that.anime.archives.length > 0) that.anime.archives.pop(); this.$http.get(conf.archiveBySeasonIdURLPrefix + this.season_id).then(response => { let archives = response.body; if (archives && typeof archives !== 'string') { this.charts.archivesToLoad = archives.length; this.charts.archivesRenderFinished = false; archives.forEach(function (archive) { that.anime.archives.push(archive); }); } }, response => { }); } }, response => { this.anime.success = false; }); } }, mid: function () { if (this.mid) { this.$http.get(conf.authorByMidURLPrefix + this.mid).then(response => { let author = response.body; if (author && typeof author !== 'string') { this.author.success = true; this.author.uname = author.uname; this.author.follow = author.follow; if (author.last_crawl) { this.author.last_crawl = moment(author.last_crawl).format('LLL'); } else { this.author.last_crawl = null; } if (author.last_analyze) { this.author.last_analyze = moment(author.last_analyze).format('LLL'); } else { this.author.last_analyze = null; } const that = this; while (this.author.reviews.length > 0) this.author.reviews.pop(); if (author.reviews) { that.charts.reviewsToLoad = author.reviews.length; that.charts.tagsRenderFinished = false; author.reviews.forEach(function (review) { that.$http.get(conf.animeByMediaIdURLPrefix + review.media_id).then(response => { let anime = response.body; if (anime && typeof anime !== 'string') { review.anime_title = anime.title; review.anime_tags = anime.tags; review.ctime = moment(review.ctime).format('LLL'); review.mtime = moment(review.mtime).format('LLL'); that.author.reviews.push(review); } }, response => { }); }); } while (this.author.top_matches.length > 0) this.author.top_matches.pop(); if (author.top_matches) { author.top_matches.forEach(function (pair) { that.$http.get(conf.authorByMidURLPrefix + pair.mid).then(response => { let other = response.body; other.similarity = pair.similarity; that.author.top_matches.push(other); }, response => { }); }); } while (this.author.recommendation.length > 0) this.author.recommendation.pop(); if (author.recommendation) { author.recommendation.forEach(function (media_id) { that.$http.get(conf.animeByMediaIdURLPrefix + media_id).then(response => { that.author.recommendation.push(response.body); }, response => { }); }); } } }, response => { this.author.success = false; }); } }, }, methods: { switchPage: function (index) { this.page = index; this.menuVisible = false; }, applyAnime: function (season_id) { this.season_id = season_id; this.page = 0; }, applyAuthor: function (mid) { this.mid = mid; this.page = 1; }, updateAnimeArchiveCharts: function() { if (this.anime.archives) { let favoritesEl = document.getElementById('favorites-chart'); let danmakuEl = document.getElementById('danmaku-chart'); let reviewsEl = document.getElementById('reviews-chart'); if (favoritesEl && danmakuEl && reviewsEl) { let favoritesChart = echarts.init(favoritesEl); let danmakuChart = echarts.init(danmakuEl); let reviewsChart = echarts.init(reviewsEl); let dates = []; let favorites = []; let danmaku = []; let reviews = []; this.anime.archives.forEach(function (archive) { dates.push(moment(archive.date).format('LL')); favorites.push(archive.favorites); danmaku.push(archive.danmaku_count); reviews.push(archive.reviews_count); }); favoritesChart.setOption(new LineChartOption('่ฟฝ็•ชไบบๆ•ฐ', dates, favorites)); danmakuChart.setOption(new LineChartOption('ๅผนๅน•ๆ•ฐ้‡', dates, danmaku)); reviewsChart.setOption(new LineChartOption('่ฏ„่ฎบไบบๆ•ฐ', dates, reviews)); } } }, updateAuthorReviewsTagsChart: function() { if (this.author.reviews) { let tagsEl = document.getElementById('tags-chart'); if (tagsEl) { let tagsChart = echarts.init(tagsEl); let seriesData = []; let tags_count = new Map(); this.author.reviews.forEach(function (review) { if (review.anime_tags) { review.anime_tags.forEach(function (pair) { if (tags_count.has(pair.name)) { tags_count.set(pair.name, tags_count.get(pair.name) + 1); } else { tags_count.set(pair.name, 1); } }); } }); tags_count.forEach(function (value, key, map) { seriesData.push({ value: value, name: key }); }); tagsChart.setOption(new PieChartOption(seriesData)); } } } }, created: function () { document.getElementById('app').style.visibility = 'visible'; }, updated: function () { if (this.page === 0 && this.anime.archives && this.anime.archives.length === this.charts.archivesToLoad && !this.charts.archivesRenderFinished) { this.updateAnimeArchiveCharts(); this.charts.archivesRenderFinished = true; } else if (this.page === 1 && this.author.reviews && this.author.reviews.length === this.charts.reviewsToLoad && !this.charts.tagsRenderFinished) { this.updateAuthorReviewsTagsChart(); this.charts.tagsRenderFinished = true; } } }); <file_sep>/deploy.sh #!/bin/bash # Login Registry(Docker Hub) docker login -u "$DOCKER_USERNAME" -p "$DOCKER_PASSWORD" # Generate Image Author/Name/Tag image=angelmsger/bangumi-visualizer:${TRAVIS_TAG:-latest} # Tag Image docker tag bangumi-visualizer $image # Push to Registry(Docker Hub) docker push $image # Request Webhook # curl https://api.angelmsger.com/project/deploy/$image || /bin/true
b5719dfdc59d931603fcb4205f865b3ddb2cf1cc
[ "Markdown", "JavaScript", "Dockerfile", "Shell" ]
6
Dockerfile
AngelMsger/Bangumi-Visualizer
2b57e093b6dfb8e354a75e913e86fff8422a0d7a
fb2f60a6bc514da97583fc5a9e93e304c970faa5
refs/heads/master
<file_sep><?php namespace Antennaio\Clyde\Http\Controllers; use Illuminate\Contracts\Filesystem\Factory as Filesystem; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use League\Glide\Responses\SymfonyResponseFactory; use League\Glide\ServerFactory; use League\Glide\Signatures\SignatureFactory; use League\Glide\Signatures\SignatureException; class ClydeImageController extends Controller { /** * @var Filesystem */ protected $files; /** * @param Filesystem $files */ public function __construct(Filesystem $files) { $this->files = $files; } /** * Display image. * * @param Request $request * @param string $filename * * @return mixed */ public function show(Request $request, $filename) { if (config('clyde.secure_urls')) { try { SignatureFactory::create(config('clyde.sign_key')) ->validateRequest($request->path(), $request->all()); } catch (SignatureException $e) { return response()->json('Sorry, URL signature is invalid.'); } } $server = ServerFactory::create([ 'source' => $this->files->disk(config('clyde.source'))->getDriver(), 'source_path_prefix' => config('clyde.source_path_prefix'), 'cache' => $this->files->disk(config('clyde.cache'))->getDriver(), 'cache_path_prefix' => config('clyde.cache_path_prefix'), 'watermarks' => $this->files->disk(config('clyde.watermarks'))->getDriver(), 'watermarks_path_prefix' => config('clyde.watermarks_path_prefix'), 'driver' => config('clyde.driver'), 'max_image_size' => config('clyde.max_image_size'), 'presets' => config('clyde.presets'), 'response' => new SymfonyResponseFactory(), ]); return $server->outputImage($filename, $request->all()); } } <file_sep><?php namespace Antennaio\Clyde; use Illuminate\Support\ServiceProvider; class ClydeServiceProvider extends ServiceProvider { /** * Bootstrap the application events. */ public function boot() { $this->publishes([ __DIR__.'/../config/clyde.php' => config_path('clyde.php'), ]); if (!$this->app->routesAreCached()) { require __DIR__.'/Http/routes.php'; } } /** * Register bindings in the container. */ public function register() { $this->mergeConfigFrom(__DIR__.'/../config/clyde.php', 'clyde'); $this->app->bind('laravel-clyde-image', function ($app) { return $app->make(ClydeImage::class); }); $this->app->bind('laravel-clyde-upload', function ($app) { return $app->make(ClydeUpload::class); }); } }
777990c2624de128645858079babebfb521ee6e4
[ "PHP" ]
2
PHP
richiepearce/laravel-clyde
f3e4fafab6530de00c2447a15a79c50004b6063a
f792527dfff7cc497e80df8afab45b793feeca32
refs/heads/master
<repo_name>Trekivoy/Bataille-navale<file_sep>/main.c #include <stdio.h> #include <stdlib.h> #define IA_VS_IA 2 #define MAP_H 18 #define MAP_W 24 void load(int plateau [2][MAP_H][MAP_W]){ char c; int k; int i; int j; FILE *save=fopen("./save.txt","r"); for(k=0;k<2;k++){ for(i=0; i<18; i++){ for(j=0;j<24;j++){ c=fgetc(save); plateau[k][i][j]=c-'0'; } } } fclose(save); } void sauvegarde(int plateau [2][MAP_H][MAP_W]){ FILE *save=fopen("./save.txt","w+"); int i=0; int j=0; int k=0; for(k=0;k<2;k++){ for(i=0; i<18; i++){ for(j=0;j<24;j++){ fputc(plateau [k][i][j]+'0', save); } } } fclose(save); } void waitFor (unsigned int secs) { unsigned int retTime = time(0) + secs; // Get finishing time. while (time(0) < retTime); // Loop until it arrives. } int doRand(int startVal, int endVal){ waitFor(0.05); srand(time(NULL)*rand()); if(startVal == 0 && endVal == 1){ return rand() % 2; }else{ return (rand() % ((endVal + startVal -1)) + startVal); } } void affichage_plateau(int plateau[2][MAP_H][MAP_W], int joueur){ char alph[]="ABCDEFGHIJKLMONPQRSTU"; int i=joueur; int j=0; int k=0; printf("\n\nPlateau du joueur %d :", joueur+1); printf("\n 1 2 3 4 5 6 7 8 9 101112131415161718192021222324 "); for(j=0;j<18;j++){ printf("\n%c| ", alph[j]); for(k=0;k<24;k++){ printf("%d ", plateau[joueur][j][k]); } } } void placer(int plateau[2][MAP_H][MAP_W],int bateau[3],int joueur){ int ID_bateau=bateau[0]; int taille=bateau[1]; int nb=bateau[2]; int x=0; int y=0; int i=0; int j=0; int trigger=0; int taille_verif=0; int limite=0; while (i<nb){ int hor_vert=doRand(0,1); x=doRand(0,MAP_H-1); y=doRand(0,MAP_W-1); //VERIFICATIONS while (trigger !=99){ trigger=0; for(j=0;j<taille;j++){ if (hor_vert==0){ trigger+=plateau[joueur][x+j][y]; taille_verif=(x+taille); limite=18; } if (hor_vert==1){ trigger+=plateau[joueur][x][y+j]; taille_verif=(y+taille); limite=24; } } if ((trigger==0)&&(taille_verif<limite)){ trigger=99; }else{ x=doRand(0,MAP_H-1); y=doRand(0,MAP_W-1); } } for(j=0;j<taille;j++){ if (hor_vert==0){ plateau[joueur][x+j][y]=ID_bateau; } if (hor_vert==1){ plateau[joueur][x][y+j]=ID_bateau; } } i++; } } void tir_automatique(int tir_ver, int tir_hor,int player, int ID_joueur, int plateau[2][MAP_H][MAP_W], int points[player][1]){ printf("\nAu tour du joueur %d:\n", player+1); tir_hor=doRand(0,MAP_W-1); tir_ver=doRand(0,MAP_H-1); printf("\ncoordonnees chiffres:%d \n",tir_hor+1); printf("coordonnees lettres:%d \n", tir_ver+1); while (plateau[ID_joueur][tir_ver][tir_hor]>7){ printf("\ntir impossible recommence\n"); tir_hor++; if (tir_hor>MAP_W){ tir_hor=0; tir_ver++; if (tir_ver>MAP_H){ tir_ver=0; } } printf("\ncoordonnees chiffres:%d \n",tir_hor+1); printf("coordonnees lettres:%d \n", tir_ver+1); } if (plateau[ID_joueur][tir_ver][tir_hor]>0){ plateau[ID_joueur][tir_ver][tir_hor]=9; printf("\nTOUCHE !!!"); points[player][0]++; printf("\n Joueur %d || Points=%d",player+1 , points[player][0]); }else if (plateau[ID_joueur][tir_ver][tir_hor]==0){printf("\n Joueur %d || Points=%d",player+1 , points[player][0]); plateau[ID_joueur][tir_ver][tir_hor]=8; printf("\nRATE"); } affichage_plateau(plateau,ID_joueur); } void phase_de_tir(int tir_ver, int tir_hor,int player, int ID_joueur, int plateau[2][MAP_H][MAP_W], int points[player][1]){ printf("\nAu tour du joueur %d:\n", player+1); fflush(stdin); printf("\nEntrez coordonnees lettres :\n"); scanf("%d", &tir_ver); tir_ver--; printf("%d",tir_ver); while ((tir_ver<0)||(tir_ver>17)){ printf("Tir impossible, veuillez recommencer.\n"); scanf("%d", &tir_ver); tir_ver--; printf("%d",tir_ver); } fflush(stdin); printf("\nEntre coordonnees chiffres :\n"); scanf("%d",&tir_hor); tir_hor--; printf("%d",tir_hor); while ((tir_hor<0)||(tir_hor>23)){ printf("Tir impossible, recommence."); scanf("%d",&tir_hor); tir_hor--; printf("%d",tir_hor); } //VERIFICATION while (plateau[ID_joueur][tir_ver][tir_hor]>7){ printf("\n Recommence tu as deja tire ici ! "); fflush(stdin); printf("\nEntre coordonnees lettres :\n"); scanf("%d", &tir_ver); tir_ver--; printf("%d",tir_ver); while ((tir_ver<0)||(tir_ver>17)){ printf("Tir impossible, recommence."); scanf("%d", &tir_ver); tir_ver--; printf("%d",tir_ver); } fflush(stdin); printf("\nEntre coordonnees chiffres :\n"); scanf("%d",&tir_hor); tir_hor--; printf("%d",tir_hor); while ((tir_hor<0)||(tir_hor>23)){ printf("Tir impossible, recommence."); scanf("%d",&tir_hor); tir_hor--; printf("%d",tir_hor); } } if (plateau[ID_joueur][tir_ver][tir_hor]>0){ plateau[ID_joueur][tir_ver][tir_hor]=9; printf("\nTouche "); points[player][0]++; printf("\n Joueur %d || Points=%d",player+1 , points[player][0]); }else if (plateau[ID_joueur][tir_ver][tir_hor]==0){printf("\n Joueur %d || Points=%d\n",player+1 , points[player][0]); plateau[ID_joueur][tir_ver][tir_hor]=8; printf("PLOUF... "); } printf("\n+++FIN DU TOUR+++"); printf("\n+++APPUIE SUR UNE TOUCHE POUR CONTINUER+++\n\n"); fflush(stdin); getchar(); affichage_plateau(plateau,ID_joueur); } int main(){ int ID_joueur=0; int player=0; int i=0; int nb_joueurs=2; int tir_x=0; int tir_y=0; int nb_pts=0; int menu=0; int choix=0; int points[2][1]={0}; int corvette[3]={1,1,1}; int destroyer[3]={2,3,2}; int croiseur[3]={3,4,2}; int porte_avion[3]={5,6,1}; int plateau [IA_VS_IA][MAP_H][MAP_W]={0}; ID_joueur=0; placer(plateau,corvette,ID_joueur); placer(plateau,destroyer,ID_joueur); placer(plateau,croiseur,ID_joueur); placer(plateau,porte_avion,ID_joueur); ID_joueur=1; placer(plateau,corvette,ID_joueur); placer(plateau,destroyer,ID_joueur); placer(plateau,croiseur,ID_joueur); placer(plateau,porte_avion,ID_joueur); printf("\nVeux tu charger une partie ? \nOUI= 1 NON = 0\n"); scanf("%d", &choix); if (choix==1){ load(plateau); } printf("\nBataille navale :\n1= PvP \n2= PvE \n3= IAvsIA\nChoisis une des options\n"); scanf("%d", &menu); switch(menu){ case 1: while (points[player][0]<21){ ID_joueur=0; player=1; sauvegarde(plateau); phase_de_tir(tir_x,tir_y,player,ID_joueur, plateau, points); if (points[player][0]==21){ printf("\n\nFIN DU JEU ! Victoire du joueur %d", player+1); break; } ID_joueur=1; player=0; phase_de_tir(tir_x,tir_y,player,ID_joueur, plateau, points); if (points[player][0]==21){ printf("\n\nFIN DU JEU ! Victoire du joueur %d", player+1); break; } printf("\n Tour n.%d \n",i+1); i++; } case 2: while (points[player][0]<21){ ID_joueur=0; player=1; phase_de_tir(tir_x,tir_y,player,ID_joueur, plateau, points); if (points[player][0]==21){ printf("\n\nFIN DU JEU ! Victoire du joueur %d", player+1); break; } ID_joueur=1; player=0; tir_automatique(tir_x,tir_y,player,ID_joueur, plateau, points); if (points[player][0]==21){ printf("\n\n\nFIN DU JEU ! Victoire du joueur %d", player+1); break; } printf("\n Tour n.%d \n",i+1); i++; } case 3: while (points[player][0]<21){ ID_joueur=0; player=1; tir_automatique(tir_x,tir_y,player,ID_joueur, plateau, points); if (points[player][0]==21){ printf("\n\n\nFIN DU JEU ! Victoire du joueur %d", player+1); break; } ID_joueur=1; player=0; tir_automatique(tir_x,tir_y,player,ID_joueur, plateau, points); if (points[player][0]==21){ printf("\n\n\nFIN DU JEU ! Victoire du joueur %d", player+1); break; } printf("\n Tour n.%d \n",i+1); i++; } } }
d6e18cfd4375faacc666367481892084930416dc
[ "C" ]
1
C
Trekivoy/Bataille-navale
26c6ad3beed5e9fcd744171aabc21f4c6faa5fc2
e7923e91d7d26525a9faf5d0853bc8606f721418
refs/heads/master
<file_sep>๏ปฟusing Cognex.VisionPro; using Cognex.VisionPro.ImageFile; using Cognex.VisionPro.ToolBlock; using System; namespace VisionPro_Tut.Source { public class ObjectManager { //variable public CogImageFileTool mIFTool; public CogToolBlock mToolBlockProcess; public CogToolBlock mToolBlockAcq; public ulong numPass; public ulong numFail; private bool bUseCamera; public ObjectManager() { mToolBlockProcess = new CogToolBlock(); mToolBlockAcq = new CogToolBlock(); mIFTool = new CogImageFileTool(); numPass = 0; numFail = 0; bUseCamera = false; } public void InitObject(MyDefine Common) { Common.Print_Infor(); numPass = Common.numOK; numFail = Common.numNG; bUseCamera = Common.use_camera; mToolBlockProcess = CogSerializer.LoadObjectFromFile(Common.file_toolblock_process) as CogToolBlock; ToolBlock_PrintInfor(mToolBlockProcess); if (bUseCamera) { try { mToolBlockAcq = CogSerializer.LoadObjectFromFile(Common.file_toolblock_acq) as CogToolBlock; mToolBlockAcq.Ran += MToolBlockAcq_Ran; mToolBlockAcq.Changed += MToolBlockAcq_Changed; mToolBlockAcq.Running += MToolBlockAcq_Running; ToolBlock_PrintInfor(mToolBlockAcq); } catch (Exception e) { Console.WriteLine("Exception {0}", e.ToString()); } } else { //init mIFTool to get Image from database mIFTool.Operator.Open(Common.file_image_database, CogImageFileModeConstants.Read); } } private void MToolBlockAcq_Running(object sender, EventArgs e) { Console.WriteLine("MToolBlockAcq_Running"); } private void MToolBlockAcq_Changed(object sender, CogChangedEventArgs e) { Console.WriteLine("MToolBlockAcq_Changed"); } private void MToolBlockAcq_Ran(object sender, EventArgs e) { Console.WriteLine("MToolBlockAcq_Ran"); Console.WriteLine("Test step process when using camera 0 ...."); var result = (CogImage8Grey)(mToolBlockAcq.Outputs["Image"].Value); Utils.Save_BitMap(result.ToBitmap()); } public void ToolBlock_PrintInfor(CogToolBlock toolblock) { int numTools = toolblock.Tools.Count; Console.WriteLine($"-------------Toolblock {toolblock.Name} begin----------------"); Console.WriteLine("-------------element"); for (int i = 0; i < numTools; i++) { Console.WriteLine($"{toolblock.Tools[i].Name}"); //cur record Cognex.VisionPro.ICogRecord tmpRecord = toolblock.Tools[i].CreateCurrentRecord(); Console.WriteLine($"\ttmpRecord currentRecord = {tmpRecord.Annotation}"); for (int j = 0; j < tmpRecord.SubRecords.Count; j++) { Console.WriteLine($"\t\tj = {j}: {tmpRecord.SubRecords[j].Annotation}"); } //lastest record tmpRecord = toolblock.Tools[i].CreateLastRunRecord(); Console.WriteLine($"\ttmpRecord LastRecord = {tmpRecord.Annotation}"); for (int j = 0; j < tmpRecord.SubRecords.Count; j++) { Console.WriteLine($"\t\tj = {j}: {tmpRecord.SubRecords[j].Annotation}"); } } Console.WriteLine("-------------input"); int numInputs = toolblock.Inputs.Count; for (int i = 0; i < numInputs; i++) { Console.WriteLine($"{toolblock.Inputs[i].Name}"); } Console.WriteLine("-------------output"); int numOutputs = toolblock.Outputs.Count; for (int i = 0; i < numOutputs; i++) { Console.WriteLine($"{toolblock.Outputs[i].Name}"); } Console.WriteLine($"-------------Toolblock {toolblock.Name} end----------------"); } public void UpdateData(MyDefine Common) { mToolBlockProcess = CogSerializer.LoadObjectFromFile(Common.file_toolblock_process) as CogToolBlock; mIFTool.Operator.Open(Common.file_image_database, CogImageFileModeConstants.Read); } public void RunOnce() { // Get the next image if (!bUseCamera) { mIFTool.Run(); mToolBlockProcess.Inputs["Image"].Value = mIFTool.OutputImage as CogImage8Grey; } else { //FIXME: check output image of mToolBockAcq mToolBlockAcq.Run(); Console.WriteLine("Test step process when using camera 1...."); mToolBlockProcess.Inputs["Image"].Value = mToolBlockAcq.Outputs["Image"].Value; } // Run the toolblock mToolBlockProcess.Run(); } public void ReleaseObject() { if (mIFTool != null) mIFTool.Dispose(); //FIXME: check here if (mToolBlockAcq != null) mToolBlockAcq.Dispose(); if (mToolBlockProcess != null) mToolBlockProcess.Dispose(); } ~ObjectManager() { //ReleaseObject(); } } } <file_sep>๏ปฟusing System; using System.Collections.Generic; using System.IO.Ports; using System.Text; namespace VisionPro_Tut.Source.Interface { class MySerialPort { //data receive from server private string _data_receive = null; public string data_receive { get => _data_receive; set { _data_receive = value; OnNameChanged(value); } } //event private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage; public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage { add { _ReceiveMessage += value; } remove { _ReceiveMessage -= value; } } void OnNameChanged(string mess) { if (_ReceiveMessage != null) { _ReceiveMessage(this, new ReceivedMessageEventArgs(mess)); } } private string com_name = ""; private SerialPort serialPort = null; public List<string> list_comport; public bool is_success = false; public MySerialPort(SerialPortParam param) { Console.WriteLine("MySerialPort create"); //Check comport is exist? list_comport = new List<string>(); com_name = param.com_name; list_comport = Utils.Scan_Comport(); if (!list_comport.Contains(param.com_name)) { is_success = false; Console.WriteLine($"Could not find {param.com_name} in this PC"); return; } //register event serialPort = new SerialPort(); serialPort.PortName = param.com_name; serialPort.BaudRate = param.baudrate; serialPort.DataReceived += SerialPort_DataReceived; is_success = true; } ~MySerialPort() { if(is_success) { if (serialPort.IsOpen) serialPort.Close(); } Console.WriteLine("SerialPortManager destroy"); } public bool Connect() { bool is_connect = true; if (!this.serialPort.IsOpen) { this.serialPort.Open(); if (!this.serialPort.IsOpen) { is_connect = false; } } Console.WriteLine($"Connect = {is_connect}"); return is_connect; } public bool Disconnect() { bool is_disconnect = true; if (this.serialPort.IsOpen) { this.serialPort.Close(); if (this.serialPort.IsOpen) { is_disconnect = false; } } Console.WriteLine($"Disconnect = {is_disconnect}"); return is_disconnect; } public bool SendMessage(string message) { if (!this.serialPort.IsOpen) { Console.WriteLine($"{com_name} is not open, try again"); return false; } if (String.IsNullOrEmpty(message)) { Console.WriteLine("data2send is empty/null, retry"); return false; } this.serialPort.Write(message); return true; } private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { this.data_receive = this.serialPort.ReadExisting(); Console.WriteLine($"Data {com_name} received: {data_receive}"); } } } <file_sep>๏ปฟusing Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VisionPro_Tut.Source { class SaveLoadParameter { #region declare variable, object #endregion public SaveLoadParameter() { Console.WriteLine("SaveLoadParameter create ..."); } ~SaveLoadParameter() { Console.WriteLine("SaveLoadParameter destroy ..."); } public void Inital_Parameter() { //Create camera basler /*CameraPrameter cam_basler = new CameraPrameter(); cam_basler.Name = "Basler_10MP"; cam_basler.Format = CameraPrameter.EFormatCamera.MONO; cam_basler.Is_support = true; cam_basler.Fps = 10; cam_basler.Roi = new OpenCvSharp.Rect(0, 0, 1920, 1080); cam_basler.Use_calib = false; cam_basler.Flip = CameraPrameter.EFlipFrame.Flip_None; //Creater COM port ComportParameter com_light_control = new ComportParameter(); com_light_control.Name = "Light Controller"; com_light_control.Port_name = "COM2"; com_light_control.Baudrate = 9600; //Creater Socket-client SocketParameter socket_client = new SocketParameter(); socket_client.Name = "Client connect to Jump-Sys"; socket_client.Port = 8888; socket_client.Ip = "127.0.0.1"; //Add to parameter_manager parameter_manager.list_cam.Add(cam_basler); parameter_manager.list_comport.Add(com_light_control); parameter_manager.list_socket_client.Add(socket_client);*/ } public void Get_Parameter() { } public void Update_Parameter() { } public void Save_Parameter(MyDefine common) { // serialize JSON directly to a file Console.WriteLine(Utils.file_config); using (StreamWriter file = File.CreateText(Utils.file_config)) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(file, common); } } public bool Load_Parameter(ref MyDefine common) { //common = new MyDefine(); if (!File.Exists(Utils.file_config)) { Console.WriteLine($"file {Utils.file_config} not found..."); return false; } using (StreamReader file = File.OpenText(Utils.file_config)) { JsonSerializer serializer = new JsonSerializer(); common = (MyDefine)serializer.Deserialize(file, typeof(MyDefine)); } //common.Print_Infor(); Console.WriteLine($"file {Utils.file_config} load ok..."); return true; } } } <file_sep>๏ปฟusing System; using System.Threading; using System.Windows.Forms; using VisionPro_Tut.Source; using VisionPro_Tut.Source.Interface; namespace VisionPro_Tut { public partial class MainWindow : Form { #region Declare_variable_object MyDefine common = null; ObjectManager objectManager = null; SaveLoadParameter settingParam = null; MySerialPort serialPort = null; TcpChatClient chatClient = null; TcpChatServer chatServer = null; InterfaceManager interfaceManager = null; Thread thread_control_by_interface = null; bool run_thread = false; bool run_continue = false; #endregion //Consider code public MainWindow() { InitializeComponent(); Initial(); UpdateUI(); } void Initial() { common = new MyDefine(); settingParam = new SaveLoadParameter(); bool isLoadSuccess = settingParam.Load_Parameter(ref common); objectManager = new ObjectManager(); objectManager.InitObject(common); objectManager.mToolBlockProcess.Changed += mToolBlockProcess_Changed; objectManager.mToolBlockProcess.Running += mToolBlockProcess_Running; objectManager.mToolBlockProcess.Ran += mToolBlockProcess_Ran; objectManager.mToolBlockProcess.Inputs["FilterLowValue"].Value = common.blob_filter.area_low; objectManager.mToolBlockProcess.Inputs["FilterHighValue"].Value = common.blob_filter.area_high; interfaceManager = new InterfaceManager(common); //mode run switch (common.mode_run) { case Utils.MODE_RUN.Manual: break; case Utils.MODE_RUN.SerialPort: case Utils.MODE_RUN.TCP_Client: case Utils.MODE_RUN.TCP_Server: run_thread = true; thread_control_by_interface = new Thread(new ThreadStart(Thread_Control_By_Interface)); thread_control_by_interface.Name = "Thread control by interface"; thread_control_by_interface.IsBackground = true; thread_control_by_interface.Priority = ThreadPriority.AboveNormal; thread_control_by_interface.Start(); break; } //care thread ui + thread process CheckForIllegalCrossThreadCalls = false; } void UpdateUI() { lb_Toolblock_Process.Text = common.file_toolblock_process; lb_Toolblock_AcqFifo.Text = common.file_toolblock_acq; lb_ImgDatabase.Text = common.file_image_database; cb_UseCamera.Checked = common.use_camera; //result nPass.Text = common.numOK.ToString(); nFail.Text = common.numNG.ToString(); //param tbAreaHighBlob.Text = common.blob_filter.area_high.ToString(); tbAreaLowBlob.Text = common.blob_filter.area_low.ToString(); //cb_Comport var list_com = Utils.Scan_Comport(); for (int i = 0; i < list_com.Count; i++) cbb_Comport.Items.Add(list_com[i]); cbb_Comport.Text = common.serial_port.com_name; //tcp server tb_ServerIP.Text = common.tcp_server.ip; tb_ServerPort.Text = common.tcp_server.port.ToString(); //tcp client tb_ClientIP.Text = common.tcp_client.ip; tb_ClientPort.Text = common.tcp_client.port.ToString(); //cb_Baudrate binding with list baudrate var bindingBaudrate = new BindingSource(); bindingBaudrate.DataSource = Utils.list_baudrate; cbb_Baudrate.DataSource = bindingBaudrate.DataSource; cbb_Baudrate.Text = common.serial_port.baudrate.ToString(); //cb_Mode_Run var bindingModeRun = new BindingSource(); bindingModeRun.DataSource = Enum.GetValues(typeof(Utils.MODE_RUN)); cbb_ModeRun.DataSource = bindingModeRun.DataSource; cbb_ModeRun.Text = common.mode_run.ToString(); } void UpdateParam() { common.file_image_database = lb_ImgDatabase.Text; common.file_toolblock_process = lb_Toolblock_Process.Text; common.file_toolblock_acq = lb_Toolblock_AcqFifo.Text; common.use_camera = cb_UseCamera.Checked; //param common.blob_filter.area_high = Double.Parse(tbAreaHighBlob.Text); common.blob_filter.area_low = Double.Parse(tbAreaLowBlob.Text); //serial port common.serial_port.com_name = cbb_Comport.Text; common.serial_port.baudrate = int.Parse(cbb_Baudrate.Text); //tcp server common.tcp_server.ip = tb_ServerIP.Text; common.tcp_server.port = int.Parse(tb_ServerPort.Text); //tcp client common.tcp_client.ip = tb_ClientIP.Text; common.tcp_client.port = int.Parse(tb_ClientPort.Text); //mode run Enum.TryParse<Utils.MODE_RUN>(cbb_ModeRun.SelectedValue.ToString(), out common.mode_run); //result common.numOK = objectManager.numPass; common.numNG = objectManager.numFail; common.Print_Infor(); } private void MainWindow_Load(object sender, EventArgs e) { this.timer_DateTime.Start(); } private void MainWindow_FormClosing(object sender, FormClosingEventArgs e) { this.timer_DateTime.Stop(); this.interfaceManager.CloseInterface(); this.run_thread = false; //this.thread_control_by_interface.Abort(); //save param before close form UpdateParam(); settingParam.Save_Parameter(common); objectManager.ReleaseObject(); } #region Datetime_display private void timer_DateTime_Tick(object sender, EventArgs e) { this.lbDateTime.Text = DateTime.Now.ToString("ddd MM/dd/yyyy\nhh:mm::ss tt"); } #endregion } } <file_sep>๏ปฟusing Cognex.VisionPro; using Cognex.VisionPro.Blob; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Forms; using VisionPro_Tut.Source; using VisionPro_Tut.Source.Interface; using VisionPro_Tut.Windows; namespace VisionPro_Tut { public partial class MainWindow { #region CogToolBlock_event private void mToolBlockProcess_Changed(object sender, CogChangedEventArgs e) { // To see what has changed, look at the state flags that are contained in // the CogChangedEventArgs object. The StateFlags property is a bitfield, // where each bit represents a single element of the tool that may have changed. If a bit // is asserted, that element in the tool has changed. Multiple bits may be asserted // simultaneously. To see what has changed, bitwise AND the StateFlags with the static // Sf**** members in the tool class. If it returns a value greater than 0, then that // particular element has changed. // In the example below, we are testing to see if the RunStatus property has changed // by bitwise AND'ing StateFlags with SfRunStatus. // Report error conditions, if any. Console.WriteLine("mToolBlockProcess_Changed"); if ((e.StateFlags & CogBlobTool.SfRunStatus) > 0) { if (objectManager.mToolBlockProcess.RunStatus.Result == CogToolResultConstants.Error) Console.WriteLine(objectManager.mToolBlockProcess.RunStatus.Message); } } private void mToolBlockProcess_Running(object sender, EventArgs e) { // Get input image. Console.WriteLine("mToolBlockProcess_Running"); } string Blob_Packet(CogBlobResult blob) { return String.Format($"{objectManager.mToolBlockProcess.RunStatus.Result},ID={blob.ID},angle={blob.Angle},x={blob.CenterOfMassX},y={blob.CenterOfMassY}\r\n"); } private void mToolBlockProcess_Ran(object sender, EventArgs e) { // This method executes each time the TB runs bool result = (bool)(objectManager.mToolBlockProcess.Outputs["InspectionPassed"].Value); if (result) objectManager.numPass++; else objectManager.numFail++; // Update the label with pass and fail nPass.Text = objectManager.numPass.ToString(); nFail.Text = objectManager.numFail.ToString(); CogBlobTool mBlobTool = objectManager.mToolBlockProcess.Tools["CogBlobTool1"] as CogBlobTool; //get result var blobResult = mBlobTool.Results; var all_blob = blobResult.GetBlobs(); Console.WriteLine($"number blob detected = {all_blob.Count}"); for (int i = 0; i < all_blob.Count; i++) interfaceManager.SendMessage(Blob_Packet(all_blob[i])); //var blobRunParam = mBlobTool.RunParams; //Assign picture to display ICogRecord temp = mBlobTool.CreateLastRunRecord(); //temp = temp.SubRecords["BlobImage"]; temp = temp.SubRecords["InputImage"]; cogRecordDisplay1.Record = temp; cogRecordDisplay1.Fit(true); Display(result); Console.WriteLine("Ran done!, time processing = {0} ms", objectManager.mToolBlockProcess.RunStatus.TotalTime); } #endregion #region GUI_event static bool isPressRunContinue = false; static bool isPressClientConnect = false; static bool isPressServerListen = false; static bool isRunContinue = false; Thread thread_run_continue = null; private void btn_Click_Event(object sender, EventArgs e) { var curButton = sender as Button; Console.WriteLine($"btn_Click_Event name = {curButton.Name}"); switch (curButton.Name) { case "btnRun": objectManager.RunOnce(); break; case "btnRunContinue": if(!isPressRunContinue) { try { isRunContinue = true; thread_run_continue = new Thread(new ThreadStart(Thread_Run_Continuously)); thread_run_continue.Name = "thread run continue"; thread_run_continue.IsBackground = true; thread_run_continue.Start(); } catch (ThreadStateException ee) { Console.WriteLine("Caught: {0}", ee.Message); } } else { isRunContinue = false; //thread_run_continue.Abort(); } isPressRunContinue = !isPressRunContinue; break; case "btnSaveParam": UpdateParam(); settingParam.Save_Parameter(common); break; case "btnInitial": UpdateToolBlock(); break; case "btn_ClientConnect": { if (!isPressClientConnect) { if(chatClient.Connect()) { isPressClientConnect = true; btn_ClientConnect.Text = "Disconnect"; } } else { if(chatClient.DisConnect()) { isPressClientConnect = false; btn_ClientConnect.Text = "Connect"; } } } break; case "btn_ClientSend": chatClient.SendMessage(tx_ClientData2Send.Text); break; case "btn_ServerListen": { if (!isPressServerListen) { if (chatServer.Listen()) { isPressServerListen = true; btn_ServerListen.Text = "Stop"; } } else { if (chatServer.Stop()) { isPressServerListen = false; btn_ServerListen.Text = "Listen"; } } } break; case "btn_ServerSend": chatServer.SendMessage(tb_ServerData2Send.Text); break; } } private void ToolStripMenuItem_Click(object sender, EventArgs e) { var strip_menu = sender as ToolStripMenuItem; Console.WriteLine("MenuItem click = {0}", strip_menu.Name); switch (strip_menu.Name) { case "load_ImageProcessItem": ToolBlockWindow win2 = new ToolBlockWindow(objectManager, common.file_toolblock_process, Utils.TYPE_OF_TOOLBLOCK.ImageProcess); if (win2.ShowDialog() == DialogResult.OK) { objectManager.mToolBlockProcess = win2.objectManager.mToolBlockProcess; objectManager.ToolBlock_PrintInfor(objectManager.mToolBlockProcess); Console.WriteLine("update done {0}", objectManager.mToolBlockProcess.Name); } win2.Dispose(); break; case "load_AcqFifoItem": if(!common.use_camera) { System.Windows.Forms.MessageBox.Show("Warning","You not using camera, please recheck!", MessageBoxButtons.OK); break; } ToolBlockWindow win3 = new ToolBlockWindow(objectManager, common.file_toolblock_acq, Utils.TYPE_OF_TOOLBLOCK.AcqFifo); if (win3.ShowDialog() == DialogResult.OK) { objectManager.mToolBlockAcq = win3.objectManager.mToolBlockAcq; objectManager.ToolBlock_PrintInfor(objectManager.mToolBlockAcq); Console.WriteLine("update done {0}", objectManager.mToolBlockAcq.Name); } win3.Dispose(); break; default: break; } } private void label_Click_Event(object sender, EventArgs e) { var curLabel = sender as Label; Console.WriteLine($"label_Click_Event name = {curLabel.Name}"); OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.CheckFileExists = true; openFileDialog1.CheckPathExists = true; openFileDialog1.FilterIndex = 1; openFileDialog1.RestoreDirectory = true; //openFileDialog1.ReadOnlyChecked = true, openFileDialog1.ShowReadOnly = true; switch (curLabel.Name) { case "lb_ImgDatabase": openFileDialog1.InitialDirectory = Utils.path_load_img_database; openFileDialog1.Title = "Browse Image Database Files"; openFileDialog1.DefaultExt = "idb"; openFileDialog1.Filter = "idb files (*.idb)|*.idb|All files (*.*)|*.*"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { lb_ImgDatabase.Text = openFileDialog1.FileName; common.file_image_database = lb_ImgDatabase.Text; } break; case "lb_Toolblock": openFileDialog1.InitialDirectory = Utils.path_load_vpp_file; openFileDialog1.Title = "Browse Toolblock Files"; openFileDialog1.DefaultExt = "vpp"; openFileDialog1.Filter = "vpp files (*.vpp)|*.vpp|All files (*.*)|*.*"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { lb_Toolblock_Process.Text = openFileDialog1.FileName; common.file_toolblock_process = lb_Toolblock_Process.Text; } break; case "lb_Toolblock_Process": openFileDialog1.InitialDirectory = Utils.path_load_vpp_file; openFileDialog1.Title = "Browse Toolblock_ImageProcess Files"; openFileDialog1.DefaultExt = "vpp"; openFileDialog1.Filter = "vpp files (*.vpp)|*.vpp|All files (*.*)|*.*"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { lb_Toolblock_Process.Text = openFileDialog1.FileName; common.file_toolblock_process = lb_Toolblock_Process.Text; } break; case "lb_Toolblock_AcqFifo": openFileDialog1.InitialDirectory = Utils.path_load_vpp_file; openFileDialog1.Title = "Browse Toolblock_Acq Files"; openFileDialog1.DefaultExt = "vpp"; openFileDialog1.Filter = "vpp files (*.vpp)|*.vpp|All files (*.*)|*.*"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { lb_Toolblock_AcqFifo.Text = openFileDialog1.FileName; common.file_toolblock_acq = lb_Toolblock_AcqFifo.Text; } break; default: break; } } protected override void Dispose(bool disposing) { // Disconnect the event handlers before closing the form objectManager.mToolBlockProcess.Ran -= new EventHandler(mToolBlockProcess_Ran); objectManager.mToolBlockProcess.Running -= new EventHandler(mToolBlockProcess_Running); objectManager.mToolBlockProcess.Changed -= new CogChangedEventHandler(mToolBlockProcess_Changed); if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #endregion } } <file_sep>๏ปฟusing Cognex.VisionPro; using Cognex.VisionPro.ToolBlock; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using VisionPro_Tut.Source; namespace VisionPro_Tut.Windows { public partial class ToolBlockWindow : Form { #region declera variable, object private Utils.TYPE_OF_TOOLBLOCK type_of_block; public ObjectManager objectManager; public CogToolBlock toolblock; private string path_vpp_file; private ToolStripMenuItem saveAsToolStripMenuItem; private ToolStripMenuItem runToolStripMenuItem; #endregion public ToolBlockWindow() { Console.WriteLine("Tool block window default"); InitializeComponent(); } public ToolBlockWindow(ObjectManager objectManager, string path_vpp, Utils.TYPE_OF_TOOLBLOCK type_of_block) { Console.WriteLine("Tool block window create, path vpp_file = {0}, type_of_block = {1}", path_vpp, type_of_block); this.type_of_block = type_of_block; this.objectManager = objectManager; this.toolblock = new CogToolBlock(); this.path_vpp_file = path_vpp; InitializeComponent(); } private void MenuClick_Event(object sender, EventArgs e) { var menu_item = sender as ToolStripMenuItem; Console.WriteLine(menu_item.Text); switch (menu_item.Text) { case "Load": break; case "Save": Console.WriteLine($"Save file {this.path_vpp_file}"); switch (this.type_of_block) { case Utils.TYPE_OF_TOOLBLOCK.AcqFifo: File.WriteAllBytes(this.path_vpp_file, Utils.Serialize(this.objectManager.mToolBlockAcq)); break; case Utils.TYPE_OF_TOOLBLOCK.ImageProcess: File.WriteAllBytes(this.path_vpp_file, Utils.Serialize(this.objectManager.mToolBlockProcess)); break; case Utils.TYPE_OF_TOOLBLOCK.Other: File.WriteAllBytes(this.path_vpp_file, Utils.Serialize(this.toolblock)); Console.WriteLine($"{this.path_vpp_file}-> {this.type_of_block}!"); break; } break; case "Save As": SaveFileDialog saveToolBlock = new SaveFileDialog(); saveToolBlock.Filter = "ToolBlock |*.vpp|All File|*.*"; saveToolBlock.Title = "Save a Toolblock file"; saveToolBlock.RestoreDirectory = true; saveToolBlock.ShowDialog(); if (saveToolBlock.FileName != null) { Console.WriteLine(saveToolBlock.FileName); switch (this.type_of_block) { case Utils.TYPE_OF_TOOLBLOCK.AcqFifo: File.WriteAllBytes(saveToolBlock.FileName, Utils.Serialize(this.objectManager.mToolBlockAcq)); break; case Utils.TYPE_OF_TOOLBLOCK.ImageProcess: File.WriteAllBytes(saveToolBlock.FileName, Utils.Serialize(this.objectManager.mToolBlockProcess)); break; case Utils.TYPE_OF_TOOLBLOCK.Other: File.WriteAllBytes(saveToolBlock.FileName, Utils.Serialize(this.toolblock)); break; } } break; case "OK": switch (this.type_of_block) { case Utils.TYPE_OF_TOOLBLOCK.AcqFifo: case Utils.TYPE_OF_TOOLBLOCK.ImageProcess: Close(); DialogResult = DialogResult.OK; break; case Utils.TYPE_OF_TOOLBLOCK.Other: Close(); break; } break; case "Run": switch (this.type_of_block) { case Utils.TYPE_OF_TOOLBLOCK.AcqFifo: this.objectManager.mToolBlockAcq.Run(); break; case Utils.TYPE_OF_TOOLBLOCK.ImageProcess: this.objectManager.RunOnce(); break; case Utils.TYPE_OF_TOOLBLOCK.Other: this.toolblock.Run(); break; } break; } } private void ToolBlockWindow_Load(object sender, EventArgs e) { //Load Toolblock and show on window Console.WriteLine("ToolBlockWindow_Load"); cogToolBlockEditV21.LocalDisplayVisible = false; switch (this.type_of_block) { case Utils.TYPE_OF_TOOLBLOCK.AcqFifo: cogToolBlockEditV21.Subject = this.objectManager.mToolBlockAcq; break; case Utils.TYPE_OF_TOOLBLOCK.ImageProcess: cogToolBlockEditV21.Subject = this.objectManager.mToolBlockProcess; break; case Utils.TYPE_OF_TOOLBLOCK.Other: cogToolBlockEditV21.Subject = this.toolblock; break; } cogToolBlockEditV21.SubjectChanged += new EventHandler(cogToolBlockEditV21_SubjectChanged); } private void ToolBlockWindow_FormClosing(object sender, FormClosingEventArgs e) { //Close and release resource Console.WriteLine("ToolBlockWindow_FormClosing"); } void cogToolBlockEditV21_SubjectChanged(object sender, EventArgs e) { // The application is meant to be used with the TB.vpp so whenever the user changes the TB Console.WriteLine("cogToolBlockEditV21_SubjectChanged"); } #region GUI private Cognex.VisionPro.ToolBlock.CogToolBlockEditV2 cogToolBlockEditV21; private Label lbStatus; private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem saveToolStripMenuItem; private ToolStripMenuItem oKToolStripMenuItem; private MenuStrip menuStrip1; private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) { Console.WriteLine($"Dispose = {disposing}"); cogToolBlockEditV21.SubjectChanged -= new EventHandler(cogToolBlockEditV21_SubjectChanged); if (disposing && (components != null)) { components.Dispose(); Console.WriteLine("components.Dispose();"); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cogToolBlockEditV21 = new Cognex.VisionPro.ToolBlock.CogToolBlockEditV2(); this.lbStatus = new System.Windows.Forms.Label(); this.loadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.oKToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.runToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)(this.cogToolBlockEditV21)).BeginInit(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // cogToolBlockEditV21 // this.cogToolBlockEditV21.AllowDrop = true; this.cogToolBlockEditV21.ContextMenuCustomizer = null; this.cogToolBlockEditV21.Location = new System.Drawing.Point(-3, 27); this.cogToolBlockEditV21.MinimumSize = new System.Drawing.Size(489, 0); this.cogToolBlockEditV21.Name = "cogToolBlockEditV21"; this.cogToolBlockEditV21.ShowNodeToolTips = true; this.cogToolBlockEditV21.Size = new System.Drawing.Size(808, 410); this.cogToolBlockEditV21.SuspendElectricRuns = false; this.cogToolBlockEditV21.TabIndex = 0; // // lbStatus // this.lbStatus.Location = new System.Drawing.Point(3, 445); this.lbStatus.Name = "lbStatus"; this.lbStatus.Size = new System.Drawing.Size(802, 23); this.lbStatus.TabIndex = 1; this.lbStatus.Text = "Status"; // // loadToolStripMenuItem // this.loadToolStripMenuItem.Name = "loadToolStripMenuItem"; this.loadToolStripMenuItem.Size = new System.Drawing.Size(45, 20); this.loadToolStripMenuItem.Text = "Load"; this.loadToolStripMenuItem.Click += new System.EventHandler(this.MenuClick_Event); // // saveToolStripMenuItem // this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; this.saveToolStripMenuItem.Size = new System.Drawing.Size(43, 20); this.saveToolStripMenuItem.Text = "Save"; this.saveToolStripMenuItem.Click += new System.EventHandler(this.MenuClick_Event); // // oKToolStripMenuItem // this.oKToolStripMenuItem.Name = "oKToolStripMenuItem"; this.oKToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.oKToolStripMenuItem.Text = "OK"; this.oKToolStripMenuItem.Click += new System.EventHandler(this.MenuClick_Event); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.loadToolStripMenuItem, this.saveToolStripMenuItem, this.saveAsToolStripMenuItem, this.runToolStripMenuItem, this.oKToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(807, 24); this.menuStrip1.TabIndex = 2; this.menuStrip1.Text = "menuStrip1"; // // runToolStripMenuItem // this.runToolStripMenuItem.Name = "runToolStripMenuItem"; this.runToolStripMenuItem.Size = new System.Drawing.Size(40, 20); this.runToolStripMenuItem.Text = "Run"; this.runToolStripMenuItem.Click += new System.EventHandler(this.MenuClick_Event); // // saveAsToolStripMenuItem // this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem"; this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(59, 20); this.saveAsToolStripMenuItem.Text = "Save As"; // // ToolBlockWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(807, 468); this.Controls.Add(this.lbStatus); this.Controls.Add(this.cogToolBlockEditV21); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.Name = "ToolBlockWindow"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ToolBlockWindow_FormClosing); this.Load += new System.EventHandler(this.ToolBlockWindow_Load); ((System.ComponentModel.ISupportInitialize)(this.cogToolBlockEditV21)).EndInit(); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion #endregion } } <file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace VisionPro_Tut.Source.Interface { class ChatSession : TcpSession { //data receive from server private string _data_receive = null; public string data_receive { get => _data_receive; set { _data_receive = value; OnNameChanged(value); } } //event private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage; public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage { add { _ReceiveMessage += value; } remove { _ReceiveMessage -= value; } } void OnNameChanged(string mess) { if (_ReceiveMessage != null) { _ReceiveMessage(this, new ReceivedMessageEventArgs(mess)); } } public ChatSession(TcpServer server) : base(server) { } protected override void OnConnected() { Console.WriteLine($"Chat TCP session with Id {Id} connected!"); // Send invite message string message = "Hello from TCP chat! Please send a message or '!' to disconnect the client!"; SendAsync(message); } protected override void OnDisconnected() { Console.WriteLine($"Chat TCP session with Id {Id} disconnected!"); } protected override void OnReceived(byte[] buffer, long offset, long size) { string message = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); Console.WriteLine("Incoming: " + message); // Multicast message to all connected sessions Server.Multicast(message); // If the buffer starts with '!' the disconnect the current session if (message == "!") Disconnect(); data_receive = message; } protected override void OnError(SocketError error) { Console.WriteLine($"Chat TCP session caught an error with code {error}"); } } class ChatServer : TcpServer { //data receive from server private string _data_receive = null; public string data_receive { get => _data_receive; set { _data_receive = value; OnNameChanged(value); } } //event private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage; public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage { add { _ReceiveMessage += value; } remove { _ReceiveMessage -= value; } } void OnNameChanged(string mess) { if (_ReceiveMessage != null) { _ReceiveMessage(this, new ReceivedMessageEventArgs(mess)); } } public ChatServer(IPAddress address, int port) : base(address, port) { } private void Chatss_ReceiveMessage(object sender, ReceivedMessageEventArgs e) { Console.WriteLine("%%%%%%%%%%%%%%" + e.Message); data_receive = e.Message; } protected override TcpSession CreateSession() { ChatSession chatss = new ChatSession(this); chatss.ReceiveMessage += Chatss_ReceiveMessage; return chatss; } protected override void OnError(SocketError error) { Console.WriteLine($"Chat TCP server caught an error with code {error}"); } } public class TcpChatServer { //data receive from server private string _data_receive = null; public string data_receive { get => _data_receive; set { _data_receive = value; OnNameChanged(value); } } //event private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage; public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage { add { _ReceiveMessage += value; } remove { _ReceiveMessage -= value; } } void OnNameChanged(string mess) { if (_ReceiveMessage != null) { _ReceiveMessage(this, new ReceivedMessageEventArgs(mess)); } } //tcp chat server ChatServer server; public TcpChatServer(TCPParam param) { server = new ChatServer(IPAddress.Parse(param.ip), param.port); server.ReceiveMessage += Server_ReceiveMessage; } private void Server_ReceiveMessage(object sender, ReceivedMessageEventArgs e) { data_receive = e.Message; } ~TcpChatServer() { } public bool Listen() { // Start the server Console.Write("Server starting..."); bool bStart = server.Start(); Console.WriteLine("Done!"); return bStart; } public bool Stop() { Console.Write("Server Stop..."); bool bStop = server.Stop(); Console.WriteLine("Done!"); return bStop; } public bool SendMessage(string mess) { // Multicast admin message to all sessions bool bSend = server.Multicast(mess); return bSend; } } } <file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using static VisionPro_Tut.Source.Utils; namespace VisionPro_Tut.Source.Interface { public class InterfaceManager { //data receive from server private string _data_receive = null; public string data_receive { get => _data_receive; set { _data_receive = value; OnNameChanged(value); } } //event private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage; public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage { add { _ReceiveMessage += value; } remove { _ReceiveMessage -= value; } } void OnNameChanged(string mess) { if (_ReceiveMessage != null) { _ReceiveMessage(this, new ReceivedMessageEventArgs(mess)); } } //variable MySerialPort serialPort = null; TcpChatClient chatClient = null; TcpChatServer chatServer = null; MyDefine param; public string data_receiver; public InterfaceManager(MyDefine param) { this.param = param; //mode run switch (param.mode_run) { case MODE_RUN.Manual: break; case MODE_RUN.SerialPort: serialPort = new MySerialPort(param.serial_port); serialPort.ReceiveMessage += Event_ReceiveMessage; if (serialPort.is_success) { bool bConnectCOM = serialPort.Connect(); Console.WriteLine($"Comport {param.serial_port.com_name} connect ok"); } break; case MODE_RUN.TCP_Client: chatClient = new TcpChatClient(param.tcp_client); chatClient.ReceiveMessage += Event_ReceiveMessage; bool bClientConnect = chatClient.Connect(); if(bClientConnect) { Console.WriteLine($"Client connected to {param.tcp_client.ip}:{param.tcp_client.port} ok"); } break; case MODE_RUN.TCP_Server: chatServer = new TcpChatServer(param.tcp_server); chatServer.ReceiveMessage += Event_ReceiveMessage; bool bServerListen = chatServer.Listen(); if (bServerListen) { Console.WriteLine($"Server listen in {param.tcp_server.ip}:{param.tcp_server.port} ok"); } break; } } private void Event_ReceiveMessage(object sender, ReceivedMessageEventArgs e) { data_receive = e.Message; Console.WriteLine($"Interface data = {data_receive}"); } public bool SendMessage(string mess) { switch (param.mode_run) { case MODE_RUN.Manual: break; case MODE_RUN.SerialPort: serialPort.SendMessage(mess); break; case MODE_RUN.TCP_Client: chatClient.SendMessage(mess); break; case MODE_RUN.TCP_Server: chatServer.SendMessage(mess); break; } return true; } public void CloseInterface() { switch (param.mode_run) { case MODE_RUN.Manual: break; case MODE_RUN.SerialPort: if(serialPort != null) { bool ComportClose = serialPort.Disconnect(); Console.WriteLine($"Serialport close {param.serial_port.baudrate} ok"); } break; case MODE_RUN.TCP_Client: if (chatClient != null) { bool clientDisconnect = chatClient.DisConnect(); Console.WriteLine($"Client disconnect form {param.tcp_client.ip}:{param.tcp_client.port} ok"); } break; case MODE_RUN.TCP_Server: if (chatServer != null) { bool serverStop = chatServer.Stop(); Console.WriteLine($"Server close in {param.tcp_server.ip}:{param.tcp_server.port} ok"); } break; } } } } <file_sep>๏ปฟusing System; using System.Collections.Generic; using System.IO; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks; using VisionPro_Tut.Source; using static VisionPro_Tut.Source.Utils; using System.Runtime.Serialization.Formatters.Binary; using System.Drawing; using System.Drawing.Imaging; namespace VisionPro_Tut.Source { public class ReceivedMessageEventArgs : EventArgs { public string Message { get; set; } public ReceivedMessageEventArgs(string name) { Message = name; } } public class Utils { public enum TYPE_OF_TOOLBLOCK { Other = 0, AcqFifo, ImageProcess } public enum MODE_RUN { Manual = 0, SerialPort, TCP_Client, TCP_Server } public const string TRIGGER = "TRIGGER"; public const string RUNLOOP = "LOOP"; public static readonly string workingDirectory = Environment.CurrentDirectory; //C:\Users\Admin\Downloads\tuanken92\VisionPro_Tut\bin\Debug public static readonly string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName; //C:\Users\Admin\Downloads\tuanken92\VisionPro_Tut public static readonly string workspaceDirectory = Directory.GetParent(workingDirectory).Parent.Parent.FullName; //C:\Users\Admin\Downloads\tuanken92 public static readonly string file_config = String.Format($"{projectDirectory}\\Data\\config_param.json"); public static readonly string path_load_img_database = @"C:\Program Files\Cognex\VisionPro\Images"; public static readonly string path_load_vpp_file = @"C:\Users\Admin\Desktop\Vpp_file"; public static readonly string path_save_images = String.Format("{0}\\Images", projectDirectory); public static readonly List<int> list_baudrate = new List<int>{ 9600, 14400, 19200, 38400, 57600, 115200, 128000, 256000 }; public static List<string> Scan_Comport() { string[] ArrayComPortsNames = null; int index = -1; ArrayComPortsNames = SerialPort.GetPortNames(); do { index += 1; } while (!(index == ArrayComPortsNames.GetUpperBound(0))); Array.Sort(ArrayComPortsNames); foreach (var com_name in ArrayComPortsNames) Console.WriteLine(com_name); return (new List<string>(ArrayComPortsNames)); } public static byte[] Serialize(Object obj) { MemoryStream memoryStream = new MemoryStream(); BinaryFormatter binaryFomatter = new BinaryFormatter(); binaryFomatter.Serialize(memoryStream, obj); return memoryStream.ToArray(); } public static Object Deserialize(byte[] data) { MemoryStream stream = new MemoryStream(data); BinaryFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(stream); } public static bool CreateFolder(string path_folder) { bool result = Directory.Exists(path_folder); if (!result) { Directory.CreateDirectory(path_folder); result = Directory.Exists(path_folder); } return result; } public static string GenerateNameImage() { CreateFolder(path_save_images); return String.Format("{0}\\{1}.jpg", path_save_images, DateTime.Now.ToString("yyyyMMdd_hhmmss")); } public static void Save_BitMap(Bitmap bm) { string file_name = GenerateNameImage(); bm.Save(file_name, ImageFormat.Jpeg); Console.WriteLine("Saved file {0}", file_name); } } public class BlobFilter { public double area_low; public double area_high; public BlobFilter() { area_low = 0; area_high = 0; } public void Print_Infor() { Console.WriteLine($"\tblob filter area low = {area_low}"); Console.WriteLine($"\tblob filter area high = {area_high}"); } } public class SerialPortParam { public string com_name; public int baudrate; public SerialPortParam() { com_name = "COM1"; baudrate = 115200; } public void Print_Infor() { Console.WriteLine($"\tSerialport name = {com_name}"); Console.WriteLine($"\tSerialport baudrate = {baudrate}"); } } public class TCPParam { public string name; public string ip; public int port; public TCPParam() { ip = "127.0.0.1"; port = 8686; name = null; } public TCPParam(string name, string ip, int port) { this.name = name; this.ip = ip; this.port = port; } public void Print_Infor() { Console.WriteLine($"\tTcp name = {name}"); Console.WriteLine($"\tTcp address = {ip}:{port}"); } } public class MyDefine { public bool use_camera = true; public string file_image_database = Environment.GetEnvironmentVariable("VPRO_ROOT") + @"\images\coins.idb"; public string file_toolblock_process = Environment.GetEnvironmentVariable("VPRO_ROOT") + @"\samples\programming\toolblock\toolblockload\tb.vpp"; public string file_toolblock_acq = String.Format($"{projectDirectory}\\Data\\TB_ac3800_10gm.vpp"); public ulong numOK = 0; public ulong numNG = 0; public MODE_RUN mode_run = MODE_RUN.Manual; public BlobFilter blob_filter = new BlobFilter(); public SerialPortParam serial_port = new SerialPortParam(); public TCPParam tcp_client = new TCPParam("Client", "127.0.0.1", 5001); public TCPParam tcp_server = new TCPParam("Server", "127.0.0.1", 5002); public void Print_Infor() { Console.WriteLine("----MyDefine begin---"); Console.WriteLine($"\tmode run = {mode_run}"); Console.WriteLine($"\tuse_camera = {use_camera}"); Console.WriteLine($"\tfile_image_database = {file_image_database}"); Console.WriteLine($"\tfile_toolblock_process = {file_toolblock_process}"); Console.WriteLine($"\tfile_toolblock_acq = {file_toolblock_acq}"); Console.WriteLine($"\tnumber OK = {numOK}"); Console.WriteLine($"\tnumber NG = {numNG}"); blob_filter.Print_Infor(); serial_port.Print_Infor(); tcp_client.Print_Infor(); tcp_server.Print_Infor(); Console.WriteLine("----MyDefine end---"); } } } <file_sep>๏ปฟusing Cognex.VisionPro; using System; using System.Drawing; using System.Threading; using VisionPro_Tut.Source; using VisionPro_Tut.Source.Interface; namespace VisionPro_Tut { public partial class MainWindow { #region funtion process void Thread_Run_Continuously() { try { while (isRunContinue) { Thread.Sleep(1000); //TODO: care timeout processing objectManager.RunOnce(); } Console.WriteLine(Thread.CurrentThread.Name + "end"); } catch (ThreadAbortException e) { Console.WriteLine($"{Thread.CurrentThread.Name} exception: {e.ToString()}"); } } void Thread_Control_By_Interface() { try { while (run_thread) { Thread.Sleep(100); if (interfaceManager.data_receive != null) { Console.WriteLine(interfaceManager.data_receive); switch (interfaceManager.data_receive) { case Utils.TRIGGER: run_continue = false; objectManager.RunOnce(); break; case Utils.RUNLOOP: run_continue = true; objectManager.RunOnce(); break; default: break; } interfaceManager.data_receive = null; } } } catch (ThreadAbortException e) { Console.WriteLine($"{Thread.CurrentThread.Name} exception: {e.ToString()}"); } } void UpdateToolBlock() { objectManager.mToolBlockProcess.Inputs["FilterLowValue"].Value = common.blob_filter.area_low; objectManager.mToolBlockProcess.Inputs["FilterHighValue"].Value = common.blob_filter.area_high; } public void Display(bool result) { CogGraphicLabel cglCaption = new CogGraphicLabel(); Font myFont = new Font("Comic Sans MS", 16, FontStyle.Bold); // Set it's text and alignment properties cglCaption.Text = result ? "PASS" : "FAIL"; cglCaption.Color = result ? CogColorConstants.Green : CogColorConstants.Red; cglCaption.Alignment = CogGraphicLabelAlignmentConstants.BottomLeft; // .NET fonts are read only, so create a new font and then // push this font object onto the Font property of the label // myFont = new Font("Comic Sans MS", 18, FontStyle.Bold); cglCaption.Font = myFont; // Set its space to be '*' - anchored to the image cglCaption.SelectedSpaceName = "*"; // Position the label over the CogDisplay cglCaption.X = 50; cglCaption.Y = 50; // Add the label to the CogDisplay cogRecordDisplay1.InteractiveGraphics.Add(cglCaption, cglCaption.Text, false); cglCaption.Dispose(); myFont.Dispose(); } #endregion } } <file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace VisionPro_Tut.Source.Interface { class ChatClient : TcpClient { private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage; public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage { add { _ReceiveMessage += value; } remove { _ReceiveMessage -= value; } } void OnNameChanged(string mess) { if (_ReceiveMessage != null) { _ReceiveMessage(this, new ReceivedMessageEventArgs(mess)); } } private string _DataMessage; public string DataMessage { get => _DataMessage; set { _DataMessage = value; OnNameChanged(value); } } public ChatClient(string address, int port) : base(address, port) { } public void DisconnectAndStop() { _stop = true; DisconnectAsync(); while (IsConnected) Thread.Yield(); } protected override void OnConnected() { Console.WriteLine($"Chat TCP client connected a new session with Id {Id}"); } protected override void OnDisconnected() { Console.WriteLine($"Chat TCP client disconnected a session with Id {Id}"); // Wait for a while... Thread.Sleep(1000); // Try to connect again if (!_stop) ConnectAsync(); } protected override void OnReceived(byte[] buffer, long offset, long size) { DataMessage = (Encoding.UTF8.GetString(buffer, (int)offset, (int)size)); Console.WriteLine(DataMessage); } protected override void OnError(SocketError error) { Console.WriteLine($"Chat TCP client caught an error with code {error}"); } private bool _stop = true; } public class TcpChatClient { //data receive from server private string _data_receive = null; public string data_receive { get => _data_receive; set { _data_receive = value; OnNameChanged(value); } } //event private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage; public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage { add { _ReceiveMessage += value; } remove { _ReceiveMessage -= value; } } void OnNameChanged(string mess) { if (_ReceiveMessage != null) { _ReceiveMessage(this, new ReceivedMessageEventArgs(mess)); } } //tcp chat client ChatClient client; public TcpChatClient(TCPParam param) { // Create a new TCP chat client client = new ChatClient(param.ip, param.port); client.ReceiveMessage += Client_ReceiveMessage; } private void Client_ReceiveMessage(object sender, ReceivedMessageEventArgs e) { Console.WriteLine("xxxx: " + e.Message); data_receive = e.Message; } ~TcpChatClient() { } public bool Connect() { // Connect the client Console.Write("Client connecting..."); bool isConnect = client.ConnectAsync(); Console.WriteLine("Done!"); return isConnect; } public bool DisConnect() { // Disconnect the client Console.Write("Client disconnecting..."); bool isDisConnect = client.DisconnectAsync(); Console.WriteLine("Done!"); return isDisConnect; } public bool SendMessage(string mess) { // Send the entered text to the chat server bool isSend = client.SendAsync(mess); return isSend; } } }
7c3a2545017ca391a291c0a39146e79fef0d852a
[ "C#" ]
11
C#
resilencelyn/VisionPro_Tut
583fa28faffd9b63d70020f193ac7ee1b74b2e53
b9f42a4f06f7fe6be869b51bf71b0f1ed4f9ba9d
refs/heads/main
<repo_name>KeonaK/WeatherDashApp<file_sep>/README.md # WeatherDashApp This project is a weather dashboard. Type in any city and it will display the current weather as well as a 5 day forcast. (Github Repository Link: )[https://github.com/KeonaK/WeatherDashApp] (Github Deployment Link: )[https://keonak.github.io/WeatherDashApp/] ![Screen Shot](./Assets/image/Dashboard.png) <file_sep>/Assets/script.js let currentCity; const apiKey = "<KEY>"; let cities = [] let time = moment(); let search_button = document.getElementById("button-addon2"); let searchList = document.getElementById("searchList"); let cityEl = document.getElementById("nameOfCity"); let temperatureEl = document.getElementById("temperature"); let humidityEl = document.getElementById("humidity"); let windSpeedEl = document.getElementById("windSpeed"); let uvIndexEl = document.getElementById("uvIndex"); let rain= document.getElementById("iconRain"); let sun=document.getElementById("icon"); let sun2=document.getElementById("icon2"); let sun3=document.getElementById("icon3"); let sun5=document.getElementById("icon5"); let forecast1 = document.getElementById("forecast1"); let forecast2 = document.getElementById("forecast2"); let forecast3 = document.getElementById("forecast3"); let forecast4 = document.getElementById("forecast4"); let forecast5 = document.getElementById("forecast5"); let day1 = document.getElementById("day1Temp"); let day2 = document.getElementById("day2Temp"); let day3 = document.getElementById("day3Temp"); let day4 = document.getElementById("day4Temp"); let day5 = document.getElementById("day5Temp"); let humidDay1 = document.getElementById("humidDay1"); let humidDay2 = document.getElementById("humidDay2"); let humidDay3 = document.getElementById("humidDay3"); let humidDay4 = document.getElementById("humidDay4"); let humidDay5 = document.getElementById("humidDay5"); if(localStorage.getItem("cities") !== null){ cities = JSON.parse(localStorage.getItem("cities")) } //search button function search_button.addEventListener("click", function(event){ event.preventDefault(); currentCity = document.getElementById("search_input").value; cities.push(currentCity); localStorage.setItem("cities", JSON.stringify(cities)); for (let i = 0; i < cities.length; i++) { let searchItem = document.createElement('li') searchItem.classList.add("list-group-item"); searchItem.textContent = cities[i]; searchList.appendChild(searchItem); cities = []; } fetch("https://api.openweathermap.org/data/2.5/forecast?q=" +currentCity+"&appid="+apiKey +"&units=imperial") .then(response => response.json()) .then(function(data){ console.log(data); //display weather data cityEl.innerHTML = data.city.name + "(" + time.format("M/DD/YYYY ") + ") " + `<span class="iconify" data-inline="false" data-icon="emojione:sun-behind-small-cloud" style="font-size: 60px;"></span>`; temperatureEl.textContent = "Temperature: " + data.list[0].main.temp + " โ„‰"; humidityEl.textContent = "Humidity: " + data.list[0].main.humidity + " %"; windSpeedEl.textContent = "Wind Speed: " + data.list[0].wind.speed + " MPH "; //displays weather icons rain.innerHTML = `<span class="iconify" data-inline="false" data-icon="emojione:sun-behind-rain-cloud" style="font-size: 60px;"></span>`; sun.innerHTML = `<span class="iconify" data-inline="false" data-icon="emojione:sun" style="font-size: 60px;"></span>`; sun2.innerHTML = `<span class="iconify" data-inline="false" data-icon="emojione:sun" style="font-size: 60px;"></span>`; sun3.innerHTML = `<span class="iconify" data-inline="false" data-icon="emojione:sun" style="font-size: 60px;"></span>`; sun5.innerHTML = `<span class="iconify" data-inline="false" data-icon="emojione:sun" style="font-size: 60px;"></span>`; //displays weather day1.textContent = "Temp: "+data.list[3].main.temp + " โ„‰"; day2.textContent = "Temp: "+data.list[11].main.temp + " โ„‰"; day3.textContent = "Temp: "+data.list[19].main.temp + " โ„‰"; day4.textContent = "Temp: "+data.list[27].main.temp + " โ„‰"; day5.textContent = "Temp: "+data.list[35].main.temp + " โ„‰"; humidDay1.textContent = "Humidity: "+data.list[3].main.humidity + " %"; humidDay2.textContent = "Humidity: "+data.list[11].main.humidity+ " %"; humidDay3.textContent = "Humidity: "+data.list[19].main.humidity + " %"; humidDay4.textContent = "Humidity: "+data.list[27].main.humidity + " %"; humidDay5.textContent = "Humidity: "+data.list[35].main.humidity + " %"; //displays weather date forecast1.textContent = moment().add(1, 'days').calendar(); forecast2.textContent = moment().add(2, 'days').calendar(); forecast3.textContent = moment().add(3, 'days').calendar(); forecast4.textContent = moment().add(4, 'days').calendar(); forecast5.textContent = moment().add(5, 'days').calendar(); }) });
631bcf0d7f6a84c90b520842a264534719589e13
[ "Markdown", "JavaScript" ]
2
Markdown
KeonaK/WeatherDashApp
02532629a3f0e06963fd93997571e43db1b1c21f
4ebafbfa3c083009d52b6767d2a2a0be6faf17ed
refs/heads/master
<file_sep>from peewee import * import json class ObjectField(Field): """ ะŸะพะปะต-ะพะฑัŠะตะบั‚ ะดะปั ะฑะฐะทั‹ ะดะฐะฝะฝั‹ั… (ั‡ะตั€ะตะท JSON) """ field_type = 'object' def db_value(self, value): return json.dumps(value) def python_value(self, value): return json.loads(value) db = MySQLDatabase('volunteer', user='miron', password='<PASSWORD>', host='localhost', charset='utf8mb4', field_types={"object":"text"}) class BaseModel(Model): class Meta: database = db class Photo(BaseModel): id = PrimaryKeyField() path = CharField() private = BooleanField() # ะœะพะถะฝะพ ะปะธ ะฟะพะปัƒั‡ะธั‚ัŒ ะฟะพ ััั‹ะปะบะต ะฒัะตะผ ะธะปะธ ั‚ะพะปัŒะบะพ ััƒะฟะตั€-ะฐะดะผะธะฝะฐะผ class Museum(BaseModel): id = PrimaryKeyField() name = CharField() description = TextField() login = CharField() password = CharField() photo = ForeignKeyField(Photo, null=True, backref="museum_photos", default=None) class User(BaseModel): """ ะ’ะพะปะพะฝั‚ะตั€ั‹ """ user_id = IntegerField(primary_key=True) name = CharField() # ะ˜ะผั s_name = CharField() # ะคะฐะผะธะปะธั f_name = CharField() # ะžั‚ั‡ะตัั‚ะฒะพ b_date = DateField() # ะ”ะฐั‚ะฐ ั€ะพะถะดะตะฝะธั r_date = DateField() # ะ”ะฐั‚ะฐ ั€ะตะณะธัั‚ั€ะฐั†ะธะธ museum = ForeignKeyField(Museum, null=True, backref='volunteers', default=None) # ะœัƒะทะตะน, ะบ ะบะพั‚ะพั€ะพะผัƒ ะฟั€ะธะบั€ะตะฟะปะตะฝ ะ’ะพะปะพะฝั‚ะตั€ verified = BooleanField(default=False) # ะŸะพะดั‚ะฒะตั€ะถะดะตะฝ ะปะธ ะตะณะพ ะฐะบะบะฐัƒะฝั‚. ะ’ ัั‚ะพะผ ัะปัƒั‡ะฐะต ัƒ ะฝะตะณะพ ะฑัƒะดะตั‚ ะณะฐะปะพั‡ะบะฐ ัƒ ะฟั€ะพั„ะธะปั. ะŸะพัะปะต # ะธะทะผะตะฝะตะฝะธั ะปะธั‡ะฝะพะน ะธะฝั„ั‹ ะณะฐะปะพั‡ะบะฐ ัะฟะฐะดะฐะตั‚ photo = ForeignKeyField(Photo, null=True, backref="user_photos", default=None) mail = CharField(unique=True, max_length=191) phone = CharField(unique=True, max_length=191) cloth_size = CharField(default="", max_length=8) # ะ ะฐะทะผะตั€ ะพะดะตะถะดั‹, ะฟั€ะธะผะตั€ั‹: ...XXS, XS, S, M , L, XL, XXL, XXXL... subscribe = BooleanField(default=False) # ะŸะพะดะฟะธัะบะฐ ะฝะฐ mail-ั€ะฐััั‹ะปะบัƒ additional_study = TextField(default="") # ะžะฑั€ะฐะทะพะฒะฐะฝะธะต additional_child_skill = TextField(default="") # ะ ะฐะฑะพั‚ะฐ ั ะดะตั‚ัŒะผะธ additional_talent = TextField(default="") # ะžัะพะฑั‹ะต ั‚ะฐะปะฐะฝั‚ั‹ additional_allergy = TextField(default="") # ะะปะปะตั€ะณะธะธ # ... ... ... class Verification(BaseModel): # Temp.unused """ ะ—ะฐะฟั€ะพัั‹ ะฝะฐ ะฒะตั€ะธั„ะธะบะฐั†ะธัŽ """ id = PrimaryKeyField() user = ForeignKeyField(User, backref='verifications', unique=True) document = ForeignKeyField(Photo, backref="documents") # ะกัั‹ะปะบะฐ ะฒ ั„ะฐะนะปะพะฒะพะน ัะธัั‚ะตะผะต ะฝะฐ ะทะฐะณั€ัƒะถะตะฝะฝั‹ะน ะฟะฐัะฟะพั€ั‚ class Manager(BaseModel): """ ะ ะฐััˆะธั€ะตะฝะฝะฐั ัะธัั‚ะตะผะฐ ะผะตะฝะตะดะถะผะตะฝั‚ะฐ: |- ะะดะผะธะฝ-ะผัƒะทะตะน |- ะœะตะฝะตะดะถะตั€ั‹ """ user_id = IntegerField(primary_key=True) # VK-User ID name = CharField() s_name = CharField() password = CharField() photo = ForeignKeyField(Photo, backref="manager_photos") manager_vk = CharField(default='') # ะกัั‹ะปะบะฐ ะฝะฐ ะฟั€ะพั„ะธะปัŒ ะ’ะšะพะฝั‚ะฐะบั‚ะต manager_phone = CharField(default='') # ะœะพะฑะธะปัŒะฝั‹ะน ะดะปั ัะฒัะทะธ museum = ForeignKeyField(Museum, backref='managers') # ะœัƒะทะตะน, ะบ ะบะพั‚ะพั€ะพะผัƒ ะฟั€ะธะบั€ะตะฟะปะตะฝ ะœะตะฝะตะดะถะตั€ class Event(BaseModel): """ ะœะตั€ะพะฟั€ะธัั‚ะธะต """ id = PrimaryKeyField() name = CharField() description = TextField() manager = ObjectField() # ForeignKeyField(Manager, backref='events') start_datetime = DateTimeField() # ะะฐั‡ะฐะปะพ finish_datetime = DateTimeField() # ะžะบะพะฝั‡ะฐะฝะธะต photo = ForeignKeyField(Photo, null=True, backref="event_photos", default=None) state = IntegerField() # ะกะพัั‚ะพัะฝะธะต ะผะตั€ะพะฟั€ะธัั‚ะธั: INIT -> ONGOING -> FINISHED price = IntegerField() # ะฆะตะฝะฐ ั‚ะตะบัƒั‰ะตะณะพ ะผะตั€ะพะฟั€ะธัั‚ะธั # ะ”ะพะฟ. ั„ะธะปัŒั‚ั€ั‹ ะฒ ัะปะตะดัƒัŽั‰ะธั… ะพะฑะฝะพะฒะปะตะฝะธัั… class RoleForEvent(BaseModel): """ ะ ะพะปัŒ ะฒ ะผะตั€ะพะฟั€ะธัั‚ะธะธ """ id = PrimaryKeyField() name = CharField() # ะ—ะฐะณะพะปะพะฒะพะบ ั€ะพะปะธ event = ForeignKeyField(Event, backref='roles') manager = ObjectField() # ForeignKeyField(Manager, backref='roles') max_slots = IntegerField() # ะงะธัะปะพ ัะปะพั‚ะพะฒ ะดะปั ัั‚ะพะน ั€ะพะปะธ message_when_participated = TextField() # ะกะพะพะฑั‰ะตะฝะธะต ะปะธะฑะพ ั ััั‹ะปะบะพะน ะฝะฐ ะฑะตัะตะดัƒ, ะปะธะฑะพ ั ะดะพะฟ. ะธะฝั„ะพั€ะผะฐั†ะธะตะน ะฟะพ ะฟะพะฒะพะดัƒ ั‚ะพะณะพ, ะบะฐะบ ะฑัƒะดะตั‚ ะฟั€ะพั…ะพะดะธั‚ัŒ ะฒะพะปะพะฝั‚ะตั€ัั‚ะฒะพ ะฟะพ ัั‚ะพะน ั€ะพะปะธ vk_chat_link = CharField() # ะกัั‹ะปะบะฐ ะฝะฐ ะฑะตัะตะดัƒ ะ’ะš, ัƒะบะฐะทั‹ะฒะฐะตั‚ัั ะฟั€ะธ ัะพะทะดะฐะฝะธะธ/ั€ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธะธ class Participation(BaseModel): # ะŸั€ะธ ัะพะทะดะฐะฝะธะธ ัƒั‡ะฐัั‚ะธั ะฟั€ะพะฒะตั€ัั‚ัŒ ะฝะฐ ะฝะฐะปะธั‡ะธะต ัƒั‡ะฐัั‚ะธั ะฒ ั‚ะพะผ ะถะต ะผะตั€ะพะฟั€ะธัั‚ะธะธ. ะงะตั€ะตะท volunteer.roles => set(role.event...) """ ะฃั‡ะฐัั‚ะธะต ะฒ ั€ะพะปะธ """ participation_key = CharField(primary_key=True, max_length=191) # ะšะปัŽั‡ ัƒั‡ะฐัั‚ะธั role = ForeignKeyField(RoleForEvent, backref='participations') participant = ForeignKeyField(User, backref='participations') result = IntegerField(default=-1) # ะกะพัั‚ะพัะฝะธั: BAD, NEUTRAL, GOOD. ะœะฝะพะถะธั‚ะตะปัŒ ะดะปั ะผะตั€ะพัะฟั€ะธัั‚ะธั: -1, 1, 2 checked = IntegerField(default=0) # ะกะพัั‚ะพัะฝะธะต ะฒั‹ะฟะพะปะฝะตะฝะฝะพะน ั€ะฐะฑะพั‚ั‹ (0 - ะฝะต ะฟั€ะธัˆะตะป/ะฝะต ะฒั‹ะฟะพะปะฝะธะป; 1 - ั‚ะพะปัŒะบะพ ะฒะพัˆะตะป, ะฝะต ะฒั‹ัˆะตะป ั ะผะตั€ะพะฟั€ะธัั‚ะธั; 2 - ัƒัะฟะตัˆะฝะพ ะฒั‹ัˆะตะป/ะฒั‹ะฟะพะปะฝะธะป ะทะฐะดะฐะฝะธะต) comment_to_volunteer = TextField(default='') comment_from_volunteer = TextField(default='') db.connect() db.create_tables([Museum, User, Verification, Manager, Event, RoleForEvent, Participation, Photo]) db.close() <file_sep># -*- coding: utf-8 -*- import datetime from random import randint, choice from flask import * from flask_session import Session from flask_restful import Api, Resource, reqparse, abort from db_model import * import inspect import sign_valid # ะŸะพะดั‚ะฒะตั€ะถะดะตะฝะธะต ะฒะฐะปะธะดะฝะพัั‚ะธ ะฃะ ะ›ั ะดะปั ะฟะฐั€ัะฐ import constants import os import uuid app = Flask(__name__) app.secret_key = b"<KEY>" app.config['SESSION_TYPE'] = 'filesystem' api = Api(app) Session(app) @app.before_request def _db_connect(): db.connect() @app.teardown_request def _db_close(exc): if not db.is_closed(): db.close() # -------------------------------------- def participant_list_by_museum(museum_id): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะฒัะตั… ัƒั‡ะฐัั‚ะฝะธะบะพะฒ, ะฟั€ะธัะพะดะธะฝะตะฝะฝั‹ั… ะบ ะผะตั€ะพะฟั€ะธัั‚ะธัะผ ะผัƒะทะตั :param museum_id: ะ˜ะ” ะผัƒะทะตั """ ptcpnts = [] museum = get_raw_museum(museum_id) for event in museum.events: if event.state == constants.event_state.value_to_db("ONGOING"): for role in event.roles: for participation in role.participations: ptcpnts.append(parse_user(participation.participant)) return ptcpnts def get_raw_museum(museum_id): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ะผัƒะทะตะต (ะฟะพ ะ˜ะ”) :param museum_id: ะ˜ะ” ะผัƒะทะตั :return: False ะธะปะธ ะพะฑัŠะตะบั‚ ั ะผัƒะทะตะตะผ """ try: museum = Museum.get(Museum.id == museum_id) return museum except Museum.DoesNotExist: return False def parse_role(role: RoleForEvent): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ั€ะพะปะธ (ะฟะพ ะพะฑัŠะตะบั‚ัƒ ะ‘ะ”) :param role: ะพะฑัŠะตะบั‚ ะ‘ะ” """ return { "name": role.name, "manager": role.manager, "max_slots": role.max_slots, "free_slots": (role.max_slots - len(role.participations)), "vk_chat_link": role.vk_chat_link } def get_role(role_id): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ั€ะพะปะธ (ะฟะพ ะ˜ะ”) :param role_id: ะ˜ะ” ั€ะพะปะธ :return: False ะธะปะธ ะพะฑัŠะตะบั‚ ั ั€ะพะปัŒัŽ """ try: role = RoleForEvent.get(RoleForEvent.id == role_id) return parse_role(role) except RoleForEvent.DoesNotExist: return False def get_roles(event_id): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะฒัะต ั€ะพะปะธ ั‚ะตะบัƒั‰ะตะณะพ ะผะตั€ะพะฟั€ะธัั‚ะธั :param event_id: ะ˜ะ” ะผะตั€ะพะฟั€ะธัั‚ะธั """ event = get_raw_event(event_id) all_roles = [] for role in event.roles: all_roles.append(parse_role(role)) return all_roles def get_raw_role(role_id)->RoleForEvent: """ ะŸะพะปัƒั‡ะธั‚ัŒ ะพะฑัŠะตะบั‚ ะ‘ะ” ั€ะพะปะธ (ะฟะพ ะ˜ะ”) :param role_id: ะ˜ะ” ั€ะพะปะธ :return: role_id ะธะปะธ ะพะฑัŠะตะบั‚ ะ‘ะ” """ try: role = RoleForEvent.get(User.user_id == role_id) return role except User.DoesNotExist: return role_id def create_participation(user_id, role_id): """ ะกะพะทะดะฐั‚ัŒ ะฝะพะฒะพะต ัƒั‡ะฐัั‚ะธะต ะดะปั ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั :param user_id: ID ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั :param role_id: ID ั€ะพะปะธ :return: ั€ะฐัะฟะฐั€ัะตะฝะฝั‹ะน ะพะฑัŠะตะบั‚ ัƒั‡ะฐัั‚ะธั ะธะปะธ ะพะฑัŠะตะบั‚ ั SUCCESS:FALSE ะธ MESSAGE """ user = get_raw_user(user_id) role = get_raw_role(role_id) if role.max_slots - len(role.participations) <= 0: return {"success": False, "message": "slots out of range"} else: participation_data = { Participation.participation_key.name: str(uuid.uuid4()), # ะฃะฝะธะบะฐะปัŒะฝั‹ะน ะธะดะตะฝั‚ะธั„ะธะบะฐั‚ะพั€ ัƒั‡ะฐัั‚ะธั Participation.role.name: role, Participation.participant.name: user, } new_participation = Participation.create(**participation_data) return parse_participation(new_participation) def parse_event(event:Event): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ะผะตั€ะพะฟั€ะธัั‚ะธะธ (ะธะท ะพะฑัŠะตะบั‚ะฐ ะ‘ะ”) :param event: ะพะฑัŠะตะบั‚ ะธะท ะ‘ะ” """ return { "name":event.name, "description":event.description, "manager": event.manager, "start_datetime": event.start_datetime.strftime("%H:%M:%S %d/%m/%Y"), "finish_datetime": event.finish_datetime.strftime("%H:%M:%S %d/%m/%Y"), "photo": event.photo.id, "state":constants.event_state.db_to_value(event.state), "price":event.price } def get_event(event_id): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ะผะตั€ะพะฟั€ะธัั‚ะธะธ (ะฟะพ ะ˜ะ”) :param event_id: ะ˜ะ” ะผะตั€ะพะฟั€ะธัั‚ะธั """ try: event = Event.get(Event.id == event_id) return parse_event(event) except Event.DoesNotExist: return False def get_raw_event(event_id): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะพะฑัŠะตะบั‚ ะ‘ะ” ะผะตั€ะพะฟั€ะธัั‚ะธั (ะฟะพ ะ˜ะ”) :param event_id: ะ˜ะ” ะผะตั€ะพะฟั€ะธัั‚ะธั :return: ะพะฑัŠะตะบั‚ ะ‘ะ” ะธะปะธ ID ะผะตั€ะพะฟั€ะธัั‚ะธั (ะตัะปะธ ั‚ะฐะบะพะณะพ ะฝะตั‚ ะฒ ะ‘ะ”) """ try: event = Event.get(Event.id == event_id) return event except Event.DoesNotExist: return event_id def get_events(): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะฒัะต ะผะตั€ะพะฟั€ะธั‚ะธั """ all_events = [] for event in Event.select(): all_events.append(parse_user(event)) return all_events def parse_museum(museum): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ะผัƒะทะตะต (ะธะท ะพะฑัŠะตะบั‚ะฐ ะ‘ะ”) :param museum: ะพะฑัŠะตะบั‚ ะธะท ะ‘ะ” """ return { "id": museum.id, "name": museum.name, "description": museum.description, "photo": museum.photo.id } def get_museum(museum_id): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ะผัƒะทะตะต (ะฟะพ ะ˜ะ”) :param museum_id: ะ˜ะ” ะผัƒะทะตั :return: False ะธะปะธ ะฟั€ะพั„ะธะปัŒ ะผัƒะทะตั """ try: museum = Museum.get(Museum.id == museum_id) return parse_museum(museum) except Museum.DoesNotExist: return False def parse_participation(participation:Participation): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ัƒั‡ะฐัั‚ะธะธ (ะฟะพ ะพะฑัŠะตะบั‚ัƒ ะ‘ะ”) :param participation: ะพะฑัŠะตะบั‚ ะ‘ะ” """ return { "participation_key":participation.participant, "role": parse_role(participation.role), "result": constants.participation_result.db_to_value(participation.result), "checked": constants.participation_checked.db_to_value(participation.checked), "comment_to_volunteer": participation.comment_to_volunteer, "comment_from_volunteer": participation.comment_from_volunteer } def get_raw_participation(participation_key): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพะฑ ัƒั‡ะฐัั‚ะธะธ (ะฟะพ ะบะปัŽั‡ัƒ) :param participation_key: ะบะปัŽั‡ ัƒั‡ะฐัั‚ะธั :return: False ะธะปะธ ัƒั‡ะฐัั‚ะธะต """ try: participation = Participation.get(Participation.participation_key == participation_key) return participation except Participation.DoesNotExist: return False def get_participations(user): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะฒัะต "ัƒั‡ะฐัั‚ะธั" ั‡ะตะปะพะฒะตะบะฐ ะธ ะฒััŽ ะธะฝั„ัƒ ะพ ะฝะธั… :param user: ะ‘ะ” ะพะฑัŠะตะบั‚ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั """ data = [] for participation in user.participations: if participation.role.event.state != constants.event_state.value_to_db("FINISHED"): data = parse_participation(participation) return data def get_experience(user): """ ะŸะพัั‡ะธั‚ะฐะดั‚ัŒ ั‚ะตะบัƒั‰ะธะน ะพะฟั‹ั‚ :param user: ัŽะทะตั€, ัƒ ะบะพั‚ะพั€ะพะณะพ ะฒะตะดะตะผ ะฟะพะดัั‡ะตั‚ """ sum = 0 participants = [] for participation in user.participations: if participation.role.event.state == constants.event_state.value_to_db("FINISHED"): sum += participation.role.price * participation.result participants.append(parse_participation(participation)) return sum def parse_user(user): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปะต (ะธะท ะพะฑัŠะตะบั‚ะฐ ะ‘ะ”) :param user: ะพะฑัŠะตะบั‚ ะธะท ะ‘ะ” """ return { "user_id": user.user_id, "name": user.name, "b_date": user.b_date.strftime("%d/%m/%Y"), "r_date": user.r_date.strftime("%d/%m/%Y"), "experience": get_experience(user), "museum": get_museum(user.museum.id) if user.museum is not None else None, "verified": user.verified, "photo": user.photo.id if user.photo is not None else None, "mail": user.mail, "phone": user.phone, "cloth_size": user.cloth_size, "subscribe": user.subscribe, "additional_study": user.additional_study, "additional_child_skill": user.additional_child_skill, "additional_talent": user.additional_talent, "additional_allergy": user.additional_allergy } def get_user(user_id): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปะต (ะฟะพ ะ˜ะ”) :param user_id: ะ˜ะ” ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั :return: False ะธะปะธ ะฟั€ะพั„ะธะปัŒ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั """ try: user = User.get(User.user_id == user_id) return parse_user(user) except User.DoesNotExist: return False def get_raw_user(user_id)->any: """ ะŸะพะปัƒั‡ะธั‚ัŒ ะพะฑัŠะตะบั‚ ะ‘ะ” ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั (ะฟะพ ะ˜ะ”) :param user_id: ะ˜ะ” ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั :return: False ะธะปะธ ะพะฑัŠะตะบั‚ ะ‘ะ” """ try: user = User.get(User.user_id == user_id) return user except User.DoesNotExist: return False def get_photo(photo_id): """ ะŸะพะปัƒั‡ะธั‚ัŒ ะฑะธะฝะฐั€ะฝั‹ะต ะดะฐะฝะฝั‹ะต ั„ะพั‚ะพะณั€ะฐั„ะธะธ ะฟะพ ID :param photo_id: ID ั„ะพั‚ะพะณั€ะฐั„ะธะธ """ try: photo = Photo.get(Photo.id == photo_id) with open(photo.path, mode="rb") as f: content = f.read() return content except Photo.DoesNotExist: return None def create_file(private=False): """ ะกะพะทะดะฐะฝะธะต ะฟัƒัั‚ะพะณะพ ั„ะฐะนะปะฐ ะธ ะฝะพะดะฐ ะฒ ะฑะฐะทะต ะดะฐะฝะฝั‹ั… :param private: ะฟั€ะธะฒะฐั‚ะฝั‹ะน ั„ะฐะนะป - ะฝะตะดะพัั‚ัƒะฟะตะฝ ะดะปั ะฟั€ะพัะผะพั‚ั€ะฐ ั‡ะตั€ะตะท ั„ัƒะฝะบั†ะธัŽ (ะดะปั ะฒะตั€ะธั„ะธะบะฐั†ะธะธ) """ today = datetime.datetime.today() year = str(today.year) month = str(today.month) day = str(today.day) hour = str(today.hour) path = os.path.join("", year, month, day, hour) if not os.path.exists(path): os.makedirs(path) file = path + "/" + str(uuid.uuid4()) # ะกะพะทะดะฐะตะผ ะฝะพะฒั‹ะน ั„ะฐะนะป new_file = Photo.create(**{ Photo.path.name: file, Photo.private.name: private }) return file, new_file.id # -------------------------------------- class Route: """ ะŸะพะดะบะปะฐัั ะดะปั ัะพะทะดะฐะฝะธั ั€ะพัƒั‚ะพะฒ - ะฟัƒั‚ะตะน ะฒ ะฎะ ะ›ะฌ """ __subtrace__ = "" def create_resource(cls, url: str): res = cls.__class__() app.route(url, methods=["GET"])(res.get) app.route(url, methods=["POST"])(res.post) class UserAuthParam(object): parse_args = [] # ะฐั€ะณัƒะผะตะฝั‚ั‹ ะดะปั ะฟะฐั€ัะธะฝะณะฐ def __init__(self, *parse_args): self.parse_args = [{"name": "Referer", "type": str, "required": True, "help": "missed url", "location": "headers"}] self.parse_args += parse_args def __call__(self, target): def wrapped(*args, **kwargs): register_parser = reqparse.RequestParser() for arg in self.parse_args: register_parser.add_argument(**arg) new_args = register_parser.parse_args() sign = sign_valid.valid_user_id(new_args['Referer']) if not sign["valid"]: abort(constants.HTTP_ERROR_AUTH_STATUS, messages=[constants.HTTP_ERROR_AUTH_MESSAGE]) args += sign["user_id"], kwargs = {**kwargs, **new_args} result = target(*args, **kwargs) return result return wrapped class AdminAuthParam(object): parse_args = [] # ะฐั€ะณัƒะผะตะฝั‚ั‹ ะดะปั ะฟะฐั€ัะธะฝะณะฐ def __init__(self, *parse_args): self.parse_args = [{"name": "X-admin-login", "type": str, "required": True, "help": "missed login", "location": "headers"}, {"name": "X-admin-password", "type": str, "required": True, "help": "missed password", "location": "headers"}] self.parse_args += parse_args def __call__(self, target): def wrapped(*args, **kwargs): register_parser = reqparse.RequestParser() for arg in self.parse_args: register_parser.add_argument(**arg) new_args = register_parser.parse_args() museum = None try: museum = Museum.get((Museum.login == new_args['X-admin-login']) & (Museum.login == new_args['X-admin-password'])) except Museum.DoesNotExist: pass if museum is not None: abort(constants.HTTP_ERROR_AUTH_STATUS, messages=[constants.HTTP_ERROR_AUTH_MESSAGE]) args += museum.id, kwargs = {**kwargs, **new_args} result = target(*args, **kwargs) return result return wrapped def process_methods(cls, suburl): for inner in cls.__dict__.values(): if type(inner) is set: print(suburl, inner) def route(url, start_point=False): def process_resources(cls): trace = cls.__subtrace__ for inner in cls.__dict__.values(): if inspect.isclass(inner): if issubclass(inner, Resource): process_methods(inner, url + trace + inner.__subtrace__) api.add_resource(inner, url + trace + inner.__subtrace__) if issubclass(inner, Route): inner.__subtrace__ = trace + inner.__subtrace__ process_resources(inner) def decorator(cls): if start_point: if issubclass(cls, Resource): api.add_resource(cls, url) if issubclass(cls, Route): process_resources(cls) else: cls.__subtrace__ = url return cls return decorator # -------------------------------------- class Photo: @route("/<int:photo_id>") class GetCertainImage(Resource): @api.representation('image/jpeg') def get(self, photo_id, user): data = None try: photo = Photo.get(Photo.id == photo_id) if not photo.private: data = get_photo(photo_id) except Photo.DoesNotExist: pass resp = make_response(data, 200) resp.headers['Cache-Control'] = 'public, max-age=31536000' return resp def post(self): data = request.data file, file_id = create_file() # ะ—ะฐะฟะธัั‹ะฒะฐะตะผ ะฒัะต ะฒ ั„ะฐะนะป with open(file, mode="bw") as f: f.write(data) return {"fileId": file_id} @route("/private") class UploadPrivateImage(Resource): def post(self): data = request.data file, file_id = create_file(True) # ะ—ะฐะฟะธัั‹ะฒะฐะตะผ ะฒัะต ะฒ ั„ะฐะนะป with open(file, mode="bw") as f: f.write(data) return {"fileId": file_id} # -------------------------------------- @route("/volunteer", True) class Volunteer(Route): @route("/users") class User(Route): @route("/current") class Current(Resource, Route): @UserAuthParam({"name": "name", "type": str, "required": True, "help": "missed name", "location": "json"}, {"name": "s_name", "type": str, "required": True, "help": "missed surname", "location": "json"}, {"name": "f_name", "type": str, "required": True, "help": "missed father name", "location": "json"}, {"name": "b_date", "type": str, "required": True, "help": "missed birthday date", "location": "json"}, {"name": "photo", "type": int, "help": "missed photo id", "location": "json"}, {"name": "mail", "type": str, "required": True, "help": "missed mail", "location": "json"}, {"name": "phone", "type": str, "required": True, "help": "missed phone", "location": "json"}, {"name": "cloth_size", "type": str, "help": "missed cloth_size", "location": "json"}, {"name": "subscribe", "type": bool, "required": True, "help": "missed subscribe", "location": "json"}, {"name": "additional_study", "type": str,"help": "missed additional_study", "location": "json"}, {"name": "additional_child_skill", "type": str, "help": "missed additional_child_skill", "location": "json"}, {"name": "additional_talent", "type": str, "help": "missed additional_talent", "location": "json"}, {"name": "additional_allergy", "type": str, "help": "missed additional_allergy", "location": "json"}) def post(self, user_id, **kwargs): # ะžะฑะฝะพะฒะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปะต user = get_raw_user(user_id) if user is False: user_data = { User.user_id.name: user_id, User.name.name: kwargs["name"], User.s_name.name: kwargs["s_name"], User.f_name.name: kwargs["f_name"], User.subscribe.name: kwargs["subscribe"], User.b_date.name: datetime.datetime.strptime(kwargs["b_date"],"%d/%m/%Y").date(), User.r_date.name: datetime.datetime.today().date(), User.mail.name: kwargs["mail"], User.phone.name: kwargs["phone"] } user = User.create(**user_data) else: for key, value in kwargs: user.__setattr__(key, value) user.save() return parse_user(user) @UserAuthParam() def get(self, user_id): # ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะธ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปะต return {"user": get_user(user_id)} @route("/participations") class Participations(Resource): @UserAuthParam() def get(self, user_id): # ะŸะพะปัƒั‡ะธั‚ัŒ ัะฟะธัะพะบ ะฐะบั‚ะธะฒะฝั‹ั…/ะพะถะธะดะฐัŽั‰ะธั… ัƒั‡ะฐัั‚ะธะน ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั user = get_user(user_id) return get_participations(user) @route("/<int:user_id>") class User(Resource): @UserAuthParam() def get(self, user_id, current_user_id): # [DEBUG] ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ัŽะทะตั€ะต ะฟะพ ID return {"user": get_user(user_id)} @route("/login") class Register(Resource): @UserAuthParam() def get(self, user_id, headers=None, **kwargs): # ะŸั€ะพะฒะตั€ะธั‚ัŒ ะฝะฐะปะธั‡ะธะต ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั ะฒ ะ‘ะ” / "ะฐะฒั‚ะพั€ะธะทะพะฒะฐั‚ัŒัั" user = get_raw_user(user_id) return {"success": True, "user": parse_user(user)} if user is not False else {"success": False} @route("/photo") class UserPhotoLoad(Photo): pass @route("/events") class Event(Resource, Route): @UserAuthParam() def get(self): # ะกะฟะธัะพะบ ะฒัะตั… ะผะตั€ะพะฟั€ะธัั‚ะธะน return get_events() @route("/<int:event_id>") class GetCertainEvent(Resource, Route): @UserAuthParam() def get(self, event_id): # ะšะพะฝะบั€ะตั‚ะฝะพะต ะผะตั€ะพะฟั€ะธัั‚ะธะต return get_event(event_id) @route("/roles") class RolesForEvent(Resource, Route): @UserAuthParam() def get(self, event_id): # ะ ะพะปะธ ะดะปั ะบะพะฝะบั€ะตั‚ะฝะพะณะพ ะผะตั€ะพะฟั€ะธัั‚ะธั return get_roles(event_id) @route("/<int:role_id>") class GetCertainRole(Resource, Route): @UserAuthParam() def get(self, role_id): # ะžั‚ะดะตะปัŒะฝะฐั ั€ะพะปัŒ return get_role(role_id) @route("/participate") class Participate(Resource): @UserAuthParam() def get(self, role_id, event_id, user_id): # ะŸั€ะธะฝัั‚ัŒ ัƒั‡ะฐัั‚ะธะต ะฒ ั€ะพะปะธ return create_participation(user_id, role_id) # ะขะพั‡ะบะฐ ะฒั…ะพะดะฐ ะดะปั ั€ะฐะฑะพั‚ั‹ ั ัƒั‡ะฐัั‚ะธัะผะธ. ะžั‚ะผะตั‚ะบะฐ ะฒั…ะพะดะฐ/ะฒั‹ั…ะพะดะฐ, ะฟั€ะพัั‚ะฐะฒะปะตะฝะธะต ะพั†ะตะฝะบะธ, ะพั‚ะฟั€ะฐะฒะบะฐ ะบะพะผะผะตะฝั‚ะฐั€ะธั. ะŸะพะปัŒะทะพะฒะฐั‚ะตะปัŒ + ะผะตะฝะตะดะถะตั€ @route("/participations", True) class Participation(Resource, Route): @route("/hire") class Hire(Resource): @AdminAuthParam({"name": "qr", "type": str, "required": True, "help": "missed qr", "location": "json"}) def post(self, museum_id, **kwargs): # ะ’ะฟัƒัั‚ะธั‚ัŒ ะฒะพะปะพะฝั‚ะตั€ะฐ participation = get_raw_participation(kwargs["qr"]) if participation.role.event.state == constants.event_state.to_db("ONGOING"): if participation.checked == 0: participation.checked = constants.participation_checked.to_db("PARTIALLY") participation.save() return {"success":True} else: return {"success":False, "message":"ะŸะพะปัŒะทะพะฒะฐั‚ะตะปัŒ ัƒะถะต ะฟั€ะพัˆะตะป ะฝะฐ ะผะตั€ะพะฟั€ะธัั‚ะธะต"} else: return {"success":False, "message":"ะœะตั€ะพะฟั€ะธัั‚ะธะต ะฝะต ะฟั€ะพะฒะพะดะธั‚ัั ะฒ ะดะฐะฝะฝั‹ะน ะผะพะผะตะฝั‚"} @route("/free") class Free(Resource): def post(self, museum_id): # ะ’ั‹ะฟัƒัั‚ะธั‚ัŒ ะฒะพะปะพะฝั‚ะตั€ะฐ pass @route("/list") class HandMode(Resource, Route): @AdminAuthParam() def get(self, museum_id): # ะŸะพะปัƒั‡ะธั‚ัŒ ัะฟะธัะพะบ ะฒัะตั… ัƒั‡ะฐัั‚ะฝะธะบะพะฒ ะดะปั ั‚ะตะบัƒั‰ะตะณะพ ะผัƒะทะตั return participant_list_by_museum(museum_id) @route("/<int:user_id>") class GetCertainUser(Route): @route("/free") class FreeSelected(Resource): @AdminAuthParam() def post(self, museum_id): # ะŸั€ะพัั‚ะฐะฒะธั‚ัŒ ัƒั‡ะฐัั‚ะธะต ัƒะดะฐะปะตะฝะฝะพ / ะฑะตะท ะบะพะฝั‚ะฐะบั‚ะฐ ั ัƒั‡ะฐัั‚ะฝะธะบะพะผ pass # ะขะพั‡ะบะฐ ะฒั…ะพะดะฐ ะดะปั ั€ะฐะฑะพั‚ั‹ ั ะผะตะฝะตะดะถะตั€ะฐะผะธ. ะžะฑะฝะพะฒะปะตะฝะธะต ะธะฝั„ะพั€ะผะฐั†ะธะธ: ะธะผั, ั„ะฐะผะธะปะธั, ั„ะพั‚ะพ, ะ’ะš, ั‚ะตะปะตั„ะพะฝ, ะฟะฐั€ะพะปัŒ. ะกะพะทะดะฐะฝะธะต ะผะตะฝะตะดะถะตั€ะพะฒ, ัƒะดะฐะปะตะฝะธะต ะผะตะฝะตะดะถะตั€ะพะฒ # class Manager: # ะขะพั‡ะบะฐ ะฒั…ะพะดะฐ ะดะปั ั€ะฐะฑะพั‚ั‹ ั ะผัƒะทะตัะผะธ. ะะฒั‚ะพั€ะธะทะฐั†ะธั, ัะผะตะฝะฐ ะธะฝั„ะพั€ะผะฐั†ะธะธ: ะฝะฐะทะฒะฐะฝะธะต, ะพะฟะธัะฐะฝะธะต, ัะผะตะฝะฐ ั„ะพั‚ะพะณั€ะฐั„ะธะธ, ัะพะทะดะฐะฝะธะต. ะะดะผะธะฝะธัั‚ั€ะฐั†ะธั + ะผัƒะทะตะธ # class Museum: <file_sep># VKHT_VolunteerBack Backend ัะธัั‚ะตะผั‹ ัƒะฟั€ะพั‰ะตะฝะธั ั€ะฐะฑะพั‚ั‹ ั ะฒะพะปะพะฝั‚ะตั€ะฐะผะธ ะดะปั ะผัƒะทะตะตะฒ, ะฝะฐะฟะธัะฐะฝะฝะพะน ะฒ ั€ะฐะผะบะฐั… VkHackathon2019 # app.py ะคะฐะนะป ะฟั€ะธะปะพะถะตะฝะธั ะดะปั Flask # constants.py ะšะพะฝัั‚ะฐะฝั‚ั‹ (ัะพะพะฑั‰ะตะฝะธะต ะพะฑ ะพัˆะธะฑะบะต, ะทะฝะฐั‡ะตะฝะธั ะดะปั ะ‘ะ”) # db_model.py ะœะพะดะตะปัŒ ะฑะฐะทั‹ ะดะฐะฝะฝั‹ั… # main.py ะžัะฝะพะฒะฝะพะน ั„ะฐะนะป ั ะธะฝะธั†ะธะฐะปะธะทะฐั†ะธะตะน, ั€ะตะฐะปะธะทะฐั†ะธะตะน REST-ะะฟะธ ะธ ั„ัƒะฝะบั†ะธัะผะธ ะดะพัั‚ัƒะฟะฐ ะบ ะพะฑัŠะตะบั‚ะฐะผ ะธะท ะ‘ะ” # sign_valid.py ะ’ะตั€ะธั„ะธะบะฐั†ะธั ะทะฐะฟั€ะพัะพะฒ ั ั„ั€ะพะฝั‚ะฐ <file_sep>HTTP_ERROR_AUTH_STATUS = 403 HTTP_ERROR_AUTH_MESSAGE = "wrong sign" # ------------ class Converter: db_to_value = {} # ะกะปะพะฒะฐั€ัŒ ะฟะตั€ะตะฒะพะดะฐ ะ‘ะฐะทั‹ ะดะฐะฝะฝั‹ั… ะฒ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒัะบะธะน value_to_db = {} def __init__(self, dictionary): self.db_to_value = dictionary self.value_to_db = dict((v, k) for k, v in dictionary.items()) def to_db(self, value): """ ะกะตะผะฐะฝั‚ะธั‡ะตัะบะพะต ะทะฝะฐั‡ะตะฝะธะต ะฒ ะทะฝะฐั‡ะตะฝะธะต ะดะปั ะฑะฐะทั‹ ะดะฐะฝะฝั‹ั… :param value: ัะตะผะตะฝั‚ะธั‡ะตัะบะธ ะฟะพะฝัั‚ะฝะพะต ะทะฝะฐั‡ะตะฝะธะต """ return self.value_to_db.get(value) def to_value(self, db): """ ะ—ะฝะฐั‡ะตะฝะธะต ะธะท ะฑะฐะทั‹ ะดะฐะฝะฝั‹ั… ะฒ ัะตะผะฐะฝั‚ะธั‡ะตัะบะธ ะฟะพะฝัั‚ะฝัƒัŽ ะตะดะธะฝะธั†ัƒ :param db: ะทะฝะฐั‡ะตะฝะธะต ะธะท ะ‘ะ” """ return self.db_to_value(db) def get_values(self): """ ะกะฟะธัะพะบ ะฒะพะทะผะพะถะฝั‹ะต ัะตะผะตะฝั‚ะธั‡ะตัะบะธั… ะทะฝะฐั‡ะตะฝะธะน """ return self.db_to_value.values() def get_dbs(self): """ ะกะฟะธัะพะบ ะฒะพะทะผะพะถะฝั‹ั… ะทะฝะฐั‡ะตะฝะธะน ะฒ ะฑะฐะทะต ะดะฐะฝะฝั‹ั… """ return self.value_to_db.values() event_state = Converter({0: "INIT", 1: "ONGOING", 2: "FINISHED"}) # ะกะพัั‚ะพัะฝะธั ะผะตั€ะพะฟั€ะธัั‚ะธั participation_result = Converter({-1: "BAD", 1: "NEUTRAL", 2: "GOOD"}) # ะ ะตะทัƒะปัŒั‚ะฐั‚ั‹ ัƒั‡ะฐัั‚ะธั / ะผะฝะพะถะธั‚ะตะปะธ ัะบัะฟั‹ participation_checked = Converter({0: "NONE", 1: "PARTIALLY", 2: "DONE"}) # ะžั‚ะผะตั‚ะบะธ ะฒ ะฟั€ะพั†ะตััะต ะผะตั€ะพะฟั€ะธัั‚ะธั <file_sep>from base64 import b64encode from collections import OrderedDict from hashlib import sha256 from hmac import HMAC from urllib.parse import urlparse, parse_qsl, urlencode client_secret = "<KEY>" # "<KEY>" # ะ—ะฐั‰ะธั‰ั‘ะฝะฝั‹ะน ะบะปัŽั‡ def valid_user_id(url) -> dict: """ ะŸั€ะพะฒะตั€ะธั‚ัŒ ะฒะฐะปะธะดะฝะพัั‚ัŒ ะฃะ ะ›ัŒ ะธ ะฒั‹ะดะฐั‚ัŒ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒัะบะธะน ID :param url: ะฃั€ะปัŒ :return: ัะปะพะฒะฐั€ัŒ ั ะบะปัŽั‡ะฐะผะธ valid ะธ user_id """ global client_secret query = dict(parse_qsl(urlparse(url).query, keep_blank_values=True)) secret = client_secret valid, user_id = False, -1 try: vk_subset = OrderedDict(sorted(x for x in query.items() if x[0][:3] == "vk_")) hash_code = b64encode(HMAC(secret.encode(), urlencode(vk_subset, doseq=True).encode(), sha256).digest()) decoded_hash_code = hash_code.decode('utf-8')[:-1].replace('+', '-').replace('/', '_') valid = query["sign"] == decoded_hash_code user_id = query["vk_user_id"] except: pass return {"valid": valid, "user_id": user_id}
3d2035f06712a88ce8e5686990d8bf0b70052407
[ "Markdown", "Python" ]
5
Python
Bot12313/VKHT_VolunteerBack
e0b67735660fc66950eee849a00a03470b27d6e5
b64b1880f2a2d620a0686cded37f27dc1db6f232
refs/heads/master
<file_sep>const _ = require('lodash'); const uuid = require('uuid') const fs = require('fs'); const path = require('path'); const filename = path.join(__dirname, '../data/todos.json'); exports.getAll = function (req,cb) { if(req.query.complete){ if (req.query.complete === 'true'){ fs.readFile(filename, (err,buffer) => { if(err) return cb(err); try { var data = JSON.parse(buffer); data = data.filter(cur => { if(cur.isComplete){ return true; } }) cb(null,data) } catch(e){ var data = []; } }) } else { console.log('false') fs.readFile(filename, (err,buffer) => { if(err) return cb(err); try { var data = JSON.parse(buffer); data = data.filter(cur => { if(cur.isComplete === false){ return true; } }) cb(null,data) } catch(e){ var data = []; } }) } } else{ fs.readFile(filename, (err, buffer) => { if(err) return cb(err); try { var data = JSON.parse(buffer); console.log(data) cb(null, data); } catch (e) { var data = []; } }); } } exports.write = function(requested,newData, cb) { let json = JSON.stringify(newData); fs.writeFile(filename, json, (err) => { if(err)return cb(err); }); return cb(null, requested); } exports.edit = function(req, cb){ let idToEdit = req.params.id; let didIt = {}; fs.readFile(filename, (err, buffer) => { try { var data = JSON.parse(buffer); data = data.map((cur) => { if(cur.id === idToEdit && cur.isComplete){ cur.isComplete = false; didIt = { isComplete:false, name: cur.name, duedate: cur.duedate } return cur; } else if(cur.id === idToEdit && cur.isComplete == false){ cur.isComplete = true; didIt = { isComplete:true, name: cur.name, duedate: cur.duedate } return cur; } else {} return cur; }) exports.write(didIt,data, cb); } catch (e) { var data = []; } }) } exports.create = function(newItem, cb){ console.log(newItem) newItem.isComplete = false; newItem.id = uuid(); let requested = {name: newItem.name, duedate: newItem.duedate} fs.readFile(filename, (err, buffer) => { if(err) return cb(err); try { var data = JSON.parse(buffer); console.log(data) data.push(newItem) console.log(data) exports.write(requested,data, cb) } catch (e) { var data = []; } }) } exports.delete = function(req, cb){ let idToDelete = req.params.id if(idToDelete === "complete"){ fs.readFile(filename, (err, buffer) => { try { var data = JSON.parse(buffer); data = data.filter((cur) => { if(cur.isComplete){ return false; }else { return true; } }) exports.write(data,data, cb); } catch (err) { var data = []; return cb(err); } }) } else { fs.readFile(filename, (err, buffer) => { try { var data = JSON.parse(buffer); data = data.filter((cur) => { if(cur.id !== idToDelete){ return true; } }) exports.write(data,data, cb); } catch (err) { var data = []; return cb(err); } }) } } <file_sep>const PORT = 8000; const express = require('express'); const morgan = require('morgan'); const bodyParser = require('body-parser'); const flashcards = require('./models/todos.js'); const app = express(); // App Middleware app.use(morgan('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.use((req, res, next) => { res.handle = (err, data) => res.status(err ? 400 : 200).send(err || data); next(); }) // ROUTEs app.get('/todos', (req, res) => flashcards.getAll(req,res.handle)); app.post('/todos', (req,res) => flashcards.create(req.body,res.handle)); app.put('/todos/:id', (req,res) => flashcards.edit(req, res.handle)); app.delete('/todos/:id', (req,res) => flashcards.delete(req, res.handle)); app.listen(PORT, (err) => { console.log(err || `Express listening on port ${PORT}`); });
ad14433be1989c80cc2f8bfbb6b6d0888f06f362
[ "JavaScript" ]
2
JavaScript
johnsalay/todo-list-react
cc41c07ac228131ebaea2d28f3151d69d305226e
f1fe7e5f7752ffb2863919538ac56a4c45e3a1fc
refs/heads/master
<file_sep>// //Business Logic for TicketPrice function TicketPrice) { this.prices = [], } // // TicketPrice.prototype.addMoviePrice = function(price) { // this.prices.push(priceValue); // } // var price = 0; //Business Logic for Ticket function Ticket(movie, time, age) { this.movie = movie, this.time = time, this.age = age, this.ticket = 8, this.ticketPrice(); } Ticket.prototype.ticketPrice = function() { if (this.movie === "1"){ this.ticket += 5; } if(this.time === "2"){ this.ticket += 2; } else if (this.time === "3") { this.ticket += 5; } if (this.age === "2") { this.ticket += 2 } else if (this.age === "3") { this.ticket -= 2; } } // function ticketPrice(movie, time, age) { // if (Ticket.movie === 1) { // price += 5; // } // } console.log(price); // function TicketValue(movieValue, timeValue, ageValue) { // this.movieValue = movieValue, // this.timeValue = timeValue, // this.ageValue = ageValue // } //User Interface // var ticket = new Ticket(); function displayTicketPrice(ticketPriceToDisplay) { var ticketInfo = $("#ticketInfo"); var htmlForTicketInfo = ""; ticketPriceToDisplay.contacts.forEach(function(contact) { htmlForContactInfo += "<li id=" + contact.id + ">" + contact.firstName + " " + contact.lastName + "</li>"; }); contactsList.html(htmlForContactInfo); }; $(document).ready(function(){ $("form").submit(function(event){ event.preventDefault(); var movie = $("#movie-select").val(); var time = $("#time-select").val(); var age = $("#age-select").val(); //console.log(movie, time, age); // var total = add(movie, time, age); // alert(total) var ticket = new Ticket(movie, time, age); $("#ticketInfo").html(Ticket[3]); // var ticketPrice = ticket.addPrice; console.log(ticket); }); });
e7154488869c21536e30891e04637c9fc5a55a31
[ "JavaScript" ]
1
JavaScript
linbaker/movie-tickets
790612fced581f1fd1a92f3451b1763527a2e39e
34b2a43ea055e479d4dab0ac7fbe0f8b1f939b08
refs/heads/master
<file_sep><?php defined('BASEPATH') or exit('No direct script access allowed'); class Users extends CI_Model { public function __construct() { parent::__construct(); $this->load->database(); } public function get_all_users() { $query = $this->db->query('SELECT * FROM users ORDER BY username'); return [ 'status' => '200', 'users' => $query->result_array() ]; } public function get_users_by_search_query(string $query = null, bool $strict = false) { if ($query === null) { return $this->get_all_users(); } if ($strict) { $query = $this->db->query('SELECT * FROM users WHERE username = ? ORDER BY username', [$query]); } else { $query = $this->db->query('SELECT * FROM users WHERE username LIKE ? ORDER BY username', ['%' . $query . '%']); } return [ 'status' => '200', 'users' => $query->result_array() ]; } public function validate_user_array(array $user_array = null) { if (strlen($user_array['username']) < 4) { $data['error']['username'] = 'Username harus lebih dari 4 karakter'; } if (strlen($user_array['username']) > 80) { $data['error']['username'] = 'Username tidak boleh lebih dari 80 karakter'; } if (strlen($user_array['nama_lengkap']) === 0) { $data['error']['nama_lengkap'] = 'Nama lengkap kosong'; } if (strlen($user_array['nama_lengkap']) > 120) { $data['error']['nama_lengkap'] = 'Nama lengkap tidak boleh lebih dari 120 karakter'; } if ((preg_match('/[0-9]+/', $user_array['password']) !== 1) || (preg_match('/[A-Za-z]+/', $user_array['password']) !== 1)) { $data['error']['password'] = 'Password harus minimal terdiri dari satu huruf dan satu angka'; } if ($user_array['password'] === "<PASSWORD>,") { $data['error']['password'] = 'K<PASSWORD>'; } if (!filter_var($user_array['email'], FILTER_VALIDATE_EMAIL)) { $data['error']['email'] = 'Email tidak valid'; } if (!isset($data['error'])) { $data = []; array_push($data, $user_array['username']); array_push($data, $user_array['nama_lengkap']); array_push($data, $user_array['password']); array_push($data, $user_array['email']); } return $data; } public function add_user(array $user_array = null) { if ($user_array === null) { return [ 'status' => '400', 'error' => 'Request array is empty' ]; } $user_array = $this->validate_user_array($user_array); if ($user_array['error'] !== null) { return [ 'status' => '400', 'error' => $user_array['error'] ]; } $pre_create = $this->get_users_by_search_query($user_array[0], true); if (count($pre_create['users']) > 0) { return [ 'status' => '409', 'error' => 'Resource user is exists', 'users' => $pre_create['users'] ]; } $this->db->query('INSERT INTO users VALUES (? , ? , ? , ?)', $user_array); $response = $this->get_users_by_search_query($user_array[0], true); $response['status'] = 201; return $response; } public function put_user(array $user_array = null) { if ($user_array === null) { return [ 'status' => '400', 'error' => 'Request array is empty' ]; } $user_array = $this->validate_user_array($user_array); if ($user_array['error'] !== null) { return [ 'status' => '400', 'error' => $user_array['error'] ]; } for ($i = 1; $i < 4; $i++) { $user_array[$i + 3] = $user_array[$i]; } $this->db->query( 'INSERT INTO users VALUES (? , ? , ? , ?) ON DUPLICATE KEY UPDATE nama_lengkap = ?, password = ?, email = ?', $user_array ); $response = $this->get_users_by_search_query($user_array[0], true); $response['status'] = 200; return $response; } public function delete_user(string $username = null) { if ($username === null) { return [ 'status' => '400', 'error' => 'Request array is empty' ]; } $this->db->query('DELETE FROM users WHERE username = ?', [$username]); $aff = $this->db->affected_rows(); return [ 'status' => 200, 'affected_rows' => $aff ]; } } <file_sep># nyabun-opo-ngaso hmmmmmmmmmmmmmm <file_sep><?php defined('BASEPATH') or exit('No direct script access allowed'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Student Entry</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> </head> <body> <div class="container mt-5"> <h1>Student Entry</h1> <div class="modal fade" id="error-modal" tabindex="-1" role="dialog" aria-labelledby="error-modal-label" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="error-modal-label">Error</h5> </div> <div class="modal-body"> <p id="error-msg"> </p> </div> <div class="modal-footer"> <div class="container-fluid"> <button type="button" class="btn btn-secondary mb-2" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> <div class="modal fade" id="alter-modal" tabindex="-1" role="dialog" aria-labelledby="alter-modal-label" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="alter-modal-label">Student Form</h5> </div> <div class="modal-body"> <div class="container-fluid"> <form> <div class="form-group"> <label for="id-input">ID</label> <input type="text" class="form-control" id="id-input" aria-describedby="id-help" placeholder="Enter ID" autocomplete="off"> </div> <div class="form-group"> <label for="name-input">Name</label> <input type="text" class="form-control" id="name-input" aria-describedby="name-help" placeholder="Enter name" autocomplete="off"> </div> <div class="form-group"> <label for="email-input">Email</label> <input type="email" class="form-control" id="email-input" aria-describedby="email-help" placeholder="Enter email" autocomplete="off"> </div> <div class="form-group"> <label for="dob-input">Date of Birth</label> <input type="date" class="form-control" id="dob-input" aria-describedby="dob-help" placeholder="Enter your birth date" autocomplete="off"> </div> <div class="form-group"> <label for="address-input">Address</label> <textarea class="form-control" id="address-input" aria-describedby="address-help" placeholder="Enter your address" autocomplete="off"></textarea> </div> <div class="form-group"> <label for="phone-input">Phone</label> <input type="text" class="form-control" id="phone-input" aria-describedby="phone-help" placeholder="Enter your phone" autocomplete="off"> </div> <div class="father-group"> <label for="father-input">Father Name</label> <input type="text" class="form-control" id="father-input" aria-describedby="father-help" placeholder="Enter your father name " autocomplete="off"> </div> <div class="mother-group"> <label for="mother-input">Mother Name</label> <input type="text" class="form-control" id="mother-input" aria-describedby="mother-help" placeholder="Enter your mother name " autocomplete="off"> </div> </form> </div> </div> <div class="modal-footer"> <div class="container-fluid"> <button type="button" id="cancel-button" class="btn btn-secondary mb-2" data-dismiss="modal">Discard and close</button> <button type="button" id="save-button" class="btn btn-primary mb-2">Save changes</button> <button type="button" id="delete-button" class="btn btn-danger mb-2">Delete record</button> </div> </div> </div> </div> </div> <div class="modal fade" id="create-modal" tabindex="-1" role="dialog" aria-labelledby="create-modal-label" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="create-modal-label">Entry Student Form</h5> </div> <div class="modal-body"> <div class="container-fluid"> <form id="create-form"> <div class="form-group"> <label for="id-input-c">ID</label> <input type="text" class="form-control" id="id-input-c" aria-describedby="id-help" placeholder="Enter ID" autocomplete="off"> </div> <div class="form-group"> <label for="name-input-c">Name</label> <input type="text" class="form-control" id="name-input-c" aria-describedby="name-help" placeholder="Enter name" autocomplete="off"> </div> <div class="form-group"> <label for="email-input-c">Email</label> <input type="email" class="form-control" id="email-input-c" aria-describedby="email-help" placeholder="Enter email" autocomplete="off"> </div> <div class="form-group"> <label for="dob-input-c">Date of Birth</label> <input type="date" class="form-control" id="dob-input-c" aria-describedby="dob-help" placeholder="Enter your birth date" autocomplete="off"> </div> <div class="form-group"> <label for="address-input-c">Address</label> <textarea class="form-control" id="address-input-c" aria-describedby="address-help" placeholder="Enter your address" autocomplete="off"></textarea> </div> <div class="form-group"> <label for="phone-input-c">Phone</label> <input type="text" class="form-control" id="phone-input-c" aria-describedby="phone-help" placeholder="Enter your phone" autocomplete="off"> </div> <div class="father-group"> <label for="father-input-c">Father Name</label> <input type="text" class="form-control" id="father-input-c" aria-describedby="father-help" placeholder="Enter your father name " autocomplete="off"> </div> <div class="mother-group"> <label for="mother-input-c">Mother Name</label> <input type="text" class="form-control" id="mother-input-c" aria-describedby="mother-help" placeholder="Enter your mother name " autocomplete="off"> </div> </form> </div> </div> <div class="modal-footer"> <div class="container-fluid"> <button type="button" id="cancel-button-c" class="btn mb-2 btn-secondary" data-dismiss="modal">Discard and close</button> <button type="button" id="save-button-c" class="btn mb-2 btn-primary">Create Entry</button> </div> </div> </div> </div> </div> <div> <button type="button" id="create-button" class="btn btn-primary mb-4 mt-3">Entry Student</button> <br> <table class="table table-hover table-responsive-md"> <thead> <tr> <th>No</th> <th>Nama</th> <th>Email</th> </tr> </thead> <tbody id="table-body"></tbody> </table> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="<?php echo base_url(); ?>static/js/main.js"></script> </body> </html> <file_sep><?php use Restserver\Libraries\REST_Controller; defined('BASEPATH') or exit('No direct script access allowed'); require APPPATH . 'libraries/REST_Controller.php'; require APPPATH . 'libraries/Format.php'; class Api extends REST_Controller { public function __construct($config = 'rest') { parent::__construct($config); $this->load->model('users'); } public function index_get() { $this->response(['w' => 'w']); } public function users_get() { $query = $this->query('query'); if ($query === null) { $response = $this->users->get_all_users(); } else { $response = $this->users->get_users_by_search_query($query); } $this->response($response); } public function users_post() { $data = $this->post(); $response = $this->users->add_user($data); $this->response($response); } public function users_put(string $username = null) { if ($username === null) { $response = ['status' => 400, 'error' => 'URL needs a username i.e (users/{username})']; } else { $data = $this->put(); $data['username'] = $username; $response = $this->users->put_user($data); } $this->response($response); } public function users_delete(string $username = null) { if ($username === null) { $response = ['status' => 400, 'error' => 'URL needs a username i.e (users/{username})']; } else { $response = $this->users->delete_user($username); } $this->response($response); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package utsppk2018_15_8518; /** * * @author 15.8518 */ public class MainFrame extends javax.swing.JFrame { public javax.swing.JCheckBox getEditCheckBox() { return editCheckBox; } private OutputPane outputPane1; /** * Creates new form MainFrame */ public MainFrame() { initComponents(); outputPane1 = new OutputPane(); jScrollPane1.setViewportView(outputPane1); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); usernameTextField = new javax.swing.JTextField(); namaTextField = new javax.swing.JTextField(); emailTextField = new javax.swing.JTextField(); usernameAlert = new javax.swing.JLabel(); namaAlert = new javax.swing.JLabel(); passwordAlert = new javax.swing.JLabel(); konfirmasiPasswordAlert = new javax.swing.JLabel(); emailAlert = new javax.swing.JLabel(); simpanButton = new javax.swing.JButton(); passwordField = new javax.swing.JPasswordField(); konfirmasiPasswordField = new javax.swing.JPasswordField(); jScrollPane1 = new javax.swing.JScrollPane(); jLabel6 = new javax.swing.JLabel(); editCheckBox = new javax.swing.JCheckBox(); searchTextField = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); findButton = new javax.swing.JButton(); refreshButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMinimumSize(new java.awt.Dimension(600, 500)); jLabel1.setText("Username"); jLabel2.setText("Nama Lengkap"); jLabel3.setText("Password"); jLabel4.setText("Konfirmasi Password"); jLabel5.setText("Email"); usernameTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { usernameTextFieldActionPerformed(evt); } }); emailTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { emailTextFieldActionPerformed(evt); } }); usernameAlert.setForeground(new java.awt.Color(255, 51, 102)); usernameAlert.setText("username minimal 4 huruf"); namaAlert.setForeground(new java.awt.Color(255, 51, 102)); namaAlert.setText("nama harus diisi"); passwordAlert.setForeground(new java.awt.Color(255, 51, 102)); passwordAlert.setText("password <PASSWORD> <PASSWORD>"); konfirmasiPasswordAlert.setForeground(new java.awt.Color(255, 51, 102)); konfirmasiPasswordAlert.setText("konfirmasi password tidak cocok"); emailAlert.setForeground(new java.awt.Color(255, 51, 102)); emailAlert.setText("format email salah"); simpanButton.setText("Simpan"); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel6.setText("USER CLIENT"); editCheckBox.setText("Edit jika ada"); searchTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchTextFieldActionPerformed(evt); } }); jLabel7.setText("Cari :"); findButton.setText("Cari"); refreshButton.setText("Tampilkan Semua User (Refresh)"); refreshButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { refreshButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGap(50, 50, 50) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel1) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(editCheckBox)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(simpanButton) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(konfirmasiPasswordField, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE) .addComponent(usernameTextField) .addComponent(namaTextField) .addComponent(passwordField) .addComponent(emailTextField)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(usernameAlert) .addGap(134, 134, 134)) .addComponent(namaAlert, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(passwordAlert, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(konfirmasiPasswordAlert, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(emailAlert, javax.swing.GroupLayout.Alignment.LEADING))))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(findButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(refreshButton)))) .addGroup(layout.createSequentialGroup() .addGap(26, 26, 26) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 722, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(37, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(34, 34, 34) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(usernameAlert)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(namaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(namaAlert)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(passwordAlert) .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(konfirmasiPasswordAlert) .addComponent(konfirmasiPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(emailTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(emailAlert)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(simpanButton) .addComponent(editCheckBox)) .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7) .addComponent(findButton) .addComponent(refreshButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void usernameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_usernameTextFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_usernameTextFieldActionPerformed private void emailTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_emailTextFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_emailTextFieldActionPerformed private void searchTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchTextFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_searchTextFieldActionPerformed private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed // TODO add your handling code here: }//GEN-LAST:event_refreshButtonActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox editCheckBox; private javax.swing.JLabel emailAlert; private javax.swing.JTextField emailTextField; private javax.swing.JButton findButton; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel konfirmasiPasswordAlert; private javax.swing.JPasswordField konfirmasiPasswordField; private javax.swing.JLabel namaAlert; private javax.swing.JTextField namaTextField; private javax.swing.JLabel passwordAlert; private javax.swing.JPasswordField passwordField; private javax.swing.JButton refreshButton; private javax.swing.JTextField searchTextField; private javax.swing.JButton simpanButton; private javax.swing.JLabel usernameAlert; private javax.swing.JTextField usernameTextField; // End of variables declaration//GEN-END:variables public javax.swing.JLabel getEmailAlert() { return emailAlert; } public javax.swing.JTextField getEmailTextField() { return emailTextField; } public javax.swing.JLabel getKonfirmasiPasswordAlert() { return konfirmasiPasswordAlert; } public javax.swing.JPasswordField getKonfirmasiPasswordField() { return konfirmasiPasswordField; } public javax.swing.JLabel getNamaAlert() { return namaAlert; } public javax.swing.JTextField getNamaTextField() { return namaTextField; } public javax.swing.JLabel getPasswordAlert() { return passwordAlert; } public javax.swing.JPasswordField getPasswordField() { return passwordField; } public javax.swing.JButton getSimpanButton() { return simpanButton; } public javax.swing.JLabel getUsernameAlert() { return usernameAlert; } public javax.swing.JTextField getUsernameTextField() { return usernameTextField; } public void setUsernameTextField(javax.swing.JTextField usernameTextField) { this.usernameTextField = usernameTextField; } public OutputPane getOutputPane1() { return outputPane1; } public javax.swing.JButton getFindButton() { return findButton; } public javax.swing.JTextField getSearchTextField() { return searchTextField; } public javax.swing.JButton getRefreshButton() { return refreshButton; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package utsppk2018_15_8518; /** * * @author 15.8518 */ public class Main { public static void main(String args[]) { MainFrame mf = new MainFrame(); RestProxy proxy = RestProxy.getInstance(); GUIController gc = new GUIController(mf, proxy); java.awt.EventQueue.invokeLater(() -> { mf.setVisible(true); }); } } <file_sep><?php defined('BASEPATH') or exit('No direct script access allowed'); class Student extends CI_Model { public function __construct() { parent::__construct(); $this->load->database(); } public function get_all_students() { $query = $this->db->query('SELECT * FROM students ORDER BY id'); if ($this->db->error()['code'] !== 0) { return ['error' => 'db_error', 'code' => $this->db->error()['code']]; } return ['students' => $query->result_array()]; } public function get_students_by_id(string $id = null, bool $strict = false) { if ($id === null || strlen($id) === 0) { return ['students' => []]; } if ($strict) { $query = $this->db->query('SELECT * FROM students WHERE id = ? ORDER BY id', [$id]); } else { $query = $this->db->query('SELECT * FROM students WHERE id LIKE ? ORDER BY id', ['%' . $id . '%']); } if ($this->db->error()['code'] !== 0) { return ['error' => 'db_error', 'code' => $this->db->error()['code']]; } return ['students' =>$query->result_array()]; } public function get_students_by_name(string $name = null, bool $strict = false) { if ($name === null || strlen($name) === 0) { return ['students' => []]; } if ($strict) { $query = $this->db->query('SELECT * FROM students WHERE name = ? ORDER BY name', [$name]); } else { $query = $this->db->query('SELECT * FROM students WHERE name LIKE ? ORDER BY name', ['%' . $name . '%']); } if ($this->db->error()['code'] !== 0) { return ['error' => 'db_error', 'code' => $this->db->error()['code']]; } return ['students' =>$query->result_array()]; } public function validate_student(array $student_array = null) { if ($student_array === null) { return [ 'error' => 'student array is null' ]; } if (preg_match('/(^[\d]{9}$|^[\d]{2}[.][\d]{4}$)/', $student_array['id']) !== 1) { $data['error']['id'] = 'Student id is not match (i.e. 16.1111 or 211231233)'; } if (strlen($student_array['name']) === 0) { $data['error']['name'] = 'Student name is empty'; } if (strlen($student_array['name']) > 120) { $data['error']['name'] = 'Student name should be less than 120 characters'; } if (!filter_var($student_array['email'], FILTER_VALIDATE_EMAIL)) { $data['error']['email'] = 'Email is not valid'; } if (preg_match('/^[\d]{4}[-][\d]{1,2}[-][\d]{1,2}$/', $student_array['dob']) === 1) { $re = explode('-', $student_array['dob']); if (!checkdate((int)$re[1], (int)$re[2], (int)$re[0])) { $data['error']['dob'] = 'Date is not valid or out of range (should be yyyy-mm-dd)'; } } else { $data['error']['dob'] = 'Date is not well formed (i.e. yyyy-mm-dd)'; } if (strlen($student_array['address']) < 5) { $data['error']['address'] = 'Please provide more detailed address'; } if (preg_match('/^[\d]{3,15}$/', $student_array['phone']) !== 1) { $data['error']['phone'] = 'Phone number is not valid (should be 3 - 15 digit)'; } if (strlen($student_array['father_name']) === 0) { $data['error']['father_name'] = 'Father name is empty'; } if (strlen($student_array['father_name']) > 120) { $data['error']['father_name'] = 'Father name should be less than 120 characters'; } if (strlen($student_array['mother_name']) === 0) { $data['error']['mother_name'] = 'Mother name is empty'; } if (strlen($student_array['mother_name']) > 120) { $data['error']['mother_name'] = 'Mother name should be less than 120 characters'; } if (!isset($data['error'])) { $data = []; array_push($data, $student_array['id']); array_push($data, $student_array['name']); array_push($data, $student_array['email']); array_push($data, $student_array['dob']); array_push($data, $student_array['address']); array_push($data, $student_array['phone']); array_push($data, $student_array['father_name']); array_push($data, $student_array['mother_name']); } return $data; } public function add_student(array $student_array = null) { $data = $this->validate_student($student_array); if (isset($data['error'])) { return ['error' => $data['error']]; } $this->db->query('INSERT INTO students VALUES (? , ? , ? , ? , ? , ? , ? , ?)', $data); if ($this->db->error()['code'] !== 0) { return ['error' => 'db_error', 'code' => $this->db->error()['code']]; } return $this->get_students_by_id($data[0], true); } public function put_student(array $student_array = null) { $data = $this->validate_student($student_array); if (isset($data['error'])) { return ['error' => $data['error']]; } for ($i=1; $i < 8; $i++) { $data[$i+7] = $data[$i]; } $this->db->query( 'INSERT INTO students VALUES (? , ? , ? , ? , ? , ? , ? , ?) ON DUPLICATE KEY '. 'UPDATE name = ?, email = ?, dob = ?, address = ?, phone = ?, father_name = ?, mother_name = ?', $data); if ($this->db->error()['code'] !== 0) { return ['error' => 'db_error', 'code' => $this->db->error()['code']]; } return $this->get_students_by_id($data[0], true); } public function delete_student(string $id = null) { if ($id === null){ $aff = 0; } else { $this->db->query('DELETE FROM students WHERE id = ?', [$id]); $aff = $this->db->affected_rows(); } return ['affected_rows' => $aff]; } }
d67ab69e8f6a3c3b2da285aa019337c2a685f6d2
[ "Markdown", "Java", "PHP" ]
7
PHP
irfansbom/nyabun-opo-ngaso
559b757f26e969192535506c7122a82017493c46
08e1b0f145a184fe35939a03a31a4f1f9481ec4a
refs/heads/master
<file_sep><?php return [ "addtitle" => "New Pet", "add" => "Add a new Pet", "petname" => "<NAME>", "kind" => "Kind", "type" => "Type", "sex" => "Sex", "born" => "Born", "tall" => "Tall", "weight" => "Weight", "pet_users" => "Pet Users", ]; <file_sep><?php namespace App; use DB; use Illuminate\Database\Eloquent\Model; class Pet extends Model { public function users() { return $this->belongsToMany('App\User')->withPivot('admin'); } public function kind() { return $this->belongsTo('App\Kind'); } public function type() { return $this->belongsTo('App\Type'); } public function recodes() { return $this->hasMany('App\Recode')->orderBy('created_at','desc'); } public function admin($user_id) { $result = DB::select('select admin from pet_user where `pet_id` = ? and `user_id` = ? ', [$this->id,$user_id]); return $result[0]->admin; } /** * To check this dont have other reservation * * @var boolean */ public function reserved($date) { echo $date; $status = 5; $result = DB::select("select * from recodes where `pet_id` = ? AND `service_date` = ? AND `status` != ?", [$this->id,$date,$status]); if($result) return true; else return false; } } <file_sep>folk from Laravel Framework 5 Bootstrap 3 Starter Site<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Eloquent; class Recode extends Model { // protected $pet; // protected $auth; static public $status = [ 0 =>'้ ็ด„ไธญ', 1 =>'้ ็ด„ๆˆๅŠŸ', 2 =>'่™•็†ไธญ', 3 =>'ๅฎŒๆˆ', 4 =>'ๅทฒ้ ˜่ตฐ', 5 =>'ๅ–ๆถˆ', 6 =>'้€พๆ™‚็ณป็ตฑๅ–ๆถˆ', 7 =>'้ ็ด„ๅทฒๆปฟ', ]; static public $services =[ 0=>'cut', 1=>'wash', 2=>'cut and wash', ]; static public $payment_method = [ 0=>'cash', 1=>'cash 23', ]; static public $max_reserve_count = 4; public function pet(){ return $this->belongsTo('App\Pet'); } public function user(){ return $this->belongsTo('App\User'); } /** * update recode status, (not necessary * *@return boolean */ public function update_status($status) { $this->status = $status; $this->save(); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ use App\User; use App\Pet; use App\Recode; use App\Kind; use App\Type; Route::get('test', function(){ // $user = new User; // $user->name = 'test1'; // $user->username = 'test1'; // $user->email = '<EMAIL>'; // $user->save(); // $Type = new Type; // $Type->name = '้ปƒ้‡‘'; // $Type->kind_id = 1; // $Type->save(); $pet = Pet::find(1); // echo '================<pre>'; // var_dump($pet->users); // echo '</pre>================'; echo '================<pre>'; $kind = $pet->kind; var_dump($pet->kind->name); echo '</pre>================'; echo '================<pre>'; $type = $pet->type; var_dump($type->name); var_dump($pet->type->name); echo '</pre>================'; exit; }); Route::get('/', 'HomeController@index'); Route::get('home', 'HomeController@index'); Route::get('about', 'PagesController@about'); Route::get('contact', 'PagesController@contact'); Route::pattern('id', '[0-9]+'); Route::get('news/{id}', 'ArticlesController@show'); Route::get('video/{id}', 'VideoController@show'); Route::get('photo/{id}', 'PhotoController@show'); Route::controllers([ 'auth' => 'Auth\AuthController', 'password' => '<PASSWORD>', ]); Route::controllers(['pet' => 'PetController']); Route::controllers(['recode' => 'RecodeController']); if (Request::is('admin/*')) { require __DIR__.'/admin_routes.php'; } <file_sep><?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePetsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('pets', function(Blueprint $table) { $table->increments('id'); $table->string('name'); $table->integer('kind_id'); //1=dog,2=cat $table->integer('type_id'); //1=mixd,2=maltese..others $table->string('sex'); $table->date('born'); $table->integer('tall'); $table->integer('weight'); $table->boolean('status')->default(1); $table->timestamps(); }); //many to many rel Schema::create('pet_user', function(Blueprint $table) { $table->integer('user_id'); $table->integer('pet_id'); $table->boolean('admin'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('pets'); Schema::dropIfExists('pet_user'); } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Pet; use App\User; use App\Kind; use App\Type; use App\Recode; use Illuminate\Http\Request; use Illuminate\Contracts\Auth\Guard; class PetController extends Controller { protected $pet; protected $auth; public function getIndex(Guard $auth) { $user = $auth->user(); $mypets = $user->pets; return view('pet.index',compact('mypets')); } public function getCreate() { //kind $kinds = Kind::all(); $types = Type::all(); return view('pet.create',compact('kinds','types')); } public function postCreate(Request $request,Guard $auth) { /** * 1.add pet * 2.add the relationship user_pet */ $this->pet = new Pet; $this->pet->name = $request->input('petname'); $this->pet->kind_id = $request->input('kind_id'); $this->pet->type_id = $request->input('type_id'); $this->pet->sex = $request->input('sex'); $this->pet->born = date("Y-m-d",strtotime($request->input('born'))); $this->pet->tall = $request->input('tall'); $this->pet->weight = $request->input('weight'); $this->pet->save(); $this->auth = $auth; $this->pet->users()->attach($this->auth->user()->id,['admin' => 1]); return redirect($this->redirectPath()); } public function getShow(Guard $auth,$id) { $pet = Pet::find($id); $admin = $pet->admin($auth->user()->id); $status = Recode::$status; $services = Recode::$services; $payment_method = Recode::$payment_method; return view('pet.show',compact('pet','admin','status','services','payment_method')); } public function getAdduser($id,Guard $auth) { $pet = Pet::find($id); $admin = $pet->admin($auth->user()->id); if($admin){ $users = User::all(); foreach ($users as $index => $user) { foreach ($pet->users as $selected_user) { if($user->id == $selected_user->id){ unset($users[$index]); break; } } } }else { $user = array(); } return view('pet.adduser',compact('pet','users','admin')); } public function postAdduser(Request $request,$id) { $this->pet = Pet::find($id); $this->pet->users()->attach($request->input('user_id')); return redirect($this->redirectPath()); } public function getDeluser($id,Guard $auth) { $pet = Pet::find($id); $admin = $pet->admin($auth->user()->id); $users = array(); foreach ($pet->users as $user) { if($user->id != $auth->user()->id) { $users[] = $user; } } return view('pet.deluser',compact('pet','users','admin')); } public function postDeluser(Request $request,$id) { $this->pet = Pet::find($id); $this->pet->users()->detach($request->input('user_id')); return redirect($this->redirectPath()); } public function getEdit() { // $users = User::all(); // return view('pet.edituser',compact('users')); } public function postEdit() { // $this->pet->users()->attach($this->auth->user()->id); // return redirect($this->redirectPath()); } /** * Get the post register / login redirect path. * * @return string */ public function redirectPath() { if (property_exists($this, 'redirectPath')) { return $this->redirectPath; } return property_exists($this, 'redirectTo') ? $this->redirectTo : '/pet'; } } <file_sep><?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateRecodesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('recodes', function(Blueprint $table) { $table->increments('id'); $table->integer('user_id'); //foreign key from user $table->integer('pet_id'); //foreign key from pet $table->integer('status'); $table->integer('service'); $table->integer('price'); $table->integer('payment'); //how to pay ,now should be only cash $table->boolean('paied'); $table->date('service_date'); //how to pay ,now should be only cash $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('recodes'); } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Pet; use App\User; use App\Recode; use Illuminate\Http\Request; use Illuminate\Contracts\Auth\Guard; use Illuminate\Support\Facades\Session; class RecodeController extends Controller { public function getIndex(Guard $auth) { $user = $auth->user(); $status = Recode::$status; $services = Recode::$services; $payment_method = Recode::$payment_method; return view('recode.index',compact('user','status','services','payment_method')); } public function getCreate(Guard $auth) { $pets = $auth->user()->pets; $services = Recode::$services; $payment_method = Recode::$payment_method; return view('recode.create',compact('pets','services','payment_method')); } public function postCreate(Request $request,Guard $auth) { /** * add recode */ $recode = new Recode; $recode->user_id = $auth->user()->id; $recode->pet_id = $request->input('pet_id'); $recode->service = $request->input('service'); $recode->payment = $request->input('payment'); $recode->service_date = date("Y-m-d",strtotime($request->input('service_date'))); $recode->status = array_search('้ ็ด„ไธญ',Recode::$status); /** * service_date is in 28 days */ if(strtotime($recode->service_date) > strtotime("+28 day",strtotime(date("Y-m-d")))) { return redirect($this->redirectPath())->with("error"," Chosen date needs in 28 days"); } /** * check the selected pet dont have other alive reserve today */ $pet = Pet::find($recode->pet_id); if($pet->reserved($recode->service_date)) return redirect($this->redirectPath())->with("error","$pet->name already has a reservetion on $recode->service_date. "); $recode->save(); return redirect($this->redirectPath()); } /* * use to cancel a recode */ public function anyCancel($recode_id,Guard $auth) { $recode = Recode::find($recode_id); if($recode->user_id != $auth->user()->id || !in_array($recode->status, array(array_search('้ ็ด„ไธญ',Recode::$status), array_search('้ ็ด„ๆˆๅŠŸ',Recode::$status)))) return redirect('recode')->with('error', 'You can not cancel this ! '); /* change status to cancel */ $recode->status = array_search("ๅ–ๆถˆ", Recode::$status); $recode->save(); return redirect('recode')->with('success', 'Your Reserve is Canceled! '); } /* * won't use this */ public function getShow($id,Guard $auth) { $pet = Pet::find($id); $admin = $pet->admin($auth->user()->id); return view('pet.show',compact('pet','admin')); } public function getEdit($recode_id,Guard $auth) { $recode = Recode::find($recode_id); if(empty($recode)) return redirect('recode')->with('error', 'No Such Recode !'); if($recode->user_id != $auth->user()->id || !in_array($recode->status,array(array_search('้ ็ด„ไธญ',Recode::$status),array_search('้ ็ด„ๆˆๅŠŸ',Recode::$status)))) return redirect('recode')->with('error', 'You can not edit this recode! '); $services = Recode::$services; $payment_method = Recode::$payment_method; return view('recode.edit',compact('recode','services','payment_method')); } public function postEdit(Request $request,Guard $auth,$recode_id) { if($recode->user_id != $auth->user()->id) return redirect('recode')->with('error', 'You can not edit this recode! '); $recode = Recode::find($recode_id); if(empty($recode)) return redirect('/admin/recodes/'.date('Y-m-d'))->with('error','No Such Recode'); $recode->service = $request->input('service'); $recode->payment = $request->input('payment'); $recode->service_date = date("Y-m-d",strtotime($request->input('service_date'))); return redirect($this->redirectPath()); } public function getAdmin(Guard $auth,$date='') { if($auth->user()->admin != 1 ) return redirect($this->redirectPath()); if(!preg_match("/[0-9]{4}-[0-9]{2}-[0-9]{2}/",$date)) return redirect("/admin/recodes/".date('Y-m-d')); $recodes = Recode::where("service_date","=",$date)->get(); $status = Recode::$status; $services = Recode::$services; $payment_method = Recode::$payment_method; return view('recode.admin',compact('recodes','status','services','payment_method','date')); } public function getAdminedit(Guard $auth,$recode_id) { if($auth->user()->admin != 1) return redirect($this->redirectPath()); $recode = Recode::find($recode_id); if(empty($recode)) return redirect('/admin/recodes/'.date('Y-m-d'))->with('error','No Such Recode'); if(in_array($recode->status,array(4,5,6))) return redirect('/admin/recodes/'.date('Y-m-d'))->with('error','You can not edit a finish recode'); $services = Recode::$services; $payment_method = Recode::$payment_method; $status = Recode::$status; return view('recode.adminedit',compact('recode','services','payment_method','status')); } public function postAdminedit(Request $request,Guard $auth,$recode_id) { if($auth->user()->admin != 1) return redirect($this->redirectPath()); $recode = Recode::find($recode_id); if(empty($recode)) return redirect('/admin/recodes/'.date('Y-m-d'))->with('error','No Such Recode'); $recode->service = $request->input('service'); $recode->payment = $request->input('payment'); $recode->service_date = date("Y-m-d",strtotime($request->input('service_date'))); /*admin only*/ $recode->status = $request->input('status'); $recode->price = $request->input('price'); $recode->paied = $request->input('paied'); if($recode->save()) return redirect('/admin/recodes/'.$recode->service_date)->with('success','Edit Success'); else return redirect('/admin/recodes/'.$recode->service_date)->with('error','Something wrong when you edit recode'); } public function getAdmincreate(Guard $auth) { if($auth->user()->admin != 1) return redirect($this->redirectPath()); $services = Recode::$services; $payment_method = Recode::$payment_method; //just show the status we need $status = array(); $status[1] = Recode::$status[1]; $status[2] = Recode::$status[2]; $status[3] = Recode::$status[3]; $status[4] = Recode::$status[4]; $status[5] = Recode::$status[5]; return view('recode.admincreate',compact('services','payment_method','status')); } public function postAdmincreate(Request $request,Guard $auth) { if($auth->user()->admin != 1) return redirect($this->redirectPath()); $recode = new Recode; $recode->user_id = $auth->user()->id; $recode->pet_id = $request->input('pet_id'); $recode->service = $request->input('service'); $recode->payment = $request->input('payment'); $recode->service_date = date("Y-m-d",strtotime($request->input('service_date'))) ; /*admin only*/ $recode->status = $request->input('status'); $recode->paied = ($request->input('paied')) ?1:0; if($recode->save()) return redirect('/admin/recodes/'.$recode->service_date)->with('success','Create Success'); else return redirect('/admin/recodes/'.$recode->service_date)->with('error','Something wrong when you create recode'); } public function postFinduser(Request $request,Guard $auth) { if($auth->user()->admin != 1) return redirect($this->redirectPath()); $method = $request->input('method'); $data = $request->input('data'); if(empty($data)) return json_encode(array('msg'=>'no data to search')); $users = User::where($method,"like","%$data%")->get(); if(empty($users)) return json_encode(array('msg'=>'no such user')); return json_encode($users); } public function postFindpet(Request $request,Guard $auth) { if($auth->user()->admin != 1) return redirect($this->redirectPath()); $user_id = $request->input('user_id'); $user = User::find($user_id); if(empty($user_id)) return json_encode(array('msg'=>'no user selected or no such user')); $pets = $user->pets; if(empty($pets)) return json_encode(array('msg'=>'no pet for this user')); return json_encode($pets); } public function getAdminreceive(Guard $auth) { if($auth->user()->admin != 1) return redirect($this->redirectPath()); $services = Recode::$services; //just show the status we need $status = array(); $status[1] = Recode::$status[1]; $status[7] = Recode::$status[7]; //find all receive $date = date("Y-m-d"); $receive_recodes = Recode::where("service_date",">",$date)->where("status","in",array(0,1))->get(); $recodes = array(); foreach ($receive_recodes as $recode) { $recodes[$recode->service_date][] = $recode; } ksort($recodes); //count each days receive num $date_count = array(); foreach ($recodes as $date =>$daterecodes) { $date_count[$date] = Recode::where("status","=","1")->where("service_date","=",$date)->count(); } return view('recode.adminreceive',compact('recodes','services','status','date_count')); } public function postAdminreceive(Request $request,Guard $auth) { if($auth->user()->admin != 1) return redirect($this->redirectPath()); $status = $request->input('status'); $recode_ids = $request->input('checked_recode'); foreach($recode_ids as $recode_id) { $recode = Recode::find($recode_id); $recode->status = $status; $recode->save(); } return redirect('/admin/recodes/receive')->with('success','Receive Check Success'); } public function postReserveStatus(Request $request,Guard $auth) { // $user_id = $request->input('user_id'); // $user = User::find($user_id); // if(empty($user_id)) // return json_encode(array('msg'=>'no user selected or no such user')); // $pets = $user->pets; // if(empty($pets)) // return json_encode(array('msg'=>'no pet for this user')); $sFirstDate = $request->input('first_date'); $iNumber = $request->input('number'); $sDate = $sFirstDate; $sToday = date("Y-m-d"); $sEndDate = date("Y-m-d",strtotime("+28 day")); // ่ƒฝ้ ็ด„็š„ๆœ€ๅพŒไธ€ๅคฉ $iMaxReserve = Recode::$max_reserve_count; $aReserveStatus = array(); for ($i=0; $i < $iNumber; $i++) { $aReserveStatus[$i]['date'] = $sDate; if(strtotime($sDate)<=strtotime($sToday)) { $aReserveStatus[$i]['title'] = "ๅทฒ้ŽๆœŸ"; $aReserveStatus[$i]['color'] = "#BDBDBD"; } elseif(strtotime($sDate)>strtotime($sEndDate)) { $aReserveStatus[$i]['title'] = "ๆœช้–‹ๆ”พ้ ็ด„"; $aReserveStatus[$i]['color'] = "#BDBDBD"; } else{ $iCount = Recode::where("service_date","=",$sDate)->where("status","in",array(0,1))->count(); $iRemainNumber = $iMaxReserve - $iCount;//ๅ‰ฉ้ค˜ๆ•ธ้‡ if($iRemainNumber<=0) { $aReserveStatus[$i]['title'] = "้ ็ด„ๅทฒๆปฟ"; $aReserveStatus[$i]['color'] = "red"; } elseif($iRemainNumber<=3) { $aReserveStatus[$i]['title'] = "ๅฐšๅฏ้ ็ด„ๆ•ธ้‡๏ผš".$iRemainNumber; $aReserveStatus[$i]['color'] = "yellow"; } else { $aReserveStatus[$i]['title'] = "ๅฐšๅฏ้ ็ด„"; $aReserveStatus[$i]['color'] = "blue"; } } $sDate = date("Y-m-d",strtotime("+1 day",strtotime($sDate))); } return json_encode($aReserveStatus); } /** * Get the post register / login redirect path. * * @return string */ public function redirectPath() { if (property_exists($this, 'redirectPath')) { return $this->redirectPath; } return property_exists($this, 'redirectTo') ? $this->redirectTo : '/recode'; } } <file_sep><?php return [ "create" => "Create", "service" => "Service", "reserve" => "Reserve", "pet" => "Pet", "payment_method" => "Payment Method", "edit_title" => "Edit Recode", "edit" => "Edit ", "status" => "Status ", "cancel" => "Cancel ", "date" => "Date ", "paied" => "Paied ", "price" => "Price ", "user" => "User ", "search_user_data" => "Search Data ", "search_user_by" => "Search User By ", "phone" => "Phone ", "name" => "Name ", "service_date" => "Service Date ", "create_at" => "Create Time ", ]; <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Kind extends Model { public function types(){ return $this->hasMany('App\Type'); } }
3f962a07a6722947c13a4f84b78f710fb005c991
[ "Markdown", "PHP" ]
11
PHP
far666/petshop
5b35d8dac9d01731bd4731405a710f250c903b36
5428798111b5b0501b4e78808a9823029b5e4ff5
refs/heads/master
<file_sep># sample_selenium This python script is a sample for selenium test using Excel.sheet. <file_sep>#20190401 # https://note.nkmk.me/python-openpyxl-usage/ ''' Auto form fulling test_Hotel_reservation_form using selsenium. ''' import time from selenium import webdriver from selenium.webdriver.common.by import By import openpyxl class EX_LIST: def __init__(self,file_1): self.file_1 = file_1 def get_value_list(self,t_2d): return([[cell.value for cell in row] for row in t_2d]) def get_list_2d(self,sheet, start_row, end_row, start_col, end_col): return self.get_value_list(sheet.iter_rows(min_row=start_row, max_row=end_row, min_col=start_col, max_col=end_col)) def make_list(self): wb = openpyxl.load_workbook(self.file_1) sheet_names = wb.get_sheet_names() sheet = wb.get_sheet_by_name(sheet_names[0]) # print(sheet.max_row) l_2d = self.get_list_2d(sheet, 2, sheet.max_row, 1, sheet.max_column) return l_2d class FORM_SEND(): def __init__(self, driver): self._driver = driver def name_formsend_befor_clear(self,name,text1): try: element =driver.find_element_by_name(name) element.clear() self._driver.find_element_by_name(name).send_keys(text1) # elememt.send_keys(text1) except KeyError: # KerError """ except Exception as e: print("ไพ‹ๅค–args:", e.args) """ time.sleep(3) self._driver.quit() def determin_botun(self,text4): try: self._driver.find_element_by_id(text4).click() except Exception as e: print("Exception args:", e.args) if __name__=='__main__': test1 = EX_LIST('selenium_test.xlsx') result =test1.make_list() print(result) url_1= 'http://example.selenium.jp/reserveApp/' driver = webdriver.Chrome() driver.get(url_1) form_ex1 = FORM_SEND(driver) for row in range(len(result)): # redserve date form_ex1.name_formsend_befor_clear('reserve_y',result[row][0]) time.sleep(1) # manth form_ex1.name_formsend_befor_clear('reserve_m',result[row][1]) time.sleep(1) # day form_ex1.name_formsend_befor_clear('reserve_d',result[row][2]) time.sleep(1) # How long stay form_ex1.name_formsend_befor_clear('reserve_t',result[row][3]) time.sleep(1) # How manay person form_ex1.name_formsend_befor_clear('hc',result[row][4]) time.sleep(1) # have a breakfasr if result[row][6] =='1': form_ex1.determin_botun('breakfast_on') else: form_ex1.determin_botun('breakfast_off') # plan a or b if result[row][8] =='1': form_ex1.determin_botun('plan_a') else: form_ex1.determin_botun('plan_b') # customer name form_ex1.name_formsend_befor_clear('gname',result[row][5]) time.sleep(1) # next page form_ex1.determin_botun('goto_next') time.sleep(3) form_ex1.determin_botun('commit') time.sleep(3) form_ex1.determin_botun('returnto_checkInfo') form_ex1.determin_botun('returnto_index') time.sleep(3) time.sleep(2) driver.quit()
6ddb73b202dbc4bd69bfa70ab09abce67ada3978
[ "Markdown", "Python" ]
2
Markdown
genkioyaji/sample_selenium
ccc7331e8d6d7904db42e93ae46b8cda59a06726
ad52a2e73bfc241b1e43b3ecf37381f34c353ea6
refs/heads/master
<repo_name>Regoradin/Seminar<file_sep>/placement.py import random, sqlite3 class Seminar: def __init__(self, id, capacity, session, no_random): self.id = id self.capacity = capacity self.students = [] self.session = session self.no_random = no_random def AddStudent(self, student, keep_capacity = True): self.students.append(student) if keep_capacity: self.RemoveStudents() def RemoveStudents(self): while len(self.students) > self.capacity: min_benefit = 100 min_student = None for student in self.students: if self.session == 1: rankings = student.first_rankings if self.session == 2: rankings = student.second_rankings for i in range(0,len(rankings)): if rankings[i][0] == self: #benefit is calculated as (the weight assigned to this seminar - the next best seminar) found_next_best = False #Loops to the next highest ranked seminar with open seats for j in range(i,len(rankings)): next_best_seminar = rankings[j][0] if next_best_seminar.capacity > len(next_best_seminar.students): benefit = rankings[i][1] - rankings[j][1] found_next_best = True #If that doesn't exist, benefit is just the benefit of being in the current seminar if not found_next_best: benefit = rankings[i][1] #Minor bias towards upperclassmen here if benefit < min_benefit or (benefit == min_benefit and student.grade < min_student.grade): min_benefit = benefit min_student = student break #only gets to here if this seminar isn't even on their list, in which case it's impossible to get benefit min_student = student min_benefit = 0 #Kicks the student out, and moves them to their highest ranked seminar with open seats self.students.remove(min_student) placed = False if self.session == 1: rankings = min_student.first_rankings if self.session == 2: rankings = min_student.second_rankings if self.session == 3: rankings = min_student.double_rankings for ranking in rankings: if ranking[0].capacity > len(ranking[0].students): ranking[0].AddStudent(min_student) placed = True if not placed: if self.session == 1: PlaceRandomly(all_first_seminars, student) if self.session == 2: PlaceRandomly(all_second_seminars, student) if self.session == 3: min_student.first_rankings[0][0].AddStudent(student) min_student.second_rankings[0][0].AddStudent(student) return def PrintStudents(self): print("Students in seminar " + str(self.id)) for student in self.students: print(student.id) class Student: def __init__(self, id, grade): self.id = id self.first_rankings = [] self.second_rankings = [] self.double_rankings = [] self.grade = grade def AddRanking(self, sem, ranking): if sem.session == 1: rankings = self.first_rankings if sem.session == 2: rankings = self.second_rankings if sem.session == 3: rankings = self.double_rankings #places the new ranking in the appropriate list in order if len(rankings) == 0: rankings.append((sem, ranking)) else: for i in range(0, len(self.rankings)): if rankings[i][1] < ranking: rankings.insert(i, (sem, ranking)) def PlaceRandomly(seminars, student): seminar = seminars.values()[random.randint(0, len(all_seminars.values())-1)] while seminar.no_random == True: seminar = seminars.values()[random.randint(0, len(all_seminars.values())-1)] seminar.AddStudent(student) def SortStudents(students, seminars, unranked_students): total_students = len(students) + len(unranked_students) seminar_slots = 0 for seminar in seminars: seminar_slots += seminar.capacity if (seminar_slots/2) < total_students: #there is a slight chance that this will fire even if there are enough spots because double period seminars should count double. print("\x1b[1;31;40mThere are more students than their are available seminars!\x1b[0m") #Adds all students into their first choice seminar for student in students: if len(student.double_rankings) != 0: student.double_rankings[0][0].AddStudent(student, False) else: if len(student.first_rankings) != 0: student.first_rankings[0][0].AddStudent(student, False) else: PlaceRandomly(all_first_seminars, student) if len(student.second_rankings) != 0: student.second_rankings[0][0].AddStudent(student, False) else: PlaceRandomly(all_second_seminars, student) #Places students who did not make a selection into a random seminar for student in unranked_students: PlaceRandomly(all_first_seminars, student) PlaceRandomly(all_second_seminars, student) for seminar in seminars: seminar.RemoveStudents() #All seminars should now be at or under capacity and students should be properly sorted conn.execute('''DROP TABLE if exists assignments''') conn.execute('''CREATE TABLE assignments( id INTEGER PRIMARY KEY, sems_id INTEGER NOT NULL, student_id INTEGER NOT NULL, FOREIGN KEY (sems_id) REFERENCES seminar_semester(id), FOREIGN KEY (student_id) REFERENCES students(id))''') for seminar in seminars: for student in seminar.students: c.execute('''INSERT INTO assignments (sems_id, student_id) VALUES (?, ?)''',(seminar.id, student.id)) conn.commit() conn = sqlite3.connect('seminars.db') c = conn.cursor() #Builds seminar items all_first_seminars = {} all_second_seminars = {} all_double_seminars = {} c.execute('''SELECT sems.id, semi.capacity, sems.session, semi.sign_up, semi.no_random FROM seminar_semester sems INNER JOIN seminars semi ON semi.id = sems.seminar_id INNER JOIN semesters seme ON seme.id = sems.semester_id WHERE seme.is_current = 1''') results = c.fetchall() for result in results: if result[3] == 1 or result[4] == 1: no_random = True new_seminar = Seminar(result[0], result[1], result[2], no_random) if int(result[2]) == 1: all_first_seminars[result[0]] = new_seminar if int(result[2]) == 2: all_second_seminars[result[0]] = new_seminar if int(result[2]) == 3: all_double_seminars[result[0]] = new_seminar all_seminars = all_first_seminars all_seminars.update(all_second_seminars) all_seminars.update(all_double_seminars) #Builds student items all_ranked_students = [] created_ids = [] c.execute('''SELECT choices.student_id, choices.rank, choices.sems_id, students.grade FROM student_choices choices INNER JOIN students students ON choices.student_id = students.id''') results = c.fetchall() for result in results: #matches sems_id to seminar object seminar = all_seminars[result[2]] if result[0] not in created_ids: student = Student(result[0], int(result[3])) all_ranked_students.append(student) created_ids.append(result[0]) student.AddRanking(seminar, result[1]) else: for student in all_ranked_students: if student.id == result[0]: student.AddRanking(seminar, result[1]) break #creating students who did not put a ranking all_unranked_students = [] c.execute('''SELECT id,grade FROM students WHERE id NOT IN (SELECT student_id FROM student_choices)''') unranked_students = c.fetchall() for student in unranked_students: new_student = Student(student[0], int(student[1])) all_unranked_students.append(new_student) SortStudents(all_ranked_students, all_seminars.values(), all_unranked_students) # sem1 = Seminar(1, 0) # sem2 = Seminar(2, 1) # sem3 = Seminar(3, 2) # stud1 = Student(1, [(sem2, 10), (sem1, 4)]) # stud2 = Student(2, [(sem2, 10), (sem1, 6), (sem3, 2)]) # all_seminars = [sem1, sem2, sem3] # sem2.AddStudent(stud1) # sem2.AddStudent(stud2) # sem1.PrintStudents() # sem2.PrintStudents() # sem3.PrintStudents() <file_sep>/js/scripts.js function AddTeacher(teachers, selected_teacher = false){ var div = document.getElementById("teacher_select"); var select = document.createElement("select"); select.name = "teacher" div.appendChild(select); for (var i in teachers){ var option = document.createElement("option"); option.id = teachers[i][0]; option.value = teachers[i][0]; option.text = teachers[i][1]; if(selected_teacher == teachers[i][0]){ option.selected = true; } select.appendChild(option); } } function RemoveTeacher(teacher_id){ var div = document.getElementById("teacher_remove"); var remove = document.createElement("button"); div.appendChild(remove); remove.onclick = function(){RemoveElement(teacher_id);}; remove.innerHTML = "Remove"; } function RemoveElement(id){ console.log("Removing " + id); var elem = document.getElementById(id); elem.parentNode.removeChild(elem); } <file_sep>/tutorial.py from bottle import route, run, template, static_file, error, response, redirect, request, template @route('/hello') def hello_again(): if request.get_cookie("visited"): return "Welcome back! Nice to see you again" else: response.set_cookie("visited", "yes") return "Hello there! Nice to meet you" @route('/') @route('/hello/<name>/<i:int>') def greet(i = 1, name = 'Stranger'): response.set_header("Content-language", "en") return (template('Hello {{name}}, how are you?\n', name = name)) * i @route('/static/<filename>') def server_static(filename): return static_file(filename, root = './static') @error(404) def error(error): return 'Error! Alert! Everything is breaking!' @route('/wrong') def wrong(): if request.get_cookie("wronged"): return "you have wronged twice. no redirect for you." response.set_cookie("wronged", "yes") redirect("/hello/errorer/2") @route('/login') def login(): return ''' <form action="/login" method="post"> Username: <input name="username" type="text" /> Password: <input name="<PASSWORD>" type="<PASSWORD>" /> <input value="Login" type = "submit" /> </form> ''' @route("/login", method="POST") def do_login(): username = request.forms.get('username') password = request.forms.get('<PASSWORD>') return(str(username) + " " + str(password)) @route("/template") def hello(): return template("hello_template", name = "world") run(host='localhost', port=8080, debug = True) <file_sep>/seminar.py import sqlite3, json from bottle import route, run, debug, template, request, static_file,redirect conn = sqlite3.connect('seminars.db') c = conn.cursor() #seminars table creation conn.execute('''CREATE TABLE IF NOT EXISTS seminars ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, description TEXT NOT NULL, first_day_note TEXT NOT NULL, capacity INTEGER NOT NULL, cost INTEGER NOT NULL, sign_up INT NOT NULL DEFAULT 0 CHECK (sign_up IN (0, 1)), no_random INT NOT NULL DEFAULT 0 CHECK(no_random IN (0, 1)))''') #semesters table creation conn.execute('''CREATE TABLE IF NOT EXISTS semesters ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, is_current INTEGER NOT NULL CHECK(is_current IN (0,1)))''') #room table creation conn.execute('''CREATE TABLE IF NOT EXISTS rooms ( id INTEGER PRIMARY KEY, name TEXT NOT NULL)''') #seminar_semester table creation conn.execute('''CREATE TABLE IF NOT EXISTS seminar_semester ( id INTEGER PRIMARY KEY, seminar_id INTEGER NOT NULL, semester_id INTEGER NOT NULL, session INTEGER NOT NULL, room_id INTEGER NOT NULL, FOREIGN KEY (semester_id) REFERENCES semesters(id), FOREIGN KEY(seminar_id) REFERENCES seminars(id), FOREIGN KEY (room_id) REFERENCES rooms(id), CHECK (session in (1, 2, 3)), UNIQUE (semester_id, room_id, session))''') #teachers table creation conn.execute('''CREATE TABLE IF NOT EXISTS teachers ( id INTEGER PRIMARY KEY, name TEXT NOT NULL)''') #teacher_sems table creation conn.execute('''CREATE TABlE IF NOT EXISTS teacher_sems ( id INTEGER PRIMARY KEY, teacher_id INTEGER NOT NULL, sems_id INTEGER NOT NULL, is_primary INTEGER NOT NULL CHECK(is_primary IN (0,1)), FOREIGN KEY (teacher_id) REFERENCES teachers(id), FOREIGN KEY(sems_id) REFERENCES semester_seminar(id))''') #student table creation conn.execute('''CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, grade INT NOT NULL CHECK(grade IN (1, 2, 3, 4)))''') #student_choices table creation conn.execute('''CREATE TABLE IF NOT EXISTS student_choices ( id INTEGER PRIMARY KEY, student_id INTEGER NOT NULL, sems_id INTEGER NOT NULL, rank INTEGER NOT NULL, FOREIGN KEY (student_id) REFERENCES students(id), FOREIGN KEY (sems_id) REFERENCES seminar_semester(id))''') #Semester system will remain janky for now # c.execute("INSERT INTO semesters (name, is_current) VALUES ('Fall 2017', 0)") # c.execute("INSERT INTO semesters (name, is_current) VALUES ('Spring 2018', 1)") # c.execute('INSERT INTO teachers (name) VALUES ("Hyman"), ("Catlin"), ("Cristiano"), ("Tolias"), ("Person");') # c.execute('INSERT INTO rooms (name) VALUES ("101"), ("102"), ("103"), ("104"), ("105"), ("106"), ("107"), ("108"), ("109"), ("110"), ("111");') # conn.commit() def CheckboxToInt(input): if input != None: return 1 else: return 0 @route('/js/<filename:path>') def send_js(filename): return static_file(filename, root='js') @route('/css/<filename:path>') def send_css(filename): return static_file(filename, root='css') #TEACHER SIDE @route('/teacher') def teacher_home(): return template('templates/teacher_home.tpl') @route('/teacher/add', method="GET") def add_page(): c.execute("SELECT id, name FROM teachers") teachers = json.dumps(c.fetchall()) #This will select all rooms that do not have any seminars in them this semester. #c.execute('''SELECT id, name FROM rooms WHERE id NOT IN( # SELECT room_id FROM seminar_semester semx # INNER JOIN semesters seme ON semx.semester_id = seme.id # WHERE is_current = 1)''') c.execute('''SELECT id, name FROM rooms''') rooms = json.dumps(c.fetchall()) return template('templates/add_seminar.tpl', teachers=teachers, rooms=rooms) @route('/teacher/add', method="POST") def add_page(): title = request.forms.get('title') description = request.forms.get('description') teachers = request.forms.getall('teacher') first_day_note = request.forms.get('first_day_note') capacity = request.forms.get('capacity') cost = request.forms.get('cost') sign_up = CheckboxToInt(request.forms.get('sign_up')) no_random = CheckboxToInt(request.forms.get('no_random')) session = request.forms.get('session') room_id = request.forms.get('room_id') c.execute("INSERT INTO seminars (title, description, first_day_note, capacity, cost, sign_up, no_random) VALUES (?, ?, ?, ?, ?, ?, ?)",(title, description, first_day_note, capacity, cost, sign_up, no_random)) seminar_id = c.lastrowid c.execute("SELECT id FROM semesters WHERE is_current = 1") semester_id = c.fetchone()[0] c.execute("INSERT INTO seminar_semester (seminar_id, semester_id, session, room_id) VALUES (?,?,?, ?)", (seminar_id, semester_id, session, room_id)) sems_id = c.lastrowid for teacher in teachers: c.execute("INSERT INTO teacher_sems (teacher_id, sems_id, is_primary) VALUES (?,?, 1)", (teacher, sems_id)) conn.commit() redirect('/teacher') @route('/teacher/add_old', method = "GET") def add_old(): #selects seminars that were offered in previous semester but are NOT offered this semester c.execute('''SELECT semi.id, semi.title, semi.description FROM seminars semi INNER JOIN seminar_semester sems ON sems.seminar_id = semi.id INNER JOIN semesters seme ON sems.semester_id = seme.id AND seme.is_current = 0 WHERE semi.id NOT IN( SELECT semi.id FROM seminars semi INNER JOIN seminar_semester sems ON sems.seminar_id = semi.id INNER JOIN semesters seme ON sems.semester_id = seme.id AND seme.is_current = 1)''') old_seminars = json.dumps(c.fetchall()) #This will select all rooms without any seminars in them this semester. #c.execute('''SELECT id, name FROM rooms WHERE id NOT IN( # SELECT room_id FROM seminar_semester semx # INNER JOIN semesters seme ON semx.semester_id = seme.id # WHERE is_current = 1)''') c.execute('''SELECT id, name FROM rooms''') rooms = json.dumps(c.fetchall()) return template('templates/add_old_seminar.tpl', old_seminars=old_seminars, rooms = rooms) @route('/teacher/add_old', method = "POST") def add_old_save(): sem_id = request.forms.get('sem_id') session = request.forms.get('session') room_id = request.forms.get('room_id') c.execute("SELECT id FROM semesters WHERE is_current = 1") semester_id = c.fetchone()[0] c.execute("INSERT INTO seminar_semester (seminar_id, semester_id, session, room_id) VALUES (?, ?, ?, ?)", (sem_id, semester_id, session, room_id)) conn.commit() print("Adding old") redirect("/teacher/add_old") @route('/teacher/edit/select', method="GET") def edit_select(): #Edit select page: picks a seminar to edit from the seminar table that is linked to the currently active semester c.execute('''SELECT sems.id, semi.title FROM seminar_semester sems INNER JOIN seminars semi ON sems.seminar_id = semi.id INNER JOIN semesters seme ON sems.semester_id = seme.id WHERE seme.is_current =1''') results = json.dumps(c.fetchall()) return template('templates/edit_select.tpl', results = results) @route('/teacher/edit/seminar', method = "POST") def edit(): #Actual editing page sems_id = request.forms.get('sems_id') print("SEMS ID: %s" %sems_id) #This gets unpacked inside edit_seminar.tpl c.execute('SELECT id, title, description, first_day_note, capacity, cost, sign_up, no_random FROM seminars WHERE id IN (SELECT seminar_id FROM seminar_semester WHERE id = ?)', (sems_id,)) seminar = c.fetchone() c.execute('SELECT room_id, session FROM seminar_semester WHERE id = ?', (sems_id,)) result = c.fetchone() room_id = result[0] session = result[1] #This will select only rooms that have no seminars in them at all this semester. #c.execute('''SELECT id, name FROM rooms WHERE (id = ?) OR (id NOT IN( # SELECT room_id FROM seminar_semester semx # INNER JOIN semesters seme ON semx.semester_id = seme.id # WHERE is_current = 1))''', (room_id,)) c.execute('''SELECT id, name FROM rooms''') all_rooms = json.dumps(c.fetchall()) c.execute("SELECT id, name FROM teachers") teachers = json.dumps(c.fetchall()) c.execute("SELECT teacher_id, name FROM teacher_sems INNER JOIN teachers ON teacher_sems.teacher_id = teachers.id WHERE sems_id = ?", (sems_id,)) selected_teachers = json.dumps(c.fetchall()) return template('templates/edit_seminar.tpl', seminar = seminar, teachers=teachers, sems_id = sems_id, selected_teachers = selected_teachers, room_id = room_id, all_rooms = all_rooms, session = session) @route('/teacher/edit/save', method="POST") def edit_save(): #Saves the edits to the seminars table sem_id = request.forms.get('sem_id') title = request.forms.get('title') description = request.forms.get('description') first_day_note = request.forms.get('first_day_note') capacity = request.forms.get('capacity') cost = request.forms.get('cost') sign_up = CheckboxToInt(request.forms.get('sign_up')) no_random = CheckboxToInt(request.forms.get('no_random')) session = request.forms.get('session') room = request.forms.get('room') print("SIGN UP: %s" %sign_up) print("NO_RAND: %s" %no_random) c.execute('UPDATE seminars SET title = ?, description = ?, capacity = ?, cost = ?, sign_up = ?, no_random = ? WHERE id = ?', (title, description, capacity, cost, sign_up, no_random, sem_id)) #Resets links in the teacher_sems table sems_id = request.forms.get('sems_id') c.execute("DELETE FROM teacher_sems WHERE sems_id = ?", (sems_id)) added_teachers = [] for teacher in request.forms.getall('teacher'): if teacher not in added_teachers: added_teachers.append(teacher) c.execute("INSERT INTO teacher_sems (teacher_id, sems_id, is_primary) VALUES (?, ?, 0)", (teacher, sems_id)) c.execute('UPDATE seminar_semester SET session = ?, room_id = ? WHERE id = ?', (session, room, sems_id)) conn.commit() redirect("/teacher/edit/select", code=303) @route('/teacher/remove', method="GET") def remove(): c.execute('''SELECT sems.id, semi.title FROM seminar_semester sems INNER JOIN seminars semi ON sems.seminar_id = semi.id INNER JOIN semesters seme ON sems.semester_id = seme.id WHERE seme.is_current =1''') seminars = json.dumps(c.fetchall()) return template('templates/remove_seminar.tpl', seminars = seminars) @route('/teacher/remove', method="POST") def remove_submit(): for sems_id in request.forms.getall("removed"): c.execute("DELETE FROM seminars WHERE id = (SELECT seminar_id FROM seminar_semester WHERE ID = ?)",(sems_id)) c.execute("DELETE FROM seminar_semester WHERE id = ?",(sems_id)) conn.commit() redirect("/teacher") #STUDENT SIDE @route('/student', method="GET") def student(): c.execute('''SELECT sems.id, semi.title, semi.description, sems.session FROM seminar_semester sems INNER JOIN seminars semi ON sems.seminar_id = semi.id INNER JOIN semesters seme ON sems.semester_id = seme.id WHERE seme.is_current =1 and semi.sign_up = 0''') seminars = c.fetchall() first_seminars = [] second_seminars = [] double_seminars = [] for seminar in seminars: if seminar[3] == 1: first_seminars.append(seminar) if seminar[3] == 2: second_seminars.append(seminar) if seminar[3] == 3: double_seminars.append(seminar) return template('templates/student_home.tpl', first_seminars = json.dumps(first_seminars), second_seminars = json.dumps(second_seminars), double_seminars = json.dumps(double_seminars)) @route('/student/submit', method="POST") def submit(): student_id = request.forms.get("student_id") # chosen_seminars = request.forms.getall("chosen_seminars") for key, value in request.forms.items(): if key.startswith('seminar_'): x, seminar_id = key.split("_") if value != "0": c.execute("INSERT INTO student_choices (student_id, sems_id, rank) VALUES (?, ?, ?)", (student_id, seminar_id, value)) conn.commit() return "Seminars chosen!" run(debug = True, reloader = True) #because for some reason the reloader doesn't work on my laptop because everything is terrible. #run(debug =True)
2c7bd6ac12ad6c81985ec35fa7a8e24ff0ef3249
[ "JavaScript", "Python" ]
4
Python
Regoradin/Seminar
20ce3c0675ac7bcfbf8910f5bf51ece6f7eec013
e7252fa320cdb655903859ff3e95d2e587e12606
refs/heads/master
<repo_name>team-emm-too/kalendae<file_sep>/my-app/src/App.js import React from 'react'; import './App.css'; import 'semantic-ui-css/semantic.min.css'; import {Form, Grid, Header, Menu, Message, TextArea, Button, Icon, List, Segment, Divider} from 'semantic-ui-react'; class App extends React.Component { state = { eventName: "", eventLocation: "", start: "", end: "", eventDescription: "", repeat: "No Repeat", class: "PUBLIC", priority: "9", error: [], timezone: "", RSVP: false, toRSVP: "", arrRSVP: [], GEO: "", sender: "", dateException: "", arrDate: [], resources: [], resource: '', arrMonths: [], emailError: false, repeatOptions: [ {key: 'n', value: "No Repeat", text: 'No Repeat'}, {key: 'd', value: 'DAILY', text: 'Daily'}, {key: 'w', value: 'WEEKLY', text: 'Weekly'}, {key: 'm', value: 'MONTHLY', text: 'Monthly'}, {key: 'y', value: 'YEARLY', text: 'Yearly'}, ], classOptions: [ {key: 'u', value: 'PUBLIC', text: 'Public'}, {key: 'r', value: 'PRIVATE', text: 'Private'}, {key: 's', value: 'CONFIDENTIAL', text: 'Confidential'}, ], priorityOptions: [ {key: 'l', value: '9', text: 'Low'}, {key: 'm', value: '5', text: 'Medium'}, {key: 'h', value: '1', text: 'High'}, ], months: [ {key: "JAN", value: '1', text: "January"}, {key: "FEB", value: '2', text: "February"}, {key: "MAR", value: '3', text: "March"}, {key: "APR", value: '4', text: "April"}, {key: "MAY", value: '5', text: "May"}, {key: "JUN", value: '6', text: "June"}, {key: "JUL", value: '7', text: "July"}, {key: "AUG", value: '8', text: "August"}, {key: "SEP", value: '9', text: "September"}, {key: "OCT", value: '10', text: "October"}, {key: "NOV", value: '11', text: "November"}, {key: "DEC", value: '12', text: "December"}, ] }; componentDidMount() { let timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; let xhr = new XMLHttpRequest(); xhr.responseType = "text";//force the HTTP response, response-type header to be blob xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { let arr = xhr.response.split("\r\n"); let result = arr.slice(arr.indexOf("BEGIN:VTIMEZONE"), arr.indexOf("END:VTIMEZONE") + 1).join("\r\n"); this.setState({timezone: result}); } }.bind(this); xhr.open("GET", `https://cors-anywhere.herokuapp.com/http://tzurl.org/zoneinfo-outlook/${timezone}`); xhr.send(); this.initAutocomplete(); } submit = (e) => { e.preventDefault(); let element = document.createElement('a'); let date = new Date(); let startDate = new Date(this.state.start); let endDate = new Date(this.state.end); let formError = false; let errorMessages = []; //Date checking if (startDate > endDate) { formError = true; errorMessages.push("The event start date cannot be later than the event end date!"); } let currentDateTime = date.getFullYear() + '' + +'' + (date.getMonth() + 1) + '' + ("0" + date.getDate()).slice(-2) + 'T' + ("0" + date.getHours()).slice(-2) + '' + ("0" + date.getMinutes()).slice(-2) + '' + ("0" + date.getSeconds()).slice(-2); let recurrence = ''; let classification = ''; let priority = ''; let timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; let RSVP = ''; let resource = 'RESOURCE:'; let dateExceptions = ""; if (this.state.repeat !== 'No Repeat') { recurrence += 'RRULE:FREQ=' + this.state.repeat + '\r\n'; } if (this.state.arrMonths.length !== 0) { recurrence += 'EXRULE:FREQ=YEARLY;BYMONTH=' + this.state.arrMonths.join(",") + '\r\n'; } if (this.state.class !== '') { classification += 'CLASS:' + this.state.class + '\r\n'; } if (this.state.priority !== '') { priority += 'PRIORITY:' + this.state.priority + '\r\n'; } if (this.state.RSVP === true) { this.state.arrRSVP.forEach( (value) => RSVP += 'ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;\r\n RSVP=TRUE:MAILTO:' + value + '\r\n' ) } if (this.state.resources.length !== 0) { this.state.resources.forEach( (value) => (resource.substring(resource.indexOf('\n')).length + value.length > 28) ? resource += `\r\n ${value},` : resource += `${value},` ); resource = resource.substring(0, resource.length - 1); resource += '\r\n'; } if (this.state.arrDate.length !== 0) { dateExceptions = 'EXDATE:' + this.state.arrDate.join(",").split("-").join("") + '\r\n'; } element.setAttribute('href', 'data:text/calendar;charset=utf-8,' + //Starting Calendar 'BEGIN:VCALENDAR\r\n' + //Calendar Version 'VERSION:2.0\r\n' + 'PRODID:-//Team-emm-too//Kalendae//EN\r\n' + //Calendar Type 'CALSCALE:GREGORIAN\r\n' + 'METHOD:PUBLISH\r\n' + //Timezone info this.state.timezone + "\r\n" + //Starting Event 'BEGIN:VEVENT\r\n' + "UID:" + currentDateTime + "-<EMAIL>4.com\r\n" + 'SEQUENCE:0\r\n' + // Time event was created 'DTSTAMP;TZID=' + timezone + ":" + currentDateTime + '\r\n' + //Start time of event 'DTSTART;TZID=' + timezone + ":" + this.state.start.split('-').join('').replace(':', '') + '00\r\n' + //End time of event 'DTEND;TZID=' + timezone + ":" + this.state.end.split('-').join('').replace(':', '') + '00\r\n' + //Event Name 'SUMMARY:' + this.state.eventName + '\r\n' + //Event Description 'DESCRIPTION:' + this.state.eventDescription + '\r\n' + //Event Location 'LOCATION:' + this.state.eventLocation + '\r\n' + //GEO LOCATION 'GEO:' + this.state.GEO + '\r\n' + //Recurrence recurrence + //Date Exceptions dateExceptions + //Classification classification + //Priority priority + //Organizer(Sender) "ORGANIZER:MAILTO:" + this.state.sender + '\r\n' + //Attendee RSVP + //Resources resource + //Ending Event 'END:VEVENT\r\n' + //Ending Calendar 'END:VCALENDAR\r\n'); if (!formError) { element.setAttribute('download', this.state.eventName + ".ics"); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); this.setState({ eventName: "", eventLocation: "", start: "", end: "", eventDescription: "", repeat: "No Repeat", class: "PUBLIC", priority: "9", error: [], RSVP: false, toRSVP: "", arrRSVP: [], GEO: "", sender: "", resources: [], resource: '', emailError: false, dateException: "", arrDate: [], arrMonths: [], }); } else { console.log("error"); this.setState({error: errorMessages}); } }; handleChange = (e) => { this.setState({[e.target.name]: e.target.value}); }; handlePlaceChange = (place) => { this.setState({ eventLocation: place.formatted_address, GEO: `${place.geometry.location.lat()};${place.geometry.location.lng()}` }); } showRSVP = () => { this.setState({RSVP: !this.state.RSVP}); } handleRSVP = () => { //email checking let email = /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(.\w{2,3})+$/.test(this.state.toRSVP); if (email && this.state.arrRSVP.indexOf(this.state.toRSVP) === -1) { let arr = this.state.arrRSVP; arr.push(this.state.toRSVP); this.setState({arrRSVP: arr, toRSVP: '', emailError: false}); } else if (email === false) { this.setState({emailError: true}); } else { this.setState({toRSVP: '', emailError: false}); } } handleResources = () => { if (this.state.resources.indexOf(this.state.resource) === -1 && this.state.resource !== "") { let arr = this.state.resources; arr.push(this.state.resource); this.setState({resources: arr, resource: ''}); } else { this.setState({resource: ''}); } console.log(this.state.resources); } handleDateExceptions = () => { if (this.state.arrDate.indexOf(this.state.dateException) === -1 && this.state.dateException !== "") { let arr = this.state.arrDate; arr.push(this.state.dateException); this.setState({arrDate: arr, dateException: ''}); } else { this.setState({dateException: ''}); } } handleRemove = (value) => { let index = this.state.arrRSVP.indexOf(value); let arr = this.state.arrRSVP.slice(); arr.splice(index, 1); this.setState({arrRSVP: arr}); console.log(index, arr); } handleResourceRemove = (value) => { let index = this.state.resources.indexOf(value); let arr = this.state.resources.slice(); arr.splice(index, 1); this.setState({resources: arr}); } handleDateRemove = (value) => { let index = this.state.arrDate.indexOf(value); let arr = this.state.arrDate.slice(); arr.splice(index, 1); this.setState({arrDate: arr}); } initAutocomplete = () => { // Create the search box and link it to the UI element. const input = document.getElementById("pac-input"); const searchBox = new window.google.maps.places.Autocomplete(input); // Listen for the event fired when the user selects a prediction and retrieve // more details for that place. searchBox.addListener("place_changed", () => { const place = searchBox.getPlace(); this.handlePlaceChange(place) }); } handleEnter = (event) => { if (event.which === 13) { event.preventDefault(); if (event.target.name === 'resource') { this.handleResources(); } else if (event.target.name === 'toRSVP') { this.handleRSVP(); } } } render() { return ( <div className="App"> <Menu size="huge" inverted> <Grid style={{margin: "3px 0px 2px 0px"}}> <Grid.Row> <Grid.Column> <Header as="h1" textAlign="center" style={{color: "white"}}><Icon name="calendar alternate" color="blue"/> Kalendae</Header> </Grid.Column> </Grid.Row> </Grid> </Menu> <Grid container stretched> <Grid.Column> <Header as="h2" textAlign="center" className='white'>Add an Event!</Header> <Segment> <Form style={{padding: "5px 30px 10px 30px"}} onSubmit={this.submit} error> <Form.Input style={{paddingBottom: "30px"}} required fluid name='eventName' value={this.state.eventName} label='Event Name' placeholder='Ex. New Year Party' onChange={this.handleChange}/> <Divider style={{backgroundColor: "paleturquoise"}}/> <Form.Group widths='equal' style={{paddingBottom: "30px"}}> <Form.Input id="pac-input" required name='eventLocation' value={this.state.eventLocation} label='Location' placeholder='Ex. 1234 Foo St. Honolulu, HI 96821' onChange={this.handleChange} /> <Form.Input required name='start' value={this.state.start} label='Start Date' type='datetime-local' onChange={this.handleChange}/> <Form.Input required name='end' value={this.state.end} label='End Date' type='datetime-local' onChange={this.handleChange}/> </Form.Group> <Divider style={{backgroundColor: "paleturquoise"}}/> <Form.Group style={{paddingBottom: "30px"}}> <Form.Select name='repeat' value={this.state.repeat} label='Repeat' options={this.state.repeatOptions} onChange={ (e, {value}) => { this.setState({repeat: value}); } } /> {this.state.repeat !== 'No Repeat' ? <Form.Select multiple name='monthException' label='Month Exception' options={this.state.months} onChange={ (e, {value}) => { this.setState({arrMonths: value}); } } /> : ""} </Form.Group> {this.state.repeat !== 'No Repeat' ? <Form.Group style={{paddingBottom: "30px"}}> <Form.Input action={ <Button type="button" onClick={this.handleDateExceptions} icon> <Icon color="green" name="add"/> </Button>} type='date' value={this.state.dateException} name='dateException' label='Date Exceptions' onChange={this.handleChange} onKeyDown={this.handleEnter}/> <Grid container> <Grid.Row centered verticalAlign="middle" style={{padding: "0 0 0 0"}}> <Grid.Column> <Header as='h5' textAlign="center" style={{height: "15px"}}>Date Exceptions List</Header> </Grid.Column> </Grid.Row> <Grid.Row id="date-exception" stretched> <List ordered horizontal> {this.state.arrDate.map((value) => <List.Item key={value}> {value} <Button style={{backgroundColor: 'transparent'}} type='button' size='tiny' value={value} onClick={() => this.handleDateRemove(value)} icon circular> <Icon color='red' name='close'/> </Button> </List.Item>)} </List> </Grid.Row> </Grid> </Form.Group> : "" } <Divider style={{backgroundColor: "paleturquoise"}}/> <Form.Group widths='equal' style={{paddingBottom: "30px"}}> <Form.Select name='classification' value={this.state.class} label='Classification' options={this.state.classOptions} onChange={ (e, {value}) => { this.setState({class: value}); } } /> <Form.Select name='priority' value={this.state.priority} label='Priority' options={this.state.priorityOptions} onChange={ (e, {value}) => { this.setState({priority: value}); } } /> </Form.Group> <Divider style={{backgroundColor: "paleturquoise"}}/> <Form.Group style={{paddingBottom: "30px"}}> <Form.Input action={ <Button type="button" onClick={this.handleResources} icon> <Icon color="green" name="add"/> </Button>} type='text' value={this.state.resource} name='resource' label='Resources' placeholder='Ex. Projector, Camera, etc.' onChange={this.handleChange} onKeyDown={this.handleEnter}/> <Grid container> <Grid.Row centered verticalAlign="middle" style={{padding: "0 0 0 0"}}> <Grid.Column> <Header as='h5' textAlign="center" style={{height: "15px"}}>Resource List</Header> </Grid.Column> </Grid.Row> <Grid.Row id="resource" stretched> <List ordered horizontal> {this.state.resources.map((value) => <List.Item key={value}> {value} <Button style={{backgroundColor: 'transparent'}} type='button' size='tiny' value={value} onClick={() => this.handleResourceRemove(value)} icon circular> <Icon color='red' name='close'/> </Button> </List.Item>)} </List> </Grid.Row> </Grid> </Form.Group> <Divider style={{backgroundColor: "paleturquoise"}}/> <Form.Group> <Form.Radio name='RSVP' label='RSVP' toggle onChange={this.showRSVP}/> </Form.Group> <Form.Group style={{paddingBottom: "40px"}}> {this.state.RSVP === true && this.state.emailError === false ? <Form.Input id="toRSVP" action={ <Button type="button" onClick={this.handleRSVP} icon> <Icon color="green" name="add"/> </Button>} type='email' value={this.state.toRSVP} multiple name='toRSVP' label='RSVP To' placeholder='Ex. <EMAIL>' onChange={this.handleChange} onKeyDown={this.handleEnter}/> : (this.state.emailError && this.state.RSVP) ? <Form.Input id="toRSVP" error={{ content: 'Please enter a valid email', pointing: 'below' }} action={ <Button type="button" onClick={this.handleRSVP} icon> <Icon color="green" name="add"/> </Button>} type='email' value={this.state.toRSVP} multiple name='toRSVP' label='RSVP To' placeholder='Ex. <EMAIL>' onChange={this.handleChange} onKeyDown={this.handleEnter}/> : ""} {this.state.RSVP === true ? <Form.Input required type='email' value={this.state.sender} name='sender' label='Organizer Email' placeholder='Ex. <EMAIL>' onChange={this.handleChange}/> : ""} {this.state.RSVP === true ? ( <Grid container> <Grid.Row centered verticalAlign="middle" style={{padding: "0 0 0 0"}}> <Grid.Column> <Header as='h5' textAlign="center" style={{height: "15px"}}>Attendee List</Header> </Grid.Column> </Grid.Row> <Grid.Row id='attendee' stretched> <List ordered horizontal> {this.state.arrRSVP.map((value) => <List.Item key={value}> {value} <Button style={{backgroundColor: 'transparent'}} type='button' size='tiny' value={value} onClick={() => this.handleRemove(value)} icon circular> <Icon color='red' name='close'/> </Button> </List.Item>)} </List> </Grid.Row> </Grid> ) : ""} </Form.Group> <Divider style={{backgroundColor: "paleturquoise"}}/> <Form.Input name='eventDescription' value={this.state.eventDescription} control={TextArea} label='Event Description' placeholder='Ex. New Year Party' onChange={this.handleChange}/> <Form.Button color="green" icon labelPosition='right'>Submit/Download<Icon name="download"/></Form.Button> {this.state.error.length !== 0 ? <Message error header='Action Forbidden' list={this.state.error} /> : ""} </Form> </Segment> </Grid.Column> </Grid> </div> ); } } export default App;
c0142e636edc6334f06344de3057d6776fdb581e
[ "JavaScript" ]
1
JavaScript
team-emm-too/kalendae
f6e0947c893592dd311d9b318c3f7b64f187bfa3
1186ab5bc97db3dfff405e994dc465e2d548c5f2
refs/heads/master
<repo_name>Korben3/liskland<file_sep>/liskland.js //liskland by lisk delegate: korben3 // //config variables var network="test"; // main or test var maxObjects=25; // max number of transactions checked for objects var liskAddress="112233444L"; // lisk address used to receive the transactions //setup $("#maxObjects").html(maxObjects); if(network=="test"){var networkClient=lisk.APIClient.createTestnetAPIClient();}else{var networkClient=lisk.APIClient.createMainnetAPIClient();} $("#liskAddress").html(liskAddress); var timestamp=0; var qu=String.fromCharCode(34); //" //functions function loadObjects(){ console.log(timestamp); networkClient.transactions.get({"recipientId":liskAddress,"limit":maxObjects,"offset":0,"sort":"timestamp:desc"}) .then(res => { console.log(res.data[0].timestamp); if (timestamp!=(res.data[0].timestamp)){ $(".liskland").html("") //new objects detected, reset field "Incoming object!" timestamp=res.data[0].timestamp; var objectNum=0; for (var i=0; i<res.data.length; i++) { try { var data=JSON.parse(res.data[i].asset.data); }catch(e){ var tmp="{"+qu+"liskland"+qu+":{"+qu+"object"+qu+":"+qu+"ufo01"+qu+","+qu+"move"+qu+":"+qu+"left"+qu+"}}"; data=JSON.parse(tmp); //bad json, show ufo } objectNum++; objectSender=res.data[i].senderId; getDelegateName(objectNum,res.data[i].senderId); var img=data.liskland.object; if(data.liskland.move){ //place moving object if(data.liskland.move=="left"){img+="rl";}else{img+="lr";} img="images/"+img+".png"; $(".liskland").append("<div id='object"+objectNum+"' class='objects'><img src='"+img+"' onerror='noObject(this)'><div class='delegate' id='objectDelId"+objectNum+"'>"+objectSender+"</div></div>"); if(data.liskland.move=="left"){ $("#object"+objectNum).addClass("objectrlClass"); $("#object"+objectNum).css("animation-delay",Math.floor((Math.random()*9)+1)+"s"); //randomize a bit to prevent overlap $("#object"+objectNum).css("animation-duration",Math.floor((Math.random()*20)+20)+"s"); $("#object"+objectNum).css("transform","translate(-300px,170px)"); }else{ $("#object"+objectNum).addClass("objectlrClass"); $("#object"+objectNum).css("animation-delay",Math.floor((Math.random()*9)+1)+"s"); $("#object"+objectNum).css("animation-duration",Math.floor((Math.random()*20)+20)+"s"); $("#object"+objectNum).css("transform","translate(0px,170px)"); } }else{ //place fixed object img="images/"+img+".png"; var xpos=data.liskland.x; if(xpos>4000 || xpos<0){xpos=Math.floor(Math.random()*4000);} //if an incorrect x value is given place it at a rnd valid position $(".liskland").append("<div id='object"+objectNum+"' class='objects'><img src='"+img+"' onerror='noObject(this)'><div class='delegate' id='objectDelId"+objectNum+"'>"+objectSender+"</div></div>"); $("#object"+objectNum).css("transform","translate("+xpos+"px,170px)"); } } } }) } //incorrect object/image show ufo function noObject(image){ image.onerror = ""; image.src="images/ufo01.png"; return(true) }; function placeRefCode(object,canMove){ if(canMove){ var direction=$("#dir").val(); if(direction!="left" && direction!="right"){direction="left";} var newRefCode="{"+qu+"liskland"+qu+":{"+qu+"object"+qu+":"+qu+object+qu+","+qu+"move"+qu+":"+qu+direction+qu+"}}"; }else{ var xValue=$("#x-pos").val(); if(xValue>4000 || xValue<0){xValue=1875;} var newRefCode="{"+qu+"liskland"+qu+":{"+qu+"object"+qu+":"+qu+object+qu+","+qu+"x"+qu+":"+xValue+"}}"; } $("#refCode").html(newRefCode); } // no need to wait for all api calls for possible delegate names, we'll just start the show and fill in the names later function getDelegateName(id, senderId){ networkClient.delegates.get({"address":senderId,"limit":1}) .then(res2 => { try{objectSender=res2.data[0].username}catch(e){objectSender=senderId}; $("#objectDelId"+id).html(objectSender); }).catch(console.error); }; $("#menuButton").click(function(){ $(".menuFull").toggle(); }); $(".menuImage").click( function(){ console.log(this.className); if(this.className.split(" ")[1]=="canMove"){ $("#objectFixed").hide(); $("#objectMoving").show(); placeRefCode(this.title,true); }else{ $("#objectFixed").show(); $("#objectMoving").hide(); placeRefCode(this.title,false); } }); //fill in the x position for static objects by clicking on the playfield $(document).click( function (event) { if(event.pageY>220 && $("#objectFixed").css("display")!="none"){ var x = event.pageX; $("#x-pos").val(x); placeRefCode((JSON.parse($("#refCode").html()).liskland.object),false); } }); $("#x-pos").change( function(){ placeRefCode((JSON.parse($("#refCode").html()).liskland.object),false); }); $("#dir").change( function(){ placeRefCode((JSON.parse($("#refCode").html()).liskland.object),true); }); $("#sendButton").click( function(){ window.location.assign("lisk://wallet?recipient="+liskAddress+"&amount=0.01&reference="+$("#refCode").html()); }); //run loadObjects(); //check for new objects - liskland is (a)live setInterval(loadObjects,10000); <file_sep>/README.md # liskland Liskland allows users to add objects to a website using the reference code in a lisk transaction. Liskland checks the latest x number of transactions from a certain address each 10 seconds. If a transactions has a valid json code in the data field, the script reads the code to retrieve the object and the position. It then places the object on the board and repeats this process. Build in javascript using lisk elements.
1492519cfbcb012fc5eff296f0f668ba5845fe7d
[ "JavaScript", "Markdown" ]
2
JavaScript
Korben3/liskland
f705db8298e4c958ab86c7deb53f081a728f24bf
3b0f0badab4c219b95172f45d061944317a43ee5
refs/heads/master
<file_sep>i = 4 d = 4.0 s = 'HackerRank ' val=int(input()) val1=float(input()) s1=input() value=i+val print(value) value1=d+val1 print(value1) stri=s+s1 print(stri)<file_sep># 30DaysOfCodePython These are my solutions for 30 Days of code on HackerRank. I have solved these using Python. Feel free to use the code in your solutions or your projects. <file_sep>#Stub code: import math import os import random import re import sys #Solution begins here: if __name__ == '__main__': n = int(input()) count = 0 maxi = 0 while n > 0: if n % 2 == 1: count += 1 else: if count > maxi: maxi = count count = 0 n=math.floor(n / 2) if count > maxi: maxi = count print(maxi) <file_sep>numberOfEntries = int(input()) addressBook = {} for entry in range(numberOfEntries): inputFromUser = list(map(str,input().split())) addressBook[inputFromUser[0]] = inputFromUser[1] inputs = [] while True: try: inp = input() inputs.append(inp) except: break for name in inputs: if name in addressBook: print(name + "="+ str(addressBook[name])) else: print("Not found") <file_sep>#Stub code: import math import os import random import re import sys #Solution begins here: def solve(meal_cost, tip_percent, tax_percent): tip_cost = (meal_cost * tip_percent)/100 tax_cost = (meal_cost * tax_percent)/100 total_cost = meal_cost + tip_cost + tax_cost print(round(total_cost)) #Stub code: if __name__ == '__main__': meal_cost = float(input()) tip_percent = int(input()) tax_percent = int(input()) solve(meal_cost, tip_percent, tax_percent) <file_sep>#Stub code: import math import os import random import re import sys #Solution begins here: def hourGlass(mat,n): max = -99999999999999999 for i in range(n-2): for j in range(n-2): sum = mat[i][j] + mat[i][j+1] + mat[i][j+2] + mat[i+1][j+1] + mat[i+2][j] + mat[i+2][j+1] + mat[i+2][j+2] if sum > max: max = sum return max #Stub code: if __name__ == '__main__': arr = [] for _ in range(6): arr.append(list(map(int, input().rstrip().split(' ')))) print(hourGlass(arr,6)) <file_sep>#Stub code: import math import os import random import re import sys #Solution begins here: if __name__ == '__main__': n = int(input()) for i in range(1,11): prod = n * i print(n,'x',i,'=',prod) <file_sep>#Stub code: import math import os import random import re import sys #Solution begins here: if __name__ == '__main__': n = int(input()) arr = list(map(int, input().rstrip().split())) reversed_array = arr[::-1] output_string = '' for i in range(len(reversed_array)): output_string+= str(reversed_array[i]) + ' ' print(output_string)
3da8092853cf6e911ad40c70f832a384074f40b2
[ "Markdown", "Python" ]
8
Python
hayagreevvaradarajan/30DaysOfCodeUsingPython
5908b246bcd56f1dfdd0998a01e2b975028d0a6e
e1a40cd8502dd26f5f8f79eb15646bd7ff7f5cc4
refs/heads/master
<repo_name>JefeNovato044/ObjectsExamples<file_sep>/EjemplosObjetos.js var Animal = { philo: "Perro", nombre:"Mishu" , edad: 50, saludar : function (){ console.log("Hola soy un " + this.philo + " que habla," + " y mi nombre es " + this.nombre); } } class Sujeto { //Constructor de objeto constructor (nombre, edad, personalidad, altura){ this.nombre = nombre; this.edad = edad; this.personalidad = personalidad; this.altura = altura; } //Metodo de objeto presentarse (){ console.log("Hola soy " + this.nombre + " tengo " + this.edad + " aรฑos, mido " + this.altura + " metros y mi personalidad es del tipo " + this.personalidad + "."); return 0; } } //Una clase hijo de Sujeto class Mujer extends Sujeto{ constructor(nombre, edad, personalidad, altura,colorFalda){ super(nombre, edad, personalidad, altura) //Heredar variables de objeto padre. this.colorFalda = colorFalda; } presentarse(){ console.log("Hola soy " + this.nombre + " tengo " + this.edad + " aรฑos, mido " + this.altura + " metros y mi personalidad es del tipo " + this.personalidad + " y mi falda es " + this.colorFalda + "."); } } //Modificar los parametros del objeto Animal.philo = "Gato"; //Llamar al metodo saludar del objeto animal Animal.saludar(); Animal.atacar = function (){ //Agregar un nuevo metodo al objeto console.log("Soy un " + this.philo + " y te voa a tacar"); } Animal.atacar(); //Crear un nuevo objeto con el constructor NPC1 = new Sujeto("Jefe", 24, "INTP", 2.14); NPC1.presentarse(); NPC2 = new Mujer("Gorriรณn", 24, "INTP", 2.00,"azul") NPC2.presentarse();
3cbed34e90a5b4c91517f3809198bcd0b6eb37fd
[ "JavaScript" ]
1
JavaScript
JefeNovato044/ObjectsExamples
c9b1d3d23fdcf9113ee3dcef20af032af711e6b1
7c24fc0df0cf8aff9ea390fdd199233064143c89
refs/heads/master
<file_sep># sid ## Description: The sid script provide an easy way to install an email service using vimbadmin to manage user and a nextcloud instance. ## Usage: Just run the script ```sid.sh``` and provide the differents informations ``` ./sid.sh ``` If you want to re-run the script, you need to delete the following files: - .env - docker-compose.yml - nginx.conf ## Email service: The email service contain: - SMTP using posfix (port 25, 587) - POP/IMAP using dovecot (port 110, 143, 993, 995) - SIEVE filter using dovecot (port 4190) - antispam and antivirus using amavis - DKIM using opendkin - Users and domains management using vimbadmin ## Nextcloud: The nexcloud service come with basic configuration but the image provide all the dependencies list in the documentation, so feel free to extend the configuration to match your needs ## Nginx: The nginx web server is configure for the vimbadmin and nextcloud services, feel free to extend the configuration if you want to add some services ## docker-compose.yml: The docker-compose.yml contain the images to run the email service and the nextcloud instance, feel free to extend it if you want to add some services ## SSL certificates: The SSL certificates are create with Let's Encrypt when you run the script ```sid.sh``` ## ATTENTION: - The script does not check the validity of the user input - The docker-compose.yml file generate by the script have the following specification: * a custom network using the subnet 172.18.0.0/16 * the mail image have the IP 172.18.0.10 * all the logs are redirect to the syslog of the host server ## Documentations: - [nextcloud image](https://github.com/aknaebel/docker-nextcloud) - [mail image](https://github.com/aknaebel/docker-mail) - [amavis image](https://github.com/aknaebel/docker-amavis) - [vimbadmin image](https://github.com/aknaebel/docker-vimbadmin) - [opendkim image](https://github.com/aknaebel/docker-opendkim) <file_sep>#!/bin/bash if [ -f nginx.conf || -f docker-compose.yml || -f .env ]; then echo "ERROR: a config file found in the current directory" echo "Unable to rerun the install script" exit0 fi echo "General informations" read -p "Enter domain name (default: example.com): " domain domain=${domain:-example.com} read -p "Enter an admin email adress (default: admin@$domain): " global_admin_email global_admin_email=${global_admin_email:-admin@$domain} read -p "Enter the root password for mariadb: " dbpassword dbpassword=${dbpassword:-""} echo "Vimbadmin configuration" read -p "Enter the vimbadmin password for the sql user: " vimbadmin_sql_password vimbadmin_sql_password=${vimbadmin_sql_password:-""} read -p "Enter the vimbadmin admin email (default: admin@$domain): " vimbadmin_admin_email vimbadmin_admin_email=${vimbadmin_admin_email:-"admin@$domain"} read -p "Enter the vimbadmin admin password: " <PASSWORD>_<PASSWORD> vimdadmin_admin_password=${vimdadmin_admin_password:-""} echo "Nextcloud configuration" echo "Do you wish to configure nextcloud? [Yes/No]" select yn in "Yes" "No"; do case $yn in Yes ) nextcloud_db_type="mysql" nexrcloud_db_name="nextcloud" nextcloud_db_user="nextcloud" nextcloud_db_host="mariadb" read -p "Enter the nextcloud password for the sql user: " nextcloud_sql_password nextcloud_sql_password=${nextcloud_sql_password:-""} read -p "Enter the nextcloud admin username (default: admin): " nextcloud_admin_user nextcloud_admin_user=${nextcloud_admin_user:-"admin"} read -p "Enter the nextcloud admin password: " nextcloud_admin_password nextcloud_admin_password=${nextcloud_admin_password:-""} read -P "Enter trust domain to grant access to the interface (default: localhost): " nextcloud_trusted_domain nextcloud_trusted_domain=${nextcloud_trusted_domain:-localhost} break;; No ) echo "Configuring nextcloud with default value" nextcloud_db_type="sqlite3" nexrcloud_db_name="nextcloud" nextcloud_db_user="nextcloud" nextcloud_sql_password="<PASSWORD>" nextcloud_db_host="mariadb" nextcloud_admin_user="admin" nextcloud_admin_password="<PASSWORD>" nextcloud_trusted_domain="localhost" break;; esac done cat > .env << EOF; ######## # mail # ######## ADMIN_EMAIL=$vimbadmin_admin_email ADMIN_PASSWORD=$<PASSWORD> VIMBADMIN_PASSWORD=$<PASSWORD> DBHOST=mariadb MEMCACHE_HOST=memcached HOSTNAME=mail.$hostname DOMAIN=$domain SMTP_HOST=mail SSL_KEY_PATH=/etc/letsencrypt/live/##HOSTNAME##/privkey.pem SSL_CERT_PATH=/etc/letsencrypt/live/##HOSTNAME##/fullchain.pem ############# # nextcloud # ############# ADMIN_USER=$nextcloud_admin_user ADMIN_PASSWORD=$<PASSWORD> DB_TYPE=$nextcloud_db_type DB_NAME=$nexrcloud_db_name DB_USER=$nextcloud_db_user DB_PASSWORD=$<PASSWORD> DB_HOST=$nextcloud_db_host TRUSTED_DOMAIN=$nextcloud_trusted_domain EOF cat > initdb.sql << EOF; CREATE USER 'nextcloud'@'%' IDENTIFIED BY '$nextcloud_sql_password'; CREATE DATABASE IF NOT EXISTS nextcloud; GRANT ALL ON nextcloud.* TO 'nextcloud'@'%'; FLUSH PRIVILEGES ; CREATE USER 'vimbadmin'@'%' IDENTIFIED BY '$vimbadmin_sql_password'; CREATE DATABASE IF NOT EXISTS vimbadmin; GRANT ALL ON vimbadmin.* TO 'vimbadmin'@'%'; FLUSH PRIVILEGES ; EOF cp docker-compose.yml.tpl docker-compose.yml sed -i "s/##dbpassword##/$dbpassword/" docker-compose.yml cp nginx.conf.tpl nginx.conf sed -i "s/##domain##/$domain/g" nginx.conf echo "Generating DH parameters, please wait" openssl dhparam -out dhparams.pem 2048 echo "Generating Let's Encrypt certificate, please wait" echo "Let's encrypt use port 80 and 443 to validate certificates, be sure theses port are available" cert_path=$(pwd) docker run -it --rm -p 443:443 -p 80:80 --name letsencrypt \ -v $cert_path/LE/etc/letsencrypt:/etc/letsencrypt \ -v $cert_path/LE/var/lib/letsencrypt:/var/lib/letsencrypt \ quay.io/letsencrypt/letsencrypt:latest certonly --standalone --expand -n -m $global_admin_email --agree-tos \ -d mail.$domain -d owncloud.$domain -d vimbadmin.$domain echo "SUMMARY:" echo "https://owncloud.$domain --> nextcloud service" if [ $nextcloud_db_type == "sqlite3" ];then echo "admin --> admin user login for nextcloud" echo "password --> admin user password for nextcloud" fi echo "https://vimbadmin.$domain --> vimbadmin service" echo "mail.$domain --> service mail (smtp, pop and imap"
5201951171ebb210550980deab78b0f82e9bf025
[ "Markdown", "Shell" ]
2
Markdown
aknaebel/sid
8496cafec202f746b740fab8bd9eeee62adf8e09
c3ea689e5691c6a3cc1da3bb9f82316106b74c18
refs/heads/master
<file_sep>package org.firstinspires.ftc.teamcode; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cColorSensor; import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cRangeSensor; import com.qualcomm.robotcore.util.Range; import com.qualcomm.robotcore.hardware.*; import org.firstinspires.ftc.robotcore.external.Telemetry; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import java.util.*; public class Bot { static DcMotor BL, BR, FL, FR, ARM; HardwareMap map; Telemetry tele; static Servo lClaw, rClaw, colorServo; static BNO055IMU gyro; BNO055IMU.Parameters parameters; Orientation angles; Double powerModifier = 0.02; ModernRoboticsI2cColorSensor colorSensor; public Bot() {} public void init(HardwareMap map, Telemetry tele, boolean auton){ this.map = map; this.tele = tele; BL = this.map.get(DcMotor.class, "BL"); BR = this.map.get(DcMotor.class, "BR"); FL = this.map.get(DcMotor.class, "FL"); FR = this.map.get(DcMotor.class, "FR"); ARM = this.map.get(DcMotor.class, "ARM"); colorSensor = this.map.get(ModernRoboticsI2cColorSensor.class, "colorSensor"); colorSensor.enableLed(true); if(auton) runToPosition(); else runToEncoder(); ARM.setMode(DcMotor.RunMode.RUN_USING_ENCODER); lClaw = map.servo.get("lClaw"); rClaw = map.servo.get("rClaw"); colorServo = map.servo.get("colorServo"); // colorServo = map.servo.get("colorServo"); ARM.setDirection(DcMotorSimple.Direction.FORWARD); BR.setDirection(DcMotorSimple.Direction.FORWARD); BL.setDirection(DcMotorSimple.Direction.FORWARD); FL.setDirection(DcMotorSimple.Direction.FORWARD); FR.setDirection(DcMotorSimple.Direction.FORWARD); FR.setPower(0); BL.setPower(0); FL.setPower(0); FR.setPower(0); ARM.setPower(0); BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC; parameters.calibrationDataFile = "BNO055IMUCalibration.json"; gyro = map.get(BNO055IMU.class, "gyro"); gyro.initialize(parameters); tele.addData(">","Gyro Calibrating. Do Not move!"); tele.update(); } public void runToPosition(){ BL.setMode(DcMotor.RunMode.RUN_TO_POSITION); BR.setMode(DcMotor.RunMode.RUN_TO_POSITION); FL.setMode(DcMotor.RunMode.RUN_TO_POSITION); FR.setMode(DcMotor.RunMode.RUN_TO_POSITION); } public void runToEncoder(){ BL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); BR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); FL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); FR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } public void drive(double y, double x, double r) { double bl = - y - x + r; double br = y - x + r; double fr = -y + x + r; double fl = y + x + r; BL.setPower(bl); BR.setPower(br); FR.setPower(fr); FL.setPower(fl); } public void turn(double in){ BL.setPower(in); BR.setPower(in); FL.setPower(in); FR.setPower(in); } public void armUp(double in){ ARM.setPower(in); } public void armDown(double in){ ARM.setPower(-in); } public void openClaw(){ lClaw.setPosition(0.6); rClaw.setPosition(0.4); } public void closeClaw(){ lClaw.setPosition(1.0); rClaw.setPosition(0.0); } public void addServo(double add) { rClaw.setPosition(rClaw.getPosition() + add); lClaw.setPosition(lClaw.getPosition() + add); } public void decreaseServo(double sub) { rClaw.setPosition(rClaw.getPosition() - sub); lClaw.setPosition(lClaw.getPosition() - sub); } // public void resetColor(){ // colorServo.setPosition(0.0); // } public void strafe(double in){ BR.setPower(-in); FR.setPower(in); BL.setPower(-in); FL.setPower(in); } public void resetEncoders(){ BL.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); BR.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); FL.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); FR.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); runToPosition(); } public void setToPosition(int position){ BL.setTargetPosition(position); BR.setTargetPosition(-position); FL.setTargetPosition(-position); FR.setTargetPosition(position); } /* public void fieldCentricDrive(double lStickX, double lStickY, double rStickX) { // Get the controller values double forward = (-1)*lStickY; double right = lStickX; double clockwise = rStickX; double temp; double k; // Apply the turn modifier k clockwise *= k; // Turn the output heading value to be based on counterclockwise turns angles = gyro.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); if (angles.firstAngle < 0) { angles.firstAngle += 360; } // Convert to Radians for Math.sin/cos angles.firstAngle = (float)(angles.firstAngle * (Math.PI / 180)); // Do Math temp = forward * Math.cos(angles.firstAngle) - right * Math.sin(angles.firstAngle); right = forward * Math.sin(angles.firstAngle) + right * Math.cos(angles.firstAngle); forward = temp; // Set power values using Math frontLeft = forward + clockwise + right; frontRight = forward - clockwise - right; rearLeft = forward + clockwise - right; rearRight = forward - clockwise + right; // Clip power values to within acceptable ranges for the motors frontLeft = Range.clip(frontLeft, -1.0, 1.0); frontRight = Range.clip(frontRight, -1.0, 1.0); rearLeft = Range.clip(rearLeft, -1.0, 1.0); rearRight = Range.clip(rearRight, -1.0, 1.0); // Send power values to motors FL.setPower(frontLeft); BL.setPower(rearLeft); FR.setPower(frontRight); BR.setPower(rearRight); } */ public boolean adjustHeading(int targetHeading) { double curHeading = gyro.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle; if (Math.abs(Math.abs(targetHeading) - Math.abs(curHeading)) < .5) { FL.setPower(0); BL.setPower(0); FR.setPower(0); BR.setPower(0); return true; } double headingError; if (targetHeading == 0) { headingError = curHeading < 0 ? targetHeading + curHeading : Math.abs(targetHeading + curHeading); } else headingError = targetHeading + curHeading; double driveScale = headingError * powerModifier; if (Math.abs(driveScale) < .06) { driveScale = .06 * (driveScale < 0 ? -1 : 1); } Range.clip(driveScale, -1, 1); turn(driveScale); return false; } public void testServos(Telemetry tele){ tele.addData("Claw: ", lClaw.getPosition()); tele.update(); } public void testMotor(Telemetry tele){ tele.addData("Motor: ", FL.getCurrentPosition()); tele.update(); } public void upColor(){ colorServo.setPosition(0.0); } public void downColor(){ colorServo.setPosition(1.0); } public boolean isRed(){ return colorSensor.red() >= 2; } public int getMotorPosition(){ return Math.max(BR.getCurrentPosition(),Math.max(BL.getCurrentPosition(),Math.max(FL.getCurrentPosition(),FR.getCurrentPosition()))); } public int getTargetPosition() { return FL.getTargetPosition();} }
46f27b483af2019224ae241927b552b1d24ce0b3
[ "Java" ]
1
Java
Dwight-Englewood/13048-Relic-Recovery
67af99224b6b9499bbc8fd295aefe7767ba663ea
cdb0648101fd82be04fd016387a87dea8886afd6
refs/heads/master
<file_sep>var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var centerX = canvas.width / 2; var centerY = canvas.height / 2; function drawCircle(x,y) { context.beginPath(); var MULT = 2.5; var rad = 4; context.arc(MULT*x + centerX, MULT*y + centerY, rad, 0, 2 * Math.PI, false); context.fillStyle = 'white'; context.fill(); } function drawPattern(){ context.clearRect(0, 0, canvas.width, canvas.height); var num_circles = document.getElementById("num_circles").valueAsNumber; var dist_circles = document.getElementById("dist_circles").valueAsNumber; var init_circle_dots = document.getElementById("init_circle_dots").valueAsNumber; var mult_dots = document.getElementById("mult_circles").valueAsNumber; var fullGCode ="G28 \n"; // Homing printer fullGCode += "G92 E0 \n"; // Reset extruder // Loop over number of circles var radius = dist_circles; // Radius of the current circle var dots_num = init_circle_dots; for (var loop_circle = 0; loop_circle < num_circles; loop_circle++) { // Loop over number of dots per circle for (var loop_dots = 0; loop_dots < dots_num; loop_dots++) { // Current dot angle var dot_angle_rad = ((2*Math.PI)/Math.round(dots_num)) * loop_dots; var x = radius * Math.cos(dot_angle_rad); var y = radius * Math.sin(dot_angle_rad); drawCircle(x,y); } radius += dist_circles; // double radius after each circle dots_num *= mult_dots; } } function initCircleDot(){ var classname = document.getElementsByClassName("inputs"); // Global variable within scopin function // Function that fills all the inputs var input_change = function() { drawPattern(); }; // Add event listener to all inputs for (var i = 0; i < classname.length; i++) { classname[i].addEventListener('click', input_change, false); } input_change(); } function buildGCode() { var num_circles = document.getElementById("num_circles").valueAsNumber; var dist_circles = document.getElementById("dist_circles").valueAsNumber; var init_circle_dots = document.getElementById("init_circle_dots").valueAsNumber; var mult_dots = document.getElementById("mult_circles").valueAsNumber; var start_height = document.getElementById("start_height").valueAsNumber; var speed = document.getElementById("speed").valueAsNumber; var e_speed = document.getElementById("e_speed").valueAsNumber; var extrusion = document.getElementById("extrusion").valueAsNumber; var retraction = document.getElementById("retraction").valueAsNumber; var fullGCode ="G28 \n"; // Homing printer fullGCode += "G92 E0 \n"; // Reset extruder // Loop over number of circles var radius = dist_circles; // Radius of the current circle var dots_num = init_circle_dots; var total_extrusion = 0; for (var loop_circle = 0; loop_circle < num_circles; loop_circle++) { // Loop over number of dots per circle for (var loop_dots = 0; loop_dots < dots_num; loop_dots++) { //console.log("loop dots = " + loop_dots); // Current dot angle var dot_angle_rad = ((2*Math.PI)/dots_num) * loop_dots; var x = radius * Math.cos(dot_angle_rad); var y = radius * Math.sin(dot_angle_rad); //console.log("x = " + x); //console.log("y = " + y); fullGCode += "G1 X" + Math.round(x*100)/100 + " Y" + Math.round(y*100)/100 + " Z" + Math.round(start_height*100)/100 + " F"+ speed + "\n"; // Extrusion calculation total_extrusion = total_extrusion + extrusion + retraction; fullGCode += "G1 E" + Math.round(total_extrusion*100)/100 + " F" + e_speed + "\n"; // Add dot extrusion // Dot retraction total_extrusion -= retraction; fullGCode += "G1 E" + Math.round(total_extrusion*100)/100 + " F" + e_speed + "\n"; fullGCode += "G1 Z" + 2*start_height + " F"+ speed + "\n"; } radius += dist_circles; // double radius after each circle dots_num *= mult_dots; dots_num = dots_num; } fullGCode += "G28 \n"; // Initial height and print speed return fullGCode; } function createFile(){ var output = getParameters(); output += buildGCode(); //console.log(output); var GCodeFile = new Blob([output], {type: 'text/plain'}); saveAs(GCodeFile, "Circle" + '.gcode'); } function getParameters(){ var params = []; params += "; GCode generated with Circle dots from www.3digitalcooks.com \n"; params += "; Number of circles [mm]: " + document.getElementById("num_circles").value + "\n"; params += "; Distance between circles [mm]: " + document.getElementById("dist_circles").value + "\n"; params += "; Init circle number of dots [mm]: " + document.getElementById("init_circle_dots").value + "\n"; params += "; Dots multiplier [mm]: " + document.getElementById("mult_circles").value + "\n"; params += "; Start height [mm]: " + document.getElementById("start_height").value + "\n"; params += "; Speed [s]: " + document.getElementById("speed").value + "\n"; params += "; Extruder speed [s]: " + document.getElementById("e_speed").value + "\n"; params += "; Extrusion [mm]: " + document.getElementById("extrusion").value + "\n"; params += "; Retraction [mm]: " + document.getElementById("retraction").value + "\n"; return params; } initCircleDot();<file_sep># CircleDots Food design app to make dotted circles. Checkout some examples at: https://www.instagram.com/3digitalcooks/
7d71c20f7e0d20d5469b70ab931c50f1d1742eb9
[ "JavaScript", "Markdown" ]
2
JavaScript
LasVegasOle/CircleDots
95d16e8b8099fb2a44f147d13215be2ca66932d6
5f4e184a89e7310fa90b271d66c4c21745de3604
refs/heads/master
<file_sep>package server_side; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class MySerialServer implements Server { private ServerSocket listener = null; private boolean _run = true; public void start(int port, ClientHandler c) { try { this.listener = new ServerSocket(port); } catch (IOException e) { e.printStackTrace(); return; } System.out.println("Serial-Server started listening..."); Runnable runnable = () -> { while(this._run) { try { this.listener.setSoTimeout(10000); Socket s = this.listener.accept(); System.out.println("Connection established."); c.handleClient(s.getInputStream(), s.getOutputStream()); } catch (IOException | NullPointerException e) { e.printStackTrace(); } } }; Thread thread = new Thread(runnable); thread.start(); } public void stop() { this._run = false; try { this.listener.close(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>package test; import server_side.*; import java.util.List; public class TestSetter { static Server s; public static void runServer(int port) { // put the code here that runs your server CacheManager cm = new FileCacheManager(); Searcher<Pair<Integer,Integer>> searcher = new BestFirstSearch<>(); Solver<Searchable<Pair<Integer, Integer>>, List<State<Pair<Integer, Integer>>>> solver = new SearcherAdapter<>(searcher); ClientHandler c1 = new MyClientHandler(solver, cm); s = new MySerialServer(); s.start(port, c1); } public static void stopServer() { s.stop(); } }
b951068e549ff3a1d5d687764e91600c4cd30951
[ "Java" ]
2
Java
barakoo121/PTM
f239011d384012cdf42ee433bf73cb0fb6872532
d154560b0bec450b37eef806ebbcf43e9298c277
refs/heads/master
<repo_name>priyankacheema/eTuition<file_sep>/RegisterTut.aspx.cs ๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; public partial class RegisterTut : System.Web.UI.Page { SqlConnection con; protected void Page_Load(object sender, EventArgs e) { con = new SqlConnection("Data Source=sandeep-pc\\priyanka;Initial Catalog=Priyanka;Integrated Security=True"); } protected void btnRegister_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=sandeep-pc\\priyanka;Initial Catalog=Priyanka;Integrated Security=True"); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "insert into eTutor(FName,LName,EmailId,Password,Gender,Age,MotherTongue,Address,City,State,ContactNo,Qualification1,Qualification2,Subject,Experience)values('" + txtFName.Text + "','" + txtLName.Text + "','" + txtEmail.Text + "','" + txtPasswrd.Text + "','" + RadioButtonList1.SelectedItem.Text + "'," + txtAge.Text + ",'" + txtMotherTng.Text + "','" + txtAddr.Text + "','" + DropDnCity.SelectedItem.Text + "','" + DropDnState.SelectedItem.Text + "'," + txtContact.Text + ",'" + DropDnQual.SelectedItem.Text + "','" + txtQual.Text + "','" + txtSub.Text + "'," + txtExp.Text + ")"; cmd.Connection = con; con.Open(); int ok = cmd.ExecuteNonQuery(); if (ok > 0) { Label19.ForeColor = System.Drawing.Color.DeepPink; Label19.Text = "Registration Successful"; Clear(); } else { Label19.ForeColor = System.Drawing.Color.DeepPink; Label19.Text = "Registration Failed"; } con.Close(); } private void Clear() { txtFName.Text = ""; txtLName.Text = ""; txtEmail.Text = ""; txtPasswrd.Text = ""; txtAge.Text = ""; txtMotherTng.Text = ""; txtAddr.Text = ""; txtContact.Text = ""; txtQual.Text = ""; txtSub.Text = ""; txtExp.Text = ""; } }<file_sep>/StuViewSPapers.aspx.cs ๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Text; using System.Data.SqlClient; using System.Data; public partial class StuViewPapers : System.Web.UI.Page { string query; SqlConnection con; SqlCommand com; string strCon = "Data Source=sandeep-pc\\priyanka;Initial Catalog=Priyanka;Integrated Security=True"; protected void Page_Load(object sender, EventArgs e) { con = new SqlConnection("Data Source=sandeep-pc\\priyanka;Initial Catalog=Priyanka;Integrated Security=True"); con.Open(); query = "Select *from TutSPaper"; SqlDataAdapter da = new SqlDataAdapter(query, con); DataSet ds = new DataSet(); da.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); con.Close(); } //This button click event is used to download files from gridview protected void lnkDownload_Click(object sender, EventArgs e) { LinkButton lnkbtn = sender as LinkButton; GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow; int fileid = Convert.ToInt32(GridView1.DataKeys[gvrow.RowIndex].Value.ToString()); //string name, type; using (SqlConnection con = new SqlConnection(strCon)) { using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "select FileName, FileType, FileData from TutSPaper where Id=@Id"; cmd.Parameters.AddWithValue("@id", fileid); cmd.Connection = con; con.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { Response.ContentType = dr["FileType"].ToString(); Response.AddHeader("Content-Disposition", "attachment;filename=\"" + dr["FileName"] + "\""); Response.BinaryWrite((byte[])dr["FileData"]); Response.End(); } } } } }<file_sep>/RegisterStu.aspx.cs ๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; public partial class RegisterStu : System.Web.UI.Page { SqlConnection con; protected void Page_Load(object sender, EventArgs e) { con = new SqlConnection("Data Source=sandeep-pc\\priyanka;Initial Catalog=Priyanka;Integrated Security=True"); } protected void Button3_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=sandeep-pc\\priyanka;Initial Catalog=Priyanka;Integrated Security=True"); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "insert into Student(FName,LName,EmailId,Password,Gender,Age,ParentName,Address,City,State,ContactNo,Class,Subject1,Subject2,Subject3)values('" + txtFName.Text + "','" + txtLName.Text + "','" + txtEmail.Text + "','" + txtPasswrd.Text + "','" + RadioButtonList1.SelectedItem.Text + "'," + txtAge.Text + ",'" + txtParent.Text + "','" + txtAddress.Text + "','" + DropDnCity.SelectedItem.Text + "','" + DropDnState.SelectedItem.Text + "'," + txtContact.Text + "," + txtClass.Text + ",'" + txtSub1.Text + "','" + txtSub2.Text + "','" + txtSub3.Text + "')"; cmd.Connection = con; con.Open(); int ok = cmd.ExecuteNonQuery(); if (ok > 0) { Label19.ForeColor = System.Drawing.Color.DeepPink; Label19.Text = "Registration Successful"; Clear(); } else { Label19.ForeColor = System.Drawing.Color.DeepPink; Label19.Text = "Registration Failed"; } con.Close(); } private void Clear() { txtFName.Text = ""; txtLName.Text = ""; txtEmail.Text = ""; txtPasswrd.Text = ""; txtAge.Text = ""; txtParent.Text = ""; txtAddress.Text = ""; txtContact.Text = ""; txtClass.Text = ""; txtSub1.Text = ""; txtSub2.Text = ""; txtSub3.Text = ""; } }
280898fa3318483025c0227c0f7257603c9f0076
[ "C#" ]
3
C#
priyankacheema/eTuition
80411321e5cb6619573c8621029a28436a97fce9
57b8b857dea3b9b600e6b745e6bb2f99beb52b5e
refs/heads/master
<file_sep>import sys entrada=open(sys.argv[1],"r") salida=open(sys.argv[2],"w") print (sys.argv) for line in entrada: if "1" in line[0]: salida.write(line) salida.close() entrada.close() <file_sep># python-mcnp
cebed80169656a4b276f41453d13b68c6bfd227c
[ "Markdown", "Python" ]
2
Python
PabloSartorio/python-mcnp
0722bf84e0ea03b55a4150a9c40698a922989237
9bd6011bed793feda818c4c5cbb3036741a80839
refs/heads/master
<repo_name>nalakas/carbon-commons-1<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/registry/RegistryManager.java /* * Copyright 2005-2007 WSO2, Inc. (http://wso2.com) * * 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 org.wso2.carbon.logging.service.registry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.Appender; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.FileAppender; import org.apache.log4j.Layout; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.net.SyslogAppender; import org.wso2.carbon.core.RegistryResources; import org.wso2.carbon.core.util.CryptoException; import org.wso2.carbon.core.util.CryptoUtil; import org.wso2.carbon.utils.logging.CircularBuffer; import org.wso2.carbon.logging.service.appender.CarbonMemoryAppender; import org.wso2.carbon.logging.service.config.SyslogConfigManager; import org.wso2.carbon.logging.service.config.SyslogConfiguration; import org.wso2.carbon.logging.service.data.SyslogData; import org.wso2.carbon.logging.service.util.LoggingConstants; import org.wso2.carbon.registry.core.Collection; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.utils.ServerConstants; import java.io.File; import java.io.IOException; public class RegistryManager { private static Log log = LogFactory.getLog(RegistryManager.class); private static Registry registry; public static void setRegistry(Registry registryParam) { registry = registryParam; } public String getConfigurationProperty(String propertyName) throws RegistryException { String resourcePath = RegistryResources.LOGGING + propertyName; String value = null; if (registry.resourceExists(resourcePath)) { Resource resource = registry.get(resourcePath); value = resource.getProperty(propertyName); } return value; } public void updateConfigurationProperty(String propertyName, String value) throws RegistryException { if (propertyName == null || value == null) { return; } String resourcePath = RegistryResources.LOGGING + propertyName; Resource resource; if (!registry.resourceExists(resourcePath)) { resource = registry.newResource(); resource.addProperty(propertyName, value); registry.put(resourcePath, resource); } else { resource = registry.get(resourcePath); String existingValue = resource.getProperty(propertyName); if (!(existingValue != null && existingValue.equals(value))) { resource.setProperty(propertyName, value); registry.put(resourcePath, resource); } } } /** * when getting loggers from getCurrentLoggers method it will return all the * loggers in the system. this includes loggers we have initialized using * getLogger methods. but these loggers does not have a log level set they * get the log level from the parent loggers. but to store in registry we * use only loggers with a log level * <p/> * Store the provided Log4J Logger in the Registry * * @param logger The Log4J Logger to be stored in the registry */ public void addLogger(Logger logger) throws Exception { try { registry.beginTransaction(); Resource loggerResource = registry.newResource(); loggerResource.addProperty(LoggingConstants.LoggerProperties.NAME, logger.getName()); loggerResource.addProperty( LoggingConstants.LoggerProperties.LOG_LEVEL, logger .getEffectiveLevel().toString()); loggerResource.addProperty( LoggingConstants.LoggerProperties.ADDITIVITY, Boolean.toString(logger.getAdditivity())); registry.put(LoggingConstants.LOGGERS + logger.getName(), loggerResource); registry.commitTransaction(); } catch (Exception e) { registry.rollbackTransaction(); log.error("Unable to add the logger", e); throw e; } } public Resource getLogger(String loggerName) throws Exception { String loggerResourcePath = LoggingConstants.LOGGERS + loggerName; if (registry.resourceExists(loggerResourcePath)) { return registry.get(loggerResourcePath); } return null; } public Collection getLoggers() throws Exception { if (registry.resourceExists(LoggingConstants.LOGGERS)) { return (Collection) registry.get(LoggingConstants.LOGGERS); } return null; } public void updateLogger(String loggerName, String loggerLevel, boolean aditivity) throws Exception { try { registry.beginTransaction(); Resource loggerResource; String loggerResourcePath = LoggingConstants.LOGGERS + loggerName; if (registry.resourceExists(loggerResourcePath)) { loggerResource = registry.get(loggerResourcePath); loggerResource.setProperty( LoggingConstants.LoggerProperties.LOG_LEVEL, loggerLevel); loggerResource.setProperty( LoggingConstants.LoggerProperties.ADDITIVITY, Boolean.toString(aditivity)); registry.put(loggerResourcePath, loggerResource); } else { loggerResource = registry.newResource(); loggerResource.addProperty( LoggingConstants.LoggerProperties.NAME, loggerName); loggerResource.addProperty( LoggingConstants.LoggerProperties.LOG_LEVEL, loggerLevel); loggerResource.addProperty( LoggingConstants.LoggerProperties.ADDITIVITY, Boolean.toString(aditivity)); registry.put(loggerResourcePath, loggerResource); } registry.commitTransaction(); } catch (Exception e) { registry.rollbackTransaction(); log.error("Unable to update the logger", e); throw e; } } private String encriptSyslogPassword(String password) throws CryptoException { return CryptoUtil.getDefaultCryptoUtil().encryptAndBase64Encode( password.getBytes()); } private String decriptPassword(String encriptedPassword) throws CryptoException, IOException { return new String(CryptoUtil.getDefaultCryptoUtil() .base64DecodeAndDecrypt(encriptedPassword)); } public void addSyslogConfig(SyslogData syslogData) throws Exception { try { registry.beginTransaction(); Resource syslogResource = registry.newResource(); syslogResource.addProperty( LoggingConstants.SyslogProperties.LOG_INDEX_URL, syslogData.getUrl()); syslogResource.addProperty( LoggingConstants.SyslogProperties.SYSLOG_PORT, syslogData.getPort()); syslogResource.addProperty(LoggingConstants.SyslogProperties.REALM, syslogData.getRealm()); syslogResource.addProperty( LoggingConstants.SyslogProperties.USER_NAME, syslogData.getUserName()); syslogResource.addProperty( LoggingConstants.SyslogProperties.PASSWORD, encriptSyslogPassword(syslogData.getPassword())); registry.put(LoggingConstants.SYSLOG, syslogResource); registry.commitTransaction(); } catch (RegistryException e) { registry.rollbackTransaction(); log.error("Cannot add syslog properties ", e); throw e; } } /** * Store the provided Log4J Appender in the Registry * * @param appender Log4J Appender to be stored in the registry */ public void addAppender(Appender appender) throws Exception { try { registry.beginTransaction(); Resource appenderResource = registry.newResource(); if (appender.requiresLayout()) { Layout layout = appender.getLayout(); if (layout instanceof PatternLayout) { appenderResource.addProperty( LoggingConstants.AppenderProperties.PATTERN, ((PatternLayout) layout).getConversionPattern()); } } if (appender instanceof FileAppender) { FileAppender fileAppender = (FileAppender) appender; String fileName = fileAppender.getFile(); File logFile = new File(fileName); if (!logFile.isAbsolute()) { if (fileName.startsWith(".")) { fileName = fileName.substring(1); } fileName = (System.getProperty(ServerConstants.CARBON_HOME) + "/" + fileName).replace('\\', '/'); fileAppender.setFile(fileName); fileAppender.activateOptions(); } appenderResource.addProperty( LoggingConstants.AppenderProperties.LOG_FILE_NAME, fileName); appenderResource.addProperty( LoggingConstants.AppenderProperties.IS_FILE_APPENDER, Boolean.toString(true)); } else { appenderResource.addProperty( LoggingConstants.AppenderProperties.IS_FILE_APPENDER, Boolean.toString(false)); } if (appender instanceof CarbonMemoryAppender) { CarbonMemoryAppender memoryAppender = (CarbonMemoryAppender) appender; memoryAppender.setCircularBuffer(new CircularBuffer( LoggingConstants.MEMORY_APPENDER_BUFFER_SZ)); memoryAppender.activateOptions(); } // normally all the appenders inherit from AppenderSkelton if (appender instanceof AppenderSkeleton) { AppenderSkeleton appenderSkeleton = (AppenderSkeleton) appender; if (appenderSkeleton.getThreshold() != null) { appenderResource.addProperty( LoggingConstants.AppenderProperties.THRESHOLD, appenderSkeleton.getThreshold().toString()); } else { appenderResource.addProperty( LoggingConstants.AppenderProperties.THRESHOLD, "DEBUG"); } } if (appender instanceof SyslogAppender) { SyslogAppender syslogAppender = (SyslogAppender) appender; // if user has not set these properties system automatically // assign default values appenderResource.addProperty( LoggingConstants.AppenderProperties.SYS_LOG_HOST, syslogAppender.getSyslogHost()); appenderResource.addProperty( LoggingConstants.AppenderProperties.FACILITY, syslogAppender.getFacility()); appenderResource .addProperty( LoggingConstants.AppenderProperties.IS_SYS_LOG_APPENDER, Boolean.toString(true)); } else { appenderResource .addProperty( LoggingConstants.AppenderProperties.IS_SYS_LOG_APPENDER, Boolean.toString(false)); } registry.put(LoggingConstants.APPENDERS + appender.getName(), appenderResource); registry.commitTransaction(); } catch (Exception e) { registry.rollbackTransaction(); log.error("Cannot add appender", e); throw e; } } public void updateCassandraConfig(String url, String keyspace, String columnFamily, String userName, String password) throws Exception { String cassandraResourcePath = LoggingConstants.CASSANDRA; try { if (registry.resourceExists(cassandraResourcePath)) { try { registry.beginTransaction(); Resource appenderResource = registry .get(cassandraResourcePath); appenderResource.setProperty( LoggingConstants.CassandraProperties.URL, url); appenderResource.setProperty( LoggingConstants.CassandraProperties.KEYSPACE, keyspace); appenderResource.setProperty( LoggingConstants.CassandraProperties.COLUMN_FAMILY, columnFamily); appenderResource.setProperty( LoggingConstants.CassandraProperties.USER_NAME, userName); appenderResource.setProperty( LoggingConstants.CassandraProperties.PASSWORD, encriptSyslogPassword(password)); registry.put(LoggingConstants.CASSANDRA, appenderResource); registry.commitTransaction(); } catch (RegistryException e) { registry.rollbackTransaction(); log.error("Unable to update the appender", e); throw e; } } } catch (RegistryException e) { log.error("Unable to update the appender", e); throw e; } } /** * this method is used to update syslog properties in the registry if syslog * property is not available a new resource is added to the registry along * with the syslog properties * * @param url - syslog logs location * @param port - port * @param realm - realm * @param userName - syslog server authentic user name * @param password - syslog server authentic password * @throws Exception */ public void updateSyslogConfig(String url, String port, String realm, String userName, String password) throws Exception { String syslogResourcePath = LoggingConstants.SYSLOG; try { if (registry.resourceExists(syslogResourcePath)) { try { registry.beginTransaction(); Resource appenderResource = registry .get(syslogResourcePath); appenderResource.setProperty( LoggingConstants.SyslogProperties.LOG_INDEX_URL, url); appenderResource .setProperty( LoggingConstants.SyslogProperties.SYSLOG_PORT, port); appenderResource.setProperty( LoggingConstants.SyslogProperties.REALM, realm); appenderResource.setProperty( LoggingConstants.SyslogProperties.USER_NAME, userName); appenderResource.setProperty( LoggingConstants.SyslogProperties.PASSWORD, encriptSyslogPassword(password)); registry.put(LoggingConstants.SYSLOG, appenderResource); registry.commitTransaction(); } catch (RegistryException e) { registry.rollbackTransaction(); log.error("Unable to update the appender", e); throw e; } } else { SyslogData syslogData = new SyslogData(url, port, realm, userName, password); addSyslogConfig(syslogData); } } catch (RegistryException e) { log.error("Unable to update the appender", e); throw e; } } public SyslogData getSyslogData() throws Exception { Resource syslogConfigResource; try { syslogConfigResource = getSyslogConfig(); String url = ""; String port = ""; String realm = ""; String userName = ""; String password = ""; if (syslogConfigResource != null) { // Check if the properties are // coming from the registry. url = syslogConfigResource .getProperty(LoggingConstants.SyslogProperties.LOG_INDEX_URL); port = syslogConfigResource .getProperty(LoggingConstants.SyslogProperties.SYSLOG_PORT); realm = syslogConfigResource .getProperty(LoggingConstants.SyslogProperties.REALM); userName = syslogConfigResource .getProperty(LoggingConstants.SyslogProperties.USER_NAME); password = <PASSWORD>(syslogConfigResource .getProperty(LoggingConstants.SyslogProperties.PASSWORD)); } else { // read syslog properties from the syslog-config.xml SyslogConfiguration config = SyslogConfigManager .loadSyslogConfiguration(); url = config.getSyslogHostURL(); port = config.getPort(); realm = config.getRealm(); userName = config.getUserName(); password = <PASSWORD>(); } return new SyslogData(url, port, realm, userName, password); } catch (Exception e) { log.error("Unable get SyslogData ", e); throw e; } } /** * @return Registry resource of syslog property file. * @throws Exception */ public Resource getSyslogConfig() throws Exception { String syslogResourcePath = LoggingConstants.SYSLOG; if (registry.resourceExists(syslogResourcePath)) { return registry.get(syslogResourcePath); } return null; } public Resource getCassandraConfig() throws Exception { String cassandraResourcePath = LoggingConstants.CASSANDRA; if (registry.resourceExists(cassandraResourcePath)) { return registry.get(cassandraResourcePath); } return null; } public void updateAppender(Appender appender, String appenderName, String appenderPattern, String threshold, String logFileName, String sysLogHost, String facility, boolean isFileAppender, boolean isSysLogAppender) throws Exception { String appenderResourcePath = LoggingConstants.APPENDERS + appenderName; if (registry.resourceExists(appenderResourcePath)) { try { registry.beginTransaction(); Resource appenderResource = registry.get(appenderResourcePath); appenderResource.setProperty( LoggingConstants.AppenderProperties.PATTERN, appenderPattern); if (isFileAppender) { appenderResource.setProperty( LoggingConstants.AppenderProperties.LOG_FILE_NAME, logFileName); appenderResource .setProperty( LoggingConstants.AppenderProperties.IS_FILE_APPENDER, Boolean.toString(true)); } if (isSysLogAppender) { appenderResource.setProperty( LoggingConstants.AppenderProperties.SYS_LOG_HOST, sysLogHost); appenderResource.setProperty( LoggingConstants.AppenderProperties.FACILITY, facility); appenderResource .setProperty( LoggingConstants.AppenderProperties.IS_SYS_LOG_APPENDER, Boolean.toString(true)); } appenderResource.setProperty( LoggingConstants.AppenderProperties.THRESHOLD, threshold); registry.put(LoggingConstants.APPENDERS + appenderName, appenderResource); registry.commitTransaction(); } catch (Exception e) { registry.rollbackTransaction(); log.error("Unable to update the appender", e); throw e; } } else { if (log.isDebugEnabled()) { log.debug("appender " + appenderName + " is not available, therefore adding to registry"); } addAppender(appender); updateAppender(appender, appenderName, appenderPattern, threshold, logFileName, sysLogHost, facility, isFileAppender, isSysLogAppender); } } public Resource getAppender(String appenderName) throws Exception { String appenderResourcePath = LoggingConstants.APPENDERS + appenderName; if (registry.resourceExists(appenderResourcePath)) { return registry.get(appenderResourcePath); } return null; } public Collection getAppenders() throws Exception { if (registry.resourceExists(LoggingConstants.APPENDERS)) { return (Collection) registry.get(LoggingConstants.APPENDERS); } return null; } /** * method is used to check current appender is a syslog appender. * * @return isSyslogAppender * @throws RegistryException */ public boolean isSysLogAppender() throws RegistryException { boolean isSyslogAppender = false; String appenderResourcePath = LoggingConstants.APPENDERS + LoggingConstants.WSO2CARBON_SYS_LOG_APPENDER; if (registry.resourceExists(appenderResourcePath)) { Resource appenderResource = registry.get(appenderResourcePath); isSyslogAppender = Boolean .parseBoolean(appenderResource .getProperty(LoggingConstants.AppenderProperties.IS_SYS_LOG_APPENDER)); } return isSyslogAppender; } public void removeAllRegistryEntries() throws Exception { try { registry.beginTransaction(); if (registry.resourceExists(LoggingConstants.LOGGERS)) { registry.delete(LoggingConstants.LOGGERS); } if (registry.resourceExists(LoggingConstants.APPENDERS)) { registry.delete(LoggingConstants.APPENDERS); } if (registry.resourceExists(RegistryResources.LOGGING + LoggingConstants.SYSTEM_LOG_PATTERN)) { registry.delete(RegistryResources.LOGGING + LoggingConstants.SYSTEM_LOG_PATTERN); } if (registry.resourceExists(RegistryResources.LOGGING + LoggingConstants.SYSTEM_LOG_LEVEL)) { registry.delete(RegistryResources.LOGGING + LoggingConstants.SYSTEM_LOG_LEVEL); } registry.commitTransaction(); } catch (Exception e) { registry.rollbackTransaction(); log.error("Unable to remove all the loggers and appenders", e); throw e; } } } <file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/data/LoggingConfig.java /* * Copyright The Apache Software Foundation. * * 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 org.wso2.carbon.logging.service.data; import java.util.HashMap; import java.util.Map; public class LoggingConfig { private String logProviderImplClassName; private String logFileProviderImplClassName; private Map<String, String> logProviderPropMap = new HashMap<String, String>(); private Map<String, String> logFileProviderPropMap = new HashMap<String, String>(); public LoggingConfig() { } public void setLogProviderProperty(String key, String value) { this.logProviderPropMap.put(key, value); } public void setLogFileProviderProperty(String key, String value) { this.logFileProviderPropMap.put(key, value); } public String getLogProviderProperty(String key) { return this.logProviderPropMap.get(key); } public String getLogFileProviderProperty(String key) { return this.logFileProviderPropMap.get(key); } public String getLogProviderImplClassName() { return logProviderImplClassName; } public void setLogProviderImplClassName(String logProviderImplClassName) { if (logProviderImplClassName == null | logProviderImplClassName.equals("")) { throw new IllegalArgumentException("LogProvider implementation class name should not be null or empty"); } this.logProviderImplClassName = logProviderImplClassName; } public String getLogFileProviderImplClassName() { return logFileProviderImplClassName; } public void setLogFileProviderImplClassName(String logFileProviderImplClassName) { if (logFileProviderImplClassName == null | logFileProviderImplClassName.equals("")) { throw new IllegalArgumentException("LogProvider implementation class name should not be null or empty"); } this.logFileProviderImplClassName = logFileProviderImplClassName; } } <file_sep>/components/deployment-synchronizer/org.wso2.carbon.deployment.synchronizer.git/src/main/java/org/wso2/carbon/deployment/synchronizer/git/GitDeploymentSynchronizerComponent.java package org.wso2.carbon.deployment.synchronizer.git; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.deployment.synchronizer.ArtifactRepository; /** * @scr.component name="org.wso2.carbon.deployment.synchronizer.git" immediate="true" */ public class GitDeploymentSynchronizerComponent { private static final Log log = LogFactory.getLog(GitDeploymentSynchronizerComponent.class); private ServiceRegistration gitDepSyncServiceRegistration; /** * Activate Git Deployment Synchronizer Component * * @param context ComponentContext instance to access osgi runtime */ protected void activate(ComponentContext context) { ArtifactRepository gitBasedArtifactRepository = new GitBasedArtifactRepository(); gitDepSyncServiceRegistration = context.getBundleContext().registerService(ArtifactRepository.class.getName(), gitBasedArtifactRepository, null); /*ServerConfiguration serverConf = ServerConfiguration.getInstance(); String depSyncEnabledParam = serverConf.getFirstProperty(GitDeploymentSynchronizerConstants.ENABLED); //Check if deployment synchronization is enabled if (depSyncEnabledParam != null && depSyncEnabledParam.equals("true")) { //check if repository type is 'git', else no need to create GitBasedArtifactRepository instance String repoTypeParam = serverConf.getFirstProperty(GitDeploymentSynchronizerConstants.REPOSITORY_TYPE); if (repoTypeParam != null && repoTypeParam.equals(DeploymentSynchronizerConstants.REPOSITORY_TYPE_GIT)) { ArtifactRepository gitBasedArtifactRepository = new GitBasedArtifactRepository(); gitDepSyncServiceRegistration = context.getBundleContext().registerService(ArtifactRepository.class.getName(), gitBasedArtifactRepository, null); } else { if(log.isDebugEnabled()) { log.debug("Git deployment synchronization disabled, GitBasedArtifactRepository instance not created"); } } } else { if(log.isDebugEnabled()) { log.debug("Deployment synchronization disabled, GitBasedArtifactRepository instance not created"); } }*/ if(log.isDebugEnabled()) { log.debug("Git based deployment synchronizer component activated"); } } /** * De-activate Git Deployment Synchronizer Component * * @param context ComponentContext instance to access osgi runtime */ protected void deactivate(ComponentContext context) { if(gitDepSyncServiceRegistration != null){ gitDepSyncServiceRegistration.unregister(); gitDepSyncServiceRegistration = null; } if(log.isDebugEnabled()) { log.debug("Git based deployment synchronizer component deactivated"); } } } <file_sep>/components/deployment-synchronizer/org.wso2.carbon.deployment.synchronizer.subversion/src/main/java/org/wso2/carbon/deployment/synchronizer/subversion/SVNDeploymentSynchronizerComponent.java /* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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 org.wso2.carbon.deployment.synchronizer.subversion; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.ComponentContext; import org.tigris.subversion.svnclientadapter.commandline.CmdLineClientAdapterFactory; import org.tigris.subversion.svnclientadapter.javahl.JhlClientAdapterFactory; import org.tigris.subversion.svnclientadapter.svnkit.SvnKitClientAdapterFactory; import org.wso2.carbon.deployment.synchronizer.ArtifactRepository; import org.wso2.carbon.deployment.synchronizer.subversion.util.SVNDataHolder; import org.wso2.carbon.tomcat.api.CarbonTomcatService; /** * @scr.component name="org.wso2.carbon.deployment.synchronizer.subversion" immediate="true" * @scr.reference name="carbon.tomcat.service" * interface="org.wso2.carbon.tomcat.api.CarbonTomcatService" * cardinality="0..1" policy="dynamic" bind="setCarbonTomcatService" * unbind="unsetCarbonTomcatService" */ public class SVNDeploymentSynchronizerComponent { private static final Log log = LogFactory.getLog(SVNDeploymentSynchronizerComponent.class); private ServiceRegistration svnDepSyncServiceRegistration; protected void activate(ComponentContext context) { boolean allClientsFailed = true; try { SvnKitClientAdapterFactory.setup(); allClientsFailed = false; log.debug("SVN Kit client adapter initialized"); } catch (Throwable t) { log.debug("Unable to initialize the SVN Kit client adapter - Required jars " + "may be missing"); } try { JhlClientAdapterFactory.setup(); allClientsFailed = false; log.debug("Java HL client adapter initialized"); } catch (Throwable t) { log.debug("Unable to initialize the Java HL client adapter - Required jars " + " or the native libraries may be missing"); } try { CmdLineClientAdapterFactory.setup(); allClientsFailed = false; log.debug("Command line client adapter initialized"); } catch (Throwable t) { log.debug("Unable to initialize the command line client adapter - SVN command " + "line tools may be missing"); } if(allClientsFailed){ String error = "Could not initialize any of the SVN client adapters - " + "Required jars/libraries may be missing"; log.debug(error); return; } ArtifactRepository svnBasedArtifactRepository = new SVNBasedArtifactRepository(); svnDepSyncServiceRegistration = context.getBundleContext().registerService(ArtifactRepository.class.getName(), svnBasedArtifactRepository, null); log.debug("SVN based deployment synchronizer component activated"); } protected void deactivate(ComponentContext context) { if(svnDepSyncServiceRegistration != null){ svnDepSyncServiceRegistration.unregister(); svnDepSyncServiceRegistration = null; } log.debug("SVN based deployment synchronizer component deactivated"); } protected void setCarbonTomcatService(CarbonTomcatService carbonTomcatService) { SVNDataHolder.getInstance().setCarbonTomcatService(carbonTomcatService); } protected void unsetCarbonTomcatService(CarbonTomcatService carbonTomcatService) { SVNDataHolder.getInstance().setCarbonTomcatService(null); } } <file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/sync/LoggingConfigSyncRequest.java /* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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 org.wso2.carbon.logging.service.sync; import org.apache.axis2.clustering.ClusteringCommand; import org.apache.axis2.clustering.ClusteringFault; import org.apache.axis2.clustering.ClusteringMessage; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.logging.service.util.LoggingUtil; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; /** * Cluster message to be sent when logging configurations are modified. */ public class LoggingConfigSyncRequest extends ClusteringMessage { private static final Log log = LogFactory.getLog(LoggingConfigSyncRequest.class); private static final long serialVersionUID = -689482772914112325L; public LoggingConfigSyncRequest() { } @Override public void execute(ConfigurationContext configurationContext) throws ClusteringFault { if (log.isDebugEnabled()) { log.debug("Received [" + this + "] "); } try { // load the configuration from registry as ST PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); LoggingUtil.loadCustomConfiguration(); } catch (Exception e) { log.error("Cannot load logging configuration from the registry", e); } finally { PrivilegedCarbonContext.endTenantFlow(); } } @Override public ClusteringCommand getResponse() { return null; } @Override public String toString() { return "LoggingConfigSyncRequest{" + "messageId=" + getUuid() + "}"; } } <file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/data/PaginatedLogEvent.java /* * Copyright 2005,2014 WSO2, Inc. http://www.wso2.org * 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 org.wso2.carbon.logging.service.data; import org.wso2.carbon.utils.Pageable; import java.util.List; public class PaginatedLogEvent implements Pageable { private LogEvent[] logEvt; private int numberOfPages; public int getNumberOfPages() { return numberOfPages; } public void setNumberOfPages(int numberOfPages) { this.numberOfPages = numberOfPages; } public LogEvent[] getLogInfo() { return logEvt; } public void setLogInfo(LogEvent[] logEvt) { this.logEvt = logEvt; } public <T> void set(List<T> items) { this.logEvt = items.toArray(new LogEvent[items.size()]); } } <file_sep>/components/deployment-synchronizer/org.wso2.carbon.deployment.synchronizer/src/main/java/org/wso2/carbon/deployment/synchronizer/internal/DeploymentSynchronizerComponent.java /* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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 org.wso2.carbon.deployment.synchronizer.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.deployment.synchronizer.ArtifactRepository; import org.wso2.carbon.deployment.synchronizer.DeploymentSynchronizationManager; import org.wso2.carbon.deployment.synchronizer.DeploymentSynchronizerException; import org.wso2.carbon.deployment.synchronizer.repository.CarbonRepositoryUtils; import org.wso2.carbon.deployment.synchronizer.services.DeploymentSynchronizerService; import org.wso2.carbon.deployment.synchronizer.internal.util.RepositoryReferenceHolder; import org.wso2.carbon.deployment.synchronizer.internal.util.ServiceReferenceHolder; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.utils.Axis2ConfigurationContextObserver; import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.registry.core.service.RegistryService; /** * @scr.component name="org.wso2.carbon.deployment.synchronizer.XXX" immediate="true" * @scr.reference name="configuration.context.service" * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1" * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService" * @scr.reference name="repository.reference.service" * interface="org.wso2.carbon.deployment.synchronizer.ArtifactRepository" cardinality="0..n" * policy="dynamic" bind="addArtifactRepository" unbind="removeArtifactRepository" * @scr.reference name="registry.service" immediate="true" * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="1..1" * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService" */ public class DeploymentSynchronizerComponent { private static final Log log = LogFactory.getLog(DeploymentSynchronizerComponent.class); private ServiceRegistration observerRegistration; protected void activate(ComponentContext context) { try { // Initialize the repository manager so that it can be later used to // start a synchronizer (eg: via the UI) ServerConfiguration serverConfig = ServerConfiguration.getInstance(); DeploymentSynchronizationManager.getInstance().init(serverConfig); try { initDeploymentSynchronizerForSuperTenant(); } catch (DeploymentSynchronizerException e) { log.error("Error while initializing a deployment synchronizer for the super tenant " + "Carbon repository", e); } // Register an observer so we can track tenant ConfigurationContext creation and // do the synchronization operations as necessary BundleContext bundleContext = context.getBundleContext(); observerRegistration = bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), new DeploymentSyncAxis2ConfigurationContextObserver(), null); // register the OSGi service bundleContext.registerService(new String[]{DeploymentSynchronizerService.class.getName(), org.wso2.carbon.core.deployment.DeploymentSynchronizer.class.getName()}, new DeploymentSynchronizerServiceImpl(), null); log.debug("Deployment synchronizer component activated"); } catch (Throwable e) { log.info("Error activating Deployment Synchronizer component. " + e.getMessage(), e); } } private void initDeploymentSynchronizerForSuperTenant() throws DeploymentSynchronizerException { if (!CarbonRepositoryUtils.isSynchronizerEnabled(MultitenantConstants.SUPER_TENANT_ID)) { return; } if (log.isDebugEnabled()) { log.debug("Initializing the deployment synchronizer for super tenant"); } CarbonRepositoryUtils.newCarbonRepositorySynchronizer(MultitenantConstants.SUPER_TENANT_ID); } protected void deactivate(ComponentContext context) { DeploymentSynchronizationManager.getInstance().shutdown(); if (observerRegistration != null) { observerRegistration.unregister(); observerRegistration = null; } log.debug("Deployment synchronizer component deactivated"); } protected void setConfigurationContextService(ConfigurationContextService service) { if (log.isDebugEnabled()) { log.debug("Deployment synchronizer component bound to the " + "configuration context service"); } ServiceReferenceHolder.setConfigurationContextService(service); } protected void unsetConfigurationContextService(ConfigurationContextService service) { if (log.isDebugEnabled()) { log.debug("Deployment synchronizer component unbound from the " + "configuration context service"); } ServiceReferenceHolder.setConfigurationContextService(null); } protected void addArtifactRepository(ArtifactRepository artifactRepository){ RepositoryReferenceHolder repositoryReferenceHolder = RepositoryReferenceHolder.getInstance(); repositoryReferenceHolder.addRepository(artifactRepository, artifactRepository.getParameters()); } protected void removeArtifactRepository(ArtifactRepository artifactRepository){ RepositoryReferenceHolder repositoryReferenceHolder = RepositoryReferenceHolder.getInstance(); repositoryReferenceHolder.removeRepository(artifactRepository); } protected void setRegistryService(RegistryService service) { if (log.isDebugEnabled()) { log.debug("Deployment synchronizer component bound to the registry service"); } ServiceReferenceHolder.setRegistryService(service); } protected void unsetRegistryService(RegistryService service) { if (log.isDebugEnabled()) { log.debug("Deployment synchronizer component unbound from the registry service"); } ServiceReferenceHolder.setRegistryService(null); } } <file_sep>/components/logging/org.wso2.carbon.logging.summarizer/src/main/java/org/wso2/carbon/logging/summarizer/scriptCreator/QueryGenerator.java package org.wso2.carbon.logging.summarizer.scriptCreator; /* * Copyright 2005,2006 WSO2, Inc. http://www.wso2.org * * 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. */ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.logging.summarizer.core.SummarizerException; import org.wso2.carbon.logging.summarizer.utils.LoggingConfig; import org.wso2.carbon.logging.summarizer.utils.LoggingConfigManager; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class QueryGenerator { private static final Log log = LogFactory.getLog(QueryGenerator.class); LoggingConfig config = LoggingConfigManager.loadLoggingConfiguration(); String keyspaceName = config.getKeyspace(); String archivedLogLocation = config.getArchivedLogLocation(); public List<String> createFilePaths() throws SummarizerException { ColumnFamilyHandler cfHandler = new ColumnFamilyHandler(); List<String> selectedColFamilies = cfHandler.filterColumnFamilies(keyspaceName); String logFileLocation = config.getTmpLogsDirectory(); List<String> filePathList = new ArrayList<String>(selectedColFamilies.size()); for (int i = 0; i < selectedColFamilies.size(); i++) { String colFamilyName = selectedColFamilies.get(i); if (colFamilyName.contains("log")) { String[] strArrayColFamilyNameParts = colFamilyName.split("_"); int strArrayLength = strArrayColFamilyNameParts.length; if (strArrayLength > 1) { String tenantId = strArrayColFamilyNameParts[1]; if (strArrayLength > 2) { String serverName = strArrayColFamilyNameParts[2]; for (int j = 3; j < strArrayLength - 3; j++) { serverName += "_" + strArrayColFamilyNameParts[j]; } String date = strArrayColFamilyNameParts[strArrayLength - 3] + "_" + strArrayColFamilyNameParts[strArrayLength - 2] + "_" + strArrayColFamilyNameParts[strArrayLength - 1]; filePathList.add(archivedLogLocation + tenantId + "/" + serverName + "/" + date); } } } } return filePathList; } public Map<String, String> createQuery() throws SummarizerException { Map hiveQueryMap = new HashMap(); List<String> filteredColFamilies = new ColumnFamilyHandler().filterColumnFamilies(keyspaceName); List<String> filePaths = createFilePaths(); for (int i = 0; i < filePaths.size(); i++) { String filePath = filePaths.get(i); log.info(filePath); String columnFamilyName = "\"" + filteredColFamilies.get(i) + "\""; String hiveQueryTemplate = config.getHiveQuery(); String cassandraHost = config.getCassandraHost(); String cassandraUserName = config.getCassUsername(); String cassandraPassword = config.getCassPassword(); String cassandraKeySpace = config.getKeyspace(); String hiveQuery = replaceVars(hiveQueryTemplate, filePath, columnFamilyName, cassandraHost, cassandraUserName, cassandraPassword, cassandraKeySpace); hiveQueryMap.put(filteredColFamilies.get(i), hiveQuery); } return hiveQueryMap; } public String replaceVars(String queryTemplate, String filePath, String cfName, String cassHost, String cassUsrName, String cassPswd, String cassKeySpace) { //When there are multiple cassandra hosts given in the summarizer-config.xml String[] strArrCassHostList = cassHost.split(","); String hosts = ""; String cassPort = strArrCassHostList[0].substring(strArrCassHostList[0].indexOf(":") + 1, strArrCassHostList[0].length()); for(String host : strArrCassHostList) { hosts += host.substring(0, host.indexOf(":")) + ","; } hosts = hosts.substring(0, hosts.length() - 1); queryTemplate = queryTemplate.replace("set logs_column_family = %s;", "set logs_column_family = " + cfName + ";"); queryTemplate = queryTemplate.replace("set file_path= %s;", "set file_path = " + filePath + ";"); queryTemplate = queryTemplate.replace("\"cassandra.host\" = %s,", "\"cassandra.host\" = \"" + hosts + "\","); queryTemplate = queryTemplate.replace("\"cassandra.port\" = %s,", "\"cassandra.port\" =\"" + cassPort + "\","); queryTemplate = queryTemplate.replace("\"cassandra.ks.name\" = %s,", "\"cassandra.ks.name\" = \"" + cassKeySpace + "\","); queryTemplate = queryTemplate.replace("\"cassandra.ks.username\" = %s,", "\"cassandra.ks.username\" = \"" + cassUsrName + "\","); queryTemplate = queryTemplate.replace("\"cassandra.ks.password\" = %s,", "\"cassandra.ks.password\" =\"" + cassPswd + "\","); return queryTemplate; } } <file_sep>/components/application-mgt/org.wso2.carbon.application.mgt/src/main/java/org/wso2/carbon/application/mgt/internal/AppManagementServiceComponent.java /* * Copyright 2005-2007 WSO2, Inc. (http://wso2.com) * * 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 org.wso2.carbon.application.mgt.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.axis2.context.ConfigurationContext; import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.application.deployer.service.ApplicationManagerService; import org.wso2.carbon.registry.core.service.RegistryService; import org.osgi.service.component.ComponentContext; /** * @scr.component name="application.mgt.dscomponent" immediate="true" * @scr.reference name="application.manager" interface="org.wso2.carbon.application.deployer.service.ApplicationManagerService" * cardinality="1..1" policy="dynamic" bind="setAppManager" unbind="unsetAppManager" */ public class AppManagementServiceComponent { private static Log log = LogFactory.getLog(AppManagementServiceComponent.class); private static ApplicationManagerService applicationManager; protected void activate(ComponentContext ctxt) { if (log.isDebugEnabled()) { log.debug("Activated AppManagementServiceComponent"); } } protected void deactivate(ComponentContext ctxt) { if (log.isDebugEnabled()) { log.debug("Deactivated AppManagementServiceComponent"); } } protected void setAppManager(ApplicationManagerService appManager) { applicationManager = appManager; } protected void unsetAppManager(ApplicationManagerService appManager) { applicationManager = null; } public static ApplicationManagerService getAppManager() throws Exception { if (applicationManager == null) { String msg = "Before activating App management service bundle, an instance of " + "ApplicationManager should be in existance"; log.error(msg); throw new Exception(msg); } return applicationManager; } } <file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/data/LogEvent.java /* * Copyright The Apache Software Foundation. * * 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 org.wso2.carbon.logging.service.data; public class LogEvent { private String key; private String tenantId; private String serverName; private String appName; private String logTime; private String logger; private String priority; private String message; private String ip; private String stacktrace; private String instance; public LogEvent() { } public LogEvent(String tenantId, String serverName, String appName, String logTime, String logger, String priority, String message, String ip, String stacktrace, String instance) { super(); this.tenantId = tenantId; this.serverName = serverName; this.appName = appName; this.logTime = logTime; this.logger = logger; this.priority = priority; this.message = message; this.ip = ip; this.stacktrace = stacktrace; this.instance = instance; } public LogEvent(String message, String priority) { this.message = message; this.priority = priority; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getServerName() { return serverName; } public void setServerName(String serverName) { this.serverName = serverName; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getLogTime() { return logTime; } public void setLogTime(String logTime) { this.logTime = logTime; } public String getLogger() { return logger; } public void setLogger(String logger) { this.logger = logger; } public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getStacktrace() { return stacktrace; } public void setStacktrace(String stacktrace) { this.stacktrace = stacktrace; } public String getInstance() { return instance; } public void setInstance(String instance) { this.instance = instance; } } <file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/data/LoggerData.java /* * Copyright 2004,2005 The Apache Software Foundation. * * 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 org.wso2.carbon.logging.service.data; public class LoggerData { private String name; private String level; private String parentName; private boolean additivity; public LoggerData() { } public LoggerData(String name, String level, boolean aditivity, String parentName) { this.name = name; this.level = level; this.additivity = aditivity; this.parentName = parentName; } public boolean getAdditivity() { return additivity; } public void setAdditivity(boolean additivity) { this.additivity = additivity; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } } <file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/sort/LogEventSorter.java /* * Copyright 2005,2014 WSO2, Inc. http://www.wso2.org * 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 org.wso2.carbon.logging.service.sort; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.logging.service.data.LogEvent; import org.wso2.carbon.logging.service.util.LoggingConstants; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.Callable; public class LogEventSorter implements Callable<List<LogEvent>> { private static LogTaskThreadPoolExecuter executer; private static Log log = LogFactory.getLog(LogEventSorter.class); private List<LogEvent> events; private List<LogEvent> preprocessedEvents; public LogEventSorter(List<LogEvent> events) { this.events = events; executer = new LogTaskThreadPoolExecuter(); this.preprocessedEvents = new ArrayList<LogEvent>(); } private static List<LogEvent> sortLogs(List<LogEvent> logEvents, int left, int right) { if (left < right) { int initialPivot = left + ((right - left) / 2); int pivot = partition(logEvents, left, right, initialPivot); if (pivot > 0) { sortLogs(logEvents, left, pivot - 1); } else if (pivot < (logEvents.size() - 1)) { sortLogs(logEvents, pivot + 1, right); } } return logEvents; } private synchronized static int partition(List<LogEvent> logEvents, int left, int right, int pivot) { int storeIndex; long logTime = createDateObject(logEvents.get(pivot).getLogTime()).getTime(); LogEvent logEvent = logEvents.get(right); logEvents.set(right, logEvents.get(pivot)); logEvents.set(pivot, logEvent); storeIndex = left; for (int i = left; i < right; i++) { long t1 = createDateObject(logEvents.get(i).getLogTime()).getTime(); if (t1 > logTime) { logEvent = logEvents.get(storeIndex); logEvents.set(storeIndex, logEvents.get(i)); logEvents.set(i, logEvent); storeIndex = storeIndex + 1; } } logEvent = logEvents.get(storeIndex); logEvents.set(storeIndex, logEvents.get(right)); logEvents.set(right, logEvent); return storeIndex; } private static Date createDateObject(String date) { Date d = null; DateFormat formatter; try { formatter = new SimpleDateFormat(LoggingConstants.DATE_TIME_FORMATTER); d = formatter.parse(date); } catch (ParseException e) { log.error("Illegal Date Format", e); } return d; } private List<LogEvent> getLogEvents() { return this.events; } private LogTaskThreadPoolExecuter getExecuter() { return executer; } public List<LogEvent> getPreprocessedEvents() { return preprocessedEvents; } @Override public List<LogEvent> call() throws Exception { List<LogEvent> logEvents; if (events != null) { logEvents = sortLogs(events, 0, events.size() - 1); } else { logEvents = new ArrayList<LogEvent>(); } return logEvents; } }<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/util/LoggingUtil.java /* * Copyright 2005-2007 WSO2, Inc. (http://wso2.com) * * 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 org.wso2.carbon.logging.service.util; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.description.AxisService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.Appender; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.DailyRollingFileAppender; import org.apache.log4j.FileAppender; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.net.SyslogAppender; import org.springframework.util.Log4jConfigurer; import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.core.util.SystemFilter; import org.wso2.carbon.logging.service.LogViewerException; import org.wso2.carbon.logging.service.appender.CarbonMemoryAppender; import org.wso2.carbon.logging.service.config.ServiceConfigManager; import org.wso2.carbon.logging.service.config.SyslogConfigManager; import org.wso2.carbon.logging.service.config.SyslogConfiguration; import org.wso2.carbon.logging.service.data.SyslogData; import org.wso2.carbon.logging.service.internal.DataHolder; import org.wso2.carbon.logging.service.internal.LoggingServiceComponent; import org.wso2.carbon.logging.service.registry.RegistryManager; import org.wso2.carbon.registry.core.Collection; import org.wso2.carbon.registry.core.RegistryConstants; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.Pageable; import org.wso2.carbon.utils.ServerConstants; import org.wso2.carbon.utils.logging.CircularBuffer; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class LoggingUtil { public static final String SYSTEM_LOG_PATTERN = "[%d] %5p - %x %m {%c}%n"; private static final int MAX_LOG_MESSAGES = 200; private static final String CARBON_LOGFILE_APPENDER = "CARBON_LOGFILE"; private static final Log log = LogFactory.getLog(LoggingUtil.class); private static RegistryManager registryManager = new RegistryManager(); public static boolean isStratosService() throws Exception { String serviceName = ServerConfiguration.getInstance().getFirstProperty("ServerKey"); return ServiceConfigManager.isStratosService(serviceName); } public static void setSystemLoggingParameters(String logLevel, String logPattern) throws Exception { registryManager.updateConfigurationProperty(LoggingConstants.SYSTEM_LOG_LEVEL, logLevel); registryManager .updateConfigurationProperty(LoggingConstants.SYSTEM_LOG_PATTERN, logPattern); } public static SyslogData getSyslogData() throws Exception { return registryManager.getSyslogData(); } private static String[] getAdminServiceNames() { ConfigurationContext configurationContext = DataHolder.getInstance() .getServerConfigContext(); Map<String, AxisService> services = configurationContext.getAxisConfiguration() .getServices(); List<String> adminServices = new ArrayList<String>(); for (Map.Entry<String, AxisService> entry : services.entrySet()) { AxisService axisService = entry.getValue(); if (SystemFilter.isAdminService(axisService) || SystemFilter.isHiddenService(axisService)) { adminServices.add(axisService.getName()); } } return adminServices.toArray(new String[adminServices.size()]); } public static int getTenantIdForDomain(String tenantDomain) throws LogViewerException { int tenantId; TenantManager tenantManager = LoggingServiceComponent.getTenantManager(); if (tenantDomain == null || tenantDomain.equals("")) { tenantId = MultitenantConstants.SUPER_TENANT_ID; } else { try { tenantId = tenantManager.getTenantId(tenantDomain); } catch (UserStoreException e) { throw new LogViewerException("Cannot find tenant id for the given tenant domain."); } } return tenantId; } public static boolean isValidTenant(String domain) { int tenantId; if (domain == null || domain.equals("")) { tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); } else { try { tenantId = LoggingUtil.getTenantIdForDomain(domain); } catch (LogViewerException e) { return false; } } if (tenantId == org.wso2.carbon.base.MultitenantConstants.INVALID_TENANT_ID) { return false; } return true; } public static boolean isFileAppenderConfiguredForST() { Logger rootLogger = Logger.getRootLogger(); DailyRollingFileAppender logger = (DailyRollingFileAppender) rootLogger .getAppender(CARBON_LOGFILE_APPENDER); if (logger != null && CarbonContext.getThreadLocalCarbonContext().getTenantId() == org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID) { return true; } else { return false; } } public static boolean isAdmingService(String serviceName) { String[] adminServices = getAdminServiceNames(); for (String adminService : adminServices) { if (adminService.equals(serviceName)) { return true; } } return false; } public static String getSystemLogLevel() throws Exception { String systemLogLevel = registryManager .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_LEVEL); if (systemLogLevel == null) { return Logger.getRootLogger().getLevel().toString(); } return systemLogLevel; } public static String getSystemLogPattern() throws Exception { String systemLogPattern = registryManager .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_PATTERN); if (systemLogPattern == null) { return LoggingUtil.SYSTEM_LOG_PATTERN; } return systemLogPattern; } public static boolean isValidTenantDomain(String tenantDomain) { try { getTenantIdForDomain(tenantDomain); return true; } catch (LogViewerException e) { return false; } } public static boolean isManager() { if (LoggingConstants.WSO2_STRATOS_MANAGER.equalsIgnoreCase(ServerConfiguration.getInstance() .getFirstProperty("ServerKey"))) { return true; } else { return false; } } public static void loadCustomConfiguration() throws Exception { // set the appender details // we have not provided a facility to add or remove appenders so all the // initial appender set should present in the system. // and all the initall logger should present in the system Set<Appender> appenderSet = new HashSet<Appender>(); Logger rootLogger = LogManager.getRootLogger(); // set the root logger level, if the system log level is changed. String persistedSystemLoggerLevel = registryManager .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_LEVEL); boolean systemLogLevelChanged = (persistedSystemLoggerLevel != null); if (systemLogLevelChanged) { rootLogger.setLevel(Level.toLevel(persistedSystemLoggerLevel)); } String persistedSystemLogPattern = registryManager .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_PATTERN); boolean systemLogPatternChanged = (persistedSystemLogPattern != null); setSystemLoggingParameters(persistedSystemLoggerLevel, (systemLogPatternChanged) ? persistedSystemLogPattern : SYSTEM_LOG_PATTERN); addAppendersToSet(rootLogger.getAllAppenders(), appenderSet); // System log level has been changed, need to update all the loggers and // appenders if (systemLogLevelChanged) { Logger logger; Enumeration loggersEnum = LogManager.getCurrentLoggers(); Level systemLevel = Level.toLevel(persistedSystemLoggerLevel); while (loggersEnum.hasMoreElements()) { logger = (Logger) loggersEnum.nextElement(); // we ignore all class level defined loggers addAppendersToSet(logger.getAllAppenders(), appenderSet); logger.setLevel(systemLevel); } for (Appender appender : appenderSet) { if (appender instanceof AppenderSkeleton) { AppenderSkeleton appenderSkeleton = (AppenderSkeleton) appender; appenderSkeleton.setThreshold(systemLevel); appenderSkeleton.activateOptions(); } } } // Update the logger data according to the data stored in the registry. Collection loggerCollection = registryManager.getLoggers(); if (loggerCollection != null) { String[] loggerResourcePaths = loggerCollection.getChildren(); for (String loggerResourcePath : loggerResourcePaths) { String loggerName = loggerResourcePath.substring(LoggingConstants.LOGGERS.length()); Logger logger = LogManager.getLogger(loggerName); Resource loggerResource = registryManager.getLogger(loggerName); if (loggerResource != null && logger != null) { logger.setLevel(Level.toLevel(loggerResource .getProperty(LoggingConstants.LoggerProperties.LOG_LEVEL))); logger.setAdditivity(Boolean.parseBoolean(loggerResource .getProperty(LoggingConstants.LoggerProperties.ADDITIVITY))); } } } // update the appender data according to data stored in database Collection appenderCollection = registryManager.getAppenders(); if (appenderCollection != null) { String[] appenderResourcePaths = appenderCollection.getChildren(); for (String appenderResourcePath : appenderResourcePaths) { String appenderName = appenderResourcePath.substring(LoggingConstants.APPENDERS .length()); Appender appender = getAppenderFromSet(appenderSet, appenderName); Resource appenderResource = registryManager.getAppender(appenderName); if (appenderResource != null && appender != null) { if ((appender.getLayout() != null) && (appender.getLayout() instanceof PatternLayout)) { ((PatternLayout) appender.getLayout()) .setConversionPattern(appenderResource .getProperty(LoggingConstants.AppenderProperties.PATTERN)); } if (appender instanceof FileAppender) { FileAppender fileAppender = ((FileAppender) appender); // resolves the log file path, if not absolute path, calculate with CARBON_HOME as the base Path logFilePath = Paths.get(appenderResource.getProperty( LoggingConstants.AppenderProperties.LOG_FILE_NAME)); if (!logFilePath.isAbsolute()) { logFilePath = Paths.get(System.getProperty(ServerConstants.CARBON_HOME)).resolve(logFilePath); } fileAppender.setFile(logFilePath.normalize().toString()); fileAppender.activateOptions(); } if (appender instanceof CarbonMemoryAppender) { CarbonMemoryAppender memoryAppender = (CarbonMemoryAppender) appender; memoryAppender.setCircularBuffer(new CircularBuffer(200)); memoryAppender.activateOptions(); } if (appender instanceof SyslogAppender) { SyslogAppender syslogAppender = (SyslogAppender) appender; syslogAppender.setSyslogHost(appenderResource .getProperty(LoggingConstants.AppenderProperties.SYS_LOG_HOST)); syslogAppender.setFacility(appenderResource .getProperty(LoggingConstants.AppenderProperties.FACILITY)); } if (appender instanceof AppenderSkeleton) { AppenderSkeleton appenderSkeleton = (AppenderSkeleton) appender; appenderSkeleton.setThreshold(Level.toLevel(appenderResource .getProperty(LoggingConstants.AppenderProperties.THRESHOLD))); appenderSkeleton.activateOptions(); } } } } } private static void addAppendersToSet(Enumeration appenders, Set<Appender> appenderSet) { while (appenders.hasMoreElements()) { Appender appender = (Appender) appenders.nextElement(); appenderSet.add(appender); } } public static Appender getAppenderFromSet(Set<Appender> appenderSet, String name) { for (Appender appender : appenderSet) { if ((appender.getName() != null) && (appender.getName().equals(name))) { return appender; } } return null; } public static void updateConfigurationProperty(String key, String value) throws RegistryException { registryManager.updateConfigurationProperty(key, value); } public static String getConfigurationProperty(String key) throws RegistryException { return registryManager.getConfigurationProperty(key); } public static void removeAllLoggersAndAppenders() throws Exception { registryManager.removeAllRegistryEntries(); } public static boolean isSysLogAppender(String tenantDomain) throws Exception { SyslogConfiguration syslogConfig = SyslogConfigManager.loadSyslogConfiguration(); return syslogConfig.isSyslogOn(); } public static boolean isSyslogConfigured() throws Exception { if (registryManager.getSyslogConfig() == null) { return false; } else { return true; } } public static int getLineNumbers(String logFile) throws Exception { InputStream logStream; try { logStream = getLocalInputStream(logFile); } catch (IOException e) { throw new LogViewerException("Cannot find the specified file location to the log file", e); } catch (Exception e) { throw new LogViewerException("Cannot find the specified file location to the log file", e); } try { byte[] c = new byte[1024]; int count = 0; int readChars = 0; while ((readChars = logStream.read(c)) != -1) { for (int i = 0; i < readChars; ++i) { if (c[i] == '\n') { ++count; } } } return count; } catch (IOException e) { throw new LogViewerException("Cannot read file size from the " + logFile, e); } finally { try { logStream.close(); } catch (IOException e) { throw new LogViewerException("Cannot close the input stream " + logFile, e); } } } public static String[] getLogLinesFromFile(String logFile, int maxLogs, int start, int end) throws LogViewerException { ArrayList<String> logsList = new ArrayList<String>(); InputStream logStream; if (end > maxLogs) { end = maxLogs; } try { logStream = getLocalInputStream(logFile); } catch (Exception e) { throw new LogViewerException("Cannot find the specified file location to the log file", e); } int index = 1; String line; try (BufferedReader dataInput = new BufferedReader(new InputStreamReader(logStream))) { while ((line = dataInput.readLine()) != null) { if (index <= end && index > start) { logsList.add(line); } index++; } } catch (IOException e) { log.error("Cannot read the log file", e); throw new LogViewerException("Cannot read the log file", e); } return logsList.toArray(new String[logsList.size()]); } public static void restoreDefaults() throws Exception { registryManager.removeAllRegistryEntries(); LogManager.resetConfiguration(); try { String logFile = CarbonUtils.getCarbonConfigDirPath() + RegistryConstants.PATH_SEPARATOR + "log4j.properties"; Log4jConfigurer.initLogging(logFile); } catch (FileNotFoundException e) { String msg = "Cannot restore default logging configuration." + " log4j.properties file is not found in the classpath"; throw new LogViewerException(msg, e); } } private static InputStream getLocalInputStream(String logFile) throws FileNotFoundException, LogViewerException { Path logFilePath = Paths.get(CarbonUtils.getCarbonLogsPath(), logFile); if (!isPathInsideBaseDirectory(Paths.get(CarbonUtils.getCarbonLogsPath()), logFilePath)) { throw new LogViewerException("Specified log file path is outside carbon logs directory."); } FileAppender carbonLogFileAppender = (FileAppender) Logger.getRootLogger().getAppender(CARBON_LOGFILE_APPENDER); String carbonLogFileName = new File(carbonLogFileAppender.getFile()).getName(); if (!logFilePath.getFileName().toString().startsWith(carbonLogFileName)) { throw new LogViewerException("Trying to access logs other than CARBON_LOGFILE appender log file."); } InputStream is = new BufferedInputStream(new FileInputStream(logFilePath.toString())); return is; } /** * This method stream log messages and retrieve 100 log messages per page * * @param pageNumber The page required. Page number starts with 0. * @param sourceList The original list of items * @param pageable The type of Pageable item * @return Returned page */ public static <C> List<C> doPaging(int pageNumber, List<C> sourceList, int maxLines, Pageable pageable) { if (pageNumber < 0 || pageNumber == Integer.MAX_VALUE) { pageNumber = 0; } if (sourceList.size() == 0) { return sourceList; } if (pageNumber < 0) { throw new RuntimeException("Page number should be a positive integer. " + "Page numbers begin at 0."); } int itemsPerPageInt = MAX_LOG_MESSAGES; // the default number of item // per page int numberOfPages = (int) Math.ceil((double) maxLines / itemsPerPageInt); if (pageNumber > numberOfPages - 1) { pageNumber = numberOfPages - 1; } List<C> returnList = new ArrayList<C>(); for (int i = 0; i < sourceList.size(); i++) { returnList.add(sourceList.get(i)); } int pages = calculatePageLevel(pageNumber + 1); if (pages > numberOfPages) { pages = numberOfPages; } pageable.setNumberOfPages(pages); pageable.set(returnList); return returnList; } /* * This is an equation to retrieve the visible number of pages ie p1-p5 -> 5 * p6-p10 -> 10 p11-p15 -> 15 */ private static int calculatePageLevel(int x) { int p = x / 5; int q = x % 5; int t = (p + 1) * 5; int s = (p * 5) + 1; int y = q > 0 ? t : s; return y; } /** * Tests if the provided path is inside the base directory path. * * @param baseDirPath absolute {@link Path} of the base directory in which we want to check whether the given path * is inside * @param path {@link Path} to be tested * @return {@code true} if the given path is inside the base directory path, otherwise {@code false} */ private static boolean isPathInsideBaseDirectory(Path baseDirPath, Path path) { Path resolvedPath = baseDirPath.resolve(path).normalize(); return resolvedPath.startsWith(baseDirPath.normalize()); } } <file_sep>/components/reporting/org.wso2.carbon.reporting.core/src/main/java/org/wso2/carbon/reporting/core/internal/ReportingComponent.java /** * Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * 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 org.wso2.carbon.reporting.core.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.reporting.core.utils.CommonUtil; import org.wso2.carbon.utils.Axis2ConfigurationContextObserver; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; /** * @scr.component name="reporting.services" immediate="true" * @scr.reference name="registry.service" interface="org.wso2.carbon.registry.core.service.RegistryService" * cardinality="1..1" policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService" * @scr.reference name="org.wso2.carbon.ndatasource.core.DataSourceService" interface="org.wso2.carbon.ndatasource.core.DataSourceService" * cardinality="0..1" policy="dynamic" bind="setCarbonDataSourceService" unbind="unsetCarbonDataSourceService" */ public class ReportingComponent { private static Log log = LogFactory.getLog(ReportingComponent.class); private static RegistryService registryServiceInstance; private static DataSourceService dataSourceService1; protected void activate(ComponentContext componentContext) { try { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); ReportingAxis2ConfigurationContextObserver observer = new ReportingAxis2ConfigurationContextObserver(); componentContext.getBundleContext(). registerService(Axis2ConfigurationContextObserver.class.getName(), observer, null); CommonUtil.addJrxmlConfigs(registryServiceInstance.getSystemRegistry()); } catch (Throwable e) { log.error(e.getMessage(), e); } } protected void deactivate(ComponentContext componentContext) { log.debug("report definition deactivated"); } protected void setRegistryService(RegistryService registryService) { registryServiceInstance = registryService; } protected void unsetRegistryService(RegistryService registryService) { registryServiceInstance = null; } public static RegistryService getRegistryService() throws RegistryException { if (registryServiceInstance == null) { throw new RegistryException("Registry Service instance null"); } return registryServiceInstance; } protected void setCarbonDataSourceService( DataSourceService dataSourceService) { if (log.isDebugEnabled()) { log.debug("Setting the Carbon Data Sources Service"); } ReportingComponent.dataSourceService1 = dataSourceService; } protected void unsetCarbonDataSourceService( DataSourceService dataSourceService) { dataSourceService1 = dataSourceService; } public static DataSourceService getCarbonDataSourceService() { return dataSourceService1; } }<file_sep>/components/logging/org.wso2.carbon.logging.summarizer/src/main/java/org/wso2/carbon/logging/summarizer/utils/LoggingConfigManager.java /* * Copyright The Apache Software Foundation. * * 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. */ // TOD0 Change the packaging to org.wso2.carbon.logging.common package org.wso2.carbon.logging.summarizer.utils; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.wso2.carbon.registry.core.RegistryConstants; import org.wso2.carbon.utils.CarbonUtils; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Iterator; public class LoggingConfigManager { private static final Log log = LogFactory.getLog(LoggingConfigManager.class); private static LoggingConfigManager cassandraConfig; private static BundleContext bundleContext; public static LoggingConfigManager getCassandraConfig() { return cassandraConfig; } public static void setBundleContext(BundleContext bundleContext) { LoggingConfigManager.bundleContext = bundleContext; } public static void setCassandraConfig(LoggingConfigManager syslogConfig) { LoggingConfigManager.cassandraConfig = syslogConfig; } public static Log getLog() { return log; } public LoggingConfig getSyslogData() { return null; } /** * Returns the configurations from the Cassandra configuration file. * * @return cassandra configurations */ public static LoggingConfig loadLoggingConfiguration() { // gets the configuration file name from the cassandra-config.xml. String cassandraConfigFileName = CarbonUtils.getCarbonConfigDirPath() + RegistryConstants.PATH_SEPARATOR + LoggingConstants.ETC_DIR + RegistryConstants.PATH_SEPARATOR + LoggingConstants.LOGGING_CONF_FILE; return loadLoggingConfiguration(cassandraConfigFileName); } private InputStream getInputStream(String configFilename) throws IOException { InputStream inStream = null; File configFile = new File(configFilename); if (configFile.exists()) { inStream = new FileInputStream(configFile); } String warningMessage = ""; if (inStream == null) { URL url; if (bundleContext != null) { if ((url = bundleContext.getBundle().getResource( LoggingConstants.LOGGING_CONF_FILE)) != null) { inStream = url.openStream(); } else { warningMessage = "Bundle context could not find resource " + LoggingConstants.LOGGING_CONF_FILE + " or user does not have sufficient permission to access the resource."; log.warn(warningMessage); } } else { if ((url = this.getClass().getClassLoader() .getResource(LoggingConstants.LOGGING_CONF_FILE)) != null) { inStream = url.openStream(); } else { warningMessage = "Could not find resource " + LoggingConstants.LOGGING_CONF_FILE + " or user does not have sufficient permission to access the resource."; log.warn(warningMessage); } } } return inStream; } private static LoggingConfig loadDefaultConfiguration() { LoggingConfig config = new LoggingConfig(); config.setCassandraServerAvailable(false); return config; } /** * Loads the given logging Configuration file. * * @param configFilename Name of the configuration file * @return the syslog configuration data. */ private static LoggingConfig loadLoggingConfiguration( String configFilename) { LoggingConfig config = new LoggingConfig(); InputStream inputStream = null; try { inputStream = new LoggingConfigManager() .getInputStream(configFilename); } catch (IOException e1) { log.error("Could not close the Configuration File " + configFilename); } if (inputStream != null) { try { XMLStreamReader parser = XMLInputFactory.newInstance() .createXMLStreamReader(inputStream); StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement documentElement = builder.getDocumentElement(); @SuppressWarnings("rawtypes") Iterator it = documentElement.getChildElements(); while (it.hasNext()) { OMElement element = (OMElement) it.next(); // Checks whether logging configuration enable. if (LoggingConstants.CassandraConfigProperties.IS_CASSANDRA_AVAILABLE .equals(element.getLocalName())) { String isCassandraOn = element.getText(); // by default, make the loggingConfig off. boolean isCassandraAvailable = false; if (isCassandraOn.trim().equalsIgnoreCase("true")) { isCassandraAvailable = true; } config.setCassandraServerAvailable(isCassandraAvailable); }if (LoggingConstants.CassandraConfigProperties.IS_DELETE_COL_FAMILY .equals(element.getLocalName())) { String isDeleteColFamily = element.getText(); // by default, make the loggingConfig off. boolean isDeleteColumnFamily = false; if (isDeleteColFamily.trim().equalsIgnoreCase("true")) { isDeleteColumnFamily = true; } config.setDeleteColFamily(isDeleteColumnFamily); } else if (LoggingConstants.CassandraConfigProperties.USER_NAME .equals(element.getLocalName())) { config.setCassUsername(element.getText()); } else if (LoggingConstants.CassandraConfigProperties.PASSWORD .equals(element.getLocalName())) { config.setCassPassword(element.getText()); } else if (LoggingConstants.CassandraConfigProperties.CONSISTENCY_LEVEL .equals(element.getLocalName())) { config.setConsistencyLevel(element.getText()); } else if (LoggingConstants.CassandraConfigProperties.AUTO_DISCOVERY .equals(element.getLocalName())) { String autoDiscoveryEnable = element.getAttributeValue( new QName(LoggingConstants.CassandraConfigProperties.AUTO_DISCOVERY_ENABLE)); boolean isAutoDiscoveryEnable = false; if (autoDiscoveryEnable.trim().equalsIgnoreCase("true")) { isAutoDiscoveryEnable = true; } config.setAutoDiscoveryEnable(isAutoDiscoveryEnable); String delay = element.getAttributeValue( new QName(LoggingConstants.CassandraConfigProperties.AUTO_DISCOVERY_DELAY)); if (delay != null && !"".equals(delay.trim())) { int delayAsInt = -1; try { delayAsInt = Integer.parseInt(delay.trim()); } catch (NumberFormatException ignored) { } if (delayAsInt > 0) { config.setAutoDiscoveryDelay(delayAsInt); } } } else if (LoggingConstants.CassandraConfigProperties.RETRY_DOWNED_HOSTS .equals(element.getLocalName())) { String retryDownedEnable = element.getAttributeValue( new QName(LoggingConstants.CassandraConfigProperties.RETRY_DOWNED_HOSTS_ENABLE)); boolean isRetryDownedHostsEnable = false; if (retryDownedEnable.trim().equalsIgnoreCase("true")) { isRetryDownedHostsEnable = true; } config.setRetryDownedHostsEnable(isRetryDownedHostsEnable); String queue = element.getAttributeValue( new QName(LoggingConstants.CassandraConfigProperties.RETRY_DOWNED_HOSTS_QUEUE)); if (queue != null && !"".equals(queue.trim())) { int queueAsInt = -1; try { queueAsInt = Integer.parseInt(queue.trim()); } catch (NumberFormatException ignored) { } if (queueAsInt > 0) { config.setRetryDownedHostsQueueSize(queueAsInt); } } } else if (LoggingConstants.CassandraConfigProperties.PUBLISHER_URL .equals(element.getLocalName())) { config.setPublisherURL(element.getText()); } else if (LoggingConstants.CassandraConfigProperties.PUBLISHER_USER .equals(element.getLocalName())) { config.setPublisherUser(element.getText()); } else if (LoggingConstants.CassandraConfigProperties.PUBLISHER_PASSWORD .equals(element.getLocalName())) { config.setPublisherPassword(element.getText()); } else if (LoggingConstants.CassandraConfigProperties.CRON_EXPRESSION .equals(element.getLocalName())) { config.setCronExpression(element.getText()); } else if (LoggingConstants.CassandraConfigProperties.HIVE_QUERY .equals(element.getLocalName())) { config.setHiveQuery(element.getText()); } else if (LoggingConstants.CassandraConfigProperties.LOG_DIRECTORY .equals(element.getLocalName())) { config.setLogDirectory(element.getText()); } else if (LoggingConstants.CassandraConfigProperties.TMP_LOG_DIRECTORY .equals(element.getLocalName())) { config.setTmpLogsDirectory(element.getText()); } else if (LoggingConstants.CassandraConfigProperties.CASSANDRA_HOST .equals(element.getLocalName())) { config.setCassandraHost(element.getText()); } else if (LoggingConstants.BamProperties.BAM_USERNAME .equals(element.getLocalName())) { config.setBamUserName(element.getText()); } else if (LoggingConstants.BamProperties.BAM_PASSWORD .equals(element.getLocalName())) { config.setBamPassword(element.getText()); } else if (LoggingConstants.HdfsProperties.HDFS_CONFIG .equals(element.getLocalName())) { config.setHdfsConfig(element.getText()); } else if (LoggingConstants.HdfsProperties.ARCHIVED_LOG_LOCATION .equals(element.getLocalName())) { config.setArchivedLogLocation(element.getText()); } } //setting the default valus to config config.setColFamily("log"); config.setCluster("admin"); config.setKeyspace("EVENT_KS"); return config; } catch (Exception e) { String msg = "Error in loading Stratos Configurations File: " + configFilename + ". Default Settings will be used."; log.error(msg, e); return loadDefaultConfiguration(); // returns the default // configurations, if the // file could not be loaded. } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.error("Could not close the Configuration File " + configFilename); } } } } log.error("Unable to locate the stratos configurations file. " + "Default Settings will be used."); return loadDefaultConfiguration(); // return the default configurations, // if the file not found. } } <file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/config/ServiceConfigManager.java /* * Copyright 2005,2014 WSO2, Inc. http://www.wso2.org * 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 org.wso2.carbon.logging.service.config; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.logging.service.LogViewerException; import org.wso2.carbon.logging.service.util.LoggingConstants; import org.wso2.carbon.utils.CarbonUtils; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ServiceConfigManager { private static final Log log = LogFactory.getLog(ServiceConfigManager.class); public static String[] getServiceNames() throws LogViewerException { String configFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator + LoggingConstants.MULTITENANCY_CONFIG_FOLDER + File.separator + LoggingConstants.CONFIG_FILENAME; List<String> serviceNames = new ArrayList<String>(); File configFile = new File(configFileName); if (configFile.exists()) { FileInputStream inputStream = null; try { inputStream = new FileInputStream(configFile); XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader( inputStream); StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement documentElement = builder.getDocumentElement(); @SuppressWarnings("unchecked") Iterator<OMElement> properties = documentElement.getChildrenWithName(new QName( "cloudService")); while (properties.hasNext()) { OMElement element = properties.next(); Iterator<OMElement> child = element.getChildElements(); while (child.hasNext()) { OMElement element1 = (OMElement) child.next(); if ("key".equalsIgnoreCase(element1.getLocalName())) { serviceNames.add(element1.getText()); } } } } catch (Exception e) { String msg = "Error in loading Stratos Configurations File: " + configFileName; throw new LogViewerException(msg, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.error("Could not close the Configuration File " + configFileName, e); } } } } return serviceNames.toArray(new String[serviceNames.size()]); } public static boolean isStratosService(String serviceName) throws LogViewerException { String services[] = getServiceNames(); for (String service : services) { if (service.equals(serviceName)) { return true; } } return false; } } <file_sep>/components/logging/org.wso2.carbon.logging.service/src/test/java/org/wso2/carbon/logging/service/util/LoggingUtilTest.java /* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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 org.wso2.carbon.logging.service.util; import org.apache.log4j.Appender; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.SimpleLayout; import org.testng.Assert; import org.testng.annotations.Test; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; /** * Unit tests for logging utils. */ public class LoggingUtilTest { private static final String APPENDER_NAME = "SIMPLE_APPENDER"; @Test(groups = {"org.wso2.carbon.logging.service.util"}, description = "Tests whether the Appender with the specified name is returned from " + "LoggingUtil.getAppenderFromSet method given that the Appender set contains an appender " + "without a name.") public void testGettingAppenderFromAppenderSet() { Appender appenderWithoutName = new ConsoleAppender(new SimpleLayout()); Appender appenderWithName = new ConsoleAppender(new SimpleLayout()); appenderWithName.setName(APPENDER_NAME); Set<Appender> appenderSet = new LinkedHashSet<>(); appenderSet.add(appenderWithoutName); appenderSet.add(appenderWithName); Assert.assertEquals(appenderWithName, LoggingUtil.getAppenderFromSet(appenderSet, APPENDER_NAME), "Appender with the name " + APPENDER_NAME + " is not returned from getAppenderFromSet method."); } } <file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/config/LoggingConfigManager.java /* * Copyright 2005,2014 WSO2, Inc. http://www.wso2.org * 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 org.wso2.carbon.logging.service.config; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.wso2.carbon.logging.service.LoggingConfigReaderException; import org.wso2.carbon.logging.service.data.LoggingConfig; import org.wso2.carbon.logging.service.util.LoggingConstants; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Iterator; /*** * This class is used to read the logging configurations from the configuration file. * eg file: <CARBON_SERVER>/repository/conf/etc/logging-config.xml */ public class LoggingConfigManager { private static final Log log = LogFactory.getLog(LoggingConfigManager.class); private static BundleContext bundleContext; public static void setBundleContext(BundleContext bundleContext) { LoggingConfigManager.bundleContext = bundleContext; } /** * Loads the given logging configuration file. * * @param configFilenameWithPath * Name of the configuration file * @return the syslog configuration data. An empty configuration will be returned, if there any * issue while loading configurations. */ public static LoggingConfig loadLoggingConfiguration(String configFilenameWithPath) throws IOException, XMLStreamException, LoggingConfigReaderException { InputStream inputStream; LoggingConfig config = new LoggingConfig(); inputStream = new LoggingConfigManager().getInputStream(configFilenameWithPath); if (inputStream != null) { try { XMLStreamReader parser = XMLInputFactory.newInstance() .createXMLStreamReader(inputStream); StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement documentElement = builder.getDocumentElement(); // load log provider configurations OMElement logProviderConfig = documentElement.getFirstChildWithName( getQName(LoggingConstants.LogConfigProperties.LOG_PROVIDER_CONFIG)); config = loadLogProviderProperties(config, logProviderConfig); // load log file provider configurations OMElement logFileProviderConfig = documentElement.getFirstChildWithName( getQName(LoggingConstants.LogConfigProperties.LOG_FILE_PROVIDER_CONFIG)); config = loadLogFileProviderProperties(config, logFileProviderConfig); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.error("Could not close the logging configuration file " + configFilenameWithPath, e); } } } } return config; } /** * Load log file provider configs from the logging-config xml file. * * @param config * - logging config which will be injected with config information * @param logFileProviderConfig * - OM Element containing from the xml file * @return - logging config with injected LogFileProvider data * @throws LoggingConfigReaderException * - if an error occured while parsing the xml file. */ private static LoggingConfig loadLogFileProviderProperties(LoggingConfig config, OMElement logFileProviderConfig) throws LoggingConfigReaderException { String implClass = logFileProviderConfig.getAttributeValue( new QName("", LoggingConstants.LogConfigProperties.CLASS_ATTRIBUTE)); if (implClass != null) { config.setLogFileProviderImplClassName(implClass); OMElement propertiesElement = logFileProviderConfig.getFirstChildWithName( getQName(LoggingConstants.LogConfigProperties.PROPERTIES)); if (propertiesElement != null) { Object nextElement; OMElement propertyElement; // iterate through each property element in the xml file and add (name, value) // to the map within the LoggingConfig object for LogProvider properties. for (Iterator it = propertiesElement.getChildrenWithLocalName( LoggingConstants.LogConfigProperties.PROPERTY); it.hasNext(); ) { nextElement = it.next(); if (nextElement instanceof OMElement) { propertyElement = (OMElement) nextElement; config.setLogFileProviderProperty( propertyElement.getAttributeValue(new QName( LoggingConstants.LogConfigProperties.PROPERTY_NAME)), propertyElement.getAttributeValue(new QName( LoggingConstants.LogConfigProperties.PROPERTY_VALUE))); } } } else { String msg = "Error loading log file provider properties for " + implClass + " Check the logging configuration file"; throw new LoggingConfigReaderException(msg); } } else { String msg = "LogFileProvider implementation class name is null, " + "check the logging configuration file"; throw new LoggingConfigReaderException(msg); } return config; } /** * Load log provider configs from the logging-config xml file. * * @param config * - logging config which will be injected with config information * @param logProviderConfig * - OM Element containing from the xml file * @return - logging config with injected LogProvider data * @throws LoggingConfigReaderException * - if an error occured while parsing the xml file. */ private static LoggingConfig loadLogProviderProperties(LoggingConfig config, OMElement logProviderConfig) throws LoggingConfigReaderException { String implClass = logProviderConfig.getAttributeValue( new QName("", LoggingConstants.LogConfigProperties.CLASS_ATTRIBUTE)); if (implClass != null) { config.setLogProviderImplClassName(implClass); // load log provider configuration OMElement propertiesElement = logProviderConfig.getFirstChildWithName( getQName(LoggingConstants.LogConfigProperties.PROPERTIES)); if (propertiesElement != null) { OMElement propertyElement; Object nextElement; // iterate through each property element in the xml file and add (name, value) // to the map within the LoggingConfig object for LogFileProvider properties. for (Iterator it = propertiesElement.getChildrenWithLocalName( LoggingConstants.LogConfigProperties.PROPERTY); it.hasNext(); ) { nextElement = it.next(); if (nextElement instanceof OMElement) { propertyElement = (OMElement) nextElement; config.setLogProviderProperty( propertyElement.getAttributeValue(new QName( LoggingConstants.LogConfigProperties.PROPERTY_NAME)), propertyElement.getAttributeValue(new QName( LoggingConstants.LogConfigProperties.PROPERTY_VALUE))); } } } else { String msg = "Error loading log provider properties for " + implClass + " Check the logging configuration file "; throw new LoggingConfigReaderException(msg); } } else { String msg = "LogProvider implementation class name is null, " + "Check the loggging configuration file"; throw new LoggingConfigReaderException(msg); } return config; } private static QName getQName(String localName) { return new QName(LoggingConstants.LogConfigProperties.DEFAULT_LOGGING_CONFIG_NAMESPACE, localName); } /** * Get an input stream to read the file after loading the logging-config file. * * @param configFilename * - configuration file name * @return - an input stream to the file * @throws IOException * - if the file could not be opened */ private InputStream getInputStream(String configFilename) throws IOException { InputStream inputStream = null; File configFile = new File(configFilename); if (configFile.exists()) { inputStream = new FileInputStream(configFile); } String warningMessage; if (inputStream == null) { URL url; if (bundleContext != null) { if ((url = bundleContext.getBundle().getResource( LoggingConstants.LOGGING_CONF_FILE)) != null) { inputStream = url.openStream(); } else { warningMessage = "Bundle context could not find resource " + LoggingConstants.LOGGING_CONF_FILE + " or user does not have sufficient permission to access " + "the resource."; log.warn(warningMessage); } } else { if ((url = this.getClass().getClassLoader() .getResource(LoggingConstants.LOGGING_CONF_FILE)) != null) { inputStream = url.openStream(); } else { warningMessage = "Could not find resource " + LoggingConstants.LOGGING_CONF_FILE + " or user does not have sufficient permission to access " + "the resource."; log.warn(warningMessage); } } } return inputStream; } } <file_sep>/components/logging/org.wso2.carbon.logging.admin.ui/src/main/resources/org/wso2/carbon/logging/admin/ui/i18n/Resources.properties log-admin.logs=Logging logger=Logger parent.logger=Parent Logger effective.level=Level additivity=Additivity true=True false=False logging.configuration=Logging Configuration persist.all.configuration.changes=Persist All Configuration Changes global.log4j.configuration=Global Log4J Configuration log.level=Log Level log.pattern=Log Pattern syslog.porperty.configuration= Syslog Property Configuration syslog.log.url=Syslog-ng log host port=Port realm=Realm user.name = User Name password = <PASSWORD> update=Update restore.defaults=Restore Defaults configure.log4j.loggers=Configure Log4J Loggers filter.loggers.by=Filter Loggers by starts.with=Starts With contains=Contains configure.log4j.appenders=Configure Log4J Appenders name=Name threshold=Threshold log.file=Log File sys.log.host=Sys Log Host facility=Facility global.log.update.confirm=Do you really want to globally update the logging configuration? syslog.log.update.confirm=Do you really want to globally update the syslog configuration? global.log.restore.confirm=Do you really want to restore the original logging configuration? appender.log.update.confirm=Do you really want to update the appender configuration? loading=Loading... successfully.updated.logger=Successfully updated logger successfully.updated.syslog.config=Successfully updated Syslog config logger.update.failed=Logger update failed syslog.config.update.failed=Syslog config update failed successfully.updated.appender=Successfully updated appender appender.update.failed=Appender update failed no.loggers.found=No loggers satisfying the search criteria found global.log4j.config.restored.successfully=Global Log4j Configuration is Restored Successfully successfully.updated.gloable.log4j.configuration=Successfully updated Global Log4j Configuration gloable.log4j.configuration.update.failed=Global Log4j Configuration update failed successfully.restored.gloable.log4j.configuration=Successfully Restored Global Log4j Configuration gloable.log4j.configuration.retore.failed=Restoring of Global Log4j Configuration is failed <file_sep>/components/hostobjects/org.wso2.carbon.hostobjects.carbonutil/src/main/java/org/wso2/carbon/hostobjects/carbonutil/internal/CarbonHostObjectServiceComponent.java package org.wso2.carbon.hostobjects.carbonutil.internal; import org.wso2.carbon.user.core.service.RealmService; /** * @scr.component name="org.wso2.carbon.hostobject.carbonutil" immediate="true" * @scr.reference name="user.realmservice.default" * interface="org.wso2.carbon.user.core.service.RealmService" * cardinality="1..1" policy="dynamic" bind="setRealmService" unbind="unsetRealmService" */ public class CarbonHostObjectServiceComponent { protected void setRealmService(RealmService realmService) { ServiceHodler.setRealmService(realmService); } protected void unsetRealmService(RealmService realmService) { ServiceHodler.setRealmService(null); } } <file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/sort/LogTaskThreadPoolExecuter.java /* * Copyright 2005,2014 WSO2, Inc. http://www.wso2.org * 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 org.wso2.carbon.logging.service.sort; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class LogTaskThreadPoolExecuter { private static final Log log = LogFactory.getLog(LogTaskThreadPoolExecuter.class); private final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(5); private ThreadPoolExecutor threadPool = null; private int poolSize = 5; private int maxPoolSize = 5; private long keepAliveTime = 10; public LogTaskThreadPoolExecuter() { threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, queue); } public void runTask(Runnable task) { threadPool.execute(task); log.info("Task Count : " + queue.size()); } }<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/LogViewerException.java /* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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 org.wso2.carbon.logging.service; public class LogViewerException extends Exception { public LogViewerException(String s) { super(s); } public LogViewerException(String s, Throwable e) { super(s, e); } } <file_sep>/components/logging/org.wso2.carbon.logging.view.ui/src/main/resources/org/wso2/carbon/logging/view/ui/i18n/Resources.properties archived.logs=Show archived logs adv.search=Show advanced search max.exceed.message=Maximum Number of Log Retrieval for the Day Exceeded... Your latest logs will be omitted. logsmenutext=System Logs applogsmenutext=Application Logs viewlogsmenutext=View Logs text system.logs=System Logs app.logs=Application Logs system.logs.view = System Log View view=View download=Download search.logs=Search Logs file.size = File Size clear.all=Clear All Logs clear.all.log.message=Do you want to clear all the logs no.logs=--- No log entries found. --- invalid.tenant= --- Invalid tenant domain --- file.name = File Name date = Date action = Action log.tail = Log Tail service.name = Service Name log.head = Log Head log.message = Log Message log.type = Type local.log.location.information = Logs are taken from the local file system. remote.log.location.information = Logs are taken from the remote log hosted server. log.head.help = Enter the number of log lines to be displayed from the top-down. tenant.domain = Tenant Domain return.rows = Return Rows show.at.or.before = Show at or Between advanced.properties = Advanced Properties priority = Priority keyword = Keyword logger = Logger application.name=Application Name filter.system.logs=Filter System Logs date.format=mm/dd/yyyy hh:mm date.example=(eg 2012-05-18 06:21:39) view.stack.trace=More view.logs.within.the.past.thirty.mins=Logs taken within past thirty minutes. view.logs.between=Logs taken between. log.level=Level current.time=Current Time Zone: <file_sep>/components/url-mapper/org.wso2.carbon.url.mapper.clustermessage/src/main/java/org/wso2/carbon/url/mapper/clustermessage/internal/VirtualHostClusterServiceComponent.java /* * Copyright (c), WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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 org.wso2.carbon.url.mapper.clustermessage.internal; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.engine.AxisConfiguration; import org.apache.axis2.transport.local.LocalTransportReceiver; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.tomcat.api.CarbonTomcatService; import org.wso2.carbon.url.mapper.clustermessage.util.DataHolder; import org.wso2.carbon.utils.ConfigurationContextService; /** * Service Component to sending cluster message * @scr.component name="org.wso2.carbon.url.mapper.clustermessage" immediate="true" * @scr.reference name="config.context.service" * interface="org.wso2.carbon.utils.ConfigurationContextService" * cardinality="1..1" policy="dynamic" bind="setConfigurationContextService" * unbind="unsetConfigurationContextService" * @scr.reference name="tomcat.service.provider" * interface="org.wso2.carbon.tomcat.api.CarbonTomcatService" * cardinality="1..1" policy="dynamic" bind="setCarbonTomcatService" * unbind="unsetCarbonTomcatService" * */ public class VirtualHostClusterServiceComponent { private static Log log = LogFactory.getLog(VirtualHostClusterServiceComponent.class); protected void activate(ComponentContext context) { try { DataHolder.getInstance().registerRetrieverServices(context.getBundleContext()); if(log.isDebugEnabled()){ log.debug("******* Tenant Activity bundle is activated ******* "); } } catch (Throwable e) { log.error("******* Error in activating Tenant Activity bundle ******* ", e); } } protected void deactivate(ComponentContext context) { if (log.isDebugEnabled()) { log.debug("******* Tenant Activity is deactivated ******* "); } } protected void setConfigurationContextService(ConfigurationContextService ccService) { ConfigurationContext serverCtx = ccService.getServerConfigContext(); AxisConfiguration serverConfig = serverCtx.getAxisConfiguration(); LocalTransportReceiver.CONFIG_CONTEXT = new ConfigurationContext(serverConfig); LocalTransportReceiver.CONFIG_CONTEXT.setServicePath("services"); LocalTransportReceiver.CONFIG_CONTEXT.setContextRoot("local:/"); DataHolder.getInstance().setConfigurationContextService(ccService); } protected void unsetConfigurationContextService(ConfigurationContextService ccService) { DataHolder.getInstance().setConfigurationContextService(null); } protected void setCarbonTomcatService(CarbonTomcatService carbonTomcatService) { //keeping the carbonTomcatService in UrlMapperAdminService class DataHolder.getInstance().setCarbonTomcatService(carbonTomcatService); } protected void unsetCarbonTomcatService(CarbonTomcatService carbonTomcatService) { DataHolder.getInstance().setCarbonTomcatService(null); } } <file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/provider/FileLogProvider.java /* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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 org.wso2.carbon.logging.service.provider; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.ServerConfiguration; import org.apache.log4j.FileAppender; import org.apache.log4j.Logger; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.logging.service.LogViewerException; import org.wso2.carbon.logging.service.config.ServiceConfigManager; import org.wso2.carbon.logging.service.config.SyslogConfigManager; import org.wso2.carbon.logging.service.config.SyslogConfiguration; import org.wso2.carbon.logging.service.data.LogFileInfo; import org.wso2.carbon.logging.service.data.LoggingConfig; import org.wso2.carbon.logging.service.data.SyslogData; import org.wso2.carbon.logging.service.provider.api.LogFileProvider; import org.wso2.carbon.logging.service.util.LoggingConstants; import org.wso2.carbon.logging.service.util.LoggingUtil; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import javax.activation.DataHandler; import javax.mail.util.ByteArrayDataSource; import java.io.BufferedInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class FileLogProvider implements LogFileProvider { private static final String APPLICATION_TYPE_ZIP = "application/zip"; private static final String SERVER_KEY = "ServerKey"; private static final String URL_ENCODED_SPACE_CHAR = "%20"; private static final String CARBON_LOGFILE_APPENDER = "CARBON_LOGFILE"; private static Log log = LogFactory.getLog(FileLogProvider.class); /** * Initialize the log provider by reading the property comes with logging configuration file * This will be called immediate after create new instance of LogProvider * * @param loggingConfig - */ @Override public void init(LoggingConfig loggingConfig) { if(log.isDebugEnabled()){ log.debug("FileLogProvider is initialized."); } } @Override public List<LogFileInfo> getLogFileInfoList(String tenantDomain, String serverKey) throws LogViewerException { String folderPath = CarbonUtils.getCarbonLogsPath(); List<LogFileInfo> logs = new ArrayList<LogFileInfo>(); LogFileInfo logFileInfo; String currentServerName = getCurrentServerName(); if ((((tenantDomain == null || "".equals(tenantDomain)) && isSuperTenantUser()) || (tenantDomain != null && MultitenantConstants.SUPER_TENANT_DOMAIN_NAME .equalsIgnoreCase(tenantDomain))) && (serverKey == null || "".equals(serverKey) || serverKey.equalsIgnoreCase( currentServerName))) { File folder = new File(folderPath); FileFilter fileFilter = new WildcardFileFilter(LoggingConstants.RegexPatterns.LOCAL_CARBON_LOG_PATTERN); File[] listOfFiles = folder.listFiles(fileFilter); // folder.listFiles consumes lot of memory when there are many files in the folder // (> 10 000), can be fixed with nio support in Java7 if (listOfFiles == null) { // folder.listFiles can return a null, in that case return a default log info if (log.isDebugEnabled()) { log.debug("List of log files of the given pattern is null."); } return getDefaultLogInfoList(); } for (File file : listOfFiles) { String filename = file.getName(); String[] fileDates = filename.split(LoggingConstants.RegexPatterns.LOG_FILE_DATE_SEPARATOR); String filePath = CarbonUtils.getCarbonLogsPath() + LoggingConstants.URL_SEPARATOR + filename; File logfile = new File(filePath); if (fileDates.length == 2) { logFileInfo = new LogFileInfo(filename, fileDates[1], getFileSize(logfile)); } else { logFileInfo = new LogFileInfo(filename, LoggingConstants.RegexPatterns.CURRENT_LOG, getFileSize(logfile)); } logs.add(logFileInfo); } } return getSortedPerLogInfoList(logs); } @Override public DataHandler downloadLogFile(String logFile, String tenantDomain, String serverKey) throws LogViewerException { InputStream is = null; ByteArrayDataSource bytArrayDS; int tenantId = LoggingUtil.getTenantIdForDomain(tenantDomain); try { is = getInputStream(logFile, tenantId, serverKey); bytArrayDS = new ByteArrayDataSource(is, APPLICATION_TYPE_ZIP); return new DataHandler(bytArrayDS); } catch (LogViewerException e) { log.error("Cannot read InputStream from the file " + logFile, e); throw e; } catch (IOException e) { String msg = "Cannot read file size from the " + logFile; log.error(msg, e); throw new LogViewerException(msg, e); } finally { if (null != is) { try { is.close(); } catch (IOException e) { log.error("Error while closing inputStream of log file", e); } } } } private boolean isSyslogOn() { SyslogConfiguration syslogConfig = SyslogConfigManager.loadSyslogConfiguration(); return syslogConfig.isSyslogOn(); } private List<LogFileInfo> getSortedPerLogInfoList(List<LogFileInfo> logs) { if (logs == null || logs.isEmpty()) { return getDefaultLogInfoList(); } else { Collections.sort(logs, new Comparator<Object>() { public int compare(Object o1, Object o2) { LogFileInfo log1 = (LogFileInfo) o1; LogFileInfo log2 = (LogFileInfo) o2; return log1.getLogName().compareToIgnoreCase(log2.getLogName()); } }); return logs; } } private InputStream getLogDataStream(String logFile, int tenantId, String productName) throws Exception { SyslogData syslogData = getSyslogData(); //throws an Exception, so cannot throw a // specific exception from getLogDataStream() String url; // manager can view all the products tenant log information url = getLogsServerURLforTenantService(syslogData.getUrl(), logFile, tenantId, productName); String password = <PASSWORD>(); String userName = syslogData.getUserName(); int port = Integer.parseInt(syslogData.getPort()); String realm = syslogData.getRealm(); URI uri = new URI(url); String host = uri.getHost(); HttpClient client = new HttpClient(); client.getState().setCredentials(new AuthScope(host, port, realm), new UsernamePasswordCredentials(userName, password)); GetMethod get = new GetMethod(url); get.setDoAuthentication(true); client.executeMethod(get); return get.getResponseBodyAsStream(); } private SyslogData getSyslogData() throws Exception { return LoggingUtil.getSyslogData(); } private String getLogsServerURLforTenantService(String syslogServerURL, String logFile, int tenantId, String serverKey) throws LogViewerException { String serverUrl; String lastChar = String.valueOf(syslogServerURL.charAt(syslogServerURL.length() - 1)); if (lastChar.equals(LoggingConstants.URL_SEPARATOR)) { // http://my.log.server/logs/stratos/ syslogServerURL = syslogServerURL.substring(0, syslogServerURL.length() - 1); } if (isSuperTenantUser()) { // ST can view tenant specific log files. if (isManager()) { // manager can view different services log // messages. if (serverKey != null && serverKey.length() > 0) { serverUrl = getServerUrl(syslogServerURL, tenantId, serverKey); } else { serverUrl = getServerUrl(syslogServerURL, tenantId, LoggingConstants.WSO2_STRATOS_MANAGER); } if (!isStratosService()) { // stand-alone apps. serverUrl = getServerUrl(syslogServerURL, tenantId, ServerConfiguration.getInstance() .getFirstProperty(SERVER_KEY)); } } else { // for other stratos services can view only their relevant // logs. serverUrl = getServerUrl(syslogServerURL, tenantId, ServerConfiguration.getInstance() .getFirstProperty(SERVER_KEY)); } } else { // tenant level logging if (isManager()) { if (serverKey != null && serverKey.length() > 0) { serverUrl = getServerUrl(syslogServerURL, CarbonContext.getThreadLocalCarbonContext() .getTenantId(), serverKey); } else { serverUrl = getServerUrl(syslogServerURL, CarbonContext.getThreadLocalCarbonContext() .getTenantId(), LoggingConstants.WSO2_STRATOS_MANAGER); } } else { serverUrl = getServerUrl(syslogServerURL, CarbonContext.getThreadLocalCarbonContext().getTenantId(), ServerConfiguration.getInstance() .getFirstProperty(SERVER_KEY)); } } serverUrl = serverUrl.replaceAll("\\s", URL_ENCODED_SPACE_CHAR); logFile = logFile.replaceAll("\\s", URL_ENCODED_SPACE_CHAR); return serverUrl + logFile; } private String getServerUrl(String syslogServerURL, int tenantId, String serverKey) { return syslogServerURL + LoggingConstants.URL_SEPARATOR + tenantId + LoggingConstants.URL_SEPARATOR + serverKey + LoggingConstants.URL_SEPARATOR; } private boolean isStratosService() throws LogViewerException { String serverKey = ServerConfiguration.getInstance().getFirstProperty(SERVER_KEY); return ServiceConfigManager.isStratosService(serverKey); } private boolean isManager() { return LoggingConstants.WSO2_STRATOS_MANAGER.equalsIgnoreCase(ServerConfiguration.getInstance() .getFirstProperty(SERVER_KEY)); } private boolean isSuperTenantUser() { CarbonContext carbonContext = CarbonContext.getThreadLocalCarbonContext(); int tenantId = carbonContext.getTenantId(); return tenantId == MultitenantConstants.SUPER_TENANT_ID; } private String getCurrentServerName() { return ServerConfiguration.getInstance().getFirstProperty(SERVER_KEY); } private String getFileSize(File file) { long bytes = file.length(); int unit = 1024; if (bytes < unit) { return bytes + " B"; } int exp = (int) (Math.log(bytes) / Math.log(unit)); char pre = "KMGTPE".charAt(exp - 1); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); } private InputStream getInputStream(String logFile, int tenantId, String serverKey) throws LogViewerException { InputStream inputStream; try { if (isSyslogOn()) { inputStream = getLogDataStream(logFile, tenantId, serverKey); } else { if (isSuperTenantUser()) { Path logFilePath = Paths.get(CarbonUtils.getCarbonLogsPath(), logFile); if (!isPathInsideBaseDirectory(Paths.get(CarbonUtils.getCarbonLogsPath()), logFilePath)) { throw new LogViewerException("Specified log file path is outside carbon logs directory."); } FileAppender carbonLogFileAppender = (FileAppender) Logger.getRootLogger().getAppender(CARBON_LOGFILE_APPENDER); String carbonLogFileName = new File(carbonLogFileAppender.getFile()).getName(); if (!logFilePath.getFileName().toString().startsWith(carbonLogFileName)) { throw new LogViewerException("Trying to access logs other than " + "CARBON_LOGFILE appender log file."); } inputStream = getLocalInputStream(logFilePath.toString()); } else { throw new LogViewerException("Syslog Properties are not properly configured"); } } return inputStream; } catch (Exception e) { // cannot catch a specific exception since RegistryManager.getSyslogConfig (which is // used in the call stack of getLogDataStream()) throws an exception throw new LogViewerException("Error getting the file input stream", e); } } private InputStream getLocalInputStream(String logFile) throws FileNotFoundException { return new BufferedInputStream(new FileInputStream(logFile)); } private List<LogFileInfo> getDefaultLogInfoList() { List<LogFileInfo> defaultLogFileInfoList = new ArrayList<LogFileInfo>(); defaultLogFileInfoList.add(new LogFileInfo("NO_LOG_FILES", "---", "---")); return defaultLogFileInfoList; } /** * Tests if the provided path is inside the base directory path. * * @param baseDirPath absolute {@link Path} of the base directory in which we want to check whether the given path * is inside * @param path relative {@link Path} to be tested * @return {@code true} if the given path is inside the base directory path, otherwise {@code false} */ private static boolean isPathInsideBaseDirectory(Path baseDirPath, Path path) { Path resolvedPath = baseDirPath.resolve(path.normalize()).normalize(); return resolvedPath.startsWith(baseDirPath.normalize()); } }
db40e5a827141eaeac6c73af4b4d020b742e45d9
[ "Java", "INI" ]
25
Java
nalakas/carbon-commons-1
8dedc9d70f62d94c46e1eb2fccf22bb92fc6adbb
36915a3c5b460e6012713b2fb27653cc12bd9653
refs/heads/master
<repo_name>mbsuarezg/Proyecto<file_sep>/src/Model/Pentagon.java package Model; import java.awt.Color; import java.awt.Graphics2D; public class Pentagon extends ClosedFigure{ public Pentagon(Color color, BoundBox bbox, int thickness, Color backcolor) { super(color, bbox, thickness, backcolor); // TODO Auto-generated constructor stub } private static final long serialVersionUID = 1L; int [] heightPoints = {getBoundBox().y,getBoundBox().y + getBoundBox().height/3,getBoundBox().y + getBoundBox().height,getBoundBox().y + getBoundBox().height,getBoundBox().y + getBoundBox().height/3}; int [] weidthPoints = {getBoundBox().x + getBoundBox().width/2, getBoundBox().x + getBoundBox().width,getBoundBox().x + (2*getBoundBox().width)/3,getBoundBox().x + getBoundBox().width/3, getBoundBox().x}; @Override public void endPaint(Graphics2D g) { // TODO Auto-generated method stub g.drawPolygon(weidthPoints,heightPoints,5); } @Override public void fillBackGround(Graphics2D g) { // TODO Auto-generated method stub g.fillPolygon(weidthPoints, heightPoints, 5); } } <file_sep>/src/View/LineCreationTool.java package View; import java.awt.Point; import Controller.App; import Model.BoundBox; import Model.Figure; import Model.Line; public class LineCreationTool extends CreationTool { public Figure createFigure(Point ptPress, Point ptReleased) { Figure fig = new Line(App.getInstance().getThicknessColor(), new BoundBox(ptPress, ptReleased), 1); return fig; } } <file_sep>/src/View/MainFrame.java package View; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import javax.swing.JFrame; import javax.swing.WindowConstants; public class MainFrame extends JFrame { private static MainFrame mf; private MenuHelper mh; private Canvas cv; public static MainFrame getInstance() { if (mf == null) { mf = new MainFrame(); } return mf; } private MainFrame() { } public void init() { mf.setTitle("Paint proyect"); mf.setVisible(true); Toolkit screen = Toolkit.getDefaultToolkit(); Dimension dimension = screen.getScreenSize(); int widthD = dimension.width; int heightD = dimension.height; addMenuHelper(); addCanvas(); setBounds(widthD / 8, heightD / 8, widthD / 2, heightD / 2); mf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public void addCanvas() { cv = Canvas.getInstance(); this.add(cv, BorderLayout.CENTER); } public void addMenuHelper() { mh = MenuHelper.getInstance(); this.add(mh, BorderLayout.NORTH); } public void setActiveToolCanvas(int activeTool) { cv.setActiveTool(activeTool); } } <file_sep>/src/View/MenuHelper.java package View; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import Controller.App; public class MenuHelper extends JMenuBar{ private static MenuHelper menu; public static MenuHelper getInstance() { if (menu == null) { menu = new MenuHelper(); } return menu; } private MenuHelper() { super(); this.add(setFile()); this.add(setTool()); this.add(setColor()); } private JMenu setFile() { JMenu file = new JMenu("File"); JMenuItem snew = new JMenuItem("New"); JMenuItem sdelete = new JMenuItem("Delete"); JMenuItem sclose = new JMenuItem("Close"); file.add(snew); file.add(sdelete); file.add(sclose); sclose.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub System.exit(0); } }); return file; } private JMenu setTool() { JMenu tool = new JMenu("Tool"); JMenuItem circle = new JMenuItem("Circle"); JMenuItem rectangle = new JMenuItem("Rectangle"); JMenuItem phenta = new JMenuItem("Pentagon"); JMenuItem line = new JMenuItem("Line"); JMenuItem text = new JMenuItem("Text"); tool.add(circle); tool.add(rectangle); tool.add(phenta); tool.add(line); tool.add(text); circle.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub App.getInstance().setActiveTool(Canvas.ELLIPSE_CREATION_TOOL); } }); rectangle.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub App.getInstance().setActiveTool(Canvas.RECTANGLE_CREATION_TOOL); } }); phenta.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub App.getInstance().setActiveTool(Canvas.PENTAGON_CREATION_TOOL); } }); line.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub App.getInstance().setActiveTool(Canvas.LINE_CREATION_TOOL); } }); text.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub App.getInstance().setActiveTool(Canvas.TEXT_CREATION_TOOL); } }); return tool; } private JMenu setColor() { JMenu color = new JMenu("Color"); JMenuItem bc = new JMenuItem("Background color"); JMenuItem tc = new JMenuItem("Thickness color"); color.add(bc); color.add(tc); bc.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { App.getInstance().setBackGroundColor(); } }); tc.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { App.getInstance().setThicknessColor();; } }); return color; } } <file_sep>/src/View/Canvas.java package View; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.swing.JPanel; import Model.Drawing; import Model.Figure; public class Canvas extends JPanel implements CanvasListener { private static Canvas canvas; static final int LINE_CREATION_TOOL = 0; static final int ELLIPSE_CREATION_TOOL = 1; static final int RECTANGLE_CREATION_TOOL = 2; static final int TEXT_CREATION_TOOL = 3; static final int PENTAGON_CREATION_TOOL = 4; private Tools[] tools; private Tools activeTool; private List<CanvasListener> listeners = new LinkedList(); public static Canvas getInstance() { if (canvas == null) { canvas = new Canvas(); } return canvas; } private Canvas() { super(); setBackground(Color.WHITE); tools = new Tools[PENTAGON_CREATION_TOOL + 1]; tools[LINE_CREATION_TOOL] = new LineCreationTool(); tools[ELLIPSE_CREATION_TOOL] = new EllipseCreationTool(); tools[RECTANGLE_CREATION_TOOL] = new RectangleCreationTool(); tools[TEXT_CREATION_TOOL] = new TextCreationTool(); tools[PENTAGON_CREATION_TOOL] = new PentagonCreationTool(); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { activeTool.mousePressed(e); } @Override public void mouseReleased(MouseEvent e) { activeTool.mouseReleased(e); } }); } public void notifyListeners(CanvasEvent e) { Iterator<CanvasListener> iterator = listeners.iterator(); while (iterator.hasNext()) { iterator.next().update(e); } } public void setActiveTool(final int activeTool) { this.activeTool = tools[activeTool]; notifyListeners(CanvasEvent.TOOL_CHANGED); } public void paint(Graphics g) { super.paint(g); Iterator<Figure> it = Drawing.getInstance().getIterator(); while (it.hasNext()) { it.next().paint((Graphics2D) g); } } @Override public void update(CanvasEvent e) { this.repaint(); } } <file_sep>/src/View/EllipseCreationTool.java package View; import java.awt.Point; import Controller.App; import Model.BoundBox; import Model.Ellipse; import Model.Figure; public class EllipseCreationTool extends CreationTool { @Override public Figure createFigure(Point ptPress, Point ptReleased) { Figure fig = new Ellipse(App.getInstance().getThicknessColor(), new BoundBox(ptPress, ptReleased),1, App.getInstance().getBackGroundColor()); return fig; } } <file_sep>/src/View/CanvasListener.java package View; import View.CanvasListener.CanvasEvent; public interface CanvasListener { public enum CanvasEvent{ TOOL_CHANGED; } public abstract void update(CanvasEvent e); }
28fdf498a18b8d9c99e9f61a7055f1b66c5675b1
[ "Java" ]
7
Java
mbsuarezg/Proyecto
56b1751d863d0063f594dd3a78a4f37b7211adf5
91aacc5e1527792a61dcf26e1e57fc0f3e2ba49d
refs/heads/main
<repo_name>Glifu/PG-Projects<file_sep>/BackpackProblem/ProblemPlecakowyV2/ProblemPlecakowyV2.cpp ๏ปฟ// ProblemPlecakowyV2.cpp : Ten plik zawiera funkcjฤ™ โ€žmainโ€. W nim rozpoczyna siฤ™ i koล„czy wykonywanie programu. // #include <iostream> using namespace std; int plecaki(int n, int waga[], int wartosc[], int c, int i) { int wInc, wExc; if (i == n || waga[i] <= 0) { return 0; } if (waga[i] <= c) { wInc = plecaki(n, waga, wartosc, c - waga[i], i + 1) + wartosc[i]; wExc = plecaki(n, waga, wartosc, c, i + 1); if (wInc > wExc) { return wInc; } else { return wExc; } } else { wExc = plecaki(n, waga, wartosc, c, i + 1); return wExc; } }; int main() { int iloscAut; scanf("%d", &iloscAut); for (int a = 0; a < iloscAut; a++) { int iloscPrzedmiotow; scanf("%d", &iloscPrzedmiotow); int zarobek = -20; int pojemnosc=1; int waga[15]; int cena[15]; int stosunek[15]; for (int i = 0; i < iloscPrzedmiotow; i++) { scanf("%d", &cena[i]); } for (int i = 0; i < iloscPrzedmiotow; i++) { scanf("%d", &waga[i]); if (waga[i] > 100) { cena[i] = cena[i] - 5; } if (waga[i] == 0 || cena[i] == 0) { stosunek[i] = 0; } else { stosunek[i] = waga[i] / cena[i]; } } scanf("%d", &pojemnosc); for (int i = 0; i < iloscPrzedmiotow; i++) { int temp; if (waga[i] > pojemnosc) { temp = waga[i]; waga[i] = waga[iloscPrzedmiotow - 1]; waga[iloscPrzedmiotow - 1] = temp; temp = cena[i]; cena[i] = cena[iloscPrzedmiotow - 1]; cena[iloscPrzedmiotow - 1] = temp; temp = stosunek[i]; stosunek[i] = stosunek[iloscPrzedmiotow - 1]; stosunek[iloscPrzedmiotow - 1] = temp; iloscPrzedmiotow = iloscPrzedmiotow - 1; } } //Bubble Sort if (iloscPrzedmiotow < 0) { for (int i = iloscPrzedmiotow; i > 0; i--) { int temp; for (int j = 0; j < i - 1; j++) { if (stosunek[j] < stosunek[j + 1]) { temp = waga[j]; waga[i] = waga[j + 1]; waga[j + 1] = temp; temp = cena[j]; cena[j] = cena[j + 1]; cena[j + 1] = temp; temp = stosunek[j]; stosunek[j] = stosunek[j + 1]; stosunek[j + 1] = temp; iloscPrzedmiotow = iloscPrzedmiotow - 1; } } } } zarobek = zarobek + plecaki(iloscPrzedmiotow, waga, cena, pojemnosc, 0); if (zarobek < 0) { zarobek = 0; } printf( "%d\n" ,zarobek); } } // Uruchomienie programu: Ctrl + F5 lub menu Debugowanie > Uruchom bez debugowania // Debugowanie programu: F5 lub menu Debugowanie > Rozpocznij debugowanie // Porady dotyczฤ…ce rozpoczynania pracy: // 1. Uลผyj okna Eksploratora rozwiฤ…zaล„, aby dodaฤ‡ pliki i zarzฤ…dzaฤ‡ nimi // 2. Uลผyj okna programu Team Explorer, aby nawiฤ…zaฤ‡ poล‚ฤ…czenie z kontrolฤ… ลบrรณdล‚a // 3. Uลผyj okna Dane wyjล›ciowe, aby sprawdziฤ‡ dane wyjล›ciowe kompilacji i inne komunikaty // 4. Uลผyj okna Lista bล‚ฤ™dรณw, aby zobaczyฤ‡ bล‚ฤ™dy // 5. Wybierz pozycjฤ™ Projekt > Dodaj nowy element, aby utworzyฤ‡ nowe pliki kodu, lub wybierz pozycjฤ™ Projekt > Dodaj istniejฤ…cy element, aby dodaฤ‡ istniejฤ…ce pliku kodu do projektu // 6. Aby w przyszล‚oล›ci ponownie otworzyฤ‡ ten projekt, przejdลบ do pozycji Plik > Otwรณrz > Projekt i wybierz plik sln <file_sep>/BackpackProblem/ProblemPlecakowy/ProblemPlecakowy.cpp ๏ปฟ// ProblemPlecakowy.cpp : Ten plik zawiera funkcjฤ™ โ€žmainโ€. W nim rozpoczyna siฤ™ i koล„czy wykonywanie programu. // #include <iostream> #include <queue> using namespace std; struct Przedmiot { double waga; //Waga danego przedmiotu double cena; //Cena danego przedmiotu double stosunek; //Stosunek ceny do Wagi void liczStosunek() { stosunek = cena / waga; } }; int main() { int iloscAut; int iloscPrzedmiotow; queue <double> wyniki; cin >> iloscAut; for (int licznik = 0; licznik < iloscAut; licznik++) { double zarobek = 0; double udzwigAut = 0; Przedmiot A[15]; zarobek = zarobek - 20; cin >> iloscPrzedmiotow; for (int i = 0; i < iloscPrzedmiotow; i++) { cin >> A[i].cena; } for (int i = 0; i < iloscPrzedmiotow; i++) { cin >> A[i].waga; } cin >> udzwigAut; for (int i = 0; i < iloscPrzedmiotow; i++) { if (A[i].waga > 100) { A[i].cena = A[i].cena - 5; } A[i].liczStosunek(); } if (iloscPrzedmiotow > 1) { for (int i = iloscPrzedmiotow; i > 0; i--) { for (int j = 0; j < i - 1; j++) { if (A[j].stosunek < A[j + 1].stosunek) { swap(A[j], A[j + 1]); } } } } for (int i = 0; i < iloscPrzedmiotow; i++) { if (udzwigAut - A[i].waga >= 0) { zarobek = zarobek + A[i].cena; udzwigAut = udzwigAut - A[i].waga; } } if (zarobek < 0) { zarobek = 0; } wyniki.push(zarobek); } for (int i = 0; i < iloscAut; i++) { cout << wyniki.front() << endl; wyniki.pop(); } } <file_sep>/SectSim/Sekta/Sekta.KtoraDzialaJakoscpp.cpp ๏ปฟ// Sekta.cpp : Ten plik zawiera funkcjฤ™ โ€žmainโ€. W nim rozpoczyna siฤ™ i koล„czy wykonywanie programu. // #include <iostream> #include <list> using namespace std; struct listaCykliczna { int data; struct listaCykliczna* nastepnik; }; void lista_next(listaCykliczna* glowa) { glowa = glowa->nastepnik; } int selekcjaSekty(int k, listaCykliczna* lista, int coDrugi, listaCykliczna* poprzednik = nullptr) { int coZostaloWyjebane; if (coDrugi % 2 == 1) { // && k=!0 coZostaloWyjebane = lista->data; poprzednik->nastepnik = lista->nastepnik; //usuniecie elementu z listy if ( k ==1 || k == 0 ) { return coZostaloWyjebane; } } poprzednik = lista; //Niezaleznie co sie dzieje idziemy do kolejnego elementu if (k != 0) { if (coDrugi % 2 == 1) { coDrugi++; selekcjaSekty(k - 1, lista->nastepnik, coDrugi, poprzednik); } else { coDrugi++; selekcjaSekty(k, lista->nastepnik, coDrugi, poprzednik); } } }; int main() { int iloscWejsc; int iloscOsob=11; int zgadywanaPozycja=-1; //cin >> iloscWejsc; //cout << endl; //cin >> iloscOsob >> zgadywanaPozycja; // Inichjalizacja// listaCykliczna* glowa = new listaCykliczna; listaCykliczna* poczatek = new listaCykliczna; glowa->data = 1; glowa->nastepnik = glowa; poczatek = glowa; //listaCykliczna* nowy = new listaCykliczna; //nowy->data = 7; //nowy->nastepnik = poczatek; //glowa->nastepnik = nowy; //glowa = nowy; //cout << glowa->data; //listaCykliczna* nowy2 = new listaCykliczna; //nowy2->data = 16; //nowy2->nastepnik = poczatek; //glowa->nastepnik = nowy2; //glowa = nowy2; if (zgadywanaPozycja < 0) { //konwersja ujemnej pozycji zgadywanaPozycja = (iloscOsob+1)+zgadywanaPozycja; } for (int i = 2; i <= iloscOsob ; i++) { //zapelnienie kolejki listaCykliczna* nowy = new listaCykliczna; nowy->data = i; nowy->nastepnik = poczatek; glowa->nastepnik = nowy; glowa = nowy; } lista_next(glowa); glowa = glowa->nastepnik; for (int i = 0; i < iloscOsob; i++) { //sprawdzenie dzialania kolejki cout << glowa->data << endl; glowa = glowa->nastepnik; } cout << selekcjaSekty(zgadywanaPozycja, poczatek, 0); //cout << glowa->data; //cout << endl << iloscOsob[i] << " " << zgadywanaPozycja[i]; } // Uruchomienie programu: Ctrl + F5 lub menu Debugowanie > Uruchom bez debugowania // Debugowanie programu: F5 lub menu Debugowanie > Rozpocznij debugowanie // Porady dotyczฤ…ce rozpoczynania pracy: // 1. Uลผyj okna Eksploratora rozwiฤ…zaล„, aby dodaฤ‡ pliki i zarzฤ…dzaฤ‡ nimi // 2. Uลผyj okna programu Team Explorer, aby nawiฤ…zaฤ‡ poล‚ฤ…czenie z kontrolฤ… ลบrรณdล‚a // 3. Uลผyj okna Dane wyjล›ciowe, aby sprawdziฤ‡ dane wyjล›ciowe kompilacji i inne komunikaty // 4. Uลผyj okna Lista bล‚ฤ™dรณw, aby zobaczyฤ‡ bล‚ฤ™dy // 5. Wybierz pozycjฤ™ Projekt > Dodaj nowy element, aby utworzyฤ‡ nowe pliki kodu, lub wybierz pozycjฤ™ Projekt > Dodaj istniejฤ…cy element, aby dodaฤ‡ istniejฤ…ce pliku kodu do projektu // 6. Aby w przyszล‚oล›ci ponownie otworzyฤ‡ ten projekt, przejdลบ do pozycji Plik > Otwรณrz > Projekt i wybierz plik sln <file_sep>/GraphColoring/Grafy_v2/Grafy_v2.cpp ๏ปฟ// Grafy.cpp : Ten plik zawiera funkcjฤ™ โ€žmainโ€. W nim rozpoczyna siฤ™ i koล„czy wykonywanie programu. // #include <iostream> using namespace std; int main() { //Data Holder int graphSize = 0; char inputData; //For input int numberOfInputs; //For output //int graphGradeCounter = 0; std::ios::sync_with_stdio(false); cin >> numberOfInputs; for (int programCyclces = 0; programCyclces < numberOfInputs; programCyclces++) { bool czyCykl = true; bool czyPelny = true; bool czyNieParzysty = true; int zeroCounter = 0; int oneCounter = 0; cin >> graphSize; if (graphSize % 2 == 0) { czyNieParzysty = false; } int graphLongSize = graphSize * graphSize; for (int i = 0; i < graphLongSize; i++) { cin >> inputData; if (inputData == '0' && czyPelny == true) { zeroCounter++; if (zeroCounter > graphSize) { czyPelny = false; } } else if (inputData == '1') { oneCounter++; } if ((i % graphSize) == (graphSize - 1)) { if (oneCounter != 2 && czyPelny == false) { czyCykl = false; cin.ignore(graphLongSize - i); goto TestowaEtykieta; } else { oneCounter = 0; } } } //if (i%graphSize == graphSize-1) { // cout << i << " | Czy jest cyklem: " << czyCykl << " Czy jest Pelny: " << czyPelny << " Czy jest nieparzysty: " << graphSize % 2 << endl; //} TestowaEtykieta: if ((czyCykl == 1 && czyNieParzysty == 1) || czyPelny == 1) { cout << "True\n"; } else { cout << "False\n"; } } }<file_sep>/BackpackProblem/ProblemPlecakowy_v4/ProblemPlecakowy_v4.cpp ๏ปฟ// ProblemPlecakowy_v4.cpp : Ten plik zawiera funkcjฤ™ โ€žmainโ€. W nim rozpoczyna siฤ™ i koล„czy wykonywanie programu. // #include <iostream> int weight[15]; int price[15]; int backPack(int remainingWeight, int indexNumber, int numberOfItems) { if (remainingWeight == 0 || indexNumber == numberOfItems) { return 0; } if (weight[indexNumber] > remainingWeight) { return backPack(remainingWeight, indexNumber + 1, numberOfItems); } int wInc, wExc; // weightInclude weightExclude wInc = price[indexNumber] + backPack(remainingWeight-weight[indexNumber], indexNumber + 1, numberOfItems); wExc = backPack(remainingWeight, indexNumber + 1, numberOfItems); if (wInc > wExc) { return wInc; } else { return wExc; } }; int main() { int numberOfInputs; int numberOfItems; int carCapacity; int result; scanf("%d", &numberOfInputs); for (int i = 0; i < numberOfInputs; i++) { scanf("%d", &numberOfItems); for (int a = 0; a < numberOfItems; a++) { scanf("%d", &price[a]); } for (int a = 0; a < numberOfItems; a++) { scanf("%d", &weight[a]); if ( weight[a] > 100){ price[a] = price[a] - 5; } } scanf("%d", &carCapacity); int profit = -20; profit = profit + backPack(carCapacity, 0, numberOfItems); if (profit < 0) { profit = 0; } printf("%d\n", profit); } }<file_sep>/WagonProblem/main.cpp // WagonLista.cpp : Ten plik zawiera funkcjฤ™ โ€žmainโ€. W nim rozpoczyna siฤ™ i koล„czy wykonywanie programu. // #include "pch.h" #include <iostream> using namespace std; struct Wezel { int data; struct Wezel *next; }; int main() { int n, we, wy=0; // int bocznica = 0; Wezel *glowa; glowa = nullptr; // cout << "\nTest adresu: " << glowa << endl; cin >> n; for (int i = 0; i < (2*n) ;i++) { if(i < n) { cin >> we; } else { we = NULL; } if ((wy+1) == we && we != NULL) { wy = we; // cout << "Z wejscia na Wejscie" << endl; } else if(glowa != nullptr && (wy+1) == glowa->data) { wy = glowa->data; glowa->data = NULL; glowa = glowa->next; // cout << "Z bocznicy na Wyjscie;" << endl; } else if( we != NULL ){ Wezel *nowy = new Wezel; nowy->data = we; nowy->next = glowa; glowa = nowy; // cout << "\nNa bocznice" << endl; // cout << "nowyData: " << nowy->data << " nowyAdres: " << nowy->next << " Glowa: " << glowa << endl; } } if (glowa != nullptr) { // cout << "Bocznica: " << bocznica << endl; cout << "NIE"; } else { cout << "TAK"; } } // Uruchomienie programu: Ctrl + F5 lub menu Debugowanie > Uruchom bez debugowania // Debugowanie programu: F5 lub menu Debugowanie > Rozpocznij debugowanie // Porady dotyczฤ…ce rozpoczynania pracy: // 1. Uลผyj okna Eksploratora rozwiฤ…zaล„, aby dodaฤ‡ pliki i zarzฤ…dzaฤ‡ nimi // 2. Uลผyj okna programu Team Explorer, aby nawiฤ…zaฤ‡ poล‚ฤ…czenie z kontrolฤ… ลบrรณdล‚a // 3. Uลผyj okna Dane wyjล›ciowe, aby sprawdziฤ‡ dane wyjล›ciowe kompilacji i inne komunikaty // 4. Uลผyj okna Lista bล‚ฤ™dรณw, aby zobaczyฤ‡ bล‚ฤ™dy // 5. Wybierz pozycjฤ™ Projekt > Dodaj nowy element, aby utworzyฤ‡ nowe pliki kodu, lub wybierz pozycjฤ™ Projekt > Dodaj istniejฤ…cy element, aby dodaฤ‡ istniejฤ…ce pliku kodu do projektu // 6. Aby w przyszล‚oล›ci ponownie otworzyฤ‡ ten projekt, przejdลบ do pozycji Plik > Otwรณrz > Projekt i wybierz plik sln<file_sep>/README.md # PG-Projects Some completed projects, mostly algorythmic problems. (C++) <file_sep>/BackpackProblem/ProblemPlecakowy_v3/ProblemPlecakowy_v3.cpp ๏ปฟ#include <iostream> using namespace std; short value[15]; short weight[15]; short tests, n, capacity, result; short inline max(short n1, short n2) { return n1 > n2 ? n1 : n2; } short package(short localWeight, short index = 0) { if (localWeight == 0 || index == n) return 0; if (weight[index] > localWeight) return package(localWeight, index + 1); short rightMax = (weight[index] <= 100 ? value[index] : value[index] - 5) + package(localWeight - weight[index], index + 1); short leftMax = package(localWeight, index + 1); return max(leftMax, rightMax); } int main() { scanf("%hi", &tests); while (tests--) { scanf("%hi", &n); for (int i = 0; i < n; i++) { scanf("%hi", &value[i]); } for (int i = 0; i < n; i++) { scanf("%hi", &weight[i]); } scanf("%hi", &capacity); result = package(capacity) - 20; printf("%i\n", result > 0 ? result : 0); } return 0; }<file_sep>/StackMachine/main_v2.cpp // PoProstu2.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include <iostream> using namespace std; struct Wezel { int data; struct Wezel *next; }; int main() { char a='d'; int ia; Wezel *glowa; glowa = nullptr; Wezel *temp; cout << "\nTest adresu: " << glowa << endl; while (a != 'q') { cout << "\n\nPodaj wartosc: "; cin >> a; ia = (int)a - 48; Wezel nowy; if (0 <= ia && ia <= 9) { nowy.data = ia; // ia -> int z A, nowy.next = glowa; glowa = &nowy; cout << "Data: " << nowy.data << " Adres: " << nowy.next << " Glowa: " << glowa << endl; } else { switch (a) { case 'r': cout << "r - zdjecie ze stosu liczby n, przeniesienie liczby z wierzcholka stosu na n-te miejsce liczac od wierzcholka; 0 r oraz 1 r nic nie robi, 2 r jest tozsame z s, 3 r zamienia 3 2 1 na 2 1 3 itd. "; break; case 'p': cout << "p - wypisanie stosu\n"; temp = glowa; while (temp != nullptr) { cout << temp->data << " " ; temp = nowy.next; } break; case 's': cout << "s - zamiana miejscami dwoch licz na szczyciestosu"; break; case 'x': cout << "x - usuniecie liczby z wierzchu stosu"; break; case '+': cout << "+ - zdjecie dwoch liczb ze stosu i wlozenie na stos ich sumy"; break; case 'q': cout << "Nastapi zakonczenie programu"; break; default: break; } } if (glowa == nullptr) { cout << "\n**Lista jest pusta**\n"; } else { cout << "\nWartosc ostatniego elementu w liscie: " << glowa->data; } /* for (int j = 0; j < n; j++) { cout << "Wielkosc elementu " << j << ": " << stos[j] << endl; } int *wsk; //wsk = &stos[5]; cout << "\n\nTest case: " << *wsk << " " << wsk; */ } } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file<file_sep>/MinMax/MinMax.cpp #include <iostream> using namespace std; struct przedzial { short int poczatek; short int koniec; }; void minmax(int poczatek, int koniec, int *tablica, int min, int max); int main() { int wielkosc; cin >> wielkosc; int *ciag; ciag = new int[wielkosc]; for (int i = 0; i < wielkosc; i++) { cin >> ciag[i]; } int iloscZ;//ilosc wczytywanych par cin >> iloscZ; przedzial *zapytanie; zapytanie = new przedzial[iloscZ]; // tablica wczytywanych par for (int i = 0; i < iloscZ; i++) { cin >> zapytanie[i].poczatek; cin >> zapytanie[i].koniec; } int min = NULL; int max = NULL; for (int i = 0; i < iloscZ; i++) { minmax(zapytanie[i].poczatek, zapytanie[i].koniec, ciag, min, max); } //cout << "\n" << ciag[5]; //cout << "Test : " << 1 % 2; delete[] ciag; delete[] zapytanie; } void minmax(int poczatek, int koniec, int *tablica, int min, int max){ min = tablica[poczatek]; max = tablica[poczatek]; while (poczatek < koniec+1) { if (max < tablica[poczatek]) { max = tablica[poczatek]; } if (min > tablica[poczatek]) { min = tablica[poczatek]; } poczatek++; //return minmax(poczatek + 1, koniec, tablica, min, max); } cout << min << " " << max << endl; }
d72f082531e1d1a276d8cfea5e67e57bfe6b0888
[ "Markdown", "C++" ]
10
C++
Glifu/PG-Projects
ad4996808caf88f934580201d505c116980a5b76
400d257225d493eeb337f8389b5747c6eca2678b
refs/heads/master
<file_sep>๏ปฟ// ****************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE IS PROVIDED โ€œAS ISโ€, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH // THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // ****************************************************************** using System; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace Microsoft.Toolkit.Uwp.UI.Controls { /// <summary> /// Class used to display glTF models /// </summary> [TemplatePart(Name = WebViewPart, Type = typeof(WebView))] [TemplatePart(Name = CommandGridPart, Type = typeof(Grid))] [TemplatePart(Name = AnimationListPart, Type = typeof(ComboBox))] [TemplatePart(Name = AnimationSliderPart, Type = typeof(Slider))] [TemplatePart(Name = PlaySymbolPart, Type = typeof(SymbolIcon))] [TemplatePart(Name = PauseSymbolPart, Type = typeof(SymbolIcon))] [TemplatePart(Name = PlayPauseButtonPart, Type = typeof(Button))] public sealed class Model3D : Control { private WebView _view; private ComboBox _animationList; private Grid _commandGrid; private Slider _animationSlider; private SymbolIcon _playSymbol; private SymbolIcon _pauseSymbol; private Button _playPauseButton; private bool _sliderLayoutUpdated = false; private double _lastValueSetFromAnimation = 0; /// <summary> /// Event raised when the assets are loading /// </summary> public event EventHandler AssetLoading; /// <summary> /// Event raised when assets are loaded /// </summary> public event EventHandler AssetLoaded; /// <summary> /// Initializes a new instance of the <see cref="Model3D"/> class /// </summary> public Model3D() { DefaultStyleKey = typeof(Model3D); } /// <summary> /// Invoked whenever application code or internal processes (such as a rebuilding layout pass) call /// ApplyTemplate. In simplest terms, this means the method is called just before a UI element displays /// in your app. Override this method to influence the default post-template logic of a class. /// </summary> protected override void OnApplyTemplate() { if (_view != null) { _view.ScriptNotify -= View_ScriptNotify; _view.NavigationCompleted -= View_NavigationCompleted; } if (_playPauseButton != null) { _playPauseButton.Click -= PlayPauseButton_Click; } if (_animationList != null) { _animationList.SelectionChanged -= AnimationList_SelectionChanged; } if (_animationSlider != null) { _animationSlider.LayoutUpdated -= AnimationSlider_LayoutUpdated; _animationSlider.ValueChanged -= AnimationSlider_ValueChanged; } base.OnApplyTemplate(); _view = GetTemplateChild(WebViewPart) as WebView; if (_view != null) { _view.ScriptNotify += View_ScriptNotify; _view.NavigationCompleted += View_NavigationCompleted; _view.Navigate(new Uri("ms-appx-web:///CrossDeviceExpDemo.Shared/Controls/Model3D/BabylonView.html")); } _animationList = GetTemplateChild(AnimationListPart) as ComboBox; if (_animationList != null) { _animationList.SelectionChanged += AnimationList_SelectionChanged; } _commandGrid = GetTemplateChild(CommandGridPart) as Grid; _playSymbol = GetTemplateChild(PlaySymbolPart) as SymbolIcon; _pauseSymbol = GetTemplateChild(PauseSymbolPart) as SymbolIcon; _animationSlider = GetTemplateChild(AnimationSliderPart) as Slider; if (_animationSlider != null) { _animationSlider.Minimum = 0; _animationSlider.Maximum = 100; _animationSlider.LayoutUpdated += AnimationSlider_LayoutUpdated; _animationSlider.ValueChanged += AnimationSlider_ValueChanged; } _playPauseButton = GetTemplateChild(PlayPauseButtonPart) as Button; if (_playPauseButton != null) { _playPauseButton.Click += PlayPauseButton_Click; } } private static async void OnCameraControlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { await (d as Model3D).UpdateCameraControlAsync(); } private static async void OnRadiusValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { await (d as Model3D).UpdateRadiusAsync(); } private static async void OnCameraValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { await (d as Model3D).UpdateCameraAsync(); } private static async void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { await (d as Model3D).SetupSourceAsync(); } private static async void OnEnvironmentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { await (d as Model3D).UpdateEnvironment(); } private async void AnimationSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e) { if (e.NewValue == _lastValueSetFromAnimation) { // This is an animated value return; } await _view.InvokeScriptAsync("goToFrame", new string[] { (e.NewValue / 100.0).ToString() }); } private async void AnimationList_SelectionChanged(object sender, SelectionChangedEventArgs e) { await _view.InvokeScriptAsync("switchToAnimationGroup", new string[] { _animationList.SelectedIndex.ToString() }); await Play(); } private void AnimationSlider_LayoutUpdated(object sender, object e) { // We will use it to prevent layout cycle exception _sliderLayoutUpdated = true; } private async Task Pause() { _playSymbol.Visibility = Visibility.Visible; _pauseSymbol.Visibility = Visibility.Collapsed; await _view.InvokeScriptAsync("pauseAnimations", new string[] { }); } private async Task Play() { _playSymbol.Visibility = Visibility.Collapsed; _pauseSymbol.Visibility = Visibility.Visible; await _view.InvokeScriptAsync("playAnimations", new string[] { }); } private async void PlayPauseButton_Click(object sender, RoutedEventArgs e) { if (_playSymbol == null || _pauseSymbol == null) { return; } if (_playSymbol.Visibility == Visibility.Collapsed) { // Let's pause await Pause(); } else { // Or play await Play(); } } private async void View_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args) { await SetupSourceAsync(); await UpdateCameraAsync(); await UpdateRadiusAsync(); await UpdateCameraControlAsync(); await UpdateEnvironment(); } private void View_ScriptNotify(object sender, NotifyEventArgs e) { var key = e.Value.Substring(0, 4); var value = e.Value.Substring(4); switch (key) { // Loading assets case "LOAD": { AssetLoading?.Invoke(this, EventArgs.Empty); break; } // Assets loaded case "LODD": { _view.Opacity = 1; AssetLoaded?.Invoke(this, EventArgs.Empty); break; } // Camera alpha angle in radians case "ALPH": { AlphaInDegrees = GetDegreeFromRadian(double.Parse(value)); break; } // Camera beta angle in radians case "BETA": { BetaInDegrees = GetDegreeFromRadian(double.Parse(value)); break; } // Camera radius case "RADI": { RadiusPercentage = double.Parse(value); break; } // Animations are supported case "ANIM": { if (_commandGrid == null) { return; } _commandGrid.Visibility = Visibility.Visible; var animationNames = value.Split(','); if (_animationList != null) { _animationList.Items.Clear(); foreach (var animName in animationNames) { _animationList.Items.Add(animName); } _animationList.SelectedIndex = 0; _playSymbol.Visibility = Visibility.Collapsed; _pauseSymbol.Visibility = Visibility.Visible; } break; } // No animation case "NANM": { if (_commandGrid != null) { _commandGrid.Visibility = Visibility.Collapsed; } break; } // Current animation frame case "FRAM": { if (_animationSlider == null || !_sliderLayoutUpdated) { return; } var position = Math.Min(1, Math.Max(0, double.Parse(value))); // Making sure we are not overwhelming the system _sliderLayoutUpdated = false; _lastValueSetFromAnimation = position * 99.0; _animationSlider.Value = _lastValueSetFromAnimation; break; } } } private async Task SetupSourceAsync() { if (_view == null || string.IsNullOrWhiteSpace(Source)) { return; } string root = null, fileName = null; if (Uri.TryCreate(Source, UriKind.Relative, out var uri)) { root = "ms-appx-web:///"; int slashIndex = 0; while (Source[slashIndex] == '/') { slashIndex++; } fileName = Source.Substring(slashIndex); } else if (Uri.TryCreate(Source, UriKind.Absolute, out uri)) { var scheme = uri.Scheme == "ms-appx" ? "ms-appx-web" : uri.Scheme; root = $"{scheme}://{uri.Authority}/"; int slashIndex = 0; while (uri.LocalPath[slashIndex] == '/') { slashIndex++; } fileName = uri.LocalPath.Substring(slashIndex); } else { return; } await _view.InvokeScriptAsync("setupSource", new string[] { root, fileName }); } private async Task UpdateEnvironment() { if (_view == null || string.IsNullOrWhiteSpace(Environment)) { return; } await _view.InvokeScriptAsync("updateEnvironment", new string[] { Environment }); } private async Task UpdateCameraAsync() { if (_view == null) { return; } var alpha = GetRadianFromDegree(AlphaInDegrees); var beta = GetRadianFromDegree(BetaInDegrees); await _view.InvokeScriptAsync("updateCameraPositionValues", new string[] { alpha.ToString(), beta.ToString() }); } private async Task UpdateRadiusAsync() { if (_view == null) { return; } await _view.InvokeScriptAsync("updateCameraRadiusValue", new string[] { RadiusPercentage.ToString() }); } private async Task UpdateCameraControlAsync() { if (_view == null) { return; } await _view.InvokeScriptAsync("updateCameraControl", new string[] { CameraControl.ToString() }); } private double GetRadianFromDegree(double degrees) { return degrees / 180d * Math.PI; } private double GetDegreeFromRadian(double radians) { var value = (radians * 180d / Math.PI) % 360f; if (value < 0) { value += 360f * Math.Ceiling(Math.Abs(value / 360.0f)); } return value; } /// <summary> /// Gets or sets a string indicating the source path for the model /// </summary> public string Source { get { return (string)GetValue(SourceProperty); } set { SetValue(SourceProperty, value); } } /// <summary> /// Identifies the <see cref="Source"/> property /// </summary> public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(string), typeof(Model3D), new PropertyMetadata(string.Empty, OnSourceChanged)); /// <summary> /// Gets or sets a string indicating the path for the environment texture (must be a DDS file) /// </summary> public string Environment { get { return (string)GetValue(EnvironmentProperty); } set { SetValue(EnvironmentProperty, value); } } /// <summary> /// Identifies the <see cref="Environment"/> property /// </summary> public static readonly DependencyProperty EnvironmentProperty = DependencyProperty.Register("Environment", typeof(string), typeof(Model3D), new PropertyMetadata(string.Empty, OnEnvironmentChanged)); /// <summary> /// Gets or sets a double value indicating the alpha angle in degrees (which defines the rotation on horizontal plane) /// </summary> public double AlphaInDegrees { get { return (double)GetValue(AlphaInDegreesProperty); } set { SetValue(AlphaInDegreesProperty, value); } } /// <summary> /// Identifies the <see cref="AlphaInDegrees"/> property /// </summary> public static readonly DependencyProperty AlphaInDegreesProperty = DependencyProperty.Register("AlphaInDegrees", typeof(double), typeof(Model3D), new PropertyMetadata(90f, OnCameraValueChanged)); /// <summary> /// Gets or sets a double value indicating the beta angle in degrees (which defines the rotation on vertical plane) /// </summary> public double BetaInDegrees { get { return (double)GetValue(BetaInDegreesProperty); } set { SetValue(BetaInDegreesProperty, value); } } /// <summary> /// Identifies the <see cref="BetaInDegrees"/> property /// </summary> public static readonly DependencyProperty BetaInDegreesProperty = DependencyProperty.Register("BetaInDegrees", typeof(double), typeof(Model3D), new PropertyMetadata(90f, OnCameraValueChanged)); /// <summary> /// Gets or sets a double value between 0 and 100 indicating the distance from the center of the scene /// </summary> public double RadiusPercentage { get { return (double)GetValue(RadiusPercentageProperty); } set { SetValue(RadiusPercentageProperty, value); } } /// <summary> /// Identifies the <see cref="RadiusPercentage"/> property /// </summary> public static readonly DependencyProperty RadiusPercentageProperty = DependencyProperty.Register("RadiusPercentage", typeof(double), typeof(Model3D), new PropertyMetadata(5f, OnRadiusValueChanged)); /// <summary> /// Gets or sets a value indicating whether the camera can be controlled with pointers (mouse, touch, pencil) or not /// </summary> public bool CameraControl { get { return (bool)GetValue(CameraControlProperty); } set { SetValue(CameraControlProperty, value); } } /// <summary> /// Identifies the <see cref="CameraControl"/> property /// </summary> public static readonly DependencyProperty CameraControlProperty = DependencyProperty.Register("CameraControl", typeof(bool), typeof(Model3D), new PropertyMetadata(true, OnCameraControlChanged)); /// <summary> /// Key of the UI Element that contains the webview /// </summary> private const string WebViewPart = "PART_WebView"; /// <summary> /// Key of the UI Element that contains the command grid /// </summary> private const string CommandGridPart = "PART_CommandGrid"; /// <summary> /// Key of the UI Element that contains the list of animations /// </summary> private const string AnimationListPart = "PART_AnimationList"; /// <summary> /// Key of the UI Element that contains the animation slider /// </summary> private const string AnimationSliderPart = "PART_AnimationSlider"; /// <summary> /// Key of the UI Element that contains the play/pause button /// </summary> private const string PlayPauseButtonPart = "PART_PlayPauseButton"; /// <summary> /// Key of the UI Element that contains the play symbol /// </summary> private const string PlaySymbolPart = "PART_PlaySymbol"; /// <summary> /// Key of the UI Element that contains the play symbol /// </summary> private const string PauseSymbolPart = "PART_PauseSymbol"; } }<file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Numerics; using Windows.UI.Composition; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Shapes; namespace CrossDeviceExpDemo.Shared.Controls { public sealed partial class AnimatedBubbleBackground : UserControl { public AnimatedBubbleBackground() { InitializeComponent(); TopRectangles.Add(Rectangle3); TopRectangles.Add(Rectangle4); BottomRectangles.Add(Rectangle1); BottomRectangles.Add(Rectangle2); Loaded += OnLoaded; SizeChanged += OnSizeChanged; } private List<Rectangle> TopRectangles { get; } = new List<Rectangle>(); private List<Rectangle> BottomRectangles { get; } = new List<Rectangle>(); private void OnLoaded(object sender, RoutedEventArgs e) { var compositor = Window.Current.Compositor; var rotationAnimation = compositor.CreateScalarKeyFrameAnimation(); var linear = compositor.CreateLinearEasingFunction(); rotationAnimation.InsertKeyFrame(1.0f, 360, linear); rotationAnimation.Duration = TimeSpan.FromSeconds(9); rotationAnimation.Target = nameof(Rectangle1.Rotation); rotationAnimation.IterationBehavior = AnimationIterationBehavior.Forever; Rectangle1.StartAnimation(rotationAnimation); Rectangle3.StartAnimation(rotationAnimation); rotationAnimation.Duration = TimeSpan.FromSeconds(8); Rectangle2.StartAnimation(rotationAnimation); Rectangle4.StartAnimation(rotationAnimation); } private void OnSizeChanged(object sender, SizeChangedEventArgs e) { foreach (var rectangle in TopRectangles) { var min = Math.Min(ActualWidth, ActualHeight); rectangle.Width = rectangle.Height = min * 0.8; rectangle.RadiusX = rectangle.Width * 0.49; rectangle.RadiusY = rectangle.Height * 0.45; Canvas.SetLeft(rectangle, ActualWidth - rectangle.Width * 0.4); Canvas.SetTop(rectangle, -rectangle.Height + rectangle.Height * 0.4); rectangle.CenterPoint = new Vector3((float)rectangle.Width / 2, (float)rectangle.Height / 2, 0); } foreach (var rectangle in BottomRectangles) { var min = Math.Min(ActualWidth, ActualHeight); rectangle.Width = rectangle.Height = min * 1.2; rectangle.RadiusX = rectangle.Width * 0.49; rectangle.RadiusY = rectangle.Height * 0.45; Canvas.SetLeft(rectangle, -rectangle.Width * 0.4); Canvas.SetTop(rectangle, ActualHeight - rectangle.Height + rectangle.Height * 0.4); rectangle.CenterPoint = new Vector3((float)rectangle.Width / 2, (float)rectangle.Height / 2, 0); } } } }<file_sep>๏ปฟusing CrossDeviceExpDemo.Shared.Models; using System; using System.Collections.ObjectModel; using System.Numerics; using System.Threading.Tasks; using Windows.UI.Composition; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Hosting; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Shapes; namespace CrossDeviceExpDemo.Main { public sealed partial class MainPage : Page { private ObservableCollection<Product> MyProducts { get; } = new ObservableCollection<Product> { //new Product("Ankylosaurus.glb", "Ankylosaurus"), //new Product("Apatosaurus.glb", "Apatosaurus"), //new Product("Pterodactyl.glb", "Pterodactyl"), //new Product("Triceratops.glb", "Triceratops"), new Product("TyrannosaurusRex.glb", "Tyrannosaurus Rex"), //new Product("Velociraptor.glb", "Velociraptor") }; public MainPage() { InitializeComponent(); Loaded += MainPage_Loaded; } private async void MainPage_Loaded(object sender, RoutedEventArgs e) { await Task.Delay(1000); } private void OnVisualPlaceholderLoaded(object sender, RoutedEventArgs e) { Compositor compositor = Window.Current.Compositor; Rectangle visualPlaceholder = (Rectangle)sender; if (visualPlaceholder.DataContext is Product product) { //var spatialVisual = compositor.CreateSpriteVisual(); //spatialVisual.Brush = compositor.CreateColorBrush(Colors.LightBlue); var spatialVisual = compositor.CreateSpatialVisual(); spatialVisual.LoadModel(product.ModelPathLocal); spatialVisual.RelativeSizeAdjustment = Vector2.One; spatialVisual.CenterPoint = new Vector3(visualPlaceholder.RenderSize.ToVector2() * 0.5f, 0.5f); spatialVisual.RotationAxis = new Vector3(0.0f, 1.0f, 0.0f); //spatialVisual.RotationAngleInDegrees = 90.0f; ScalarKeyFrameAnimation rotationAnimation = compositor.CreateScalarKeyFrameAnimation(); rotationAnimation.InsertKeyFrame(1.0f, 360.0f, compositor.CreateLinearEasingFunction()); rotationAnimation.Duration = TimeSpan.FromMilliseconds(4000); rotationAnimation.IterationBehavior = AnimationIterationBehavior.Forever; spatialVisual.StartAnimation(nameof(Visual.RotationAngleInDegrees), rotationAnimation); ElementCompositionPreview.SetElementChildVisual(visualPlaceholder, spatialVisual); } else { product = new Product("house.glb", "<NAME>"); var spatialVisual = compositor.CreateSpatialVisual(); spatialVisual.LoadModel(product.ModelPathLocal); spatialVisual.RelativeSizeAdjustment = Vector2.One; spatialVisual.CenterPoint = new Vector3(visualPlaceholder.RenderSize.ToVector2() * 0.5f, 75.0f); spatialVisual.RotationAxis = new Vector3(1.0f, 1.0f, 0.0f); //spatialVisual.RotationAngleInDegrees = 45.0f; float radianPerDegree = (float)Math.PI / 180.0f; var xRotation = Quaternion.CreateFromAxisAngle(new Vector3(1.0f, 0.0f, 0.0f), radianPerDegree * -15.0f); var yRotation = Quaternion.CreateFromAxisAngle(new Vector3(0.0f, 1.0f, 0.0f), radianPerDegree * 45.0f); spatialVisual.Orientation = Quaternion.Multiply(xRotation, yRotation); //ScalarKeyFrameAnimation rotationAnimation = compositor.CreateScalarKeyFrameAnimation(); //rotationAnimation.InsertKeyFrame(1.0f, 360.0f, compositor.CreateLinearEasingFunction()); //rotationAnimation.Duration = TimeSpan.FromMilliseconds(4000); //rotationAnimation.IterationBehavior = AnimationIterationBehavior.Forever; //spatialVisual.StartAnimation(nameof(Visual.RotationAngleInDegrees), rotationAnimation); ElementCompositionPreview.SetElementChildVisual(visualPlaceholder, spatialVisual); } } private void VisualPlaceholder_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e) { TranslateTransform transform = new TranslateTransform(); VisualPlaceholder.RenderTransform = transform; transform.Y = e.Cumulative.Translation.Y; } } }<file_sep>๏ปฟnamespace CrossDeviceExpDemo.Shared.Models { public class Product { public string ModelName { get; set; } public string ModelPath => $"ms-appx:///CrossDeviceExpDemo.Shared/Assets/3D/{ModelName}"; public string ModelPathLocal => $"Assets/3D/{ModelName}"; public string DisplayName { get; set; } public Product(string modelName, string displayName) { ModelName = modelName; DisplayName = displayName; } } }
131725b68ac929eccf4b0d7f0fb78f5b9a4031f5
[ "C#" ]
4
C#
JustinXinLiu/CrossDeviceExpDemo
9e15ad415545f212458d60841b739c26583bf099
55f5d31b2c7ff4d11d50b10aff799a284e5af835
refs/heads/master
<file_sep>import pandas as pd # from tqdm import tqdm # # _filename = './comm_n_and_v_utf8_1_ordered_q.csv' # encoding = 'utf-8' # columns = ['mid', 'mname', 'score', 'genre', 'comments'] # # read = pd.read_csv(_filename, encoding=encoding, header=None, names=columns, low_memory=False) # tmp_mid = 0 # # list0 = ['a', 'a', 'a', 'b'] # list1 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['d', 'e', 'f']] # # count = 0 # mid_list = [] # for i in tqdm(range(0, len(read.mid))): # try: # if not read.mid[i] == read.mid[i+1]: # mid_list.append(count) # except: # pass # count += 1 # print(mid_list) # for i in range(1, int(mid_list[0]) + 1): # read.comments[0].extend(read.comments[i]) # # for i in tqdm(range(0, len(mid_list))): # for j in range(int(mid_list[i]) + 1, int(mid_list[i+1]) + 1): # if j == int(mid_list[i] + 1): # pass # else: # read.comments[int(mid_list[i]) + 1] = ', '.join([str(read.comments[int(mid_list[i]) + 1]), str( # read.comments[j])]) # # read.comments[int(mid_list[i]) + 1] = str(read.comments[int(mid_list[i]) + 1]) + ', ' + str(read.comments[j]) # read.comments[j] = '' # print(read.comments[int(mid_list[i]) + 1]) # # print(read.comment) import pandas as pd from tqdm import tqdm # _filename = './comm_n_and_v_utf8_1_ordered_q.csv' # encoding = 'utf-8' # columns = ['mid', 'mname', 'score', 'genre', 'comments'] # # read = pd.read_csv(_filename, encoding=encoding, header=None, names=columns, low_memory=False) # tmp_mid = 0 # # list0 = ['a', 'a', 'a', 'b'] # list1 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['d', 'e', 'f']] # # count = 0 # for i in tqdm(range(0, len(read.mid))): # try: # if not read.mid[i] == read.mid[i+1]: # mid_list.append(count) # except: # pass # count += 1 # print(mid_list) # for i in range(1, int(mid_list[0]) + 1): # read.comments[0].extend(read.comments[i]) # # for i in tqdm(range(0, len(mid_list))): # for j in range(int(mid_list[i]) + 1, int(mid_list[i+1]) + 1): # if j == int(mid_list[i] + 1): # pass # else: # read.comments[int(mid_list[i]) + 1] = ', '.join([str(read.comments[int(mid_list[i]) + 1]), str( # read.comments[j])]) # # read.comments[int(mid_list[i]) + 1] = str(read.comments[int(mid_list[i]) + 1]) + ', ' + str(read.comments[j]) # read.comments[j] = '' # print(read.comments[int(mid_list[i]) + 1]) # # print(read.comment) import pickle mid_mname_vec = {} for _number in tqdm(range(1, 9)): _filename = './comm_n_and_v_utf8_' + str(_number) + '_ordered_q.csv' encoding = 'utf-8' columns = ['mid', 'mname', 'score', 'genre', 'comments'] read = pd.read_csv(_filename, encoding=encoding, header=None, names=columns, low_memory=False) for i in tqdm(range(len(read.mid) - 1)): try: if not read.mid[i] == read.mid[i+1]: mid_mname_vec[int(read.mid[i])] = read.mname[i] except: pass with open('../dict_mid_mname.bin', 'wb') as f: pickle.dump(mid_mname_vec, f) <file_sep>from nugu.movie_comment_scrapper.crawling.naver_movie import get_movie_comm as get_comm import os import time from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm with ThreadPoolExecutor(max_workers=100) as executor: # Thread # executor.submit(get_comm, 172816) for i in range(1, 200000): # ๋„ค์ด๋ฒ„ ๊ณ ์œ  ์˜ํ™” ID 1 ~ 200000 ๊นŒ์ง€ ํฌ๋กค๋ง executor.submit(get_comm, i) <file_sep># NUGU_movie_recommendation movie recommendation proxy server in NUGU Play ## ํ”„๋กœ์ ํŠธ ์†Œ๊ฐœ - SK Telecom ์‚ฐํ•™ํ˜‘๋ ฅ ์ธ๊ณต์ง€๋Šฅ ์„ํ•™์‚ฌ ํ†ตํ•ฉ ๊ต๊ณผ๋ชฉ ์ง„ํ–‰ ํ”„๋กœ์ ํŠธ - NUGU Play Kit Platform์„ ์ด์šฉํ•ด์„œ ์ง„ํ–‰๋˜์—ˆ์œผ๋ฉฐ, ์œ ์ € ๋งž์ถคํ˜• ์˜ํ™” ์ถ”์ฒœ ์„œ๋น„์Šค ## ํŒ€ ๊ตฌ์„ฑ - ์„œ๋ฒ„ ๊ตฌํ˜„: [๊น€์ธํ˜ธ](https://github.com/kih1024) - ๋‚ด๋ถ€ ์˜ํ™” ์ถ”์ฒœ ์•Œ๊ณ ๋ฆฌ์ฆ˜: [์‹ ํƒœ์šฑ](https://github.com/momentum1993), [๊ฐ•์Šน์—ฐ](https://github.com/tmddusgood) ## ๊ฐœ๋ฐœ ๋™๊ธฐ - ํ˜ผ์˜, ํ˜ผ์ˆ  ๋“ฑ์˜ ์—ฌ๊ฐ€ํ™œ๋™์„ ์ง‘์—์„œ ์ฆ๊ธฐ๋Š” "ํ™ˆ์Šคํ…Œ์ด์กฑ" ์ฆ๊ฐ€๋กœ ์ธํ•œ ์ง‘์—์„œ ๋ชจ๋“  ๊ฑธ ํ•ด๊ฒฐํ•˜๋Š” ํ™ˆ์ฝ”๋…ธ๋ฏธ ๊ด€๋ จ ์—…์ข…๋“ค์˜ ๋šœ๋ ทํ•œ ์„ฑ์žฅ์„ธ - ํ™ˆ์ฝ”๋…ธ๋ฏธ ์„œ๋น„์Šค๋ฅผ ์ œ๊ณตํ•˜๋Š”๋ฐ ๊ต‰์žฅํžˆ ์ ํ•ฉํ•œ ํ”Œ๋žซํผ์ธ NUGU๋ฅผ ํ†ตํ•ด, ๊ฐœ์ธ๋ณ„ ์ ์ ˆํ•œ ์—ฌ๊ฐ€ํ™œ๋™ ํŠนํžˆ ์˜ํ™”๋ผ๋Š” ๋„๋ฉ”์ธ์„ ๊ธฐ๋ฐ˜์œผ๋กœํ•œ ๋งž์ถคํ˜• ์„œ๋น„์Šค ๊ธฐํš ## ์ „์ฒด ๊ตฌ์„ฑ๋„ ![](./flow_chart.jpg) #### ์ฃผ์š” ๊ธฐ๋Šฅ - ์œ ์‚ฌ ์˜ํ™” ์ถ”์ฒœ ex) {์•„์ด์–ธ๋งจ} ๊ฐ™์€ ์˜ํ™” ์ถ”์ฒœํ•ด์ค˜ - ์œ ์ € ๋กœ๊ทธ ๊ธฐ๋ฐ˜ ์ถ”์ฒœ (Btv ์—ฐ๋™) ex) ์˜ํ™” ์ถ”์ฒœ ํ•ด์ค˜ - ์žฅ๋ฅด ๊ธฐ๋ฐ˜ ์ถ”์ฒœ ex) {์Šค๋ฆด๋Ÿฌ} ์˜ํ™” ์ถ”์ฒœํ•ด์ค˜ ## ๋ฐ์ดํ„ฐ ์ถ”์ถœ ๊ณผ์ • ![](./data_scraping.jpg) - ๋„ค์ด๋ฒ„ ์˜ํ™” ํŽ˜์ด์ง€ โ†’ ์˜ํ™” ๋ฆฌ๋ทฐ, ์ค„๊ฑฐ๋ฆฌ - ํ† ํฐํ™”(๋ช…์‚ฌ, ํ˜•์šฉ์‚ฌ ์ถ”์ถœ) - Word2vec (์šฉ์–ธ ๋ฒกํ„ฐ โ†’ ์˜ํ™” ๋ฒกํ„ฐ) ## ์œ ์ € ๋กœ๊ทธ ๊ธฐ๋ฐ˜ ์ถ”์ฒœ ์„œ๋น„์Šค ![](./user_log_based.jpg) - ์œ ์ € ๋กœ๊ทธ ์ •๋ณด ๊ธฐ๋ฐ˜ - ํ˜„์žฌ๋Š” proxy ์„œ๋ฒ„์˜ ์œ ์ € ์ •๋ณด db๋กœ ๋ถ€ํ„ฐ ์ถ”์ถœ (ํ˜„์žฌ ํŠน์ • Persona์— ๋Œ€ํ•œ ๊ธฐ๋ก์„ ์ž„์˜๋กœ ์ง‘์–ด๋„ฃ์–ด ์ถ”์ฒœ ์ง„ํ–‰) - ์œ ์ €๋งŒ์˜ ๊ณ ์œ  ๋ฒกํ„ฐ โ†’ ๊ธฐ๋ก์„ ํ†ตํ•œ ์œ ์ €๋งŒ์˜ ๋ฒกํ„ฐ์™€ ๊ทธ์— ๋Œ€ํ•œ ์œ ์‚ฌํ•œ ์˜ํ™” ์ถ”์ถœ (์œ ์ €์— ๋”ฐ๋ฅธ ์ถ”์ฒœ) ## ์žฅ๋ฅด ๊ธฐ๋ฐ˜ ์ถ”์ฒœ ์„œ๋น„์Šค ![](genre_based.jpg) - ์˜ํ™” ์žฅ๋ฅด ๋ฒกํ„ฐ & ์œ ์ € ๋กœ๊ทธ ๊ธฐ๋ฐ˜ โ†’ ์œ ์‚ฌ ์žฅ๋ฅด์˜ ์˜ํ™” ์ถ”์ฒœ ์„œ๋น„์Šค - ๊ณตํฌ(horror)๋ผ๋Š” ์žฅ๋ฅด ์š”์ฒญ์˜ ๊ฒฝ์šฐ: ์ฒ˜ํ‚ค, ์Šคํฌ๋ฆผ, ์ปจ์ €๋ง, ์• ๋‚˜๋ฒจ ## ๋น„์Šทํ•œ ์˜ํ™” ์ถ”์ฒœ ์„œ๋น„์Šค ![](similar_movie.jpg) - ์˜ํ™” ๋ณ„ ๊ณ ์œ  ๋ฒกํ„ฐ ๊ธฐ๋ฐ˜ - Input ์˜ํ™”์™€ ๋น„์Šทํ•œ ์˜ํ™” ์ถ”์ฒœ ์„œ๋น„์Šค - '์•„์ด์–ธ๋งจ ๊ฐ™์€ ์˜ํ™” ์ถ”์ฒœํ•ด์ค˜'์˜ ๊ฒฝ์šฐ: ์ŠคํŒŒ์ด๋”๋งจ, ์•คํŠธ๋งจ, ๋ฐฐํŠธ๋งจ, ์Šคํƒ€์›Œ์ฆˆ, ํ„ฐ๋ฏธ๋„ค์ดํ„ฐ ## ํ–ฅํ›„ ๋ฐœ์ „ ๋ฐฉํ–ฅ - ํ˜„์žฌ์˜ ์˜ํ™”๋ฅผ ์ด์šฉํ•œ ์„œ๋น„์Šค์—์„œ ์˜ˆ๋Šฅ, ๋“œ๋ผ๋งˆ ๋“ฑ์˜ ๋„๋ฉ”์ธ ํ™•์žฅ์„ ํ†ตํ•ด์„œ ์‚ฌ์šฉ์ž๋“ค์—๊ฒŒ ๋” ํญ๋„“์€ ์ถ”์ฒœ ์„œ๋น„์Šค ์ œ๊ณต ๊ฐ€๋Šฅ - ์Šคํฌ๋ ˆ์ดํ•‘ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ํ†ตํ•ด์„œ ์ถ”์ฒœ ์„œ๋น„์Šค๋ฅผ ์ œ๊ณตํ•˜๊ณ  ์žˆ์ง€๋งŒ, BTV๋‚˜ WAVVE์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ด์šฉํ•ด์„œ ์—ฐ๊ณ„ ์„œ๋น„์Šค ์ œ๊ณต ๊ฐ€๋Šฅ - ์‹œ์ฒญ ๊ธฐ๋ก๋งŒ์„ ํ†ตํ•ด ๊ฐœ์ธ ์ถ”์ฒœ ์„œ๋น„์Šค๋ฅผ ์ œ๊ณตํ•˜๊ณ  ์žˆ์ง€๋งŒ, ์ปจํ…์ธ ๋ณ„ ์‹œ์ฒญ ์‹œ๊ฐ„ ๋ฐ ์‚ฌ์šฉ์ž ํŒจํ„ด ๋ถ„์„์„ ํ†ตํ•ด ๋”์šฑ ๋งŒ์กฑ์Šค๋Ÿฌ์šด ์ปจํ…์ธ  ์ถ”์ฒœ ์„œ๋น„์Šค ์ œ๊ณต ๊ฐ€๋Šฅ - ํ˜„์žฌ ์ถ”์ฒœ์— ์‚ฌ์šฉ๋˜๋Š” feature๋“ค์„ ๋”์šฑ ์„ธ๋ถ„ํ™”ํ•˜๊ฑฐ๋‚˜ ์ถ”๊ฐ€ํ•˜์—ฌ ๊ตฌ์ฒด์ ์ธ ์ถ”์ฒœ ์„œ๋น„์Šค ์ œ๊ณต ๊ฐ€๋Šฅ <file_sep># ํŽธ์ง‘ ๊ฑฐ๋ฆฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ import pickle # kor_begin = 44032 # kor_end = 55203 # chosung_base = 588 # jungsung_base = 28 # jaum_begin = 12593 # jaum_end = 12622 # moum_begin = 12623 # moum_end = 12643 # # chosung_list = [ 'ใ„ฑ', 'ใ„ฒ', 'ใ„ด', 'ใ„ท', 'ใ„ธ', 'ใ„น', 'ใ…', 'ใ…‚', 'ใ…ƒ', # 'ใ……', 'ใ…†', 'ใ…‡' , 'ใ…ˆ', 'ใ…‰', 'ใ…Š', 'ใ…‹', 'ใ…Œ', 'ใ…', 'ใ…Ž'] # ์ดˆ์„ฑ # # jungsung_list = ['ใ…', 'ใ…', 'ใ…‘', 'ใ…’', 'ใ…“', 'ใ…”', # 'ใ…•', 'ใ…–', 'ใ…—', 'ใ…˜', 'ใ…™', 'ใ…š', # 'ใ…›', 'ใ…œ', 'ใ…', 'ใ…ž', 'ใ…Ÿ', 'ใ… ', # 'ใ…ก', 'ใ…ข', 'ใ…ฃ'] # ์ค‘์„ฑ # # jongsung_list = [ # ' ', 'ใ„ฑ', 'ใ„ฒ', 'ใ„ณ', 'ใ„ด', 'ใ„ต', 'ใ„ถ', 'ใ„ท', # 'ใ„น', 'ใ„บ', 'ใ„ป', 'ใ„ผ', 'ใ„ฝ', 'ใ„พ', 'ใ„ฟ', 'ใ…€', # 'ใ…', 'ใ…‚', 'ใ…„', 'ใ……', 'ใ…†', 'ใ…‡', 'ใ…ˆ', 'ใ…Š', # 'ใ…‹', 'ใ…Œ', 'ใ…', 'ใ…Ž'] # ์ข…์„ฑ # # jaum_list = ['ใ„ฑ', 'ใ„ฒ', 'ใ„ณ', 'ใ„ด', 'ใ„ต', 'ใ„ถ', 'ใ„ท', 'ใ„ธ', 'ใ„น', # 'ใ„บ', 'ใ„ป', 'ใ„ผ', 'ใ„ฝ', 'ใ„พ', 'ใ„ฟ', 'ใ…€', 'ใ…', 'ใ…‚', # 'ใ…ƒ', 'ใ…„', 'ใ……', 'ใ…†', 'ใ…‡', 'ใ…ˆ', 'ใ…‰', 'ใ…Š', 'ใ…‹', 'ใ…Œ', 'ใ…', 'ใ…Ž'] # ์ž์Œ # # moum_list = ['ใ…', 'ใ…', 'ใ…‘', 'ใ…’', 'ใ…“', 'ใ…”', 'ใ…•', 'ใ…–', 'ใ…—', 'ใ…˜', # 'ใ…™', 'ใ…š', 'ใ…›', 'ใ…œ', 'ใ…', 'ใ…ž', 'ใ…Ÿ', 'ใ… ', 'ใ…ก', 'ใ…ข', 'ใ…ฃ'] # ๋ชจ์Œ def load_from_pickle(_string_name): ''' load_from_pickle : pickleํŒŒ์ผ์—์„œ ์˜ํ™” id์— ๋Œ€ํ•œ ์˜ํ™” ๋ฒกํ„ฐ๋ฅผ ์ง€๋‹ˆ๋Š” dictํƒ€์ž… ๊ฐ์ฒด๋กœ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ๋ชจ๋“ˆ :param _string_name: pickle ํŒŒ์ผ ์ด๋ฆ„ :return: ์˜ํ™” id์— ๋Œ€ํ•œ ์˜ํ™” ๋ฒกํ„ฐ๋ฅผ ์ง€๋‹ˆ๋Š” dictํƒ€์ž… ๊ฐ์ฒด ''' with open(_string_name + '.bin', 'rb') as f: _dict = pickle.load(f) return _dict def levenshtein(s1, s2, cost=None, debug=False): ''' levenshtein: :param s1: ๋น„๊ตํ•  ๋‹จ์–ด 1 :param s2: ๋น„๊ตํ•  ๋‹จ์–ด 2 :param cost: :param debug: :return: ''' if len(s1) < len(s2): # ๋น„๊ตํ•  ์ฒซ๋ฒˆ์งธ ๋‹จ์–ด๊ฐ€ ๋‘๋ฒˆ์งธ ๋‹จ์–ด๋ณด๋‹ค ๊ธธ์–ด์•ผ ํ•œ๋‹ค. return levenshtein(s2, s1, debug=debug) # ์ฒซ๋ฒˆ์งธ ๋‹จ์–ด, ๋‘๋ฒˆ์งธ ๋‹จ์–ด ์œ„์น˜๋ฅผ swapํ•ด์„œ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ง„ํ–‰ if len(s2) == 0: # ๋น„๊ตํ•  ๋‘๋ฒˆ์งธ ๋‹จ์–ด๊ฐ€ ๋นˆ์นธ์ผ ๋•Œ return len(s1) # ์ฒซ๋ฒˆ์งธ ๋‹จ์–ด์˜ ๊ธธ์ด๋งŒํผ ๋ฐ˜ํ™˜ if cost is None: cost = {} # changed def substitution_cost(c1, c2): if c1 == c2: # ๋งŒ์•ฝ c1๊ณผ c2 ๊ธธ์ด๊ฐ€ ๊ฐ™๋‹ค๋ฉด cost = 0 return 0 return cost.get((c1, c2), 1) # cost dict์— (c1, c2)์— ๋Œ€ํ•œ value ๋ฐ˜ํ™˜ํ•˜๊ฑฐ๋‚˜ ์—†๋‹ค๋ฉด 1 ๋ฐ˜ํ™˜ previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): # ์ฒซ๋ฒˆ์งธ ๋‹จ์–ด์— ๋Œ€ํ•ด enumerate current_row = [i + 1] # ํ˜„์žฌ ํ™•์ธํ•  row for j, c2 in enumerate(s2): # ๋‘๋ฒˆ์งธ ๋‹จ์–ด์— ๋Œ€ํ•ด enumerate insertions = previous_row[j + 1] + 1 # ๋ฐ”๋กœ ์œ„์ชฝ์˜ cost + 1 deletions = current_row[j] + 1 # ์™ผ์ชฝ์˜ cost + 1 # Changed substitutions = previous_row[j] + substitution_cost(c1, c2) # ์ขŒ์ƒํ–ฅ(โ†–) ๋Œ€๊ฐ์„ ์— ์žˆ๋Š” cost (๋น„๊ตํ•˜๋Š” ์•ŒํŒŒ๋ฒณ or ํ•œ๊ธ€ ์Œ์ ˆ์ด ๋‹ค๋ฅผ ๊ฒฝ์šฐ +1) current_row.append(min(insertions, deletions, substitutions)) # ํ˜„์žฌ ์—ด์— ์œ„์˜ 3๊ฐ€์ง€ ๊ฐ’ ์ค‘ ์ตœ์†Œ๊ฐ’์„ ๋„ฃ๋Š”๋‹ค. # if debug: # print(current_row[1:]) previous_row = current_row return previous_row[-1] # def compose(chosung, jungsung, jongsung): # char = chr( # kor_begin + # chosung_base * chosung_list.index(chosung) + # jungsung_base * jungsung_list.index(jungsung) + # jongsung_list.index(jongsung) # ) # return char # # def decompose(c): # if not character_is_korean(c): # return None # i = ord(c) # if (jaum_begin <= i <= jaum_end): # return (c, ' ', ' ') # if (moum_begin <= i <= moum_end): # return (' ', c, ' ') # # # decomposition rule # i -= kor_begin # cho = i // chosung_base # jung = ( i - cho * chosung_base ) // jungsung_base # jong = ( i - cho * chosung_base - jung * jungsung_base ) # return (chosung_list[cho], jungsung_list[jung], jongsung_list[jong]) # # def character_is_korean(c): # i = ord(c) # return ((kor_begin <= i <= kor_end) or # (jaum_begin <= i <= jaum_end) or # (moum_begin <= i <= moum_end)) # # def jamo_levenshtein(s1, s2, debug=False): # if len(s1) < len(s2): # return jamo_levenshtein(s2, s1, debug) # # if len(s2) == 0: # return len(s1) # # def substitution_cost(c1, c2): # if c1 == c2: # return 0 # return levenshtein(decompose(c1), decompose(c2))/3 # # previous_row = range(len(s2) + 1) # for i, c1 in enumerate(s1): # current_row = [i + 1] # for j, c2 in enumerate(s2): # insertions = previous_row[j + 1] + 1 # deletions = current_row[j] + 1 # # Changed # substitutions = previous_row[j] + substitution_cost(c1, c2) # current_row.append(min(insertions, deletions, substitutions)) # # # # if debug: # # pass # # # print(['%.3f'%v for v in current_row[1:]]) # # previous_row = current_row # # return previous_row[-1] def main(_string): ''' main: ์ฃผ์–ด์ง„ String์— ๋Œ€ํ•ด์„œ ์กด์žฌํ•˜๋Š” ๋‹จ์–ด ์ค‘ ํŽธ์ง‘๊ฑฐ๋ฆฌ๊ฐ€ ๊ฐ€์žฅ ์งง์€ ๋‹จ์–ด ๋ฐ˜ํ™˜ :param _string: ํŽธ์ง‘๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•  String :return: ์˜ํ™” ์ œ๋ชฉ ์ค‘์— ๊ฐ€์žฅ ํŽธ์ง‘๊ฑฐ๋ฆฌ๊ฐ€ ์งง์€ ๋‹จ์–ด ๋ฐ˜ํ™˜ ''' address = 'nugu/movie_story_scrapper/' dict_name_2 = 'dict_mid_mname' mid_mname = load_from_pickle(address + dict_name_2) # {์˜ํ™” id: ์˜ํ™”์ œ๋ชฉ} dict result = [] weight = [] weight_dic = {} for k, v in mid_mname.items(): w = 0.01 s1 = _string # NUGU๋กœ ๋ถ€ํ„ฐ ๋ฐ›์€ entity s2 = str(v) # ํ˜„์žฌ ๋ฃจํ”„์—์„œ์˜ ์˜ํ™”์ œ๋ชฉ e_distance = levenshtein(s1, s2, debug=True) # ํŽธ์ง‘๊ฑฐ๋ฆฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ if e_distance < 20: # ํŽธ์ง‘๊ฑฐ๋ฆฌ๊ฐ€ 20 ์ดํ•˜์ธ ๊ฒƒ๋“ค์— ๋Œ€ํ•ด์„œ weight_dic[k] = e_distance # {์˜ํ™” id: ํŽธ์ง‘๊ฑฐ๋ฆฌ} dict #print(weight_dic) result = min(zip(weight_dic.values(), weight_dic.keys())) print(mid_mname[result[1]]) return mid_mname[result[1]] # ์ž์‹ ์„ ์ œ์™ธํ•œ ํŽธ์ง‘๊ฑฐ๋ฆฌ๊ฐ€ ๊ฐ€์žฅ ์งง์€ ์˜ํ™” ์ œ๋ชฉ ๋ฐ˜ํ™˜ <file_sep>from gensim.models.word2vec import Word2Vec model = Word2Vec.load('story_20191205_1654') word_vectors = model.wv print(model.wv['์Šคํƒ€์›Œ์ฆˆ']) print(model.wv.most_similar('์š•์ •')) print(model.wv.most_similar('์žฌ๋ฏธ')) print(model.wv.most_similar('์žฌ๋ฐŒ')) print(model.most_similar(positive=['๊น€ํ˜œ์ˆ˜', '๋ ˆ์ด์ฒผ'], negative=['์—ฌ์ž', '์—ฌ๋ฐฐ์šฐ'], topn=10)) vocabs = word_vectors.vocab.keys() word_vectors_list = [word_vectors[v] for v in vocabs]<file_sep>import pandas as pd from tqdm import tqdm import pickle import re # mid_genre_vec = {} # # for _number in tqdm(range(1, 9)): # _filename = './comm_n_and_v_utf8_' + str(_number) + '_ordered_q.csv' # encoding = 'utf-8' # columns = ['mid', 'mname', 'score', 'genre', 'comments'] # # read = pd.read_csv(_filename, encoding=encoding, header=None, names=columns, low_memory=False) # # for i in tqdm(range(len(read.mid) - 1)): # try: # if not read.mid[i] == read.mid[i+1]: # mid_genre_vec[int(read.mid[i])] = read.genre[i] # except: # pass # # # with open('../dict_mid_genre.bin', 'wb') as f: # pickle.dump(mid_genre_vec, f) # # print(mid_genre_vec) # mid_genre_dict = {} # with open('../dict_mid_genre.bin', 'rb') as f: # raw_data = pickle.load(f) # # for k, v in tqdm(raw_data.items()): # mid_genre_dict[k] = re.findall(r"[\w']+", str(v)) # # with open('../dict_mid_genre_real_eincluded.bin', 'wb') as f: # pickle.dump(mid_genre_dict, f) temp_list = ["world", 'hello'] if 'world' in temp_list: print('hi') else: print('sdfsdf') # print(temp_list.index("world!")) address = '../movie_story_scrapper/' model_name = 'story_20191205_1654' # ๋ชจ๋ธ ์ด๋ฆ„ dict_name = 'dict_20191206_1937' # ์ˆ˜์ •ํ• ๊ฒƒ dict_name_2 = 'dict_mid_mname' # ์ˆ˜์ •ํ•  ๊ฒƒ with open(address + dict_name + '.bin', 'rb') as f: _dict = pickle.load(f) print(_dict['10001']) <file_sep>from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt import json from pprint import pprint from nugu.get_recommendations import main as reco from nugu.edit_distance import main as e_distance @csrf_exempt def message(request): d = json.load(request) return_list = '' pprint(d) action = d['action'] parameters = action['parameters'] actions = action['actionName'] # print(list(parameters.keys())) # condition = list(parameters.keys()) # print(condition[0]) if actions == "answer.like": movie_name = parameters['movie_name'] v = movie_name['value'] new_v = e_distance(v) return_name = reco('3', new_v) count = 0 for i in return_name[:5]: count += 1 print(return_name[4]) if not count == 5: return_list = return_list + i + ',' else: return_list = return_list + i print(return_list) # print(request.action) return JsonResponse({ "version": "2.0", "resultCode": "OK", "output": { "movie_name": v, "result_movie": return_list } }) elif actions == "answer.genre": movie_name = parameters['movie_genre'] v = movie_name['value'] print(v) # new_v = e_distance(v) return_name = reco('2', v) print(return_name) count = 0 for i in return_name[:5]: count += 1 print(return_name[4]) if not count == 5: return_list = return_list + i + ',' else: return_list = return_list + i print(return_list) # print(request.action) return JsonResponse({ "version": "2.0", "resultCode": "OK", "output": { "movie_genre": v, "result_genre": return_list } }) elif actions == "answer.idle": print("00001") return_name = reco('1', '1') print("00002") print(return_name) count = 0 for i in return_name[:5]: count += 1 print(return_name[4]) if not count == 5: return_list = return_list + i + ',' else: return_list = return_list + i print(return_list) # print(request.action) return JsonResponse({ "version": "2.0", "resultCode": "OK", "output": { "return_idle": return_list } }) # Create your views here. <file_sep>import MeCab import pandas as pd from tqdm import tqdm import pickle from gensim.models.word2vec import Word2Vec import matplotlib.pyplot as plt from sklearn.decomposition import PCA import matplotlib mc = MeCab.Tagger() # Mecab Tagger encoding = "utf-8" columns = ['mid', 'mname', 'score', 'genre', 'comments'] # ์˜ํ™” id, ์˜ํ™”์ œ๋ชฉ, ํ‰์ , ์žฅ๋ฅด, ํ•œ์ค„ํ‰ md_path = './model_integrated_full(nouns+vs)' list_pickle_path = './integrated_nouns_vs_list' raw_path = './comm_raw_utf8_' # fixed_path = './comm_fixed_utf8_' n_and_v_path = './comm_n_and_v_utf8_' def parse_Nouns_Vs(_text): ''' parse_Nouns_Vs : ํ•œ์ค„ํ‰์„ ๋ฐ›์•„์™€์„œ ๋ช…์‚ฌ์™€ ์šฉ์–ธ์„ ๋ฝ‘์•„๋‚ด๋Š” ํ•จ์ˆ˜ :param _text: ํ•œ์ค„ํ‰(str) :return: ๋ช…์‚ฌ(Noun)๊ณผ ์šฉ์–ธ(Verb)์„ ๊ฐ€์ง€๋Š” ๋ฆฌ์ŠคํŠธ ''' _answer = [] _list = _text.split() for i in range(1, len(_list), 2): if _list[i].startswith('NN') or _list[i].startswith('V'): # ๋ช…์‚ฌ์™€ ์šฉ์–ธ์œผ๋กœ ๋œ ๊ฒƒ์„ ๋ฝ‘์•„๋‚ธ๋‹ค _answer.append(_list[i-1]) return _answer # ๋ช…์‚ฌ์™€ ์šฉ์–ธ์„ ํฌํ•จํ•˜๋Š” ๋ฆฌ์ŠคํŠธ ๋ฐ˜ํ™˜ def readcsv(_filename): ''' readcsv : ํ•ด๋‹น ์œ„์น˜์˜ csvํŒŒ์ผ์„ DataFrameํƒ€์ž… ๊ฐ์ฒด๋กœ ๋ฐ˜ํ™˜ :param _filename: csvํŒŒ์ผ ์œ„์น˜ :return: DataFrame๊ฐ์ฒด ''' _read = pd.read_csv(_filename, encoding=encoding, header=None, names=columns, low_memory=False) return _read def try_and_fix(_read, _ecount): ''' try_and_fix : :param _read: :param _ecount: :return: ''' _error = [] for item in tqdm(_read.comments): try: _ecount += 1 mc.parse(item) except: _error.append(_ecount) for i in range(len(_error)): _error[i] = int(_error[i]) - 1 _read = _read.drop(_error, 0) return _read def fixed_to_nandvs(_read): _tmp_list = [] for item in tqdm(_read.comments): try: mc.parse(item) tmp_str = mc.parse(item) _tmp_list.append(parse_Nouns_Vs(tmp_str)) except: pass _read.comments = _tmp_list return _read def csv_preprocessing(_process): ''' :param _process: :return: ''' num = 0 tmp_list = [] if _process == 'error_fix': for i in tqdm(range(0, 8)): ecount = 0 num = str(int(num) + 1) # ํŒŒ์ผ ์—ฌ๋Ÿฌ ๊ฐœ์— ์ผ๊ด„ ์ ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ ๋„ฃ์€ ์นด์šดํŠธ filename = raw_path + str(num) + ".csv" filename2 = fixed_path + str(num) + '.csv' read = readcsv(filename) read = try_and_fix(read, ecount) read.to_csv(filename2, encoding='utf-8', header=None, index=False) elif _process == 'extract_Nouns&Vs': for i in tqdm(range(0, 8)): num = str(int(num) + 1) # ํŒŒ์ผ ์—ฌ๋Ÿฌ ๊ฐœ์— ์ผ๊ด„ ์ ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ ๋„ฃ์€ ์นด์šดํŠธ filename2 = fixed_path + str(num) + '.csv' filename3 = n_and_v_path + str(num) + '.csv' read = readcsv(filename2) read = fixed_to_nandvs(read) read.to_csv(filename3, encoding='utf-8', header=None, index=False) def integrate_csv_pickle(): num = 0 tmp_list = [] for i in tqdm(range(0, 8)): num = str(int(num) + 1) # ํŒŒ์ผ ์—ฌ๋Ÿฌ ๊ฐœ์— ์ผ๊ด„ ์ ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ ๋„ฃ์€ ์นด์šดํŠธ filename = n_and_v_path + str(num) + '.csv' read = readcsv(filename) for i in tqdm(range(0, len(read.comments))): tmp_list.append(read.comments[i]) print(tmp_list) with open(list_pickle_path, 'wb') as f: pickle.dump(tmp_list, f) def pickle_to_model(_tmp_list): with open(list_pickle_path, 'rb') as f: _tmp_list = pickle.load(f) # ๋‹จ ํ•œ์ค„์”ฉ ์ฝ์–ด์˜ด print(_tmp_list) # model = Word2Vec(tmp_list, size=100, window=3, min_count=20, workers=50) # model.init_sims(replace=True) # model.save(md_path) def plot_2d_graph(vocabs, xs, ys): plt.figure(figsize=(8,6)) plt.scatter(xs, ys, marker ='o') for i, v in enumerate(vocabs): plt.annotate(v, xy=(xs[i], ys[i])) plt.show() def model_application(): model = Word2Vec.load(md_path) model.most_similar('์˜ํ™”') def model_configuration(): font_name = matplotlib.font_manager.FontProperties( fname="C:/Windows/Fonts/gulim.ttc" # ํ•œ๊ธ€ ํฐํŠธ ์œ„์น˜๋ฅผ ๋„ฃ์–ด์ฃผ์„ธ์š” ).get_name() matplotlib.rc('font', family=font_name) model = Word2Vec.load(md_path) word_vectors = model.wv vocabs = word_vectors.vocab.keys() word_vectors_list = [word_vectors[v] for v in vocabs] pca = PCA(n_components=2) xys = pca.fit_transform(word_vectors_list) xs = xys[:, 0] ys = xys[:, 1] plot_2d_graph(vocabs, xs, ys) if __name__ == "__main__": print('nothingxc')<file_sep>import csv def save_to_file(comm_info): file = open("comm.csv", mode="a+", encoding="euc-kr", newline='') writer = csv.writer(file) # writer.writerow(['title','score','genre','comment']) for comm in comm_info: writer.writerow(list(comm.values())) return <file_sep>import requests from bs4 import BeautifulSoup import time from nugu.movie_comment_scrapper.crawling.csv_save import save_to_file from tqdm import tqdm def get_last_page(M_ID): URL = f"https://movie.naver.com/movie/point/af/list.nhn?st=mcode&sword={M_ID}&target=after" # ํ•œ์ค„ํ‰ ํŽ˜์ด์ง€ ์ฃผ์†Œ result = requests.get(URL) soup = BeautifulSoup(result.text, "html.parser") pagination = soup.find("div", {"class": "h5_right_txt"}) if pagination: num = pagination.find("strong").string max_page = int(num) / 10 + 1 return int(max_page) # ๋งˆ์ง€๋ง‰ ํŽ˜์ด์ง€ ๋ฐ˜ํ™˜ else: return None def extract_comm(html, title, genre, mid): # ํ•œ์ค„ํ‰ 1๊ฐœ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜ comment = html.get_text('|', strip=True).split('|')[3] score = html.find("em").string return {'mid': mid, 'title': title, 'score': score, 'genre': genre, 'comment': comment} def extract_comms(last_page, M_ID): URL = f"https://movie.naver.com/movie/point/af/list.nhn?st=mcode&sword={M_ID}&target=after" # ํ•œ์ค„ํ‰ ํŽ˜์ด์ง€ ์ฃผ์†Œ comments_info = [] result = requests.get(URL) soup = BeautifulSoup(result.text, "html.parser") info = soup.find("div", {"class": "choice_movie_info"}) title = info.find("h5").get_text(strip=True) genre = soup.find("td").get_text(strip=True).split('|')[0] for page in range(last_page): print(f"Scrapping naver page {page + 1}") result = requests.get(f"{URL}&page={page + 1}") soup = BeautifulSoup(result.text, "html.parser") results = soup.find_all("td", {"class": "title"}) # print(results[0].get_text(strip=True)) for result in results: # comments['title']=title comm = extract_comm(result, title, genre, M_ID) # ํ•œ์ค„ํ‰ ์ถ”์ถœ # comments.update(extract_comm(result)) comments_info.append(comm) # print(comments_info) return comments_info # extract_comms(1) def get_movie_comm(i): last_page = get_last_page(i) # ๋งˆ์ง€๋ง‰ ํŽ˜์ด์ง€ (ํŽ˜์ด์ง€ ์ˆ˜) if last_page is None: #ํŽ˜์ด์ง€๊ฐ€ ์—†๋‹ค๋ฉด return None if last_page < 120: # ํŽ˜์ด์ง€ 120 ๋ฏธ๋งŒ๊นŒ์ง€ ์ถ”์ถœ comments = extract_comms(last_page, i) else: comments = extract_comms(120, i) if len(comments) is not 0: # print(comments) save_to_file(comments) # ํŒŒ์ผ๋กœ ์ €์žฅ print(comments) return comments <file_sep>from django.apps import AppConfig class NuguConfig(AppConfig): name = 'nugu' <file_sep>import requests from bs4 import BeautifulSoup import time from nugu.movie_story_scrapper.crawling.csv_save import save_to_file from nugu.movie_story_scrapper.crawling.csv2_save import save_to_file2 def get_last_page(M_ID): URL = f"https://movie.naver.com/movie/point/af/list.nhn?st=mcode&sword={M_ID}&target=after" result = requests.get(URL) soup = BeautifulSoup(result.text, "html.parser") pagination = soup.find("div", {"class": "h5_right_txt"}) if pagination: num = pagination.find("strong").string max_page = int(num) / 10 + 1 return int(max_page) else: return None def extract_comm(html, title, genre, M_ID): comment = html.get_text('|', strip=True).split('|')[3] score = html.find("em").string return {'id': M_ID, 'title': title, 'score': score, 'genre': genre, 'comment': comment} def extract_summary(M_ID): URL = f"https://movie.naver.com/movie/bi/mi/basic.nhn?code={M_ID}" # story_info = [] result = requests.get(URL) soup = BeautifulSoup(result.text, "html.parser") info = soup.find("div", {"class": "story_area"}) story = info.find("p").get_text(strip=True) return story def extract_comms(last_page, M_ID): # story = extract_summary(M_ID) # if story is None: # return URL = f"https://movie.naver.com/movie/point/af/list.nhn?st=mcode&sword={M_ID}&target=after" comments_info = [] result = requests.get(URL) soup = BeautifulSoup(result.text, "html.parser") info = soup.find("div", {"class": "choice_movie_info"}) title = info.find("h5").get_text(strip=True) genre = soup.find("td").get_text(strip=True).split('|')[0] if '๊ฐœ๋ด‰' in genre: return for page in range(last_page): print(f"Scrapping naver page {page+1}") result = requests.get(f"{URL}&page={page+1}") soup = BeautifulSoup(result.text, "html.parser") results = soup.find_all("td", {"class": "title"}) # print(results[0].get_text(strip=True)) for result in results: # comments['title']=title comm = extract_comm(result, title, genre, M_ID) # comments.update(extract_comm(result)) comments_info.append(comm) # print(comments_info) return comments_info # extract_comms(1) def get_movie_comm(i): last_page = get_last_page(i) if last_page is None: return story_info = [] story = extract_summary(i) if story is None: return story_d = {'id': i, 'story': story} story_info.append(story_d) save_to_file2(story_info) return # ๋ฐ‘์—๋Š” ์ฝ”๋ฉ˜ํŠธ ์ถ”์ถœํ•˜๋Š” ์ฝ”๋“œ ๋™์ž‘ ์‹œํ‚ค๋Š” ๋ถ€๋ถ„ # if last_page < 120: # comments = extract_comms(last_page, i) # else: # comments = extract_comms(120, i) # # if len(comments) is not 0: # # print(comments) # save_to_file(comments) # return comments <file_sep>''' ์˜ํ™” ์ค„๊ฑฐ๋ฆฌ ํฌ๋กค๋ง ํ•˜๋Š” ๋ชจ๋“ˆ ํฌ๋กค๋ง ์™„๋ฃŒ ์ดํ›„์— jsonํŒŒ์ผ์— ๋“ค์–ด๊ฐ€์„œ ํŒŒ์ผ ์ œ์ผ ๋งˆ์ง€๋ง‰ ๋ถ€๋ถ„ ",}" ์—์„œ ","๋ถ€๋ถ„์„ ์ง€์šฐ๊ณ  ์ €์žฅํ•  ๊ฒƒ ''' from nugu.movie_story_scrapper.crawling.naver_movie import get_movie_comm as get_comm import os import time from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm with open("comm3.json", mode="a+", encoding="utf-8-sig", newline='') as f: f.write('{') with ThreadPoolExecutor(max_workers=5) as executor: for i in range(1, 200000): executor.submit(get_comm, i) # with open("comm3.json", mode="a+", encoding="utf-8-sig", newline='') as f: # f.write('}') content = '' with open("comm3.json", mode="r", encoding="utf-8-sig", newline='') as f: content += f.read() with open("comm3.json", mode="w", encoding="utf-8-sig", newline='') as f: f.write(content[:-1] +"}")<file_sep>#-*- coding: utf-8 -*- import json import pickle # ์œ ์‚ฌ๋„๋ฅผ ๊ตฌํ•˜๊ธฐ ์œ„ํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ from numpy import dot from numpy.linalg import norm import numpy as np from datetime import datetime # import torch def load_corpus(_string_name): ''' load_corpus : ์˜ํ™” ๋ณ„ ๊ฐ€์ง€๋Š” (๋ช…์‚ฌ, ์šฉ์–ธ์œผ๋กœ ๊ตฌ์„ฑ๋œ) ๋‹จ์–ด๋“ค์ด ์ €์žฅ๋œ jsonํŒŒ์ผ์—์„œ dictํ˜•์‹์œผ๋กœ ๊ฐ–๊ณ ์˜ด :param _string_name: jsonํ˜•์‹์˜ ํŒŒ์ผ :return: ์˜ํ™”id๋ฅผ key๋กœ ๊ฐ€์ง€๊ณ , ํ•ด๋‹น ์˜ํ™”์˜ ๋‹จ์–ด๋“ค ๋ฆฌ์ŠคํŠธ๋ฅผ value๋กœ ๊ฐ€์ง€๋Š” dictํƒ€์ž… ๊ฐ์ฒด ''' with open(_string_name, 'r', encoding='utf-8-sig') as json_data: _corpus = json.load(json_data) # ์˜ํ™”๋ณ„ ๋‹จ์–ด ๋‹ค ๋“ค๊ณ ์˜ด return _corpus def avrgvec_to_dict(_corpus, _model, _vector_dict): ''' avrgvec_to_dict : ๊ฐ ์˜ํ™”์— ๋Œ€ํ•ด์„œ ๋‹จ์–ด ๋ฒกํ„ฐ๋“ค์˜ ํ‰๊ท ๋ฒกํ„ฐ๋ฅผ dictํ˜•์‹์œผ๋กœ ๋ฐ˜ํ™˜ํ•ด ์ฃผ๋Š” ๋ชจ๋“ˆ :param _corpus: ๊ฐ ์˜ํ™”์— ๋Œ€ํ•ด ๋‹จ์–ด๋“ค์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” dictํƒ€์ž… ๊ฐ์ฒด :param _model: ์ „์ฒด ์˜ํ™”์˜ ๋ช…์‚ฌ, ์šฉ์–ธ์— ๋Œ€ํ•œ word2vec๋ชจ๋ธ (gensim Word2vec model) :param _vector_dict: ๊ฐ ์˜ํ™”id์— ๋Œ€ํ•ด์„œ ํ•ด๋‹น ์˜ํ™”๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฒกํ„ฐ๋ฅผ ์ง€๋‹ˆ๋Š” dictํƒ€์ž… ๊ฐ์ฒด :return: ๊ฐ ์˜ํ™”id์— ๋Œ€ํ•ด์„œ ํ•ด๋‹น ์˜ํ™” ๋ฒกํ„ฐ๋ฅผ ๊ฐ€์ง€๋Š” dictํƒ€์ž… ๊ฐ์ฒด ''' for i, v in _corpus.items(): # ๊ฐ๊ฐ์˜ ์˜ํ™”์— ๋Œ€ํ•ด์„œ vector = np.zeros(100) # ๋จผ์ € word2vec๋ชจ๋ธ ๋ฒกํ„ฐ์˜ ์ฐจ์›์ด 100์ฐจ์›์ด๋ฏ€๋กœ, ์ฒ˜์Œ์— 100์ฐจ์›์˜ 0๋ฒกํ„ฐ๋กœ ์ดˆ๊ธฐํ™” count = 0 # ๋ชจ๋‘ ๋”ํ•œ ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜ (๋‚˜์ค‘์— ํ‰๊ท  ๊ตฌํ•  ๋•Œ count๋กœ ๋‚˜๋ˆ  ์ค„ ๊ฒƒ์ž„) for j in _corpus[i]: # ํ˜„์žฌ ๋ณด๊ณ  ์žˆ๋Š” ์˜ํ™”์—์„œ์˜ ๋ชจ๋“  ๋‹จ์–ด์— ๋Œ€ํ•ด์„œ if len(j) == 1: # ๋งŒ์•ฝ ๋‹จ์–ด ํฌ๊ธฐ๊ฐ€ 1์ด๋ผ๋ฉด continue # ๋„˜์–ด๊ฐ try: temp = _model.wv[j] # ๋‹จ์–ด ๋ฒกํ„ฐ๋ฅผ ๊ฐ–๊ณ ์˜ด vector += temp # ๋‹จ์–ด ๋ฒกํ„ฐ ๋”ํ•ด์คŒ count += 1 # ๋”ํ•œ ๋‹จ์–ด ๋ฒกํ„ฐ ์นด์šดํŠธํ•ด์ค€๋‹ค. except: pass try: my_vector = vector / count # ์ด ํ•ฉ๋ฒกํ„ฐ, ํ•ฉํ•œ ๋ฒกํ„ฐ ์ˆ˜, ํ‰๊ท ๋ฒกํ„ฐ _vector_dict[i] = my_vector # ๊ฐ ์˜ํ™” id๋ฅผ key๋กœ ํ•˜๊ณ , ์˜ํ™”๋ฒกํ„ฐ๋ฅผ value๋กœ ํ•ด์„œ dict์— ์ €์žฅ except: pass return _vector_dict def save_as_pickle(_dict, _string_name): ''' save_as_pickle : ์˜ํ™” id์— ๋Œ€ํ•œ ์˜ํ™” ๋ฒกํ„ฐ๋ฅผ ์ง€๋‹ˆ๋Š” dictํƒ€์ž… ๊ฐ์ฒด๋ฅผ pickle ํŒŒ์ผ์œผ๋กœ ์ €์žฅํ•˜๋Š” ๋ชจ๋“ˆ :param _dict: ์˜ํ™” id์— ๋Œ€ํ•œ ์˜ํ™” ๋ฒกํ„ฐ๋ฅผ ์ง€๋‹ˆ๋Š” dictํƒ€์ž… ๊ฐ์ฒด :param _string_name: ์ €์žฅํ•  ํŒŒ์ผ ์ด๋ฆ„ :return: None ''' with open(_string_name + '.bin', 'wb') as f: pickle.dump(_dict, f) def load_from_pickle(_string_name): ''' load_from_pickle : pickleํŒŒ์ผ์—์„œ ์˜ํ™” id์— ๋Œ€ํ•œ ์˜ํ™” ๋ฒกํ„ฐ๋ฅผ ์ง€๋‹ˆ๋Š” dictํƒ€์ž… ๊ฐ์ฒด๋กœ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ๋ชจ๋“ˆ :param _string_name: pickle ํŒŒ์ผ ์ด๋ฆ„ :return: ์˜ํ™” id์— ๋Œ€ํ•œ ์˜ํ™” ๋ฒกํ„ฐ๋ฅผ ์ง€๋‹ˆ๋Š” dictํƒ€์ž… ๊ฐ์ฒด ''' with open(_string_name + '.bin', 'rb') as f: _dict = pickle.load(f) return _dict def cos_sim(A, B): ''' cos_sim : 2๊ฐœ์˜ ๋ฒกํ„ฐ์— ๋Œ€ํ•ด์„œ ์ฝ”์‚ฌ์ธ ์œ ์‚ฌ๋„๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ๋ชจ๋“ˆ :param A: ์˜ํ™” ๋ฒกํ„ฐ A :param B: ์˜ํ™” ๋ฒกํ„ฐ B :return: ์˜ํ™” ๋ฒกํ„ฐ A, B์‚ฌ์ด์˜ ์œ ์‚ฌ๋„๋ฅผ ๊ตฌํ•ด์„œ ๋ฐ˜ํ™˜ํ•ด์คŒ ''' # x = torch.Tensor(A) # y = torch.Tensor(B) # print(x, y) return dot(A, B) / (norm(A) * norm(B)) # def get_similarities_from_title(_string_title, _mid_mname, _vector_dict): # ''' # get_similarities_from_title : ์˜ํ™” # # :param _string_title: # :param _mid_mname: # :param _vector_dict: # :return: # ''' # tmp_id = [] # sim_score = [] # for k, v in _mid_mname.items(): # if str(v) == _string_title: # tmp_id.append(k) # # if not len(tmp_id) == 0: # mid = tmp_id[0] # crt_vec = _vector_dict[str(mid)] # for key, value in _vector_dict.items(): # score = cos_sim(crt_vec, value) # sim_score.append([key, score]) # result = sorted(sim_score, key=lambda sim_score: sim_score[1], reverse=True) # # result = result[1:11] # return result # else: # print('NO MATCH!') def get_similarities(_entity, _mid_mname, _vector_dict, is_vector): ''' get_similarities: ์˜ํ™” ์ค„๊ฑฐ๋ฆฌ์— ๋Œ€ํ•œ ์œ ์‚ฌ๋„๋ฅผ ๊ตฌํ•ด์„œ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ :param _entity: ์ถ”์ฒœ entity :param _mid_mname: {์˜ํ™” id: ์˜ํ™” ์ œ๋ชฉ} ์„ ๊ฐ€์ง€๋Š” dict :param _vector_dict: { ์˜ํ™” id: ์˜ํ™” ๋ฒกํ„ฐ } ๋ฅผ ๊ฐ€์ง€๋Š” dict :return: ''' mid = -1 sim_score = {} if is_vector: # ์œ ์‚ฌ๋„ ๋น„๊ตํ•  entity๋กœ ๋ฒกํ„ฐ๊ฐ€ ์™”์„ ๋•Œ crt_vec = _entity else: # entity๋กœ ๋ฒกํ„ฐ๊ฐ€ ์•„๋‹Œ ์˜ํ™” ์ œ๋ชฉ์œผ๋กœ ์™”์„ ๋•Œ tmp_id = [] print(datetime.now(), '2.1') for k, v in _mid_mname.items(): if str(v) == _entity: # ๋™์ผํ•œ ์ œ๋ชฉ์„ ์ง€๋‹Œ ์˜ํ™”์— ๋Œ€ํ•ด์„œ tmp_id.append(k) # ์˜ํ™” id๋ฅผ ์ €์žฅ print(datetime.now(), '2.2') if not len(tmp_id) == 0: mid = tmp_id[0] # ์ œ์ผ ์ฒ˜์Œ์— ๋ฐ›์€ ์˜ํ™” id์— ๋Œ€ํ•ด์„œ try: crt_vec = _vector_dict[str(mid)] # ํ•ด๋‹น ์˜ํ™”์˜ ๋ฒกํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜จ๋‹ค. except: return None else: print('NO MATCH!') return None print(datetime.now(), '2.2.1') for key, value in _vector_dict.items(): # ๋ชจ๋“  ์˜ํ™”์— ๋Œ€ํ•ด์„œ if key == str(mid): # ๋™์ผํ•œ ์˜ํ™”๋Š” ์ œ์™ธํ•˜๊ณ  continue score = cos_sim(crt_vec, value) # consine ์œ ์‚ฌ๋„๋ฅผ ๊ตฌํ•œ๋‹ค. sim_score[key] = score # {์˜ํ™” id: ์œ ์‚ฌ๋„} ์ €์žฅ # result = result[1:11] print(datetime.now(), '2.3') return sim_score # {์˜ํ™” id: ์œ ์‚ฌ๋„} ๋ฅผ ์ง€๋‹ˆ๋Š” dict ๋ฐ˜ํ™˜ def main(entity, is_vector): ''' main: ์ค„๊ฑฐ๋ฆฌ์— ๋Œ€ํ•œ ์œ ์‚ฌ๋„๋ฅผ ๊ตฌํ•ด์„œ {์˜ํ™” id: ์œ ์‚ฌ๋„} dict๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ :param entity: ์˜ํ™” ์ถ”์ฒœ entity (๊ฐœ์ธ ๋ฒกํ„ฐ, ์˜ํ™” ๋ฒกํ„ฐ...) :param is_vector: ๋ฒกํ„ฐ์ธ์ง€ ์•„๋‹Œ์ง€ ์•Œ๋ ค์ฃผ๋Š” flag (True : ๋ฒกํ„ฐ, False : String) :return: {์˜ํ™” id: ์œ ์‚ฌ๋„} dict ''' vector_dict = {} corpus_name = 'comm3.json' address = 'nugu/movie_story_scrapper/' model_name = 'story_20191205_1654' # ๋ชจ๋ธ ์ด๋ฆ„ dict_name = 'dict_20191206_1937' dict_name_2 = 'dict_mid_mname' # ํ‰๊ท  ๋ฒกํ„ฐ ๊ตฌํ•ด์„œ ๋”•์…”๋„ˆ๋ฆฌ ํ˜•ํƒœ๋กœ ์ €์žฅํ•˜๋Š” ์ฝ”๋“œ # ๋ฐ์ดํ„ฐ ๋ถ€์กฑํ•œ ์˜ํ™”๋Š” ์ €์žฅํ•˜์ง€ ์•Š์•˜์Œ (count๊ฐ€ 0) # corpus = load_corpus(corpus_name) # model = Word2Vec.load(model_name) # pre-trained๋œ word2vec ๋ชจ๋ธ ๋กœ๋“œํ•จ # vector_dict = avrgvec_to_dict(corpus, model, vector_dict) # save_as_pickle(vector_dict, dict_name) vector_dict = load_from_pickle(address + dict_name) # {์˜ํ™” id: ์˜ํ™” ๋ฒกํ„ฐ} dict mid_mname = load_from_pickle(address + dict_name_2) # {์˜ํ™” id: ์˜ํ™” ์ œ๋ชฉ} dict sim_result = get_similarities(entity, mid_mname, vector_dict, is_vector) # ์ค„๊ฑฐ๋ฆฌ์— ๋Œ€ํ•œ ์œ ์‚ฌ๋„๋ฅผ ๊ณ„์‚ฐํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ # for mid, score in sim_result: # print(mid_mname[int(mid)], score) # print(cos_sim(vector_dict['190254'], vector_dict['10001'])) return sim_result # if __name__ == "__main__": # # main(sys.argv[1], sys.argv[2]) # main(sys.argv[1], False) <file_sep>#-*- coding: utf-8 -*- import pandas as pd from tqdm import tqdm from gensim.models.word2vec import Word2Vec from datetime import datetime import json with open('comm3.json', 'r', encoding='utf-8-sig') as json_file: json_data = json.load(json_file) model = Word2Vec(list(json_data.values()), size=100, window=3, min_count=20, workers=50) model.init_sims(replace=True) model.save('story_'+str(datetime.now()).replace('-', '').replace(' ', '_').replace(':', '')[:13]) del(json_data)<file_sep>import pandas as pd from tqdm import tqdm from gensim.models.word2vec import Word2Vec from datetime import datetime num = 0 tmp_list = [] while True: dic = {} num += 1 _filename = './comm_n_and_v_utf8_'+str(num)+'_ordered_q.csv' encoding = 'utf-8' columns = ['mid', 'mname', 'score', 'genre', 'comments'] try: read = pd.read_csv(_filename, encoding=encoding, header=None, names=columns, low_memory=False) except: break for i in tqdm(range(0, len(read.mid))): try: temp = [x.strip() for x in read.comments[i].split(',')] for j in temp: if len(j) == 1: temp.remove(j) tmp_list.append(temp) except: pass model = Word2Vec(tmp_list, size=100, window=3, min_count=20, workers=50) model.init_sims(replace=True) model.save('C:/Users/Yeon/PycharmProjects/SAnalysis/movie_comment_scrapper/comm_'+str(datetime.now()).replace('-', '').replace(' ', '_').replace(':', '')[:13]) del(tmp_list) <file_sep>#-*- coding: utf-8 -*- import sys import logging import warnings warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim') import pickle from nugu.movie_story_scrapper.get_recommendations import main as get_story_reco from nugu.movie_comment_scrapper.get_recommendations import main as get_comm_reco import pandas as pd import numpy as np from datetime import datetime import json def get_prsnl_vector(id): ''' get_prsnl_vector: id์— ๋งž๋Š” ๊ฐœ์ธ ์ถ”์ฒœ ๋ฒกํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ :param id: user id๋ฅผ String์œผ๋กœ ๋ฐ›์Œ :return: user์— ๋Œ€ํ•œ ๊ฐœ์ธ ์ถ”์ฒœ ๋ฒกํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์คŒ ''' address = 'nugu/movie_story_scrapper/' dict_name = 'dict_20191206_1937' # with open(address + dict_name + '.bin', 'rb') as f: _dict = pickle.load(f) vector = np.zeros(100) df = pd.read_csv("nugu/user_log.csv") # id, mid, time์œผ๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ์Œ count = 0 for i in range(len(df)): # ๋ชจ๋“  user log์— ๋Œ€ํ•ด์„œ if str(df['id'][i]) == id: # ํ˜„์žฌ user id์— ๋Œ€ํ•œ log๋ผ๋ฉด try: vector += _dict[str(df['mid'][i])] # ํ•ด๋‹น mid๋ฅผ ๊ฐ€์ง€๋Š” ์˜ํ™” ๋ฒกํ„ฐ๋ฅผ ๋”ํ•ด์ค€๋‹ค. count += 1 except: continue if count != 0: vector = list(np.dot(vector, 1/count)) # ๊ทธ๋ฆฌ๊ณ  ์˜ํ™” ๋ฒกํ„ฐ๋“ค์˜ ํ‰๊ท ์„ ๊ตฌํ•ด์ค€๋‹ค. return vector # ๊ทธ๋ฆฌ๊ณ  ์ด๋ฅผ ๊ฐœ์ธ ์˜ํ™” ์ถ”์ฒœ ๋ฒกํ„ฐ๋กœ ์‚ผ์•„ ๋ฐ˜ํ™˜ํ•ด์ค€๋‹ค. def get_reco(entity, is_vector, n): ''' get_reco: ์ถ”์ฒœ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ†ตํ•ด์„œ Top N๊ฐœ์˜ ์˜ํ™”๋ฅผ ์ถ”์ฒœํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ :param entity: ์œ ์ €๊ฐ€ ์ถ”์ฒœ ์š”์ฒญ์„ ํ•œ entity (์˜ํ™” ๋ฒกํ„ฐ, ๊ฐœ์ธ ๋ฒกํ„ฐ, ์žฅ๋ฅด) :param is_vector: ๋“ค์–ด์˜จ entity๊ฐ€ ๋ฒกํ„ฐ ํ˜•์‹์ธ์ง€ ์•„๋‹Œ์ง€ ํ‘œ์‹œํ•ด ์ฃผ๋Š” flag :param n: ์ถ”์ฒœํ•  n๊ฐœ์˜ ์˜ํ™” :return: ์œ ์‚ฌ๋„ ๋†’์€ n๊ฐœ์˜ ์˜ํ™” ์ œ๋ชฉ์„ ์ง€๋‹Œ ๋ฆฌ์ŠคํŠธ ๋ฐ˜ํ™˜ ''' w_story = 0.4 # ์ค„๊ฑฐ๋ฆฌ ์œ ์‚ฌ๋„์— ๋Œ€ํ•œ ๊ฐ€์ค‘์น˜ w_comment = 0.6 # ํ•œ์ค„ํ‰ ์œ ์‚ฌ๋„์— ๋Œ€ํ•œ ๊ฐ€์ค‘์น˜ story_sim = get_story_reco(entity, is_vector) # ์ค„๊ฑฐ๋ฆฌ์— ๋Œ€ํ•œ {์˜ํ™”id: ์œ ์‚ฌ๋„} ํ˜•ํƒœ์˜ dict ๋ฐ˜ํ™˜ comment_sim = get_comm_reco(entity, is_vector) # ํ•œ์ค„ํ‰์— ๋Œ€ํ•œ {์˜ํ™”id: ์œ ์‚ฌ๋„} ํ˜•ํƒœ์˜ dict ๋ฐ˜ํ™˜ with open('nugu/dict_mid_mname.bin', 'rb') as f: # {์˜ํ™” id : ์˜ํ™” ์ œ๋ชฉ} ํ˜•ํƒœ์˜ dict ID_dict = pickle.load(f) entire_sim = [] # ๊ฐ€์ค‘์น˜ ๊ณ„์‚ฐ์„ ํ†ตํ•œ ์ตœ์ข… ์œ ์‚ฌ๋„๋ฅผ ์ €์žฅํ•  ๋ฆฌ์ŠคํŠธ try: for k, v in comment_sim.items(): try: sim = (w_story * story_sim[k]) + (w_comment * v) # ์ค„๊ฑฐ๋ฆฌ ๊ฐ€์ค‘์น˜ * ์ค„๊ฑฐ๋ฆฌ ์œ ์‚ฌ๋„ + ํ•œ์ค„ํ‰ ๊ฐ€์ค‘์น˜ * ํ•œ์ค„ํ‰ ์œ ์‚ฌ๋„ = ์ตœ์ข… ์œ ์‚ฌ๋„ entire_sim.append((sim, k)) except: continue except: return [] entire_sim.sort(reverse=True) # ์œ ์‚ฌ๋„ ๋†’์€ ์ˆœ์œผ๋กœ ์ •๋ ฌ print([(ID_dict[int(x[1])], x[0]) for x in entire_sim[:n]]) return [ID_dict[int(x[1])] for x in entire_sim[:n]] # ์œ ์‚ฌ๋„ ๋†’์€ ์ˆœ์œผ๋กœ ์˜ํ™” ์ œ๋ชฉ n๊ฐœ ๋ฐ˜ํ™˜ def get_reco2(prsnl_vector, reco_entity, include_genre, n): ''' get_reco2: ๊ฐœ์ธ ์˜ํ™” ์ถ”์ฒœ, ์žฅ๋ฅด ์ถ”์ฒœ์„ ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ :param prsnl_vector: ๊ฐœ์ธ ์ถ”์ฒœ ๋ฒกํ„ฐ (์œ ์ €์˜ ์‹œ์ฒญ ๊ธฐ๋ก์„ ํ† ๋Œ€๋กœ ์ƒ์„ฑ๋œ ๋ฒกํ„ฐ) :param reco_entity: ์žฅ๋ฅด ์ถ”์ฒœ์˜ ๊ฒฝ์šฐ ์žฅ๋ฅด ์ด๋ฆ„์ด ๋„˜์–ด์˜จ๋‹ค. ex) ๊ณตํฌ, ๋“œ๋ผ๋งˆ, ๋กœ๋งจ์Šค, ... :param include_genre: ์žฅ๋ฅด ์ถ”์ฒœ์ธ์ง€ ์•„๋‹Œ์ง€(๊ฐœ์ธ ์˜ํ™” ์ถ”์ฒœ) ํŒ๋‹จํ•ด์ฃผ๋Š” (True: ์žฅ๋ฅด ์ถ”์ฒœ, False: ๊ฐœ์ธ ์ถ”์ฒœ) :param n: ์ถ”์ฒœํ•  n๊ฐœ์˜ ์˜ํ™” :return: ์œ ์‚ฌ๋„ ๋†’์€ n๊ฐœ์˜ ์˜ํ™” ์ œ๋ชฉ์„ ์ง€๋‹Œ ๋ฆฌ์ŠคํŠธ ๋ฐ˜ํ™˜ ''' w_story = 0.4 # ์ค„๊ฑฐ๋ฆฌ ์œ ์‚ฌ๋„์— ๋Œ€ํ•œ ๊ฐ€์ค‘์น˜ w_comment = 0.6 # ํ•œ์ค„ํ‰ ์œ ์‚ฌ๋„์— ๋Œ€ํ•œ ๊ฐ€์ค‘์น˜ story_sim = get_story_reco(prsnl_vector, True) # ๊ฐœ์ธ ์ถ”์ฒœ ๋ฒกํ„ฐ์— ๋Œ€ํ•ด์„œ ์ค„๊ฑฐ๋ฆฌ์— ๋Œ€ํ•œ {์˜ํ™”id: ์œ ์‚ฌ๋„} ํ˜•ํƒœ์˜ dict ๋ฐ˜ํ™˜ comment_sim = get_comm_reco(prsnl_vector, True) # ๊ฐœ์ธ ์ถ”์ฒœ ๋ฒกํ„ฐ์— ๋Œ€ํ•ด์„œ ํ•œ์ค„ํ‰์— ๋Œ€ํ•œ {์˜ํ™”id: ์œ ์‚ฌ๋„} ํ˜•ํƒœ์˜ dict ๋ฐ˜ํ™˜ with open('nugu/dict_mid_mname.bin', 'rb') as f: # {์˜ํ™” id : ์˜ํ™” ์ œ๋ชฉ} ํ˜•ํƒœ์˜ dict ID_dict = pickle.load(f) with open('nugu/dict_mid_genre_real_eincluded_1212.bin', 'rb') as f: # {์˜ํ™” id : [์žฅ๋ฅด]} ํ˜•ํƒœ์˜ dict mid_genre_dict = pickle.load(f) entire_sim = [] # ๊ฐ€์ค‘์น˜ ๊ณ„์‚ฐ์„ ํ†ตํ•œ ์ตœ์ข… ์œ ์‚ฌ๋„๋ฅผ ์ €์žฅํ•  ๋ฆฌ์ŠคํŠธ try: for k, v in comment_sim.items(): try: sim = (w_story * story_sim[k]) + (w_comment * v) # ์ค„๊ฑฐ๋ฆฌ ๊ฐ€์ค‘์น˜ * ์ค„๊ฑฐ๋ฆฌ ์œ ์‚ฌ๋„ + ํ•œ์ค„ํ‰ ๊ฐ€์ค‘์น˜ * ํ•œ์ค„ํ‰ ์œ ์‚ฌ๋„ = ์ตœ์ข… ์œ ์‚ฌ๋„ entire_sim.append((sim, k)) except: continue except: return [] entire_sim.sort(reverse=True) # ์œ ์‚ฌ๋„ ๋†’์€ ์ˆœ์œผ๋กœ ์ •๋ ฌ if not include_genre: # ๋งŒ์•ฝ ๊ฐœ์ธ ์ถ”์ฒœ ์š”์ฒญ์ด๋ผ๋ฉด return [ID_dict[int(x[1])] for x in entire_sim[:n]] # ์œ ์‚ฌ๋„ ๋†’์€ ์ˆœ์œผ๋กœ ์˜ํ™” ์ œ๋ชฉ n๊ฐœ ๋ฐ˜ํ™˜ # ์žฅ๋ฅด ์ถ”์ฒœ new_sim = entire_sim[:1000] # ๊ฐœ์ธ ์ถ”์ฒœ ๋ฒกํ„ฐ์™€ ์œ ์‚ฌํ•œ 1000๊ฐœ์˜ ์˜ํ™”๋“ค์„ ๋ฝ‘์•„๋ƒ„. count = 0 count_list = [] temp_list = [] for x in new_sim: # ์œ ์‚ฌํ•œ 1000๊ฐœ์˜ ์˜ํ™”๋“ค ์ค‘์—์„œ count = count + 1 if reco_entity in mid_genre_dict[int(x[1])]: # ์œ ์ €๊ฐ€ ์›ํ•˜๋Š” ์žฅ๋ฅด๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์˜ํ™”๋ฅผ ๋”ฐ๋กœ ์ €์žฅ temp_list.append(x) for item in count_list: del new_sim[int(item)] return [ID_dict[int(x[1])] for x in temp_list[:n]] # ์œ ์‚ฌ๋„ ๋†’์€ ์ˆœ์œผ๋กœ ์˜ํ™” ์ œ๋ชฉ n๊ฐœ ๋ฐ˜ํ™˜ def main(reco_num, reco_entity): ''' main: ์ถ”์ฒœ๋„๊ฐ€ ๋†’์€ ์˜ํ™” ์ œ๋ชฉ๋“ค์„ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ :param reco_num: ์ถ”์ฒœ ์ข…๋ฅ˜ (1: ๊ฐœ์ธ ์ถ”์ฒœ, 2: ์žฅ๋ฅด ์ถ”์ฒœ, 3: ์œ ์‚ฌ ์˜ํ™” ์ถ”์ฒœ) :param reco_entity: user๊ฐ€ ์›ํ•˜๋Š” ์ถ”์ฒœ์— ๋Œ€ํ•œ entity :return: ์ถ”์ฒœ๋„์— ๋”ฐ๋ฅธ ์˜ํ™” ์ œ๋ชฉ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ๋ฆฌ์ŠคํŠธ ''' n = 10 # ์ถ”์ฒœ๋ฐ›์„ ์˜ํ™” ๊ฐœ์ˆ˜ if reco_num == '1': # ๊ฐœ์ธ ์ถ”์ฒœ # with open(address + dict_name + '.bin', 'rb') as f: # _dict = pickle.load(f) # prsnl_vector = _dict['10001'] # ์‹œ๋„ค๋งˆ ์ฒœ๊ตญ์ด ์ผ๋‹จ์€ ๋ฒกํ„ฐ๊ฐ’์œผ๋กœ ๋“ค์–ด๊ฐ€๊ฒŒ ๋œ๋‹ค prsnl_vector = get_prsnl_vector(reco_entity) # return get_reco2(prsnl_vector, reco_entity, False, n) elif reco_num == '2': # ์žฅ๋ฅด ์ถ”์ฒœ prsnl_vector = get_prsnl_vector(reco_entity) print(prsnl_vector) return get_reco2(prsnl_vector, reco_entity, True, n) elif reco_num == '3': # ์œ ์‚ฌ ์˜ํ™” ์ถ”์ฒœ return get_reco(reco_entity, False, n) else: logging.info("์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. 1.๊ฐœ์ธ์ถ”์ฒœ 2.์žฅ๋ฅด์ถ”์ฒœ 3.์œ ์‚ฌ์˜ํ™”์ถ”์ฒœ") return None # if __name__ == "__main__": # ''' # python get_recommendations.py {arg 1} {arg 2} # [arg 1 : ์ถ”์ฒœ ์ข…๋ฅ˜] # ๊ฐœ์ธ์ถ”์ฒœ : 1 # ์žฅ๋ฅด์ถ”์ฒœ : 2 # ์œ ์‚ฌ์˜ํ™”์ถ”์ฒœ : 3 # # [arg 2 : ์ถ”์ฒœ entity] # ๊ฐœ์ธ์ถ”์ฒœ ex) 'ํ•ด๋‹น ์‚ฌ๋žŒ์˜ ID' # ์žฅ๋ฅด์ถ”์ฒœ ex) '๊ณตํฌ', '๋“œ๋ผ๋งˆ', '์Šค๋ฆด๋Ÿฌ', '์•ก์…˜', ... # ์œ ์‚ฌ์˜ํ™”์ถ”์ฒœ ex) '์‹ ๊ณผํ•จ๊ป˜', '๋ช…๋Ÿ‰', ... # ''' # print(main(sys.argv[1], sys.argv[2])) <file_sep>from gensim.models.word2vec import Word2Vec import matplotlib.pyplot as plt from sklearn.decomposition import PCA import matplotlib font_name = matplotlib.font_manager.FontProperties( fname="C:/Windows/Fonts/gulim.ttc" # ํ•œ๊ธ€ ํฐํŠธ ์œ„์น˜๋ฅผ ๋„ฃ์–ด์ฃผ์„ธ์š” ).get_name() matplotlib.rc('font', family=font_name) def plot_2d_graph(vocabs, xs, ys): plt.figure(figsize=(8,6)) plt.scatter(xs, ys, marker ='o') for i, v in enumerate(vocabs): plt.annotate(v, xy=(xs[i], ys[i])) plt.show() model = Word2Vec.load('../20191124_0200') word_vectors = model.wv print(model.wv['๊น€ํ˜œ์ˆ˜']) print(model.wv.most_similar('์š•์ •')) print(model.wv.most_similar('์žฌ๋ฏธ')) print(model.wv.most_similar('์žฌ๋ฐŒ')) print(model.most_similar(positive=['๊น€ํ˜œ์ˆ˜', '๋ ˆ์ด์ฒผ'], negative=['์—ฌ์ž', '์—ฌ๋ฐฐ์šฐ'], topn=10)) vocabs = word_vectors.vocab.keys() word_vectors_list = [word_vectors[v] for v in vocabs] # pca = PCA(n_components=2) # xys = pca.fit_transform(word_vectors_list) # xs = xys[:, 0] # ys = xys[:, 1] # #plot_2d_graph(vocabs, xs, ys) # from sklearn.decomposition import IncrementalPCA # inital reduction # from sklearn.manifold import TSNE # final reduction # import numpy as np # array handling # from gensim.models.word2vec import Word2Vec # import matplotlib.pyplot as plt # from sklearn.decomposition import PCA # import matplotlib # from plotly.offline import init_notebook_mode, iplot, plot # import plotly.graph_objs as go # import random # # font_name = matplotlib.font_manager.FontProperties( # fname="C:/Windows/Fonts/gulim.ttc" # ํ•œ๊ธ€ ํฐํŠธ ์œ„์น˜๋ฅผ ๋„ฃ์–ด์ฃผ์„ธ์š” # ).get_name() # matplotlib.rc('font', family=font_name) # model = Word2Vec.load('20191123_2300') # # def reduce_dimensions(model): # num_dimensions = 2 # final num dimensions (2D, 3D, etc) # # vectors = [] # positions in vector space # labels = [] # keep track of words to label our data again later # for word in model.wv.vocab: # vectors.append(model.wv[word]) # labels.append(word) # # # convert both lists into numpy vectors for reduction # vectors = np.asarray(vectors) # labels = np.asarray(labels) # # # reduce using t-SNE # vectors = np.asarray(vectors) # tsne = TSNE(n_components=num_dimensions, random_state=0) # vectors = tsne.fit_transform(vectors) # # x_vals = [v[0] for v in vectors] # y_vals = [v[1] for v in vectors] # return x_vals, y_vals, labels # # # x_vals, y_vals, labels = reduce_dimensions(model) # # def plot_with_plotly(x_vals, y_vals, labels, plot_in_notebook=True): # # trace = go.Scatter(x=x_vals, y=y_vals, mode='text', text=labels) # data = [trace] # # if plot_in_notebook: # init_notebook_mode(connected=True) # iplot(data, filename='word-embedding-plot') # else: # plot(data, filename='word-embedding-plot.html') # # # def plot_with_matplotlib(x_vals, y_vals, labels): # # random.seed(0) # # plt.figure(figsize=(12, 12)) # plt.scatter(x_vals, y_vals) # # # # # Label randomly subsampled 25 data points # # # indices = list(range(len(labels))) # selected_indices = random.sample(indices, 25) # for i in selected_indices: # plt.annotate(labels[i], (x_vals[i], y_vals[i])) # plt.show() # # try: # get_ipython() # except Exception: # plot_function = plot_with_matplotlib # else: # plot_function = plot_with_plotly # # plot_function(x_vals, y_vals, labels)<file_sep>#-*- coding: utf-8 -*- import re import MeCab from datetime import datetime def save_to_file2(comm_info): m = MeCab.Tagger() with open("comm3.json", mode="a+", encoding="utf-8-sig", newline='') as f: word_list = [] tagged_str = m.parse(comm_info[0]['story']) tagged_str = list(re.split('\t|\n',tagged_str)) for i in range(1, len(tagged_str), 2): if tagged_str[i].startswith('NN') or tagged_str[i].startswith('V'): # ๋ช…์‚ฌ์™€ ์šฉ์–ธ์œผ๋กœ ๋œ ๊ฒƒ์„ ๋ฝ‘์•„๋‚ธ๋‹ค word_list.append(tagged_str[i - 1]) temp = str({str(comm_info[0]['id']) : word_list}).replace("'", '\"') f.write(temp[1:-1]+', ') if comm_info[0]['id'] % 2000 == 0: print("current id : {}, {}% completed, time : {}".format(comm_info[0]['id'], int(comm_info[0]['id']/2000), datetime.now())) return
73de4c6e8ea9dac90d94b0018869313086f4e76d
[ "Markdown", "Python" ]
19
Python
momentum1993/NUGU_movie_recommendation
4fc106ec4f3a7e44813aa52912134b68b3902235
79f43cd867cf07c1c1308731295e71a79f29baa7
refs/heads/master
<file_sep>from room import Room from player import Player from item import Item # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons", [Item("sword", "this sword has dull edges")]), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east.""",[Item("bow", "a bow with no arrows")]), 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm.""",[Item("arrows", "a box of arrows are neatly stored here")]), 'narrow': Room("Narrow Passage", """The narrow passage bends here from west to north. The smell of gold permeates the air.""",[Item("gun", "the gun is jammed")]), 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south.""", [Item("longsword", "this sword has sharp edges")]), } # Link rooms together room['outside'].n_to = room['foyer'] room['foyer'].s_to = room['outside'] room['foyer'].n_to = room['overlook'] room['foyer'].e_to = room['narrow'] room['overlook'].s_to = room['foyer'] room['narrow'].w_to = room['foyer'] room['narrow'].n_to = room['treasure'] room['treasure'].s_to = room['narrow'] # # Main # import textwrap # grabs user input def grab_input(): command = input("\nPlease enter an action: ") command = command.strip().lower().split(" ") if len(command) < 2: if command[0] == "q": exit() elif command[0] in ["n", "s", "e", "w"]: return command[0] elif command[0] in ["i", "inventory"]: print(f"Current Inventory: {player.inventory}") else: print("Invalid entry! Please use 'n', 's', 'e' or 'w' to navigate rooms\nEnter 'i' to view the rooms inventory\nEnter 'q' to exit the game") grab_input() else: if command[0] in ["get", "take"]: add_item(command[1]) elif command[0] == "drop": drop_item(command[1]) else: print("Invalid action: ") grab_input() # add item to player inventory and remove it from room def add_item(item): for i, val in enumerate(player.current_room.items): if str(item) == str(val): player.inventory.append(player.current_room.items[i]) player.current_room.items[i].on_take(val) player.current_room.items.remove(val) elif i >= len(player.current_room.items) - 1: print("\nItem not in room\n") # drop item from player inventory and add it to room def drop_item(item): for i, val in enumerate(player.inventory): if str(item) == str(val): player.current_room.items.append(val) player.inventory.remove(val) player.current_room.items[i].on_drop(item) elif i >= len(player.current_room.items) - 1: print("\nItem not in inventory\n") # checks to see if room has direction attribute def try_direction(direction, current_room): attribute = direction + "_to" if hasattr(current_room, attribute): return getattr(current_room, attribute) else: print(direction_error(direction)) return current_room # error messages for invalid room directions def direction_error(direction): if direction == "n": return "There is no room to the North\n" elif direction == "s": return "There is no room to the South\n" elif direction == "e": return "There is no room to the East\n" elif direction == "w": return "There is no room to the West\n" else: return "Goodbye!" # message for room items def print_items(item_list): if len(item_list) > 0: for i, val in enumerate(item_list): print(f"A {item_list[i]} can be found in this room. " + f"To take the {item_list[i]}, type 'get [item name]' or 'take [item name]' ") print("Welcome to the game!\n") username = input("Please enter your players name: ") print(f"\nHello {username}, within this game you can navigate rooms using n, s, w, or e\n") # Make a new player object that is currently in the 'outside' room. player = Player(username, room["outside"]) # Write a loop that: # # * Prints the current room name # * Prints the current description (the textwrap module might be useful here). # * Waits for user input and decides what to do. # # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. # # If the user enters "q", quit the game. action = None while (action != "q"): print("Current Position: " + textwrap.fill(player.current_room.name + ". " + player.current_room.description, width=50)) print_items(player.current_room.items) action = grab_input() if action in ["n", "s", "e", "w"]: player.current_room = try_direction(action, player.current_room)<file_sep># Implement a class to hold room information. This should have name and # description attributes. class Room(): def __init__(self, name, description, items=[]): self.name = name self.description = description self.items = items def add_item(self, item): self.items.append(item) def display_items(self): if len(self.items) == 0: return None else: for i in self.items: print(f"{i.name}") def __repr__(self): return f"{self.name}"
d359bcec0114a0ef4d594066bd6e07ddc11c4265
[ "Python" ]
2
Python
kmonique/Intro-Python-II
2c4505b7ec014eee37356941072ef3017c89cfb4
b48b955447cfc8c502732bf632017fa7f279c8ce
refs/heads/master
<file_sep>package com.testRedis.test; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class FistRedis { JedisPool jedisPool ; Jedis jedis; @Before public void setUp(){ jedisPool = new JedisPool(new JedisPoolConfig(),"127.0.0.1"); jedis = jedisPool.getResource(); } //@Test public void Test(){ //System.out.println(jedis.get("i"));; jedis.set("name", "wangwu"); //ๅญ˜ๅ‚จๅญ—็ฌฆไธฒ jedis.append("name", "liu"); //่ฟฝๅŠ ๅญ—็ฌฆไธฒ System.out.println(jedis.get("name")); jedis.del("name");//ๅˆ ้™คnameๅฏนๅบ”่ฎฐๅฝ• jedis.mset("name","dabing","age","5");//่ฎพ็ฝฎๅคšไธชๅ€ผ System.out.println(jedis.mget("name","age")); Map<String,String> map = new HashMap<String,String>(); map.put("a", "xiaowang"); map.put("b", "xiaohong"); jedis.hmset("map", map); //่ฎพ็ฝฎmap //็งป้™คๆ‰€ๆœ‰ๆ•ฐๆฎ jedis.del("list"); System.out.println(jedis.lrange("list", 0, -1)); jedis.lpush("list", "a"); jedis.lpush("list", "b"); jedis.lpush("list", "c"); System.out.println(jedis.lrange("list",0,jedis.llen("list"))); //lrange 1:key 2:่ตทๅง‹ไฝ็ฝฎ, ไปŽ้›ถๅผ€ๅง‹, 3:็ป“ๆŸไฝ็ฝฎ,-1่กจ็คบๆ‰€ๆœ‰, llenๅฏไปฅ่Žทๅ–้•ฟๅบฆ } @Test public void basicTest() throws InterruptedException{ System.out.println(jedis.keys("*")); //่ฟ”ๅ›žๅฝ“ๅ‰ๅบ“ไธญๆ‰€ๆœ‰็š„key [sose, sanme, name, jarorwar, foo, sname, java framework, user, braand] System.out.println(jedis.keys("*name"));//่ฟ”ๅ›ž็š„sname [sname, name] System.out.println(jedis.del("sanmdde"));//ๅˆ ้™คkeyไธบsanmdde็š„ๅฏน่ฑก ๅˆ ้™คๆˆๅŠŸ่ฟ”ๅ›ž1 ๅˆ ้™คๅคฑ่ดฅ๏ผˆๆˆ–่€…ไธๅญ˜ๅœจ๏ผ‰่ฟ”ๅ›ž 0 System.out.println(jedis.ttl("sname"));//่ฟ”ๅ›ž็ป™ๅฎškey็š„ๆœ‰ๆ•ˆๆ—ถ้—ด๏ผŒๅฆ‚ๆžœๆ˜ฏ-1ๅˆ™่กจ็คบๆฐธ่ฟœๆœ‰ๆ•ˆ jedis.setex("timekey", 10, "min");//้€š่ฟ‡ๆญคๆ–นๆณ•๏ผŒๅฏไปฅๆŒ‡ๅฎškey็š„ๅญ˜ๆดป๏ผˆๆœ‰ๆ•ˆๆ—ถ้—ด๏ผ‰ ๆ—ถ้—ดไธบ็ง’ Thread.sleep(5000);//็ก็œ 5็ง’ๅŽ๏ผŒๅ‰ฉไฝ™ๆ—ถ้—ดๅฐ†ไธบ<=5 System.out.println(jedis.ttl("timekey")); //่พ“ๅ‡บ็ป“ๆžœไธบ5 jedis.setex("timekey", 1, "min"); //่ฎพไธบ1ๅŽ๏ผŒไธ‹้ขๅ†็œ‹ๅ‰ฉไฝ™ๆ—ถ้—ดๅฐฑๆ˜ฏ1ไบ† System.out.println(jedis.ttl("timekey")); //่พ“ๅ‡บ็ป“ๆžœไธบ1 System.out.println(jedis.exists("key"));//ๆฃ€ๆŸฅkeyๆ˜ฏๅฆๅญ˜ๅœจ System.out.println(jedis.rename("timekey","time")); System.out.println(jedis.get("timekey"));//ๅ› ไธบ็งป้™ค๏ผŒ่ฟ”ๅ›žไธบnull System.out.println(jedis.get("time")); //ๅ› ไธบๅฐ†timekey ้‡ๅ‘ฝๅไธบtime ๆ‰€ไปฅๅฏไปฅๅ–ๅพ—ๅ€ผ min //jedis ๆŽ’ๅบ //ๆณจๆ„๏ผŒๆญคๅค„็š„rpushๅ’Œlpushๆ˜ฏList็š„ๆ“ไฝœใ€‚ๆ˜ฏไธ€ไธชๅŒๅ‘้“พ่กจ๏ผˆไฝ†ไปŽ่กจ็Žฐๆฅ็œ‹็š„๏ผ‰ jedis.del("a");//ๅ…ˆๆธ…้™คๆ•ฐๆฎ๏ผŒๅ†ๅŠ ๅ…ฅๆ•ฐๆฎ่ฟ›่กŒๆต‹่ฏ• jedis.rpush("a", "1"); jedis.lpush("a","6"); jedis.lpush("a","3"); jedis.lpush("a","9"); System.out.println(jedis.lrange("a",0,-1));// [9, 3, 6, 1] System.out.println(jedis.sort("a")); //[1, 3, 6, 9] //่พ“ๅ…ฅๆŽ’ๅบๅŽ็ป“ๆžœ System.out.println(jedis.lrange("a",0,-1)); } }
1878ec20d134c7c84256a75c64a36f024e63cd53
[ "Java" ]
1
Java
nux123/FirstRedis
04608e6a58ed85984617ddd5503dbac065ac3dd8
ef899d8a9d156578477eddf1f4663b5798211f4f
refs/heads/master
<file_sep>var util = require('../../utils/util.js'); //่Žทๅ–ๅบ”็”จๅฎžไพ‹ const app = getApp() const NEWS_TYPES=["gn", "gj", "cj", "yl", "js", "ty", "other"] let sliderWidth = 26 // ้œ€่ฆ่ฎพ็ฝฎslider็š„ๅฎฝๅบฆ๏ผŒ็”จไบŽ่ฎก็ฎ—ไธญ้—ดไฝ็ฝฎ Page({ data: { tabs: ["ๅ›ฝๅ†…", "ๅ›ฝ้™…", "่ดข็ป", "ๅจฑไน", "ๅ†›ไบ‹", "ไฝ“่‚ฒ", "ๅ…ถไป–"], activeTabIndex: 0, sliderOffset: 0, sliderLeft: 0, newsList:[], errorMessage:'' }, onLoad: function () { let that = this //caculate navbar slider position wx.getSystemInfo({ success: function (res) { that.setData({ sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2, sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeTabIndex }); } }) wx.showLoading({ title: 'ๅŠ ่ฝฝ' + this.data.tabs[this.data.activeTabIndex]+'ๆ–ฐ้—ป...' }) this.getNewsList(NEWS_TYPES[this.data.activeTabIndex], () => { wx.hideLoading() }) }, //swhich news type when tap the top navbar onTabTap: function (e) { if (this.data.activeTabIndex!= e.currentTarget.id){ this.setData({ sliderOffset: e.currentTarget.offsetLeft, activeTabIndex: e.currentTarget.id }); //get the news for the current type wx.showLoading({ title: 'ๅŠ ่ฝฝ' + this.data.tabs[this.data.activeTabIndex] + 'ๆ–ฐ้—ป...' }) this.getNewsList(NEWS_TYPES[this.data.activeTabIndex], () => { wx.hideLoading() }) } }, onPullDownRefresh: function() { this.getNewsList(NEWS_TYPES[this.data.activeTabIndex], () => { wx.stopPullDownRefresh() }) }, //function to get the news list based on news type getNewsList: function(newsType, callback){ let that=this //uset error message that.setData( { errorMessage: '' } ) //get news list for newsType from API wx.request({ url: app.globalData.api_base_url + '/list', data:{ 'type': newsType }, method: 'GET', header: { 'content-type': 'application/json' }, success(res) { let result = res.data.result //format date using moment lib result.forEach(function (item) { item.date = util.formatTimeNew(new Date(item.date)) }); if (res.data.result.length>0){ that.setData( { newsList: res.data.result, errorMessage: '' } ) }else{ that.setData( { newsList: [], errorMessage: 'ๆš‚ๆ—ถๆฒกๆœ‰' + that.data.tabs[that.data.activeTabIndex] + 'ๆ–ฐ้—ป๏ผŒ่ฏท็จๅŽๅˆทๆ–ฐใ€‚' } ) } }, complete() { typeof callback === 'function' && callback() } }) } }) <file_sep>var util = require('../../utils/util.js'); //่Žทๅ–ๅบ”็”จๅฎžไพ‹ const app = getApp() Page({ /** * ้กต้ข็š„ๅˆๅง‹ๆ•ฐๆฎ */ data: { news:{} }, /** * ็”Ÿๅ‘ฝๅ‘จๆœŸๅ‡ฝๆ•ฐ--็›‘ๅฌ้กต้ขๅŠ ่ฝฝ */ onLoad: function (options) { let newsId = options.id; this.getNewsDetail(newsId) }, //function to get the news list based on news type getNewsDetail: function(newsId) { let that = this wx.showLoading({ title: 'ๅŠ ่ฝฝๆ–ฐ้—ปๅ†…ๅฎน...' }) //get news list for newsType from API wx.request({ url: app.globalData.api_base_url + '/detail', data: { 'id': newsId }, method: 'GET', header: { 'content-type': 'application/json' }, success(res) { let result = res.data.result //format date using moment lib result.date = util.formatTimeNew(new Date(result.date)) that.setData( { news: result } ) //console.log(that.data.news) }, complete(res) { wx.hideLoading() } }) } })
33f69bacdc252a2c071cb62799f3a1023d5bfc32
[ "JavaScript" ]
2
JavaScript
ruiyi02/mininews
c359e9129a06f3688c75ba558b57c2a3abd55f6d
de6c51a9aa78263a9aea7b48f016a774e4f9bbb5
refs/heads/master
<repo_name>Ryycs/nim-sum-game<file_sep>/nimsum.php <?php $human = 0; $ai = 0; function takeMatch($row, $cnt, $inRow){ if($row==="error"){ echo "You must choose a, b, c, or d" . PHP_EOL; return false; }elseif(!is_numeric($cnt)){ echo "You entered a non numeric value of matches" . PHP_EOL; return false; }elseif($cnt!=intval($cnt)){ echo "You cannot take fractions of matches" . PHP_EOL; return false; }elseif($cnt < 1){ echo "You must take at least one match from the playing area" . PHP_EOL; return false; }elseif($row==0){ echo "There are no matches in that row" . PHP_EOL; return false; }elseif($cnt > $row){ echo "There aren't that many matches in that row" . PHP_EOL; return false; }else{ $GLOBALS[$inRow] = $row - $cnt; return true; } } function aiTakeMatch($passNim){ $nimSum = false; while(!$nimSum){ $rowExists = false; while(!$rowExists){ $row = rand(0,3); switch($row){ case 0: if($GLOBALS["a"]>0){ $rowExists = true; $row = "a"; } break; case 1: if($GLOBALS["b"]>0){ $rowExists = true; $row = "b"; } break; case 2: if($GLOBALS["c"]>0){ $rowExists = true; $row = "c"; } break; case 3: if($GLOBALS["d"]>0){ $rowExists = true; $row = "d"; } break; } } $cntValid = false; while(!$cntValid){ $cnt = rand(1,7); if($GLOBALS[$row]>=$cnt){ $cntValid = true; } } $GLOBALS[$row] = $GLOBALS[$row] - $cnt; if(!$passNim){ if(!testNim()){ $nimSum = true; }else{ $GLOBALS[$row] = $GLOBALS[$row] + $cnt; } }else{ $nimSum = true; } } printStatement($cnt, $row); } function aiTakeMatchNim(){ $zeroCount = 0; $nonZeros = array(); if($GLOBALS["a"]==0){ $zeroCount++; }else{ $notZero = "a"; $nonZeros[] = "a"; } if($GLOBALS["b"]==0){ $zeroCount++; }else{ $notZero = "b"; $nonZeros[] = "b"; } if($GLOBALS["c"]==0){ $zeroCount++; }else{ $notZero = "c"; $nonZeros[] = "c"; } if($GLOBALS["d"]==0){ $zeroCount++; }else{ $notZero = "d"; $nonZeros[] = "d"; } if($zeroCount==3){ $cnt = $GLOBALS[$notZero] - 1; if($cnt!=0){ $GLOBALS[$notZero] = $GLOBALS[$notZero] - $cnt; printStatement($cnt, $notZero); }else{ if(!testNim()){ $passNim = true; }else{ $passNim = false; } aiTakeMatch($passNim); } }elseif($zeroCount==2){ if($GLOBALS[$nonZeros[0]]==1){ $cnt = $GLOBALS[$nonZeros[1]]; $GLOBALS[$nonZeros[1]] = 0; printStatement($cnt,$nonZeros[1]); }elseif($GLOBALS[$nonZeros[1]]==1){ $cnt = $GLOBALS[$nonZeros[0]]; $GLOBALS[$nonZeros[0]] = 0; printStatement($cnt,$nonZeros[0]); }else{ aiTakeMatch(!testNim()); } }else{ $nimSum = ($GLOBALS["a"] ^ $GLOBALS["b"] ^ $GLOBALS["c"] ^ $GLOBALS["d"]); switch($nimSum){ case 0: aiTakeMatch(true); break; case 1: if(($GLOBALS["a"] % 2)!=0){ $GLOBALS["a"] = $GLOBALS["a"] - 1; printStatement(1,"a"); }elseif(($GLOBALS["b"] % 2)!=0){ $GLOBALS["b"] = $GLOBALS["b"] - 1; printStatement(1,"b"); }elseif(($GLOBALS["c"] % 2)!=0){ $GLOBALS["c"] = $GLOBALS["c"] - 1; printStatement(1,"c"); }elseif(($GLOBALS["d"] % 2)!=0){ $GLOBALS["d"] = $GLOBALS["d"] - 1; printStatement(1,"d"); } break; case 2: if($GLOBALS["a"]+$GLOBALS["b"]+$GLOBALS["c"]+$GLOBALS["d"]==4){ if($GLOBALS["a"]==2){ $GLOBALS["a"] = 1; printStatement(1,"a"); }elseif($GLOBALS["b"]==2){ $GLOBALS["b"] = 1; printStatement(1,"b"); }elseif($GLOBALS["c"]==2){ $GLOBALS["c"] = 1; printStatement(1,"c"); }elseif($GLOBALS["d"]==2){ $GLOBALS["d"] = 1; printStatement(1,"d"); } }elseif(($GLOBALS["b"] % 2)==0 && $GLOBALS["b"]!=0){ $GLOBALS["b"] = $GLOBALS["b"] - 2; printStatement(2,"b"); }elseif(($GLOBALS["c"] % 2)==0 && $GLOBALS["c"]!=4 && $GLOBALS["c"]!=0){ $GLOBALS["c"] = $GLOBALS["c"] - 2; printStatement(2,"c"); }elseif(($GLOBALS["d"] % 2)==0 && $GLOBALS["d"]!=4 && $GLOBALS["d"]!=0){ $GLOBALS["d"] = $GLOBALS["d"] - 2; printStatement(2,"d"); }else{ foreach($nonZeros as $nz){ if($GLOBALS[$nz]>1){ $GLOBALS[$nz] = $GLOBALS[$nz] - 2; printStatement(2,$nz); break; } } } break; case 3: $finish = false; if($GLOBALS["b"]==3){ if(($GLOBALS["a"] ^ ($GLOBALS["b"]-3) ^ $GLOBALS["c"] ^ $GLOBALS["d"])==0){ $GLOBALS["b"] = $GLOBALS["b"] - 3; printStatement(3,"b"); $finish = true; } } if(!$finish){ if($GLOBALS["c"]>=3){ if(($GLOBALS["a"] ^ $GLOBALS["b"] ^ ($GLOBALS["c"]-3) ^ $GLOBALS["d"])==0){ $GLOBALS["c"] = $GLOBALS["c"] - 3; printStatement(3,"c"); $finish = true; } } } if(!$finish){ if($GLOBALS["d"]>=3){ if(($GLOBALS["a"] ^ $GLOBALS["b"] ^ $GLOBALS["c"] ^ ($GLOBALS["d"]-3))==0){ $GLOBALS["d"] = $GLOBALS["d"] - 3; printStatement(3,"d"); $finish = true; } } } if(!$finish){ aiTakeMatch(false); } break; case 4: if($GLOBALS["c"]>=4){ $GLOBALS["c"] = $GLOBALS["c"] - 4; printStatement(4,"c"); }elseif($GLOBALS["d"]>=4){ $GLOBALS["d"] = $GLOBALS["d"] - 4; printStatement(4,"d"); } break; case 5: aiTakeMatch(false); break; case 6: aiTakeMatch(false); break; case 7: aiTakeMatch(false); break; } } } function printMatches(){ echo ' '; for($cx = 0; $cx < $GLOBALS['a']; $cx++){ echo '1 '; } echo PHP_EOL; echo ' '; for($cx = 0; $cx < $GLOBALS['b']; $cx++){ echo '1 '; } echo PHP_EOL; echo ' '; for($cx = 0; $cx < $GLOBALS['c']; $cx++){ echo '1 '; } echo PHP_EOL; for($cx = 0; $cx < $GLOBALS['d']; $cx++){ echo '1 '; } echo PHP_EOL; } function printStatement($count, $row){ echo "I take " . $count . " match"; if($count>1){ echo "es"; } echo " from row " . $row . "." . PHP_EOL; } function testNim(){ if(($GLOBALS["a"] ^ $GLOBALS["b"] ^ $GLOBALS["c"] ^ $GLOBALS["d"])==0){ return false; }else{ return true; } } echo "Greetings." . PHP_EOL; do{ echo "Would you like to play a game?" . PHP_EOL; $startGame = stream_get_line(STDIN,1024,PHP_EOL); switch(strtolower($startGame)){ case 'yes': case 'y': $go = true; $end = false; break; case 'no': case 'n': $go = false; $end = true; break; default: echo "I do not understand..." . PHP_EOL; $go = false; $end = false; break; } if($go){ do{ do{ echo "Would you like to go first or second?" . PHP_EOL; $response = stream_get_line(STDIN,1024,PHP_EOL); switch(strtolower($response)){ case "first": case "1": case "1st": $i = 0; $start = true; break; case "second": case "2": case "2nd": $i = 1; $start = true; break; default: echo "I do not understand..." . PHP_EOL; $start = false; break; } }while(!$start); $a = 1; $b = 3; $c = 5; $d = 7; while(($a + $b + $c + $d)>0){ printMatches(); if(($i%2)==0){ echo "Which row would you like to take from?" . PHP_EOL; $inRow = stream_get_line(STDIN,1024,PHP_EOL); switch($inRow){ case 'a': case 'A': $row = $a; break; case 'b': case 'B': $row = $b; break; case 'c': case 'C': $row = $c; break; case 'd': case 'D': $row = $d; break; default: $row = "error"; break; } echo "How many matches would you like to take?" . PHP_EOL; $cnt = stream_get_line(STDIN,1024,PHP_EOL); $continue = takeMatch($row, $cnt, $inRow); }else{ aiTakeMatchNim(); $continue = true; } if($continue){ $i++; } sleep(1); } if($i%2){ echo PHP_EOL . "I win." . PHP_EOL . PHP_EOL; $ai++; echo "Score" . PHP_EOL; echo "Joshua: " . $ai . PHP_EOL; echo "You: " . $human . PHP_EOL . PHP_EOL; }else{ echo PHP_EOL . "You win!" . PHP_EOL . PHP_EOL; $human++; echo "Score" . PHP_EOL; echo "Joshua: " . $ai . PHP_EOL; echo "You: " . $human . PHP_EOL . PHP_EOL; } do{ echo "Would you like to play again?" .PHP_EOL; $resp = stream_get_line(STDIN,1024,PHP_EOL); switch(strtolower($resp)){ case "yes": case "y": $valid = true; $gameOn = true; break; case "no": case "n": $valid = true; $gameOn = false; $end = true; break; default: echo "Invalid response..." . PHP_EOL; $valid = false; break; } }while(!$valid); }while($gameOn); } }while(!$end); ?>
5cd5a806894d8340aa041baf74df058f07f5d8c1
[ "PHP" ]
1
PHP
Ryycs/nim-sum-game
e7a772bc9d6a4fc8c9a4f62608af3bf09811cc8d
1e9f9a7b34e740b213504f7e4c3e6900e0d37ec0
refs/heads/master
<file_sep>exports.up = async function up(knex) { await knex.schema.createTable('users', table => { table.increments('id').unsigned().notNullable().primary(); table.string('user_id', 20).unique().notNullable(); table.string('email', 100).unique().notNullable(); table.string('name', 100).notNullable(); table.string('password', 100).unique().notNullable(); table.float('balance').notNullable().defaultTo(0); table.enum('status', ['active','not_active']).notNullable().defaultTo('active'); table.dateTime('created').notNullable().defaultTo(knex.fn.now()); }); }; exports.down = async function down(knex) { await knex.schema.dropTable('users'); }; <file_sep>const dotenv = require('dotenv'); dotenv.config({path: '../config/.env'}); const environment = process.env.NODE_ENV; const config = require('./knexfile.js')[environment]; const pool = require('knex')(config); module.exports = pool;<file_sep>const passport = require('passport'); const bcrypt = require('bcrypt'); var crypto = require('crypto'); const { usersModel, userBanksModel } = require('../database/models/user.model'); const { debitTransactionModel, creditTransactionModel } = require('../database/models/transaction.model'); const { getCurrentTime, idGenerator, issueJWT, generateReference } = require('../utils/helpers.utils'); const catchAsync = require('../utils/async.utils'); const { listBanks, createTransferRecipient, initializeTransaction, initiateTransfer } = require('../controllers/paystack.controller'); exports.createAccount = catchAsync ( async (req, res, next) => { const { name, email, password } = req.body; try { const password_hash = await bcrypt.hash(password, 12); const user_id = idGenerator(); const created = getCurrentTime(); await usersModel.query().insert({user_id, email, name, password:<PASSWORD>, created}); req.result = {status:'success',message:'Account created successfully, please proceed to login',code:200}; return next(); } catch (err) { console.log(err); req.result = {status: 'failed',message: 'Unable to perform request',code:500}; return next(); } }); exports.loginAccount = catchAsync ( async (req, res, next) => { try { const { email, password } = req.body; const { hash, user_id } = req.login_access; const compare_password = await bcrypt.compare(password, hash); if (compare_password == true) { const data = {key:user_id}; const jwt = issueJWT(data, process.env.JWT_EXPIRES); req.result = {status:'success',message:'Logged in successfully',code:200,data:{token:jwt}}; return next(); } req.result = {status:'failed',message: 'Invalid login credentials',code:401}; return next(); } catch (err) { console.log(err); req.result = {status: 'failed',message: 'Unable to perform request',code:500}; return next(); } }); exports.checkAuthentication = passport.authenticate('jwt', { session: false }); exports.getBanks = catchAsync ( async (req, res, next) => { try { const { body: { message, data: banks } } = await listBanks('NGN'); const data = banks.map(bank => { return {bank_name:bank.name,bank_code:bank.code,slug:bank.slug}; }); req.result = {status:'success',message,data,code:200}; return next(); } catch (err) { console.log(err); req.result = {status: 'failed',message: 'Unable to perform request',code:500}; return next(); } }); exports.createBeneficiary = catchAsync ( async (req, res, next) => { const { bank_code, account_no: bank_account } = req.body; const { name, user_id } = req.user; try { const created = getCurrentTime(); const { body: { data } } = await createTransferRecipient({type:"nuban",name,account_number:bank_account,bank_code}); await userBanksModel.query().insert({user_id, bank_code, bank_account, transfer_code:data.recipient_code, created}); req.result = {status:'success',message:'Beneficiary successfully added',code:200}; return next(); } catch (err) { console.log(err); req.result = {status: 'failed',message: 'Invalid account details',code:500}; return next(); } }); exports.getBeneficiaries = catchAsync ( async (req, res, next) => { const { user_id } = req.user; try { const data = await userBanksModel.query().select('transfer_code','bank_code','bank_account').where({user_id}); req.result = {status:'success',message:'Beneficiary successfully added',data,code:200}; return next(); } catch (err) { console.log(err); req.result = {status: 'failed',message: 'Unable to perform request',code:500}; return next(); } }); exports.getAccountBalance = catchAsync ( async (req, res, next) => { try { const { balance: account_balance } = req.user; req.result = {status:'success',message:'Balance retrieved successfully',data:{account_balance},code:200}; return next(); } catch (err) { console.log(err); req.result = {status: 'failed',message: 'Unable to perform request',code:500}; return next(); } }); exports.fundAccount = catchAsync ( async (req, res, next) => { try { const { user_id, email } = req.user; const { channel, amount } = req.body; const meta_data = JSON.stringify({data:req.user}); const credit_amount = Math.abs(parseFloat(amount)); const ref_code = generateReference(); const channels = [channel]; const params = {reference:ref_code,amount:`${credit_amount*100}`,email,callback_url:`${req.protocol}://${req.get('host')}/users/account/payment_success`,channels,metadata:meta_data} const { data: { data: { authorization_url }} } = await initializeTransaction(params); await creditTransactionModel.query().insert({user_id, channel, ref_code, meta_data, amount:credit_amount, created:getCurrentTime()}); req.result = {status:'success',message:'Complete your transaction',data:{authorization_url},code:200}; return next(); } catch (err) { console.log(err); req.result = {status: 'failed',message: 'Unable to perform request',code:500}; return next(); } }); exports.transferFunds = catchAsync ( async (req, res, next) => { try { const { user_id } = req.user; const {transfer_id, amount} = req.transfer; const debit_amount = Math.abs(parseFloat(amount)); const meta_data = JSON.stringify({recipient:transfer_id}); const created = getCurrentTime(); const ref_code = generateReference(); const transaction = await creditTransactionModel.transaction(async trx => { await debitTransactionModel.query(trx).insert({user_id,trx_type:'transfer',ref_code,meta_data,amount,status:'completed',created}); await usersModel.query(trx).where({user_id}).decrement('balance', debit_amount).limit(1); await usersModel.query(trx).where({user_id:transfer_id}).increment('balance', debit_amount).limit(1); await creditTransactionModel.query(trx).insert({user_id:transfer_id, channel:'transfer', ref_code, meta_data, amount:debit_amount,status:'completed',created}); }); req.result = {status:'success',message:'Transfer completed successfully',code:200}; return next(); } catch (err) { console.log(err.message); req.result = {status: 'failed',message: 'Unable to perform request',code:500}; return next(); } }); exports.withdrawFunds = catchAsync ( async (req, res, next) => { try { const { user_id } = req.user; const { transfer_code, amount } = req.body; const meta_data = JSON.stringify({data:{user_id,transfer:transfer_code}}); const debit_amount = Math.abs(parseFloat(amount)); const ref_code = generateReference(); const params = {reference:ref_code,amount:debit_amount*100,metadata:meta_data,recipient:transfer_code,source:'balance'} const { body: { message, data } } = await initiateTransfer(params); await debitTransactionModel.query().insert({user_id, trx_type:'withdraw', ref_code, meta_data, amount:debit_amount, created:getCurrentTime()}); req.result = {status:'success',message:'Your funds is on its way to your account',code:200}; return next(); } catch (err) { console.log(err); req.result = {status: 'failed',message:'You cannot initiate third party payouts as a starter business',code:500}; return next(); } }); exports.checkPayment = catchAsync ( async (req, res, next) => { try { const hash = crypto.createHmac('sha512', process.env.PAYSTACK_SECRET_KEY).update(JSON.stringify(req.body)).digest('hex'); if (hash == req.headers['x-paystack-signature']) { const { event } = req.body; if (event == 'charge.success') { const { data: { reference, amount, metadata: { data: meta_data } } } = req.body; const { user_id } = meta_data; const credit_amount = amount/100; res.status(200); const transaction = await creditTransactionModel.transaction(async trx => { await creditTransactionModel.query(trx).where({ref_code:reference}).patch({status:'completed',created:getCurrentTime()}); await usersModel.query(trx).where({user_id}).increment('balance', Math.abs(credit_amount)).limit(1); }); } if (event == 'transfer.success') { const { data: { reference, amount, recipient: { metadata: {data: meta_data} } } } = req.body; const { user_id } = meta_data; const debit_amount = amount/100; res.status(200); const transaction = await creditTransactionModel.transaction(async trx => { await debitTransactionModel.query(trx).where({ref_code:reference}).patch({status:'completed',created:getCurrentTime()}); await usersModel.query(trx).where({user_id}).decrement('balance', Math.abs(debit_amount)).limit(1); }); } if (event == 'transfer.failed' || event == 'transfer.failed') { res.status(200); await debitTransactionModel.query(trx).where({ref_code:reference}).patch({status:'failed',created:getCurrentTime()}); } } res.status(400); } catch (err) { console.log(err); res.status(500); } });<file_sep>### Postman URL https://documenter.getpostman.com/view/10031264/U16kqQUD <file_sep>module.exports = { apps: [ { name: "nodejs-test-app", script: "./server.js", instances : 1, error_file: './errors/err.log', out_file: './errors/out.log', log_file: './errors/combined.log', exec_mode : "cluster", env: { ODE_ENV: "development", }, env_staging: { NODE_ENV: "staging", }, env_production: { NODE_ENV: "production", } } ] }<file_sep>const errors = require('../controllers/error.controller'); const sendErrorDev = (err, req, res) => { if (req.originalUrl .startsWith('/api')) { return res.status(err.statusCode).json({ status: err.status, error:err, message: err.message, stack: err.stack }) } return res.status(err.statusCode).send('<h1 style="font-weight:bold;">Oops...!!!!<h1>'); } const sendErrorStag = (err, req, res) => { if (req.originalUrl .startsWith('/api')) { if (err.isOperational) { return res.status(err.statusCode).json({ status: err.status, message: err.message, }) } return res.status(500).json({ status: 'error', message: "Service unavailable" }); } return res.status(err.statusCode).send('<h1 style="font-weight:bold;">Oops...!!!!<h1>'); } const sendErrorPro = (err, req, res) => { if (req.originalUrl .startsWith('/api')) { if (err.isOperational) { return res.status(err.statusCode).json({ status: err.status, message: err.message }) } return res.status(500).json({ status: 'error', message: "Service unavailable" }); } return res.status(err.statusCode).send('<h1 style="font-weight:bold;">Oops...!!!!<h1>'); } module.exports = (err, req, res, next) => { err.statusCode = err.statusCode || 500; err.status = err.status || 'error' if (process.env.NODE_ENV === 'development') { sendErrorDev(err, req, res); } if (process.env.NODE_ENV === 'staging') { sendErrorStag(err, req, res); } if (process.env.NODE_ENV === 'production') { let error = {...err}; error.message = err.message; sendErrorPro(error, req, res); } }<file_sep>exports.up = async function up(knex) { await knex.schema.createTable('beneficiary_banks', table => { table.increments('id').unsigned().notNullable().primary(); table.string('user_id', 20).notNullable(); table.string('bank_code', 10).notNullable(); table.string('bank_account', 20).notNullable(); table.string('transfer_code', 100).unique().notNullable(); table.dateTime('created').notNullable().defaultTo(knex.fn.now()); table.foreign('user_id').references('users.user_id'); }); }; exports.down = async function down(knex) { await knex.schema.dropTable('beneficiary_banks'); }; <file_sep>const fs = require('fs'); const path = require('path'); const { usersModel } = require('../database/models/user.model'); const JwtStrategy = require('passport-jwt').Strategy; const ExtractJwt = require('passport-jwt').ExtractJwt; const pathToKey = path.join(__dirname, '../config', 'id_rsa_pub.pem'); const PUB_KEY = fs.readFileSync(pathToKey, 'utf8'); const options = { jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey:PUB_KEY, algorithms: [process.env.JWT_ALOGRITHM], ignoreExpiration:false }; const strategy = new JwtStrategy(options, async (payload, done) => { const {key} = payload; try { const get_user = usersModel.query().select('user_id','name','email','balance','status').where({user_id:key}).limit(1); get_user.then((user) => { if (user) { const {user_id, name, email, balance} = user[0] return done(null, {user_id,name,email,balance}); }else{ return done(null, false, {message:"Invalid credentials"}); } }) .catch(err => done(err, null, {message:"Invalid login credentials"})) } catch (err) { console.log(err) return done(null, false, {message:"Invalid credentials"}); } }); module.exports = (passport) => { passport.use(strategy); }<file_sep>const { body, param, validationResult } = require('express-validator'); const { usersModel, userBanksModel } = require('../database/models/user.model'); exports.validateAccount = [ body('name').trim().escape().not().isEmpty().withMessage('Full name is required').matches(/([A-Za-z]{1})([A-Za-z]+)(\s)([A-Za-z]{1})([A-Za-z]+){1}/) .withMessage('Please provide your valid full name').bail(), body('email', 'Provide a valid email address').trim().not().isEmpty().exists().isEmail().normalizeEmail() .custom( async (value, { req }) => { try { const check = await usersModel.query().where({email:value}).select('id').limit(1); if (check.length > 0) { return Promise.reject('Email is already in use'); }else { return; } } catch (err) { console.log(err); return Promise.reject('Unable to perform request'); } }), body('password').trim().escape().not().isEmpty().withMessage('Password is required').isLength({min:8}).withMessage('Password must be at least 8 characters long') .matches(/^.*(?=.{6,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/).withMessage('Password must contain a number and an uppercase letter').bail(), (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) { const extractedErrors = []; errors.array({ onlyFirstError: true }).map(err => extractedErrors.push(err.msg)); return res.status(422).json({status:'failed',message:'All account data is required',errors:extractedErrors}); } next(); } ] exports.validateLogin = [ body('email', 'Provide a valid email address').trim().not().isEmpty().exists().isEmail().normalizeEmail() .custom( async (value, { req }) => { try { const check = await usersModel.query().where({email:value}).select('user_id','password').limit(1); if (check.length < 1) { return Promise.reject('Your credentials did not match any of our records'); }else { req.login_access = {hash:check[0].password,user_id:check[0].user_id}; return; } } catch (err) { return Promise.reject('Unable to perform request'); } }), body('password').trim().escape().not().isEmpty().withMessage('Password is required').isLength({min:8}).withMessage('Invalid Password') .matches(/^.*(?=.{6,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/).withMessage('Invalid Password').bail(), (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) { const extractedErrors = []; errors.array({ onlyFirstError: true }).map(err => extractedErrors.push(err.msg)); return res.status(422).json({status:'failed',message:'Invalid login data',errors:extractedErrors}); } next(); } ] exports.validateBeneficiary = [ body('bank_code').trim().escape().not().isEmpty().withMessage('Bank code is required').bail(), body('account_no','Invalid bank account number').trim().escape().not().isEmpty().withMessage('Bank account number is required') .isLength({min:10,max:11}).isNumeric().withMessage('Invalid bank account number') .custom( async (value, { req }) => { try { const check = await userBanksModel.query().where({user_id:req.user.user_id,bank_account:value}).select('id').limit(1); if (check.length == 1) { return Promise.reject('Beneficiary already added'); } return; } catch (err) { return Promise.reject('Unable to perform request'); } }), (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) { const extractedErrors = []; errors.array({ onlyFirstError: true }).map(err => extractedErrors.push(err.msg)); return res.status(422).json({status:'failed',message:'Invalid beneficiary data',errors:extractedErrors}); } next(); } ] exports.validateFundAccount = [ body('channel').trim().escape().not().isEmpty().withMessage('funding channel is required') .custom( async (value, { req }) => { if (value != 'card' && value != 'bank_transfer') { return Promise.reject('channel can only be card or bank_transfer'); } return; }), body('amount','amount is required').trim().escape().not().isEmpty().withMessage('amount is required').isNumeric().withMessage('Invalid amount').bail(), (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) { const extractedErrors = []; errors.array({ onlyFirstError: true }).map(err => extractedErrors.push(err.msg)); return res.status(422).json({status:'failed',message:'Invalid funding data',errors:extractedErrors}); } next(); } ] exports.validateTransfer = [ body('email', 'Please provide a valid email address').trim().not().isEmpty().withMessage('Please provide a valid email address').exists().isEmail().normalizeEmail() .custom( async (value, { req }) => { try { const check = await usersModel.query().where({email:value}).andWhere('user_id','!=', req.user.user_id).select('user_id').limit(1); if (check.length < 1) { return Promise.reject('Email does not exist'); }else { req.transfer = {transfer_id:check[0].user_id,amount:req.body.amount}; return; } } catch (err) { return Promise.reject('Unable to perform request'); } }), body('amount','amount is required').trim().escape().not().isEmpty().withMessage('amount is required').isNumeric().withMessage('Invalid amount') .custom( async (value, { req }) => { try { const check = await usersModel.query().where('user_id','=', req.user.user_id).select('balance').limit(1); if (check.length < 1) { return Promise.reject('Invalid request'); }else { const { balance } = check[0]; if (Math.abs(balance) < value || balance == 0){ return Promise.reject('Insufficient balance'); }else{ return; } } } catch (err) { return Promise.reject('Unable to perform request'); } }), (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) { const extractedErrors = []; errors.array({ onlyFirstError: true }).map(err => extractedErrors.push(err.msg)); return res.status(422).json({status:'failed',message:'Invalid transfer data',errors:extractedErrors}); } next(); } ] exports.validateWithdrawal = [ body('transfer_code', 'Please provide transfer code').trim().escape().not().isEmpty() .custom( async (value, { req }) => { try { const check = await userBanksModel.query().where({transfer_code:value}).andWhere('user_id','=', req.user.user_id).select('id').limit(1); if (check.length < 1) { return Promise.reject('Beneficiary does not exist'); }else { req.transfer = {transfer_id:check[0].user_id,amount:req.body.amount}; return; } } catch (err) { return Promise.reject('Unable to perform request'); } }), body('amount','amount is required').trim().escape().not().isEmpty().withMessage('amount is required').isNumeric().withMessage('Invalid amount') .custom( async (value, { req }) => { try { const check = await usersModel.query().where('user_id','=', req.user.user_id).select('balance').limit(1); if (check.length < 1) { return Promise.reject('Invalid request'); }else { const { balance } = check[0]; if (Math.abs(balance) < value || balance == 0){ return Promise.reject('Insufficient balance'); }else{ return; } } } catch (err) { return Promise.reject('Unable to perform request'); } }), (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) { const extractedErrors = []; errors.array({ onlyFirstError: true }).map(err => extractedErrors.push(err.msg)); return res.status(422).json({status:'failed',message:'Invalid transfer data',errors:extractedErrors}); } next(); } ]<file_sep>const express = require('express'); const ratelimit = require('express-rate-limit'); const { validateAccount, validateLogin, validateBeneficiary, validateFundAccount, validateTransfer, validateWithdrawal } = require('../middleware/validator.middleware'); const { response } = require('../middleware/response.middleware'); const { limiter } = require('../utils/helpers.utils'); const userController = require('../controllers/user.controller'); const router = express.Router(); router.use(express.json({limit: '10Kb'})); router.post('/account/create', limiter(10, 36000), validateAccount, userController.createAccount, response); router.post('/account/login', limiter(10, 36000), validateLogin, userController.loginAccount, response); router.use(userController.checkAuthentication); router.get('/account/banks', userController.getBanks, response); router.route('/account/beneficiary') .get(limiter(10, 36000), userController.getBeneficiaries, response) .post(limiter(10, 36000), validateBeneficiary, userController.createBeneficiary, response); router.get('/account/balance', limiter(10, 36000), userController.getAccountBalance, response); router.post('/account/fund', limiter(10, 36000), validateFundAccount, userController.fundAccount, response); router.post('/account/transfer', limiter(10, 36000), validateTransfer, userController.transferFunds, response); router.post('/account/withdraw', limiter(10, 36000), validateWithdrawal, userController.withdrawFunds, response); module.exports = router;<file_sep>const path = require('path'); const express = require('express'); const logger = require('morgan'); const xss = require('xss-clean'); const helmet = require('helmet'); const hpp = require('hpp'); const compression = require('compression'); const cors = require('cors'); const passport = require('passport'); const appError = require('./controllers/error.controller'); const globalErrorHandler = require('./middleware/error.middleware'); const userRoutes = require('./routes/user.routes'); const { checkPayment } = require('./controllers/user.controller') const app = express(); app.enable("trust proxy"); app.set('view engine', 'pug'); app.set('views', path.join(__dirname, 'views')); app.use(express.static(path.join(__dirname, 'public'))); app.use(cors()); app.options('*', cors()); app.use(helmet()); app.use(xss()); app.use(hpp()); app.use(compression()); app.use(express.json()); app.use(express.urlencoded({extended: true})); if (process.env.NODE_ENV != 'production') { app.use(logger('dev')); } require('./middleware/passport.middleware')(passport); app.get('/users/account/payment_success', (req, res, next) => { res.status(200).render('payment_success', {message: 'Account successfully funded'}); }); app.use('/webhook/payment', checkPayment); app.use('/api/v1/users', userRoutes); app.all('*', (req, res, next) => { next(new appError(`Requested resource not available`, 404)); }) app.use(globalErrorHandler); module.exports = app; <file_sep>const fs = require('fs'); const dotenv = require('dotenv'); dotenv.config({path: '../config/.env'}); module.exports = { development: { client: process.env.DB_DIALECT, connection: { host: process.env.DB_HOST, port: parseInt(process.env.DB_PORT), user: process.env.DB_USERNAME, password: <PASSWORD>, database: process.env.DB_NAME }, pool: { min: parseInt(process.env.DB_POOL_MIN), max: parseInt(process.env.DB_POOL_MAX), createTimeoutMillis: 3000, acquireTimeoutMillis: 30000, idleTimeoutMillis: 30000, reapIntervalMillis: 1000, createRetryIntervalMillis: 100, propagateCreateError: false }, migrations: {directory: './migrations', tableName: 'migrations'}, seeds:{directory: './seeds'} }, staging: { client: process.env.DB_DIALECT, connection: { host: process.env.DB_HOST, port: parseInt(process.env.DB_PORT), user: process.env.DB_USERNAME, password: <PASSWORD>, database: process.env.DB_NAME }, ssl: { ca:fs.readFileSync(`${__dirname}/../config/cert.crt`)}, pool: { min: parseInt(process.env.DB_POOL_MIN), max: parseInt(process.env.DB_POOL_MAX), createTimeoutMillis: 3000, acquireTimeoutMillis: 30000, idleTimeoutMillis: 30000, reapIntervalMillis: 1000, createRetryIntervalMillis: 100, propagateCreateError: false }, migrations: {directory: './migrations',tableName: 'migrations'}, seeds:{directory: './seeds'} }, production: { client: process.env.DB_DIALECT, connection: { host: process.env.DB_HOST, port: parseInt(process.env.DB_PORT), user: process.env.DB_USERNAME, password: <PASSWORD>, database: process.env.DB_NAME }, ssl: { ca:fs.readFileSync(`${__dirname}/../config/cert.crt`)}, pool: {min: parseInt(process.env.DB_POOL_MIN), max: parseInt(process.env.DB_POOL_MAX)}, migrations: { directory: './migrations', tableName: 'migrations'} } };<file_sep>const Model = require('../objection'); exports.creditTransactionModel = class creditTransaction extends Model { static get tableName() { return 'credit_transactions'; } static get idColumn() { return 'ref_code'; } static get jsonSchema() { return { type: 'object', required: ['user_id', 'channel', 'ref_code', 'meta_data', 'amount', 'created'], properties: { user_id: { type: 'string' }, channel: {type: 'string'}, ref_code: {type: 'string'}, meta_data: {type: ['string', null]}, amount: {type: 'number'}, captured: {type: Date} } }; } } exports.debitTransactionModel = class debitTransaction extends Model { static get tableName() { return 'debit_transactions'; } static get idColumn() { return 'ref_code'; } static get jsonSchema() { return { type: 'object', required: ['user_id', 'trx_type', 'ref_code', 'meta_data', 'amount', 'created'], properties: { user_id: { type: 'string' }, trx_type: {type: 'string'}, ref_code: {type: 'string'}, meta_data: {type: ['string', null]}, amount: {type: 'number'}, captured: {type: Date} } }; } }
80454ddc883d95d58e8bff3940b453f9bbdc7579
[ "JavaScript", "Markdown" ]
13
JavaScript
ayodejiabon/Node-Engineer-Test-77d2bc2ba6d8494d8fd9dcc1f7337f7e
0949102f0006e9e51b24579769b943a5e139c7fd
ab18d3bcbde63b1ec5f99d0454faf9b33b2b93ff
refs/heads/main
<repo_name>ThijsDollekens/GUESS-THE-NUMBER-GAME<file_sep>/project.js function myFunction() { var person = prompt("Leuk dat je er bent! wat is je naam?", "<NAME>"); if (person != null) { document.getElementById("Naam").innerHTML = "Hey " + person + "!" ; } } function guessNumber() { var getal = prompt("Denk goed na, welk getal denk je dat het is?", "9"); if (getal != null) { document.getElementById("Getal").innerHTML = "Dat is helaas onjuist..." + "Klik op de knop hieboven om het opnieuw te proberen"; } if (getal == getRandomInt(25)){ document.getElementById("Getal").innerHTML = "Gefeliciteerd! " + getal + " Was het juiste nummer" ; } } function getRandomInt(max){ return Math.floor(Math.random()* max); }
46f79bd08b891a04c6cce5dba59c5400e3ae7cb2
[ "JavaScript" ]
1
JavaScript
ThijsDollekens/GUESS-THE-NUMBER-GAME
826940aba9b9fd50bc9d64306a3fe3a587c3feb5
2962b50dbbc34c7fe492a165ce33ecfa1ab19e85
refs/heads/main
<file_sep>import smbus import time BH1750 = 0x23 reciever = 0x23 bus = smbus.SMBus(1) def Light(): address = bus.read_i2c_block_data(BH1750,reciever) value = (address[1] + (256 * address[0])) return value def main(): while True: light_value =Light() if(light_value >= 900): print(str(light_value) + " -> Too Bright") elif(light_value > 500 and light_value < 900): print(str(light_value) + " -> Bright") elif(light_value > 100 and light_value < 500): print(str(light_value) + " -> Medium") elif(light_value < 100 and light_value > 20): print(str(light_value) + " -> Dark") else: print(str(light_value)+" -> Too Dark") time.sleep(1) main()
993a055dcbf25cb90f29d08da6b2aa9333f9fd2f
[ "Python" ]
1
Python
cyber-panther/SIT210_Task8.1D_RPi_I2C
bed9d70083c0796551c07617148b7f0b1c997b40
5a8606fc47be9e0672b2773f607e824a528e879e
refs/heads/master
<repo_name>mcumiskey/Unity_Museum_Tour<file_sep>/GalleryDemo/Assets/scripts/milesMouseLook.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; public class milesMouseLook : MonoBehaviour { [SerializeField] public float sensitivity = 5.0f; [SerializeField] //Time.deltaTime makes smoothing framerate indipendant public float smoothing = 2.0f; // the chacter is the tube public Transform player; // get the incremental value of mouse moving private Vector2 mouseLook; private float xRotation = 0f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { //use the mouse to determine x and y float mouseX = Input.GetAxis("Mouse X") * sensitivity * smoothing; float mouseY = Input.GetAxis("Mouse Y") * sensitivity * smoothing; // the interpolated float result between float values xRotation = Mathf.Lerp(xRotation, mouseY, 1f / smoothing); // incrementally add this to the camera look mouseLook.y -= xRotation; //do not allow mouseLook.y to exceed -90 to 90 degrees if(mouseLook.y > 90){ mouseLook.y = 90; } if(mouseLook.y < -90){ mouseLook.y = -90; } // vector3.right means the x-axis //the transform is for the camera the script is attached to transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right); //this rotates the chatracter (and the camera) left + right player.Rotate(Vector3.up * mouseX); } } <file_sep>/GalleryDemo/Assets/Scripts/SelectionControl.cs ๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class SelectionControl : MonoBehaviour { [SerializeField] public GameObject textGUI; [SerializeField] public GameObject camera; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { RaycastHit hit; if(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity)){ GameObject selection = hit.transform.gameObject; Debug.Log("hit " + selection.tag); if(selection.CompareTag("Art")){ textGUI.SetActive(true); } else { textGUI.SetActive(false); } } } }
070de7313da64619c5156743a4aa1b6758326e6c
[ "C#" ]
2
C#
mcumiskey/Unity_Museum_Tour
a6372054931d1056abcaa5f241a99632bf2c6a7f
8ce4b2ea78e4d17ab1694891bfbf74feabbb717a
refs/heads/master
<repo_name>oghie/c<file_sep>/big_pangkat.c #include <stdio.h> #define BATAS 16 int main(void) { int n; int nilai = 1; printf("\t n \t 2^n\n"); printf("\t================\n"); for (n=0; n<=BATAS; n++) { printf("\t%3d \t %6d\n", n, nilai); nilai = 2*nilai; } return 0; } <file_sep>/simplecipher.c #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char cipher[256]; printf("Enter: "); scanf("%[^\n]", cipher); char *to = "qwertyuiopasdfghjklmnbvcxz"; int i; for (i = 0; i < strlen(cipher); i++) { if (cipher[i] >= 'a' && cipher[i] <= 'z') { cipher[i] = to[cipher[i] - 'a']; } else if (cipher[i] >= 'A' && cipher[i] <= 'Z') { cipher[i] = to[cipher[i] - 'A'] + ('A' - 'a'); } } printf("%s\n", cipher); return EXIT_SUCCESS; }
324b469ce7ae1e052a5df4d7a886f0431cde03eb
[ "C" ]
2
C
oghie/c
199a5cd2831c2d825aa5c47215d352bb3d8d8500
a5739c6a6b323cd4883122fb5fa9492f717c42f0
refs/heads/master
<file_sep>to run project add LED_Setup_Interface.dll to path<file_sep>๏ปฟusing System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using Newtonsoft.Json; using System.Runtime.InteropServices; using System.IO; namespace ledWFormsControl { public partial class Form1 : Form { Thread thr; ushort sendersCount; int[] senderIDs = new int[2]; DateTime cdt; // Params wich send to post method ushort senderID1; ushort senderID2; int FoundReceivers; bool ReceiverSearchingStatus = true; string ServerIp; string ServerPort; bool boolSendToServer; public class PostData { public int SendersCount; public ushort SenderID2; public ushort SenderID1; public int ReceiversCount; public string Modules; public bool DVIinput; public string Time; } PostData PD = new PostData(); //public Form1(string p, string p2) public Form1() { InitializeComponent(); fillIP(); fillLstShedule(); } //start button private void button8_Click_1(object sender, EventArgs e) { button8.Enabled = false; button9.Enabled = true; ServerIp = textBox1.Text; ServerPort = textBox2.Text; if(checkBox3.Checked) { boolSendToServer = true; } else { boolSendToServer = false; } writeIPToFile(); if (FoundReceivers < 1) { Connect(); } thr = new Thread(CheckDisplay); thr.IsBackground = true; thr.Start(); } //stop program private void button9_Click(object sender, EventArgs e) { button8.Enabled = true; button9.Enabled = false; thr.Abort(); } private void fillLstShedule() { using (StreamReader r = new StreamReader("time.json")) { string json = r.ReadToEnd(); dynamic array = JsonConvert.DeserializeObject(json); foreach (var item in array) { ListViewItem itm = new ListViewItem((String)item.Name); itm.SubItems.Add((String)item.Value ); lstShedule.Items.Add(itm); } } } private void fillIP() { using (StreamReader r = new StreamReader("send.json")) { string json = r.ReadToEnd(); dynamic array = JsonConvert.DeserializeObject(json); foreach (var item in array) { if(item.Name == "send") { if(item.Value == "True") { checkBox3.Checked = true; boolSendToServer = true; } if (item.Value == "False") { checkBox3.Checked = false; boolSendToServer = false; } } else { ServerIp = item.Name; textBox1.Text = item.Name; ServerPort = item.Value; textBox2.Text = item.Value; } } } } private void Connect() { Thread.Sleep(500); label3.Invoke((MethodInvoker)delegate { label3.Text = "Senders initialization..."; label3.ForeColor = Color.Blue; }); Thread.Sleep(300); button1.Invoke((MethodInvoker)delegate { button1.PerformClick(); }); } private void Connect2() { Thread.Sleep(5000); label6.Invoke((MethodInvoker)delegate { label6.Text = "Searching receivers..."; label6.ForeColor = Color.Blue; }); label5.Invoke((MethodInvoker)delegate { label5.Text = "0"; label5.ForeColor = Color.Blue; }); button2.Invoke((MethodInvoker)delegate { button2.PerformClick(); }); cdt = DateTime.Now; while (ReceiverSearchingStatus == true) { Thread.Sleep(10000); button3.Invoke((MethodInvoker)delegate { button3.PerformClick(); }); if ((DateTime.Now - cdt).Seconds > 90) { ReceiverSearchingStatus = false; NativeMethods.StopSearchReceiver(); } } Thread.Sleep(5000); button3.Invoke((MethodInvoker)delegate { button3.PerformClick(); }); Thread.Sleep(300); button4.Invoke((MethodInvoker)delegate { button4.PerformClick(); }); Thread.Sleep(300); button5.Invoke((MethodInvoker)delegate { button5.PerformClick(); }); } private void CheckDisplay() { while (true) { FoundReceivers = NativeMethods.GetFoundReceiverCount(); Connect2(); Thread.Sleep(300); if (FoundReceivers > 0) { setBrightness(); } Thread.Sleep(300); label7.Invoke((MethodInvoker)delegate { label7.Text = "Searching module info..."; label7.ForeColor = Color.Blue; }); Thread.Sleep(500); button6.Invoke((MethodInvoker)delegate { button6.PerformClick(); }); } } private void setBrightness() { if (checkBox1.Checked) { checkBox2.Checked = false; DateTime localDate = DateTime.Now; TimeSpan ct = localDate.TimeOfDay; var brightnessValue = 0; using (StreamReader r = new StreamReader("time.json")) { string json = r.ReadToEnd(); dynamic array = JsonConvert.DeserializeObject(json); foreach (var item in array) { TimeSpan t = TimeSpan.Parse(item.Name); if (ct > t) { brightnessValue = item.Value; } else { break; } } try { NativeMethods.SetDisplayBrightness((byte)brightnessValue); } catch (Exception e) { } } } } public void InitSenders() { // Initialization senders if (NativeMethods.ReConnectSender()) { sendersCount = NativeMethods.GetConnectSenderCount(); if (sendersCount<1) { label3.Invoke((MethodInvoker)delegate { label3.Text = "Initialization failed"; label3.ForeColor = Color.Red; }); } else { PD.SendersCount = sendersCount; // Senders Count (ushort) for (int step = 0; step < sendersCount; step++) { senderIDs[step] = NativeMethods.GetSenderId((byte)step); } senderID1 = (ushort)senderIDs[0]; senderID2 = (ushort)senderIDs[1]; PD.SenderID1 = senderID1; PD.SenderID2 = senderID2; string countOfSenders = sendersCount.ToString(); label2.Invoke((MethodInvoker)delegate { label2.Text = countOfSenders; }); label3.Invoke((MethodInvoker)delegate { label3.Text = "Initialization complete"; label3.ForeColor = Color.Green; }); } } else { label3.Invoke((MethodInvoker)delegate { label3.Text = "Initialization failed"; label3.ForeColor = Color.Red; }); } } private void SearchReceivers() { NativeMethods.ReSearchReceivers(); } private void isReceiversearching() { if (NativeMethods.IsSearchingReceiver() == true) { button3.Invoke((MethodInvoker)delegate { button3.PerformClick(); }); } else { } } private void button1_Click(object sender, EventArgs e) { InitSenders(); } private void button2_Click(object sender, EventArgs e) { SearchReceivers(); } private void button3_Click(object sender, EventArgs e) { bool a = NativeMethods.IsSearchingReceiver(); if (a == true) { ReceiverSearchingStatus = true; } else { ReceiverSearchingStatus = false; } } private void button4_Click(object sender, EventArgs e) { FoundReceivers = NativeMethods.GetFoundReceiverCount(); PD.ReceiversCount = FoundReceivers; if (FoundReceivers < 1) { label6.Text = "Receivers not found"; label6.ForeColor = Color.Orange; } else { label5.Text = FoundReceivers.ToString(); label6.Text = "Receivers found"; label6.ForeColor = Color.Green; } } private void button5_Click(object sender, EventArgs e) { // START DVI IPUT STATUS for (ushort step1 = 0; step1 < sendersCount; step1++) { bool bResult = NativeMethods.IsSenderDviInputOk((byte)step1); if (bResult) { PD.DVIinput = true; label9.Text = "DVI signal OK"; label9.ForeColor = Color.Green; } else { PD.DVIinput = false; label9.Text = "No DVI signal"; label9.ForeColor = Color.Red; } } //END DVI INPUT } private void button6_Click(object sender, EventArgs e) { string[] iReceivers = new string[0]; if (FoundReceivers < 1) { label7.Text = "Module information not found"; label7.ForeColor = Color.Red; } else { iReceivers = new string[FoundReceivers]; //START GEt module voltage and temperature Information NativeMethods.tagReceiverModuleDetailInfo stModuleDetailInfo; int x, y; double voltage; int j; for (int step1 = 0; step1 < FoundReceivers; step1++) { if (NativeMethods.QueryReceiverModuleDetailInfo(out stModuleDetailInfo, (ushort)step1)) { ushort ModuleAmount = stModuleDetailInfo.nRealModuleAmount; string[] jReceivers = new string[ModuleAmount]; if (ModuleAmount < 1) { label7.Text = "Module amount information not found"; label7.ForeColor = Color.Red; } else { for (j = 0; j < ModuleAmount; j++) { x = stModuleDetailInfo.stReceiverModlInfo[j].byModuleVoltage; voltage = x * 32 / 1000.0; y = stModuleDetailInfo.stReceiverModlInfo[j].sbyModuleTemperature; string a = "ReceiverCountValue: " + step1.ToString() + " Module number: " + j.ToString() + " voltage: " + voltage.ToString() + " temperature: " + y.ToString(); jReceivers[j] = a; // MessageBox.Show("ReceiverCount "+ step1 + " Module "+stModuleDetailInfo.stReceiverModlInfo[j].byModuleAddr + " voltage: " + voltage + " temperature: " + y); } label7.Text = "Module information found"; label7.ForeColor = Color.Green; string json = JsonConvert.SerializeObject(jReceivers); iReceivers[step1] = json; } } else { label7.Text = "Module information not found"; label7.ForeColor = Color.Red; } } } PD.Modules = JsonConvert.SerializeObject(iReceivers); PD.Time = DateTime.Now.ToString("HH:mm:ss"); Server server = new Server(); server.SendRequest(PD, boolSendToServer, ServerIp, ServerPort); } private void button7_Click(object sender, EventArgs e) { //Manual brightness set var brightnessValue = Int32.Parse(maskedTextBox13.Text); if (brightnessValue>100) { brightnessValue = 100; } NativeMethods.SetDisplayBrightness((byte)brightnessValue); } private void button8_Click(object sender, EventArgs e) { // auto brightness set } private void checkBox2_CheckedChanged(object sender, EventArgs e) { if (checkBox2.Checked) { checkBox1.Checked = false; } } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked) { checkBox2.Checked = false; } } private void btnEditShedule_Click(object sender, EventArgs e) { ListView.SelectedListViewItemCollection lv = lstShedule.SelectedItems; if (lv.Count > 0){ txtTime.Text = lv[0].Text; txtBrightness.Text = lv[0].SubItems[1].Text; lstShedule.Items.Remove(lv[0]); lstShedule.Refresh(); writeToFile(); } } private void writeToFile() { Dictionary<String, int> d = new Dictionary<String, int>(); foreach (ListViewItem item in lstShedule.Items) { d[item.Text] = Int32.Parse(item.SubItems[1].Text); } String s = JsonConvert.SerializeObject(d); using (StreamWriter w = new StreamWriter("time.json")) { w.Write(s); } } private void writeIPToFile() { Dictionary<String, String> d = new Dictionary<String, String>(); d[textBox1.Text] = textBox2.Text; d["send"] = checkBox3.Checked.ToString(); String s = JsonConvert.SerializeObject(d); using (StreamWriter w = new StreamWriter("send.json")) { w.Write(s); } } private void btnApplyEditShedule_Click(object sender, EventArgs e) { if (!txtTime.Text.Equals("") & !txtBrightness.Text.Equals("")) { ListViewItem itm = new ListViewItem((String)txtTime.Text); itm.SubItems.Add((String)txtBrightness.Text); lstShedule.Items.Add(itm); writeToFile(); txtTime.Text = ""; txtBrightness.Text = ""; } } private void btnSetDefaultBrightness_Click(object sender, EventArgs e) { Connect(); Connect2(); NativeMethods.SetSenderBrightness((byte)0, (byte)Byte.Parse(maskedTextBox13.Text)); NativeMethods.SaveSetsToSender((byte)0); NativeMethods.SetSenderBrightness((byte)1, (byte)Byte.Parse(maskedTextBox13.Text)); NativeMethods.SaveSetsToSender((byte)1); } // END get module info } } /////start get Bad panels ////int reseivers = (int)NativeMethods.GetFoundReceiverCount(); //if (FoundReceivers == 0) //{ // label7.Text = "Couldn't search bad panels"; // label7.ForeColor = Color.Orange; //} //else //{ // NativeMethods.tagReceiverBadPanels badPanels; // for (ushort step1 = 0; step1 < FoundReceivers; step1++) // { // bool status; // for (int step = 0; step < sendersCount; step++) // { // //NativeMethods.tagReceiverMonitorData monitor; // //status = GetReceiverMonitorData(out monitor, (ushort)step1); // //MessageBox.Show(monitor.bwPowerVolt.hi.ToString() + " "+monitor.bwPowerVolt.lo.ToString()); // status = NativeMethods.GetReceiverBadPanels(step1, out badPanels);; // //status = NativeMethods.GetReceiverBadPanels_ById((ushort)senderIDs[step], (byte)step, step1, out badPanels); // if (status == false) // { // MessageBox.Show("read dataFail"); // return; // //MessageBox.Show("col " + badPanels.wReceiverCol.ToString() + " row " + badPanels.wReceiverRow.ToString() + " " + badPanels.byBadPanelCol[step1].ToString()); // } // if (badPanels.byBadPanelCount < 1) // { // //all panels ok // } // else // { // MessageBox.Show("Receiver:row " + badPanels.wReceiverRow + " col " + badPanels.wReceiverCol); // for (int i = 0; i < badPanels.byBadPanelCount; i++) // { // // string message bad panel row and col badPanels.byBadPanelRow[i], badPanels.byBadPanelCol[i] // MessageBox.Show("Receiver:row " + badPanels.byBadPanelRow[i] + " col " + badPanels.byBadPanelCol[i]); // } // } // MessageBox.Show("col " + badPanels.wReceiverCol.ToString() + " row " + badPanels.wReceiverRow.ToString() + " " + badPanels.byBadPanelCol[step1].ToString()); // } // } // //int reseivers = (int)NativeMethods.GetFoundReceiverCount(); // ////NativeMethods.tagReceiverModuleDetailInfo ModuleDetails; // //NativeMethods.tagReceiverBadPanels BadPanels; // //for (int step = 0; step < sendersCount; step++) // //{ // // ushort senderID = NativeMethods.GetSenderId((byte)step); // // for (int step1 = 0; step1 < reseivers; step1++) // // { // // // NativeMethods.GetReceiverBadPanels((ushort)step1, out BadPanels); // // NativeMethods.GetReceiverBadPanels_ById(senderID, (byte)step, (ushort)step1, out BadPanels); // // } // //} //} ////end get Bad Panels /* private void Connect() { Thread.Sleep(500); label3.Invoke((MethodInvoker)delegate { label3.Text = "Senders initialization..."; label3.ForeColor = Color.Blue; }); Thread.Sleep(300); button1.Invoke((MethodInvoker)delegate { button1.PerformClick(); }); Thread.Sleep(5000); label6.Invoke((MethodInvoker)delegate { label6.Text = "Searching receivers..."; label6.ForeColor = Color.Blue; }); button2.Invoke((MethodInvoker)delegate { button2.PerformClick(); }); while (ReceiverSearchingStatus == true) { Thread.Sleep(10000); button3.Invoke((MethodInvoker)delegate { button3.PerformClick(); }); } Thread.Sleep(5000); button3.Invoke((MethodInvoker)delegate { button3.PerformClick(); }); Thread.Sleep(300); button4.Invoke((MethodInvoker)delegate { button4.PerformClick(); }); Thread.Sleep(300); button5.Invoke((MethodInvoker)delegate { button5.PerformClick(); }); } private void BW_DoWork(object sender, DoWorkEventArgs e) { Thread.Sleep(500); label3.Invoke((MethodInvoker)delegate { label3.Text = "Senders initialization..."; label3.ForeColor = Color.Blue; }); Thread.Sleep(300); button1.Invoke((MethodInvoker)delegate { button1.PerformClick(); }); Thread.Sleep(5000); label6.Invoke((MethodInvoker)delegate { label6.Text = "Searching receivers..."; label6.ForeColor = Color.Blue; }); button2.Invoke((MethodInvoker)delegate { button2.PerformClick(); }); while (ReceiverSearchingStatus == true) { Thread.Sleep(10000); button3.Invoke((MethodInvoker)delegate { button3.PerformClick(); }); } Thread.Sleep(5000); button3.Invoke((MethodInvoker)delegate { button3.PerformClick(); }); Thread.Sleep(300); button4.Invoke((MethodInvoker)delegate { button4.PerformClick(); }); Thread.Sleep(300); button5.Invoke((MethodInvoker)delegate { button5.PerformClick(); }); Thread.Sleep(300); label7.Invoke((MethodInvoker)delegate { label7.Text = "Searching module info..."; label7.ForeColor = Color.Blue; }); Thread.Sleep(500); button6.Invoke((MethodInvoker)delegate { button6.PerformClick(); }); } */ <file_sep>๏ปฟusing Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Windows.Forms; using System.Threading; namespace ledWFormsControl { public class Server { public void SendRequest(object sendingData, bool sendData, string serverIP, string serverPort) { var date = DateTime.Now.ToString("yyyy-dd-M"); using (StreamWriter file = File.AppendText(@"C:\senderLog\log" + date + ".txt")) { string json = JsonConvert.SerializeObject(sendingData); file.WriteLine(json + Environment.NewLine); //serialize object directly into file stream } if(sendData) { var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://"+ serverIP +":"+serverPort); string postDataJSON = JsonConvert.SerializeObject(sendingData); var Data = Encoding.ASCII.GetBytes(postDataJSON); httpWebRequest.Method = "POST"; httpWebRequest.ContentType = "application/x-www-form-urlencoded"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { streamWriter.Write(Data); streamWriter.Flush(); streamWriter.Close(); } var response = (HttpWebResponse)httpWebRequest.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); } Thread.Sleep(5000); //Application.Exit(); } } } <file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ledWFormsControl { using System.Runtime.InteropServices; class NativeMethods { public const string DllName = "LED_Setup_Interface.dll"; /// <summary> /// ๆŽฅๆ”ถๅกHubๆฟๆœ€ๅคง็ซฏๅฃๆ•ฐ /// </summary> public const int MAX_RECEIVER_HUB_PORT_AMNT = 16; /// <summary> /// ไธ€ไธชHubๆฟ็ซฏๅฃไธ‹ๆœ€ๅคงๆจก็ป„ๆ•ฐ /// </summary> public const int MAX_RECV_HUB_PORT_MODL_AMNT = 16; public struct tagReceiverIdInfo { /// <summary> /// ๅ‘้€ๅก็ดขๅผ•ๅท๏ผŒ็ฌฌไธ€ๅผ ๅ‘้€ๅก็ดขๅผ•ๅทไธบ0๏ผŒ็ฌฌไบŒๅผ ไธบ1๏ผŒไปฅๆญค็ฑปๆŽจใ€‚ /// </summary> public byte bySenderIndex; /// <summary> /// ๅ‘้€ๅก็ซฏๅฃ็ดขๅผ•ๅท๏ผŒA็ซฏๅฃไธบ0๏ผŒB็ซฏๅฃไธบ1. /// </summary> public byte bySenderPortIndex; /// <summary> /// Hubๅก็ซฏๅฃ็ดขๅผ•ๅท๏ผŒๆฒกๆœ‰ไฝฟ็”จHubๅกๆ—ถไธบ0๏ผŒๆœ‰ไฝฟ็”จHubๅกๆ—ถ็ฌฌไธ€ไธช็ซฏๅฃไธบ0๏ผŒ็ฌฌไบŒไธชไธบ1๏ผŒไปฅๆญค็ฑปๆŽจใ€‚ /// </summary> public byte byHubPortIndex; } public struct tagReceiverBadPanels { /// <summary> /// ไธๆญฃๅธธๆจก็ป„ๆ•ฐ /// </summary> public byte byBadPanelCount; /// <summary> /// ไธๆญฃๅธธๆจก็ป„็š„่กŒไฝ็ฝฎ๏ผˆๆณจ๏ผš้ป˜่ฎค้ƒฝๆ˜ฏไปŽๅฑไฝ“็š„ๆญฃ้ข็œ‹๏ผ‰ /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public byte[] byBadPanelRow; /// <summary> /// ไธๆญฃๅธธๆจก็ป„็š„ๅˆ—ไฝ็ฝฎ /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public byte[] byBadPanelCol; /// <summary> /// ๆŽฅๆ”ถๅก็š„่กŒไฝ็ฝฎ /// </summary> public ushort wReceiverRow; /// <summary> /// ๆŽฅๆ”ถๅก็š„ๅˆ—ไฝ็ฝฎ /// </summary> public ushort wReceiverCol; } public struct tagSenderVersionInfo { /// <summary> /// ๅ‘้€ๅกCPUไธป็‰ˆๆœฌ /// </summary> public byte bySenderCpuMainVer; /// <summary> /// ๅ‘้€ๅกCPUๅญ็‰ˆๆœฌ /// </summary> public byte bySenderCpuSubVer; /// <summary> /// ๅ‘้€ๅกFPGAไธป็‰ˆๆœฌ /// </summary> public byte bySenderFpgaMainVer; /// <summary> /// ๅ‘้€ๅกFPGAๅญ็‰ˆๆœฌ /// </summary> public byte bySenderFpgaSubVer; } [StructLayout(LayoutKind.Sequential)] public struct tagSenderBrightness { /// <summary> /// ๅ‘้€ๅกๆ€ปไฝ“ไบฎๅบฆ /// </summary> public byte byTotalBright; /// <summary> /// ๅ‘้€ๅก็บขไบฎๅบฆ /// </summary> public byte byRedBright; /// <summary> /// ๅ‘้€ๅก็ปฟไบฎๅบฆ /// </summary> public byte byGreenBright; /// <summary> /// ๅ‘้€ๅก่“ไบฎๅบฆ /// </summary> public byte byBlueBright; } public struct tagSenderPortRect { /// <summary> /// ๅ‘้€ๅก็ซฏๅฃ่พ“ๅ‡บXๅๆ ‡ๅ็งป /// </summary> public ushort wLeft; /// <summary> /// ๅ‘้€ๅก็ซฏๅฃ่พ“ๅ‡บYๅๆ ‡ๅ็งป /// </summary> public ushort wTop; /// <summary> /// ๅ‘้€ๅก็ซฏๅฃ่พ“ๅ‡บๅฎฝๅบฆ /// </summary> public ushort wWidth; /// <summary> /// ๅ‘้€ๅก็ซฏๅฃ่พ“ๅ‡บ้ซ˜ๅบฆ /// </summary> public ushort wHeight; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct tagSenderExProp { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)] public string wcSenderIp; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string wcSenderNickName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 30)] public string wcSenderMac; } public struct tagApiBigWord { public byte hi; public byte lo; public ushort GetWord() { return (ushort)(this.hi << 8 + this.lo); } } public struct tagApiBigShort { public byte hi; public byte lo; public short GetShort() { if ((hi & 0x80) != 0) { var temp = (hi & 0x7F) << 8 + lo; return (short)-temp; } return (short)(hi << 8 + lo); } } public struct tagReceiverMonitorData { /// <summary> /// ๆ•ฐๆฎ้ƒจๅˆ†้•ฟๅบฆ128ๅญ—่Š‚ /// Data0-1๏ผšPCB็‰ˆๆœฌๅท, byPcbMainไธป็‰ˆๆœฌๅท๏ผŒbyPcbSubๅญ็‰ˆๆœฌๅท. /// </summary> public byte byPcbMain; public byte byPcbSub; /// <summary> /// Data2-3๏ผšCPU็‰ˆๆœฌๅท, byCpuMainไธป็‰ˆๆœฌๅท,byCpuSubๅญ็‰ˆๆœฌๅท. /// </summary> public byte byCpuMain; public byte byCpuSub; /// <summary> /// Data4-5๏ผš่ฎพๅค‡IDๅท /// </summary> public tagApiBigWord bwDeviceId; /// <summary> /// Data6๏ผš ๅ‡็บงไปฃ็ ๆœ‰ๆ•ˆๆ ‡ๅฟ— ๆˆ– ้ฉฑๅŠจ่Šฏ็‰‡็ฑปๅž‹ /// </summary> public byte byFlagOrChipl; /// <summary> /// Data7๏ผš ๆŽฅๆ”ถๅกๅœฐๅ€ๆจกๅผ /// </summary> public byte byAddressMode; /// <summary> /// Data8-9 ็”ตๆบ็”ตๅŽ‹(ๅ•ไฝmv) /// </summary> public tagApiBigWord bwPowerVolt; /// <summary> /// Data0xA-B /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public byte[] byReserved; /// <summary> /// Data0xC ็Žฏๅขƒไบฎๅบฆๆ ‡ๅฟ— 0: ็Žฏๅขƒไบฎๅบฆๆ— ๆ•ˆ, 1: ็Žฏๅขƒไบฎๅบฆๆœ‰ๆ•ˆ๏ผŒ 2: ไบฎๅบฆๆบขๅ‡บ /// </summary> public byte byEnviBritFlag; /// <summary> /// Data0xD-E ็Žฏๅขƒไบฎๅบฆ๏ผŒ็ญ‰ไบŽ0ๆ—ถๆ— ๆ•ˆ,ๅ•ไฝluxใ€(bwEnviBritValue.GetWord()*nBritCfct)/100ใ€‘,nBritCfct๏ผšไบฎๅบฆ่กฐๅ‡็ณปๆ•ฐ /// </summary> public tagApiBigWord bwEnviBritValue; /// <summary> /// Data0xF ็ฎฑไฝ“ๆนฟๅบฆ /// </summary> public byte byHumidity; /// <summary> /// Data0x10-0x11๏ผš FPGA็‰ˆๆœฌๅท,byFpgaMainไธป็‰ˆๆœฌ๏ผŒ byFpgaSubๅญ็‰ˆๆœฌ. /// </summary> public byte byFpgaMain; public byte byFpgaSub; /// <summary> /// Data0x12-0x13: ็ฎฑไฝ“ๅฎฝๅบฆ /// </summary> public tagApiBigWord bwWidth; /// <summary> /// Data0x14-0x15: ็ฎฑไฝ“้ซ˜ๅบฆ /// </summary> public tagApiBigWord bwHeight; /// <summary> /// Data0x16-0x17: /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public byte[] byReserved2; /// <summary> /// Data0x18-19 ็ฎฑไฝ“ๆธฉๅบฆ,ๅ•ไฝโ„ƒ๏ผˆbnCabinetTemperature.GetShort()/10.0f) /// </summary> public tagApiBigShort bnCabinetTemperature; /// <summary> /// Data0x1A-1B ๆจก็ป„ๅนณๅ‡ๆธฉๅบฆ,ๅ•ไฝโ„ƒ๏ผˆbnCabinetTemperature.GetShort()/10.0f) /// </summary> public tagApiBigShort bnPaneAvgTemperature; /// <summary> /// Data0x1C-1D /// </summary> public tagApiBigWord bwBadPackage; /// <summary> /// Data0x1E-1F /// </summary> public tagApiBigWord bwPixelChipCount; /// <summary> /// Data0x20-2F ้ขๆฟ็Šถๆ€, Bit1๏ผšๆจก็ป„ๆธฉๅบฆไผ ๆ„Ÿๅ™จๆœ‰ๆ•ˆๆ ‡ๅฟ—๏ผŒ0๏ผšๆ— ๆ•ˆ๏ผŒ1๏ผšๆœ‰ๆ•ˆ ; Bit0๏ผšๆจก็ป„I2Cๅญ˜ๅ‚จๅ™จๆœ‰ๆ•ˆๆ ‡ๅฟ—๏ผŒ0๏ผšๆ— ๆ•ˆ๏ผŒ1๏ผšๆœ‰ๆ•ˆ /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public byte[] byPaneStates; /// <summary> /// Data0x30-4f ้ขๆฟๆธฉๅบฆ,ๅ•ไฝโ„ƒ๏ผˆbnCabinetTemperature.GetShort()/10.0f) /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16, ArraySubType = UnmanagedType.I2)] public tagApiBigShort[] bnPaneTemeratures; /// <summary> /// Data0x50-6f ๅƒ็ด ๆฃ€ๆต‹ๅ็‚นๆ•ฐ(16่ทฏ) /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16, ArraySubType = UnmanagedType.I2)] public tagApiBigShort[] bwBadPixelCount; /// <summary> /// Data0x70-7F /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public byte[] byReserved4; /// <summary> /// ๆจก็ป„ๅญ˜ๅ‚จๅ™จๆœ‰ๆ•ˆ? /// </summary> /// <param name="byIndex"></param> /// <returns></returns> public bool IsPaneValid(byte byIndex) { return byIndex < 16 ? (byPaneStates[byIndex] & 0x01) != 0 : false; } public bool IsPaneTemperatureValid(byte byIndex) { return byIndex < 16 ? (byPaneStates[byIndex] & 0x02) != 0 : false; } } /// <summary> /// ๆŸฅ่ฏขๆŽฅๆ”ถๅก่ฟ”ๅ›žๆ•ฐๆฎ่ฟฝๅŠ ้ƒจๅˆ† /// </summary> public struct tagReceiverMonitorData_ExPart { /// <summary> /// Data0x80-8F ๆ•ฐๆฎ็บฟๅฏนๅบ”ๆจก็ป„ๆ•ฐ้‡ไปฅๅŠๆŽ’็บฟ็Šถๆ€ใ€‚bit0~3๏ผšๆจก็ป„ๆ•ฐ้‡๏ผ› bit7:1่กจ็คบ้ƒฝๅฅฝ็š„๏ผŒ0่กจ็คบๆœ‰ๅ็š„๏ผ› /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public byte[] byModuleNumberCableStatus; /// <summary> /// Data90-AF ๆจก็ป„็”ตๅŽ‹(ๅฎž้™…็”ตๅŽ‹=bwModuleVolt*32/1000.0) /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16, ArraySubType = UnmanagedType.I2)] public tagApiBigWord[] bwModuleVolt; /// <summary> /// DataB0-CF ๆจก็ป„ๆธฉๅบฆใ€‚ไฝŽๅญ—่Š‚๏ผšๆ•ฐๆฎ็บฟไธ‹ๆœ€้ซ˜ๆธฉๅบฆ๏ผ›้ซ˜ๅญ—่Š‚๏ผšๆ•ฐๆฎ็บฟไธ‹ๅนณๅ‡ๆธฉๅบฆ๏ผ› /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16, ArraySubType = UnmanagedType.I2)] public tagApiBigWord[] bwModuleTemperature; public bool IsAllCableOk(byte byIndex) { return byIndex < 16 ? (byModuleNumberCableStatus[byIndex] & 0x80) != 0 : false; } public byte GetModuleNumber(byte byIndex) { return (byte)(byIndex < 16 ? (byModuleNumberCableStatus[byIndex] & 0xF) : 0); } public ushort GetAvgVolt(byte byIndex) { return (ushort)(byIndex < 16 ? ((bwModuleVolt[byIndex].hi)) : 0); } public ushort GetLowVolt(byte byIndex) { return (ushort)(byIndex < 16 ? ((bwModuleVolt[byIndex].lo)) : 0); } public sbyte GetAvgTemp(byte byIndex) { return (sbyte)(byIndex < 16 ? ((bwModuleTemperature[byIndex].hi)) : 0); } public sbyte GetLowTemp(byte byIndex) { return (sbyte)(byIndex < 16 ? ((bwModuleTemperature[byIndex].lo)) : 0); } } public struct tagRecvModlInfo { /// <summary> /// ๆจก็ป„ๅœฐๅ€ [BIT7-4] = Row address 0~15, [BIT3-0] = Column address 0~13 /// </summary> public byte byModuleAddr; /// <summary> /// ่ฟž็บฟ็Šถๆ€ [BIT2] = 0 B data line broke /// ใ€€ใ€€ 1 good /// ใ€€ [BIT1] = 0 G data line broke /// ใ€€ใ€€ 1 good /// [BIT0] = 0 R data line broke /// 1 good /// </summary> public byte byCableStatus; /// <summary> /// ๆจก็ป„็”ตๅŽ‹(ๅฎž้™…็”ตๅŽ‹=byModuleVoltage*32/1000.0) /// </summary> public byte byModuleVoltage; /// <summary> /// ๆจก็ป„ๆธฉๅบฆ /// </summary> public sbyte sbyModuleTemperature; short GetModlVoltAsShort() { return byModuleVoltage; } sbyte GetModlTemperature() { return sbyModuleTemperature; } byte GetModlAddrRow() { return (byte)(byModuleAddr >> 4); } byte GetModlAddrCol() { return (byte)(byModuleAddr & 0xF); } bool IsCableOk() { return ((byCableStatus & 0x1) != 0 && (byCableStatus & 0x2) != 0 && (byCableStatus & 0x4) != 0); } } public struct tagReceiverModuleDetailInfo { public int bQueryResultOk; public ushort nRealModuleAmount; [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_RECEIVER_HUB_PORT_AMNT * MAX_RECV_HUB_PORT_MODL_AMNT, ArraySubType = UnmanagedType.I4)] public tagRecvModlInfo[] stReceiverModlInfo; public bool GetReceiverModlInfo(byte byRowAddr/*0~15*/, byte byColAddr/*0~13*/, ref tagRecvModlInfo rReceiverModlInfo) { bool bResult = false; if (nRealModuleAmount > MAX_RECEIVER_HUB_PORT_AMNT * MAX_RECV_HUB_PORT_MODL_AMNT) { nRealModuleAmount = MAX_RECEIVER_HUB_PORT_AMNT * MAX_RECV_HUB_PORT_MODL_AMNT; } for (int i = 0; i < nRealModuleAmount; i++) { if ((stReceiverModlInfo[i].byModuleAddr >> 4) == byRowAddr && (stReceiverModlInfo[i].byModuleAddr & 0xF) == byColAddr) { rReceiverModlInfo = stReceiverModlInfo[i]; bResult = true; break; } } return bResult; } } /// <summary> /// ้‡ๆ–ฐ่ฟžๆŽฅๅ‘้€ๅก /// </summary> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool ReConnectSender(); /// <summary> /// ่Žทๅ–ๅ‘้€ๅก่ฟžๆŽฅไฝฟ็”จ็š„็ฝ‘็ปœ็ซฏๅฃๅท /// </summary> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern ushort GetSenderNetCommPort(); /// <summary> /// ่ฎพ็ฝฎๅ‘้€ๅก่ฟžๆŽฅไฝฟ็”จ็š„็ฝ‘็ปœ็ซฏๅฃๅท๏ผŒ้œ€ไธŽๅ‘้€ๅกๅŒน้…๏ผŒ้ป˜่ฎคไธบ8399 /// </summary> /// <param name="wNetCommPort"></param> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void SetSenderNetCommPort(ushort wNetCommPort = 8399); /// <summary> /// ๆ นๆฎIPๅœฐๅ€่Œƒๅ›ด่ฟžๆŽฅๅ‘้€ๅก๏ผŒ่ฟ”ๅ›ž่ฟžๆŽฅไธŠ็š„ๅ‘้€ๅกๆ•ฐ /// </summary> /// <param name="byIpAddrSub1"></param> /// <param name="byIpAddrSub2"></param> /// <param name="byIpAddrSub3"></param> /// <param name="byIpAddr4_Start"></param> /// <param name="byIpAddr4_End"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern int ConnectSenderByIp(byte byIpAddrSub1, byte byIpAddrSub2, byte byIpAddrSub3, byte byIpAddr4_Start, byte byIpAddr4_End); /// <summary> /// ๆธ…้™คๅทฒ่ฟžๆŽฅไธŠ็š„ๆ‰€ๆœ‰ๅ‘้€ๅก /// </summary> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool ClearSenders(); /// <summary> /// ่Žทๅ–ๅทฒ่ฟžๆŽฅๅ‘้€ๅกๆ•ฐ้‡ /// </summary> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern ushort GetConnectSenderCount(); /// <summary> /// ้‡ๆ–ฐๆœ็ดขๆŽฅๆ”ถๅก /// </summary> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void ReSearchReceivers(); /// <summary> /// ่Žทๅ–ๆœ็ดขๅˆฐ็š„ๆŽฅๆ”ถๅกๆ•ฐ้‡,ๅฆ‚ๆžœไปŽๆœช่ฟžๆŽฅไธŠๅ‘้€ๅกๅนถๆ‰ง่กŒReSearchReceivers๏ผˆ๏ผ‰ๅˆ™่ฟ”ๅ›ž-1 /// </summary> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern int GetFoundReceiverCount(); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๅ‘้€ๅก็ซฏๅฃไธ‹๏ผŒ่ฟžๆŽฅๆญฃๅธธ็š„ๆŽฅๆ”ถๅกๆ•ฐ้‡๏ผ› /// </summary> /// <param name="wSenderId"></param> /// <param name="byPortIndex"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern int GetConnectingReceiverCount(ushort wSenderId, byte byPortIndex); /// <summary> /// ๅˆคๆ–ญๆ˜ฏๅฆๆญฃๅœจๆœ็ดขๆŽฅๆ”ถๅก /// </summary> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool IsSearchingReceiver(); /// <summary> /// ๅœๆญขๆœ็ดขๆŽฅๆ”ถๅก /// </summary> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void StopSearchReceiver(); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๆŽฅๆ”ถๅก็›‘ๆŽง่ฟ”ๅ›ž็š„ๆ•ฐๆฎ /// </summary> /// <param name="pReceiverMonitorData"></param> /// <param name="wReceiverConnIndex"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetReceiverMonitorData(out tagReceiverMonitorData pReceiverMonitorData, ushort wReceiverConnIndex); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๆŽฅๆ”ถๅก็›‘ๆŽง่ฟ”ๅ›ž็š„ๆ•ฐๆฎ /// </summary> /// <param name="pReceiverMonitorData"></param> /// <param name="wSenderId"></param> /// <param name="bySenderPortIndex"></param> /// <param name="wReceiverIndex"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetReceiverMonitorData_ById(out tagReceiverMonitorData pReceiverMonitorData, ushort wSenderId, byte bySenderPortIndex, ushort wReceiverIndex); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๆŽฅๆ”ถๅก็›‘ๆŽง่ฟ”ๅ›ž็š„้ขๅค–ๆ•ฐๆฎ๏ผˆๆจก็ป„ๆฑ‡ๆ€ปไฟกๆฏ๏ผ‰ /// </summary> /// <param name="pReceiverMonitorData_ExPart"></param> /// <param name="wReceiverConnIndex"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetReceiverMonitorData_ExPart(out tagReceiverMonitorData_ExPart pReceiverMonitorData_ExPart, ushort wReceiverConnIndex); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๆŽฅๆ”ถๅก็›‘ๆŽง่ฟ”ๅ›ž็š„้ขๅค–ๆ•ฐๆฎ๏ผˆๆจก็ป„ๆฑ‡ๆ€ปไฟกๆฏ๏ผ‰ /// </summary> /// <param name="pReceiverMonitorData_ExPart"></param> /// <param name="wSenderId"></param> /// <param name="bySenderPortIndex"></param> /// <param name="wReceiverIndex"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetReceiverMonitorData_ExPart_ById(out tagReceiverMonitorData_ExPart pReceiverMonitorData_ExPart, ushort wSenderId, byte bySenderPortIndex, ushort wReceiverIndex); /// <summary> /// ๆŸฅ่ฏขๆŒ‡ๅฎšๆŽฅๆ”ถๅกๆจก็ป„่ฏฆ็ป†ไฟกๆฏ /// </summary> /// <param name="pReceiverModuleDetailInfo"></param> /// <param name="wReceiverConnIndex"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool QueryReceiverModuleDetailInfo(out tagReceiverModuleDetailInfo pReceiverModuleDetailInfo, ushort wReceiverConnIndex); /// <summary> /// ๆŸฅ่ฏขๆŒ‡ๅฎšๆŽฅๆ”ถๅกๆจก็ป„่ฏฆ็ป†ไฟกๆฏ /// </summary> /// <param name="pReceiverModuleDetailInfo"></param> /// <param name="wSenderId"></param> /// <param name="bySenderPortIndex"></param> /// <param name="wReceiverIndex"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool QueryReceiverModuleDetailInfo_ById(out tagReceiverModuleDetailInfo pReceiverModuleDetailInfo, ushort wSenderId, byte bySenderPortIndex, ushort wReceiverIndex); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๆŽฅๆ”ถๅกIdไฟกๆฏ /// </summary> /// <param name="pRecvIdInfo"></param> /// <param name="wReceiverConnIndex"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetReceiverIdInfo(out tagReceiverIdInfo pRecvIdInfo, ushort wReceiverConnIndex); /// <summary> /// ่Žทๅ–ๅ‘้€ๅกID /// </summary> /// <param name="bySenderIndex"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern ushort GetSenderId(byte bySenderIndex); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetSenderExProp(byte bySenderIndex, out tagSenderExProp pSenderExProp); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetSenderExProp_ById(ushort wSenderId, out tagSenderExProp pSenderExProp); /// <summary> /// ่ฎพ็ฝฎๆ˜พ็คบๅฑ่ตทๅง‹ๅๆ ‡ /// </summary> /// <param name="wLeft"></param> /// <param name="wTop"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetDisplayOrigin(ushort wLeft, ushort wTop); /// <summary> /// ่ฎพ็ฝฎๅ‘้€ๅก่ตทๅง‹ๅๆ ‡ /// </summary> /// <param name="bySenderIndex"></param> /// <param name="wLeft"></param> /// <param name="wTop"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetSenderOrigin(byte bySenderIndex, ushort wLeft, ushort wTop); /// <summary> /// ่ฎพ็ฝฎๅ‘้€ๅก่ตทๅง‹ๅๆ ‡ /// </summary> /// <param name="wSenderId"></param> /// <param name="wLeft"></param> /// <param name="wTop"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetSenderOrigin_ById(ushort wSenderId, ushort wLeft, ushort wTop); /// <summary> /// ่ฎพ็ฝฎๅ‘้€ๅก็ซฏๅฃๅๆ ‡ๅ็งป /// </summary> /// <param name="bySenderIndex"></param> /// <param name="bySenderPortIndex"></param> /// <param name="wLeft"></param> /// <param name="wTop"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetSenderPortOffset(byte bySenderIndex, byte bySenderPortIndex, ushort wLeft, ushort wTop); /// <summary> /// ่ฎพ็ฝฎๅ‘้€ๅก็ซฏๅฃๅๆ ‡ๅ็งป /// </summary> /// <param name="wSenderId"></param> /// <param name="bySenderPortIndex"></param> /// <param name="wLeft"></param> /// <param name="wTop"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetSenderPortOffset_ById(ushort wSenderId, byte bySenderPortIndex, ushort wLeft, ushort wTop); /// <summary> /// ่ฎพ็ฝฎๅ‘้€ๅก็ซฏๅฃ่พ“ๅ‡บๅฎฝ้ซ˜ /// </summary> /// <param name="bySenderIndex"></param> /// <param name="bySenderPortIndex"></param> /// <param name="wWidth"></param> /// <param name="wHeight"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetSenderPortSize(byte bySenderIndex, byte bySenderPortIndex, ushort wWidth, ushort wHeight); /// <summary> /// ่ฎพ็ฝฎๅ‘้€ๅก็ซฏๅฃ่พ“ๅ‡บๅฎฝ้ซ˜ /// </summary> /// <param name="wSenderId"></param> /// <param name="bySenderPortIndex"></param> /// <param name="wWidth"></param> /// <param name="wHeight"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetSenderPortSize_ById(ushort wSenderId, byte bySenderPortIndex, ushort wWidth, ushort wHeight); /// <summary> /// ่ฎพ็ฝฎๆ˜พ็คบๅฑๆ€ปไฝ“ไบฎๅบฆ /// </summary> /// <param name="byBrightness"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetDisplayBrightness(byte byBrightness); /// <summary> /// ่ฎพ็ฝฎๅ‘้€ๅกๆ€ปไฝ“ไบฎๅบฆ /// </summary> /// <param name="bySenderIndex"></param> /// <param name="byBrightness"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetSenderBrightness(byte bySenderIndex, byte byBrightness); /// <summary> /// ่ฎพ็ฝฎๅ‘้€ๅกๆ€ปไฝ“ไบฎๅบฆ /// </summary> /// <param name="wSenderId"></param> /// <param name="byBrightness"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetSenderBrightness_ById(ushort wSenderId, byte byBrightness); /// <summary> /// ่ฎพ็ฝฎๆ˜พ็คบๅฑ็บขใ€็ปฟใ€่“ไบฎๅบฆ /// </summary> /// <param name="byRed"></param> /// <param name="byGreen"></param> /// <param name="byBlue"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetDisplayColor(byte byRed, byte byGreen, byte byBlue); /// <summary> /// ่ฎพ็ฝฎๅ‘้€ๅก็บขใ€็ปฟใ€่“ไบฎๅบฆ /// </summary> /// <param name="bySenderIndex"></param> /// <param name="byRed"></param> /// <param name="byGreen"></param> /// <param name="byBlue"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetSenderColor(byte bySenderIndex, byte byRed, byte byGreen, byte byBlue); /// <summary> /// ่ฎพ็ฝฎๅ‘้€ๅก็บขใ€็ปฟใ€่“ไบฎๅบฆ /// </summary> /// <param name="wSenderId"></param> /// <param name="byRed"></param> /// <param name="byGreen"></param> /// <param name="byBlue"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetSenderColor_ById(ushort wSenderId, byte byRed, byte byGreen, byte byBlue); /// <summary> /// ๅผ€ๅ…ณๆ˜พ็คบๅฑ /// </summary> /// <param name="bOn"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetDisplayState(bool bOn); /// <summary> /// ๆฃ€ๆŸฅๅ‘้€ๅกๆ˜ฏๅฆๅœจ่ฟžๆŽฅ็Šถๆ€ /// </summary> /// <param name="bySenderIndex"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool IsSenderConnect(byte bySenderIndex); /// <summary> /// ๆฃ€ๆŸฅๅ‘้€ๅกๆ˜ฏๅฆๅœจ่ฟžๆŽฅ็Šถๆ€ /// </summary> /// <param name="wSenderId"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool IsSenderConnect_ById(ushort wSenderId); /// <summary> /// ๆฃ€ๆŸฅๅ‘้€ๅกDVI่พ“ๅ…ฅๆ˜ฏๅฆๆญฃๅธธ /// </summary> /// <param name="bySenderIndex"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool IsSenderDviInputOk(byte bySenderIndex); /// <summary> /// ๆฃ€ๆŸฅๅ‘้€ๅกDVI่พ“ๅ…ฅๆ˜ฏๅฆๆญฃๅธธ /// </summary> /// <param name="wSenderId"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool IsSenderDviInputOk_ById(ushort wSenderId); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๅ‘้€ๅก่พ“ๅ…ฅๅˆ†่พจ็Ž‡ /// </summary> /// <param name="bySenderIndex"></param> /// <param name="rHorResolution"></param> /// <param name="rVerResolution"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetSenderDviInput(byte bySenderIndex, out ushort rHorResolution, out ushort rVerResolution); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๅ‘้€ๅก่พ“ๅ…ฅๅˆ†่พจ็Ž‡ /// </summary> /// <param name="wSenderId"></param> /// <param name="rHorResolution"></param> /// <param name="rVerResolution"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetSenderDviInput_ById(ushort wSenderId, out ushort rHorResolution, out ushort rVerResolution); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๅ‘้€ๅก็‰ˆๆœฌไฟกๆฏ /// </summary> /// <param name="bySenderIndex"></param> /// <param name="pSenderVersionInfo"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetSenderVersionInfo(byte bySenderIndex, out tagSenderVersionInfo pSenderVersionInfo); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๅ‘้€ๅก็‰ˆๆœฌไฟกๆฏ /// </summary> /// <param name="wSenderId"></param> /// <param name="pSenderVersionInfo"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetSenderVersionInfo_ById(ushort wSenderId, out tagSenderVersionInfo pSenderVersionInfo); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๅ‘้€ๅกไบฎๅบฆไฟกๆฏ /// </summary> /// <param name="bySenderIndex"></param> /// <param name="pSenderBrightness"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetSenderBrightness(byte bySenderIndex, out tagSenderBrightness pSenderBrightness); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๅ‘้€ๅกไบฎๅบฆไฟกๆฏ /// </summary> /// <param name="wSenderId"></param> /// <param name="pSenderBrightness"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetSenderBrightness_ById(ushort wSenderId, out tagSenderBrightness pSenderBrightness); /// <summary> /// ่Žทๅ–ๅ‘้€ๅก็ซฏๅฃ่พ“ๅ‡บๅŒบๅŸŸ /// </summary> /// <param name="bySenderIndex"></param> /// <param name="bySenderPortIndex"></param> /// <param name="pSenderPortRect"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetSenderPortRect(byte bySenderIndex, byte bySenderPortIndex, out tagSenderPortRect pSenderPortRect); /// <summary> /// ่Žทๅ–ๅ‘้€ๅก็ซฏๅฃ่พ“ๅ‡บๅŒบๅŸŸ /// </summary> /// <param name="wSenderId"></param> /// <param name="bySenderPortIndex"></param> /// <param name="pSenderPortRect"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetSenderPortRect_ById(ushort wSenderId, byte bySenderPortIndex, out tagSenderPortRect pSenderPortRect); /// <summary> /// ๅŠ ่ฝฝๆ˜พ็คบๅฑ่ฎพ็ฝฎๆ–‡ไปถ /// </summary> /// <param name="pFileName"></param> /// <returns></returns> [DllImport(DllName, CharSet = CharSet.Unicode)] public static extern bool LoadDisplaySetFile(string pFileName); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๆŽฅๆ”ถๅกไธๆญฃๅธธๆจก็ป„ไฟกๆฏ /// </summary> /// <param name="wReceiverConnIndex"></param> /// <param name="pReceiverBadPanels"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetReceiverBadPanels(ushort wReceiverConnIndex, out tagReceiverBadPanels pReceiverBadPanels); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๆŽฅๆ”ถๅกไธๆญฃๅธธๆจก็ป„ไฟกๆฏ /// </summary> /// <param name="wSenderId"></param> /// <param name="bySenderPortIndex"></param> /// <param name="wReceiverIndex"></param> /// <param name="pReceiverBadPanels"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetReceiverBadPanels_ById(ushort wSenderId, byte bySenderPortIndex, ushort wReceiverIndex, out tagReceiverBadPanels pReceiverBadPanels); /// <summary> /// ๅผ€ๅ…ณๆŽฅๆ”ถๅก็›‘ๆŽง /// </summary> /// <param name="bOn"></param> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void SetReceiverMonitor(bool bOn); /// <summary> /// ่Žทๅ–ๆŽฅๆ”ถๅก้‡‡้›†ๅˆฐ็š„็Žฏๅขƒไบฎๅบฆ /// </summary> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern int GetEnvironmentBright(); /// <summary> /// ่ฎพ็ฝฎไบฎๅบฆ่กฐๅ‡็ณปๆ•ฐ๏ผˆๅฝ“้‡‡้›†ๅˆฐ็š„ไบฎๅบฆไธŽๅฎž้™…็Žฏๅขƒไบฎๅบฆไธไธ€่‡ดๆ—ถ๏ผŒๅฏ้€š่ฟ‡่ฎพ็ฝฎๆญคๅ‚ๆ•ฐ่พพๅˆฐๆ กๆญฃ๏ผ‰ /// </summary> /// <param name="wLumAtteCoef"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetLumAttenuationCoefficient(ushort wLumAtteCoef); /// <summary> /// ่Žทๅ–ๅฝ“ๅ‰ไบฎๅบฆ่กฐๅ‡็ณปๆ•ฐ /// </summary> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern ushort GetLumAttenuationCoefficient(); /// <summary> /// ๆฃ€ๆŸฅๆŽฅๆ”ถๅกๆ˜ฏๅฆๅค„ๅœจ็›‘ๆŽง็Šถๆ€ /// </summary> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool IsReceiverMonitorOn(); /// <summary> /// ้‡ๅฏๆŽฅๆ”ถๅก, nSenderId = -1ๆ—ถ๏ผŒ้‡ๅฏๆ‰€ๆœ‰ๅ‘้€ๅกไธ‹็š„ๆŽฅๆ”ถๅก /// </summary> /// <param name="nSenderId"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool ReStartReceivers(int nSenderId = -1); /// <summary> /// ่ฎพ็ฝฎๆŒ‡ๅฎšๅ‘้€ๅกๆ˜พ็คบๆบ๏ผŒnSenderId = -1ๆ—ถ่ฎพ็ฝฎๆ‰€ๆœ‰ๅ‘้€ๅก, bySource = 0๏ผš ๅˆ‡ๆขๅฝ“ๅ‰้€‰ๆ‹ฉ็š„ๆบ,ๅŒๆญฅ->ๅผ‚ๆญฅ๏ผŒๅผ‚ๆญฅ->ๅŒๆญฅใ€€1๏ผš ๅŒๆญฅไผ˜ๅ…ˆๆจกๅผใ€€2๏ผš ๅผบๅˆถๅผ‚ๆญฅๆจกๅผใ€€3๏ผš ๅผบๅˆถๅŒๆญฅๆจกๅผใ€€ใ€€ /// ่ฟ”ๅ›ž่ฎพ็ฝฎๅ‘้€ๅก็š„ๆ•ฐ้‡ /// </summary> /// <param name="bySource"></param> /// <param name="nSenderId"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetDisplaySource(byte bySource = 1, int nSenderId = -1); /// <summary> /// ่Žทๅ–ๆŒ‡ๅฎšๅ‘้€ๅกๆ˜พ็คบๆบ๏ผŒnSenderId = -1ๆ—ถ่Žทๅ–็ฌฌไธ€ๅผ ๅ‘้€ๅกๆ˜พ็คบๆบใ€‚ ่ฟ”ๅ›ž 0๏ผšๅผ‚ๆญฅ๏ผŒ 1๏ผšๅŒๆญฅ /// </summary> /// <param name="nSenderId"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern byte GetDisplaySource(int nSenderId = -1); /// <summary> /// ่ฎพ็ฝฎๅ‘้€ๅก็ซฏๅฃๅผ€ๅ…ณ็Šถๆ€ /// </summary> /// <param name="wSenderId"></param> /// <param name="bPortA_On"></param> /// <param name="bPortB_On"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetSenderPortState(ushort wSenderId, bool bPortA_On = true, bool bPortB_On = true); /// <summary> /// ่Žทๅ–ๅ‘้€ๅก็ซฏๅฃๅผ€ๅ…ณ็Šถๆ€ /// </summary> /// <param name="wSenderId"></param> /// <param name="bPortA_On"></param> /// <param name="bPortB_On"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetSenderPortState(ushort wSenderId, ref bool bPortA_On, ref bool bPortB_On); /// <summary> /// ่ฎพ็ฝฎๅ‘้€ๅก็ซฏๅฃไบฎๅบฆ /// </summary> /// <param name="wSenderId"></param> /// <param name="stPortA_Brightness"></param> /// <param name="stPortB_Brightness"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetSenderPortBright(ushort wSenderId, tagSenderBrightness stPortA_Brightness, tagSenderBrightness stPortB_Brightness); /// <summary> /// ่Žทๅ–ๅ‘้€ๅก็ซฏๅฃไบฎๅบฆ /// </summary> /// <param name="wSenderId"></param> /// <param name="stPortA_Brightness"></param> /// <param name="stPortB_Brightness"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetSenderPortBright(ushort wSenderId, out tagSenderBrightness stPortA_Brightness, out tagSenderBrightness stPortB_Brightness); /// <summary> /// ไฟๅญ˜ๅ‘้€ๅก่ฎพ็ฝฎๆ•ฐๆฎ /// </summary> /// <param name="bySenderIndex"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool SaveSetsToSender(byte bySenderIndex); /// <summary> /// ไฟๅญ˜ๅ‘้€ๅก่ฎพ็ฝฎๆ•ฐๆฎ /// </summary> /// <param name="wSenderId"></param> /// <returns></returns> [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern bool SaveSetsToSender_ById(ushort wSenderId); } }
a016029969306d1d023be87047589ec351d551e2
[ "C#", "Text" ]
4
Text
EreminDm/ledWFormsControl
31f81cac1b5134dc3a32edc8916779548cffcb5f
ce6a8b03ec11940388780f2a08ce2facff04cb96
refs/heads/main
<repo_name>careythetech/Rebilla<file_sep>/main.js var radioButtons = $(".form-radio"); var dropdownContainer = $("#dropdown-container") function handleChange(data) { var tdObj = jQuery(data) var parent = jQuery(tdObj.next()) var label = parent.text() // console.log(label) if (label === "Auto-ship - Subscribe & Save! (USA Orders Only)") { dropdownContainer.append(`<select> <option>Send every 1 months</option> <option>Send every 2 months</option> <option>Send every 3 months</option> <option>Send every 1 year</option> <option>Send every 1 weeks</option> <option>Send every 2 weeks</option> <option>Send every 3 weeks</option> <option>Send every 4 months</option> <option>Send every 5 months</option> <option>Send every 6 months</option> </select>`) } else if (label === "One Time Only") { dropdownContainer.html("") } }
b17dd93b75ee1b9030ccfb08fe3f680f9b0667dc
[ "JavaScript" ]
1
JavaScript
careythetech/Rebilla
94a955ffd5e1f2dd38e01b0809a42f2912919cbb
9504c8b5f363a6ceea8413da35d68e227116a429
refs/heads/master
<repo_name>pedroaro/FORMINST<file_sep>/forminst_new1/app/views/entidads/index.json.jbuilder json.array!(@entidads) do |entidad| json.extract! entidad, :id, :id, :nombre, :escuelaId json.url entidad_url(entidad, format: :json) end <file_sep>/forminst_new1/app/models/informe_actividad.rb class InformeActividad < ActiveRecord::Base belongs_to :informe has_many :documento has_many :observacion_actividad_informe has_many :actividad_ejecutada has_many :observacion_tutor belongs_to :actividad end <file_sep>/forminst_new1/app/models/adecuacionactividad.rb class Adecuacionactividad < ActiveRecord::Base belongs_to :adecuacion has_many :observacionesactividadadecuacion belongs_to :actividad end<file_sep>/forminst_new1/app/models/permisologium.rb class Permisologium < ActiveRecord::Base belongs_to :usuario belongs_to :permiso end<file_sep>/forminst_new1/app/controllers/inicioinstructor_controller.rb ๏ปฟclass InicioinstructorController < ApplicationController layout 'ly_inicio_entidad' #Inicio del Modulo del Instructor def index if session[:usuario_id] && session[:instructor] == true #verificar que no ingresara con el link del modulo plan = Planformacion.where(instructor_id: session[:usuario_id]).take #Se busca el plan de formaciรณn del instructor session[:adecuacion_id] = Adecuacion.where(planformacion_id: plan.id).take.id #se busca la adecuacion del instructor session[:plan_id] = plan.id #se alamacena el plan de formaciรณn session[:instructorName] = nil session[:informe_id] = nil @nombre = session[:nombre_usuario] #almacenar las notificaciones del usuario para mostrarlas @notificaciones1= [] @notificaciones = Notificacion.where(instructor_id: session[:usuario_id]).all @notificaciones.each do |notificaciones| if notificaciones.actual == 2 #Caso de notificaciones del instructor @notificaciones1.push(notificaciones) end end #si intenta ingresar por la direccion del url else redirect_to controller:"forminst", action: "index" end end def destroyNotifications @post = Notificacion.find(params[:id]) respond_to do |format| if @post.destroy format.html { redirect_to :back } else flash[:notice] = "Post failed to delete." format.html { redirect_to :back } end end end #Vista de los soportes agregados def ver_soporte @plan = Planformacion.where(id: session[:plan_id]).take #buscar planformacion de instructor $actividad = params[:actividad_id].to_i @documents = [] #si son los soportes de un informe if !session[:informe_id].blank? @documents = Document.where("informe_id <= ? AND adecuacion_id = ? AND actividad_id = ?",session[:informe_id] , session[:adecuacion_id], $actividad).all #si son los soporter de una adecuacion else @documents = Document.where(adecuacion_id: session[:adecuacion_id], informe_id: nil).all end end def listar_adecuaciones if session[:usuario_id] && session[:instructor] == true @nombre = session[:nombre_usuario] @plan_formacion = Planformacion.where(instructor_id: session[:usuario_id]).take @adecuacion = Adecuacion.where(planformacion_id: @plan_formacion).take @tutor1 = Persona.where(usuario_id: @adecuacion.tutor_id).take @tutor = @tutor1.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @tutor1.apellidos.to_s.split.map(&:capitalize).join(' ') @status_adecuacion = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take @tipo_status = "[" + @status_adecuacion.fecha.to_s + "]: " + TipoEstatus.where(id: @status_adecuacion.estatus_id, ).take.concepto if not @adecuacion end else redirect_to controller:"forminst", action: "index" end end def ver_respaldos if session[:usuario_id] && session[:instructor] @plan = Planformacion.where(id: session[:plan_id]).take @documents = [] adec = Adecuacion.where(planformacion_id: session[:plan_id]).take #si se desea saber el respaldo de los informes if !session[:informe_id].blank? @documents = Respaldo.where(adecuacion_id: adec.id, informe_id: session[:informe_id], actual: 0).all else @documents = Respaldo.where(adecuacion_id: adec.id, informe_id: nil, actual: 0).all end #si intenta ingresar mediante el link else redirect_to controller:"forminst", action: "index" end end #mostrar el pdf del respaldo def show #si es informe if params[:informe_id].blank? @document = Respaldo.where(adecuacion_id: params[:adecuacion_id], informe_id: nil, version: params[:version].to_i, filename: params[:namefile]).take #si es adecuacion else @document = Respaldo.where(adecuacion_id: params[:adecuacion_id], informe_id: params[:informe_id],version: params[:version].to_i, filename: params[:namefile]).take end #abrir el documento send_data(@document.file_contents, type: @document.content_type, filename: @document.filename) end #modulo de prorroga (fuera de funcionamiento) def prorrogas if session[:usuario_id] && session[:instructor] == true @persona = Persona.where(usuario_id: session[:usuario_id]).take @nombre = session[:nombre_usuario] @planformacion = Planformacion.where(instructor_id: session[:usuario_id]).take #@tutor = Persona.where(usuario_id: @adecuacion.tutor_id).take.nombres @informes = Informe.where(planformacion_id: @planformacion) @informe = Informe.where(planformacion_id: @planformacion).take session[:informe_id] = nil @tipos= [] @informes.each do |inf| if inf.tipo_id == 1 @tipos.push('Semestral') else if inf.tipo_id ==2 @tipos.push('Anual') else if inf.tipo_id==3 @tipos.push('Final') end end end end if not @nombre print "NO HAY USUARIO" end else redirect_to controller:"forminst", action: "index" end end #Vista previa del Informe def vista_previa1 if !session[:informe_id].blank? #Obtener todos los datos importantes de la base de datos @informe= Informe.find(session[:informe_id]) @TipoSemestre=TipoInforme.where(id: @informe.tipo_id).take @fechaActual = Date.current.to_s @plan= Planformacion.find(session[:plan_id]) @fechaConcurso = @plan.fecha_inicio @usere= Usuarioentidad.where(usuario_id: @plan.instructor_id).take @escuela= Escuela.find(@usere.escuela_id) @adecuacion= Adecuacion.where(planformacion_id: @plan.id).take @adscripcion_docencia= @plan.adscripcion_docencia @adscripcion_investigacion= @plan.adscripcion_investigacion @persona= Persona.where(usuario_id: @plan.instructor_id).take @cpinstruccion = @persona.grado_instruccion @user = Usuario.find(@plan.instructor_id) @tutor = Persona.where(usuario_id: @plan.tutor_id).take @periodo = @informe.fecha_inicio.to_s + " al " + @informe.fecha_fin.to_s @nombre_informe = "" if (@informe.numero == 1 || @informe.numero == 3) @nombre_informe= "PRIMER INFORME " elsif (@informe.numero == 2 || @informe.numero == 6) @nombre_informe= "SEGUNDO INFORME " elsif @informe.numero == 4 @nombre_informe= "TERCER INFORME " elsif @informe.numero == 5 @nombre_informe= "CUARTO INFORME " end if @informe.tipo_id == 1 @nombre_informe= @nombre_informe+"SEMESTRAL" elsif @informe.tipo_id == 2 @nombre_informe= @nombre_informe+"ANUAL" else @nombre_informe= "INFORME "+"FINAL" end @docencia='docencia' @investigacion= 'investigacion' @obligatoria= 'obligatoria' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @CJagregado=["no","no","no","no"] @semestres = [] @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @actividades1doc= [] @actividades1inv= [] @actividades1ext= [] @actividades1for= [] @actividades1otr= [] @actividades1= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividades1.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades1doc.push(@act) else if tipo==2 if @informe.numero == 1 @resActi= InformeActividad.where(informe_id: @informe.id, actividad_id: @act.id).take @res= Resultado.where(informe_actividad_id: @resActi.id).all end @actividades1inv.push(@act) else if tipo==3 @actividades1ext.push(@act) else if tipo==4 @actividades1for.push(@act) else if tipo==5 @actividades1otr.push(@act) end end end end end end @actividades2doc= [] @actividades2inv= [] @actividades2ext= [] @actividades2for= [] @actividades2otr= [] @actividades2= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @actividades2.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades2doc.push(@act) else if tipo==2 @actividades2inv.push(@act) else if tipo==3 @actividades2ext.push(@act) else if tipo==4 @actividades2for.push(@act) else if tipo==5 @actividades2otr.push(@act) end end end end end end @actividades3doc= [] @actividades3inv= [] @actividades3ext= [] @actividades3for= [] @actividades3otr= [] @actividades3= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all @actividades3.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades3doc.push(@act) else if tipo==2 @actividades3inv.push(@act) else if tipo==3 @actividades3ext.push(@act) else if tipo==4 @actividades3for.push(@act) else if tipo==5 @actividades3otr.push(@act) end end end end end end @actividades4doc= [] @actividades4inv= [] @actividades4ext= [] @actividades4for= [] @actividades4otr= [] @actividades4= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all @actividades4.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades4doc.push(@act) else if tipo==2 @actividades4inv.push(@act) else if tipo==3 @actividades4ext.push(@act) else if tipo==4 @actividades4for.push(@act) else if tipo==5 @actividades4otr.push(@act) end end end end end end @actividades5doc= [] @actividades5inv= [] @actividades5ext= [] @actividades5for= [] @actividades5otr= [] @actividades5= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 5).all @actividades5.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades5doc.push(@act) elsif tipo==2 @actividades5inv.push(@act) elsif tipo==3 @actividades5ext.push(@act) elsif tipo==4 @actividades5for.push(@act) end end @bool_enviado = 0 estatus_informe = EstatusInforme.where(informe_id: @informe.id, actual: 1).take if (estatus_informe.estatus_id != 6 && estatus_informe.estatus_id != 5) @bool_enviado = 1 end actividades = AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0) actividades1 = [] if !actividades.blank? actividades.each do |actividadAde| actividad = Actividad.find(actividadAde.actividad_id) actividades1.push(actividad) end end @presentacion = "" @descripcion = "" @docencia = [] @investigacion = [] @formacion = [] @extension = [] if !actividades1.blank? actividades1.each do |actividadAde| if actividadAde.tipo_actividad_id == 9 if actividadAde.actividad.blank? @presentacion = " " else @presentacion = actividadAde.actividad end elsif actividadAde.tipo_actividad_id == 8 if actividadAde.actividad.blank? @descripcion = " " else @descripcion = actividadAde.actividad end elsif actividadAde.tipo_actividad_id == 1 if actividadAde.actividad.blank? @docencia.push(" ") else @docencia.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 2 if actividadAde.actividad.blank? @investigacion.push(" ") else @investigacion.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 4 if actividadAde.actividad.blank? @formacion.push(" ") else @formacion.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 3 if actividadAde.actividad.blank? @extension.push(" ") else @extension.push(actividadAde) end end end else @presentacion = " " @descripcion = " " @docencia = [" "] @investigacion = [" "] @formacion = [" "] @extension = [" "] end @j = 0 @i = 0 @actividadesa= InformeActividad.where(informe_id: @informe.id).all @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaobli= [] @actividadesaotr= [] @resultados= [] @actividadese= [] @observaciont= [] @resultTP = [] @resultPP = [] @resultPIT = [] @resultO = [] @resultAEC = [] @resultOEC = [] @resultDCS = [] @actividadesa.each do |actade| @resultados2 = "" @res= Resultado.where(informe_actividad_id: actade.id).all if actade.actividad_id == nil #Es el caso que es un resultado no contemplado en el plan de formacion o un avancwe de postgrado if [email protected]? @res.each do |res| @resultados2 = "" @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a","a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = res.titulo.capitalize @cparray[1] = res.autor.capitalize @cparray[2] = res.nombre_capitulo.to_s.capitalize @cparray[3] = res.autor_capitulo.to_s.capitalize @cparray[4] = res.dia @cparray[5] = res.mes @cparray[6] = res.ano @cparray[7] = res.ciudad.to_s.capitalize @cparray[8] = res.estado.to_s.capitalize @cparray[9] = res.pais.to_s.capitalize @cparray[10] = res.organizador.to_s.capitalize @cparray[11] = res.duracion.to_s.capitalize @cparray[12] = res.editor.to_s.capitalize @cparray[13] = res.titulo_libro.to_s.capitalize @cparray[14] = res.autor_libro.to_s.capitalize @cparray[15] = res.nombre_revista.to_s.capitalize @cparray[16] = res.nombre_periodico.to_s.capitalize @cparray[17] = res.nombre_acto.to_s.capitalize @cparray[18] = res.paginas @cparray[19] = res.nombre_paginaw.to_s.capitalize @cparray[20] = res.sitio_paginaw @cparray[21] = res.infoafiliaion.to_s.capitalize @cparray[22] = res.cptipo.to_s.capitalize @cparray[23] = res.nombre.to_s.capitalize @cparray[24] = res.ISSN_impreso.to_s.capitalize @cparray[25] = res.ISSN_electro.to_s.capitalize @cparray[26] = res.volumen.to_s.capitalize @cparray[27] = res.edicion.to_s.capitalize @cparray[28] = res.DOI @cparray[29] = res.ISBN @cparray[30] = res.universidad.to_s.capitalize @cparray[31] = res.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = "* " + @noemptyarray end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @resultados2 + @noemptyarray.join(', ') end end end if res.tipo_resultado_id == 1 @resultTP.push(@resultados2) elsif res.tipo_resultado_id == 2 @resultPP.push(@resultados2) elsif res.tipo_resultado_id == 3 @resultPIT.push(@resultados2) elsif res.tipo_resultado_id == 4 @resultO.push(@resultados2) elsif res.tipo_resultado_id == 5 @resultAEC.push(@resultados2) elsif res.tipo_resultado_id == 6 @resultOEC.push(@resultados2) elsif res.tipo_resultado_id == 7 @resultDCS.push(@resultados2) end @resultados.push(res) end end else @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if [email protected]? @res.each do |res| @resultados2 = "" @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a","a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = res.titulo.capitalize @cparray[1] = res.autor.capitalize @cparray[2] = res.nombre_capitulo.to_s.capitalize @cparray[3] = res.autor_capitulo.to_s.capitalize @cparray[4] = res.dia @cparray[5] = res.mes @cparray[6] = res.ano @cparray[7] = res.ciudad.to_s.capitalize @cparray[8] = res.estado.to_s.capitalize @cparray[9] = res.pais.to_s.capitalize @cparray[10] = res.organizador.to_s.capitalize @cparray[11] = res.duracion.to_s.capitalize @cparray[12] = res.editor.to_s.capitalize @cparray[13] = res.titulo_libro.to_s.capitalize @cparray[14] = res.autor_libro.to_s.capitalize @cparray[15] = res.nombre_revista.to_s.capitalize @cparray[16] = res.nombre_periodico.to_s.capitalize @cparray[17] = res.nombre_acto.to_s.capitalize @cparray[18] = res.paginas @cparray[19] = res.nombre_paginaw.to_s.capitalize @cparray[20] = res.sitio_paginaw @cparray[21] = res.infoafiliaion.to_s.capitalize @cparray[22] = res.cptipo.to_s.capitalize @cparray[23] = res.nombre.to_s.capitalize @cparray[24] = res.ISSN_impreso.to_s.capitalize @cparray[25] = res.ISSN_electro.to_s.capitalize @cparray[26] = res.volumen.to_s.capitalize @cparray[27] = res.edicion.to_s.capitalize @cparray[28] = res.DOI @cparray[29] = res.ISBN @cparray[30] = res.universidad.to_s.capitalize @cparray[31] = res.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = "* " + @noemptyarray end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @resultados2 + @noemptyarray.join(', ') end end end if res.tipo_resultado_id == 1 @resultTP.push(@resultados2) elsif res.tipo_resultado_id == 2 @resultPP.push(@resultados2) elsif res.tipo_resultado_id == 3 @resultPIT.push(@resultados2) elsif res.tipo_resultado_id == 4 @resultO.push(@resultados2) elsif res.tipo_resultado_id == 5 @resultAEC.push(@resultados2) elsif res.tipo_resultado_id == 6 @resultOEC.push(@resultados2) elsif res.tipo_resultado_id == 7 @resultDCS.push(@resultados2) end @resultados.push(res) end end end @ae= ActividadEjecutada.where(informe_actividad_id: actade.id).take @actividadese.push(@ae) @obs= ObservacionTutor.where(informe_actividad_id: actade.id).take semestre = AdecuacionActividad.where(actividad_id: @act.id).take.semestre @semestres[@act.id]=semestre if @obs==nil @observaciont.push("") else @observaciont.push(@obs.observaciones) end if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) elsif tipo==7 @actividadesaobli.push(@act) end end else flash[:info]="Selecciona un informe" redirect_to controller: "inicioinstructor", action: "listar_informes" end end #listar todos los informes del instructor def listar_informes if session[:usuario_id] && session[:instructor] == true @nombre = session[:nombre_usuario] @planformacion = Planformacion.where(instructor_id: session[:usuario_id]).take @informes = Informe.where(planformacion_id: @planformacion).order(fecha_modificacion: :desc) @status = [] session[:informe_id] = nil @tipos= [] @informes.each do |inf| si = EstatusInforme.where(informe_id: inf.id, actual: 1).take #Status a mostrar segun el informe if(si.estatus_id==1) @st = "[" + si.fecha.to_s + "]: APROBADO POR CONSEJO DE FACULTAD" elsif(si.estatus_id==2) @st = "[" + si.fecha.to_s + "]: ENVIADO A CONSEJO Tร‰CNICO" elsif(si.estatus_id==3) @st = "[" + si.fecha.to_s + "]: ENVIADO A COMISION DE INVESTIGACIร“N" elsif(si.estatus_id==4) @st = "[" + si.fecha.to_s + "]: ENVIADO A CONSEJO DE FACULTAD" elsif(si.estatus_id==5) @st = "[" + si.fecha.to_s + "]: APROBADO CON OBSERVACIONES POR CONSEJO DE FACULTAD" elsif(si.estatus_id==6) @st = "GUARDADO" elsif(si.estatus_id==8) @st = "[" + si.fecha.to_s + "]: ENVIADO A CONSEJO DE ESCUELA" elsif(si.estatus_id==9) @st = "[" + si.fecha.to_s + "]: RECHAZADO POR CONSEJO DE FACULTAD" elsif(si.estatus_id==12) @st = "[" + si.fecha.to_s + "]: ENVIADO A CONSEJO Tร‰CNICO SIN REVISIร“N" elsif(si.estatus_id==13) @st = "[" + si.fecha.to_s + "]: ENVIADO A COMISIร“N DE INVESTIGACIร“N SIN REVISIร“N" elsif(si.estatus_id==14) @st = "[" + si.fecha.to_s + "]: ENVIADO A CONSEJO DE FACULTAD SIN REVISIร“N" elsif(si.estatus_id==18) @st = "[" + si.fecha.to_s + "]: ENVIADO A CONSEJO DE ESCUELA SIN REVISIร“N" end #Tipo de los informes @status.push(@st) if inf.tipo_id == 1 @tipos.push('Semestral') else if inf.tipo_id ==2 @tipos.push('Anual') else if inf.tipo_id==3 @tipos.push('Final') end end end end #si intenta ingresar con el link else redirect_to controller:"forminst", action: "index" end end def logout reset_session redirect_to controller: "forminst", action: "index" end def ver_detalles_adecuacion if session[:usuario_id] && session[:instructor] == true @plan_formacion = Planformacion.where(instructor_id: session[:usuario_id]).take @adecuacion = Adecuacion.where(planformacion_id: @plan_formacion).take @status_adecuacion = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take @tipo_status = TipoEstatus.where(id: @status_adecuacion.estatus_id, ).take.concepto @nombre = session[:nombre_usuario] @instructorName = session[:nombre_usuario] @modifique=false session[:informe_id] = nil @cant_delete= params[:cant_delete] @cant_edit= params[:cant_edit] @cant_doc= params[:cant_docencia] @cant_inv= params[:cant_investigacion] @cant_for= params[:cant_formacion] @cant_ext= params[:cant_extension] @cant_otr= params[:cant_otra] semestre= params[:semestre].to_i #if params[:adecuacion_id]!=nil session[:adecuacion_id]= @adecuacion.id #end @tutoresAnteriores = Instructortutor.where(instructor_id: session[:usuario_id], actual: 0) @adecuacion= Adecuacion.find(session[:adecuacion_id]) @plan = Planformacion.where(instructor_id: session[:usuario_id]).take @userentidad= Usuarioentidad.where(usuario_id: session[:usuario_id]).take @entidad= Entidad.find(@userentidad.entidad_id) @escuela= Escuela.where(id: @userentidad.escuela_id).take @tutor = Persona.where(usuario_id: @adecuacion.tutor_id).take @usuario = Usuario.where(id: session[:usuario_id]).take @persona = Persona.where(usuario_id: session[:usuario_id]).take @cpTutor= Persona.where(usuario_id: @plan.tutor_id).take @cpTutorEmail= Usuario.find(@plan.tutor_id).email @instructor= Persona.where(usuario_id: session[:usuario_id]).take @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] if @cant_edit.to_i > 0 @modifique= true j=0 i=:edit.to_s+j.to_s @edit= params[i].to_i while j < @cant_edit.to_i @act= Actividad.find(@edit) tipo= @act.tipo_actividad_id if tipo==1 m=:[email protected]_s text= params[m] else if tipo==2 m=:[email protected]_s text= params[m] else if tipo==3 m=:[email protected]_s text= params[m] else if tipo==4 m=:[email protected]_s text= params[m] else if tipo==5 m=:[email protected]_s text= params[m] end end end end end @act.actividad= text @act.save j= j+1 i=:edit.to_s+j.to_s @edit= params[i].to_i end end if @cant_delete.to_i > 0 @modifique= true j= 0 i=:delete.to_s+j.to_s; @delete = params[i].to_i while j < @cant_delete.to_i AdecuacionActividad.where(actividad_id: @delete).destroy_all Actividad.find(@delete).destroy j = j + 1 i=:delete.to_s+j.to_s; @delete = params[i] end end j=0 i=:nuevadoc.to_s+j.to_s @docencias = params[i] while j < @cant_doc.to_i @modifique= true if @docencias!=nil && @docencias!="" a = Actividad.new a.tipo_actividad_id = 1 a.actividad = @docencias a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion.id adac.actividad_id = a.id adac.semestre = semestre adac.save end j = j + 1 i=:nuevadoc.to_s+j.to_s; @docencias = params[i] end j=0 i=:nuevainv.to_s+j.to_s @invest = params[i] while j < @cant_inv.to_i @modifique= true if @invest!=nil && @invest!="" a = Actividad.new a.tipo_actividad_id = 2 a.actividad = @invest a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion.id adac.actividad_id = a.id adac.semestre = semestre adac.save end j = j + 1 i=:nuevainv.to_s+j.to_s; @invest = params[i] end j=0 i=:nuevafor.to_s+j.to_s @formacion = params[i] while j < @cant_for.to_i @modifique= true if @formacion!=nil && @formacion!="" a = Actividad.new a.tipo_actividad_id = 4 a.actividad = @formacion a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion.id adac.actividad_id = a.id adac.semestre = semestre adac.save end j = j + 1 i=:nuevafor.to_s+j.to_s; @formacion = params[i] end j=0 i=:nuevaext.to_s+j.to_s @extension = params[i] while j < @cant_ext.to_i @modifique= true if @extension!=nil && @extension!="" a = Actividad.new a.tipo_actividad_id = 3 a.actividad = @extension a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion.id adac.actividad_id = a.id adac.semestre = semestre adac.save end j = j + 1 i=:nuevaext.to_s+j.to_s; @extension = params[i] end j=0 i=:nuevaotr.to_s+j.to_s @otra = params[i] while j < @cant_otr.to_i @modifique= true if @otra!=nil && @otra!="" a = Actividad.new a.tipo_actividad_id = 5 a.actividad = @otra a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion.id adac.actividad_id = a.id adac.semestre = semestre adac.save end j = j + 1 i=:nuevaotr.to_s+j.to_s; @otra = params[i] end if @modifique == true flash[:mensaje]= "La adecuaciรณn fue modificada y guardada correctamente" redirect_to controller:"iniciotutor", action: "detalles_adecuacion3" end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion2 if session[:usuario_id] && session[:instructor] if params[:plan_id] @planformacion = Planformacion.find(params[:plan_id]) session[:plan_id] = @planformacion.id @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take session[:adecuacion_id]= @adecuacion.id else @planformacion = Planformacion.find(session[:plan_id]) end if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@planformacion.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take if params[:editar] == 'no' session[:editar]= false end @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if !session[:editar] && (@est.estatus_id == 6 || @est.estatus_id == 5) flash.now[:info]= "Para editar la Adecuaciรณn debe seleccionar Modificar Adecuaciรณn" end @adecuaciones = Adecuacion.where(planformacion_id: session[:plan_id]) @iddoc= 'id_docencia' @docencia='docencia' @desc='descripcion' @pres='presentacion' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @plan= Planformacion.find(session[:plan_id]) @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observacionesExtras= [] @j=0 @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) else if tipo==2 @actividadesainv.push(@act) else if tipo==3 @actividadesaext.push(@act) else if tipo==4 @actividadesafor.push(@act) else if tipo==5 @actividadesaotr.push(@act) elsif tipo==8 @[email protected] @[email protected] elsif tipo==9 @[email protected] @[email protected] end end end end end end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0).all @actividadesa.each do |actade| @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @observacionesExtras[actade.id]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras[actade.id]="no" else @observacionesExtras[actade.id]="si" end end end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion3 if session[:usuario_id] && session[:instructor] == true session[:informe_id] = nil @iddoc= 'id_docencia' @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @adecuacion= Adecuacion.find(session[:adecuacion_id]) @plan = Planformacion.where(instructor_id: session[:usuario_id]).take @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observacionesExtras= [] @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) else if tipo==2 @actividadesainv.push(@act) else if tipo==3 @actividadesaext.push(@act) else if tipo==4 @actividadesafor.push(@act) else if tipo==5 @actividadesaotr.push(@act) end end end end end end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividadesa.each do |actade| @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @observacionesExtras[actade.id]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras[actade.id]="no" else @observacionesExtras[actade.id]="si" end end end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion4 if session[:usuario_id] && session[:instructor] == true @iddoc= 'id_docencia' session[:informe_id] = nil @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @adecuacion= Adecuacion.find(session[:adecuacion_id]) @plan = Planformacion.where(instructor_id: session[:usuario_id]).take @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observacionesExtras= [] @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) else if tipo==2 @actividadesainv.push(@act) else if tipo==3 @actividadesaext.push(@act) else if tipo==4 @actividadesafor.push(@act) else if tipo==5 @actividadesaotr.push(@act) end end end end end end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @actividadesa.each do |actade| @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @observacionesExtras[actade.id]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras[actade.id]="no" else @observacionesExtras[actade.id]="si" end end end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion5 if session[:usuario_id] && session[:instructor] == true session[:informe_id] = nil @iddoc= 'id_docencia' @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @adecuacion= Adecuacion.find(session[:adecuacion_id]) @plan = Planformacion.where(instructor_id: session[:usuario_id]).take @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observacionesExtras= [] @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) else if tipo==2 @actividadesainv.push(@act) else if tipo==3 @actividadesaext.push(@act) else if tipo==4 @actividadesafor.push(@act) else if tipo==5 @actividadesaotr.push(@act) end end end end end end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all @actividadesa.each do |actade| @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @observacionesExtras[actade.id]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras[actade.id]="no" else @observacionesExtras[actade.id]="si" end end end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion6 if session[:usuario_id] && session[:instructor] == true session[:informe_id] = nil @iddoc= 'id_docencia' @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @adecuacion= Adecuacion.find(session[:adecuacion_id]) @plan = Planformacion.where(instructor_id: session[:usuario_id]).take @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observacionesExtras= [] @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) else if tipo==2 @actividadesainv.push(@act) else if tipo==3 @actividadesaext.push(@act) else if tipo==4 @actividadesafor.push(@act) else if tipo==5 @actividadesaotr.push(@act) end end end end end end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all @actividadesa.each do |actade| @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @observacionesExtras[actade.id]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras[actade.id]="no" else @observacionesExtras[actade.id]="si" end end end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion7 if session[:usuario_id] && session[:instructor] == true session[:informe_id] = nil @iddoc= 'id_docencia' @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @adecuacion= Adecuacion.find(session[:adecuacion_id]) @plan = Planformacion.where(instructor_id: session[:usuario_id]).take @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observacionesExtras= [] @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 5).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) else if tipo==2 @actividadesainv.push(@act) else if tipo==3 @actividadesaext.push(@act) else if tipo==4 @actividadesafor.push(@act) else if tipo==5 @actividadesaotr.push(@act) end end end end end end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 5).all @actividadesa.each do |actade| @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @observacionesExtras[actade.id]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras[actade.id]="no" else @observacionesExtras[actade.id]="si" end end end else redirect_to controller:"forminst", action: "index" end end def vista_previa @fechaActual = Date.current.to_s session[:informe_id] = nil @plan= Planformacion.where(instructor_id: session[:usuario_id]).take @usere= Usuarioentidad.where(usuario_id: @plan.instructor_id).take @fechaConcurso = @plan.fecha_inicio @escuela= Escuela.find(@usere.escuela_id) @adecuacion= Adecuacion.where(planformacion_id: @plan.id).take @adscripcion_docencia= @plan.adscripcion_docencia @adscripcion_investigacion= @plan.adscripcion_investigacion @persona= Persona.where(usuario_id: @plan.instructor_id).take @cpinstruccion = @persona.grado_instruccion @user = Usuario.find(@plan.instructor_id) @cpTutor= Persona.where(usuario_id: @plan.tutor_id).take @cpTutorEmail= Usuario.find(@plan.tutor_id).email @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @obligatoria= 'obligatoria' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] actividades = AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0) if !actividades.blank? actividades.each do |actividadAde| actividad = Actividad.find(actividadAde.actividad_id) if actividad.tipo_actividad_id == 9 @presentacion = actividad.actividad elsif actividad.tipo_actividad_id == 8 @descripcion = actividad.actividad end end else @presentacion = " " @descripcion = " " end @actividades0doc= [] @actividades0inv= [] @actividades0ext= [] @actividades0for= [] @actividades0otr= [] @actividades0= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0).all @actividades0.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades0doc.push(@act) elsif tipo==2 @actividades0inv.push(@act) elsif tipo==3 @actividades0ext.push(@act) elsif tipo==4 @actividades0for.push(@act) elsif tipo==5 @actividades0otr.push(@act) end end @actividades1doc= [] @actividades1inv= [] @actividades1ext= [] @actividades1for= [] @actividades1otr= [] @actividades1= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividades1.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades1doc.push(@act) else if tipo==2 @actividades1inv.push(@act) else if tipo==3 @actividades1ext.push(@act) else if tipo==4 @actividades1for.push(@act) else if tipo==5 @actividades1otr.push(@act) end end end end end end @actividades2doc= [] @actividades2inv= [] @actividades2ext= [] @actividades2for= [] @actividades2otr= [] @actividades2= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @actividades2.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades2doc.push(@act) else if tipo==2 @actividades2inv.push(@act) else if tipo==3 @actividades2ext.push(@act) else if tipo==4 @actividades2for.push(@act) else if tipo==5 @actividades2otr.push(@act) end end end end end end @actividades3doc= [] @actividades3inv= [] @actividades3ext= [] @actividades3for= [] @actividades3otr= [] @actividades3= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all @actividades3.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades3doc.push(@act) else if tipo==2 @actividades3inv.push(@act) else if tipo==3 @actividades3ext.push(@act) else if tipo==4 @actividades3for.push(@act) else if tipo==5 @actividades3otr.push(@act) end end end end end end @actividades4doc= [] @actividades4inv= [] @actividades4ext= [] @actividades4for= [] @actividades4otr= [] @actividades4= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all @actividades4.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades4doc.push(@act) else if tipo==2 @actividades4inv.push(@act) else if tipo==3 @actividades4ext.push(@act) else if tipo==4 @actividades4for.push(@act) else if tipo==5 @actividades4otr.push(@act) end end end end end end @actividades5doc= [] @actividades5inv= [] @actividades5ext= [] @actividades5for= [] @actividades5otr= [] @actividades5= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 5).all @actividades5.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades5doc.push(@act) else if tipo==2 @actividades5inv.push(@act) else if tipo==3 @actividades5ext.push(@act) else if tipo==4 @actividades5for.push(@act) end end end end end end def ver_detalles_informe if session[:usuario_id] && session[:instructor] == true @nombre = session[:nombre_usuario] if not @nombre print "NO HAY USUARIO" end @persona = Persona.where(usuario_id: session[:usuario_id]).take if session[:plan_id] @planformacion = Planformacion.where(instructor_id: session[:usuario_id]).take else @planformacion = Planformacion.where(instructor_id: session[:usuario_id]).take session[:plan_id] = @planformacion.id end if params[:informe_id]!=nil session[:informe_id]= params[:informe_id] end if !session[:informe_id].blank? @tutor = Persona.where(usuario_id: @planformacion.tutor_id).take @instructor = Persona.where(usuario_id: @planformacion.instructor_id).take if session[:informe_id] == nil session[:informe_id] = params[:informe_id] @informe= Informe.find(session[:informe_id]) else @informe = Informe.find(session[:informe_id]) end @periodo = @informe.fecha_inicio.to_s + " al " + @informe.fecha_fin.to_s if @informe.numero == 1 @nombre_informe= "<NAME> " session[:numero_informe]=1 else if @informe.numero == 2 @nombre_informe= "<NAME> " session[:numero_informe]=2 else if @informe.numero == 3 @nombre_informe= "<NAME> " session[:numero_informe]=3 else @nombre_informe= "<NAME> " session[:numero_informe]=4 end end end if @informe.tipo_id == 1 @nombre_informe= @nombre_informe+"SEMESTRAL" else if @informe.tipo_id == 2 @nombre_informe= @nombre_informe+"ANUAL" else @nombre_informe= @nombre_informe+"FINAL" end end @estatus= EstatusInforme.where(informe_id: @informe.id).take @status= TipoEstatus.find(@estatus.estatus_id) @userentidad= Usuarioentidad.where(usuario_id: @planformacion.instructor_id).take @entidad= Entidad.find(@userentidad.entidad_id) @escuela= Escuela.find(@userentidad.escuela_id) session[:nombre_informe] = @nombre_informe session[:status_informe] = @status.concepto else flash[:info]="Selecciona un informe" redirect_to controller: "inicioinstructor", action: "listar_informes" end else redirect_to controller:"forminst", action: "index" end end def detalles_informe2 if !session[:informe_id].blank? @nombre = session[:nombre_usuario] @CJagregado = ["no","no","no","no"] if not @nombre print "NO HAY USUARIO" end @informe= Informe.find(session[:informe_id]) @est= EstatusInforme.where(informe_id: @informe.id).take @modificar= false if @est.estatus_id == 6 @modificar=true end @docencia= "docencia" @j= 0 @k=0 @actividadesa= InformeActividad.where(informe_id: @informe.id).all @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaobli= [] @actividadesaotr= [] @resultados= [] @semestres=[] @CJagregado=["no","no","no","no"] @resultados2= "" @resultados2a= [] @resultados2b= [] @actividadese= [] @observaciont= [] @actividadesa.each do |actade| if actade.actividad_id == nil #Es el caso que es un resultado no contemplado en el plan de formacion o un avancwe de postgrado if @resultados2b != [] @resultados2b= Array.new(0) { |i| } end @res= Resultado.where(informe_actividad_id: actade.id).all @resultados.push(@res) @res.each do |cpresultado| @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = cpresultado.titulo @cparray[1] = cpresultado.autor @cparray[2] = cpresultado.nombre_capitulo @cparray[3] = cpresultado.autor_capitulo @cparray[4] = cpresultado.dia @cparray[5] = cpresultado.mes @cparray[6] = cpresultado.ano @cparray[7] = cpresultado.ciudad @cparray[8] = cpresultado.estado @cparray[9] = cpresultado.pais @cparray[10] = cpresultado.organizador @cparray[11] = cpresultado.duracion @cparray[12] = cpresultado.editor @cparray[13] = cpresultado.titulo_libro @cparray[14] = cpresultado.autor_libro @cparray[15] = cpresultado.nombre_revista @cparray[16] = cpresultado.nombre_periodico @cparray[17] = cpresultado.nombre_acto @cparray[18] = cpresultado.paginas @cparray[19] = cpresultado.nombre_paginaw @cparray[20] = cpresultado.sitio_paginaw @cparray[21] = cpresultado.infoafiliaion @cparray[22] = cpresultado.cptipo @cparray[23] = cpresultado.nombre @cparray[24] = cpresultado.ISSN_impreso @cparray[25] = cpresultado.ISSN_electro @cparray[26] = cpresultado.volumen @cparray[27] = cpresultado.edicion @cparray[28] = cpresultado.DOI @cparray[29] = cpresultado.ISBN @cparray[30] = cpresultado.universidad @cparray[31] = cpresultado.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @noemptyarray.join(',') end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @noemptyarray.join(',') end end @resultados2b.push(@resultados2) end end @resultados2a.push(@resultados2b) else @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if @resultados2b != [] @resultados2b= Array.new(0) { |i| } end @res= Resultado.where(informe_actividad_id: actade.id).all @resultados.push(@res) @res.each do |cpresultado| @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = cpresultado.titulo @cparray[1] = cpresultado.autor @cparray[2] = cpresultado.nombre_capitulo @cparray[3] = cpresultado.autor_capitulo @cparray[4] = cpresultado.dia @cparray[5] = cpresultado.mes @cparray[6] = cpresultado.ano @cparray[7] = cpresultado.ciudad @cparray[8] = cpresultado.estado @cparray[9] = cpresultado.pais @cparray[10] = cpresultado.organizador @cparray[11] = cpresultado.duracion @cparray[12] = cpresultado.editor @cparray[13] = cpresultado.titulo_libro @cparray[14] = cpresultado.autor_libro @cparray[15] = cpresultado.nombre_revista @cparray[16] = cpresultado.nombre_periodico @cparray[17] = cpresultado.nombre_acto @cparray[18] = cpresultado.paginas @cparray[19] = cpresultado.nombre_paginaw @cparray[20] = cpresultado.sitio_paginaw @cparray[21] = cpresultado.infoafiliaion @cparray[22] = cpresultado.cptipo @cparray[23] = cpresultado.nombre @cparray[24] = cpresultado.ISSN_impreso @cparray[25] = cpresultado.ISSN_electro @cparray[26] = cpresultado.volumen @cparray[27] = cpresultado.edicion @cparray[28] = cpresultado.DOI @cparray[29] = cpresultado.ISBN @cparray[30] = cpresultado.universidad @cparray[31] = cpresultado.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @noemptyarray.join(',') end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @noemptyarray.join(',') end end @resultados2b.push(@resultados2) end end @resultados2a.push(@resultados2b) @ae= ActividadEjecutada.where(informe_actividad_id: actade.id).take @actividadese.push(@ae) @obs= ObservacionTutor.where(informe_actividad_id: actade.id).take if @obs==nil @observaciont.push("") else @observaciont.push(@obs.observaciones) end semestre = AdecuacionActividad.where(actividad_id: @act.id).take.semestre @semestres[@<EMAIL>]=semestre if tipo==1 @actividadesadoc.push(@act) else if tipo==2 @actividadesainv.push(@act) else if tipo==3 @actividadesaext.push(@act) else if tipo==4 @actividadesafor.push(@act) else if tipo==5 @actividadesaotr.push(@act) elsif tipo==7 @actividadesaobli.push(@act) end end end end end end end else flash[:info]="Selecciona un informe" redirect_to controller: "inicioinstructor", action: "listar_informes" end end def borrar_notificaciones #mas obs de actividades del informe if session[:usuario_id] && session[:instructor] == true @noti= params[:noti] notaeliminar = Notificacion.where(id: @noti ).take if notaeliminar.blank? flash[:danger] = "Ha ocurrido un error al eliminar (notificacion no existente)" else notaeliminar.destroy end redirect_to controller:"inicioinstructor", action: "index" else redirect_to controller:"forminst", action: "index" end end def mas_observaciones3 #mas obs de actividades del informe @adecuacion= Adecuacion.find(session[:adecuacion_id]) @planformacion=Planformacion.find(@adecuacion.planformacion_id) if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@planformacion.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end if ( params[:informe_id].blank?) @semestre = params[:semestre].to_i @actividad_id = params[:actividad_id].to_i puts @adecuacion.id puts @semestre puts @actividad_id aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: @semestre, actividad_id: @actividad_id).take @observaciones = ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa.id) @observaciones.each do |obs| if(obs.observaciones != "") @boolobs = 1 end end @observaciones.each do |obs| rev = Revision.find(obs.revision_id) entidad = Usuarioentidad.where(usuario_id: rev.usuario_id).take if (entidad.entidad_id >= 7 && entidad.entidad_id <= 12) #comision investigacion @obs_inv = obs.observaciones #Estatus enviado a comision de investigacion else if (entidad.entidad_id >= 14 && entidad.entidad_id <= 17) #Consejo tecnico @obs_consejoT = obs.observaciones else if (entidad.entidad_id >= 1 && entidad.entidad_id <= 6) #Consejo de escuela @obs_consejoE = obs.observaciones else if (entidad.entidad_id == 13) #Consejo de facultad @obs_consejoF = obs.observaciones end end end end end else @informe_id = params[:informe_id].to_i @actividad_id = params[:actividad_id].to_i aa= InformeActividad.where(informe_id: @informe_id, actividad_id: @actividad_id).take @observaciones = ObservacionActividadInforme.where(informe_actividad_id: aa.id) @observaciones.each do |obs| if(obs.observaciones != "") @boolobs = 1 end end @observaciones.each do |obs| rev = Revision.find(obs.revision_id) entidad = Usuarioentidad.where(usuario_id: rev.usuario_id).take if (entidad.entidad_id >= 7 && entidad.entidad_id <= 12) #comision investigacion @obs_inv = obs.observaciones #Estatus enviado a comision de investigacion else if (entidad.entidad_id >= 14 && entidad.entidad_id <= 17) #Consejo tecnico @obs_consejoT = obs.observaciones else if (entidad.entidad_id >= 1 && entidad.entidad_id <= 6) #Consejo de escuela @obs_consejoE = obs.observaciones else if (entidad.entidad_id == 13) #Consejo de facultad @obs_consejoF = obs.observaciones end end end end end end end end <file_sep>/forminst_new1/app/models/observacion_tutor.rb class ObservacionTutor < ActiveRecord::Base belongs_to :informe_actividad end <file_sep>/forminst_new1/app/models/actividad.rb class Actividad < ActiveRecord::Base has_many :informe_actividad has_many :adecuacion_actividad belongs_to :tipo_actividad has_one :resultado end<file_sep>/forminst_new1/test/controllers/tipoactividads_controller_test.rb require 'test_helper' class TipoactividadsControllerTest < ActionController::TestCase setup do @tipoactividad = tipoactividads(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:tipoactividads) end test "should get new" do get :new assert_response :success end test "should create tipoactividad" do assert_difference('Tipoactividad.count') do post :create, tipoactividad: { concepto: @tipoactividad.concepto, grupoActividadesId: @tipoactividad.grupoActividadesId, id: @tipoactividad.id, subGrupoActividadId: @tipoactividad.subGrupoActividadId } end assert_redirected_to tipoactividad_path(assigns(:tipoactividad)) end test "should show tipoactividad" do get :show, id: @tipoactividad assert_response :success end test "should get edit" do get :edit, id: @tipoactividad assert_response :success end test "should update tipoactividad" do patch :update, id: @tipoactividad, tipoactividad: { concepto: @tipoactividad.concepto, grupoActividadesId: @tipoactividad.grupoActividadesId, id: @tipoactividad.id, subGrupoActividadId: @tipoactividad.subGrupoActividadId } assert_redirected_to tipoactividad_path(assigns(:tipoactividad)) end test "should destroy tipoactividad" do assert_difference('Tipoactividad.count', -1) do delete :destroy, id: @tipoactividad end assert_redirected_to tipoactividads_path end end <file_sep>/forminst_new1/app/controllers/actividadejecutadas_controller.rb class ActividadejecutadasController < ApplicationController before_action :set_actividadejecutada, only: [:show, :edit, :update, :destroy] # GET /actividadejecutadas # GET /actividadejecutadas.json def index @actividadejecutadas = Actividadejecutada.all end # GET /actividadejecutadas/1 # GET /actividadejecutadas/1.json def show end # GET /actividadejecutadas/new def new @actividadejecutada = Actividadejecutada.new end # GET /actividadejecutadas/1/edit def edit end # POST /actividadejecutadas # POST /actividadejecutadas.json def create @actividadejecutada = Actividadejecutada.new(actividadejecutada_params) respond_to do |format| if @actividadejecutada.save format.html { redirect_to @actividadejecutada, notice: 'Actividadejecutada was successfully created.' } format.json { render :show, status: :created, location: @actividadejecutada } else format.html { render :new } format.json { render json: @actividadejecutada.errors, status: :unprocessable_entity } end end end # PATCH/PUT /actividadejecutadas/1 # PATCH/PUT /actividadejecutadas/1.json def update respond_to do |format| if @actividadejecutada.update(actividadejecutada_params) format.html { redirect_to @actividadejecutada, notice: 'Actividadejecutada was successfully updated.' } format.json { render :show, status: :ok, location: @actividadejecutada } else format.html { render :edit } format.json { render json: @actividadejecutada.errors, status: :unprocessable_entity } end end end # DELETE /actividadejecutadas/1 # DELETE /actividadejecutadas/1.json def destroy @actividadejecutada.destroy respond_to do |format| format.html { redirect_to actividadejecutadas_url, notice: 'Actividadejecutada was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_actividadejecutada @actividadejecutada = Actividadejecutada.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def actividadejecutada_params params.require(:actividadejecutada).permit(:id, :descripcion, :fecha, :actual, :informeActividadId) end end <file_sep>/forminst_new1/app/controllers/planformacions_controller.rb class PlanformacionsController < ApplicationController layout 'ly_inicio_tutor' before_action :set_planformacion, only: [:show, :edit, :update, :destroy] # GET /planformacions # GET /planformacions.json def index @persona = Persona.where(usuarioId: session[:usuario_id]).take @planformacions = Planformacion.where(tutorId: session[:usuario_id]).take #@usuarios= Usuario.all #se quiere acceder a la informacion del usuario como el nombre, para agregarlo en la tabla pero aun no sabemos como #@personas= Persona.all end # GET /planformacions/1 # GET /planformacions/1.json def show end # GET /planformacions/new def new @planformacion = Planformacion.new end # GET /planformacions/1/edit def edit end # POST /planformacions # POST /planformacions.json def create @planformacion = Planformacion.new(planformacion_params) respond_to do |format| if @planformacion.save format.html { redirect_to @planformacion, notice: 'Planformacion was successfully created.' } format.json { render :show, status: :created, location: @planformacion } else format.html { render :new } format.json { render json: @planformacion.errors, status: :unprocessable_entity } end end end # PATCH/PUT /planformacions/1 # PATCH/PUT /planformacions/1.json def update respond_to do |format| if @planformacion.update(planformacion_params) format.html { redirect_to @planformacion, notice: 'Planformacion was successfully updated.' } format.json { render :show, status: :ok, location: @planformacion } else format.html { render :edit } format.json { render json: @planformacion.errors, status: :unprocessable_entity } end end end # DELETE /planformacions/1 # DELETE /planformacions/1.json def destroy @planformacion.destroy respond_to do |format| format.html { redirect_to planformacions_url, notice: 'Planformacion was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_planformacion @planformacion = Planformacion.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def planformacion_params params.require(:planformacion).permit(:id, :fechaInicio, :fechaFin, :activo, :instructorId, :tutorId) end end <file_sep>/forminst_new1/app/models/prorroga.rb class Prorroga < ActiveRecord::Base belongs_to :planformacion end<file_sep>/forminst_new1/test/controllers/actividadejecutadas_controller_test.rb require 'test_helper' class ActividadejecutadasControllerTest < ActionController::TestCase setup do @actividadejecutada = actividadejecutadas(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:actividadejecutadas) end test "should get new" do get :new assert_response :success end test "should create actividadejecutada" do assert_difference('Actividadejecutada.count') do post :create, actividadejecutada: { actual: @actividadejecutada.actual, descripcion: @actividadejecutada.descripcion, fecha: @actividadejecutada.fecha, id: @actividadejecutada.id, informeActividadId: @actividadejecutada.informeActividadId } end assert_redirected_to actividadejecutada_path(assigns(:actividadejecutada)) end test "should show actividadejecutada" do get :show, id: @actividadejecutada assert_response :success end test "should get edit" do get :edit, id: @actividadejecutada assert_response :success end test "should update actividadejecutada" do patch :update, id: @actividadejecutada, actividadejecutada: { actual: @actividadejecutada.actual, descripcion: @actividadejecutada.descripcion, fecha: @actividadejecutada.fecha, id: @actividadejecutada.id, informeActividadId: @actividadejecutada.informeActividadId } assert_redirected_to actividadejecutada_path(assigns(:actividadejecutada)) end test "should destroy actividadejecutada" do assert_difference('Actividadejecutada.count', -1) do delete :destroy, id: @actividadejecutada end assert_redirected_to actividadejecutadas_path end end <file_sep>/forminst_new1/test/controllers/permisologia_controller_test.rb require 'test_helper' class PermisologiaControllerTest < ActionController::TestCase setup do @permisologium = permisologia(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:permisologia) end test "should get new" do get :new assert_response :success end test "should create permisologium" do assert_difference('Permisologium.count') do post :create, permisologium: { attribute: @permisologium.attribute, id: @permisologium.id, permisosId: @permisologium.permisosId, read: @permisologium.read, usuarioId: @permisologium.usuarioId, write: @permisologium.write } end assert_redirected_to permisologium_path(assigns(:permisologium)) end test "should show permisologium" do get :show, id: @permisologium assert_response :success end test "should get edit" do get :edit, id: @permisologium assert_response :success end test "should update permisologium" do patch :update, id: @permisologium, permisologium: { attribute: @permisologium.attribute, id: @permisologium.id, permisosId: @permisologium.permisosId, read: @permisologium.read, usuarioId: @permisologium.usuarioId, write: @permisologium.write } assert_redirected_to permisologium_path(assigns(:permisologium)) end test "should destroy permisologium" do assert_difference('Permisologium.count', -1) do delete :destroy, id: @permisologium end assert_redirected_to permisologia_path end end <file_sep>/forminst_new1/app/views/documentos/index.json.jbuilder json.array!(@documentos) do |documento| json.extract! documento, :id, :id, :informeActividadId, :archivo json.url documento_url(documento, format: :json) end <file_sep>/forminst_new1/test/controllers/tiporesultados_controller_test.rb require 'test_helper' class TiporesultadosControllerTest < ActionController::TestCase setup do @tiporesultado = tiporesultados(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:tiporesultados) end test "should get new" do get :new assert_response :success end test "should create tiporesultado" do assert_difference('Tiporesultado.count') do post :create, tiporesultado: { concepto: @tiporesultado.concepto, id: @tiporesultado.id, idPadre: @tiporesultado.idPadre, tipoActividadId: @tiporesultado.tipoActividadId } end assert_redirected_to tiporesultado_path(assigns(:tiporesultado)) end test "should show tiporesultado" do get :show, id: @tiporesultado assert_response :success end test "should get edit" do get :edit, id: @tiporesultado assert_response :success end test "should update tiporesultado" do patch :update, id: @tiporesultado, tiporesultado: { concepto: @tiporesultado.concepto, id: @tiporesultado.id, idPadre: @tiporesultado.idPadre, tipoActividadId: @tiporesultado.tipoActividadId } assert_redirected_to tiporesultado_path(assigns(:tiporesultado)) end test "should destroy tiporesultado" do assert_difference('Tiporesultado.count', -1) do delete :destroy, id: @tiporesultado end assert_redirected_to tiporesultados_path end end <file_sep>/forminst_new1/test/controllers/planformacions_controller_test.rb require 'test_helper' class PlanformacionsControllerTest < ActionController::TestCase setup do @planformacion = planformacions(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:planformacions) end test "should get new" do get :new assert_response :success end test "should create planformacion" do assert_difference('Planformacion.count') do post :create, planformacion: { activo: @planformacion.activo, fechaFin: @planformacion.fechaFin, fechaInicio: @planformacion.fechaInicio, id: @planformacion.id, instructorId: @planformacion.instructorId, tutorId: @planformacion.tutorId } end assert_redirected_to planformacion_path(assigns(:planformacion)) end test "should show planformacion" do get :show, id: @planformacion assert_response :success end test "should get edit" do get :edit, id: @planformacion assert_response :success end test "should update planformacion" do patch :update, id: @planformacion, planformacion: { activo: @planformacion.activo, fechaFin: @planformacion.fechaFin, fechaInicio: @planformacion.fechaInicio, id: @planformacion.id, instructorId: @planformacion.instructorId, tutorId: @planformacion.tutorId } assert_redirected_to planformacion_path(assigns(:planformacion)) end test "should destroy planformacion" do assert_difference('Planformacion.count', -1) do delete :destroy, id: @planformacion end assert_redirected_to planformacions_path end end <file_sep>/forminst_new1/app/views/informes/index.json.jbuilder json.array!(@informes) do |informe| json.extract! informe, :id, :id, :PlanFormacionId, :tutorId, :opinionTutor, :conclusiones json.url informe_url(informe, format: :json) end <file_sep>/forminst_new1/test/controllers/estatusadecuacions_controller_test.rb require 'test_helper' class EstatusadecuacionsControllerTest < ActionController::TestCase setup do @estatusadecuacion = estatusadecuacions(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:estatusadecuacions) end test "should get new" do get :new assert_response :success end test "should create estatusadecuacion" do assert_difference('Estatusadecuacion.count') do post :create, estatusadecuacion: { actual: @estatusadecuacion.actual, adecuacionId: @estatusadecuacion.adecuacionId, estatusId: @estatusadecuacion.estatusId, fecha: @estatusadecuacion.fecha, id: @estatusadecuacion.id } end assert_redirected_to estatusadecuacion_path(assigns(:estatusadecuacion)) end test "should show estatusadecuacion" do get :show, id: @estatusadecuacion assert_response :success end test "should get edit" do get :edit, id: @estatusadecuacion assert_response :success end test "should update estatusadecuacion" do patch :update, id: @estatusadecuacion, estatusadecuacion: { actual: @estatusadecuacion.actual, adecuacionId: @estatusadecuacion.adecuacionId, estatusId: @estatusadecuacion.estatusId, fecha: @estatusadecuacion.fecha, id: @estatusadecuacion.id } assert_redirected_to estatusadecuacion_path(assigns(:estatusadecuacion)) end test "should destroy estatusadecuacion" do assert_difference('Estatusadecuacion.count', -1) do delete :destroy, id: @estatusadecuacion end assert_redirected_to estatusadecuacions_path end end <file_sep>/forminst_new1/bin/server #!/usr/bin/env ruby ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV'] || 'development' require File.expand_path(File.dirname(__FILE__) + "/../config/environment") require 'daemons' #Daemons.daemonize # Change the following to reflect your database settings ActiveRecord::Base.establish_connection( adapter: 'mysql2', # or 'postgresql' or 'sqlite3' or 'oracle_enhanced' host: 'localhost', database: 'FORMIST', username: 'root', password: '<PASSWORD>' ) while true puts "ejecutando..." #Aclualizar los estatus de las adecuaciones luego de haber pasado dos semana----------------------------------------------- estatus_adecuacion = EstatusAdecuacion.where(actual: 1).all fecha = Time.now.strftime("%Y-%m-%d") fecha2 = Time.now estatus_adecuacion.each do |status| if status.fecha + 3.week <= fecha2 @adecuacion_id = status.adecuacion_id.to_i if (status.estatus_id == 3 || status.estatus_id == 13) #Usuario comision status.actual = 0 status.save cambio_est = EstatusAdecuacion.new cambio_est.adecuacion_id = @adecuacion_id cambio_est.fecha = Time.now cambio_est.estatus_id = 18 cambio_est.actual = 1 cambio_est.save adac = AdecuacionActividad.where(adecuacion_id: @adecuacion_id).all adac.each do |adaa| oa = ObservacionActividadAdecuacion.where(adecuacionactividad_id: adaa.id, actual: 1).all oa.each do |oaa| oaa.fecha = Time.now oaa.actual = 0 oaa.save end end adecuacion = Adecuacion.find(@adecuacion_id) plan = Planformacion.find(adecuacion.planformacion_id) notific = Notificacion.new @document = Respaldo.where(adecuacion_id: @adecuacion_id, informe_id: nil, actual: 1).take @document.estatus = "Enviado a Consejo de Escuela" @document.save notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = @adecuacion_id notific.informe_id = nil notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] La adecuaciรณn de "+ person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " fue enviada a Consejo de Escuela sin ser revisado." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = @adecuacion_id notific2.informe_id = nil notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] Su adecuaciรณn fue enviada a Consejo de Escuela sin ser revisada" notific2.save notific3 = Notificacion.new notific3.instructor_id = plan.instructor_id notific3.tutor_id = plan.tutor_id notific3.adecuacion_id = @adecuacion_id notific3.informe_id = nil notific3.actual = 4 #Consejo de Escuela notific3.mensaje = "[" + notificacionfecha + "] Se ha recibido una nueva Adecuaciรณn: "+ person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + ", favor aprobar y enviar a la siguiente entidad." notific3.save user =Usuarioentidad.where(usuario_id: plan.instructor_id).take if(user.escuela_id == 1) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 1).take else if(user.escuela_id == 2) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 2).take else if(user.escuela_id == 3) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 3).take else if(user.escuela_id == 4) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 4).take else if(user.escuela_id == 9) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 5).take else if(user.escuela_id == 10) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 6).take end end end end end end linkT = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion&param1=" + plan.id.to_s + "&param2=no" linkI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion" linkE = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion&param3=" + @adecuacion_id.to_s remitente3 = Usuario.where(id: plan.tutor_id).take ActionCorreo.envio_adecuacion(remitente3, notific.mensaje,2,linkT,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_adecuacion(remitente2, notific2.mensaje,1,linkI,@document).deliver remitente = Usuario.where(id: uentidad.usuario_id).take ActionCorreo.envio_adecuacion(remitente, notific3.mensaje,0,linkE,@document).deliver elsif (status.estatus_id == 8 || status.estatus_id == 18) #Consejo de escuela adac = AdecuacionActividad.where(adecuacion_id: @adecuacion_id).all adac.each do |adaa| oa = ObservacionActividadAdecuacion.where(adecuacionactividad_id: adaa.id, actual: 1).all oa.each do |oaa| oaa.fecha = Time.now oaa.actual = 0 oaa.save end end @document = Respaldo.where(adecuacion_id: @adecuacion_id, informe_id: nil, actual: 1).take @document.estatus = "Enviado a Consejo de Facultad" @document.save cambio_act = EstatusAdecuacion.where(adecuacion_id: @adecuacion_id, actual: 1).take cambio_act.actual = 0 cambio_act.save cambio_est = EstatusAdecuacion.new cambio_est.adecuacion_id = @adecuacion_id cambio_est.fecha = Time.now cambio_est.estatus_id = 14 cambio_est.actual = 1 cambio_est.save adecuacion = Adecuacion.find(@adecuacion_id) plan= Planformacion.find(adecuacion.planformacion_id) notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = @adecuacion_id notific.informe_id = nil notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] La adecuaciรณn de "+ person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " fue enviada a Consejo de Facultad sin ser revisado." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = @adecuacion_id notific2.informe_id = nil notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] Su adecuaciรณn fue enviada a Consejo de Facultad sin ser revisado" notific2.save notific3 = Notificacion.new notific3.instructor_id = plan.instructor_id notific3.tutor_id = plan.tutor_id notific3.adecuacion_id = @adecuacion_id notific3.informe_id = nil notific3.actual = 5 #Consejo de Escuela notific3.mensaje = "[" + notificacionfecha + "] Se ha recibido una nueva Adecuaciรณn: "+ person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + ", Revisar." notific3.save uentidad = Usuarioentidad.where(entidad_id: 13).take linkT = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion&param1=" + plan.id.to_s + "&param2=no" linkI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion" linkE = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion&param3=" + @adecuacion_id.to_s remitente3 = Usuario.where(id: plan.tutor_id).take ActionCorreo.envio_adecuacion(remitente3, notific.mensaje,2,linkT,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_adecuacion(remitente2, notific2.mensaje,1,linkI,@document).deliver remitente = Usuario.where(id: uentidad.usuario_id).take ActionCorreo.envio_adecuacion(remitente, notific3.mensaje,0,linkE,@document).deliver ActionCorreo.envio_adecuacion("<EMAIL>", notific3.mensaje,0, linkE,@document).deliver end end end #FIN clualizar los estatus de las adecuaciones luego de haber pasado dos semana--------------------------------------------- #Aclualizar los estatus de los informes luego de haber pasado dos semana----------------------------------------------- estatus_informes = EstatusInforme.where(actual: 1).all fecha = Time.now.strftime("%Y-%m-%d") fecha2 = Time.now estatus_informes.each do |status| if status.fecha + 3.week <= fecha2 @informe_id = status.informe_id.to_i informeAct = Informe.where(id: @informe_id).take plan_id = informeAct.planformacion_id adec = Adecuacion.where(planformacion_id: informeAct.planformacion_id).take adecuacion_id = adec.id if (status.estatus_id == 3 || status.estatus_id == 13) #Comision de investigacion @document = Respaldo.where(adecuacion_id: adecuacion_id, informe_id: @informe_id, actual: 1).take @document.estatus = "Enviado a Consejo de Escuela" @document.save cambio_act = EstatusInforme.where(informe_id: @informe_id, actual: 1).take cambio_act.actual = 0 cambio_act.save cambio_est = EstatusInforme.new cambio_est.informe_id = @informe_id cambio_est.fecha = Time.now cambio_est.estatus_id = 18 cambio_est.actual = 1 cambio_est.save plan = Planformacion.find(plan_id) cambio_est.fecha = Time.now if (informeAct.numero == 1 || informeAct.numero == 3) nombre_informe= "<NAME> " elsif (informeAct.numero == 2 || informeAct.numero == 6) nombre_informe= "<NAME> " elsif informeAct.numero == 4 nombre_informe= "<NAME> " elsif informeAct.numero == 5 nombre_informe= "<NAME> " end if informeAct.tipo_id == 1 nombre_informe= nombre_informe+"SEMESTRAL" elsif informeAct.tipo_id == 2 nombre_informe= nombre_informe+"ANUAL" else nombre_informe= "INFORME "+"FINAL" end notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = informeAct.tutor_id notific.adecuacion_id = adecuacion_id notific.informe_id = @informe_id notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] El " + nombre_informe + " de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha sido aprobado por Comisiรณn de Investigaciรณn y fue enviada a Consejo de Escuela." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = informeAct.tutor_id notific2.adecuacion_id = adecuacion_id notific2.informe_id = @informe_id notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] El " + nombre_informe + " ha sido aprobado por Comisiรณn de Investigaciรณn y fue enviada a Consejo de Escuela." notific2.save notific3 = Notificacion.new notific3.instructor_id = plan.instructor_id notific3.tutor_id = informeAct.tutor_id notific3.adecuacion_id = adecuacion_id notific3.informe_id = @informe_id notific3.actual = 4 #Consejo de Escuela notific3.mensaje = "[" + notificacionfecha + "] Ha recibido un nuevo Informe: ' " + nombre_informe + " ' de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + ", favor aprobar y enviar a la siguiente entidad." notific3.save user =Usuarioentidad.where(usuario_id: plan.instructor_id).take if(user.escuela_id == 1) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 1).take elsif(user.escuela_id == 2) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 2).take elsif(user.escuela_id == 3) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 3).take elsif(user.escuela_id == 4) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 4).take elsif(user.escuela_id == 9) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 5).take elsif(user.escuela_id == 10) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 6).take end linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe&param1=" + plan.id.to_s + "&param2="+ @informe_id.to_s linkE = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe&param1=" + plan.id.to_s+ "&param2="+@informe_id.to_s+"&param3="+adec.id.to_s remitente3 = Usuario.where(id: informeAct.tutor_id).take ActionCorreo.envio_informe(remitente3, notific.mensaje,2,linkTeI,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_informe(remitente2, notific2.mensaje,1,linkTeI,@document).deliver remitente = Usuario.where(id: uentidad.usuario_id).take ActionCorreo.envio_informe(remitente, notific3.mensaje,0,linkE,@document).deliver elsif (status.estatus_id == 8 || status.estatus_id == 18) #Consejo de escuela @document = Respaldo.where(adecuacion_id: adecuacion_id, informe_id: @informe_id, actual: 1).take @document.estatus = "Enviado a Consejo de Facultad" @document.save cambio_act = EstatusInforme.where(informe_id: @informe_id, actual: 1).take cambio_act.actual = 0 cambio_act.save cambio_est = EstatusInforme.new cambio_est.informe_id = @informe_id cambio_est.fecha = Time.now cambio_est.estatus_id = 14 cambio_est.actual = 1 cambio_est.save plan = Planformacion.find(plan_id) cambio_est.fecha = Time.now if (informeAct.numero == 1 || informeAct.numero == 3) nombre_informe= "<NAME> " elsif (informeAct.numero == 2 || informeAct.numero == 6) nombre_informe= "<NAME> " elsif informeAct.numero == 4 nombre_informe= "<NAME> " elsif informeAct.numero == 5 nombre_informe= "CUARTO INFORME " end if informeAct.tipo_id == 1 nombre_informe= nombre_informe+"SEMESTRAL" elsif informeAct.tipo_id == 2 nombre_informe= nombre_informe+"ANUAL" else nombre_informe= "INFORME "+"FINAL" end notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = informeAct.tutor_id notific.adecuacion_id = adecuacion_id notific.informe_id = @informe_id notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] El " + nombre_informe + " de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha sido aprobado por Consejo de Escuela y fue enviada a Consejo de Facultad." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = informeAct.tutor_id notific2.adecuacion_id = adecuacion_id notific2.informe_id = @informe_id notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] El " + nombre_informe + " ha sido aprobado por Consejo de Escuela y fue enviada a Consejo de Facultad." notific2.save notific3 = Notificacion.new notific3.instructor_id = plan.instructor_id notific3.tutor_id = informeAct.tutor_id notific3.adecuacion_id = adecuacion_id notific3.informe_id = @informe_id notific3.actual = 5 #Consejo de Facultad notific3.mensaje = "[" + notificacionfecha + "] Ha recibido un nuevo Informe: ' " + nombre_informe + " ' de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + ", revisar." notific3.save uentidad = Usuarioentidad.where(entidad_id: 13).take remitente3 = Usuario.where(id: informeAct.tutor_id).take linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe&param1=" + plan.id.to_s + "&param2="+ @informe_id.to_s linkE = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe&param1=" + plan.id.to_s+ "&param2="+@informe_id.to_s+"&param3="+adec.id.to_s ActionCorreo.envio_informe(remitente3, notific.mensaje,2,linkTeI,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_informe(remitente2, notific2.mensaje,1,linkTeI,@document).deliver remitente = Usuario.where(id: uentidad.usuario_id).take ActionCorreo.envio_informe(remitente, notific3.mensaje,0,linkE,@document).deliver ActionCorreo.envio_informe("<EMAIL>", notific3.mensaje,0, linkE,@document).deliver end end end #FIN aclualizar los estatus de los informes luego de haber pasado dos semana-------------------------------------------- #Enviar correo de notificacion de informes------------------------------------------------------------------------------ planFormacion = Planformacion.all fecha = Time.now.strftime("%Y-%m-%d") fecha2 = Time.now puts "inicio" planFormacion.each do |plan| puts plan.fecha_inicio + 5.month puts fecha2 puts plan.fecha_inicio + 11.month puts plan.fecha_inicio + 5.month <= fecha2 puts plan.fecha_inicio + 11.month >= fecha2 puts plan.mensaje puts plan.mensaje.blank? if plan.fecha_inicio + 5.month <= fecha2 && plan.fecha_inicio + 6.month >= fecha2 && plan.mensaje.blank? puts "entro!" puts plan.fecha_inicio adecuacion = Adecuacion.where(planformacion_id: plan.id).take notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = adecuacion.id notific.actual = 1 person = Persona.where(usuario_id: plan.tutor_id).take person2 = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " usted posee un mes para enviar el primer informe semestral de " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +"." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = adecuacion.id notific2.actual = 2 notificacionfecha = Date.current.to_s notific2.mensaje = "[" + notificacionfecha + "] " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') + " su tutor " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +" dispone de un mes para enviar el primer informe semestral." notific2.save linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe" remitente4 = Usuario.where(id: plan.instructor_id).take ActionCorreo.retraso_informe(remitente4, notific2.mensaje,linkTeI).deliver remitente3 = Usuario.where(id: plan.tutor_id).take ActionCorreo.retraso_informe(remitente3, notific.mensaje,linkTeI).deliver plan.mensaje = 1 plan.save end if plan.fecha_inicio + 11.month <= fecha2 && plan.fecha_inicio + 12.month >= fecha2 && (plan.mensaje.blank? || plan.mensaje < 3) puts plan.fecha_inicio adecuacion = Adecuacion.where(planformacion_id: plan.id).take notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = adecuacion.id notific.actual = 1 person = Persona.where(usuario_id: plan.tutor_id).take person2 = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " usted posee un mes para enviar el segundo informe semestral junto con el primer informe anual de " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +"." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = adecuacion.id notific2.actual = 2 notificacionfecha = Date.current.to_s notific2.mensaje = "[" + notificacionfecha + "] " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') + " su tutor " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +" dispone de un mes para enviar el segundo informe semestral junto con el primer informe anual." notific2.save linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe" remitente4 = Usuario.where(id: plan.instructor_id).take ActionCorreo.retraso_informe(remitente4, notific2.mensaje,linkTeI).deliver remitente3 = Usuario.where(id: plan.tutor_id).take ActionCorreo.retraso_informe(remitente3, notific.mensaje,linkTeI).deliver plan.mensaje = 3 plan.save end if plan.fecha_inicio + 17.month <= fecha2 && plan.fecha_inicio + 18.month >= fecha2 && (plan.mensaje.blank? || plan.mensaje < 5) puts plan.fecha_inicio adecuacion = Adecuacion.where(planformacion_id: plan.id).take notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = adecuacion.id notific.actual = 1 person = Persona.where(usuario_id: plan.tutor_id).take person2 = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " usted posee un mes para enviar el tercer informe semestral de " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +"." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = adecuacion.id notific2.actual = 2 notificacionfecha = Date.current.to_s notific2.mensaje = "[" + notificacionfecha + "] " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') + " su tutor " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +" dispone de un mes para enviar el tercer informe semestral ." notific2.save linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe" remitente4 = Usuario.where(id: plan.instructor_id).take ActionCorreo.retraso_informe(remitente4, notific2.mensaje,linkTeI).deliver remitente3 = Usuario.where(id: plan.tutor_id).take ActionCorreo.retraso_informe(remitente3, notific.mensaje,linkTeI).deliver plan.mensaje = 5 plan.save end if plan.fecha_inicio + 23.month <= fecha2 && (plan.mensaje.blank? || plan.mensaje < 7) puts plan.fecha_inicio adecuacion = Adecuacion.where(planformacion_id: plan.id).take notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = adecuacion.id notific.actual = 1 person = Persona.where(usuario_id: plan.tutor_id).take person2 = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " usted posee un mes para enviar el cuarto informe semestral junto con el segundo informe anual y el final de " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +"." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = adecuacion.id notific2.actual = 2 notificacionfecha = Date.current.to_s notific2.mensaje = "[" + notificacionfecha + "] " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') + " su tutor " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +" dispone de un mes para enviarlo el cuarto informe semestral junto con el segundo informe anual y el final." notific2.save linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe" remitente4 = Usuario.where(id: plan.instructor_id).take ActionCorreo.retraso_informe(remitente4, notific2.mensaje,linkTeI).deliver remitente3 = Usuario.where(id: plan.tutor_id).take ActionCorreo.retraso_informe(remitente3, notific.mensaje,linkTeI).deliver plan.mensaje = 7 plan.save end info = Informe.where(planformacion_id: plan.id).all infor1 = 0 infor2 = 0 infor3 = 0 infor4 = 0 infor5 = 0 infor6 = 0 infor7 = 0 info.each do |inf| #Se ven los informe enviados if inf.numero == 1 est_inf = EstatusInforme.where(informe_id: inf.id, actual:1).take if (est_inf.estatus_id != 6 && est_inf.estatus_id != 9) infor1 = 1 end elsif inf.numero == 2 est_inf = EstatusInforme.where(informe_id: inf.id, actual:1).take if (est_inf.estatus_id != 6 && est_inf.estatus_id != 9) infor2 = 1 end elsif inf.numero == 3 est_inf = EstatusInforme.where(informe_id: inf.id, actual:1).take if (est_inf.estatus_id != 6 && est_inf.estatus_id != 9) infor3 = 1 end elsif inf.numero == 4 est_inf = EstatusInforme.where(informe_id: inf.id, actual:1).take if (est_inf.estatus_id != 6 && est_inf.estatus_id != 9) infor4 = 1 end elsif inf.numero == 5 est_inf = EstatusInforme.where(informe_id: inf.id, actual:1).take if (est_inf.estatus_id != 6 && est_inf.estatus_id != 9) infor5 = 1 end elsif inf.numero == 6 est_inf = EstatusInforme.where(informe_id: inf.id, actual:1).take if (est_inf.estatus_id != 6 && est_inf.estatus_id != 9) infor6 = 1 end elsif inf.numero == 7 est_inf = EstatusInforme.where(informe_id: inf.id, actual:1).take if (est_inf.estatus_id != 6 && est_inf.estatus_id != 9) infor7 = 1 end end end if plan.fecha_inicio + 6.month + 15.day <= fecha2 && plan.mensaje2.blank? && infor1 == 0 puts "AAAAAAAAAAAAAAAAAAAAAAAAA" puts ((fecha2 - Time.parse((plan.fecha_inicio + 6.month).to_s)).to_i / (24 * 60 * 60)).round dias = ((fecha2 - Time.parse((plan.fecha_inicio + 6.month).to_s)).to_i / (24 * 60 * 60)).round.to_s puts plan.fecha_inicio adecuacion = Adecuacion.where(planformacion_id: plan.id).take notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = adecuacion.id notific.actual = 1 person = Persona.where(usuario_id: plan.tutor_id).take person2 = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha excedido en "+dias+" dias el dia tope de entrega del primer informe semestral de " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +", enviar en la brevedad posible." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = adecuacion.id notific2.actual = 2 notificacionfecha = Date.current.to_s notific2.mensaje = "[" + notificacionfecha + "] " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') + " su tutor " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +" ha excedido en "+dias+" dias el dia tope de entrega del primer informe semestral, enviar en la brevedad posible." notific2.save linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe" remitente4 = Usuario.where(id: plan.instructor_id).take ActionCorreo.retraso_informe(remitente4, notific2.mensaje,linkTeI).deliver remitente3 = Usuario.where(id: plan.tutor_id).take ActionCorreo.retraso_informe(remitente3, notific.mensaje,linkTeI).deliver plan.mensaje2 = 1 plan.save end if plan.fecha_inicio + 12.month + 15.day <= fecha2 && (plan.mensaje2.blank? || plan.mensaje2 < 2) && (infor2 == 0 || infor3 == 0) dias = ((fecha2 - Time.parse((plan.fecha_inicio + 12.month).to_s)).to_i / (24 * 60 * 60)).round.to_s puts plan.fecha_inicio adecuacion = Adecuacion.where(planformacion_id: plan.id).take notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = adecuacion.id notific.actual = 1 person = Persona.where(usuario_id: plan.tutor_id).take person2 = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s if infor2 == 0 notific.mensaje = "[" + notificacionfecha + "] " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha excedido en "+dias+" dias el dia tope de entrega del segundo informe semestral y con el primer informe anual de " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +", enviar en la brevedad posible." else notific.mensaje = "[" + notificacionfecha + "] " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha excedido en "+dias+" dias el dia tope de entrega del primer informe anual de " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +", enviar en la brevedad posible." end notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = adecuacion.id notific2.actual = 2 notificacionfecha = Date.current.to_s if infor2 == 0 notific2.mensaje = "[" + notificacionfecha + "] " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') + " su tutor " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +" ha excedido en "+dias+" dias el dia tope de entrega del segundo informe semestral y con el primer informe anual, enviar en la brevedad posible." else notific2.mensaje = "[" + notificacionfecha + "] " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') + " su tutor " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +" ha excedido en "+dias+" dias el dia tope de entrega del primer informe anual, enviar en la brevedad posible." end notific2.save linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe" remitente4 = Usuario.where(id: plan.instructor_id).take ActionCorreo.retraso_informe(remitente4, notific2.mensaje,linkTeI).deliver remitente3 = Usuario.where(id: plan.tutor_id).take ActionCorreo.retraso_informe(remitente3, notific.mensaje,linkTeI).deliver plan.mensaje2 = 2 plan.save end if plan.fecha_inicio + 18.month + 15.day <= fecha2 && (plan.mensaje2.blank? || plan.mensaje2 < 3) && infor4 == 0 dias = ((fecha2 - Time.parse((plan.fecha_inicio + 18.month).to_s)).to_i / (24 * 60 * 60)).round.to_s puts plan.fecha_inicio adecuacion = Adecuacion.where(planformacion_id: plan.id).take notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = adecuacion.id notific.actual = 1 person = Persona.where(usuario_id: plan.tutor_id).take person2 = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha excedido en "+dias+" dias el dia tope de entrega del tercer informe semestral de " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +", enviar en la brevedad posible." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = adecuacion.id notific2.actual = 2 notificacionfecha = Date.current.to_s notific2.mensaje = "[" + notificacionfecha + "] " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') + " su tutor " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +" ha excedido en "+dias+" dias el dia tope de entrega del tercer informe semestral, enviar en la brevedad posible." notific2.save linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe" remitente4 = Usuario.where(id: plan.instructor_id).take ActionCorreo.retraso_informe(remitente4, notific2.mensaje,linkTeI).deliver remitente3 = Usuario.where(id: plan.tutor_id).take ActionCorreo.retraso_informe(remitente3, notific.mensaje,linkTeI).deliver plan.mensaje2 = 3 plan.save end if plan.fecha_inicio + 24.month + 15.day <= fecha2 && (plan.mensaje2.blank? || plan.mensaje2 < 4) && (infor5 == 0 || infor6 == 0 || infor7 == 0) dias = ((fecha2 - Time.parse((plan.fecha_inicio + 24.month).to_s)).to_i / (24 * 60 * 60)).round.to_s puts plan.fecha_inicio adecuacion = Adecuacion.where(planformacion_id: plan.id).take notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = adecuacion.id notific.actual = 1 person = Persona.where(usuario_id: plan.tutor_id).take person2 = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s if infor5 == 0 notific.mensaje = "[" + notificacionfecha + "] " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha excedido en "+dias+" dias el dia tope de entrega del cuarto informe semestral, el segundo informe anual y el final de " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +", enviar en la brevedad posible." elsif infor6 == 0 notific.mensaje = "[" + notificacionfecha + "] " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha excedido en "+dias+" dias el dia tope de entrega del segundo informe anual y el final de " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +", enviar en la brevedad posible." else notific.mensaje = "[" + notificacionfecha + "] " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha excedido en "+dias+" dias el dia tope de entrega del informe final de " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +", enviar en la brevedad posible." end notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = adecuacion.id notific2.actual = 2 notificacionfecha = Date.current.to_s if infor5 == 0 notific2.mensaje = "[" + notificacionfecha + "] " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') + " su tutor " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +" ha excedido en "+dias+" dias el dia tope de entrega del cuarto informe semestral, con el primer informe anual y el iforme final, enviar en la brevedad posible." elsif infor6 == 0 notific2.mensaje = "[" + notificacionfecha + "] " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') + " su tutor " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +" ha excedido en "+dias+" dias el dia tope de entrega del segundo informe final y con el informe final, enviar en la brevedad posible." else notific2.mensaje = "[" + notificacionfecha + "] " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') + " su tutor " + person2.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person2.apellidos.to_s.split.map(&:capitalize).join(' ') +" ha excedido en "+dias+" dias el dia tope de entrega del informe final, enviar en la brevedad posible." end notific2.save linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe" remitente4 = Usuario.where(id: plan.instructor_id).take ActionCorreo.retraso_informe(remitente4, notific2.mensaje,linkTeI).deliver remitente3 = Usuario.where(id: plan.tutor_id).take ActionCorreo.retraso_informe(remitente3, notific.mensaje,linkTeI).deliver plan.mensaje2 = 4 plan.save end end #FIN Enviar correo de notificacion de informes-------------------------------------------------------------------------- puts "fin" sleep(1.minute) end<file_sep>/forminst_new1/app/models/departamento.rb class Departamento < ActiveRecord::Base has_many :departamento end<file_sep>/forminst_new1/app/controllers/tipoactividads_controller.rb class TipoactividadsController < ApplicationController before_action :set_tipoactividad, only: [:show, :edit, :update, :destroy] # GET /tipoactividads # GET /tipoactividads.json def index @tipoactividads = Tipoactividad.all end # GET /tipoactividads/1 # GET /tipoactividads/1.json def show end # GET /tipoactividads/new def new @tipoactividad = Tipoactividad.new end # GET /tipoactividads/1/edit def edit end # POST /tipoactividads # POST /tipoactividads.json def create @tipoactividad = Tipoactividad.new(tipoactividad_params) respond_to do |format| if @tipoactividad.save format.html { redirect_to @tipoactividad, notice: 'Tipoactividad was successfully created.' } format.json { render :show, status: :created, location: @tipoactividad } else format.html { render :new } format.json { render json: @tipoactividad.errors, status: :unprocessable_entity } end end end # PATCH/PUT /tipoactividads/1 # PATCH/PUT /tipoactividads/1.json def update respond_to do |format| if @tipoactividad.update(tipoactividad_params) format.html { redirect_to @tipoactividad, notice: 'Tipoactividad was successfully updated.' } format.json { render :show, status: :ok, location: @tipoactividad } else format.html { render :edit } format.json { render json: @tipoactividad.errors, status: :unprocessable_entity } end end end # DELETE /tipoactividads/1 # DELETE /tipoactividads/1.json def destroy @tipoactividad.destroy respond_to do |format| format.html { redirect_to tipoactividads_url, notice: 'Tipoactividad was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_tipoactividad @tipoactividad = Tipoactividad.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def tipoactividad_params params.require(:tipoactividad).permit(:id, :concepto, :grupoActividadesId, :subGrupoActividadId) end end <file_sep>/forminst_new1/app/models/observacionactividadinforme.rb class Observacionesactividadinforme < ActiveRecord::Base belongs_to :informeactividad belongs_to :revision end<file_sep>/forminst_new1/app/models/observacion_actividad_adecuacion.rb class ObservacionActividadAdecuacion < ActiveRecord::Base belongs_to :revision belongs_to :adecuacion_actividad end <file_sep>/forminst_new1/app/views/tipoestatuses/show.json.jbuilder json.extract! @tipoestatus, :id, :id, :informeId, :created_at, :updated_at <file_sep>/forminst_new1/app/views/tipoestatuses/index.json.jbuilder json.array!(@tipoestatuses) do |tipoestatus| json.extract! tipoestatus, :id, :id, :informeId json.url tipoestatus_url(tipoestatus, format: :json) end <file_sep>/forminst_new1/app/controllers/tipoestatuses_controller.rb class TipoestatusesController < ApplicationController before_action :set_tipoestatus, only: [:show, :edit, :update, :destroy] # GET /tipoestatuses # GET /tipoestatuses.json def index @tipoestatuses = Tipoestatus.all end # GET /tipoestatuses/1 # GET /tipoestatuses/1.json def show end # GET /tipoestatuses/new def new @tipoestatus = Tipoestatus.new end # GET /tipoestatuses/1/edit def edit end # POST /tipoestatuses # POST /tipoestatuses.json def create @tipoestatus = Tipoestatus.new(tipoestatus_params) respond_to do |format| if @tipoestatus.save format.html { redirect_to @tipoestatus, notice: 'Tipoestatus was successfully created.' } format.json { render :show, status: :created, location: @tipoestatus } else format.html { render :new } format.json { render json: @tipoestatus.errors, status: :unprocessable_entity } end end end # PATCH/PUT /tipoestatuses/1 # PATCH/PUT /tipoestatuses/1.json def update respond_to do |format| if @tipoestatus.update(tipoestatus_params) format.html { redirect_to @tipoestatus, notice: 'Tipoestatus was successfully updated.' } format.json { render :show, status: :ok, location: @tipoestatus } else format.html { render :edit } format.json { render json: @tipoestatus.errors, status: :unprocessable_entity } end end end # DELETE /tipoestatuses/1 # DELETE /tipoestatuses/1.json def destroy @tipoestatus.destroy respond_to do |format| format.html { redirect_to tipoestatuses_url, notice: 'Tipoestatus was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_tipoestatus @tipoestatus = Tipoestatus.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def tipoestatus_params params.require(:tipoestatus).permit(:id, :informeId) end end <file_sep>/forminst_new1/app/models/observaciontutor.rb class Observaciontutor < ActiveRecord::Base belongs_to :informeactividad end<file_sep>/forminst_new1/app/views/personas/index.json.jbuilder json.array!(@personas) do |persona| json.extract! persona, :id, :id, :usuarioId, :nombres, :apellidos, :fechaNac, :ci, :telefono1, :telefono2, :direccion json.url persona_url(persona, format: :json) end <file_sep>/forminst_new1/app/models/tipoestatus.rb class Tipoestatus < ActiveRecord::Base has_many :estatusinforme has_many :estatusadecuacion has_many :revision end<file_sep>/forminst_new1/app/controllers/observacionactividadinformes_controller.rb class ObservacionactividadinformesController < ApplicationController before_action :set_observacionactividadinforme, only: [:show, :edit, :update, :destroy] # GET /observacionactividadinformes # GET /observacionactividadinformes.json def index @observacionactividadinformes = Observacionactividadinforme.all end # GET /observacionactividadinformes/1 # GET /observacionactividadinformes/1.json def show end # GET /observacionactividadinformes/new def new @observacionactividadinforme = Observacionactividadinforme.new end # GET /observacionactividadinformes/1/edit def edit end # POST /observacionactividadinformes # POST /observacionactividadinformes.json def create @observacionactividadinforme = Observacionactividadinforme.new(observacionactividadinforme_params) respond_to do |format| if @observacionactividadinforme.save format.html { redirect_to @observacionactividadinforme, notice: 'Observacionactividadinforme was successfully created.' } format.json { render :show, status: :created, location: @observacionactividadinforme } else format.html { render :new } format.json { render json: @observacionactividadinforme.errors, status: :unprocessable_entity } end end end # PATCH/PUT /observacionactividadinformes/1 # PATCH/PUT /observacionactividadinformes/1.json def update respond_to do |format| if @observacionactividadinforme.update(observacionactividadinforme_params) format.html { redirect_to @observacionactividadinforme, notice: 'Observacionactividadinforme was successfully updated.' } format.json { render :show, status: :ok, location: @observacionactividadinforme } else format.html { render :edit } format.json { render json: @observacionactividadinforme.errors, status: :unprocessable_entity } end end end # DELETE /observacionactividadinformes/1 # DELETE /observacionactividadinformes/1.json def destroy @observacionactividadinforme.destroy respond_to do |format| format.html { redirect_to observacionactividadinformes_url, notice: 'Observacionactividadinforme was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_observacionactividadinforme @observacionactividadinforme = Observacionactividadinforme.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def observacionactividadinforme_params params.require(:observacionactividadinforme).permit(:id, :informeActividadId, :revisionId, :observacion) end end <file_sep>/forminst_new1/app/models/pdf.rb class Pdf # estas funciones permite generar el cuerpo del documento en formato pdf def self.pdf_adecuacion(actividades, plan, adecuacion, tutor, instructor, correoi, correot, escuela, pactv_docencia, pactv_investigacion, pactv_extension, pactv_formacion, pactv_otras, sactv_docencia, sactv_investigacion, sactv_extension, sactv_formacion, sactv_otras, tactv_docencia, tactv_investigacion, tactv_extension, tactv_formacion, tactv_otras, cactv_docencia, cactv_investigacion, cactv_extension, cactv_formacion, cactv_otras, fechaActual, fechaConcurso, soportes,numeroDeVersion, dactv_docencia, dactv_investigacion, dactv_extension, dactv_formacion) #def self.pdf_adecuacion(adecuacion, tutor, instructor, notificacion, perfil, pactv_docencia, pactv_investigacion, pactv_extension, pactv_formacion, pactv_otras, sactv_docencia, sactv_investigacion, sactv_extension, sactv_formacion, sactv_otras, tactv_docencia, tactv_investigacion, tactv_extension, tactv_formacion, tactv_otras, cactv_docencia, cactv_investigacion, cactv_extension, cactv_formacion, cactv_otras) # se invocan la bibliotecas require "prawn" require "prawn/layout" presentacion = "" descripcion = "" docencia = [] investigacion = [] formacion = [] extension = [] culminacion = [] if !actividades.blank? puts "Generando PDF.........." actividades.each do |actividadAde| if actividadAde.tipo_actividad_id == 9 if actividadAde.actividad.blank? presentacion = " " else presentacion = actividadAde.actividad end elsif actividadAde.tipo_actividad_id == 8 if actividadAde.actividad.blank? descripcion = " " else descripcion = actividadAde.actividad end elsif actividadAde.tipo_actividad_id == 1 if actividadAde.actividad.blank? docencia.push(" ") else docencia.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 2 if actividadAde.actividad.blank? investigacion.push(" ") else investigacion.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 4 if actividadAde.actividad.blank? formacion.push(" ") else formacion.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 3 if actividadAde.actividad.blank? extension.push(" ") else extension.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 5 if actividadAde.actividad.blank? culminacion.push(" ") else culminacion.push(actividadAde) end end end else presentacion = " " descripcion = " " docencia = [" "] investigacion = [" "] formacion = [" "] extension = [" "] culminacion = [" "] end pdf= Prawn::Document.new(:background=>"#{Rails.root}/app/assets/images/fondo.png", :top_margin=> 99, :bottom_margin=>35, :page_size => 'A4') # se coloca la imagen de fondo del documento pdf.repeat :all do #Encabezado pdf.text_box "UNIVERSIDAD CENTRAL DE VENEZUELA \n FACULTAD DE CIENCIAS\n "+escuela.nombre.upcase+"\n\n",:style => :bold, :at => [pdf.bounds.right-490, pdf.bounds.top+59] end pdf.repeat :all do #Pie de pagina point = [pdf.bounds.right-525, pdf.bounds.bottom+35] pdf.lazy_bounding_box(point, :width => 500) do pdf.text " Universidad Central de Venezuela - Facultad de Ciencias \n", :size=>9 , :align=>:center, :style => :bold pdf.text "Av. Los Ilustres, Ciudad Universitaria de Caracas, Facultad de Ciencias, \n Edificio del Decanato, Planta Baja, Los Chaguaramos, Caracas-Venezuela\n Telรฉfono/Fax: 58-212-605.11.65 / 605.11.63 / E-mail: <EMAIL>", :size=>7 , :align=>:center end.draw end ####### pdf.text("ADECUACIร“N DEL PLAN DE FORMACIร“N Y CAPACITACIร“N DE DOCENTES EN LA CATEGORรA DE INSTRUCTOR\n\n", :align=>:center, :style => :bold) # titulo del documento pdf.bounding_box([0,pdf.bounds.top], :width=>350, :height=>675) do # permite establecer el espacio en donde se puede escribir en el docuemnto pdf.move_down(35) # Datos de la dependencia pdf.text("1.- DATOS DE LA DEPENDENCIA:", :style => :bold, :size => 10) if plan.adscripcion_docencia == nil plan.adscripcion_docencia= "" plan.save end if plan.adscripcion_investigacion == nil plan.adscripcion_investigacion= "" plan.save end if instructor.area == nil instructor.area= "" instructor.save end if instructor.subarea == nil instructor.subarea= "" instructor.save end if instructor.grado_instruccion == nil instructor.grado_instruccion= "" instructor.save end data1 = [[{:text=>"Escuela o Instituto:", :font_style => :bold}, {:text => escuela.nombre, :align=>:left}], [{:text=>"รrea:", :font_style => :bold}, {:text => instructor.area , :align=>:left}], [{:text=>"Fecha de realizaciรณn del presente documento:", :font_style => :bold},{:text => fechaActual, :align=>:left}], [{:text=>"Unidad de Adscripciรณn de Docencia:", :font_style => :bold},{:text => plan.adscripcion_docencia, :align=>:left}], [{:text=>"Unidad de Adscripciรณn de Investigaciรณn:", :font_style => :bold},{:text => plan.adscripcion_investigacion, :align=>:left}]] # datos que se desean en la tabla pdf.table data1, # lineas para generar la tabla en el docuemnto :border_style => :grid, :font_size => 10, :font_style => :blod, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 130, 1 => 390}, :position => :left, :align => { 0 => :left, 1 => :right} blanco=' ' if instructor.apellidos==nil instructor.apellidos="" instructor.save end if instructor.nombres==nil instructor.nombres="" instructor.save end if instructor.telefono1==nil instructor.telefono1="" instructor.save end if instructor.telefono2==nil instructor.telefono2="" instructor.save end pdf.text("\n") pdf.text("2.- DATOS DEL INSTRUCTOR EN FORMACIร“N:", :style => :bold, :size => 10) dataa2 = [ [{:text=>"Fecha del Concurso de Oposiciรณn:", :font_style=>:bold},{:text => fechaConcurso.to_s, :align=>:left}], [{:text=>"Apellidos y Nombres:", :font_style => :bold}, {:text => instructor.apellidos.to_s.split.map(&:capitalize).join(' ') + " " + instructor.nombres.to_s.split.map(&:capitalize).join(' '), :align=>:left}], [{:text=>"Cรฉdula de Identidad:", :font_style => :bold}, {:text => instructor.ci.to_s, :align=>:left}], [{:text=>"Correo Electrรณnico:", :font_style => :bold},{:text => correoi, :align=>:left}], [{:text=>"Telรฉfono Celular:", :font_style => :bold},{:text => instructor.telefono1, :align=>:left}], [{:text=>"Otro telรฉfono:", :font_style => :bold},{:text => instructor.telefono2, :align=>:left}] ] # datos que se desean en la tabla pdf.table dataa2, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 130, 1 => 390}, :position => :left, :align => { 0 => :left, 1 => :right} pdf.text("\n") pdf.text("3.- PERFIL DE INSTRUCTOR EN FORMACIร“N:", :style => :bold, :size => 10) data3 = [ [{:text=>"Grado de Instrucciรณn:",:font_style => :bold}, {:text => instructor.grado_instruccion, :align=>:left}], [{:text=>"รrea:", :font_style => :bold}, {:text => instructor.area, :align=>:left}], [{:text=>"Sub รrea u Opciรณn:", :font_style => :bold},{:text => instructor.subarea, :align=>:left}] ] # datos que se desean en la tabla pdf.table data3, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 130, 1=>390}, :position => :left, :align => { 0 => :left, 1 => :right} salto='\n' pdf.text("\n") pdf.text("4.- DATOS DEL TUTOR ENCARGADO:", :style => :bold, :size => 10) if !tutor.telefono2.blank? dataa4 = [ [{:text=>"Apellidos y Nombres:", :font_style => :bold}, {:text => tutor.nombres.to_s.split.map(&:capitalize).join(' ') + " " + tutor.apellidos.to_s.split.map(&:capitalize).join(' ') , :align=>:left}], [{:text=>"Direcciรณn:", :font_style => :bold},{:text => tutor.direccion, :align=>:left}], [{:text=>"Correo Electrรณnico:", :font_style => :bold},{:text => correot, :align=>:left}], [{:text=>"Telefono Celular:", :font_style => :bold},{:text => tutor.telefono1, :align=>:left}] , [{:text=>"Otro Telefono:", :font_style => :bold},{:text => tutor.telefono2, :align=>:left}] ] # datos que se desean en la tabla else dataa4 = [ [{:text=>"Apellidos y Nombres:", :font_style => :bold}, {:text => tutor.nombres.to_s.split.map(&:capitalize).join(' ') + " " + tutor.apellidos.to_s.split.map(&:capitalize).join(' ') , :align=>:left}], [{:text=>"Direcciรณn:", :font_style => :bold},{:text => "No posee", :align=>:left}], [{:text=>"Correo Electrรณnico:", :font_style => :bold},{:text => correot, :align=>:left}], [{:text=>"Telefono Celular:", :font_style => :bold},{:text => "No posee", :align=>:left}], [{:text=>"Otro Telefono:", :font_style => :bold},{:text => "No posee", :align=>:left}] ] # end pdf.table dataa4, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 130, 1=>390}, :position => :left, :align => { 0 => :left, 1 => :right} pdf.text("\n") pdf.text("\n") pdf.text("5.- PRESENTACIร“N", :style => :bold, :size => 10) dataaa35 = [[{:text=> presentacion , :align=>:left}]] # datos que se desean en la tabla pdf.table dataaa35, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} pdf.text("\n") pdf.text("6.- DESCRIPCIร“N DEL PERFIL DEL INSTRUCTOR <NAME>", :style => :bold, :size => 10) data350 = [[{:text=> descripcion , :align=>:left}]] # datos que se desean en la tabla pdf.table data350, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} pdf.text("\n") pdf.text("7.- DOCENCIA", :style => :bold, :size => 10) if docencia != [" "] docencia.each do |actv| data5 = [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data5 = [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end pdf.text("\n") pdf.text("8.- INVESTIGACIร“N", :style => :bold, :size => 10) if investigacion != [" "] investigacion.each do |actv| data5 = [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data5 = [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end pdf.text("\n") pdf.text("9.- FORMACIร“N Y CAPACITACIร“N PROFESIONAL", :style => :bold, :size => 10) if formacion != [" "] formacion.each do |actv| data5 = [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data5 = [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end pdf.text("\n") pdf.text("10.- EXTENSION", :style => :bold, :size => 10) if extension != [" "] extension.each do |actv| data5 = [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data5 = [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end pdf.text("\n") pdf.text("11.- CULMINACIร“N", :style => :bold, :size => 10) if culminacion != [" "] culminacion.each do |actv| data5 = [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data5 = [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end salto='\n' pdf.text("\n") pdf.text("12.- ACTIVIDADES A REALIZAR POR EL INSTRUCTOR:", :style => :bold, :size => 10) data4= [[{:text=>"<NAME> ", :font_style => :bold}], [{:text=>"12.1.- DOCENCIA:",:font_style => :bold }]] # datos que se desean en la tabla pdf.table data4, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if pactv_docencia != [] pactv_docencia.each do |actv| data5 = [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data5 = [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data61=[[{:text=>"12.2.- INVESTIGACIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data61, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if pactv_investigacion != [] pactv_investigacion.each do |actv| data6= [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data6, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data6= [[{:text=> "No hubo." , :align=>:left}]]# datos que se desean en la tabla pdf.table data6, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data81=[[{:text=>"12.3.- FORMACIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data81, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if pactv_formacion != [] pactv_formacion.each do |actv| data8=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data8, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data8=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data8, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data71=[[{:text=>"12.4.- EXTENSIร“N:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data71, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if pactv_extension != [] pactv_extension.each do |actv| data7=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data7, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data7=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data7, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data91=[[{:text=>"12.5.- OTRAS ACTIVIDADES:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data91, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if pactv_otras != [] pactv_otras.each do |actv| data9 =[[{:text => actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data9, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data9 =[[{:text => "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data9, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data10 = [[{:text=>"<NAME> ", :font_style => :bold}], [{:text=>"12.1.- DOCENCIA:",:font_style => :bold }]] # datos que se desean en la tabla pdf.table data10, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if sactv_docencia != [] sactv_docencia.each do |actv| data11 = [[{:text=> actv.actividad , :align=>:left}]]# datos que se desean en la tabla pdf.table data11, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data11 = [[{:text=> "No hubo." , :align=>:left}]]# datos que se desean en la tabla pdf.table data11, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data121= [[{:text=>"12.2.- INVESTIGACIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data121, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if sactv_investigacion != [] sactv_investigacion.each do |actv| data12= [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data12, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data12= [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data12, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data141=[[{:text=>"12.3.- FORMACIร“N:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data141, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if sactv_formacion != [] sactv_formacion.each do |actv| data14=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data14, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data14=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data14, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data131=[[{:text=>"12.4.- EXTENSIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data131, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if sactv_extension != [] sactv_extension.each do |actv| data13=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data13, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data13=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data13, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data151=[[{:text=>"12.5.- OTRAS ACTIVIDADES:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data151, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if sactv_otras != [] sactv_otras.each do |actv| data15 =[[{:text => actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data15, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data15 =[[{:text => "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data15, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data152= [[{:text=>"<NAME> ", :font_style => :bold}], [{:text=>"12.1.- DOCENCIA:",:font_style => :bold }]] # datos que se desean en la tabla pdf.table data152, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if tactv_docencia != [] tactv_docencia.each do |actv| data153 = [[{:text=> actv.actividad , :align=>:left}]]# datos que se desean en la tabla pdf.table data153, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data153 = [[{:text=> "No hubo." , :align=>:left}]]# datos que se desean en la tabla pdf.table data153, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data154=[[{:text=>"12.2.- INVESTIGACIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data154, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if tactv_investigacion != [] tactv_investigacion.each do |actv| data155= [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data155, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data155= [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data155, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data156=[[{:text=>"12.3.- FORMACIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data156, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if tactv_formacion != [] tactv_formacion.each do |actv| data157=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data157, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data157=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data157, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data158=[[{:text=>"12.4.- EXTENSIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data158, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if tactv_extension != [] tactv_extension.each do |actv| data159=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data159, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data159=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data159, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data160=[[{:text=>"12.5.- OTRAS ACTIVIDADES:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data160, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if tactv_otras != [] tactv_otras.each do |actv| data161 =[[{:text => actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data161, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data161 =[[{:text => "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data161, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data162 = [[{:text=>"<NAME> ", :font_style => :bold}], [{:text=>"12.1.- DOCENCIA:",:font_style => :bold }]] # datos que se desean en la tabla pdf.table data162, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if cactv_docencia != [] cactv_docencia.each do |actv| data163 = [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data163, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data163 = [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data163, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data164= [[{:text=>"12.2.- INVESTIGACIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data164, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if cactv_investigacion != [] cactv_investigacion.each do |actv| data165= [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data165, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data165= [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data165, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data166=[[{:text=>"12.3.- FORMACIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data166, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if cactv_formacion != [] cactv_formacion.each do |actv| data167=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data167, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data167=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data167, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data168=[[{:text=>"12.4.- EXTENSIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data168, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if cactv_extension != [] cactv_extension.each do |actv| data169=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data169, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data169=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data169, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data170 = [[{:text=>"ACTIVIDADES OBLIGATORIAS ", :font_style => :bold}], [{:text=>"12.1.- DOCENCIA:",:font_style => :bold }]] # datos que se desean en la tabla pdf.table data170, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if dactv_docencia != [] dactv_docencia.each do |actv| data171 = [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data171, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data171 = [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data171, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data172= [[{:text=>"12.2.- INVESTIGACIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data172, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if dactv_investigacion != [] dactv_investigacion.each do |actv| data173= [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data173, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data173= [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data173, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data174=[[{:text=>"12.3.- FORMACIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data174, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if dactv_formacion != [] dactv_formacion.each do |actv| data175=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data175, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data175=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data175, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data176=[[{:text=>"12.4.- EXTENSIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data176, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if dactv_extension != [] dactv_extension.each do |actv| data177=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data177, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data177=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data177, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end pdf.text("\n") data = [ [{:text=>"Firma del Tutor: \n", :font_style => :bold}, {:text => '', :align=>:left, :font_style => :bold} ], [{:text=>"Adecuaciรณn del Plan de Formaciรณn y Capacitaciรณn Aprobado por el Consejo de Escuela o Instituto en Sesiรณn de Fecha: \n", :font_style => :bold}, {:text => 'Adecuaciรณn del Plan de Formaciรณn y Capacitaciรณn Aprobado por el Consejo de la Facultad de Ciencias en Sesiรณn de Fecha:', :align=>:left, :font_style => :bold} ] ] # cuadro final del documento pdf.table data, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 15, :border_width => 0.7, :column_widths => {0 => 260, 1=>260}, :position => :left, :align => {0 => :left, 1=> :left} @i = soportes.size pdf.text("\n") pdf.text("Cantidad de soportes adjuntos:"+ @i.to_s+" \n", :style => :bold, :size => 10) end ################### if numeroDeVersion == nil nombre_archivo= instructor.ci.to_s+'-'+fechaActual+'-adecuacion.pdf' # nombre del dcouemrnto else nombre_archivo= instructor.ci.to_s+'-'+fechaActual+'-adecuacionV'+numeroDeVersion.to_s+'.pdf' # nombre del dcouemrnto end url = "#{Rails.root}/tmp/PDFs/" + nombre_archivo pdf.render_file(url) # creaciรณn del docuemnto bajo su nombre return nombre_archivo end ######################################################################################################################################################################### def self.pdf_informe(actividades, tipo_informe,escuela,informe, adecuacion, tutor, instructor, pactv_docencia, pactv_investigacion, pactv_extension, pactv_formacion, pactv_otras, sactv_docencia, sactv_investigacion, sactv_extension, sactv_otras, sactv_formacion, tactv_docencia, tactv_investigacion, tactv_extension,tactv_formacion, tactv_otras, cactv_docencia, cactv_investigacion, cactv_extension, cactv_formacion, cactv_otras, info_docencia, info_investigacion,info_formacion, info_extension, info_otras,resx,resultados,actividadese,observaciont, resultTP, resultPP, resultO, resultAEC, resultOEC, resultDCS,documents, numeroDeVersion, factv_obligatoria, actividadesaobli, dactv_docencia, dactv_investigacion, dactv_extension, dactv_formacion, semestres) presentacion = "" descripcion = "" docencia = [] investigacion = [] formacion = [] extension = [] if !actividades.blank? puts "Generando PDF.........." actividades.each do |actividadAde| if actividadAde.tipo_actividad_id == 9 if actividadAde.actividad.blank? presentacion = " " else presentacion = actividadAde.actividad end elsif actividadAde.tipo_actividad_id == 8 if actividadAde.actividad.blank? descripcion = " " else descripcion = actividadAde.actividad end elsif actividadAde.tipo_actividad_id == 1 if actividadAde.actividad.blank? docencia.push(" ") else docencia.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 2 if actividadAde.actividad.blank? investigacion.push(" ") else investigacion.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 4 if actividadAde.actividad.blank? formacion.push(" ") else formacion.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 3 if actividadAde.actividad.blank? extension.push(" ") else extension.push(actividadAde) end end end else presentacion = " " descripcion = " " docencia = [" "] investigacion = [" "] formacion = [" "] extension = [" "] end noplan_a=[] noplan_na=[] res_tp=[] res_ppcc=[] res_otp=[] res_aec=[] res_oec=[] res_dctsc=[] resultados.each do |resultado| if resultado.tipo_resultado_id == 1 res_tp.push(resultado) elsif resultado.tipo_resultado_id == 2 res_ppcc.push(resultado) elsif resultado.tipo_resultado_id == 4 res_otp.push(resultado) elsif resultado.tipo_resultado_id == 5 res_aec.push(resultado) elsif resultado.tipo_resultado_id == 6 res_oec.push(resultado) elsif resultado.tipo_resultado_id == 7 res_dctsc.push(resultado) end end # se invocan la bibliotecas require "prawn" require 'prawn/layout' pdf= Prawn::Document.new(:background=>"#{Rails.root}/app/assets/images/fondo.png", :top_margin=> 99, :bottom_margin=>35, :page_size => 'A4') # se coloca la imagen de fondo del documento pdf.repeat :all do #Encabezado pdf.text_box "UNIVERSIDAD CENTRAL DE VENEZUELA \n FACULTAD DE CIENCIAS\n "+escuela.nombre.upcase+"\n\n",:style => :bold, :at => [pdf.bounds.right-490, pdf.bounds.top+59] end pdf.repeat :all do #Pie de pagina point = [pdf.bounds.right-525, pdf.bounds.bottom+35] pdf.lazy_bounding_box(point, :width => 500) do pdf.text " Universidad Central de Venezuela - Facultad de Ciencias \n", :size=>9 , :align=>:center, :style => :bold pdf.text "Av. Los Ilustres, Ciudad Universitaria de Caracas, Facultad de Ciencias, \n Edificio del Decanato, Planta Baja, Los Chaguaramos, Caracas-Venezuela\n Telรฉfono/Fax: 58-212-605.11.65 / 605.11.63 / E-mail: <EMAIL>", :size=>7 , :align=>:center end.draw end nombre_informe = "" if (informe.numero == 1 || informe.numero == 3) nombre_informe= "PRIMER INFORME " elsif (informe.numero == 2 || informe.numero == 6) nombre_informe= "SEGUNDO INFORME " elsif informe.numero == 4 nombre_informe= "TERCER INFORME " elsif informe.numero == 5 nombre_informe= "<NAME> " end if informe.tipo_id == 1 nombre_informe= nombre_informe+"SEMESTRAL" elsif informe.tipo_id == 2 nombre_informe= nombre_informe+"ANUAL" else nombre_informe= "INFORME "+"FINAL" end #titulo del documento ati = tipo_informe.tipo.upcase pdf.text("#{nombre_informe} DE ACTIVIDADES REALIZADAS POR EL INSTRUCTOR DURANTE LA EJECUCIร“N DE SU PLAN DE FORMACIร“N Y CAPACITACIร“N\n\n", :align=>:center, :style => :bold) # titulo del documento ################ pdf.bounding_box([0,pdf.bounds.top], :width=>350, :height=>675) do # permite establecer el espacio en donde se puede escribir en el docuemnto pdf.move_down(35) #apartado 1 pdf.text("1.- DATOS DEL INSTRUCTOR EN FORMACIร“N Y SU TUTOR:", :style => :bold, :size => 10) blanco=' ' data1 = [ #[{:text=>"Nยฐ del informe", :font_style => :bold}, {:text => informe.numero_informe.to_s, :align=>:left}], [{:text=>"Nยฐ del informe", :font_style => :bold}, {:text => nombre_informe.capitalize, :align=>:left}], #[{:text=>"Fecha de realizaciรณn del informe:", :font_style => :bold}, {:text => informe.fecha_informe.to_s, :align=>:left}], [{:text=>"Fecha de realizaciรณn del informe:", :font_style => :bold}, {:text => informe.fecha_creacion.to_s, :align=>:left}], #[{:text=>"Apellidos y Nombres del Instructor:", :font_style => :bold},{:text => instructor.apellidos+blanco+instructor.nombres, :align=>:left}], [{:text=>"Apellidos y Nombres del Instructor:", :font_style => :bold},{:text => instructor.nombres.to_s.split.map(&:capitalize).join(' ') + " " + instructor.apellidos.to_s.split.map(&:capitalize).join(' '), :align=>:left}], #[{:text=>"Cรฉdula de Identidad del Instructor:", :font_style => :bold}, {:text => instructor.ci.to_s, :align=>:left}], [{:text=>"Cรฉdula de Identidad del Instructor:", :font_style => :bold}, {:text => instructor.ci.to_s, :align=>:left}], #[{:text=>"Perรญodo que comprende el Informe:", :font_style => :bold}, {:text => informe.periodo.to_s, :align=>:left}], [{:text=>"Perรญodo que comprende el Informe:", :font_style => :bold}, {:text => informe.fecha_inicio.to_s + " al " + informe.fecha_fin.to_s, :align=>:left}], #[{:text=>"Apellidos y Nombre del Tutor:", :font_style => :bold}, {:text => tutor.nombres, :align=>:left}], [{:text=>"Apellidos y Nombre del Tutor:", :font_style => :bold}, {:text => tutor.nombres.to_s.split.map(&:capitalize).join(' ') + " " + tutor.apellidos.to_s.split.map(&:capitalize).join(' '), :align=>:left}], #[{:text=>"Cรฉdula de Identidad del Tutor:", :font_style => :bold}, {:text => tutor.ci.to_s, :align=>:left}], [{:text=>"Cรฉdula de Identidad del Tutor:", :font_style => :bold}, {:text => tutor.ci.to_s, :align=>:left}], #+[{:text=>"Escuela o Instituto de adscripciรณn:", :font_style => :bold}, {:text => escuela.nombre, :align=>:left}] [{:text=>"Escuela o Instituto de adscripciรณn:", :font_style => :bold}, {:text => escuela.nombre, :align=>:left}] ]# datos que se desean en la tabla pdf.table data1, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :font_style => :blod, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 200, 1 => 320}, :position => :left, :align => { 0 => :left, 1 => :right} pdf.text("\n") pdf.text("\n") pdf.text("2.- PRESENTACIร“N", :style => :bold, :size => 10) dataaa35 = [[{:text=> presentacion , :align=>:left}]] # datos que se desean en la tabla pdf.table dataaa35, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} pdf.text("\n") pdf.text("3.- DESCRIPCIร“N DEL PERFIL DEL INSTRUCTOR <NAME>", :style => :bold, :size => 10) data350 = [[{:text=> descripcion , :align=>:left}]] # datos que se desean en la tabla pdf.table data350, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} pdf.text("\n") pdf.text("4.- DOCENCIA", :style => :bold, :size => 10) if docencia != [] docencia.each do |actv| data5 = [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data5 = [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end pdf.text("\n") pdf.text("5.- INVESTIGACIร“N", :style => :bold, :size => 10) if investigacion != [] investigacion.each do |actv| data5 = [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data5 = [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end pdf.text("\n") pdf.text("6.- FORMACIร“N Y CAPACITACIร“N PROFESIONAL", :style => :bold, :size => 10) if formacion != [] formacion.each do |actv| data5 = [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data5 = [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end pdf.text("\n") pdf.text("7.- EXTENSIร“N", :style => :bold, :size => 10) if extension != [] extension.each do |actv| data5 = [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data5 = [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 10, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end salto='\n' pdf.text("\n") #apartado 2 data2 = [[{:text=>"8.- PRESENTACIร“N DE PLAN DE FORMACIร“N Y CAPACITACIร“N:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data2, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} data24= [[{:text=>"<NAME> ", :font_style => :bold}], [{:text=>"8.1.- DOCENCIA:",:font_style => :bold }]]# datos que se desean en la tabla pdf.table data24, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !pactv_docencia.blank? pactv_docencia.each do |actv| data25 = [[{:text=> actv.actividad , :align=>:left}]]# datos que se desean en la tabla pdf.table data25, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data25 = [[{:text=> "No hubo." , :align=>:left}]]# datos que se desean en la tabla pdf.table data25, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data261= [[{:text=>"8.2.- INVESTIGACIร“N:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data261, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !pactv_investigacion.blank? pactv_investigacion.each do |actv| data26= [[{:text=> actv.actividad , :align=>:left}]]# datos que se desean en la tabla pdf.table data26, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data26= [[{:text=> "No hubo." , :align=>:left}]]# datos que se desean en la tabla pdf.table data26, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data281=[[{:text=>"8.3.- FORMACIร“N:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data281, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !pactv_formacion.blank? pactv_formacion.each do |actv| data28=[[{:text=> actv.actividad , :aling=> :left}]]# datos que se desean en la tabla pdf.table data28, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data28=[[{:text=> "No hubo." , :aling=> :left}]]# datos que se desean en la tabla pdf.table data28, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data271=[[{:text=>"8.4.- EXTENSIร“N:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data271, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !pactv_extension.blank? pactv_extension.each do |actv| data27=[[{:text=> actv.actividad , :aling=> :left}]]# datos que se desean en la tabla pdf.table data27, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data27=[[{:text=> "No hubo." , :aling=> :left}]]# datos que se desean en la tabla pdf.table data27, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data291 =[[{:text=>"8.5.- OTRAS ACTIVIDADES:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data291, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !pactv_otras.blank? pactv_otras.each do |actv| data29 =[[{:text => actv.actividad , :aling=> :left}]]# datos que se desean en la tabla pdf.table data29, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data29 =[[{:text => "No hubo." , :aling=> :left}]]# datos que se desean en la tabla pdf.table data29, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data210 = [[{:text=>"<NAME> ", :font_style => :bold}], [{:text=>"8.1.- DOCENCIA:",:font_style => :bold }]]# datos que se desean en la tabla pdf.table data210, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !sactv_docencia.blank? sactv_docencia.each do |actv| data211 = [[{:text=> actv.actividad , :align=>:left}]]# datos que se desean en la tabla pdf.table data211, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data211 = [[{:text=> "No hubo." , :align=>:left}]]# datos que se desean en la tabla pdf.table data211, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data2121= [[{:text=>"8.2.- INVESTIGACIร“N:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data2121, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !sactv_investigacion.blank? sactv_investigacion.each do |actv| data212= [[{:text=> actv.actividad , :align=>:left}]]# datos que se desean en la tabla pdf.table data212, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data212= [[{:text=> "No hubo." , :align=>:left}]]# datos que se desean en la tabla pdf.table data212, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data2141=[[{:text=>"8.3.- FORMACIร“N:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data2141, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !sactv_formacion.blank? sactv_formacion.each do |actv| data214=[[{:text=> actv.actividad , :aling=> :left}]]# datos que se desean en la tabla pdf.table data214, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data214=[[{:text=> "No hubo." , :aling=> :left}]]# datos que se desean en la tabla pdf.table data214, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data2131=[[{:text=>"8.4.- EXTENSIร“N:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data2131, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !sactv_extension.blank? sactv_extension.each do |actv| data213=[[{:text=> actv.actividad , :aling=> :left}]]# datos que se desean en la tabla pdf.table data213, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data213=[[{:text=> "No hubo." , :aling=> :left}]]# datos que se desean en la tabla pdf.table data213, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data2151 =[[{:text=>"8.5.- OTRAS ACTIVIDADES:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data2151, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !sactv_otras.blank? sactv_otras.each do |actv| data215 =[[{:text => actv.actividad , :aling=> :left}]]# datos que se desean en la tabla pdf.table data215, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data215 =[[{:text => "No hubo." , :aling=> :left}]]# datos que se desean en la tabla pdf.table data215, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data152= [[{:text=>"<NAME> ", :font_style => :bold}], [{:text=>"8.1.- DOCENCIA:",:font_style => :bold }]]# datos que se desean en la tabla pdf.table data152, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !tactv_docencia.blank? tactv_docencia.each do |actv| data153 = [[{:text=> actv.actividad , :align=>:left}]]# datos que se desean en la tabla pdf.table data153, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data153 = [[{:text=> "No hubo." , :align=>:left}]]# datos que se desean en la tabla pdf.table data153, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data154=[[{:text=>"8.2.- INVESTIGACIร“N:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data154, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !tactv_investigacion.blank? tactv_investigacion.each do |actv| data155= [[{:text=> actv.actividad , :align=>:left}]]# datos que se desean en la tabla pdf.table data155, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data155= [[{:text=> "No hubo." , :align=>:left}]]# datos que se desean en la tabla pdf.table data155, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data156=[[{:text=>"8.3.- FORMACIร“N:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data156, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !tactv_formacion.blank? tactv_formacion.each do |actv| data157=[[{:text=> actv.actividad , :aling=> :left}]]# datos que se desean en la tabla pdf.table data157, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data157=[[{:text=> "No hubo." , :aling=> :left}]]# datos que se desean en la tabla pdf.table data157, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data158=[[{:text=>"8.4.- EXTENSIร“N:", :font_style => :bold}]]# datos que se desean en la tabla pdf.table data158, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !tactv_extension.blank? tactv_extension.each do |actv| data159=[[{:text=> actv.actividad , :aling=> :left}]]# datos que se desean en la tabla pdf.table data159, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data159=[[{:text=> "No hubo." , :aling=> :left}]]# datos que se desean en la tabla pdf.table data159, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data160=[[{:text=>"8.5.- OTRAS ACTIVIDADES:", :font_style => :bold}]]# cuadro final del documento pdf.table data160, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !tactv_otras.blank? tactv_otras.each do |actv| data161 =[[{:text => actv.actividad , :aling=> :left}]]# datos que se desean en la tabla pdf.table data161, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data161 =[[{:text => "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data161, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data162 = [[{:text=>"<NAME> ", :font_style => :bold}], [{:text=>"8.1.- DOCENCIA:",:font_style => :bold }]] # datos que se desean en la tabla pdf.table data162, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !cactv_docencia.blank? cactv_docencia.each do |actv| data163 = [[{:text=> actv.actividad , :align=>:left}]]# datos que se desean en la tabla pdf.table data163, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data163 = [[{:text=> "No hubo." , :align=>:left}] ] # datos que se desean en la tabla pdf.table data163, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data164= [[{:text=>"8.2.- INVESTIGACIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data164, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !cactv_investigacion.blank? cactv_investigacion.each do |actv| data165= [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data165, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data165= [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data165, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data166=[[{:text=>"8.3.- FORMACIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data166, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !cactv_formacion.blank? cactv_formacion.each do |actv| data167=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data167, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data167=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data167, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data168=[[{:text=>"8.4.- EXTENSIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data168, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !cactv_extension.blank? cactv_extension.each do |actv| data169=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data169, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data169=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data169, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data170=[[{:text=>"8.5.- OTRAS ACTIVIDADES:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data170, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !cactv_otras.blank? cactv_otras.each do |actv| data171 =[[{:text => actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data171, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data171 =[[{:text => "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data171, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data162 = [[{:text=>"ACTIVIDADES OBLIGATORIAS ", :font_style => :bold}], [{:text=>"8.1.- DOCENCIA:",:font_style => :bold }]] # datos que se desean en la tabla pdf.table data162, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !cactv_docencia.blank? dactv_docencia.each do |actv| data163 = [[{:text=> actv.actividad , :align=>:left}]]# datos que se desean en la tabla pdf.table data163, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data163 = [[{:text=> "No hubo." , :align=>:left}] ] # datos que se desean en la tabla pdf.table data163, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data164= [[{:text=>"8.2.- INVESTIGACIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data164, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !cactv_investigacion.blank? dactv_investigacion.each do |actv| data165= [[{:text=> actv.actividad , :align=>:left}]] # datos que se desean en la tabla pdf.table data165, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data165= [[{:text=> "No hubo." , :align=>:left}]] # datos que se desean en la tabla pdf.table data165, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data166=[[{:text=>"8.3.- FORMACIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data166, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !cactv_formacion.blank? dactv_formacion.each do |actv| data167=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data167, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data167=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data167, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end data168=[[{:text=>"8.4.- EXTENSIร“N:", :font_style => :bold}]] # datos que se desean en la tabla pdf.table data168, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if !cactv_extension.blank? dactv_extension.each do |actv| data169=[[{:text=> actv.actividad , :aling=> :left}]] # datos que se desean en la tabla pdf.table data169, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else data169=[[{:text=> "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table data169, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end pdf.text("\n") pdf.text("ACTIVIDADES DESARROLLADAS \n") pdf.text("\n") salto='\n' #apartado 3 pdf.text("9.- ACTIVIDADES DE DOCENCIA:", :style => :bold, :size => 10) data3 = [[{:text=>"ACTIVIDAD DE DOCENCIA PROGRAMADA",:align=>:center,:font_style => :bold}, {:text =>"ACTIVIDAD DE DOCENCIA EJECUTADA", :align=>:center,:font_style => :bold},{:text =>"OBSERVACIONES", :align=>:center,:font_style => :bold}]] # datos que se desean en la tabla pdf.table data3, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 3, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => { 0 => :left, 1 => :left, 2=> :left} if !info_docencia.blank? listo = "no" info_docencia.each do |actv| if semestres[actv.id] == 5 && listo == "no" data31 = [[{:text=> "Obligatorias", :align=>:center}]] pdf.table data31, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 =>519}, :position => :left, :align => { 0 => :left} listo = "si" end ae = InformeActividad.where(actividad_id: actv.id, informe: informe.id).take ai = ActividadEjecutada.where(informe_actividad_id: ae.id).take obs= ObservacionTutor.where(informe_actividad_id: ae.id).take if !obs.blank? if !ai.blank? data31 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => ai.descripcion.to_s, :align=>:left}, {:text => obs.observaciones.to_s, :align=>:left}]] # datos que se desean en la tabla else data31 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => "", :align=>:left}, {:text => obs.observaciones.to_s, :align=>:left}]] # datos que se desean en la tabla end else if !ai.blank? data31 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => ai.descripcion.to_s, :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla else data31 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => "", :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla end end pdf.table data31, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => { 0 => :left, 1 => :left, 2=> :left} end else data31 = [[{:text=> "No hubo." , :align=>:left}, {:text=> "" , :align=>:left}, {:text=> "" , :align=>:left}]] # datos que se desean en la tabla pdf.table data31, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => { 0 => :left, 1 => :left, 2=> :left} end pdf.text("\n") #aparatado 4 Y RESULTADOS pdf.text("10.- ACTIVIDADES DE INVESTIGACIร“N:", :style => :bold, :size => 10) data4 = [[{:text=>"ACTIVIDAD DE INVESTIGACIร“N PROGRAMADA",:align=>:center,:font_style => :bold}, {:text =>"ACTIVIDAD DE INVESTIGACION EJECUTADA", :align=>:center,:font_style => :bold},{:text =>"OBSERVACIONES", :align=>:center,:font_style => :bold} ]] # datos que se desean en la tabla pdf.table data4, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => { 0 => :left, 1 => :left, 2=> :left} aee = 0 if !info_investigacion.blank? listo = "no" info_investigacion.each do |actv| if listo == "no" && semestres[actv.id] == 5 data41 = [[{:text=> "Obligatorias", :align=>:center}]] pdf.table data41, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 =>519}, :position => :left, :align => { 0 => :left} listo = "si" end ae = InformeActividad.where(actividad_id: actv.id, informe: informe.id).take ai = ActividadEjecutada.where(informe_actividad_id: ae.id).take obs= ObservacionTutor.where(informe_actividad_id: ae.id).take if !obs.blank? if !ai.blank? data41 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => ai.descripcion.to_s, :align=>:left}, {:text => obs.observaciones.to_s, :align=>:left}]] # datos que se desean en la tabla else data41 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => "", :align=>:left}, {:text => obs.observaciones.to_s, :align=>:left}]] # datos que se desean en la tabla end else if !ai.blank? data41 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => ai.descripcion.to_s, :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla else data41 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => "", :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla end end pdf.table data41, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7 , :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => { 0 => :left, 1 => :left, 2=> :left} end else data41 = [[{:text=> "No hubo." , :align=>:left}, {:text=> "" , :align=>:left}, {:text=> "" , :align=>:left}]] # datos que se desean en la tabla pdf.table data41, :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7 , :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => { 0 => :left, 1 => :left, 2=> :left} end res1 = [[{:text=> "10.1.- Divulgaciรณn de resultados:", :font_style => :bold}], [{:text=> "10.1.1.- Trabajos publicados (libros, revistas, artรญculos de prensa, CDs, manuales, publicaciones electrรณnicas, etc.): \n", :font_style => :bold}]] # cuadro final del documento pdf.table res1, # lineas para generar la tabla en el docuemnto :border_style =>:grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if resultTP != [] resultTP.each do |res| res2=[[{:text=> res, :align=>:left }]] # datos que se desean en la tabla pdf.table res2, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else res2 =[[{:text => "No hubo." , :aling=> :left}] ] # datos que se desean en la tabla pdf.table res2, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end res3 = [[{:text=> "10.1.2.- Presentaciรณn de ponencias, conferencias y carteles en eventos:\n", :font_style => :bold}]] # datos que se desean en la tabla pdf.table res3, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if resultPP !=[] resultPP.each do |res| res4 = [[{:text=> res, :align=>:left }]] # datos que se desean en la tabla pdf.table res4, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else res4 =[[{:text => "No hubo." , :aling=> :left}] ] # datos que se desean en la tabla pdf.table res4, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end res5 = [[{:text=> "10.1.3.- Otros:\n", :font_style => :bold}]] # datos que se desean en la tabla pdf.table res5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if resultO != [] resultO.each do |res| res6 = [[{:text=> res, :align=>:left }]] # datos que se desean en la tabla pdf.table res6, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else res6 =[ [{:text => "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table res6, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end res7 = [[{:text=> "10.1.4.- Asistencia a eventos cientรญficos (Congresos, Seminarios, Coloquios, Jornadas, etc.):\n", :font_style => :bold}]] # datos que se desean en la tabla pdf.table res7, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if resultAEC != [] resultAEC.each do |res| res8 = [[{:text=> res, :align=>:left }]] # datos que se desean en la tabla pdf.table res8, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else res8 =[ [{:text => "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table res8, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end res9 = [[{:text=> "10.1.5.- Organizaciรณn de eventos cientรญficos (Congresos, Seminarios, Coloquios, Jornadas, etc.):\n", :font_style => :bold}] ] # datos que se desean en la tabla pdf.table res9, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if resultOEC != [] resultOEC.each do |res| res10 = [[{:text=> res, :align=>:left }]] # datos que se desean en la tabla pdf.table res10, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else res10 =[[{:text => "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table res10, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end res11 = [[{:text=> "10.1.6.- Dictado de cursos, talleres o seminarios cientรญficos:\n", :font_style => :bold}]] # datos que se desean en la tabla pdf.table res11, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} if resultDCS != [] resultDCS.each do |res| res12= [[{:text=> res, :align=>:left }]] # datos que se desean en la tabla pdf.table res12, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end else res12 =[[{:text => "No hubo." , :aling=> :left}]] # datos que se desean en la tabla pdf.table res12, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end #aparatado 5 pdf.text("\n") pdf.text("11.- ACTIVIDADES DE FORMACIร“N:", :style => :bold, :size => 10) data5 = [[{:text=>"ACTIVIDAD DE FORMACIร“N PROGRAMADA",:align=>:center,:font_style => :bold}, {:text =>"ACTIVIDAD DE FORMACIร“N EJECUTADA", :align=>:center,:font_style => :bold},{:text =>"OBSERVACIONES", :align=>:center,:font_style => :bold} ] ] # datos que se desean en la tabla pdf.table data5, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => { 0 => :left, 1 => :left, 2=> :left} if info_formacion != [] listo = "no" info_formacion.each do |actv| if listo == "no" && semestres[actv.id] == 5 data51 = [[{:text=> "Obligatorias", :align=>:center}]] pdf.table data51, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 =>519}, :position => :left, :align => { 0 => :left} listo = "si" end ae = InformeActividad.where(actividad_id: actv.id, informe: informe.id).take ai = ActividadEjecutada.where(informe_actividad_id: ae.id).take obs= ObservacionTutor.where(informe_actividad_id: ae.id).take if !obs.blank? if !ai.blank? data51 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => ai.descripcion.to_s, :align=>:left}, {:text => obs.observaciones.to_s, :align=>:left}]] # datos que se desean en la tabla else data51 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => "", :align=>:left}, {:text => obs.observaciones.to_s, :align=>:left}]] # datos que se desean en la tabla end else if !ai.blank? data51 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => ai.descripcion.to_s, :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla else data51 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => "", :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla end end pdf.table data51, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => { 0 => :left, 1 => :left, 2=> :left} end else data51=[[{:text=> "No hubo.", :align=>:left}, {:text => "", :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla pdf.table data51, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => { 0 => :left, 1 => :left, 2=> :left} end #data52=[[{:text=> "5.1.- Grado de avance en los estudios de postgrado:\n", :font_style => :bold}], #[{:text=> informe.avance.to_s, :align=>:left}]] # datos que se desean en la tabla pdf.text("\n") pdf.text("12.- ACTIVIDADES DE EXTENSIร“N:", :style => :bold, :size => 10) data6 = [[{:text=>"ACTIVIDAD DE EXTENSIร“N PROGRAMADA",:align=>:center,:font_style => :bold}, {:text =>"ACTIVIDAD DE EXTENSIร“N EJECUTADA", :align=>:center,:font_style => :bold},{:text =>"OBSERVACIONES", :align=>:center,:font_style => :bold} ] ] # datos que se desean en la tabla pdf.table data6, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => {0 => :left, 1 => :left, 2=> :left} if info_extension != [] listo = "no" info_extension.each do |actv| if listo == "no" && semestres[actv.id] == 5 data51 = [[{:text=> "Obligatorias", :align=>:center}]] pdf.table data51, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 =>519}, :position => :left, :align => { 0 => :left} listo = "si" end ae = InformeActividad.where(actividad_id: actv.id, informe: informe.id).take ai = ActividadEjecutada.where(informe_actividad_id: ae.id).take obs= ObservacionTutor.where(informe_actividad_id: ae.id).take if !obs.blank? if !ai.blank? data61 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => ai.descripcion.to_s, :align=>:left}, {:text => obs.observaciones.to_s, :align=>:left}]] # datos que se desean en la tabla else data61 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => "", :align=>:left}, {:text => obs.observaciones.to_s, :align=>:left}]] # datos que se desean en la tabla end else if !ai.blank? data61 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => ai.descripcion.to_s, :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla else data61 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => "", :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla end end pdf.table data61, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => { 0 => :left, 1 => :left, 2=> :left} end else data61=[[{:text=> "No hubo.", :align=>:left}, {:text => "", :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla pdf.table data61, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => { 0 => :left, 1 => :left, 2=> :left} end x=13 if tipo_informe.tipo=="Final" pdf.text("\n") pdf.text(x.to_s+".- ACTIVIDADES PARA LA APROBACIร“N:", :style => :bold, :size => 10) data6 = [[{:text=>"ACTIVIDAD PARA LA APROBACIร“N",:align=>:center,:font_style => :bold}, {:text =>"ACTIVIDAD PARA LA APROBACIร“N EJECUTADA", :align=>:center,:font_style => :bold},{:text =>"OBSERVACIONES", :align=>:center,:font_style => :bold} ] ] # datos que se desean en la tabla pdf.table data6, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => {0 => :left, 1 => :left, 2=> :left} if actividadesaobli != [] actividadesaobli.each do |actv| ae = InformeActividad.where(actividad_id: actv.id, informe: informe.id).take ai = ActividadEjecutada.where(informe_actividad_id: ae.id).take obs= ObservacionTutor.where(informe_actividad_id: ae.id).take if !obs.blank? if !ai.blank? data61 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => ai.descripcion.to_s, :align=>:left}, {:text => obs.observaciones.to_s, :align=>:left}]] # datos que se desean en la tabla else data61 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => "", :align=>:left}, {:text => obs.observaciones.to_s, :align=>:left}]] # datos que se desean en la tabla end else if !ai.blank? data61 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => ai.descripcion.to_s, :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla else data61 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => "", :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla end end pdf.table data61, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => { 0 => :left, 1 => :left, 2=> :left} end else data61=[[{:text=> "No hubo.", :align=>:left}, {:text => "", :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla pdf.table data61, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 173, 1 => 173, 2 => 173}, :position => :left, :align => { 0 => :left, 1 => :left, 2=> :left} end x=x+1 end pdf.text("\n") #APARTADO 7 x=13 pdf.text(x.to_s+".- OTRAS ACTIVIDADES: \n", :style => :bold, :size => 10) data7 = [[{:text=>"CONTEMPLADAS EN EL PLAN DE FORMACIร“N Y CAPACITACIร“N:",:align=>:center,:font_style => :bold}, {:text =>"NO CONTEMPLADAS EN EL PLAN DE FORMACIร“N Y CAPACITACIร“N", :align=>:center,:font_style => :bold}]] # datos que se desean en la tabla pdf.table data7, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 2, :border_width => 0.7, :column_widths => { 0 => 259, 1 => 259}, :position => :left, :align => {0 => :left, 1 => :left} if info_otras != [] info_otras.each do |actv| ae = InformeActividad.where(actividad_id: actv.id, informe: informe.id).take ai = ActividadEjecutada.where(informe_actividad_id: ae.id).take if ai data71 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => ai.descripcion.to_s, :align=>:left}]] # datos que se desean en la tabla else data71 = [[{:text=> actv.actividad.to_s, :align=>:left}, {:text => "" , :align=>:left}]] # datos que se desean en la tabla end pdf.table data71, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 2, :border_width => 0.7, :column_widths => { 0 => 259, 1 => 259}, :position => :left, :align => {0 => :left, 1 => :left} end else data71=[[{:text=> "No hubo.", :align=>:left}, {:text => "", :align=>:left}]] # datos que se desean en la tabla pdf.table data71, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 2, :border_width => 0.7, :column_widths => { 0 => 259, 1 => 259}, :position => :left, :align => {0 => :left, 1 => :left} end x=x+1 pdf.text("\n") x=14 #aparatdo 8 punto='. ' pdf.text(x.to_s+".- CONCLUSIONES:", :style => :bold, :size => 10) if !informe.conclusiones.blank? data10 = [[{:text=> informe.conclusiones.to_s, :align=> :left}]] # datos que se desean en la tabla pdf.table data10, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} else data10 = [[{:text=> " ", :align=> :left}]] # datos que se desean en la tabla pdf.table data10, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end pdf.text("\n") x=x+1 #aparatdo 9 x=15 pdf.text(x.to_s+".- OPINIร“N DEL TUTOR:", :style => :bold, :size => 10) if !informe.opinion_tutor.blank? data11 = [[{:text=> informe.opinion_tutor.to_s, :align=> :left}]] # datos que se desean en la tabla pdf.table data11, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} else data11 = [[{:text=> " ", :align=> :left}]] # datos que se desean en la tabla pdf.table data11, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end x=16 pdf.text("\n") pdf.text(x.to_s+".- JUSTIFICACIONES:", :style => :bold, :size => 10) if !informe.justificaciones.blank? data112 = [[{:text=> informe.justificaciones.to_s, :align=> :left}]] # datos que se desean en la tabla pdf.table data112, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} else data112 = [[{:text=> " ", :align=> :left}]] # datos que se desean en la tabla pdf.table data112, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 3, :border_width => 0.7, :column_widths => { 0 => 520}, :position => :left, :align => { 0 => :left} end #FIN DEL INFORME pdf.text("\n") data12 = [ [{:text=>"<NAME>: \n", :font_style => :bold}, {:text => 'Fecha:', :align=>:left, :font_style => :bold} ], [{:text=>"Adecuaciรณn del Plan de Formaciรณn y Capacitaciรณn Aprobado por el Consejo de Escuela o Instituto en Sesiรณn de Fecha: \n", :font_style => :bold}, {:text => 'Adecuaciรณn del Plan de Formaciรณn y Capacitaciรณn Aprobado por el Consejo de la Facultad de Ciencias en Sesiรณn de Fecha:', :align=>:left, :font_style => :bold} ]] # cuadro final del documento pdf.table data12, # lineas para generar la tabla en el docuemnto :border_style => :grid, #:underline_header :font_size => 8, :horizontal_padding => 6, :vertical_padding => 15, :border_width => 0.7, :column_widths => {0 => 260, 1=>260}, :position => :left, :align => {0 => :left, 1=> :left} @i = documents.size pdf.text("\n") pdf.text("Cantidad de soportes adjuntos:"+ @i.to_s+" \n", :style => :bold, :size => 10) end #####################+ fechaActual = Date.current.to_s if numeroDeVersion == nil nombre_archivo= instructor.ci.to_s+'-'+fechaActual+'-informe.pdf' # se arma el nombre del documento else nombre_archivo= instructor.ci.to_s+'-'+fechaActual+'-informeV'+numeroDeVersion.to_s+'.pdf' # se arma el nombre del documento end url = "#{Rails.root}/tmp/PDFs/" + nombre_archivo pdf.render_file(url) # creaciรณn del docuemnto bajo su nombre return nombre_archivo end end<file_sep>/forminst_new1/test/helpers/forminst_helper_test.rb require 'test_helper' class ForminstHelperTest < ActionView::TestCase end <file_sep>/forminst_new1/app/views/observacionactividadinformes/index.json.jbuilder json.array!(@observacionactividadinformes) do |observacionactividadinforme| json.extract! observacionactividadinforme, :id, :id, :informeActividadId, :revisionId, :observacion json.url observacionactividadinforme_url(observacionactividadinforme, format: :json) end <file_sep>/forminst_new1/app/controllers/observacionactividadadecuacions_controller.rb class ObservacionactividadadecuacionsController < ApplicationController before_action :set_observacionactividadadecuacion, only: [:show, :edit, :update, :destroy] # GET /observacionactividadadecuacions # GET /observacionactividadadecuacions.json def index @observacionactividadadecuacions = Observacionactividadadecuacion.all end # GET /observacionactividadadecuacions/1 # GET /observacionactividadadecuacions/1.json def show end # GET /observacionactividadadecuacions/new def new @observacionactividadadecuacion = Observacionactividadadecuacion.new end # GET /observacionactividadadecuacions/1/edit def edit end # POST /observacionactividadadecuacions # POST /observacionactividadadecuacions.json def create @observacionactividadadecuacion = Observacionactividadadecuacion.new(observacionactividadadecuacion_params) respond_to do |format| if @observacionactividadadecuacion.save format.html { redirect_to @observacionactividadadecuacion, notice: 'Observacionactividadadecuacion was successfully created.' } format.json { render :show, status: :created, location: @observacionactividadadecuacion } else format.html { render :new } format.json { render json: @observacionactividadadecuacion.errors, status: :unprocessable_entity } end end end # PATCH/PUT /observacionactividadadecuacions/1 # PATCH/PUT /observacionactividadadecuacions/1.json def update respond_to do |format| if @observacionactividadadecuacion.update(observacionactividadadecuacion_params) format.html { redirect_to @observacionactividadadecuacion, notice: 'Observacionactividadadecuacion was successfully updated.' } format.json { render :show, status: :ok, location: @observacionactividadadecuacion } else format.html { render :edit } format.json { render json: @observacionactividadadecuacion.errors, status: :unprocessable_entity } end end end # DELETE /observacionactividadadecuacions/1 # DELETE /observacionactividadadecuacions/1.json def destroy @observacionactividadadecuacion.destroy respond_to do |format| format.html { redirect_to observacionactividadadecuacions_url, notice: 'Observacionactividadadecuacion was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_observacionactividadadecuacion @observacionactividadadecuacion = Observacionactividadadecuacion.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def observacionactividadadecuacion_params params.require(:observacionactividadadecuacion).permit(:id, :revisionId, :adecuacionActividadId, :observacion, :fecha) end end <file_sep>/forminst_new1/app/controllers/adecuacionactividads_controller.rb class AdecuacionactividadsController < ApplicationController before_action :set_adecuacionactividad, only: [:show, :edit, :update, :destroy] # GET /adecuacionactividads # GET /adecuacionactividads.json def index @adecuacionactividads = Adecuacionactividad.all end # GET /adecuacionactividads/1 # GET /adecuacionactividads/1.json def show end # GET /adecuacionactividads/new def new @adecuacionactividad = Adecuacionactividad.new end # GET /adecuacionactividads/1/edit def edit end # POST /adecuacionactividads # POST /adecuacionactividads.json def create @adecuacionactividad = Adecuacionactividad.new(adecuacionactividad_params) respond_to do |format| if @adecuacionactividad.save format.html { redirect_to @adecuacionactividad, notice: 'Adecuacionactividad was successfully created.' } format.json { render :show, status: :created, location: @adecuacionactividad } else format.html { render :new } format.json { render json: @adecuacionactividad.errors, status: :unprocessable_entity } end end end # PATCH/PUT /adecuacionactividads/1 # PATCH/PUT /adecuacionactividads/1.json def update respond_to do |format| if @adecuacionactividad.update(adecuacionactividad_params) format.html { redirect_to @adecuacionactividad, notice: 'Adecuacionactividad was successfully updated.' } format.json { render :show, status: :ok, location: @adecuacionactividad } else format.html { render :edit } format.json { render json: @adecuacionactividad.errors, status: :unprocessable_entity } end end end # DELETE /adecuacionactividads/1 # DELETE /adecuacionactividads/1.json def destroy @adecuacionactividad.destroy respond_to do |format| format.html { redirect_to adecuacionactividads_url, notice: 'Adecuacionactividad was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_adecuacionactividad @adecuacionactividad = Adecuacionactividad.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def adecuacionactividad_params params.require(:adecuacionactividad).permit(:id, :adecuacionId, :actividadId, :anulada, :semestre) end end <file_sep>/forminst_new1/test/controllers/entidads_controller_test.rb require 'test_helper' class EntidadsControllerTest < ActionController::TestCase setup do @entidad = entidads(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:entidads) end test "should get new" do get :new assert_response :success end test "should create entidad" do assert_difference('Entidad.count') do post :create, entidad: { escuelaId: @entidad.escuelaId, id: @entidad.id, nombre: @entidad.nombre } end assert_redirected_to entidad_path(assigns(:entidad)) end test "should show entidad" do get :show, id: @entidad assert_response :success end test "should get edit" do get :edit, id: @entidad assert_response :success end test "should update entidad" do patch :update, id: @entidad, entidad: { escuelaId: @entidad.escuelaId, id: @entidad.id, nombre: @entidad.nombre } assert_redirected_to entidad_path(assigns(:entidad)) end test "should destroy entidad" do assert_difference('Entidad.count', -1) do delete :destroy, id: @entidad end assert_redirected_to entidads_path end end <file_sep>/forminst_new1/config/routes.rb Rails.application.routes.draw do resources :documents post 'iniciotutor/ver_detalles_plan', to: 'iniciotutor#ver_detalles_plan' get 'adecuacions/descargar_pdf', to: 'adecuacions#descargar_pdf' get ':controller(/:action(/:id(.:format)))' post ':controller(/:action(/:id(.:format)))' root 'forminst#index' resources :resumes, only: [:index, :new, :create, :destroy] root "resumes#index" end <file_sep>/forminst_new1/app/models/estatus_informe.rb class EstatusInforme < ActiveRecord::Base belongs_to :informe belongs_to :tipo_estatus end <file_sep>/forminst_new1/app/models/tiporesultado.rb class Tiporesultado < ActiveRecord::Base belongs_to :tipoactividad has_one :resultado end <file_sep>/forminst_new1/app/views/usuarios/show.json.jbuilder json.extract! @usuario, :id, :id, :user, :ldap, :activo, :password, :email, :created_at, :updated_at <file_sep>/forminst_new1/app/views/observaciontutors/index.json.jbuilder json.array!(@observaciontutors) do |observaciontutor| json.extract! observaciontutor, :id, :id, :informeActividadId, :observacion, :fecha, :actual json.url observaciontutor_url(observaciontutor, format: :json) end <file_sep>/forminst_new1/app/views/informeactividads/show.json.jbuilder json.extract! @informeactividad, :id, :id, :informeId, :actividadId, :created_at, :updated_at <file_sep>/forminst_new1/app/models/revision.rb class Revision < ActiveRecord::Base belongs_to :tipo_estatus belongs_to :informe has_many :observacion_actividadad_adecuacion belongs_to :adecuacion has_many :observacion_actividad_informe end<file_sep>/forminst_new1/app/views/escuelas/show.json.jbuilder json.extract! @escuela, :id, :id, :nombre, :created_at, :updated_at <file_sep>/forminst_new1/app/models/entidad.rb class Entidad < ActiveRecord::Base belongs_to :usuario belongs_to :escuela has_many :usuarioentidad end<file_sep>/forminst_new1/app/controllers/firmas_controller.rb class DocumentsController < ApplicationController layout 'ly_inicio_tutor' before_action :set_document, only: [:show, :edit, :update, :destroy] # GET /documents # GET /documents.json def index if session[:usuario_id] && session[:tutor] @plan = Planformacion.where(id: session[:plan_id]).take @documents = [] if !session[:informe_id].blank? @documents = Document.where(adecuacion_id: session[:adecuacion_id], informe_id: session[:informe_id]).all else @documents = Document.where(adecuacion_id: session[:adecuacion_id], informe_id: nil).all end else redirect_to controller:"forminst", action: "index" end end # GET /documents/1 # GET /documents/1.json def show send_data(@document.file_contents, type: @document.content_type, filename: @document.filename) end # GET /documents/new def new @bool_enviado = 0 @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take if session[:informe_id].blank? estatus_x = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take else estatus_x = EstatusInforme.where(informe_id: session[:informe_id], actual: 1).take end if (estatus_x.estatus_id != 6 && estatus_x.estatus_id != 5) @bool_enviado = 1 end if ( @bool_enviado == 1) flash.now[:info]="No puede aรฑadir soportes, ya ha enviado la adecuaciรณn" else @document = Document.new end end # GET /documents/1/edit def edit end # POST /documents # POST /documents.json def create if session[:usuario_id] && session[:tutor] if params[:document].present? @document = Document.new(document_params) @planformacion = Planformacion.find(session[:plan_id]) @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take @document.instructor_id = @planformacion.instructor_id @document.tutor_id = session[:usuario_id] @document.adecuacion_id = @adecuacion.id @document.informe_id = session[:informe_id] if @document.save flash[:success]="El documento se ha subido con exito" redirect_to controller:"documents", action: "index" else flash[:danger]="El documento no se ha cargado, recuerde que debe pesar menos de 1MB" redirect_to controller:"documents", action: "new" end else flash[:info]="Debe seleccionar un archivo antes de cargar" redirect_to controller:"documents", action: "new" end else redirect_to controller:"forminst", action: "index" end end # PATCH/PUT /documents/1 # PATCH/PUT /documents/1.json def update respond_to do |format| if @document.update(document_params) format.html { redirect_to @document, notice: 'Document was successfully updated.' } format.json { render :show, status: :ok, location: @document } else format.html { render :edit } format.json { render json: @document.errors, status: :unprocessable_entity } end end end # DELETE /documents/1 # DELETE /documents/1.json def destroy @document.destroy respond_to do |format| flash[:success]="El documento fue borrado con exito" format.html { redirect_to documents_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_document @document = Document.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def document_params params.require(:document).permit(:file) end end <file_sep>/forminst_new1/app/views/escuelas/index.json.jbuilder json.array!(@escuelas) do |escuela| json.extract! escuela, :id, :id, :nombre json.url escuela_url(escuela, format: :json) end <file_sep>/forminst_new1/app/controllers/informes_controller.rb class InformesController < ApplicationController layout 'ly_inicio_tutor' def ver_crear_informe @ejecutada = 'ejecutada' @observacion = 'observacion' if session[:usuario_id] && session[:tutor] @informes= Informe.where(planformacion_id: session[:plan_id],numero: params[:informe_id]).take if [email protected]? flash[:danger]= "Este informe ya fue creado" redirect_to controller:"informes", action: "listar_informes" else if session[:adecuacion_id] @adecuacion= Adecuacion.find(session[:adecuacion_id]) esta = EstatusAdecuacion.where(adecuacion_id: session[:adecuacion_id], actual: 1).take if esta.estatus_id == 6 flash[:danger]= "La adecuaciรณn debe ser enviada/aprobada para poder crear algun informe" redirect_to controller:"informes", action: "listar_informes" end @actividadesa= [] @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @actividadesaobli= [] @actividadesadocejec = [] @actividadesainvejec = [] @actividadesaextejec = [] @actividadesaforejec = [] @actividadesaotrejec = [] @fecha_inicio1 = nil @fecha_fin1 = nil numero_informe = params[:informe_id].to_i if numero_informe == 1 || numero_informe == 2 || numero_informe == 4 || numero_informe == 5 # Si el informe es alguno semestral if(numero_informe == 1) @nombre_informe = "PRIMER SEMESTRAL" @tipo_informe=1 @numero_informe=1 @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all elsif(numero_informe == 2) @nombre_informe = "<NAME>" @tipo_informe=2 @numero_informe=2 @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all elsif(numero_informe == 4) @nombre_informe = "<NAME>" @tipo_informe=4 @numero_informe=4 @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all elsif(numero_informe == 5) @nombre_informe = "<NAME>" @tipo_informe=5 @numero_informe=5 @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all end @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) end end elsif params[:informe_id].to_i ==3 # Si el informe es el primer anual puts "HELLLOOOOOO" @nombre_informe = "<NAME>" @tipo_informe=3 @numero_informe=3 informe1 = Informe.where( planformacion_id: session[:plan_id], numero: 1).take informe2 = Informe.where( planformacion_id: session[:plan_id], numero: 2).take if informe1.blank? || informe2.blank? flash[:danger] = "Debe crear primero el primer y segundo informe semestral " redirect_to controller:"informes", action: "listar_informes" return 0 end @fecha_inicio1 = informe1.fecha_inicio @fecha_fin1 = informe2.fecha_fin @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: [1,2]).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) begin @actividadesi= InformeActividad.where(actividad_id: actade.actividad_id).take @actinf= ActividadEjecutada.where(informe_actividad_id: @actividadesi.id).take rescue => ex @actinf= [] end tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) @actividadesadocejec.push(@actinf) elsif tipo==2 @actividadesainv.push(@act) @actividadesainvejec.push(@actinf) elsif tipo==3 @actividadesaext.push(@act) @actividadesaextejec.push(@actinf) elsif tipo==4 @actividadesafor.push(@act) @actividadesaforejec.push(@actinf) elsif tipo==5 @actividadesaotr.push(@act) if(@actinf.blank?) @actividadesaotrejec.push([]) else @actividadesaotrejec.push(@actinf) end end end elsif params[:informe_id].to_i ==6 # Si el informe es el segundo anual @nombre_informe = "SEGUNDO ANUAL" @tipo_informe=6 @numero_informe=6 informe1 = Informe.where( planformacion_id: session[:plan_id], numero: 4).take informe2 = Informe.where( planformacion_id: session[:plan_id], numero: 5).take if informe1.blank? || informe2.blank? flash[:danger] = "Debe crear primero el tercer y cuarto informe semestral " redirect_to controller: "informes", action: "listar_informes" return 0 end @fecha_inicio1 = informe1.fecha_inicio @fecha_fin1 = informe2.fecha_fin @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: [3,4]).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id begin @actividadesi= InformeActividad.where(actividad_id: actade.actividad_id).take @actinf= ActividadEjecutada.where(informe_actividad_id: @actividadesi.id).take rescue => ex @actividadesi= [] @actinf= [] end if tipo==1 @actividadesadoc.push(@act) @actividadesadocejec.push(@actinf) elsif tipo==2 @actividadesainv.push(@act) @actividadesainvejec.push(@actinf) elsif tipo==3 @actividadesaext.push(@act) @actividadesaextejec.push(@actinf) elsif tipo==4 @actividadesafor.push(@act) @actividadesaforejec.push(@actinf) elsif tipo==5 @actividadesaotr.push(@act) if(@actinf.blank?) @actividadesaotrejec.push([]) else @actividadesaotrejec.push(@actinf) end end end elsif params[:informe_id].to_i ==7 # Si el informe es el final @nombre_informe = "PRIMER FINAL" @tipo_informe=7 @numero_informe=7 informe1 = Informe.where( planformacion_id: session[:plan_id], numero: 3).take informe2 = Informe.where( planformacion_id: session[:plan_id], numero: 6).take if informe1.blank? || informe2.blank? flash[:danger] = "Debe crear primero el primer y segundo informe anual " redirect_to controller: "informes", action: "listar_informes" return 0 end @fecha_inicio1 = informe1.fecha_inicio @fecha_fin1 = informe2.fecha_fin puts @adecuacion.id @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: [1,2,3,4]).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id puts actade.actividad_id begin @actividadesi= InformeActividad.where(actividad_id: actade.actividad_id).take @actinf= ActividadEjecutada.where(informe_actividad_id: @actividadesi.id).take rescue => ex @actividadesi= [] @actinf= [] end if tipo==1 @actividadesadoc.push(@act) @actividadesadocejec.push(@actinf) elsif tipo==2 @actividadesainv.push(@act) @actividadesainvejec.push(@actinf) elsif tipo==3 @actividadesaext.push(@act) @actividadesaextejec.push(@actinf) elsif tipo==4 @actividadesafor.push(@act) @actividadesaforejec.push(@actinf) elsif tipo==5 @actividadesaotr.push(@act) if(@actinf.blank?) @actividadesaotrejec.push([]) else @actividadesaotrejec.push(@actinf) end elsif tipo==7 @actividadesaobli.push(@act) end end else flash[:danger]= "Ya completo el numero de informes, no puede crear mรกs" redirect_to controller:"informes", action: "listar_informes" end @mes= ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'] @dia= [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,29,30,31] @tipos= [['Libros',1], ['Artรญculo de Revista',2], ['Artรญculo de Prensa',3], ['CD',4], ['Manuales',5], ['Publicaciones Electrรณnicas',6]] else flash[:warning]= "Error, no hay sesion de adecuacion" redirect_to controller:"iniciotutor", action: "ver_detalles_adecuacion" end end else redirect_to controller:"forminst", action: "index" end end def eliminar_informe if !session[:informe_id].blank? @informe= Informe.find(session[:informe_id]) @est= EstatusInforme.where(informe_id: @informe.id, actual: 1).take if @est.estatus_id == 6 @documents = Document.where(adecuacion_id: session[:adecuacion_id], informe_id: session[:informe_id]).all @documents.each do |documents| documents.destroy end @informesAct = InformeActividad.where(informe_id: session[:informe_id]).all @informesAct.each do |informeAct| @actividadEjec= ActividadEjecutada.where(informe_actividad_id: informeAct.id).take if [email protected]? @actividadEjec.destroy end informeAct.destroy end @informe.destroy flash[:success]= "El informe fue eliminado correctamente" else flash[:danger]= "No estรก permitido eliminar este informe" end else flash[:info]= "Seleccione un informe" end redirect_to controller:"informes", action: "listar_informes" end def detalles_informe2 if session[:usuario_id] && session[:tutor] @nombre = session[:nombre_usuario] @CJagregado = ["no","no","no","no"] if not @nombre print "NO HAY USUARIO" end @persona = Persona.where(usuario_id: session[:usuario_id]).take if session[:plan_id] @planformacion = Planformacion.find(session[:plan_id]) else @planformacion = Planformacion.find(session[:plan_id]) end if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@planformacion.instructor_id) if (cpInstructor.activo == 0) @cpBloquear = true else @cpBloquear = false end #fin end if session[:informe_id] @informe= Informe.find(session[:informe_id]) @estatus= EstatusInforme.where(informe_id: @informe.id, actual: 1).take @status= TipoEstatus.find(@estatus.estatus_id) @est= EstatusInforme.where(informe_id: @informe.id).take @numero_informe = @informe.numero @fecha1 = @informe.fecha_inicio @fecha2 = @informe.fecha_fin @modificar= false if @est.estatus_id == 6 @modificar=true end @docencia= "docencia" @j= 0 @k=0 @actividadesa= InformeActividad.where(informe_id: @informe.id).all @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @actividadesaobli= [] @semestres=[] @resultados= [] @resultados2= "" @resultados2a= [] @resultados2b= [] @actividadese= [] @observaciont= [] @observacionesExtras = [] @bool_enviado = 0 if (@estatus.estatus_id != 6 && @estatus.estatus_id != 5) @bool_enviado = 1 end @actividadesa.each do |actade| if actade.actividad_id == nil #Es el caso que es un resultado no contemplado en el plan de formacion o un avancwe de postgrado if @bool_enviado == 0 @res= Resultado.where(informe_actividad_id: actade.id).all @resultados.push(@res) else if @resultados2b != [] @resultados2b= Array.new(0) { |i| } end @res= Resultado.where(informe_actividad_id: actade.id).all @resultados.push(@res) @res.each do |cpresultado| @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = cpresultado.titulo @cparray[1] = cpresultado.autor @cparray[2] = cpresultado.nombre_capitulo @cparray[3] = cpresultado.autor_capitulo @cparray[4] = cpresultado.dia @cparray[5] = cpresultado.mes @cparray[6] = cpresultado.ano @cparray[7] = cpresultado.ciudad @cparray[8] = cpresultado.estado @cparray[9] = cpresultado.pais @cparray[10] = cpresultado.organizador @cparray[11] = cpresultado.duracion @cparray[12] = cpresultado.editor @cparray[13] = cpresultado.titulo_libro @cparray[14] = cpresultado.autor_libro @cparray[15] = cpresultado.nombre_revista @cparray[16] = cpresultado.nombre_periodico @cparray[17] = cpresultado.nombre_acto @cparray[18] = cpresultado.paginas @cparray[19] = cpresultado.nombre_paginaw @cparray[20] = cpresultado.sitio_paginaw @cparray[21] = cpresultado.infoafiliaion @cparray[22] = cpresultado.cptipo @cparray[23] = cpresultado.nombre @cparray[24] = cpresultado.ISSN_impreso @cparray[25] = cpresultado.ISSN_electro @cparray[26] = cpresultado.volumen @cparray[27] = cpresultado.edicion @cparray[28] = cpresultado.DOI @cparray[29] = cpresultado.ISBN @cparray[30] = cpresultado.universidad @cparray[31] = cpresultado.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @noemptyarray.join(',') end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @noemptyarray.join(',') end end @resultados2b.push(@resultados2) end end @resultados2a.push(@resultados2b) end else @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if @bool_enviado == 0 @res= Resultado.where(informe_actividad_id: actade.id).all @resultados.push(@res) else if @resultados2b != [] @resultados2b= Array.new(0) { |i| } end @res= Resultado.where(informe_actividad_id: actade.id).all @resultados.push(@res) @res.each do |cpresultado| @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = cpresultado.titulo @cparray[1] = cpresultado.autor @cparray[2] = cpresultado.nombre_capitulo @cparray[3] = cpresultado.autor_capitulo @cparray[4] = cpresultado.dia @cparray[5] = cpresultado.mes @cparray[6] = cpresultado.ano @cparray[7] = cpresultado.ciudad @cparray[8] = cpresultado.estado @cparray[9] = cpresultado.pais @cparray[10] = cpresultado.organizador @cparray[11] = cpresultado.duracion @cparray[12] = cpresultado.editor @cparray[13] = cpresultado.titulo_libro @cparray[14] = cpresultado.autor_libro @cparray[15] = cpresultado.nombre_revista @cparray[16] = cpresultado.nombre_periodico @cparray[17] = cpresultado.nombre_acto @cparray[18] = cpresultado.paginas @cparray[19] = cpresultado.nombre_paginaw @cparray[20] = cpresultado.sitio_paginaw @cparray[21] = cpresultado.infoafiliaion @cparray[22] = cpresultado.cptipo @cparray[23] = cpresultado.nombre @cparray[24] = cpresultado.ISSN_impreso @cparray[25] = cpresultado.ISSN_electro @cparray[26] = cpresultado.volumen @cparray[27] = cpresultado.edicion @cparray[28] = cpresultado.DOI @cparray[29] = cpresultado.ISBN @cparray[30] = cpresultado.universidad @cparray[31] = cpresultado.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @noemptyarray.join(',') end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @noemptyarray.join(',') end end @resultados2b.push(@resultados2) end end @resultados2a.push(@resultados2b) end @ae= ActividadEjecutada.where(informe_actividad_id: actade.id).take @actividadese.push(@ae) @obs= ObservacionTutor.where(informe_actividad_id: actade.id).take if @obs==nil @observaciont.push("") @cpObs= ObservacionActividadInforme.where(informe_actividad_id: actade.id).all if @cpObs.blank? @observacionesExtras.push("no") else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras.push("no") else @observacionesExtras.push("si") end end else @observaciont.push(@obs.observaciones) @cpObs= ObservacionActividadInforme.where(informe_actividad_id: actade.id).all if @cpObs.blank? @observacionesExtras.push("no") else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras.push("no") else @observacionesExtras.push("si") end end end semestre = AdecuacionActividad.where(actividad_id: @act.id).take.semestre @semestres[@act.id]=semestre if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) elsif tipo==7 @actividadesaobli.push(@act) end end end else flash[:warning]= "Error, no hay sesion de adecuacion" redirect_to controller:"iniciotutor", action: "ver_detalles_adecuacion" end else redirect_to controller:"forminst", action: "index" end end def vista_previa if (session[:informe_id] && session[:tutor] && session[:informe_id]) if(!session[:plan_id].blank?) @informe= Informe.find(session[:informe_id]) @TipoSemestre=TipoInforme.where(id: @informe.tipo_id).take @fechaActual = Date.current.to_s @plan= Planformacion.find(session[:plan_id]) @nombre_informe = "" if (@informe.numero == 1 || @informe.numero == 3) @nombre_informe= "<NAME> " elsif (@informe.numero == 2 || @informe.numero == 6) @nombre_informe= "SEGUNDO INFORME " elsif @informe.numero == 4 @nombre_informe= "<NAME> " elsif @informe.numero == 5 @nombre_informe= "CUARTO INFORME " end if @informe.tipo_id == 1 @nombre_informe= @nombre_informe+"SEMESTRAL" elsif @informe.tipo_id == 2 @nombre_informe= @nombre_informe+"ANUAL" else @nombre_informe= "INFORME "+"FINAL" end if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@plan.instructor_id) if (cpInstructor.activo == 0) @cpBloquear = true else @cpBloquear = false end #fin end @fechaConcurso = @plan.fecha_inicio @usere= Usuarioentidad.where(usuario_id: @plan.instructor_id).take @escuela= Escuela.find(@usere.escuela_id) @adecuacion= Adecuacion.where(planformacion_id: @plan.id).take @adscripcion_docencia= @plan.adscripcion_docencia @adscripcion_investigacion= @plan.adscripcion_investigacion @persona= Persona.where(usuario_id: @plan.instructor_id).take @cpinstruccion = @persona.grado_instruccion @user = Usuario.find(@plan.instructor_id) @tutor = Persona.where(usuario_id: session[:usuario_id]).take @docencia='docencia' @investigacion= 'investigacion' @obligatoria= 'obligatoria' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] actividades = AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0) actividades1 = [] if !actividades.blank? actividades.each do |actividadAde| actividad = Actividad.find(actividadAde.actividad_id) actividades1.push(actividad) end end @presentacion = "" @descripcion = "" @docencia = [] @investigacion = [] @formacion = [] @extension = [] if !actividades1.blank? puts "entroooo" actividades1.each do |actividadAde| if actividadAde.tipo_actividad_id == 9 if actividadAde.actividad.blank? @presentacion = " " else @presentacion = actividadAde.actividad end elsif actividadAde.tipo_actividad_id == 8 if actividadAde.actividad.blank? @descripcion = " " else @descripcion = actividadAde.actividad end elsif actividadAde.tipo_actividad_id == 1 if actividadAde.actividad.blank? @docencia.push(" ") else @docencia.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 2 if actividadAde.actividad.blank? @investigacion.push(" ") else @investigacion.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 4 if actividadAde.actividad.blank? @formacion.push(" ") else @formacion.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 3 if actividadAde.actividad.blank? @extension.push(" ") else @extension.push(actividadAde) end end end else @presentacion = " " @descripcion = " " @docencia = [" "] @investigacion = [" "] @formacion = [" "] @extension = [" "] end @periodo = @informe.fecha_inicio.to_s + " al " + @informe.fecha_fin.to_s @actividades1doc= [] @actividades1inv= [] @actividades1ext= [] @actividades1for= [] @actividades1otr= [] @actividades1= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividades1.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades1doc.push(@act) else if tipo==2 if @informe.numero == 1 @resActi= InformeActividad.where(informe_id: @informe.id, actividad_id: @act.id).take @res= Resultado.where(informe_actividad_id: @resActi.id).all end @actividades1inv.push(@act) else if tipo==3 @actividades1ext.push(@act) else if tipo==4 @actividades1for.push(@act) else if tipo==5 @actividades1otr.push(@act) end end end end end end @actividades2doc= [] @actividades2inv= [] @actividades2ext= [] @actividades2for= [] @actividades2otr= [] @actividades2= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @actividades2.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades2doc.push(@act) else if tipo==2 @actividades2inv.push(@act) else if tipo==3 @actividades2ext.push(@act) else if tipo==4 @actividades2for.push(@act) else if tipo==5 @actividades2otr.push(@act) end end end end end end @actividades3doc= [] @actividades3inv= [] @actividades3ext= [] @actividades3for= [] @actividades3otr= [] @actividades3= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all @actividades3.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades3doc.push(@act) else if tipo==2 @actividades3inv.push(@act) else if tipo==3 @actividades3ext.push(@act) else if tipo==4 @actividades3for.push(@act) else if tipo==5 @actividades3otr.push(@act) end end end end end end @actividades4doc= [] @actividades4inv= [] @actividades4ext= [] @actividades4for= [] @actividades4otr= [] @actividades4= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all @actividades4.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades4doc.push(@act) else if tipo==2 @actividades4inv.push(@act) else if tipo==3 @actividades4ext.push(@act) else if tipo==4 @actividades4for.push(@act) else if tipo==5 @actividades4otr.push(@act) end end end end end end @actividades5doc= [] @actividades5inv= [] @actividades5ext= [] @actividades5for= [] @actividades5otr= [] @actividades5= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 5).all @actividades5.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades5doc.push(@act) elsif tipo==2 @actividades5inv.push(@act) elsif tipo==3 @actividades5ext.push(@act) elsif tipo==4 @actividades5for.push(@act) elsif tipo==5 @actividades5otr.push(@act) end end @bool_enviado = 0 estatus_informe = EstatusInforme.where(informe_id: @informe.id, actual: 1).take if (estatus_informe.estatus_id != 6 && estatus_informe.estatus_id != 5) @bool_enviado = 1 end @j = 0 @i = 0 @actividadesa= InformeActividad.where(informe_id: @informe.id).all @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaobli= [] @actividadesaotr= [] @resultados= [] @semestres= [] @CJagregado=["no","no","no","no"] @actividadese= [] @observaciont= [] @resultTP = [] @resultPP = [] @resultPIT = [] @resultO = [] @resultAEC = [] @resultOEC = [] @resultDCS = [] @actividadesa.each do |actade| @resultados2 = "" @res= Resultado.where(informe_actividad_id: actade.id).all if actade.actividad_id == nil #Es el caso que es un resultado no contemplado en el plan de formacion o un avancwe de postgrado if [email protected]? @res.each do |res| @resultados2 = "" @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a","a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = res.titulo.capitalize @cparray[1] = res.autor.capitalize @cparray[2] = res.nombre_capitulo.to_s.capitalize @cparray[3] = res.autor_capitulo.to_s.capitalize @cparray[4] = res.dia @cparray[5] = res.mes @cparray[6] = res.ano @cparray[7] = res.ciudad.to_s.capitalize @cparray[8] = res.estado.to_s.capitalize @cparray[9] = res.pais.to_s.capitalize @cparray[10] = res.organizador.to_s.capitalize @cparray[11] = res.duracion.to_s.capitalize @cparray[12] = res.editor.to_s.capitalize @cparray[13] = res.titulo_libro.to_s.capitalize @cparray[14] = res.autor_libro.to_s.capitalize @cparray[15] = res.nombre_revista.to_s.capitalize @cparray[16] = res.nombre_periodico.to_s.capitalize @cparray[17] = res.nombre_acto.to_s.capitalize @cparray[18] = res.paginas @cparray[19] = res.nombre_paginaw.to_s.capitalize @cparray[20] = res.sitio_paginaw @cparray[21] = res.infoafiliaion.to_s.capitalize @cparray[22] = res.cptipo.to_s.capitalize @cparray[23] = res.nombre.to_s.capitalize @cparray[24] = res.ISSN_impreso.to_s.capitalize @cparray[25] = res.ISSN_electro.to_s.capitalize @cparray[26] = res.volumen.to_s.capitalize @cparray[27] = res.edicion.to_s.capitalize @cparray[28] = res.DOI @cparray[29] = res.ISBN @cparray[30] = res.universidad.to_s.capitalize @cparray[31] = res.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = "* " + @noemptyarray end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @resultados2 + @noemptyarray.join(', ') end end end if res.tipo_resultado_id == 1 @resultTP.push(@resultados2) elsif res.tipo_resultado_id == 2 @resultPP.push(@resultados2) elsif res.tipo_resultado_id == 3 @resultPIT.push(@resultados2) elsif res.tipo_resultado_id == 4 @resultO.push(@resultados2) elsif res.tipo_resultado_id == 5 @resultAEC.push(@resultados2) elsif res.tipo_resultado_id == 6 @resultOEC.push(@resultados2) elsif res.tipo_resultado_id == 7 @resultDCS.push(@resultados2) end @resultados.push(res) end end else @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if [email protected]? @res.each do |res| @resultados2 = "" @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a","a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = res.titulo.capitalize @cparray[1] = res.autor.capitalize @cparray[2] = res.nombre_capitulo.to_s.capitalize @cparray[3] = res.autor_capitulo.to_s.capitalize @cparray[4] = res.dia @cparray[5] = res.mes @cparray[6] = res.ano @cparray[7] = res.ciudad.to_s.capitalize @cparray[8] = res.estado.to_s.capitalize @cparray[9] = res.pais.to_s.capitalize @cparray[10] = res.organizador.to_s.capitalize @cparray[11] = res.duracion.to_s.capitalize @cparray[12] = res.editor.to_s.capitalize @cparray[13] = res.titulo_libro.to_s.capitalize @cparray[14] = res.autor_libro.to_s.capitalize @cparray[15] = res.nombre_revista.to_s.capitalize @cparray[16] = res.nombre_periodico.to_s.capitalize @cparray[17] = res.nombre_acto.to_s.capitalize @cparray[18] = res.paginas @cparray[19] = res.nombre_paginaw.to_s.capitalize @cparray[20] = res.sitio_paginaw @cparray[21] = res.infoafiliaion.to_s.capitalize @cparray[22] = res.cptipo.to_s.capitalize @cparray[23] = res.nombre.to_s.capitalize @cparray[24] = res.ISSN_impreso.to_s.capitalize @cparray[25] = res.ISSN_electro.to_s.capitalize @cparray[26] = res.volumen.to_s.capitalize @cparray[27] = res.edicion.to_s.capitalize @cparray[28] = res.DOI @cparray[29] = res.ISBN @cparray[30] = res.universidad.to_s.capitalize @cparray[31] = res.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = "* " + @noemptyarray end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @resultados2 + @noemptyarray.join(', ') end end end if res.tipo_resultado_id == 1 @resultTP.push(@resultados2) elsif res.tipo_resultado_id == 2 @resultPP.push(@resultados2) elsif res.tipo_resultado_id == 3 @resultPIT.push(@resultados2) elsif res.tipo_resultado_id == 4 @resultO.push(@resultados2) elsif res.tipo_resultado_id == 5 @resultAEC.push(@resultados2) elsif res.tipo_resultado_id == 6 @resultOEC.push(@resultados2) elsif res.tipo_resultado_id == 7 @resultDCS.push(@resultados2) end @resultados.push(res) end end end @ae= ActividadEjecutada.where(informe_actividad_id: actade.id).take @actividadese.push(@ae) @obs= ObservacionTutor.where(informe_actividad_id: actade.id).take if @obs==nil @observaciont.push("") else @observaciont.push(@obs.observaciones) end semestre = AdecuacionActividad.where(actividad_id: @act.id).take.semestre @semestres[@act.id]=semestre if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) elsif tipo==7 @actividadesaobli.push(@act) end end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else flash[:info]= "Seleccione un informe" redirect_to controller:"informes", action: "listar_informes" end end def ver_detalles_informe if session[:usuario_id] && session[:tutor] if(!session[:plan_id].blank?) @nombre = session[:nombre_usuario] @persona = Persona.where(usuario_id: session[:usuario_id]).take if session[:plan_id] @planformacion = Planformacion.find(session[:plan_id]) else @planformacion = Planformacion.find(session[:plan_id]) end if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@planformacion.instructor_id) if (cpInstructor.activo == 0) @cpBloquear = true else @cpBloquear = false end #fin end if params[:informe_id] session[:informe_id] = params[:informe_id] end if session[:informe_id] @instructor = Persona.where(usuario_id: @planformacion.instructor_id).take @informe= Informe.find(session[:informe_id]) #Anual if @informe.numero ==3 begin @informe.fecha_inicio = Informe.where( planformacion_id: session[:plan_id], numero: 1).take.fecha_inicio @informe.fecha_fin = Informe.where( planformacion_id: session[:plan_id], numero: 2).take.fecha_fin @informe.save rescue => ex @informe.fecha_inicio = "-" @informe.fecha_fin = "-" @informe.save flash[:danger]= "Usted ha eliminado un informe utilizado por este, por favor proceda a eliminar este" end end #Anual if @informe.numero ==6 begin @informe.fecha_inicio = Informe.where( planformacion_id: session[:plan_id], numero: 4).take.fecha_inicio @informe.fecha_fin = Informe.where( planformacion_id: session[:plan_id], numero: 5).take.fecha_fin @informe.save rescue => ex @informe.fecha_inicio = "-" @informe.fecha_fin = "-" @informe.save flash[:danger]= "Usted ha eliminado un informe utilizado por este, por favor proceda a eliminar este" end end #Anual if @informe.numero ==7 begin @informe.fecha_inicio = Informe.where( planformacion_id: session[:plan_id], numero: 1).take.fecha_inicio @informe.fecha_fin = Informe.where( planformacion_id: session[:plan_id], numero: 4).take.fecha_fin @informe.save rescue => ex @informe.fecha_inicio = "-" @informe.fecha_fin = "-" @informe.save flash[:danger]= "Usted ha eliminado un informe utilizado por este, por favor proceda a eliminar este" end end @periodo = @informe.fecha_inicio.to_s + " al " + @informe.fecha_fin.to_s @estatus= EstatusInforme.where(informe_id: @informe.id, actual: 1).take @status= TipoEstatus.find(@estatus.estatus_id) if (@informe.numero == 1 || @informe.numero == 3) @nombre_informe= "Primer Informe " session[:numero_informe]=1 elsif (@informe.numero == 2 || @informe.numero == 6) @nombre_informe= "Segundo Informe " session[:numero_informe]=2 elsif @informe.numero == 4 @nombre_informe= "Tercer Informe " session[:numero_informe]=4 elsif @informe.numero == 5 @nombre_informe= "Cuarto Informe " session[:numero_informe]=5 end if @informe.tipo_id == 1 @nombre_informe= @nombre_informe+"Semestral" else if @informe.tipo_id == 2 @nombre_informe= @nombre_informe+"Anual" else @nombre_informe= "Informe Final" end end @userentidad= Usuarioentidad.where(usuario_id: @planformacion.instructor_id).take @entidad= Entidad.find(@userentidad.entidad_id) @escuela= Escuela.find(@userentidad.escuela_id) session[:nombre_informe] = @nombre_informe session[:status_informe] = @status.concepto @bool_enviado = 0 estatus_informe = EstatusInforme.where(informe_id: @informe.id, actual: 1).take if (estatus_informe.estatus_id != 6 && estatus_informe.estatus_id != 5) @bool_enviado = 1 end else flash[:info]= "Seleccione un informe" redirect_to controller:"informes", action: "listar_informes" end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def crear_informe if session[:usuario_id] && session[:tutor] if(!session[:plan_id].blank?) nombre = session[:nombre_usuario] if not @nombre print "NO HAY USUARIO" end @persona = Persona.where(usuario_id: session[:usuario_id]).take if session[:plan_id] @planformacion = Planformacion.find(session[:plan_id]) else @planformacion = Planformacion.find(session[:plan_id]) end @fecha_inicio = params[:fechaIni] @fecha_fin = params[:fechaFin] @cant_doc= params[:cant_docencia].to_i @cant_inv= params[:cant_investigacion].to_i @cant_for= params[:cant_formacion].to_i @cant_ext= params[:cant_extension].to_i @cant_obli= params[:cant_obligatoria].to_i @cant_otr= params[:cant_otra].to_i @tipo_informe = params[:tipoinf].to_i @numero_informe= params[:numero_informe].to_i if @tipo_informe == 1 || @tipo_informe==2 || @tipo_informe==4 || @tipo_informe==5 @tipo= 1 @nombre_inf= 'Semestral' else if @tipo_informe== 3 || @tipo_informe==6 @tipo=2 @nombre_inf= 'Anual' else @tipo=3 @nombre_inf= 'Final' end end informe = Informe.new informe.planformacion_id = session[:plan_id] informe.tutor_id = session[:usuario_id] informe.opinion_tutor = params[:opinion] informe.conclusiones = params[:conclusiones] informe.justificaciones = params[:justi] informe.tipo_id = @tipo informe.numero = @numero_informe informe.fecha_creacion = Time.now informe.fecha_modificacion = Time.now if (@tipo_informe == 1 || @tipo_informe== 2 || @tipo_informe==4 || @tipo_informe==5) if !params[:fechaIni].blank? informe.fecha_inicio = @fecha_inicio end if !params[:fechaFin].blank? informe.fecha_fin = @fecha_fin end elsif (@tipo_informe == 3) #TIPO SEMESTRAL informe1 = Informe.where( planformacion_id: session[:plan_id], numero: 1).take informe2 = Informe.where( planformacion_id: session[:plan_id], numero: 2).take informe.fecha_inicio = informe1.fecha_inicio informe.fecha_fin = informe2.fecha_fin elsif(@tipo_informe == 6) #TIPO ANUAL informe1 = Informe.where( planformacion_id: session[:plan_id], numero: 4).take informe2 = Informe.where( planformacion_id: session[:plan_id], numero: 5).take informe.fecha_inicio = informe1.fecha_inicio informe.fecha_fin = informe2.fecha_fin elsif(@tipo_informe == 7) #TIPO FINAL informe1 = Informe.where( planformacion_id: session[:plan_id], numero: 1).take informe2 = Informe.where( planformacion_id: session[:plan_id], numero: 5).take informe.fecha_inicio = informe1.fecha_inicio informe.fecha_fin = informe2.fecha_fin end informe.save ei = EstatusInforme.new ei.informe_id = informe.id ei.fecha = Time.now ei.estatus_id = 6 ei.actual = 1 ei.save @estado =EstatusInforme.where(informe_id: informe.id, actual: 1).take informe.estado = @estado.id informe.save #Comienza actividades de docencia j=0 i=:doc.to_s+j.to_s @act = params[i].to_i while j < @cant_doc ia = InformeActividad.new ia.informe_id = informe.id ia.actividad_id = @act ia.save ejecutada =:[email protected]_s ae = ActividadEjecutada.new ae.descripcion = params[ejecutada] ae.fecha = Time.now ae.actual = 1 ae.informe_actividad_id = ia.id ae.save observacion =:[email protected]_s if params[observacion]!=nil && params[observacion]!="" && !params[observacion].blank? oa = ObservacionTutor.new oa.observaciones = params[observacion] oa.fecha = Time.now oa.actual = 1 oa.informe_actividad_id = ia.id oa.save end j= j+1 i=:doc.to_s+j.to_s @act= params[i].to_i end #Comienza actividades de investigacion j=0 i=:inv.to_s+j.to_s @act = params[i].to_i while j < @cant_inv ia = InformeActividad.new ia.informe_id = informe.id ia.actividad_id = @act ia.save ejecutada =:[email protected]_s ae = ActividadEjecutada.new ae.descripcion = params[ejecutada] ae.fecha = Time.now ae.actual = 1 ae.informe_actividad_id = ia.id ae.save observacion =:[email protected]_s if params[observacion]!=nil && params[observacion]!="" && !params[observacion].blank? oa = ObservacionTutor.new oa.observaciones = params[observacion] oa.fecha = Time.now oa.actual = 1 oa.informe_actividad_id = ia.id oa.save end #Guardo los resultados de la actividad cpi = 1 while (!params[:tipo.to_s+cpi.to_s+j.to_s].blank?) @tipo = params[:tipo.to_s+cpi.to_s+j.to_s].to_i @tipo_publicacion = nil @titulo = nil @autor = nil @nombre_capitulo = nil @autor_capitulo = nil @dia = nil @mes = nil @ano = nil @ciudad = nil @estado = nil @pais = nil @organizador = nil @duracion = nil @editor = nil @titulo_libro = nil @autor_libro = nil @nombre_revista = nil @nombre_periodico = nil @paginas = nil @nombre_acto = nil @nombre_paginaw = nil @sitio_paginaw = nil @url = nil @isbm = nil @volumen = nil @edicion = nil @issni = nil @issne = nil @doi = nil @nombre = nil @infoafiliaion = nil @universidad = nil @cptipo = nil # trabajos publicados if (@tipo == 1) @tipo_publicacion = params[:resultado_tipos.to_s+cpi.to_s+j.to_s].to_i # libro if (@tipo_publicacion == 1) @titulo = params[:atitulo.to_s+cpi.to_s+j.to_s] @ciudad = params[:aciudad.to_s+cpi.to_s+j.to_s] @url = params[:aURL.to_s+cpi.to_s+j.to_s] @autor = params[:aautor.to_s+cpi.to_s+j.to_s] @pais = params[:apais.to_s+cpi.to_s+j.to_s] @isbm = params[:aISBM.to_s+cpi.to_s+j.to_s] @editor = params[:aeditor.to_s+cpi.to_s+j.to_s] @ano = params[:aano.to_s+cpi.to_s+j.to_s] # articulo de revista o journals elsif (@tipo_publicacion == 2) @titulo = params[:btitulo.to_s+cpi.to_s+j.to_s] @autor = params[:bautor.to_s+cpi.to_s+j.to_s] @mes = params[:bmes.to_s+cpi.to_s+j.to_s] @ano = params[:bano.to_s+cpi.to_s+j.to_s] @ciudad = params[:bciudad.to_s+cpi.to_s+j.to_s] @estado = params[:bestado.to_s+cpi.to_s+j.to_s] @pais = params[:bpais.to_s+cpi.to_s+j.to_s] @paginas = params[:bnumpaginas.to_s+cpi.to_s+j.to_s] @url = params[:burl.to_s+cpi.to_s+j.to_s] @volumen = params[:bvolumen.to_s+cpi.to_s+j.to_s] @edicion = params[:bnedicion.to_s+cpi.to_s+j.to_s] @issni = params[:bissnimpre.to_s+cpi.to_s+j.to_s] @nombre_revista = params[:brevista.to_s+cpi.to_s+j.to_s] @issne = params[:bissnelec.to_s+cpi.to_s+j.to_s] @doi = params[:bdoi.to_s+cpi.to_s+j.to_s] # articulo de prensa elsif (@tipo_publicacion == 3) @titulo = params[:ctitulo.to_s+cpi.to_s+j.to_s] @autor = params[:cautor.to_s+cpi.to_s+j.to_s] @dia = params[:cdia.to_s+cpi.to_s+j.to_s] @mes = params[:cmes.to_s+cpi.to_s+j.to_s] @ano = params[:cano.to_s+cpi.to_s+j.to_s] @pais = params[:cpais.to_s+cpi.to_s+j.to_s] @nombre_periodico = params[:cnomperi.to_s+cpi.to_s+j.to_s] @paginas = params[:cnumpag.to_s+cpi.to_s+j.to_s] @url = params[:curl.to_s+cpi.to_s+j.to_s] # cd elsif (@tipo_publicacion == 4) @titulo = params[:dtitulo.to_s+cpi.to_s+j.to_s] @autor = params[:dautor.to_s+cpi.to_s+j.to_s] @ano = params[:daรฑo.to_s+cpi.to_s+j.to_s] @ciudad = params[:dciudad.to_s+cpi.to_s+j.to_s] @pais = params[:dpais.to_s+cpi.to_s+j.to_s] @editor = params[:deditor.to_s+cpi.to_s+j.to_s] #manuales elsif (@tipo_publicacion == 5) @titulo = params[:etitulo.to_s+cpi.to_s+j.to_s] @autor = params[:eautor.to_s+cpi.to_s+j.to_s] @mes = params[:emes.to_s+cpi.to_s+j.to_s] @ano = params[:eano.to_s+cpi.to_s+j.to_s] @ciudad = params[:eciudad.to_s+cpi.to_s+j.to_s] @pais = params[:epais.to_s+cpi.to_s+j.to_s] @editor = params[:eeditor.to_s+cpi.to_s+j.to_s] #publicaciones electronicas elsif (@tipo_publicacion == 6) @titulo = params[:ftitulo.to_s+cpi.to_s+j.to_s] @autor = params[:fautor.to_s+cpi.to_s+j.to_s] @nombre = params[:fnombre.to_s+cpi.to_s+j.to_s] @mes = params[:fmes.to_s+cpi.to_s+j.to_s] @ano = params[:fano.to_s+cpi.to_s+j.to_s] @nombre_paginaw = params[:fnompagweb.to_s+cpi.to_s+j.to_s] @sitio_paginaw = params[:fsitioweb.to_s+cpi.to_s+j.to_s] @url = params[:furl.to_s+cpi.to_s+j.to_s] @isbm = params[:fisbn.to_s+cpi.to_s+j.to_s] @doi = params[:fdoi.to_s+cpi.to_s+j.to_s] #tesis elsif (@tipo_publicacion == 7) @titulo = params[:gtitulo.to_s+cpi.to_s+j.to_s] @autor = params[:gautor.to_s+cpi.to_s+j.to_s] @mes = params[:gmes.to_s+cpi.to_s+j.to_s] @ano = params[:gano.to_s+cpi.to_s+j.to_s] @ciudad = params[:gciudad.to_s+cpi.to_s+j.to_s] @pais = params[:gpais.to_s+cpi.to_s+j.to_s] @infoafiliaion = params[:ginfoafiliacion.to_s+cpi.to_s+j.to_s] @universidad = params[:guniversidad.to_s+cpi.to_s+j.to_s] @cptipo = params[:gtipotesis.to_s+cpi.to_s+j.to_s] #acta de conferencia elsif (@tipo_publicacion == 8) @titulo = params[:htitulo.to_s+cpi.to_s+j.to_s] @autor = params[:hautor.to_s+cpi.to_s+j.to_s] @mes = params[:hmes.to_s+cpi.to_s+j.to_s] @ano = params[:hano.to_s+cpi.to_s+j.to_s] @paginas = params[:hpaginas.to_s+cpi.to_s+j.to_s] @isbm = params[:hisbm.to_s+cpi.to_s+j.to_s] @issni = params[:hissn.to_s+cpi.to_s+j.to_s] @doi = params[:hdoi.to_s+cpi.to_s+j.to_s] @nombre = params[:hnombreconf.to_s+cpi.to_s+j.to_s] #capitulo de un libro elsif (@tipo_publicacion == 9) @nombre_capitulo = params[:ititulocapitulo.to_s+cpi.to_s+j.to_s] @autor = params[:iautor.to_s+cpi.to_s+j.to_s] @ano = params[:iano.to_s+cpi.to_s+j.to_s] @titulo_libro = params[:ititulolibro.to_s+cpi.to_s+j.to_s] @paginas = params[:ipaginas.to_s+cpi.to_s+j.to_s] @isbm = params[:iisbn.to_s+cpi.to_s+j.to_s] end #presentaciรณn de potencias elsif (@tipo == 2) @titulo = params[:jtitulo.to_s+cpi.to_s+j.to_s] @autor = params[:jautordoc.to_s+cpi.to_s+j.to_s] @nombre_capitulo = params[:jtitulocapitulo.to_s+cpi.to_s+j.to_s] @autor_capitulo = params[:jautorcap.to_s+cpi.to_s+j.to_s] @dia = params[:jdia.to_s+cpi.to_s+j.to_s] @mes = params[:jmes.to_s+cpi.to_s+j.to_s] @ano = params[:jano.to_s+cpi.to_s+j.to_s] @ciudad = params[:jciudad.to_s+cpi.to_s+j.to_s] @editor = params[:jeditor.to_s+cpi.to_s+j.to_s] @paginas = params[:jnumpag.to_s+cpi.to_s+j.to_s] @nombre = params[:jnombreact.to_s+cpi.to_s+j.to_s] #presentaciรณn informes tecnicos elsif (@tipo == 3) @titulo = params[:ktitulo.to_s+cpi.to_s+j.to_s] @autor = params[:kautordoc.to_s+cpi.to_s+j.to_s] @nombre_capitulo = params[:ktitulocapitulo.to_s+cpi.to_s+j.to_s] @autor_capitulo = params[:kautorcap.to_s+cpi.to_s+j.to_s] @dia = params[:kdia.to_s+cpi.to_s+j.to_s] @mes = params[:kmes.to_s+cpi.to_s+j.to_s] @ano = params[:kano.to_s+cpi.to_s+j.to_s] @ciudad = params[:kciudad.to_s+cpi.to_s+j.to_s] @estado = params[:kestado.to_s+cpi.to_s+j.to_s] @pais = params[:kpais.to_s+cpi.to_s+j.to_s] @organizador = params[:kentidadorg.to_s+cpi.to_s+j.to_s] @editor = params[:keditor.to_s+cpi.to_s+j.to_s] @paginas = params[:knumpag.to_s+cpi.to_s+j.to_s] @nombre_acto = params[:knombreact.to_s+cpi.to_s+j.to_s] #otro elsif (@tipo == 4) @titulo = params[:ltitulo.to_s+cpi.to_s+j.to_s] @autor = params[:lautor.to_s+cpi.to_s+j.to_s] @dia = params[:ldia.to_s+cpi.to_s+j.to_s] @mes = params[:lmes.to_s+cpi.to_s+j.to_s] @ano = params[:laรฑo.to_s+cpi.to_s+j.to_s] @ciudad = params[:lciudad.to_s+cpi.to_s+j.to_s] @editor = params[:leditor.to_s+cpi.to_s+j.to_s] @paginas = params[:lnumpag.to_s+cpi.to_s+j.to_s] @nombre_acto = params[:lnomacto.to_s+cpi.to_s+j.to_s] #asistencia y organizaciรณn de eventos cientificos elsif (@tipo == 5 || @tipo == 6) @titulo = params[:ntitulo.to_s+cpi.to_s+j.to_s] @autor = params[:nautordoc.to_s+cpi.to_s+j.to_s] @nombre_capitulo = params[:ntitulocapitulo.to_s+cpi.to_s+j.to_s] @autor_capitulo = params[:nnombreautor.to_s+cpi.to_s+j.to_s] @dia = params[:ndia.to_s+cpi.to_s+j.to_s] @mes = params[:nmes.to_s+cpi.to_s+j.to_s] @ano = params[:nano.to_s+cpi.to_s+j.to_s] @ciudad = params[:nciudad.to_s+cpi.to_s+j.to_s] @estado = params[:nestado.to_s+cpi.to_s+j.to_s] @pais = params[:npais.to_s+cpi.to_s+j.to_s] @nombre_acto = params[:nnombreacto.to_s+cpi.to_s+j.to_s] #dictado de cursos, talleres, etc elsif (@tipo == 7) @titulo = params[:otitulo.to_s+cpi.to_s+j.to_s] @autor = params[:oautordoc.to_s+cpi.to_s+j.to_s] @nombre_capitulo = params[:otitulocap.to_s+cpi.to_s+j.to_s] @autor_capitulo = params[:oautorcap.to_s+cpi.to_s+j.to_s] @dia = params[:odia.to_s+cpi.to_s+j.to_s] @mes = params[:omes.to_s+cpi.to_s+j.to_s] @ano = params[:oano.to_s+cpi.to_s+j.to_s] @ciudad = params[:ociudad.to_s+cpi.to_s+j.to_s] @estado = params[:oestado.to_s+cpi.to_s+j.to_s] @pais = params[:opais.to_s+cpi.to_s+j.to_s] @organizador = params[:oentidadorg.to_s+cpi.to_s+j.to_s] @duracion = params[:oduracion.to_s+cpi.to_s+j.to_s] @editor = params[:oeditor.to_s+cpi.to_s+j.to_s] @titulo_libro = params[:otitulolib.to_s+cpi.to_s+j.to_s] @autor_libro = params[:oautorref.to_s+cpi.to_s+j.to_s] @paginas = params[:onumpag.to_s+cpi.to_s+j.to_s] end r = Resultado.new r.tipo_resultado_id = @tipo r.tipo_publicacion = @tipo_publicacion r.titulo = @titulo r.autor = @autor r.nombre_capitulo = @nombre_capitulo r.autor_capitulo = @autor_capitulo r.dia = @dia r.mes =@mes r.ano = @ano r.ciudad = @ciudad r.estado = @estado r.pais = @pais r.organizador = @organizador r.duracion = @duracion r.editor = @editor r.titulo_libro = @titulo_libro r.autor_libro = @autor_libro r.nombre_revista = @nombre_revista r.nombre_periodico = @nombre_periodico r.paginas = @paginas r.nombre_acto = @nombre_acto r.nombre_paginaw = @nombre_paginaw r.sitio_paginaw = @sitio_paginaw r.infoafiliaion = @infoafiliaion r.cptipo = @cptipo r.nombre = @nombre r.ISSN_impreso = @issni r.ISSN_electro = @issne r.volumen = @volumen r.edicion = @edicion r.DOI = @doi r.ISBN = @isbm r.universidad = @universidad r.url = @url r.informe_actividad_id = ia.id r.save cpi = cpi+1 end ia.save j= j+1 i=:inv.to_s+j.to_s @act= params[i].to_i end #Comienza actividades de formacion j=0 i=:for.to_s+j.to_s @act = params[i].to_i while j < @cant_for ia = InformeActividad.new ia.informe_id = informe.id ia.actividad_id = @act ia.save ejecutada =:[email protected]_s ae = ActividadEjecutada.new ae.descripcion = params[ejecutada] ae.fecha = Time.now ae.actual = 1 ae.informe_actividad_id = ia.id ae.save observacion =:[email protected]_s if params[observacion]!=nil && params[observacion]!="" && !params[observacion].blank? oa = ObservacionTutor.new oa.observaciones = params[observacion] oa.fecha = Time.now oa.actual = 1 oa.informe_actividad_id = ia.id oa.save end j= j+1 i=:for.to_s+j.to_s @act= params[i].to_i end if params[:postgrado]!=nil && params[:postgrado]!="" rp = Resultado.new rp.tipo_resultado_id = 8 rp.concepto = params[:postgrado] rp.save ia = InformeActividad.new ia.informe_id = informe.id ia.resultado_id = rp.id ia.save end #Comienza actividades de extension j=0 i=:ext.to_s+j.to_s @act = params[i].to_i while j < @cant_ext ia = InformeActividad.new ia.informe_id = informe.id ia.actividad_id = @act ia.save ejecutada =:[email protected]_s ae = ActividadEjecutada.new ae.descripcion = params[ejecutada] ae.fecha = Time.now ae.actual = 1 ae.informe_actividad_id = ia.id ae.save observacion =:[email protected]_s if params[observacion]!=nil && params[observacion]!="" && !params[observacion].blank? oa = ObservacionTutor.new oa.observaciones = params[observacion] oa.fecha = Time.now oa.actual = 1 oa.informe_actividad_id = ia.id oa.save end j= j+1 i=:ext.to_s+j.to_s @act= params[i].to_i end #Comienza actividades obligatorias j=0 i=:obli.to_s+j.to_s @act = params[i].to_i while j < @cant_obli ia = InformeActividad.new ia.informe_id = informe.id ia.actividad_id = @act ia.save ejecutada =:[email protected]_s ae = ActividadEjecutada.new ae.descripcion = params[ejecutada] ae.fecha = Time.now ae.actual = 1 ae.informe_actividad_id = ia.id ae.save observacion =:[email protected]_s if params[observacion]!=nil && params[observacion]!="" && !params[observacion].blank? oa = ObservacionTutor.new oa.observaciones = params[observacion] oa.fecha = Time.now oa.actual = 1 oa.informe_actividad_id = ia.id oa.save end j= j+1 i=:obli.to_s+j.to_s @act= params[i].to_i end #Comienzan otras actividades contempladas en el plan j=0 i=:otra.to_s+j.to_s @act = params[i].to_i while j < @cant_otr ia = InformeActividad.new ia.informe_id = informe.id ia.actividad_id = @act ia.save ejecutada =:[email protected]_s if params[ejecutada]!=nil && params[ejecutada]!="" ae = ActividadEjecutada.new ae.descripcion = params[ejecutada] ae.fecha = Time.now ae.actual = 1 ae.informe_actividad_id = ia.id ae.save end j= j+1 i=:otra.to_s+j.to_s @act= params[i].to_i end redirect_to controller:"informes", action: "listar_informes" flash[:success]= "El informe fue creado y guardado correctamente" else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def generar_pdf() # es funciรณn permite generar el documento pdf de la adecuaciรณn if session[:plan_id] == nil redirect_to controller:"informes", action: "listar_informes" flash[:danger]= "Ha ocurrido un error" end @informe= Informe.find(session[:informe_id]) @TipoSemestre =TipoInforme.where(id: @informe.tipo_id).take @planformacion = Planformacion.find(session[:plan_id]) @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take @fechaConcurso = @planformacion.fecha_inicio @id_docente= @planformacion.tutor_id # se obtiene el indicador del ususario al que corresponde la adecuaciรณn @usertutor= Usuario.find(@id_docente) # se obtiene la informaciรณn del tutor mediante la base de datos y la variable anterior @tutor= Persona.where(usuario_id: @id_docente).take @id_instructor= @planformacion.instructor_id # se toma el identificador del instructor @userinst=Usuario.find(@id_instructor) # se obtienen toda la informaciรณn del instructor @instructor= Persona.where(usuario_id: @id_instructor).take @fechaActual = Date.current.to_s @userentidad= Usuarioentidad.where(usuario_id: @planformacion.instructor_id).take @dactv_docencia=[] @dactv_investigacion=[] @dactv_extension=[] @dactv_formacion=[] @semestres=[] if @userentidad.escuela_id == nil @userentidad.escuela_id=12 @userentidad.save @escuela= Escuela.where(id: @userentidad.escuela_id).take else @escuela= Escuela.where(id: @userentidad.escuela_id).take end @res = [] @resActi = [] @correoi= @userinst.user+'@<EMAIL>' @pactv_docencia= [] @pactv_investigacion= [] @pactv_formacion= [] @pactv_extension=[] @pactv_otras=[] @sactv_docencia= [] @sactv_investigacion= [] @sactv_formacion= [] @sactv_extension=[] @sactv_otras=[] @tactv_docencia= [] @tactv_investigacion= [] @tactv_formacion= [] @tactv_extension=[] @tactv_otras=[] @cactv_docencia= [] @cactv_investigacion= [] @cactv_formacion= [] @cactv_extension=[] @cactv_otras=[] @factv_obligatoria=[] @semestres=[] @aactv_docencia= [] @aactv_investigacion= [] @aactv_formacion= [] @aactv_extension=[] @aactv_otras=[] @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 if @informe.numero == 1 @aactv_docencia.push(@act) end @pactv_docencia.push(@act) elsif tipo==2 if @informe.numero == 1 @resActi= InformeActividad.where(informe_id: @informe.id, actividad_id: @act.id).take @res= Resultado.where(informe_actividad_id: @resActi.id).all @aactv_investigacion.push(@act) end @pactv_investigacion.push(@act) elsif tipo==3 if @informe.numero == 1 @aactv_formacion.push(@act) end @pactv_extension.push(@act) elsif tipo==4 if @informe.numero == 1 @aactv_extension.push(@act) end @pactv_formacion.push(@act) elsif tipo==5 if @informe.numero == 1 @aactv_otras.push(@act) end @pactv_otras.push(@act) end end @sactividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @sactividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 if @informe.numero == 2 @aactv_docencia.push(@act) end @sactv_docencia.push(@act) elsif tipo==2 if @informe.numero == 2 @resActi= InformeActividad.where(informe_id: @informe.id, actividad_id: @act.id).take @res= Resultado.where(informe_actividad_id: @resActi.id).all @aactv_investigacion.push(@act) end @sactv_investigacion.push(@act) elsif tipo==3 if @informe.numero == 2 @aactv_formacion.push(@act) end @sactv_extension.push(@act) elsif tipo==4 if @informe.numero == 2 @aactv_extension.push(@act) end @sactv_formacion.push(@act) elsif tipo==5 if @informe.numero == 2 @aactv_otras.push(@act) end @sactv_otras.push(@act) end end @tactividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all @tactividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 if @informe.numero == 4 @aactv_docencia.push(@act) end @tactv_docencia.push(@act) elsif tipo==2 if @informe.numero == 4 @resActi= InformeActividad.where(informe_id: @informe.id, actividad_id: @act.id).take @res= Resultado.where(informe_actividad_id: @resActi.id).all @aactv_investigacion.push(@act) end @tactv_investigacion.push(@act) elsif tipo==3 if @informe.numero == 4 @aactv_formacion.push(@act) end @tactv_extension.push(@act) elsif tipo==4 if @informe.numero == 4 @aactv_extension.push(@act) end @tactv_formacion.push(@act) elsif tipo==5 if @informe.numero == 4 @aactv_otras.push(@act) end @tactv_otras.push(@act) end end @cactividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all @cactividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 if @informe.numero == 5 @aactv_docencia.push(@act) end @cactv_docencia.push(@act) elsif tipo==2 if @informe.numero == 5 @resActi= InformeActividad.where(informe_id: @informe.id, actividad_id: @act.id).take @res= Resultado.where(informe_actividad_id: @resActi.id).all if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = "* " + @noemptyarray end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @resultados2 + "\n" + "* " + @noemptyarray.join(',') end end end @aactv_investigacion.push(@act) end @cactv_investigacion.push(@act) elsif tipo==3 if @informe.numero == 5 @aactv_formacion.push(@act) end @cactv_extension.push(@act) elsif tipo==4 if @informe.numero == 5 @aactv_extension.push(@act) end @cactv_formacion.push(@act) elsif tipo==5 if @informe.numero == 5 @aactv_otras.push(@act) end @cactv_otras.push(@act) end end @actividadesa= InformeActividad.where(informe_id: @informe.id).all @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @actividadesaobli= [] @resultados= [] @actividadese= [] @observaciont= [] @resultTP = [] @resultPP = [] @resultPIT = [] @resultO = [] @resultAEC = [] @resultOEC = [] @resultDCS = [] @actividadesa.each do |actade| @res= Resultado.where(informe_actividad_id: actade.id).all @resultados2 = "" if actade.actividad_id == nil #Es el caso que es un resultado no contemplado en el plan de formacion o un avancwe de postgrado @res= Resultado.find(actade.resultado_id) if [email protected]? @res.each do |res| @resultados2 = "" @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a","a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = res.titulo.capitalize @cparray[1] = res.autor.capitalize @cparray[2] = res.nombre_capitulo.to_s.capitalize @cparray[3] = res.autor_capitulo.to_s.capitalize @cparray[4] = res.dia @cparray[5] = res.mes @cparray[6] = res.ano @cparray[7] = res.ciudad.to_s.capitalize @cparray[8] = res.estado.to_s.capitalize @cparray[9] = res.pais.to_s.capitalize @cparray[10] = res.organizador.to_s.capitalize @cparray[11] = res.duracion.to_s.capitalize @cparray[12] = res.editor.to_s.capitalize @cparray[13] = res.titulo_libro.to_s.capitalize @cparray[14] = res.autor_libro.to_s.capitalize @cparray[15] = res.nombre_revista.to_s.capitalize @cparray[16] = res.nombre_periodico.to_s.capitalize @cparray[17] = res.nombre_acto.to_s.capitalize @cparray[18] = res.paginas @cparray[19] = res.nombre_paginaw.to_s.capitalize @cparray[20] = res.sitio_paginaw @cparray[21] = res.infoafiliaion.to_s.capitalize @cparray[22] = res.cptipo.to_s.capitalize @cparray[23] = res.nombre.to_s.capitalize @cparray[24] = res.ISSN_impreso.to_s.capitalize @cparray[25] = res.ISSN_electro.to_s.capitalize @cparray[26] = res.volumen.to_s.capitalize @cparray[27] = res.edicion.to_s.capitalize @cparray[28] = res.DOI @cparray[29] = res.ISBN @cparray[30] = res.universidad.to_s.capitalize @cparray[31] = res.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = "* " + @noemptyarray end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @resultados2 + @noemptyarray.join(', ') end end end if res.tipo_resultado_id == 1 @resultTP.push(@resultados2) elsif res.tipo_resultado_id == 2 @resultPP.push(@resultados2) elsif res.tipo_resultado_id == 3 @resultPIT.push(@resultados2) elsif res.tipo_resultado_id == 4 @resultO.push(@resultados2) elsif res.tipo_resultado_id == 5 @resultAEC.push(@resultados2) elsif res.tipo_resultado_id == 6 @resultOEC.push(@resultados2) elsif res.tipo_resultado_id == 7 @resultDCS.push(@resultados2) end @resultados.push(res) end end else @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if [email protected]? @res.each do |res| @resultados2 = "" @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a","a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = res.titulo.capitalize @cparray[1] = res.autor.capitalize @cparray[2] = res.nombre_capitulo.to_s.capitalize @cparray[3] = res.autor_capitulo.to_s.capitalize @cparray[4] = res.dia @cparray[5] = res.mes @cparray[6] = res.ano @cparray[7] = res.ciudad.to_s.capitalize @cparray[8] = res.estado.to_s.capitalize @cparray[9] = res.pais.to_s.capitalize @cparray[10] = res.organizador.to_s.capitalize @cparray[11] = res.duracion.to_s.capitalize @cparray[12] = res.editor.to_s.capitalize @cparray[13] = res.titulo_libro.to_s.capitalize @cparray[14] = res.autor_libro.to_s.capitalize @cparray[15] = res.nombre_revista.to_s.capitalize @cparray[16] = res.nombre_periodico.to_s.capitalize @cparray[17] = res.nombre_acto.to_s.capitalize @cparray[18] = res.paginas @cparray[19] = res.nombre_paginaw.to_s.capitalize @cparray[20] = res.sitio_paginaw @cparray[21] = res.infoafiliaion.to_s.capitalize @cparray[22] = res.cptipo.to_s.capitalize @cparray[23] = res.nombre.to_s.capitalize @cparray[24] = res.ISSN_impreso.to_s.capitalize @cparray[25] = res.ISSN_electro.to_s.capitalize @cparray[26] = res.volumen.to_s.capitalize @cparray[27] = res.edicion.to_s.capitalize @cparray[28] = res.DOI @cparray[29] = res.ISBN @cparray[30] = res.universidad.to_s.capitalize @cparray[31] = res.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = "* " + @noemptyarray end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @resultados2 + @noemptyarray.join(', ') end end end if res.tipo_resultado_id == 1 @resultTP.push(@resultados2) elsif res.tipo_resultado_id == 2 @resultPP.push(@resultados2) elsif res.tipo_resultado_id == 3 @resultPIT.push(@resultados2) elsif res.tipo_resultado_id == 4 @resultO.push(@resultados2) elsif res.tipo_resultado_id == 5 @resultAEC.push(@resultados2) elsif res.tipo_resultado_id == 6 @resultOEC.push(@resultados2) elsif res.tipo_resultado_id == 7 @resultDCS.push(@resultados2) end @resultados.push(res) end end @ae= ActividadEjecutada.where(informe_actividad_id: actade.id).take @actividadese.push(@ae) @obs= ObservacionTutor.where(informe_actividad_id: actade.id).take if @obs==nil @observaciont.push("") else @observaciont.push(@obs.observaciones) end semestre = AdecuacionActividad.where(actividad_id: @act.id).take.semestre @semestres[@act.id]=semestre if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) elsif tipo==7 @actividadesaobli.push(@act) end end end @documents = [] @documents = Document.where(adecuacion_id: @adecuacion.id, informe_id: session[:informe_id] ).all respaldos = [] respaldos = Respaldo.where(adecuacion_id: @adecuacion.id, informe_id: session[:informe_id] ).all @numeroDeVersion = respaldos.size + 1 @actividades1 = [] actividades = AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0) if !actividades.blank? actividades.each do |actividadAde| actividad = Actividad.find(actividadAde.actividad_id) @actividades1.push(actividad) end end # se llama a la funciรณn de "pedf_adecuacion" del modelo "pdf", pasando todas las variables correspondientes @nombre_archivo= Pdf.pdf_informe(@actividades1,@TipoSemestre, @escuela, @informe, @adecuacion, @tutor, @instructor, @pactv_docencia, @pactv_investigacion, @pactv_extension, @pactv_formacion, @pactv_otras, @sactv_docencia, @sactv_investigacion, @sactv_extension, @sactv_formacion, @sactv_otras, @tactv_docencia, @tactv_investigacion, @tactv_extension, @tactv_formacion, @tactv_otras, @cactv_docencia, @cactv_investigacion, @cactv_extension, @cactv_formacion, @cactv_otras, @actividadesadoc, @actividadesainv, @actividadesafor, @actividadesaext, @actividadesaotr,@res,@resultados,@actividadese,@observaciont,@resultTP,@resultPP,@resultO,@resultAEC,@resultOEC,@resultDCS, @documents, @numeroDeVersion, @factv_obligatoria, @actividadesaobli, @dactv_docencia, @dactv_investigacion, @dactv_extension, @dactv_formacion, @semestres) act = "#{Rails.root}/tmp/PDFs/" + @nombre_archivo #act = @nombre_archivo send_file( act, filename: @nombre_archivo, type: "application/pdf" ) return @nombre_archivo # se retorna el nombre del archivo end def actualizar_informe @informe= Informe.find(session[:informe_id]) @informe.fecha_modificacion = Time.now @cant_doc= params[:cant_docencia].to_i @cant_inv= params[:cant_investigacion].to_i @cant_for= params[:cant_formacion].to_i @cant_ext= params[:cant_extension].to_i @cant_obli= params[:cant_obligatoria].to_i @cant_otr= params[:cant_otra].to_i @cant_result= params[:cant_result].to_i if !params[:fechaIni].blank? @fecha_inicio = params[:fechaIni] @informe.fecha_inicio = @fecha_inicio end if !params[:fechaFin].blank? @informe.fecha_fin = params[:fechaFin] end @informe.opinion_tutor = params[:opinion] @informe.conclusiones = params[:conclusiones] @informe.justificaciones = params[:justi] @plan= Planformacion.find(session[:plan_id]) @plan.fecha_modificacion = Time.now @plan.save @informe.save #Comienza actividades de docencia j=0 i=:doc.to_s+j.to_s @act = params[i].to_i while j < @cant_doc ia = InformeActividad.where(informe_id: @informe.id,actividad_id: @act).take ejecutada =:[email protected]_s if params[ejecutada]!=nil && params[ejecutada]!="" ae = ActividadEjecutada.where(informe_actividad_id: ia.id, actual: 1).take ae.descripcion = params[ejecutada] ae.save end observacion =:[email protected]_s oa = ObservacionTutor.where(informe_actividad_id: ia.id).take if !params[observacion].blank? if(oa == nil || oa =="") oa = ObservacionTutor.new oa.observaciones = params[observacion] oa.fecha = Time.now oa.informe_actividad_id = ia.id oa.save else oa.observaciones = params[observacion] oa.save end end j= j+1 i=:doc.to_s+j.to_s @act= params[i].to_i end #Comienza actividades de investigacion j=0 i=:inv.to_s+j.to_s @act = params[i].to_i k=:result.to_s+j.to_s @result= params[k].to_i while j < @cant_inv ia = InformeActividad.where(informe_id: @informe.id,actividad_id: @act).take ejecutada =:[email protected]_s if params[ejecutada]!=nil && params[ejecutada]!="" ae = ActividadEjecutada.where(informe_actividad_id: ia.id, actual: 1).take ae.descripcion = params[ejecutada] ae.save end observacion =:[email protected]_s oa = ObservacionTutor.where(informe_actividad_id: ia.id).take if !params[observacion].blank? if(oa == nil || oa =="") oa = ObservacionTutor.new oa.observaciones = params[observacion] oa.fecha = Time.now oa.informe_actividad_id = ia.id oa.save else oa.observaciones = params[observacion] oa.save end end ia.save #Actualizarรก los resultados cpi = 1 cpres= Resultado.destroy_all(informe_actividad_id: ia.id) while (!params[:tipo.to_s+cpi.to_s+j.to_s].blank?) @tipo = params[:tipo.to_s+cpi.to_s+j.to_s].to_i @tipo_publicacion = nil @titulo = nil @autor = nil @nombre_capitulo = nil @autor_capitulo = nil @dia = nil @mes = nil @ano = nil @ciudad = nil @estado = nil @pais = nil @organizador = nil @duracion = nil @editor = nil @titulo_libro = nil @autor_libro = nil @nombre_revista = nil @nombre_periodico = nil @paginas = nil @nombre_acto = nil @nombre_paginaw = nil @sitio_paginaw = nil @url = nil @isbm = nil @volumen = nil @edicion = nil @issni = nil @issne = nil @doi = nil @nombre = nil @infoafiliaion = nil @universidad = nil @cptipo = nil # trabajos publicados if (@tipo == 1) @tipo_publicacion = params[:resultado_tipos.to_s+cpi.to_s+j.to_s].to_i # libro if (@tipo_publicacion == 1) @titulo = params[:atitulo.to_s+cpi.to_s+j.to_s] @ciudad = params[:aciudad.to_s+cpi.to_s+j.to_s] @url = params[:aURL.to_s+cpi.to_s+j.to_s] @autor = params[:aautor.to_s+cpi.to_s+j.to_s] @pais = params[:apais.to_s+cpi.to_s+j.to_s] @isbm = params[:aISBM.to_s+cpi.to_s+j.to_s] @editor = params[:aeditor.to_s+cpi.to_s+j.to_s] @ano = params[:aano.to_s+cpi.to_s+j.to_s] # articulo de revista o journals elsif (@tipo_publicacion == 2) @titulo = params[:btitulo.to_s+cpi.to_s+j.to_s] @autor = params[:bautor.to_s+cpi.to_s+j.to_s] @mes = params[:bmes.to_s+cpi.to_s+j.to_s] @ano = params[:bano.to_s+cpi.to_s+j.to_s] @ciudad = params[:bciudad.to_s+cpi.to_s+j.to_s] @estado = params[:bestado.to_s+cpi.to_s+j.to_s] @pais = params[:bpais.to_s+cpi.to_s+j.to_s] @paginas = params[:bnumpaginas.to_s+cpi.to_s+j.to_s] @url = params[:burl.to_s+cpi.to_s+j.to_s] @volumen = params[:bvolumen.to_s+cpi.to_s+j.to_s] @edicion = params[:bnedicion.to_s+cpi.to_s+j.to_s] @issni = params[:bissnimpre.to_s+cpi.to_s+j.to_s] @nombre_revista = params[:brevista.to_s+cpi.to_s+j.to_s] @issne = params[:bissnelec.to_s+cpi.to_s+j.to_s] @doi = params[:bdoi.to_s+cpi.to_s+j.to_s] # articulo de prensa elsif (@tipo_publicacion == 3) @titulo = params[:ctitulo.to_s+cpi.to_s+j.to_s] @autor = params[:cautor.to_s+cpi.to_s+j.to_s] @dia = params[:cdia.to_s+cpi.to_s+j.to_s] @mes = params[:cmes.to_s+cpi.to_s+j.to_s] @ano = params[:cano.to_s+cpi.to_s+j.to_s] @pais = params[:cpais.to_s+cpi.to_s+j.to_s] @nombre_periodico = params[:cnomperi.to_s+cpi.to_s+j.to_s] @paginas = params[:cnumpag.to_s+cpi.to_s+j.to_s] @url = params[:curl.to_s+cpi.to_s+j.to_s] # cd elsif (@tipo_publicacion == 4) @titulo = params[:dtitulo.to_s+cpi.to_s+j.to_s] @autor = params[:dautor.to_s+cpi.to_s+j.to_s] @ano = params[:daรฑo.to_s+cpi.to_s+j.to_s] @ciudad = params[:dciudad.to_s+cpi.to_s+j.to_s] @pais = params[:dpais.to_s+cpi.to_s+j.to_s] @editor = params[:deditor.to_s+cpi.to_s+j.to_s] #manuales elsif (@tipo_publicacion == 5) @titulo = params[:etitulo.to_s+cpi.to_s+j.to_s] @autor = params[:eautor.to_s+cpi.to_s+j.to_s] @mes = params[:emes.to_s+cpi.to_s+j.to_s] @ano = params[:eano.to_s+cpi.to_s+j.to_s] @ciudad = params[:eciudad.to_s+cpi.to_s+j.to_s] @pais = params[:epais.to_s+cpi.to_s+j.to_s] @editor = params[:eeditor.to_s+cpi.to_s+j.to_s] #publicaciones electronicas elsif (@tipo_publicacion == 6) @titulo = params[:ftitulo.to_s+cpi.to_s+j.to_s] @autor = params[:fautor.to_s+cpi.to_s+j.to_s] @nombre = params[:fnombre.to_s+cpi.to_s+j.to_s] @mes = params[:fmes.to_s+cpi.to_s+j.to_s] @ano = params[:fano.to_s+cpi.to_s+j.to_s] @nombre_paginaw = params[:fnompagweb.to_s+cpi.to_s+j.to_s] @sitio_paginaw = params[:fsitioweb.to_s+cpi.to_s+j.to_s] @url = params[:furl.to_s+cpi.to_s+j.to_s] @isbm = params[:fisbn.to_s+cpi.to_s+j.to_s] @doi = params[:fdoi.to_s+cpi.to_s+j.to_s] #tesis elsif (@tipo_publicacion == 7) @titulo = params[:gtitulo.to_s+cpi.to_s+j.to_s] @autor = params[:gautor.to_s+cpi.to_s+j.to_s] @mes = params[:gmes.to_s+cpi.to_s+j.to_s] @ano = params[:gano.to_s+cpi.to_s+j.to_s] @ciudad = params[:gciudad.to_s+cpi.to_s+j.to_s] @pais = params[:gpais.to_s+cpi.to_s+j.to_s] @infoafiliaion = params[:ginfoafiliacion.to_s+cpi.to_s+j.to_s] @universidad = params[:guniversidad.to_s+cpi.to_s+j.to_s] @cptipo = params[:gtipotesis.to_s+cpi.to_s+j.to_s] #acta de conferencia elsif (@tipo_publicacion == 8) @titulo = params[:htitulo.to_s+cpi.to_s+j.to_s] @autor = params[:hautor.to_s+cpi.to_s+j.to_s] @mes = params[:hmes.to_s+cpi.to_s+j.to_s] @ano = params[:hano.to_s+cpi.to_s+j.to_s] @paginas = params[:hpaginas.to_s+cpi.to_s+j.to_s] @isbm = params[:hisbm.to_s+cpi.to_s+j.to_s] @issni = params[:hissn.to_s+cpi.to_s+j.to_s] @doi = params[:hdoi.to_s+cpi.to_s+j.to_s] @nombre = params[:hnombreconf.to_s+cpi.to_s+j.to_s] #capitulo de un libro elsif (@tipo_publicacion == 9) @nombre_capitulo = params[:ititulocapitulo.to_s+cpi.to_s+j.to_s] @autor = params[:iautor.to_s+cpi.to_s+j.to_s] @ano = params[:iano.to_s+cpi.to_s+j.to_s] @titulo_libro = params[:ititulolibro.to_s+cpi.to_s+j.to_s] @paginas = params[:ipaginas.to_s+cpi.to_s+j.to_s] @isbm = params[:iisbn.to_s+cpi.to_s+j.to_s] end #presentaciรณn de potencias elsif (@tipo == 2) @titulo = params[:jtitulo.to_s+cpi.to_s+j.to_s] @autor = params[:jautordoc.to_s+cpi.to_s+j.to_s] @nombre_capitulo = params[:jtitulocapitulo.to_s+cpi.to_s+j.to_s] @autor_capitulo = params[:jautorcap.to_s+cpi.to_s+j.to_s] @dia = params[:jdia.to_s+cpi.to_s+j.to_s] @mes = params[:jmes.to_s+cpi.to_s+j.to_s] @ano = params[:jano.to_s+cpi.to_s+j.to_s] @ciudad = params[:jciudad.to_s+cpi.to_s+j.to_s] @editor = params[:jeditor.to_s+cpi.to_s+j.to_s] @paginas = params[:jnumpag.to_s+cpi.to_s+j.to_s] @nombre = params[:jnombreact.to_s+cpi.to_s+j.to_s] #presentaciรณn informes tecnicos elsif (@tipo == 3) @titulo = params[:ktitulo.to_s+cpi.to_s+j.to_s] @autor = params[:kautordoc.to_s+cpi.to_s+j.to_s] @nombre_capitulo = params[:ktitulocapitulo.to_s+cpi.to_s+j.to_s] @autor_capitulo = params[:kautorcap.to_s+cpi.to_s+j.to_s] @dia = params[:kdia.to_s+cpi.to_s+j.to_s] @mes = params[:kmes.to_s+cpi.to_s+j.to_s] @ano = params[:kano.to_s+cpi.to_s+j.to_s] @ciudad = params[:kciudad.to_s+cpi.to_s+j.to_s] @estado = params[:kestado.to_s+cpi.to_s+j.to_s] @pais = params[:kpais.to_s+cpi.to_s+j.to_s] @organizador = params[:kentidadorg.to_s+cpi.to_s+j.to_s] @editor = params[:keditor.to_s+cpi.to_s+j.to_s] @paginas = params[:knumpag.to_s+cpi.to_s+j.to_s] @nombre_acto = params[:knombreact.to_s+cpi.to_s+j.to_s] #otro elsif (@tipo == 4) @titulo = params[:ltitulo.to_s+cpi.to_s+j.to_s] @autor = params[:lautor.to_s+cpi.to_s+j.to_s] @dia = params[:ldia.to_s+cpi.to_s+j.to_s] @mes = params[:lmes.to_s+cpi.to_s+j.to_s] @ano = params[:laรฑo.to_s+cpi.to_s+j.to_s] @ciudad = params[:lciudad.to_s+cpi.to_s+j.to_s] @editor = params[:leditor.to_s+cpi.to_s+j.to_s] @paginas = params[:lnumpag.to_s+cpi.to_s+j.to_s] @nombre_acto = params[:lnomacto.to_s+cpi.to_s+j.to_s] #asistencia y organizaciรณn de eventos cientificos elsif (@tipo == 5 || @tipo == 6) @titulo = params[:ntitulo.to_s+cpi.to_s+j.to_s] @autor = params[:nautordoc.to_s+cpi.to_s+j.to_s] @nombre_capitulo = params[:ntitulocapitulo.to_s+cpi.to_s+j.to_s] @autor_capitulo = params[:nnombreautor.to_s+cpi.to_s+j.to_s] @dia = params[:ndia.to_s+cpi.to_s+j.to_s] @mes = params[:nmes.to_s+cpi.to_s+j.to_s] @ano = params[:nano.to_s+cpi.to_s+j.to_s] @ciudad = params[:nciudad.to_s+cpi.to_s+j.to_s] @estado = params[:nestado.to_s+cpi.to_s+j.to_s] @pais = params[:npais.to_s+cpi.to_s+j.to_s] @nombre_acto = params[:nnombreacto.to_s+cpi.to_s+j.to_s] #dictado de cursos, talleres, etc elsif (@tipo == 7) @titulo = params[:otitulo.to_s+cpi.to_s+j.to_s] @autor = params[:oautordoc.to_s+cpi.to_s+j.to_s] @nombre_capitulo = params[:otitulocap.to_s+cpi.to_s+j.to_s] @autor_capitulo = params[:oautorcap.to_s+cpi.to_s+j.to_s] @dia = params[:odia.to_s+cpi.to_s+j.to_s] @mes = params[:omes.to_s+cpi.to_s+j.to_s] @ano = params[:oano.to_s+cpi.to_s+j.to_s] @ciudad = params[:ociudad.to_s+cpi.to_s+j.to_s] @estado = params[:oestado.to_s+cpi.to_s+j.to_s] @pais = params[:opais.to_s+cpi.to_s+j.to_s] @organizador = params[:oentidadorg.to_s+cpi.to_s+j.to_s] @duracion = params[:oduracion.to_s+cpi.to_s+j.to_s] @editor = params[:oeditor.to_s+cpi.to_s+j.to_s] @titulo_libro = params[:otitulolib.to_s+cpi.to_s+j.to_s] @autor_libro = params[:oautorref.to_s+cpi.to_s+j.to_s] @paginas = params[:onumpag.to_s+cpi.to_s+j.to_s] end r = Resultado.new r.tipo_resultado_id = @tipo r.tipo_publicacion = @tipo_publicacion r.titulo = @titulo r.autor = @autor r.nombre_capitulo = @nombre_capitulo r.autor_capitulo = @autor_capitulo r.dia = @dia r.mes =@mes r.ano = @ano r.ciudad = @ciudad r.estado = @estado r.pais = @pais r.organizador = @organizador r.duracion = @duracion r.editor = @editor r.titulo_libro = @titulo_libro r.autor_libro = @autor_libro r.nombre_revista = @nombre_revista r.nombre_periodico = @nombre_periodico r.paginas = @paginas r.nombre_acto = @nombre_acto r.nombre_paginaw = @nombre_paginaw r.sitio_paginaw = @sitio_paginaw r.infoafiliaion = @infoafiliaion r.cptipo = @cptipo r.nombre = @nombre r.ISSN_impreso = @issni r.ISSN_electro = @issne r.volumen = @volumen r.edicion = @edicion r.DOI = @doi r.ISBN = @isbm r.universidad = @universidad r.url = @url r.informe_actividad_id = ia.id r.save cpi = cpi+1 end j=j+1 k=:result.to_s+j.to_s @result= params[k].to_i i=:inv.to_s+j.to_s @act= params[i].to_i end #Comienza actividades de formaciรณn j=0 i=:for.to_s+j.to_s @act = params[i].to_i while j < @cant_for ia = InformeActividad.where(informe_id: @informe.id,actividad_id: @act).take ejecutada =:[email protected]_s if params[ejecutada]!=nil && params[ejecutada]!="" ae = ActividadEjecutada.where(informe_actividad_id: ia.id, actual: 1).take ae.descripcion = params[ejecutada] ae.save end observacion =:[email protected]_s oa = ObservacionTutor.where(informe_actividad_id: ia.id).take if !params[observacion].blank? if(oa == nil || oa =="") oa = ObservacionTutor.new oa.observaciones = params[observacion] oa.fecha = Time.now oa.informe_actividad_id = ia.id oa.save else oa.observaciones = params[observacion] oa.save end end j= j+1 i=:for.to_s+j.to_s @act= params[i].to_i end #Resultado de avances de postgrado if params[:postgrado]!=nil && params[:postgrado]!="" if params[:postg].to_i == -1 rp = Resultado.new rp.tipo_resultado_id = 8 rp.concepto = params[:postgrado] rp.save ia = InformeActividad.new ia.informe_id = @informe.id ia.resultado_id = rp.id ia.save else rp= Resultado.find(params[:postg].to_i) rp.concepto = params[:postgrado] rp.save end end #Comienzan actividades de extensiรณn j=0 i=:ext.to_s+j.to_s @act = params[i].to_i while j < @cant_ext ia = InformeActividad.where(informe_id: @informe.id,actividad_id: @act).take ejecutada =:[email protected]_s if params[ejecutada]!=nil && params[ejecutada]!="" ae = ActividadEjecutada.where(informe_actividad_id: ia.id, actual: 1).take ae.descripcion = params[ejecutada] ae.save end observacion =:[email protected]_s oa = ObservacionTutor.where(informe_actividad_id: ia.id).take if !params[observacion].blank? if(oa == nil || oa =="") oa = ObservacionTutor.new oa.observaciones = params[observacion] oa.fecha = Time.now oa.informe_actividad_id = ia.id oa.save else oa.observaciones = params[observacion] oa.save end end j= j+1 i=:ext.to_s+j.to_s @act= params[i].to_i end #Comienza actividades obligatorias j=0 i=:obli.to_s+j.to_s @act = params[i].to_i while j < @cant_obli ia = InformeActividad.where(informe_id: @informe.id,actividad_id: @act).take ejecutada =:[email protected]_s if params[ejecutada]!=nil && params[ejecutada]!="" ae = ActividadEjecutada.where(informe_actividad_id: ia.id, actual: 1).take ae.descripcion = params[ejecutada] ae.save end observacion =:[email protected]_s oa = ObservacionTutor.where(informe_actividad_id: ia.id).take if !params[observacion].blank? if(oa == nil || oa =="") oa = ObservacionTutor.new oa.observaciones = params[observacion] oa.fecha = Time.now oa.informe_actividad_id = ia.id oa.save else oa.observaciones = params[observacion] oa.save end end j= j+1 i=:obli.to_s+j.to_s @act= params[i].to_i end #Comienzan otras actividades j=0 i=:otra.to_s+j.to_s @act = params[i].to_i while j < @cant_otr ia = InformeActividad.where(informe_id: @informe.id,actividad_id: @act).take ejecutada =:[email protected]_s if params[ejecutada]!=nil && params[ejecutada]!="" ae = ActividadEjecutada.where(informe_actividad_id: ia.id, actual: 1).take if ae.blank? ae = ActividadEjecutada.new ae.descripcion = params[ejecutada] ae.fecha = Time.now ae.actual = 1 ae.informe_actividad_id = ia.id ae.save end ae.descripcion = params[ejecutada] ae.save end j= j+1 i=:otra.to_s+j.to_s @act= params[i].to_i end #EN ESTA SECCION IRIAN LAS OTRAS ACTIVIDADES CONTEMPLADAS EN EL PLAN HAY QUE VERIFICAR SI ESTAS SE PUEDEN MODIFICAR flash[:success]="Su informe fue editado exitosamente" redirect_to controller:"informes", action: "ver_detalles_informe" end def listar_informes if session[:usuario_id] && session[:tutor] @persona = Persona.where(usuario_id: session[:usuario_id]).take @nombre = session[:nombre_usuario] @planformacion = session[:plan_id] @instructorName = session[:instructorName] @informes = Informe.where(planformacion_id: @planformacion).order(fecha_modificacion: :desc) @informe = Informe.where(planformacion_id: @planformacion).take @status = [] @tipos= [] @informes.each do |inf| si = EstatusInforme.where(informe_id: inf.id, actual: 1).take if(si.estatus_id==1) @st = "[" + si.fecha.to_s + "]: APROBADO POR CONSEJO DE FACULTAD" elsif(si.estatus_id==2) @st = "[" + si.fecha.to_s + "]: ENVIADO A CONSEJO Tร‰CNICO" elsif(si.estatus_id==3) @st = "[" + si.fecha.to_s + "]: ENVIADO A COMISION DE INVESTIGACIร“N" elsif(si.estatus_id==4) @st = "[" + si.fecha.to_s + "]: ENVIADO A CONSEJO DE FACULTAD" elsif(si.estatus_id==5) @st = "[" + si.fecha.to_s + "]: APROBADO CON OBSERVACIONES POR CONSEJO DE FACULTAD" elsif(si.estatus_id==6) @st = "GUARDADO" elsif(si.estatus_id==8) @st = "[" + si.fecha.to_s + "]: ENVIADO A CONSEJO DE ESCUELA" elsif(si.estatus_id==9) @st = "[" + si.fecha.to_s + "]: RECHAZADO POR CONSEJO DE FACULTAD" elsif(si.estatus_id==12) @st = "[" + si.fecha.to_s + "]: ENVIADO A CONSEJO Tร‰CNICO SIN REVISIร“N" elsif(si.estatus_id==13) @st = "[" + si.fecha.to_s + "]: ENVIADO A COMISIร“N DE INVESTIGACIร“N SIN REVISIร“N" elsif(si.estatus_id==14) @st = "[" + si.fecha.to_s + "]: ENVIADO A CONSEJO DE FACULTAD SIN REVISIร“N" elsif(si.estatus_id==18) @st = "[" + si.fecha.to_s + "]: ENVIADO A CONSEJO DE ESCUELA SIN REVISIร“N" end @status.push(@st) if inf.tipo_id == 1 @tipos.push('Semestral') else if inf.tipo_id ==2 @tipos.push('Anual') else if inf.tipo_id==3 @tipos.push('Final') end end end end if not @nombre print "NO HAY USUARIO" end else redirect_to controller:"forminst", action: "index" end end def cambiar_estatusI cpenviar = "si" cpStatus = EstatusAdecuacion.where(adecuacion_id: session[:adecuacion_id], actual: 1).take if cpStatus.estatus_id != 1 cpenviar = "no1" end cpInformeAVerificar = Informe.find(params[:informe_id].to_i) if cpInformeAVerificar.conclusiones.blank? cpenviar = "no2" end if cpInformeAVerificar.opinion_tutor.blank? cpenviar = "no3" end cpActividadAVerificar = InformeActividad.where(informe_id: params[:informe_id].to_i).all cpActividadAVerificar.each do |actividadV| cpActividadPrueba = Actividad.find(actividadV.actividad_id) if cpActividadPrueba.tipo_actividad_id != 5 cpActividadE = ActividadEjecutada.where(informe_actividad_id: actividadV.id, actual: 1).take if cpActividadE.blank? cpenviar = "no4" elsif cpActividadE.descripcion.blank? cpenviar = "no5" end end end if cpenviar == "si" @informe_id = params[:informe_id].to_i cambio_act = EstatusInforme.where(informe_id: @informe_id, actual: 1).take cambio_est = EstatusInforme.new cambio_est.informe_id = @informe_id cambio_est.fecha = Time.now error = 0 plan = Planformacion.where(id: session[:plan_id]).take adec = Adecuacion.where(planformacion_id: session[:plan_id]).take informesAdecuacion = Informe.where(id: @informe_id).take informesAdecuaciones = Informe.where(planformacion_id: session[:plan_id]).all contador = 0 @informe = Informe.find(@informe_id) if !informesAdecuacion.fecha_inicio.blank? if informesAdecuacion.numero != 1 maxinforme = informesAdecuacion.numero.to_i - 1 for i in 1..maxinforme informesAdecuaciones.each do |inf| estatusInf = EstatusInforme.where(informe_id: inf.id, actual: 1 ).take if (estatusInf.estatus_id != 6 && inf.numero == i) contador = contador + 1 end end end if (contador != maxinforme) error = error + 1 end end if error == 0 if @informe.justificaciones.blank? @informe.justificaciones = "Sin Justificaciones" end @informe.save cambio_est = EstatusInforme.new cambio_est.informe_id = @informe_id cambio_est.fecha = Time.now respaldos = [] respaldos = Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: @informe_id).all Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: @informe_id).update_all(actual: 0) numeroDeVersion = respaldos.size + 1 nombre = generar_pdf() nameofthefile = "#{Rails.root}/tmp/PDFs/" + nombre #nameofthefile = nombre contents = IO.binread(nameofthefile) respaldo = Respaldo.new respaldo.filename = nombre respaldo.content_type = "application/pdf" respaldo.file_contents = contents respaldo.created_at = Date.current respaldo.version = numeroDeVersion respaldo.estatus = "Enviado a Comisiรณn de Investigaciรณn" respaldo.instructor_id = plan.instructor_id respaldo.tutor_id = session[:usuario_id] respaldo.adecuacion_id = session[:adecuacion_id] respaldo.informe_id = @informe_id respaldo.actual = 1 if (cambio_act.estatus_id == 6) cambio_est.estatus_id = 3 #Enviado a comision de investigacion flash[:success]="El informe se ha enviado a Comision de Investigaciรณn" respaldo.estatus = "Enviado a Comisiรณn de Investigaciรณn" elsif (cambio_act.estatus_id == 5) cambio_est.estatus_id = 4 #Enviado a consejo de facultad flash[:success]="El informe se ha envรญado a Consejo de Facultad" respaldo.estatus = "Enviado a Consejo de Facultad" end respaldo.save cambio_est.actual = 1 cambio_est.save cambio_act.actual = 0 cambio_act.save cambio_est.fecha = Time.now notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = session[:usuario_id] notific.adecuacion_id = session[:adecuacion_id] notific.informe_id = @informe_id notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s if (cambio_act.estatus_id == 6) notific.mensaje = "[" + notificacionfecha + "] El " + session[:nombre_informe] + " de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " se ha enviado a comisiรณn de investigaciรณn." elsif (cambio_act.estatus_id == 5) notific.mensaje = "[" + notificacionfecha + "] El " + session[:nombre_informe] + " de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " se ha enviado a Consejo de Facultad." end userr= Usuario.where(id: session[:usuario_id]).take user =Usuarioentidad.where(usuario_id: userr.id).take notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = session[:usuario_id] notific2.adecuacion_id = session[:adecuacion_id] notific2.informe_id = @informe_id notific2.actual = 2 if (cambio_act.estatus_id == 6) notific2.mensaje = "[" + notificacionfecha + "] Se ha enviado el " + session[:nombre_informe] + " a comisiรณn de investigaciรณn." elsif (cambio_act.estatus_id == 5) notific2.mensaje = "[" + notificacionfecha + "] Se ha enviado el " + session[:nombre_informe] + " a Consejo de Facultad." end notific2.save notific3 = Notificacion.new notific3.instructor_id = plan.instructor_id notific3.tutor_id = session[:usuario_id] notific3.adecuacion_id = session[:adecuacion_id] notific3.informe_id = @informe_id if (cambio_act.estatus_id == 6) if(user.escuela_id == 1) notific3.departamento_id = user.departamento_id end notific3.actual = 3 #Comisiรณn de investigaciรณn notific3.mensaje = "[" + notificacionfecha + "] Ha recibido un nuevo Informe: ' " + session[:nombre_informe]+ " ' de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + ", favor aprobar y enviar a la siguiente entidad." elsif (cambio_act.estatus_id == 5) notific3.actual = 5 #consejo de facultad notific3.mensaje = "[" + notificacionfecha + "] Ha recibido un nuevo Informe: ' " + session[:nombre_informe]+ " ' de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + ", favor revisar." end notific3.save if(user.escuela_id == 1) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 7).take else if(user.escuela_id == 2) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 8).take else if(user.escuela_id == 3) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 9).take else if(user.escuela_id == 4) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 10).take else if(user.escuela_id == 9) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 11).take else if(user.escuela_id == 10) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 12).take end end end end end end linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe&param1=" + plan.id.to_s + "&param2="+ @informe_id.to_s linkE = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe&param1=" + plan.id.to_s+ "&param2="+@informe_id.to_s+"&param3="+adec.id.to_s @document = Respaldo.where(id: respaldo.id).take remitente3 = Usuario.where(id: session[:usuario_id]).take ActionCorreo.envio_informe(remitente3, notific.mensaje,2,linkTeI,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_informe(remitente2, notific2.mensaje,1,linkTeI,@document).deliver remitente = Usuario.where(id: uentidad.usuario_id).take ActionCorreo.envio_informe(remitente, notific3.mensaje,0,linkE,@document).deliver if (cambio_act.estatus_id == 5) ActionCorreo.envio_informe("<EMAIL>", notific3.mensaje,0, linkE,@document).deliver end else flash[:warning]="Debe enviar los informes en orden" end else flash[:warning]="Debe introducir una fecha de inicio" end redirect_to controller:"informes", action: "listar_informes" else if cpenviar=="no1" flash[:warning]="Debe esperar a que la adecuaciรณn sea aprobada por consejo de facultad" elsif cpenviar=="no2" || cpenviar=="no3" || cpenviar=="no4" || cpenviar=="no5" flash[:warning]="El informe no se puede enviar sin terminar" end redirect_to controller:"informes", action: "listar_informes" end end def mas_observaciones @boolobs= 0 @booltutor = 0 @informe_id = params[:informe_id].to_i @actividad_id = params[:actividad_id].to_i ia = InformeActividad.where(informe_id: @informe_id, actividad_id: @actividad_id).take @observaciones = ObservacionActividadInforme.where(informe_actividad_id: ia.id).all @observaciones.each do |obs| if(obs.observaciones != "") @boolobs = 1 end end @observaciones.each do |obs| rev = Revision.find(obs.revision_id) entidad = Usuarioentidad.where(usuario_id: rev.usuario_id).take if (entidad.entidad_id >= 7 && entidad.entidad_id <= 12) #comision investigacion @obs_inv = obs.observaciones #Estatus enviado a comision de investigacion else if (entidad.entidad_id >= 14 && entidad.entidad_id <= 17) #Consejo tecnico @obs_consejoT = obs.observaciones else if (entidad.entidad_id >= 1 && entidad.entidad_id <= 6) #Consejo de escuela @obs_consejoE = obs.observaciones else if (entidad.entidad_id == 13) #Consejo de facultad @obs_consejoF = obs.observaciones end end end end end @obs_t= ObservacionTutor.where(informe_actividad_id: ia.id).take if(@obs_t != nil && @obs_t != "") @obs_tutor = @obs_t.observaciones @booltutor = 1 end end def mas_observaciones2 @boolobsb = 0 @informe_id = params[:informe_id].to_i @resultado_id = params[:resultado_id].to_i ia = InformeActividad.where(informe_id: @informe_id, resultado_id: @resultado_id).take @observaciones = ObservacionActividadInforme.where(informe_actividad_id: ia.id) @observaciones.each do |obs| if(obs.observaciones != "") @boolobs = 1 end end @observaciones.each do |obs| rev = Revision.find(obs.revision_id) entidad = Usuarioentidad.where(usuario_id: rev.usuario_id).take if (entidad.entidad_id >= 7 && entidad.entidad_id <= 12) #comision investigacion @obs_inv = obs.observaciones #Estatus enviado a comision de investigacion else if (entidad.entidad_id >= 14 && entidad.entidad_id <= 17) #Consejo tecnico @obs_consejoT = obs.observaciones else if (entidad.entidad_id >= 1 && entidad.entidad_id <= 6) #Consejo de escuela @obs_consejoE = obs.observaciones else if (entidad.entidad_id == 13) #Consejo de facultad @obs_consejoF = obs.observaciones end end end end end end end <file_sep>/forminst_new1/app/controllers/prorrogas_controller.rb class ProrrogasController < ApplicationController before_action :set_prorroga, only: [:show, :edit, :update, :destroy] # GET /prorrogas # GET /prorrogas.json def index @prorrogas = Prorroga.all end # GET /prorrogas/1 # GET /prorrogas/1.json def show end # GET /prorrogas/new def new @prorroga = Prorroga.new end # GET /prorrogas/1/edit def edit end # POST /prorrogas # POST /prorrogas.json def create @prorroga = Prorroga.new(prorroga_params) respond_to do |format| if @prorroga.save format.html { redirect_to @prorroga, notice: 'Prorroga was successfully created.' } format.json { render :show, status: :created, location: @prorroga } else format.html { render :new } format.json { render json: @prorroga.errors, status: :unprocessable_entity } end end end # PATCH/PUT /prorrogas/1 # PATCH/PUT /prorrogas/1.json def update respond_to do |format| if @prorroga.update(prorroga_params) format.html { redirect_to @prorroga, notice: 'Prorroga was successfully updated.' } format.json { render :show, status: :ok, location: @prorroga } else format.html { render :edit } format.json { render json: @prorroga.errors, status: :unprocessable_entity } end end end # DELETE /prorrogas/1 # DELETE /prorrogas/1.json def destroy @prorroga.destroy respond_to do |format| format.html { redirect_to prorrogas_url, notice: 'Prorroga was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_prorroga @prorroga = Prorroga.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def prorroga_params params.require(:prorroga).permit(:id, :planFormacionId) end end <file_sep>/forminst_new1/app/models/tipo_resultado.rb class TipoResultado < ActiveRecord::Base belongs_to :tipo_actividad has_one :resultado end <file_sep>/forminst_new1/app/models/escuela.rb class Escuela < ActiveRecord::Base has_many :entidad end<file_sep>/forminst_new1/app/models/usuario.rb class Usuario < ActiveRecord::Base has_many :usuarioentidad has_many :permisologium has_one :persona #has_many :planformacion #has_many :adecuacion #has_many :informe end<file_sep>/forminst_new1/app/models/instructor.rb class Instructor < ActiveRecord::Base belongs_to :usuario def self.md5(clave) # funciรณn que permite encriptar las claves a MD5 Digest::MD5.hexdigest("#{clave}") end end <file_sep>/forminst_new1/app/controllers/forminst_controller.rb class ForminstController < ApplicationController require 'net-ldap' require 'pry' require 'digest/sha1' layout 'ec_aplanes' #Pรกgina Principal def index reset_session @accion = params[:accion] @param1 = params[:param1] @param2 = params[:param2] @param3 = params[:param3] end #Iniciar Sesiรณn def autenticar #Conectar con el servidor ldap ldap= Net::LDAP.new(:host=>"correo.ciens.ucv.ve",:port=>389, :auth=>{:method=> :simple, :username=>"cn=vmail,dc=ciens,dc=ucv,dc=ve", :password => "<PASSWORD>"}) correo= params[:correo] # se toma el valor correo del ususario clave= params[:password] # se toma el valor password del usuario #Si es un Administrados #Descomentar el codigo siempre que se desee encriptar todas las contraseรฑas de la base de datos #usu = Usuario.all #usu.each do |u| # u.password = <PASSWORD>::SHA1.<PASSWORD>(u.password) # u.save #end if correo == "Administrador" && params[:password]=="<PASSWORD>" session[:usuario_id] = "-2552" #nรบmero de usuario para el administrador (usado para no ingresar al modulo con el link) session[:nombre_usuario] = "Administrador" #usado para no ingresar al modulo con el link session[:administrador] = true session[:tutor] = false session[:instructor] = false session[:entidad] = false flash[:success] = "Bienvenido! Administrador" redirect_to controller:"administrador", action: "index" #Mostrar el modulo del administrador elsif correo!=nil && correo!="" && clave!=nil && clave!="" #verificar que el correo no sea nulo begin result = ldap.bind_as(:base => "dc=ciens, dc=ucv, dc=ve", :filter => "(uid=#{correo})", :password => clave) rescue => error result = nil end @usuario= Usuario.where(user: correo).take #buscar el usuario en la base de datos if @usuario #Si el usuario esta registrado [email protected] #Guardar el tipo de usuario "Secretaria, Entidad, Vista(No poder modificar en la entidad), tutor e instructor" @usuarioe= Usuarioentidad.where(usuario_id: @usuario.id).take @entidad= Entidad.find(@usuarioe.entidad_id) if @usuario.activo==true #Sber si el usuario no esta bloqueado if @usuario.ldap==true && !result.blank? #si el usuario se encuentra en el ldap entonces @usuario.password = <PASSWORD>) #Se encripta la clave del usuario para almacenarlo en la base de datos (se usa cuando no funciona el ldap) @usuario.save #segun el usuario se muestra su modulo y se almacenan los datos de las sesiones if tipo=="Secretaria" session[:usuario_id]= @usuario.id @persona = Persona.where(usuario_id: session[:usuario_id]).take session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] session[:administrador] = false session[:tutor]= false session[:instructor]= false session[:entidad]= true flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"secretarias", action: "index" elsif tipo == "Docente" if @entidad.nombre=="tutor" session[:usuario_id]= @usuario.id @persona = Persona.where(usuario_id: session[:usuario_id]).take session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] session[:administrador] = false session[:tutor]= true session[:instructor]= false session[:entidad]= false if params[:accion] == "mostrar adecuacion" plan = Planformacion.where(id: params[:param1].to_i).take if session[:usuario_id] == plan.tutor_id session[:plan_id] = plan.id @inst = Persona.where(usuario_id: plan.instructor_id).take @instructorName = @inst.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @inst.apellidos.to_s.split.map(&:capitalize).join(' ') session[:instructorName] = @instructorName @instructorName = session[:instructorName] session[:adecuacion_id] = Adecuacion.where(planformacion_id: session[:plan_id]).take.id flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"iniciotutor", action: "ver_detalles_adecuacion", plan_id: params[:param1], editar: params[:param2] else flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"iniciotutor", action: "index" end elsif params[:accion] == "mostrar informe" @inform = Informe.where(id: params[:param2].to_i).take if session[:usuario_id] == @inform.tutor_id session[:plan_id] = params[:param1].to_i session[:informe_id] = @inform.id plan = Planformacion.where(id: session[:plan_id]).take @inst = Persona.where(usuario_id: plan.instructor_id).take @instructorName = @inst.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @inst.apellidos.to_s.split.map(&:capitalize).join(' ') session[:instructorName] = @instructorName @instructorName = session[:instructorName] puts session[:instructorName] session[:adecuacion_id] = Adecuacion.where(planformacion_id: session[:plan_id]).take.id flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"informes", action: "ver_detalles_informe", informe_id: params[:param2] else flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"iniciotutor", action: "index" end elsif params[:accion] == "listar informes" flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "listar_informes" else flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"iniciotutor", action: "index" end elsif @entidad.nombre=="instructor" session[:usuario_id] = @usuario.id @persona = Persona.where(usuario_id: session[:usuario_id]).take session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] session[:administrador] = false session[:tutor]= false session[:instructor]= true session[:entidad]= false if params[:accion] == "mostrar adecuacion" if !Planformacion.where(instructor_id: session[:usuario_id]).take.blank? flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "ver_detalles_adecuacion" else flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "index" end elsif params[:accion] == "mostrar informe" if !Planformacion.where(instructor_id: session[:usuario_id]).take.blank? session[:plan_id] = params[:param1] flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "ver_detalles_informe", informe_id: params[:param2] else flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "index" end elsif params[:accion] == "listar informes" flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "listar_informes" else flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "index" end else session[:usuario_id]= @usuario.id @persona = Persona.where(usuario_id: session[:usuario_id]).take session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] session[:administrador] = false session[:tutor]= false session[:instructor]= false session[:entidad]= true flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"forminst", action: "index" end else if tipo=="Institucional" || tipo=="Vista" session[:usuario_id]= @usuario.id session[:administrador] = false session[:tutor]= false session[:instructor]= false session[:entidad]= true session[:entidad_id] = @entidad.id if(@entidad.nombre == "Comisiรณn de Investigaciรณn de Biologรญa") @depto = Departamento.where(id: @usuarioe.departamento_id).take if(@depto.blank?) puts "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq" puts @entidad.nombre session[:nombre_usuario] = @entidad.nombre else puts "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" session[:nombre_usuario] = @depto.nombre end else session[:nombre_usuario] = @entidad.nombre end if params[:accion] == "mostrar adecuacion" ea = EstatusAdecuacion.where(adecuacion_id: params[:param3], actual: 1).take.estatus_id a = [3,2,8,4,1,5,9] b = [2,8,4,1,5,9] c = [8,4,1,5,9] d = [4,1,5,9] if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12 && (a.include? ea)) || (session[:entidad_id] >= 14 && session[:entidad_id] <= 17 && (b.include? ea)) || (session[:entidad_id] >= 1 && session[:entidad_id] <= 6 && (c.include? ea)) || (session[:entidad_id] == 13 && (d.include? ea)) session[:plan_id] = plan.id plan = Planformacion.where(id: session[:plan_id]).take @inst = Persona.where(usuario_id: plan.instructor_id).take @instructorName = @inst.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @inst.apellidos.to_s.split.map(&:capitalize).join(' ') session[:instructorName] = @instructorName @instructorName = session[:instructorName] session[:adecuacion_id] = Adecuacion.where(planformacion_id: session[:plan_id]).take.id flash[:success]= "Bienvenido al " + @entidad.nombre redirect_to controller:"inicioentidad", action: "ver_detalles_adecuacion", adecuacion_id: params[:param3] else flash[:success]= "Bienvenido al " + @entidad.nombre redirect_to controller:"inicioentidad", action: "index" end elsif params[:accion] == "mostrar informe" ea = EstatusAdecuacion.where(adecuacion_id: params[:param3], actual: 1).take.estatus_id ea = ea.to_s a = ["3","2","8","4","1","5","9"] b = ["2","8","4","1","5","9"] c = ["8","4","1","5","9"] d = ["4","1","5","9"] if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12 && (a.include? ea)) || (session[:entidad_id] >= 14 && session[:entidad_id] <= 17 && (b.include? ea)) || (session[:entidad_id] >= 1 && session[:entidad_id] <= 6 && (c.include? ea)) || (session[:entidad_id] == 13 && (d.include? ea)) @inform = Informe.where(id: params[:param2].to_i).take session[:plan_id] = params[:param1].to_i session[:informe_id] = @inform.id plan = Planformacion.where(id: session[:plan_id]).take @inst = Persona.where(usuario_id: plan.instructor_id).take @instructorName = @inst.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @inst.apellidos.to_s.split.map(&:capitalize).join(' ') session[:instructorName] = @instructorName @instructorName = session[:instructorName] session[:adecuacion_id] = Adecuacion.where(planformacion_id: session[:plan_id]).take.id flash[:success]= "Bienvenido al " + @entidad.nombre redirect_to controller:"inicioentidad", action: "ver_detalles_informe", informe_id: params[:param2].to_i else flash[:success]= "Bienvenido al " + @entidad.nombre redirect_to controller:"inicioentidad", action: "index" end else flash[:success]= "Bienvenido al " + @entidad.nombre redirect_to controller:"inicioentidad", action: "index" end else flash.now[:mensaje] = 'Su contraseรฑa o correo electrรณnico es incorrecto.' redirect_to controller:"forminst", action: "index" end end else #en caso de no funcionar el ldap o de no econtrase el usuario en el mismo clave = Digest::SHA1.hexdigest(clave) #se encripta la clave resivida por el usuario para su posterior comparaciรณn if @usuario.email == correo #si el correo se encuentra registrado if @usuario.password == clave #y la clave es la misma @usuarioe= Usuarioentidad.where(usuario_id: @usuario.id).take @entidad= Entidad.find(@usuarioe.entidad_id) #segun el usuario se muestra su modulo y se almacenan los datos de las sesiones if tipo=="Secretaria" session[:usuario_id]= @usuario.id @persona = Persona.where(usuario_id: session[:usuario_id]).take session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] session[:administrador] = false session[:tutor]= false session[:instructor]= false session[:entidad]= true flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"secretarias", action: "index" elsif tipo == "Docente" if @entidad.nombre=="tutor" session[:usuario_id]= @usuario.id @persona = Persona.where(usuario_id: session[:usuario_id]).take session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] session[:administrador] = false session[:tutor]= true session[:instructor]= false session[:entidad]= false if params[:accion] == "mostrar adecuacion" plan = Planformacion.where(id: params[:param1].to_i).take if session[:usuario_id] == plan.tutor_id session[:plan_id] = plan.id @inst = Persona.where(usuario_id: plan.instructor_id).take @instructorName = @inst.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @inst.apellidos.to_s.split.map(&:capitalize).join(' ') session[:instructorName] = @instructorName @instructorName = session[:instructorName] session[:adecuacion_id] = Adecuacion.where(planformacion_id: session[:plan_id]).take.id flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"iniciotutor", action: "ver_detalles_adecuacion", plan_id: params[:param1], editar: params[:param2] else flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"iniciotutor", action: "index" end elsif params[:accion] == "mostrar informe" @inform = Informe.where(id: params[:param2].to_i).take if session[:usuario_id] == @inform.tutor_id session[:plan_id] = params[:param1].to_i session[:informe_id] = @inform.id plan = Planformacion.where(id: session[:plan_id]).take @inst = Persona.where(usuario_id: plan.instructor_id).take @instructorName = @inst.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @inst.apellidos.to_s.split.map(&:capitalize).join(' ') session[:instructorName] = @instructorName @instructorName = session[:instructorName] puts session[:instructorName] session[:adecuacion_id] = Adecuacion.where(planformacion_id: session[:plan_id]).take.id flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '+@<EMAIL>ize redirect_to controller:"informes", action: "ver_detalles_informe", informe_id: params[:param2] else flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '+@persona.<EMAIL>.titleize redirect_to controller:"iniciotutor", action: "index" end elsif params[:accion] == "listar informes" flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "listar_informes" else flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"iniciotutor", action: "index" end else if @entidad.nombre="instructor" session[:usuario_id] = @usuario.id @persona = Persona.where(usuario_id: session[:usuario_id]).take session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] session[:administrador] = false session[:tutor]= false session[:instructor]= true session[:entidad]= false if params[:accion] == "mostrar adecuacion" if !Planformacion.where(instructor_id: session[:usuario_id]).take.blank? flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "ver_detalles_adecuacion" else flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "index" end elsif params[:accion] == "mostrar informe" if !Planformacion.where(instructor_id: session[:usuario_id]).take.blank? session[:plan_id] = params[:param1] flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "ver_detalles_informe", informe_id: params[:param2] else flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "index" end elsif params[:accion] == "listar informes" flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "listar_informes" else flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"inicioinstructor", action: "index" end else session[:usuario_id]= @usuario.id @persona = Persona.where(usuario_id: session[:usuario_id]).take session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] session[:administrador] = false session[:tutor]= false session[:instructor]= false session[:entidad]= true flash[:success]= "Bienvenido! " + session[:nombre_usuario] = @persona.nombres.titleize+' '[email protected] redirect_to controller:"forminst", action: "index" end end elsif tipo == "Institucional" || tipo == "Vista" session[:usuario_id]= @usuario.id session[:administrador] = false session[:tutor]= false session[:instructor]= false session[:entidad]= true session[:entidad_id] = @entidad.id if(@entidad.nombre == "Comisiรณn de Investigaciรณn de Biologรญa") @depto = Departamento.where(id: @usuarioe.departamento_id).take if(@depto.blank?) puts "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq" puts @entidad.nombre session[:nombre_usuario] = @entidad.nombre else puts "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" session[:nombre_usuario] = @depto.nombre end else session[:nombre_usuario] = @entidad.nombre end if params[:accion] == "mostrar adecuacion" ea = EstatusAdecuacion.where(adecuacion_id: params[:param3], actual: 1).take.estatus_id a = [3,2,8,4,1,5,9] b = [2,8,4,1,5,9] c = [8,4,1,5,9] d = [4,1,5,9] if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12 && (a.include? ea)) || (session[:entidad_id] >= 14 && session[:entidad_id] <= 17 && (b.include? ea)) || (session[:entidad_id] >= 1 && session[:entidad_id] <= 6 && (c.include? ea)) || (session[:entidad_id] == 13 && (d.include? ea)) session[:plan_id] = plan.id plan = Planformacion.where(id: session[:plan_id]).take @inst = Persona.where(usuario_id: plan.instructor_id).take @instructorName = @inst.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @inst.apellidos.to_s.split.map(&:capitalize).join(' ') session[:instructorName] = @instructorName @instructorName = session[:instructorName] session[:adecuacion_id] = Adecuacion.where(planformacion_id: session[:plan_id]).take.id flash[:success]= "Bienvenido al " + @entidad.nombre redirect_to controller:"inicioentidad", action: "ver_detalles_adecuacion", adecuacion_id: params[:param3] else flash[:success]= "Bienvenido al " + @entidad.nombre redirect_to controller:"inicioentidad", action: "index" end elsif params[:accion] == "mostrar informe" ea = EstatusAdecuacion.where(adecuacion_id: params[:param3], actual: 1).take.estatus_id ea = ea.to_s a = ["3","2","8","4","1","5","9"] b = ["2","8","4","1","5","9"] c = ["8","4","1","5","9"] d = ["4","1","5","9"] if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12 && (a.include? ea)) || (session[:entidad_id] >= 14 && session[:entidad_id] <= 17 && (b.include? ea)) || (session[:entidad_id] >= 1 && session[:entidad_id] <= 6 && (c.include? ea)) || (session[:entidad_id] == 13 && (d.include? ea)) @inform = Informe.where(id: params[:param2].to_i).take session[:plan_id] = params[:param1].to_i session[:informe_id] = @inform.id plan = Planformacion.where(id: session[:plan_id]).take @inst = Persona.where(usuario_id: plan.instructor_id).take @instructorName = @inst.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @inst.apellidos.to_s.split.map(&:capitalize).join(' ') session[:instructorName] = @instructorName @instructorName = session[:instructorName] session[:adecuacion_id] = Adecuacion.where(planformacion_id: session[:plan_id]).take.id flash[:success]= "Bienvenido al " + @entidad.nombre redirect_to controller:"inicioentidad", action: "ver_detalles_informe", informe_id: params[:param2].to_i else flash[:success]= "Bienvenido al " + @entidad.nombre redirect_to controller:"inicioentidad", action: "index" end else flash[:success]= "Bienvenido al " + @entidad.nombre redirect_to controller:"inicioentidad", action: "index" end end #Autenticaciรณn Incorrecta else flash.now[:danger]="Su usuario o contraseรฑa son incorrectas" render 'index' end else flash.now[:danger]="Su usuario o contraseรฑa son incorrectas" render 'index' end end else flash.now[:danger]= "El usuario no estรก activo en el sistema" render 'index' end else flash[:danger]= "El usuario o la contraseรฑa son incorrectas" render 'index' end else flash[:danger]= "El usuario o la contraseรฑa son incorrectas" render "index" end end end <file_sep>/forminst_new1/app/assets/javascripts/informes.js // Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. function mostrarInputs(op, params, letra){ var numero = parseInt(letra); if (op == 1){ $("#tipos"+numero+params).show() $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 2){ $("#tipos"+numero+params).css({display: "none"}) $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).show() $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 3){ $("#tipos"+numero+params).css({display: "none"}) $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).show() $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 4){ $("#tipos"+numero+params).css({display: "none"}) $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).show() $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 5){ $("#tipos"+numero+params).css({display: "none"}) $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).show() $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 6){ $("#tipos"+numero+params).css({display: "none"}) $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).show() $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 7){ $("#tipos"+numero+params).css({display: "none"}) $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).show() }else{ $("#tipos"+numero+params).css({display: "none"}) $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }; } function mostrarInputsTipos(op,params,letra){ var numero = parseInt(letra); if (op == 1) { /*$("#tipos").show()*/ $("#cplibro"+numero+params).show() $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 2) { $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).show() $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 3) { $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).show() $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 4) { $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).show() $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 5) { $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).show() $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 6) { $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).show() $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 7) { $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).show() $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 8) { $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).show() $("#cpcapitulolibro"+numero+params).css({display: "none"}) $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else if (op == 9) { $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).show() $("#cppresentacionp"+numero+params).css({display: "none"}) $("#cppresentacioni"+numero+params).css({display: "none"}) $("#cpotro"+numero+params).css({display: "none"}) $("#cpasistenciae"+numero+params).css({display: "none"}) $("#cporganizaione"+numero+params).css({display: "none"}) $("#cpdictadoc"+numero+params).css({display: "none"}) }else{ $("#cplibro"+numero+params).css({display: "none"}) $("#cprevista"+numero+params).css({display: "none"}) $("#cpprensa"+numero+params).css({display: "none"}) $("#cpcd"+numero+params).css({display: "none"}) $("#cpmanuales"+numero+params).css({display: "none"}) $("#cppelectronicas"+numero+params).css({display: "none"}) $("#tesis"+numero+params).css({display: "none"}) $("#cpactaconferencia"+numero+params).css({display: "none"}) $("#cpcapitulolibro"+numero+params).css({display: "none"}) }; } <file_sep>/forminst_new1/app/controllers/estatusinformes_controller.rb class EstatusinformesController < ApplicationController before_action :set_estatusinforme, only: [:show, :edit, :update, :destroy] # GET /estatusinformes # GET /estatusinformes.json def index @estatusinformes = Estatusinforme.all end # GET /estatusinformes/1 # GET /estatusinformes/1.json def show end # GET /estatusinformes/new def new @estatusinforme = Estatusinforme.new end # GET /estatusinformes/1/edit def edit end # POST /estatusinformes # POST /estatusinformes.json def create @estatusinforme = Estatusinforme.new(estatusinforme_params) respond_to do |format| if @estatusinforme.save format.html { redirect_to @estatusinforme, notice: 'Estatusinforme was successfully created.' } format.json { render :show, status: :created, location: @estatusinforme } else format.html { render :new } format.json { render json: @estatusinforme.errors, status: :unprocessable_entity } end end end # PATCH/PUT /estatusinformes/1 # PATCH/PUT /estatusinformes/1.json def update respond_to do |format| if @estatusinforme.update(estatusinforme_params) format.html { redirect_to @estatusinforme, notice: 'Estatusinforme was successfully updated.' } format.json { render :show, status: :ok, location: @estatusinforme } else format.html { render :edit } format.json { render json: @estatusinforme.errors, status: :unprocessable_entity } end end end # DELETE /estatusinformes/1 # DELETE /estatusinformes/1.json def destroy @estatusinforme.destroy respond_to do |format| format.html { redirect_to estatusinformes_url, notice: 'Estatusinforme was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_estatusinforme @estatusinforme = Estatusinforme.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def estatusinforme_params params.require(:estatusinforme).permit(:id, :informeId, :fecha, :estatusId, :actual) end end <file_sep>/forminst_new1/app/models/tutor.rb class Tutor < ActiveRecord::Base belongs_to :usuario end <file_sep>/forminst_new1/app/controllers/observaciontutors_controller.rb class ObservaciontutorsController < ApplicationController before_action :set_observaciontutor, only: [:show, :edit, :update, :destroy] # GET /observaciontutors # GET /observaciontutors.json def index @observaciontutors = Observaciontutor.all end # GET /observaciontutors/1 # GET /observaciontutors/1.json def show end # GET /observaciontutors/new def new @observaciontutor = Observaciontutor.new end # GET /observaciontutors/1/edit def edit end # POST /observaciontutors # POST /observaciontutors.json def create @observaciontutor = Observaciontutor.new(observaciontutor_params) respond_to do |format| if @observaciontutor.save format.html { redirect_to @observaciontutor, notice: 'Observaciontutor was successfully created.' } format.json { render :show, status: :created, location: @observaciontutor } else format.html { render :new } format.json { render json: @observaciontutor.errors, status: :unprocessable_entity } end end end # PATCH/PUT /observaciontutors/1 # PATCH/PUT /observaciontutors/1.json def update respond_to do |format| if @observaciontutor.update(observaciontutor_params) format.html { redirect_to @observaciontutor, notice: 'Observaciontutor was successfully updated.' } format.json { render :show, status: :ok, location: @observaciontutor } else format.html { render :edit } format.json { render json: @observaciontutor.errors, status: :unprocessable_entity } end end end # DELETE /observaciontutors/1 # DELETE /observaciontutors/1.json def destroy @observaciontutor.destroy respond_to do |format| format.html { redirect_to observaciontutors_url, notice: 'Observaciontutor was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_observaciontutor @observaciontutor = Observaciontutor.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def observaciontutor_params params.require(:observaciontutor).permit(:id, :informeActividadId, :observacion, :fecha, :actual) end end <file_sep>/forminst_new1/app/views/tipoactividads/index.json.jbuilder json.array!(@tipoactividads) do |tipoactividad| json.extract! tipoactividad, :id, :id, :concepto, :grupoActividadesId, :subGrupoActividadId json.url tipoactividad_url(tipoactividad, format: :json) end <file_sep>/forminst_new1/test/controllers/estatusinformes_controller_test.rb require 'test_helper' class EstatusinformesControllerTest < ActionController::TestCase setup do @estatusinforme = estatusinformes(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:estatusinformes) end test "should get new" do get :new assert_response :success end test "should create estatusinforme" do assert_difference('Estatusinforme.count') do post :create, estatusinforme: { actual: @estatusinforme.actual, estatusId: @estatusinforme.estatusId, fecha: @estatusinforme.fecha, id: @estatusinforme.id, informeId: @estatusinforme.informeId } end assert_redirected_to estatusinforme_path(assigns(:estatusinforme)) end test "should show estatusinforme" do get :show, id: @estatusinforme assert_response :success end test "should get edit" do get :edit, id: @estatusinforme assert_response :success end test "should update estatusinforme" do patch :update, id: @estatusinforme, estatusinforme: { actual: @estatusinforme.actual, estatusId: @estatusinforme.estatusId, fecha: @estatusinforme.fecha, id: @estatusinforme.id, informeId: @estatusinforme.informeId } assert_redirected_to estatusinforme_path(assigns(:estatusinforme)) end test "should destroy estatusinforme" do assert_difference('Estatusinforme.count', -1) do delete :destroy, id: @estatusinforme end assert_redirected_to estatusinformes_path end end <file_sep>/forminst_new1/app/models/estatusinforme.rb class Estatusinforme < ActiveRecord::Base belongs_to :informe belongs_to :tipoestatus end<file_sep>/forminst_new1/app/models/resultado.rb class Resultado < ActiveRecord::Base belongs_to :actividad belongs_to :tipo_resultado has_one :informe_actividad end<file_sep>/forminst_new1/test/controllers/documentoinformes_controller_test.rb require 'test_helper' class DocumentoinformesControllerTest < ActionController::TestCase setup do @documentoinforme = documentoinformes(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:documentoinformes) end test "should get new" do get :new assert_response :success end test "should create documentoinforme" do assert_difference('Documentoinforme.count') do post :create, documentoinforme: { archivo: @documentoinforme.archivo, id: @documentoinforme.id, informeId: @documentoinforme.informeId } end assert_redirected_to documentoinforme_path(assigns(:documentoinforme)) end test "should show documentoinforme" do get :show, id: @documentoinforme assert_response :success end test "should get edit" do get :edit, id: @documentoinforme assert_response :success end test "should update documentoinforme" do patch :update, id: @documentoinforme, documentoinforme: { archivo: @documentoinforme.archivo, id: @documentoinforme.id, informeId: @documentoinforme.informeId } assert_redirected_to documentoinforme_path(assigns(:documentoinforme)) end test "should destroy documentoinforme" do assert_difference('Documentoinforme.count', -1) do delete :destroy, id: @documentoinforme end assert_redirected_to documentoinformes_path end end <file_sep>/forminst_new1/app/models/observacionactividadadecuacion.rb class Observacionesactividadadecuacion < ActiveRecord::Base belongs_to :revision belongs_to :adecuacionactividad end<file_sep>/forminst_new1/app/models/tipoactividad.rb class Tipoactividad < ActiveRecord::Base has_many :actividad has_many :tiporesultado end<file_sep>/forminst_new1/app/controllers/inicio_controller.rb class InicioController < ApplicationController layout 'inicio' def index puts "estoy entrando al index" end add_flash_types :danger,:info, :warning, :success def autenticar ldap= Net::LDAP.new(:host=>"strix.ciens.ucv.ve",:port=>389, :auth=>{:method=> :simple, :username=>"cn=zaira, dc=ciens, dc=ucv, dc=ve", :password => "<PASSWORD>"}) correo= params[:correo] clave= paramas[:clave] result = ldap.bind_as(:base => "dc=ciens, dc=ucv, dc=ve", :filter => "(uid=#{correo})", :password => <PASSWORD>) if result @usuario = Usuario.where(user: correo) if @usuario.activo == 1 if @usuario.ldap == 1 else flash[:mensaje]= "El usuario no debe autenticarse por ldap" end else flash[:mensaje]= "El usuario no estรก activo" end else end end end <file_sep>/forminst_new1/app/models/adecuacion_actividad.rb class AdecuacionActividad < ActiveRecord::Base belongs_to :adecuacion has_many :observacion_actividadad_adecuacion belongs_to :actividad end <file_sep>/forminst_new1/app/views/planformacions/index.json.jbuilder json.array!(@planformacions) do |planformacion| json.extract! planformacion, :id, :id, :fechaInicio, :fechaFin, :activo, :instructorId, :tutorId json.url planformacion_url(planformacion, format: :json) end <file_sep>/forminst_new1/app/controllers/tiporesultados_controller.rb class TiporesultadosController < ApplicationController before_action :set_tiporesultado, only: [:show, :edit, :update, :destroy] # GET /tiporesultados # GET /tiporesultados.json def index @tiporesultados = Tiporesultado.all end # GET /tiporesultados/1 # GET /tiporesultados/1.json def show end # GET /tiporesultados/new def new @tiporesultado = Tiporesultado.new end # GET /tiporesultados/1/edit def edit end # POST /tiporesultados # POST /tiporesultados.json def create @tiporesultado = Tiporesultado.new(tiporesultado_params) respond_to do |format| if @tiporesultado.save format.html { redirect_to @tiporesultado, notice: 'Tiporesultado was successfully created.' } format.json { render :show, status: :created, location: @tiporesultado } else format.html { render :new } format.json { render json: @tiporesultado.errors, status: :unprocessable_entity } end end end # PATCH/PUT /tiporesultados/1 # PATCH/PUT /tiporesultados/1.json def update respond_to do |format| if @tiporesultado.update(tiporesultado_params) format.html { redirect_to @tiporesultado, notice: 'Tiporesultado was successfully updated.' } format.json { render :show, status: :ok, location: @tiporesultado } else format.html { render :edit } format.json { render json: @tiporesultado.errors, status: :unprocessable_entity } end end end # DELETE /tiporesultados/1 # DELETE /tiporesultados/1.json def destroy @tiporesultado.destroy respond_to do |format| format.html { redirect_to tiporesultados_url, notice: 'Tiporesultado was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_tiporesultado @tiporesultado = Tiporesultado.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def tiporesultado_params params.require(:tiporesultado).permit(:id, :tipoActividadId, :idPadre, :concepto) end end <file_sep>/forminst_new1/app/views/observacionactividadadecuacions/index.json.jbuilder json.array!(@observacionactividadadecuacions) do |observacionactividadadecuacion| json.extract! observacionactividadadecuacion, :id, :id, :revisionId, :adecuacionActividadId, :observacion, :fecha json.url observacionactividadadecuacion_url(observacionactividadadecuacion, format: :json) end <file_sep>/forminst_new1/app/models/instructortutor.rb class Instructortutor < ActiveRecord::Base has_many :usuario end <file_sep>/forminst_new1/app/models/actividad_ejecutada.rb class ActividadEjecutada < ActiveRecord::Base belongs_to :informe_actividad end <file_sep>/forminst_new1/app/views/entidads/show.json.jbuilder json.extract! @entidad, :id, :id, :nombre, :escuelaId, :created_at, :updated_at <file_sep>/forminst_new1/app/views/estatusadecuacions/index.json.jbuilder json.array!(@estatusadecuacions) do |estatusadecuacion| json.extract! estatusadecuacion, :id, :id, :adecuacionId, :fecha, :estatusId, :actual json.url estatusadecuacion_url(estatusadecuacion, format: :json) end <file_sep>/forminst_new1/app/assets/javascripts/evitar_doble_envio.js $('#boton_enviar').click(function(e) { $(this).prop('disabled', true); $(this).addClass('disabled'); //do other stuff when a click happens });<file_sep>/forminst_new1/app/models/adecuacion.rb class Adecuacion < ActiveRecord::Base belongs_to :usuario belongs_to :planformacion has_many :estatus_adecuacion has_many :revision has_many :adecuacion_actividad end<file_sep>/forminst_new1/app/models/documentoplan.rb class Documentoplan < ActiveRecord::Base belongs_to :planformacion end<file_sep>/forminst_new1/app/controllers/estatusadecuacions_controller.rb class EstatusadecuacionsController < ApplicationController before_action :set_estatusadecuacion, only: [:show, :edit, :update, :destroy] # GET /estatusadecuacions # GET /estatusadecuacions.json def index @estatusadecuacions = Estatusadecuacion.all end # GET /estatusadecuacions/1 # GET /estatusadecuacions/1.json def show end # GET /estatusadecuacions/new def new @estatusadecuacion = Estatusadecuacion.new end # GET /estatusadecuacions/1/edit def edit end # POST /estatusadecuacions # POST /estatusadecuacions.json def create @estatusadecuacion = Estatusadecuacion.new(estatusadecuacion_params) respond_to do |format| if @estatusadecuacion.save format.html { redirect_to @estatusadecuacion, notice: 'Estatusadecuacion was successfully created.' } format.json { render :show, status: :created, location: @estatusadecuacion } else format.html { render :new } format.json { render json: @estatusadecuacion.errors, status: :unprocessable_entity } end end end # PATCH/PUT /estatusadecuacions/1 # PATCH/PUT /estatusadecuacions/1.json def update respond_to do |format| if @estatusadecuacion.update(estatusadecuacion_params) format.html { redirect_to @estatusadecuacion, notice: 'Estatusadecuacion was successfully updated.' } format.json { render :show, status: :ok, location: @estatusadecuacion } else format.html { render :edit } format.json { render json: @estatusadecuacion.errors, status: :unprocessable_entity } end end end # DELETE /estatusadecuacions/1 # DELETE /estatusadecuacions/1.json def destroy @estatusadecuacion.destroy respond_to do |format| format.html { redirect_to estatusadecuacions_url, notice: 'Estatusadecuacion was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_estatusadecuacion @estatusadecuacion = Estatusadecuacion.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def estatusadecuacion_params params.require(:estatusadecuacion).permit(:id, :adecuacionId, :fecha, :estatusId, :actual) end end <file_sep>/forminst_new1/app/models/estatus_adecuacion.rb class EstatusAdecuacion < ActiveRecord::Base belongs_to :adecuacion belongs_to :tipo_estatus end <file_sep>/forminst_new1/app/views/permisos/show.json.jbuilder json.extract! @permiso, :id, :id, :concepto, :created_at, :updated_at <file_sep>/forminst_new1/app/controllers/documents_controller.rb class DocumentsController < ApplicationController layout 'ly_inicio_tutor' before_action :set_document, only: [:show, :edit, :update, :destroy] # GET /documents # GET /documents.json def index #pdf_filename = File.join(Rails.root, "tmp/PDFs/18810993-2017-07-02-adecuacion.pdf") #send_file(pdf_filename, :filename => "18810993-2017-07-02-adecuacion.pdf", :disposition => 'inline', :type => "application/pdf") #validar si se envio la adecuacion if session[:usuario_id] && session[:tutor] if(!session[:plan_id].blank?) @bool_enviado = 0 @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take if session[:informe_id].blank? estatus_x = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take else estatus_x = EstatusInforme.where(informe_id: session[:informe_id], actual: 1).take end if (estatus_x.estatus_id != 6 && estatus_x.estatus_id != 5) @bool_enviado = 1 end @plan = Planformacion.where(id: session[:plan_id]).take if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@plan.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end $actividad = params[:actividad_id].to_i @documents = [] if !session[:informe_id].blank? @documents = Document.where("informe_id <= ? AND adecuacion_id = ? AND actividad_id = ?",session[:informe_id].to_i , session[:adecuacion_id], $actividad).all else @documents = Document.where(adecuacion_id: session[:adecuacion_id], informe_id: nil).all end else flash.now[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end # GET /documents/1.json def show puts "holaaaaaaaaaaaaaaaaaaaaaa" puts params[:commit] puts @document.filename send_data(@document.file_contents, type: @document.content_type, filename: @document.filename, disposition: 'inline') end # GET /documents/new def new @bool_enviado = 0 if(!session[:plan_id].blank?) @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take if session[:informe_id].blank? estatus_x = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take else estatus_x = EstatusInforme.where(informe_id: session[:informe_id], actual: 1).take end if (estatus_x.estatus_id != 6 && estatus_x.estatus_id != 5) @bool_enviado = 1 end if ( @bool_enviado == 1) flash.now[:info]="No puede aรฑadir soportes, ya ha enviado la adecuaciรณn" else @document = Document.new end else flash.now[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end end # GET /documents/1/edit def edit end # POST /documents # POST /documents.json def create if session[:usuario_id] && session[:tutor] if params[:document].present? @document = Document.new(document_params) @planformacion = Planformacion.find(session[:plan_id]) @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take @document.instructor_id = @planformacion.instructor_id @document.tutor_id = session[:usuario_id] @document.adecuacion_id = @adecuacion.id @document.informe_id = session[:informe_id] @document.actividad_id = $actividad if @document.save flash[:success]="El documento se ha subido con exito" redirect_to controller:"documents", action: "index", :actividad_id => $actividad else flash[:danger]="Error: Recuerde que el documento debe ser un pdf que ocupe menos de 1MB" redirect_to controller:"documents", action: "new" end else flash[:info]="Debe seleccionar un archivo antes de cargar" redirect_to controller:"documents", action: "new" end else redirect_to controller:"forminst", action: "index" end end # PATCH/PUT /documents/1 # PATCH/PUT /documents/1.json def update respond_to do |format| if @document.update(document_params) format.html { redirect_to @document, notice: 'Document was successfully updated.' } format.json { render :show, status: :ok, location: @document } else format.html { render :edit } format.json { render json: @document.errors, status: :unprocessable_entity } end end end # DELETE /documents/1 # DELETE /documents/1.json def destroy @document.destroy flash[:success]="El documento fue borrado con exito" redirect_to controller:"documents", action: "index", :actividad_id => $actividad end private # Use callbacks to share common setup or constraints between actions. def set_document @document = Document.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def document_params params.require(:document).permit(:file) end end <file_sep>/forminst_new1/app/controllers/inicioentidad_controller.rb class InicioentidadController < ApplicationController layout 'ly_inicio_entidad' def index if session[:usuario_id] && session[:entidad] == true session[:adecuacion_id] = nil session[:plan_id] = nil session[:instructorName] = nil session[:informe_id]=nil @usuarioAux=Usuario.find(session[:usuario_id]) @[email protected] @nombre = session[:nombre_usuario] @usu=Usuarioentidad.where(usuario_id: @usuarioAux.id).take @entidad_escuela_id= @usu.escuela_id @notificaciones1= [] puts @usu.departamento_id puts "aaaaaaaaaaaaaaaaaaaaaaaaaaa" puts @entidad_escuela_id if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12)#Caso de Comision de Investigaciรณn if(@entidad_escuela_id == 1) @notificaciones = Notificacion.where(actual: 3, departamento_id: @usu.departamento_id).all else @notificaciones = Notificacion.where(actual: 3).all end @notificaciones.each do |notificaciones| @tutor_escuela = Usuarioentidad.where(usuario_id: notificaciones.tutor_id).take if (@tutor_escuela.escuela_id == @entidad_escuela_id) #Caso de notificaciones del Comision de investigaciรณn @notificaciones1.push(notificaciones) end end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6)#Caso Consejo de Escuela @notificaciones = Notificacion.where(actual: 4).all @notificaciones.each do |notificaciones| @tutor_escuela = Usuarioentidad.where(usuario_id: notificaciones.tutor_id).take if (@tutor_escuela.escuela_id == @entidad_escuela_id) #Caso de notificaciones del Comision de investigaciรณn @notificaciones1.push(notificaciones) end end elsif (session[:entidad_id] == 13) #Caso Consejo de Facultad @notificaciones1 = Notificacion.where(actual: 5).all end else redirect_to controller:"forminst", action: "index" end end #Cerrar Sesiรณn def logout reset_session redirect_to controller: "forminst", action: "index" end #Modulo para activar a los instructores inhabilitados def reactivacion if session[:usuario_id] enti = Usuarioentidad.where(usuario_id: session[:usuario_id]).take end #Solamente el consejo de facultad tiene la posibilidad de reactivar instructores if session[:usuario_id] && session[:entidad] == true && enti.entidad_id == 13 session[:adecuacion_id] = nil session[:plan_id] = nil session[:instructorName] = nil session[:informe_id]=nil @cjpTipo=Usuario.find(session[:usuario_id]).tipo @nombre = session[:nombre_usuario] @usu=Usuarioentidad.where(entidad_id: session[:entidad_id]).take @entidad_escuela_id= @usu.escuela_id @usuarios = Usuario.where(activo: 0).all @instructores = [] cpcontador = 0 @instructores[cpcontador] = Array.new(2) { |i| } @instructores[cpcontador][0] = "Seleccione el instructor" @instructores[cpcontador][1] = 0 cpcontador = cpcontador + 1 @usuarios.each do |usuari| #Arreglo con los usuarios inahibilitados cppersona = Persona.find_by usuario_id: usuari.id @instructores[cpcontador] = Array.new(2) { |i| } @instructores[cpcontador][0] = cppersona.nombres.to_s.split.map(&:capitalize).join(' ') + " " + cppersona.apellidos.to_s.split.map(&:capitalize).join(' ') @instructores[cpcontador][1] = usuari.id cpcontador = cpcontador + 1 end i = 1 j = 1 nombre = "hola" cpid = 1 #Ordena los nombres por orden alfabetico (Ordenamiento Burbuja) while i < cpcontador do nombre = @instructores[i][0] cpid = @instructores[i][1] j = i + 1 while j < cpcontador do if @instructores[j][0] < nombre @instructores[i][0] = @instructores[j][0] @instructores[i][1] = @instructores[j][1] @instructores[j][0] = nombre @instructores[j][1] = cpid nombre = @instructores[i][0] cpid = @instructores[i][1] end j +=1 end i +=1 end else redirect_to controller:"forminst", action: "index" end end #Guardar la reactivacion de Usuarios def reactivacion_guardar if session[:usuario_id] if params[:Instructor].to_s != "0" usuari = Usuario.where(id: params[:Instructor]).take if !usuari.blank? usuari.activo = 1 usuari.save pers = Persona.where(usuario_id: usuari.id).take nombres = pers.nombres.to_s.split.map(&:capitalize).join(' ') + " " + pers.apellidos.to_s.split.map(&:capitalize).join(' ') flash[:success]= "Se ha habilitado a " + nombres + " de manera exitosa" else flash[:danger]= "Error al seleccionar usuario, puede no existir en la Base de Datos" end else flash[:info]= "Debe seleccionar un instructor primero" end redirect_to :back else redirect_to controller:"forminst", action: "index" end end #Lista las adecuaciones, independientemente si fueron ya enviadas a entidades mayores def listar_adecuaciones if session[:usuario_id] && session[:entidad]== true session[:informe_id]=nil @cjpTipo=Usuario.find(session[:usuario_id]).tipo session[:adecuacion_id]=nil @nombre = session[:nombre_usuario] @usu=Usuarioentidad.where(usuario_id: session[:usuario_id]).take @entidad_escuela_id= @usu.escuela_id @entidad_departamento= @usu.departamento_id @adecuaciones = [] @status = [] @fecha_status = [] @nombre_tutor = [] @nombre_instructor = [] if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision @status_inv = EstatusAdecuacion.where(actual: 1, estatus_id: [3,2,8,4,1,5,9,12,13,14,18]).order(fecha: :desc) #Estatus enviado a comision de investigacion #.order(fecha: :desc) para ordenar el arreglo poniendo los mas nuevos primero else if (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico @status_inv = EstatusAdecuacion.where(actual: 1, estatus_id: [2,8,4,1,5,9,12,18,14]).order(fecha: :desc) #Estatus enviado a consejo tecnico else if (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela @status_inv = EstatusAdecuacion.where(actual: 1, estatus_id: [8,4,1,5,9,18,14]).order(fecha: :desc) #Estatus enviado a consejo escuela else if (session[:entidad_id] == 13) #Consejo de facultad @status_inv = EstatusAdecuacion.where(actual: 1, estatus_id: [4,1,5,9,14]).order(fecha: :desc) #Estatus enviado a consejo de facultad @entidad_escuela_id=nil end end end end @status_inv.each do |si| @adec= Adecuacion.find(si.adecuacion_id) @pf = Planformacion.find(@adec.planformacion_id) if (session[:entidad_id] == 13) @adecuacion = true @adecuaciones.push(@adec) if(si.estatus_id==1) @st = "APROBADO POR CONSEJO DE FACULTAD" elsif(si.estatus_id==2) @st = "ENVIADO A CONSEJO Tร‰CNICO" elsif(si.estatus_id==3) @st = "ENVIADO A COMISION DE INVESTIGACIร“N" elsif(si.estatus_id==4) @st = "ENVIADO A CONSEJO DE FACULTAD" elsif(si.estatus_id==5) @st = "APROBADO CON OBSERVACIONES POR CONSEJO DE FACULTAD" elsif(si.estatus_id==8) @st = "ENVIADO A CONSEJO DE ESCUELA" elsif(si.estatus_id==9) @st = "RECHAZADO POR CONSEJO DE FACULTAD" elsif(si.estatus_id==12) @st = "ENVIADO A CONSEJO Tร‰CNICO SIN REVISIร“N" elsif(si.estatus_id==13) @st = "ENVIADO A COMISIร“N DE INVESTIGACIร“N SIN REVISIร“N" elsif(si.estatus_id==14) @st = "ENVIADO A CONSEJO DE FACULTAD SIN REVISIร“N" elsif(si.estatus_id==18) @st = "ENVIADO A CONSEJO DE ESCUELA SIN REVISIร“N" end tutor_aux= Persona.where(usuario_id: @pf.tutor_id) instructor_aux= Persona.where(usuario_id: @pf.instructor_id) @nombre_tutor.push(tutor_aux.take.nombres.split.map(&:capitalize).join(' ') + " " + tutor_aux.take.apellidos.split.map(&:capitalize).join(' ')) @nombre_instructor.push(instructor_aux.take.nombres.split.map(&:capitalize).join(' ') + " " + instructor_aux.take.apellidos.split.map(&:capitalize).join(' ')) @fecha_status.push(si.fecha) @status.push(@st) else #Para que salgan las adecuaciones correspondientes a la escuela y al departamento @tutor_escuela = Usuarioentidad.where(usuario_id: @adec.tutor_id).take if @tutor_escuela.escuela_id == @entidad_escuela_id && (@tutor_escuela.departamento_id == @entidad_departamento || @entidad_departamento == nil) @adecuacion = true @adecuaciones.push(@adec) if(si.estatus_id==1) @st = "APROBADO POR CONSEJO DE FACULTAD" elsif(si.estatus_id==2) @st = "ENVIADO A CONSEJO Tร‰CNICO" elsif(si.estatus_id==3) @st = "ENVIADO A COMISION DE INVESTIGACIร“N" elsif(si.estatus_id==4) @st = "ENVIADO A CONSEJO DE FACULTAD" elsif(si.estatus_id==5) @st = "APROBADO CON OBSERVACIONES POR CONSEJO DE FACULTAD" elsif(si.estatus_id==8) @st = "ENVIADO A CONSEJO DE ESCUELA" elsif(si.estatus_id==9) @st = "RECHAZADO POR CONSEJO DE FACULTAD" elsif(si.estatus_id==12) @st = "ENVIADO A CONSEJO Tร‰CNICO SIN REVISIร“N" elsif(si.estatus_id==13) @st = "ENVIADO A COMISIร“N DE INVESTIGACIร“N SIN REVISIร“N" elsif(si.estatus_id==14) @st = "ENVIADO A CONSEJO DE FACULTAD SIN REVISIร“N" elsif(si.estatus_id==18) @st = "ENVIADO A CONSEJO DE ESCUELA SIN REVISIร“N" end tutor_aux= Persona.where(usuario_id: @pf.tutor_id) instructor_aux= Persona.where(usuario_id: @pf.instructor_id) @nombre_tutor.push(tutor_aux.take.nombres.split.map(&:capitalize).join(' ') + " " + tutor_aux.take.apellidos.split.map(&:capitalize).join(' ')) @nombre_instructor.push(instructor_aux.take.nombres.split.map(&:capitalize).join(' ') + " " + instructor_aux.take.apellidos.split.map(&:capitalize).join(' ')) @fecha_status.push(si.fecha) @status.push(@st) end end end else redirect_to controller:"forminst", action: "index" end end #Modulo para poder visualizar los soportes adjuntados por el tutor def ver_soporte if(!session[:plan_id].blank?) @plan = Planformacion.where(id: session[:plan_id]).take @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take @documents = [] @cjpTipo=Usuario.find(session[:usuario_id]).tipo if !session[:informe_id].blank? $actividad = params[:actividad_id].to_i adec = Adecuacion.where(planformacion_id: session[:plan_id]).take session[:adecuacion_id] = adec.id @documents = Document.where("informe_id <= ? AND adecuacion_id = ? AND actividad_id = ?",session[:informe_id] , session[:adecuacion_id], $actividad).all @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusInforme.where(informe_id: session[:informe_id], actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusInforme.where(informe_id: session[:informe_id], actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusInforme.where(informe_id: session[:informe_id], actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusInforme.where(informe_id: session[:informe_id], actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end else @documents = Document.where(adecuacion_id: session[:adecuacion_id], informe_id: nil).all @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusAdecuacion.where(adecuacion_id: session[:adecuacion_id], actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusAdecuacion.where(adecuacion_id: session[:adecuacion_id], actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusAdecuacion.where(adecuacion_id: session[:adecuacion_id], actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusAdecuacion.where(adecuacion_id: session[:adecuacion_id], actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end end #Modulo para ver la primera pestaรฑa de las adecuaciones def ver_detalles_adecuacion if session[:usuario_id] && session[:entidad] == true if (!session[:adecuacion_id].blank? || !params[:adecuacion_id].blank?) @cjpTipo=Usuario.find(session[:usuario_id]).tipo @nombre = session[:nombre_usuario] @modifique=false session[:informe_id] = nil @cant_delete= params[:cant_delete] @cant_edit= params[:cant_edit] @cant_doc= params[:cant_docencia] @cant_inv= params[:cant_investigacion] @cant_for= params[:cant_formacion] @cant_ext= params[:cant_extension] @cant_otr= params[:cant_otra] semestre= params[:semestre].to_i if params[:adecuacion_id]!=nil session[:adecuacion_id]= params[:adecuacion_id] end @tutoresAnteriores = Instructortutor.where(instructor_id: session[:usuario_id], actual: 0) @adecuacion= Adecuacion.find(session[:adecuacion_id]) @plan= Planformacion.find(@adecuacion.planformacion_id) @inst = Persona.where(usuario_id: @plan.instructor_id).take @instructorName = @inst.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @inst.apellidos.to_s.split.map(&:capitalize).join(' ') session[:instructorName] = @instructorName session[:plan_id] = @plan.id @userentidad= Usuarioentidad.where(usuario_id: @plan.instructor_id).take if @userentidad.escuela_id == nil @userentidad.escuela_id=12 @userentidad.save @escuela= Escuela.where(id: @userentidad.escuela_id).take else @escuela= Escuela.where(id: @userentidad.escuela_id).take end @instructor= Persona.where(usuario_id: @plan.instructor_id).take @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end @nombre = session[:nombre_usuario] @adecuacion= Adecuacion.find(session[:adecuacion_id]) @plan= Planformacion.find(@adecuacion.planformacion_id) @userentidad= Usuarioentidad.where(usuario_id: @plan.instructor_id).take if @userentidad.escuela_id == nil @userentidad.escuela_id=12 @userentidad.save @escuela= Escuela.where(id: @userentidad.escuela_id).take else @escuela= Escuela.where(id: @userentidad.escuela_id).take end @persona= Persona.where(usuario_id: @plan.instructor_id).take @usuario= Usuario.find(@plan.instructor_id) @cpTutor= Persona.where(usuario_id: @plan.tutor_id).take @cpTutorEmail= Usuario.find(@plan.tutor_id).email @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end else redirect_to controller:"forminst", action: "index" end end #Modulo para ver la segunda pestaรฑa de las adecuaciones def detalles_adecuacion2 if session[:usuario_id] && session[:entidad] if session[:adecuacion_id] @cjpTipo=Usuario.find(session[:usuario_id]).tipo if params[:plan_id] @planformacion = Planformacion.find(params[:plan_id]) session[:editar]= true session[:plan_id] = @planformacion.id @inst = Persona.where(usuario_id: @plan.instructor_id).take @instructorName = @inst.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @inst.apellidos.to_s.split.map(&:capitalize).join(' ') session[:instructorName] = @instructorName @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take session[:adecuacion_id]= @adecuacion.id else @planformacion = Planformacion.find(session[:plan_id]) end @nombre = session[:nombre_usuario] @semestre="0" @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observaciont= [] @observacionesExtras= [] @iddoc= 'id_docencia' @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @j=0 if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@planformacion.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id).take @revision= Revision.where(usuario_id: session[:usuario_id], adecuacion_id: @adecuacion.id, estatus_id: @est.estatus_id, informe_id: nil).take actividades = AdecuacionActividad.where(adecuacion_id: session[:adecuacion_id], semestre: 0) if !actividades.blank? actividades.each do |actividadAde| actividad = Actividad.find(actividadAde.actividad_id) if actividad.tipo_actividad_id == 9 @presentacion = actividad.actividad @presentacionId = actividad.id if(@revision!=nil && @revision != "") @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: @presentacionId).where.not(revision_id: @revision.id).all else @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: @presentacionId).all end if @cpObs.blank? @observacionesExtras[@presentacionId]="no" else @observacionesExtras[@presentacionId]="si" end elsif actividad.tipo_actividad_id == 8 @descripcion = actividad.actividad @descripcionId = actividad.id if(@revision!=nil && @revision != "") @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: @descripcionId).where.not(revision_id: @revision.id).all else @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: @descripcionId).all end if @cpObs.blank? @observacionesExtras[@descripcionId]="no" else @observacionesExtras[@descripcionId]="si" end end end end @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id).take @revision= Revision.where(usuario_id: session[:usuario_id], adecuacion_id: @adecuacion.id, estatus_id: @est.estatus_id, informe_id: nil).take @actividadesa= AdecuacionActividad.where(adecuacion_id: session[:adecuacion_id], semestre: 0).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if(@revision!=nil && @revision != "") @obs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id, revision_id: @revision.id).take if @obs==nil @observaciont[@<EMAIL>] = "" else @observaciont[@<EMAIL>] = @obs.observaciones end @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).where.not(revision_id: @revision.id).all if @cpObs.blank? <EMAIL>]="no" else <EMAIL>]="si" end else @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @<EMAIL>]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 <EMAIL>]="no" else @<EMAIL>]="si" end end end if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) end end if params[:editar] == 'no' session[:editar]= false end @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end #Presentacion aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0, actividad_id: @presentacionId).take if !aa.blank? cp = ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa.id, actual: 1).take if !cp.blank? @obsPresentacion = cp.observaciones end end #Descripcion aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0, actividad_id: @descripcionId).take if !aa.blank? cp = ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa.id, actual: 1).take if !cp.blank? @obsDescripcion = cp.observaciones end end else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end else redirect_to controller:"forminst", action: "index" end end #Modulo para ver la tercera pestaรฑa de las adecuaciones def detalles_adecuacion3 if session[:usuario_id] && session[:entidad] == true if !session[:adecuacion_id].blank? @cjpTipo=Usuario.find(session[:usuario_id]).tipo @semestre = 1 @iddoc= 'id_docencia' @docencia='docencia' @investigacion= 'investigacion' session[:informe_id] = nil @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @adecuacion= Adecuacion.find(session[:adecuacion_id]) @plan= Planformacion.find(@adecuacion.planformacion_id) @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observaciont= [] @observacionesExtras= [] @j=0 @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id).take @revision= Revision.where(usuario_id: session[:usuario_id], adecuacion_id: @adecuacion.id, estatus_id: @est.estatus_id, informe_id: nil).take @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if(@revision!=nil && @revision != "") @obs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id, revision_id: @revision.id).take if @obs==nil @<EMAIL>[<EMAIL>] = "" else @<EMAIL>] = @obs.observaciones end @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).where.not(revision_id: @revision.id).all if @cpObs.blank? <EMAIL>]="no" else puts @act.actividad puts @act.id puts "aaaaaaaaaaaaaaaaaaaaaaaaa" <EMAIL>]="si" end else @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? <EMAIL>]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 <EMAIL>]="no" else <EMAIL>]="si" end end end if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) end end @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end else redirect_to controller:"forminst", action: "index" end end #Modulo para ver la cuarta pestaรฑa de las adecuaciones def detalles_adecuacion4 if session[:usuario_id] && session[:entidad] == true if !session[:adecuacion_id].blank? @cjpTipo=Usuario.find(session[:usuario_id]).tipo @semestre = 2 @iddoc= 'id_docencia' session[:informe_id] = nil @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @adecuacion= Adecuacion.find(session[:adecuacion_id]) @plan= Planformacion.find(@adecuacion.planformacion_id) @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observaciont= [] @observacionesExtras= [] @j=0 @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id).take @revision= Revision.where(usuario_id: session[:usuario_id], adecuacion_id: @adecuacion.id, estatus_id: @est.estatus_id, informe_id: nil).take @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if(@revision!=nil && @revision != "") @obs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id, revision_id: @revision.id).take if @obs==nil <EMAIL>]="" else @<EMAIL>][email protected] end @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).where.not(revision_id: @revision.id).all if @cpObs.blank? <EMAIL>]="no" else <EMAIL>]="si" end else @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? <EMAIL>]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 <EMAIL>]="no" else <EMAIL>]="si" end end end if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) end end @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end else redirect_to controller:"forminst", action: "index" end end #Modulo para ver la quinta pestaรฑa de las adecuaciones def detalles_adecuacion5 if session[:usuario_id] && session[:entidad] == true if !session[:adecuacion_id].blank? @cjpTipo=Usuario.find(session[:usuario_id]).tipo @semestre = 3 @iddoc= 'id_docencia' @docencia='docencia' @investigacion= 'investigacion' session[:informe_id] = nil @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @adecuacion= Adecuacion.find(session[:adecuacion_id]) @plan= Planformacion.find(@adecuacion.planformacion_id) @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observaciont= [] @observacionesExtras= [] @j=0 @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id).take @revision= Revision.where(usuario_id: session[:usuario_id], adecuacion_id: @adecuacion.id, estatus_id: @est.estatus_id, informe_id: nil).take @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if(@revision!=nil && @revision != "") @obs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id, revision_id: @revision.id).take if @obs==nil @observaciont[<EMAIL>]="" else @observaciont[@<EMAIL>][email protected] end @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).where.not(revision_id: @revision.id).all if @cpObs.blank? <EMAIL>]="no" else <EMAIL>]="si" end else @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? <EMAIL>]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 <EMAIL>]="no" else <EMAIL>]="si" end end end if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) end end @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad" , action: "listar_adecuaciones" end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion6 if session[:usuario_id] && session[:entidad] == true if !session[:adecuacion_id].blank? @cjpTipo=Usuario.find(session[:usuario_id]).tipo @semestre = 4 @iddoc= 'id_docencia' session[:informe_id] = nil @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @adecuacion= Adecuacion.find(session[:adecuacion_id]) @plan= Planformacion.find(@adecuacion.planformacion_id) @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observaciont= [] @observacionesExtras= [] @j=0 @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id).take @revision= Revision.where(usuario_id: session[:usuario_id], adecuacion_id: @adecuacion.id, estatus_id: @est.estatus_id, informe_id: nil).take @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if(@revision!=nil && @revision != "") @obs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id, revision_id: @revision.id).take if @obs==nil @observaciont[<EMAIL>]="" else @observaciont[@<EMAIL>][email protected] end @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).where.not(revision_id: @revision.id).all if @cpObs.blank? @<EMAIL>]="no" else @<EMAIL>]="si" end else @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @<EMAIL>]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @<EMAIL>]="no" else @<EMAIL>]="si" end end end if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) end end @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion7 if session[:usuario_id] && session[:entidad]== true if !session[:adecuacion_id].blank? @cjpTipo=Usuario.find(session[:usuario_id]).tipo @semestre = 5 @iddoc= 'id_docencia' session[:informe_id] = nil @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @adecuacion= Adecuacion.find(session[:adecuacion_id]) @plan= Planformacion.find(@adecuacion.planformacion_id) @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @observaciont= [] @observacionesExtras= [] @j=0 @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id).take @revision= Revision.where(usuario_id: session[:usuario_id], adecuacion_id: @adecuacion.id, estatus_id: @est.estatus_id, informe_id: nil).take @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 5).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if(@revision!=nil && @revision != "") @obs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id, revision_id: @revision.id).take if @obs==nil @observaciont[@<EMAIL>]="" else @observaciont[@<EMAIL>][email protected] end @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).where.not(revision_id: @revision.id).all if @cpObs.blank? <EMAIL>]="no" else <EMAIL>]="si" end else @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? <EMAIL>]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @<EMAIL>]="no" else @<EMAIL>]="si" end end end if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) end end @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end else redirect_to controller:"forminst", action: "index" end end #Modulo para mostrar los informes enviados a comision de investigacion o aprobadas por el mismo def listar_informes if session[:usuario_id] && session[:entidad]== true @cjpTipo=Usuario.find(session[:usuario_id]).tipo session[:informe_id]=nil @nombre = session[:nombre_usuario] @usu=Usuarioentidad.where(usuario_id: session[:usuario_id]).take @entidad_escuela_id= @usu.escuela_id @depto = @usu.departamento_id @informes = [] @tipos= [] @status = [] @fecha_status = [] @nombre_tutor = [] @nombre_instructor = [] if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision @status_inv = EstatusInforme.where(actual: 1, estatus_id: [3,2,8,4,1,5,9,13,12,18,14]).order(fecha: :desc) #Estatus enviado a comision de investigacion #.order(fecha: :desc) para ordenar el arreglo poniendo los mas nuevos primero elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico @status_inv = EstatusInforme.where(actual: 1, estatus_id: [2,8,4,1,5,9,12,18,14]).order(fecha: :desc) #Estatus enviado a consejo tecnico elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela @status_inv = EstatusInforme.where(actual: 1, estatus_id: [8,4,1,5,9,18,14]).order(fecha: :desc) #Estatus enviado a consejo escuela elsif (session[:entidad_id] == 13) #Consejo de facultad @status_inv = EstatusInforme.where(actual: 1, estatus_id: [4,1,5,9,14]).order(fecha: :desc) #Estatus enviado a consejo de facultad @entidad_escuela_id=nil end @status_inv.each do |si| @inf= Informe.find(si.informe_id) @pf = Planformacion.find(@inf.planformacion_id) @ppp = Persona.where(usuario_id: @pf.instructor_id).take.nombres if (session[:entidad_id] == 13) #Si es consejo de facultad, listar todos los informes enviados a CF sin importar la escuela @informe = true @informes.push(@inf) if(si.estatus_id==1) @st = "APROBADO POR CONSEJO DE FACULTAD" elsif(si.estatus_id==2) @st = "ENVIADO A CONSEJO Tร‰CNICO" elsif(si.estatus_id==3) @st = "ENVIADO A COMISION DE INVESTIGACIร“N" elsif(si.estatus_id==4) @st = "ENVIADO A CONSEJO DE FACULTAD" elsif(si.estatus_id==5) @st = "APROBADO CON OBSERVACIONES POR CONSEJO DE FACULTAD" elsif(si.estatus_id==6) @st = "GUARDADO" elsif(si.estatus_id==8) @st = "ENVIADO A CONSEJO DE ESCUELA" elsif(si.estatus_id==9) @st = "RECHAZADO POR CONSEJO DE FACULTAD" elsif(si.estatus_id==12) @st = "ENVIADO A CONSEJO Tร‰CNICO SIN REVISIร“N" elsif(si.estatus_id==13) @st = "ENVIADO A COMISIร“N DE INVESTIGACIร“N SIN REVISIร“N" elsif(si.estatus_id==14) @st = "ENVIADO A CONSEJO DE FACULTAD SIN REVISIร“N" elsif(si.estatus_id==18) @st = "ENVIADO A CONSEJO DE ESCUELA SIN REVISIร“N" end if @inf.tipo_id == 1 @tipos.push('Semestral') elsif @inf.tipo_id ==2 @tipos.push('Anual') elsif @inf.tipo_id==3 @tipos.push('Final') else @tipos.push('') end tutor_aux= Persona.where(usuario_id: @pf.tutor_id) instructor_aux= Persona.where(usuario_id: @pf.instructor_id) @nombre_tutor.push(tutor_aux.take.nombres.split.map(&:capitalize).join(' ') + " " + tutor_aux.take.apellidos.split.map(&:capitalize).join(' ')) @nombre_instructor.push(instructor_aux.take.nombres.split.map(&:capitalize).join(' ') + " " + instructor_aux.take.apellidos.split.map(&:capitalize).join(' ')) @fecha_status.push(si.fecha) @status.push(@st) else @tutor_escuela = Usuarioentidad.where(usuario_id: @inf.tutor_id).take if @tutor_escuela.escuela_id == @entidad_escuela_id && (@tutor_escuela.departamento_id == @depto || @depto == nil) @informe = true @informes.push(@inf) if @inf.tipo_id == 1 @tipos.push('Semestral') elsif @inf.tipo_id ==2 @tipos.push('Anual') elsif @inf.tipo_id==3 @tipos.push('Final') else @tipos.push('') end if(si.estatus_id==1) @st = "APROBADO POR CONSEJO DE FACULTAD" elsif(si.estatus_id==2) @st = "ENVIADO A CONSEJO Tร‰CNICO" elsif(si.estatus_id==3) @st = "ENVIADO A COMISION DE INVESTIGACIร“N" elsif(si.estatus_id==4) @st = "ENVIADO A CONSEJO DE FACULTAD" elsif(si.estatus_id==5) @st = "APROBADO CON OBSERVACIONES POR CONSEJO DE FACULTAD" elsif(si.estatus_id==8) @st = "ENVIADO A CONSEJO DE ESCUELA" elsif(si.estatus_id==9) @st = "RECHAZADO POR CONSEJO DE FACULTAD" elsif(si.estatus_id==12) @st = "ENVIADO A CONSEJO Tร‰CNICO SIN REVISIร“N" elsif(si.estatus_id==13) @st = "ENVIADO A COMISIร“N DE INVESTIGACIร“N SIN REVISIร“N" elsif(si.estatus_id==14) @st = "ENVIADO A CONSEJO DE FACULTAD SIN REVISIร“N" elsif(si.estatus_id==18) @st = "ENVIADO A CONSEJO DE ESCUELA SIN REVISIร“N" end tutor_aux= Persona.where(usuario_id: @pf.tutor_id) instructor_aux= Persona.where(usuario_id: @pf.instructor_id) @nombre_tutor.push(tutor_aux.take.nombres.split.map(&:capitalize).join(' ') + " " + tutor_aux.take.apellidos.split.map(&:capitalize).join(' ')) @nombre_instructor.push(instructor_aux.take.nombres.split.map(&:capitalize).join(' ') + " " + instructor_aux.take.apellidos.split.map(&:capitalize).join(' ')) @fecha_status.push(si.fecha) @status.push(@st) end end end else redirect_to controller:"forminst", action: "index" end end def ver_detalles_informe if session[:usuario_id] && session[:entidad] == true @cjpTipo=Usuario.find(session[:usuario_id]).tipo @nombre = session[:nombre_usuario] if params[:informe_id]!=nil session[:informe_id]= params[:informe_id] end if !session[:informe_id].blank? @informe= Informe.find(session[:informe_id]) session[:plan_id] = @informe.planformacion_id @est= EstatusInforme.where(informe_id: @informe.id, actual: 1).take @status= TipoEstatus.find(@est.estatus_id) @planformacion = Planformacion.find(@informe.planformacion_id) @persona = Persona.where(usuario_id: @planformacion.tutor_id).take @instructor = Persona.where(usuario_id: @planformacion.instructor_id).take @instructorName = @instructor.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @instructor.apellidos.to_s.split.map(&:capitalize).join(' ') session[:instructorName] = @instructorName @periodo = @informe.fecha_inicio.to_s + " al " + @informe.fecha_fin.to_s if (@informe.numero == 1 || @informe.numero == 3) @nombre_informe= "<NAME> " session[:numero_informe]=1 elsif (@informe.numero == 2 || @informe.numero == 6) @nombre_informe= "<NAME> " session[:numero_informe]=2 elsif @informe.numero == 4 @nombre_informe= "<NAME> " session[:numero_informe]=4 elsif @informe.numero == 5 @nombre_informe= "<NAME> " session[:numero_informe]=5 end if @informe.tipo_id == 1 @nombre_informe= @nombre_informe+"SEMESTRAL" session[:nombre_informe] = @nombre_informe elsif @informe.tipo_id == 2 @nombre_informe= @nombre_informe+"ANUAL" session[:nombre_informe] = @nombre_informe else @nombre_informe= "INFORME "+"FINAL" session[:nombre_informe] = @nombre_informe end @estatus= EstatusInforme.where(informe_id: @informe.id, actual: 1).take @status= TipoEstatus.find(@estatus.estatus_id) @userentidad=Usuarioentidad.where(entidad_id: session[:entidad_id]).take @userentidadUsuario=Usuarioentidad.where(usuario_id: @informe.tutor_id).take @escuela= Escuela.where(id: @userentidadUsuario.escuela_id).take session[:nombre_informe] = @nombre_informe.downcase.split.map(&:capitalize).join(' ') ##Capitalize every first word of the string session[:status_informe] = @status.concepto else flash[:info]= "Seleccione un informe" redirect_to controller:"inicioentidad", action: "listar_informes" end else redirect_to controller:"forminst", action: "index" end end def detalles_informe2 @cjpTipo=Usuario.find(session[:usuario_id]).tipo @nombre = session[:nombre_usuario] if !session[:informe_id].blank? @informe= Informe.find(session[:informe_id]) @est= EstatusInforme.where(informe_id: @informe.id, actual: 1).take @status= TipoEstatus.find(@est.estatus_id) @adecuacion = Adecuacion.where(planformacion_id: @informe.planformacion_id).take @modificar= false if @est.estatus_id == 6 @modificar=true end @nombre_informe = "" if (@informe.numero == 1 || @informe.numero == 3) @nombre_informe= "PRIMER INFORME " session[:numero_informe]=1 elsif (@informe.numero == 2 || @informe.numero == 6) @nombre_informe= "SEGUNDO INFORME " session[:numero_informe]=2 elsif @informe.numero == 4 @nombre_informe= "TERCER INFORME " session[:numero_informe]=4 elsif @informe.numero == 5 @nombre_informe= "CUARTO INFORME " session[:numero_informe]=5 end if @informe.tipo_id == 1 @nombre_informe= @nombre_informe+"SEMESTRAL" session[:nombre_informe] = @nombre_informe elsif @informe.tipo_id == 2 @nombre_informe= @nombre_informe+"ANUAL" session[:nombre_informe] = @nombre_informe else @nombre_informe= "INFORME "+"FINAL" session[:nombre_informe] = @nombre_informe end @docencia= "docencia" @cp=0 @j= 0 @k=0 @actividadesa= InformeActividad.where(informe_id: @informe.id).all @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @actividadesaobli= [] @semestres=[] @CJagregado=["no","no","no","no"] @resultados= [] @resultados2= "" @resultados2a= [] @resultados2b= [] @actividadese= [] @observaciont= [] @observacionesExtras = [] @revision= Revision.where(informe_id: @informe.id, usuario_id: session[:usuario_id], adecuacion_id: @adecuacion.id).take @actividadesa.each do |actade| if @resultados2b != [] @resultados2b= Array.new(0) { |i| } end if actade.actividad_id == nil #Es el caso que es un resultado no contemplado en el plan de formacion o un avancwe de postgrado @res= Resultado.where(informe_actividad_id: actade.id).all @resultados.push(@res) @actividadese.push("") @res.each do |cpresultado| @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = cpresultado.titulo @cparray[1] = cpresultado.autor @cparray[2] = cpresultado.nombre_capitulo @cparray[3] = cpresultado.autor_capitulo @cparray[4] = cpresultado.dia @cparray[5] = cpresultado.mes @cparray[6] = cpresultado.ano @cparray[7] = cpresultado.ciudad @cparray[8] = cpresultado.estado @cparray[9] = cpresultado.pais @cparray[10] = cpresultado.organizador @cparray[11] = cpresultado.duracion @cparray[12] = cpresultado.editor @cparray[13] = cpresultado.titulo_libro @cparray[14] = cpresultado.autor_libro @cparray[15] = cpresultado.nombre_revista @cparray[16] = cpresultado.nombre_periodico @cparray[17] = cpresultado.nombre_acto @cparray[18] = cpresultado.paginas @cparray[19] = cpresultado.nombre_paginaw @cparray[20] = cpresultado.sitio_paginaw @cparray[21] = cpresultado.infoafiliaion @cparray[22] = cpresultado.cptipo @cparray[23] = cpresultado.nombre @cparray[24] = cpresultado.ISSN_impreso @cparray[25] = cpresultado.ISSN_electro @cparray[26] = cpresultado.volumen @cparray[27] = cpresultado.edicion @cparray[28] = cpresultado.DOI @cparray[29] = cpresultado.ISBN @cparray[30] = cpresultado.universidad @cparray[31] = cpresultado.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @noemptyarray.join(',') end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @noemptyarray.join(',') end end @resultados2b.push(@resultados2) end end @resultados2a.push(@resultados2b) if @revision == nil || @revision == "" @obs=nil else @obs= ObservacionActividadInforme.where(informe_actividad_id: actade.id, revision_id: @revision.id).take end @cpObs2= ObservacionTutor.where(informe_actividad_id: actade.id).take cpVerificar = "si" if [email protected]? && [email protected]? @observacionesExtras.push("si") cpVerificar = "no" end if @obs==nil @observaciont.push("") if cpVerificar == "si" @cpObs= ObservacionActividadInforme.where(informe_actividad_id: actade.id).all if @cpObs.blank? @observacionesExtras.push("no") else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras.push("no") else @observacionesExtras.push("si") end end end else @observaciont.push(@obs.observaciones) if cpVerificar == "si" @cpObs= ObservacionActividadInforme.where(informe_actividad_id: actade.id).where.not(revision_id: @revision.id).all if @cpObs.blank? @observacionesExtras.push("no") else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras.push("no") else @observacionesExtras.push("si") end end end end else @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id @res= Resultado.where(informe_actividad_id: actade.id).all if [email protected]? @resultados.push(@res) @res.each do |cpresultado| @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = cpresultado.titulo @cparray[1] = cpresultado.autor @cparray[2] = cpresultado.nombre_capitulo @cparray[3] = cpresultado.autor_capitulo @cparray[4] = cpresultado.dia @cparray[5] = cpresultado.mes @cparray[6] = cpresultado.ano @cparray[7] = cpresultado.ciudad @cparray[8] = cpresultado.estado @cparray[9] = cpresultado.pais @cparray[10] = cpresultado.organizador @cparray[11] = cpresultado.duracion @cparray[12] = cpresultado.editor @cparray[13] = cpresultado.titulo_libro @cparray[14] = cpresultado.autor_libro @cparray[15] = cpresultado.nombre_revista @cparray[16] = cpresultado.nombre_periodico @cparray[17] = cpresultado.nombre_acto @cparray[18] = cpresultado.paginas @cparray[19] = cpresultado.nombre_paginaw @cparray[20] = cpresultado.sitio_paginaw @cparray[21] = cpresultado.infoafiliaion @cparray[22] = cpresultado.cptipo @cparray[23] = cpresultado.nombre @cparray[24] = cpresultado.ISSN_impreso @cparray[25] = cpresultado.ISSN_electro @cparray[26] = cpresultado.volumen @cparray[27] = cpresultado.edicion @cparray[28] = cpresultado.DOI @cparray[29] = cpresultado.ISBN @cparray[30] = cpresultado.universidad @cparray[31] = cpresultado.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @noemptyarray.join(',') end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @noemptyarray.join(',') end end @resultados2b.push(@resultados2) end end else @resultados.push(nil) end @resultados2a.push(@resultados2b) @ae= ActividadEjecutada.where(informe_actividad_id: actade.id).take if @ae==nil || @ae== "" @actividadese.push("") else @actividadese.push(@ae) end if @revision == nil || @revision == "" @obs=nil else @obs= ObservacionActividadInforme.where(informe_actividad_id: actade.id, revision_id: @revision.id).take end @cpObs2= ObservacionTutor.where(informe_actividad_id: actade.id).take cpVerificar = "si" if [email protected]? && [email protected]? @observacionesExtras.push("si") cpVerificar = "no" end if @obs==nil @observaciont.push("") if cpVerificar == "si" @cpObs= ObservacionActividadInforme.where(informe_actividad_id: actade.id).all if @cpObs.blank? @observacionesExtras.push("no") else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras.push("no") else @observacionesExtras.push("si") end end end else @observaciont.push(@obs.observaciones) if cpVerificar == "si" @cpObs= ObservacionActividadInforme.where(informe_actividad_id: actade.id).where.not(revision_id: @revision.id).all if @cpObs.blank? @observacionesExtras.push("no") else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras.push("no") else @observacionesExtras.push("si") end end end end semestre = AdecuacionActividad.where(actividad_id: @act.id).take.semestre @semestres[@act.id]=semestre if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) elsif tipo==7 @actividadesaobli.push(@act) end end end @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusInforme.where(informe_id: @informe.id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusInforme.where(informe_id: @informe.id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusInforme.where(informe_id: @informe.id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusInforme.where(informe_id: @informe.id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end else flash[:info]= "Seleccione un informe" redirect_to controller:"inicioentidad", action: "listar_informes" end end def vista_previa1 if !session[:informe_id].blank? if !session[:plan_id].blank? @cjpTipo=Usuario.find(session[:usuario_id]).tipo @informe= Informe.find(session[:informe_id]) @TipoSemestre=TipoInforme.where(id: @informe.tipo_id).take @fechaActual = Date.current.to_s @plan= Planformacion.find(session[:plan_id]) @fechaConcurso = @plan.fecha_inicio @usere= Usuarioentidad.where(usuario_id: @plan.instructor_id).take @escuela= Escuela.find(@usere.escuela_id) @adecuacion= Adecuacion.where(planformacion_id: @plan.id).take @adscripcion_docencia= @plan.adscripcion_docencia @adscripcion_investigacion= @plan.adscripcion_investigacion @persona= Persona.where(usuario_id: @plan.instructor_id).take @cpinstruccion = @persona.grado_instruccion @user = Usuario.find(@plan.instructor_id) @tutor = Persona.where(usuario_id: @plan.tutor_id).take @periodo = @informe.fecha_inicio.to_s + " al " + @informe.fecha_fin.to_s @nombre_informe = "" if (@informe.numero == 1 || @informe.numero == 3) @nombre_informe= "<NAME> " session[:numero_informe]=1 elsif (@informe.numero == 2 || @informe.numero == 6) @nombre_informe= "<NAME> " session[:numero_informe]=2 elsif @informe.numero == 4 @nombre_informe= "<NAME> " session[:numero_informe]=4 elsif @informe.numero == 5 @nombre_informe= "CUARTO INFORME " session[:numero_informe]=5 end if @informe.tipo_id == 1 @nombre_informe= @nombre_informe+"SEMESTRAL" elsif @informe.tipo_id == 2 @nombre_informe= @nombre_informe+"ANUAL" else @nombre_informe= "INFORME "+"FINAL" end @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @obligatoria= 'obligatoria' @extension= 'extension' @otra= 'otra' @CJagregado=["no","no","no","no"] @semestres = [] @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @actividades1doc= [] @actividades1inv= [] @actividades1ext= [] @actividades1for= [] @actividades1otr= [] @actividades1= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividades1.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades1doc.push(@act) elsif tipo==2 if @informe.numero == 1 @resActi= InformeActividad.where(informe_id: @informe.id, actividad_id: @act.id).take @res= Resultado.where(informe_actividad_id: @resActi.id).all end @actividades1inv.push(@act) elsif tipo==3 @actividades1ext.push(@act) elsif tipo==4 @actividades1for.push(@act) elsif tipo==5 @actividades1otr.push(@act) end end @actividades2doc= [] @actividades2inv= [] @actividades2ext= [] @actividades2for= [] @actividades2otr= [] @actividades2= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @actividades2.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades2doc.push(@act) elsif tipo==2 @actividades2inv.push(@act) elsif tipo==3 @actividades2ext.push(@act) elsif tipo==4 @actividades2for.push(@act) elsif tipo==5 @actividades2otr.push(@act) end end @actividades3doc= [] @actividades3inv= [] @actividades3ext= [] @actividades3for= [] @actividades3otr= [] @actividades3= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all @actividades3.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades3doc.push(@act) elsif tipo==2 @actividades3inv.push(@act) elsif tipo==3 @actividades3ext.push(@act) elsif tipo==4 @actividades3for.push(@act) elsif tipo==5 @actividades3otr.push(@act) end end @actividades4doc= [] @actividades4inv= [] @actividades4ext= [] @actividades4for= [] @actividades4otr= [] @actividades4= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all @actividades4.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades4doc.push(@act) elsif tipo==2 @actividades4inv.push(@act) elsif tipo==3 @actividades4ext.push(@act) elsif tipo==4 @actividades4for.push(@act) elsif tipo==5 @actividades4otr.push(@act) end end @actividades5doc= [] @actividades5inv= [] @actividades5ext= [] @actividades5for= [] @actividades5otr= [] @actividades5= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 5).all @actividades5.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades5doc.push(@act) elsif tipo==2 @actividades5inv.push(@act) elsif tipo==3 @actividades5ext.push(@act) elsif tipo==4 @actividades5for.push(@act) end end @bool_enviado = 0 estatus_informe = EstatusInforme.where(informe_id: @informe.id, actual: 1).take if (estatus_informe.estatus_id != 6 && estatus_informe.estatus_id != 5) @bool_enviado = 1 end actividades = AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0) actividades1 = [] if !actividades.blank? actividades.each do |actividadAde| actividad = Actividad.find(actividadAde.actividad_id) actividades1.push(actividad) end end @presentacion = "" @descripcion = "" @docencia = [] @investigacion = [] @formacion = [] @extension = [] if !actividades1.blank? actividades1.each do |actividadAde| if actividadAde.tipo_actividad_id == 9 if actividadAde.actividad.blank? @presentacion = " " else @presentacion = actividadAde.actividad end elsif actividadAde.tipo_actividad_id == 8 if actividadAde.actividad.blank? @descripcion = " " else @descripcion = actividadAde.actividad end elsif actividadAde.tipo_actividad_id == 1 if actividadAde.actividad.blank? @docencia.push(" ") else @docencia.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 2 if actividadAde.actividad.blank? @investigacion.push(" ") else @investigacion.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 4 if actividadAde.actividad.blank? @formacion.push(" ") else @formacion.push(actividadAde) end elsif actividadAde.tipo_actividad_id == 3 if actividadAde.actividad.blank? @extension.push(" ") else @extension.push(actividadAde) end end end else @presentacion = " " @descripcion = " " @docencia = [" "] @investigacion = [" "] @formacion = [" "] @extension = [" "] end @j = 0 @i = 0 @actividadesa= InformeActividad.where(informe_id: @informe.id).all @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @actividadesaobli= [] @resultados= [] @actividadese= [] @observaciont= [] @resultTP = [] @resultPP = [] @resultPIT = [] @resultO = [] @resultAEC = [] @resultOEC = [] @resultDCS = [] @actividadesa.each do |actade| @resultados2 = "" @res= Resultado.where(informe_actividad_id: actade.id).all if actade.actividad_id == nil #Es el caso que es un resultado no contemplado en el plan de formacion o un avancwe de postgrado if [email protected]? @res.each do |res| @resultados2 = "" @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a","a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = res.titulo.capitalize @cparray[1] = res.autor.capitalize @cparray[2] = res.nombre_capitulo.to_s.capitalize @cparray[3] = res.autor_capitulo.to_s.capitalize @cparray[4] = res.dia @cparray[5] = res.mes @cparray[6] = res.ano @cparray[7] = res.ciudad.to_s.capitalize @cparray[8] = res.estado.to_s.capitalize @cparray[9] = res.pais.to_s.capitalize @cparray[10] = res.organizador.to_s.capitalize @cparray[11] = res.duracion.to_s.capitalize @cparray[12] = res.editor.to_s.capitalize @cparray[13] = res.titulo_libro.to_s.capitalize @cparray[14] = res.autor_libro.to_s.capitalize @cparray[15] = res.nombre_revista.to_s.capitalize @cparray[16] = res.nombre_periodico.to_s.capitalize @cparray[17] = res.nombre_acto.to_s.capitalize @cparray[18] = res.paginas @cparray[19] = res.nombre_paginaw.to_s.capitalize @cparray[20] = res.sitio_paginaw @cparray[21] = res.infoafiliaion.to_s.capitalize @cparray[22] = res.cptipo.to_s.capitalize @cparray[23] = res.nombre.to_s.capitalize @cparray[24] = res.ISSN_impreso.to_s.capitalize @cparray[25] = res.ISSN_electro.to_s.capitalize @cparray[26] = res.volumen.to_s.capitalize @cparray[27] = res.edicion.to_s.capitalize @cparray[28] = res.DOI @cparray[29] = res.ISBN @cparray[30] = res.universidad.to_s.capitalize @cparray[31] = res.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = "* " + @noemptyarray end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @resultados2 + @noemptyarray.join(', ') end end end if res.tipo_resultado_id == 1 @resultTP.push(@resultados2) elsif res.tipo_resultado_id == 2 @resultPP.push(@resultados2) elsif res.tipo_resultado_id == 3 @resultPIT.push(@resultados2) elsif res.tipo_resultado_id == 4 @resultO.push(@resultados2) elsif res.tipo_resultado_id == 5 @resultAEC.push(@resultados2) elsif res.tipo_resultado_id == 6 @resultOEC.push(@resultados2) elsif res.tipo_resultado_id == 7 @resultDCS.push(@resultados2) end @resultados.push(res) end end else @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if [email protected]? @res.each do |res| @resultados2 = "" @cparray = ["a", "a", "a", "a", "a", "a", "a", "a", "a","a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] @cparray[0] = res.titulo.capitalize @cparray[1] = res.autor.capitalize @cparray[2] = res.nombre_capitulo.to_s.capitalize @cparray[3] = res.autor_capitulo.to_s.capitalize @cparray[4] = res.dia @cparray[5] = res.mes @cparray[6] = res.ano @cparray[7] = res.ciudad.to_s.capitalize @cparray[8] = res.estado.to_s.capitalize @cparray[9] = res.pais.to_s.capitalize @cparray[10] = res.organizador.to_s.capitalize @cparray[11] = res.duracion.to_s.capitalize @cparray[12] = res.editor.to_s.capitalize @cparray[13] = res.titulo_libro.to_s.capitalize @cparray[14] = res.autor_libro.to_s.capitalize @cparray[15] = res.nombre_revista.to_s.capitalize @cparray[16] = res.nombre_periodico.to_s.capitalize @cparray[17] = res.nombre_acto.to_s.capitalize @cparray[18] = res.paginas @cparray[19] = res.nombre_paginaw.to_s.capitalize @cparray[20] = res.sitio_paginaw @cparray[21] = res.infoafiliaion.to_s.capitalize @cparray[22] = res.cptipo.to_s.capitalize @cparray[23] = res.nombre.to_s.capitalize @cparray[24] = res.ISSN_impreso.to_s.capitalize @cparray[25] = res.ISSN_electro.to_s.capitalize @cparray[26] = res.volumen.to_s.capitalize @cparray[27] = res.edicion.to_s.capitalize @cparray[28] = res.DOI @cparray[29] = res.ISBN @cparray[30] = res.universidad.to_s.capitalize @cparray[31] = res.url if [email protected]? @noemptyarray = @cparray - ["", nil] if !@resultados2 @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = "* " + @noemptyarray end else @noemptyarray = @cparray - ["", nil] if [email protected](',').blank? @resultados2 = @resultados2 + @noemptyarray.join(', ') end end end if res.tipo_resultado_id == 1 @resultTP.push(@resultados2) elsif res.tipo_resultado_id == 2 @resultPP.push(@resultados2) elsif res.tipo_resultado_id == 3 @resultPIT.push(@resultados2) elsif res.tipo_resultado_id == 4 @resultO.push(@resultados2) elsif res.tipo_resultado_id == 5 @resultAEC.push(@resultados2) elsif res.tipo_resultado_id == 6 @resultOEC.push(@resultados2) elsif res.tipo_resultado_id == 7 @resultDCS.push(@resultados2) end @resultados.push(res) end end end @ae= ActividadEjecutada.where(informe_actividad_id: actade.id).take @actividadese.push(@ae) @obs= ObservacionTutor.where(informe_actividad_id: actade.id).take semestre = AdecuacionActividad.where(actividad_id: @act.id).take.semestre @semestres[@act.id]=semestre if @obs==nil @observaciont.push("") else @observaciont.push(@obs.observaciones) end if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) elsif tipo==7 @actividadesaobli.push(@act) end end @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end else flash[:info]="Selecciona un informe" redirect_to controller: "inicioentidad", action: "listar_informes" end end #Funcion para guardar observaciones def guardar_observaciones if session[:usuario_id] && session[:entidad] == true @cjpTipo=Usuario.find(session[:usuario_id]).tipo @informe = Informe.find(session[:informe_id]) @adecuacion = Adecuacion.where(planformacion_id: @informe.planformacion_id).take @estatus = EstatusInforme.where(informe_id: @informe.id, actual: 1).take @cant_doc = params[:cant_docencia].to_i @cant_inv = params[:cant_investigacion].to_i @cant_for = params[:cant_formacion].to_i @cant_ext = params[:cant_extension].to_i @cant_otr = params[:cant_otra].to_i @cant_obli = params[:cant_obligatoria].to_i @cant_result= params[:cant_result].to_i @informe.opinion_tutor = params[:opinion] @informe.conclusiones = params[:conclusiones] #@informe.save revision= Revision.where(informe_id: @informe.id, usuario_id: session[:usuario_id], adecuacion_id: @adecuacion.id, estatus_id: @estatus.estatus_id).take if(revision == nil || revision =="") revision = Revision.new revision.informe_id = @informe.id revision.usuario_id = session[:usuario_id] revision.adecuacion_id = @adecuacion.id revision.fecha = Time.now revision.estatus_id = @estatus.estatus_id revision.save else revision.fecha = Time.now revision.save end #Comienza actividades de docencia j=0 i=:doc.to_s+j.to_s @act = params[i].to_i while j < @cant_doc ia = InformeActividad.where(informe_id: @informe.id,actividad_id: @act).take observacion =:[email protected]_s oa = ObservacionActividadInforme.where(informe_actividad_id: ia, revision_id: revision.id).take if(!params[observacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadInforme.new oa.informe_actividad_id = ia.id oa.revision_id = revision.id oa.observaciones = params[observacion] oa.save else oa.observaciones = params[observacion] oa.save end end j= j+1 i=:doc.to_s+j.to_s @act= params[i].to_i end #Comienza actividades de investigacion j=0 i=:inv.to_s+j.to_s @act = params[i].to_i k=:result.to_s+j.to_s @result= params[k].to_i while j < @cant_inv ia = InformeActividad.where(informe_id: @informe.id,actividad_id: @act).take observacion =:[email protected]_s oa = ObservacionActividadInforme.where(informe_actividad_id: ia, revision_id: revision.id).take if(!params[observacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadInforme.new oa.informe_actividad_id = ia.id oa.revision_id = revision.id oa.observaciones = params[observacion] oa.save else oa.observaciones = params[observacion] oa.save end end j=j+1 i=:inv.to_s+j.to_s @act= params[i].to_i end #Comienza actividades de formaciรณn j=0 i=:for.to_s+j.to_s @act = params[i].to_i while j < @cant_for ia = InformeActividad.where(informe_id: @informe.id,actividad_id: @act).take observacion =:[email protected]_s oa = ObservacionActividadInforme.where(informe_actividad_id: ia, revision_id: revision.id).take if(!params[observacion].blank?) if(oa == nil || oa== "") oa = ObservacionActividadInforme.new oa.informe_actividad_id = ia.id oa.revision_id = revision.id oa.observaciones = params[observacion] oa.save else oa.observaciones = params[observacion] oa.save end end j= j+1 i=:for.to_s+j.to_s @act= params[i].to_i end #Resultado de avances de postgrado @id_resultado= params[:postgradoRest].to_i if @id_resultado !=0 && @id_resultado != nil ia = InformeActividad.where(informe_id: @informe.id, resultado_id: @id_resultado).take oa = ObservacionActividadInforme.where(informe_actividad_id: ia.id, revision_id: revision.id).take if(!params[:observacionPost].blank?) if(oa == nil || oa =="") oa = ObservacionActividadInforme.new oa.informe_actividad_id = ia.id oa.revision_id = revision.id oa.observaciones = params[:observacionPost].to_s oa.save else oa.observaciones = params[:observacionPost].to_s oa.save end end end #Comienzan actividades de extensiรณn j=0 i=:ext.to_s+j.to_s @act = params[i].to_i while j < @cant_ext ia = InformeActividad.where(informe_id: @informe.id, actividad_id: @act).take observacion =:[email protected]_s oa = ObservacionActividadInforme.where(informe_actividad_id: ia, revision_id: revision.id).take if(!params[observacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadInforme.new oa.informe_actividad_id = ia.id oa.revision_id = revision.id oa.observaciones = params[observacion] oa.save else oa.observaciones = params[observacion] oa.save end end j= j+1 i=:ext.to_s+j.to_s @act= params[i].to_i end #Comienza actividades de docencia j=0 i=:obli.to_s+j.to_s @act = params[i].to_i while j < @cant_obli ia = InformeActividad.where(informe_id: @informe.id,actividad_id: @act).take observacion =:[email protected]_s oa = ObservacionActividadInforme.where(informe_actividad_id: ia, revision_id: revision.id).take if(!params[observacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadInforme.new oa.informe_actividad_id = ia.id oa.revision_id = revision.id oa.observaciones = params[observacion] oa.save else oa.observaciones = params[observacion] oa.save end end j= j+1 i=:obli.to_s+j.to_s @act= params[i].to_i end #Comienzan Otras actividades j=0 i=:otr.to_s+j.to_s @act = params[i].to_i while j < @cant_otr ia = InformeActividad.where(informe_id: @informe.id,actividad_id: @act).take observacion =:[email protected]_s oa = ObservacionActividadInforme.where(informe_actividad_id: ia, revision_id: revision.id).take if(!params[observacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadInforme.new oa.informe_actividad_id = ia.id oa.revision_id = revision.id oa.observaciones = params[observacion] oa.save else oa.observaciones = params[observacion] oa.save end end j= j+1 i=:otr.to_s+j.to_s @act= params[i].to_i end #Resultado actividades no contempladas @id_resultado= params[:noConRest].to_i if @id_resultado !=0 && @id_resultado != nil ia = InformeActividad.where(informe_id: @informe.id, resultado_id: @id_resultado).take oa = ObservacionActividadInforme.where(informe_actividad_id: ia.id, revision_id: revision.id).take if(!params[:observacionNoCon].blank?) if(oa == nil || oa =="") oa = ObservacionActividadInforme.new oa.informe_actividad_id = ia.id oa.revision_id = revision.id oa.observaciones = params[:observacionNoCon].to_s oa.save else oa.observaciones = params[:observacionNoCon].to_s oa.save end end end flash[:success]="Se han creado y/o modificado las observaciones satisfactoriamente" redirect_to controller:"inicioentidad", action: "detalles_informe2" end end #Cerrar Sesiรณn def logout reset_session redirect_to controller: "forminst", action: "index" end #Observaciones de informe def mas_observaciones @boolobs= 0 @booltutor = 0 @informe_id = params[:informe_id].to_i @actividad_id = params[:actividad_id].to_i @cjpTipo=Usuario.find(session[:usuario_id]).tipo ia = InformeActividad.where(informe_id: @informe_id, actividad_id: @actividad_id).take @observaciones = ObservacionActividadInforme.where(informe_actividad_id: ia.id).all @observaciones.each do |obs| if(obs.observaciones != "") @boolobs = 1 end end @observaciones.each do |obs| rev = Revision.find(obs.revision_id) entidad = Usuarioentidad.where(usuario_id: rev.usuario_id).take if (entidad.entidad_id >= 7 && entidad.entidad_id <= 12) #comision investigacion @obs_inv = obs.observaciones #Estatus enviado a comision de investigacion elsif (entidad.entidad_id >= 14 && entidad.entidad_id <= 17) #Consejo tecnico @obs_consejoT = obs.observaciones elsif (entidad.entidad_id >= 1 && entidad.entidad_id <= 6) #Consejo de escuela @obs_consejoE = obs.observaciones elsif (entidad.entidad_id == 13) #Consejo de facultad @obs_consejoF = obs.observaciones end end @obs_t= ObservacionTutor.where(informe_actividad_id: ia.id).take if(@obs_t != nil && @obs_t != "") @obs_tutor = @obs_t.observaciones @booltutor = 1 end @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusInforme.where(informe_id: @informe_id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusInforme.where(informe_id: @informe_id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusInforme.where(informe_id: @informe_id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusInforme.where(informe_id: @informe_id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end end def mas_observaciones2 @boolobsb = 0 @informe_id = params[:informe_id].to_i @resultado_id = params[:resultado_id].to_i @cjpTipo=Usuario.find(session[:usuario_id]).tipo ia = InformeActividad.where(informe_id: @informe_id, resultado_id: @resultado_id).take @observaciones = ObservacionActividadInforme.where(informe_actividad_id: ia.id) @observaciones.each do |obs| if(obs.observaciones != "") @boolobs = 1 end end @observaciones.each do |obs| rev = Revision.find(obs.revision_id) entidad = Usuarioentidad.where(usuario_id: rev.usuario_id).take if (entidad.entidad_id >= 7 && entidad.entidad_id <= 12) #comision investigacion @obs_inv = obs.observaciones #Estatus enviado a comision de investigacion else if (entidad.entidad_id >= 14 && entidad.entidad_id <= 17) #Consejo tecnico @obs_consejoT = obs.observaciones else if (entidad.entidad_id >= 1 && entidad.entidad_id <= 6) #Consejo de escuela @obs_consejoE = obs.observaciones else if (entidad.entidad_id == 13) #Consejo de facultad @obs_consejoF = obs.observaciones end end end end end @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusInforme.where(informe_id: @informe_id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusInforme.where(informe_id: @informe_id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusInforme.where(informe_id: @informe_id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusInforme.where(informe_id: @informe_id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end end #Visualizar los respaldos def ver_respaldos if session[:usuario_id] && session[:entidad] if !session[:plan_id].blank? @cjpTipo=Usuario.find(session[:usuario_id]).tipo @plan = Planformacion.where(id: session[:plan_id]).take @adec = Adecuacion.where(planformacion_id: session[:plan_id]).take @documents = [] if !session[:informe_id].blank? @documents = Respaldo.where(adecuacion_id: @adec.id, informe_id: session[:informe_id], actual: 0).all else @documents = Respaldo.where(adecuacion_id: @adec.id, informe_id: nil, actual: 0).all end else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end else redirect_to controller:"forminst", action: "index" end end #Descargar respaldos def show if params[:informe_id].blank? @document = Respaldo.where(adecuacion_id: params[:adecuacion_id], informe_id: nil, version: params[:version].to_i, filename: params[:namefile]).take else @document = Respaldo.where(adecuacion_id: params[:adecuacion_id], informe_id: params[:informe_id],version: params[:version].to_i, filename: params[:namefile]).take end send_data(@document.file_contents, type: @document.content_type, filename: @document.filename) end def guardar_obs_primera_parte if session[:usuario_id] && session[:entidad]== true if !session[:adecuacion_id].blank? @semestre = params[:semestre].to_i @vista_adecuacion = @semestre + 2 @adecuacion= Adecuacion.find(session[:adecuacion_id]) @estatus= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id).take revision= Revision.where(usuario_id: session[:usuario_id], adecuacion_id: @adecuacion.id, estatus_id: @estatus.estatus_id, informe_id: nil).take if(revision == nil || revision =="") revision = Revision.new revision.informe_id = nil revision.usuario_id = session[:usuario_id] revision.adecuacion_id = @adecuacion.id revision.estatus_id = @estatus.estatus_id revision.fecha = Time.now revision.save else revision.fecha = Time.now revision.save end #presentacion aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0, actividad_id: params[:presentacionId]).take oa= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa.id, revision_id: revision.id).take if(!params[:obsPresentacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadAdecuacion.new oa.adecuacionactividad_id = aa.id oa.revision_id = revision.id oa.observaciones = params[:obsPresentacion] oa.actual = 1 oa.save else oa.observaciones = params[:obsPresentacion] oa.save end end #Descripcion aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0, actividad_id: params[:descripcionId]).take oa= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa, revision_id: revision.id).take if(!params[:obsDescripcion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadAdecuacion.new oa.adecuacionactividad_id = aa.id oa.revision_id = revision.id oa.observaciones = params[:obsDescripcion] oa.actual = 1 oa.save else oa.observaciones = params[:obsDescripcion] oa.save end end #Docencia aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0, actividad_id: params[:docenciaId]).take oa= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa, revision_id: revision.id).take if(!params[:obsDocencia].blank?) if(oa == nil || oa =="") oa = ObservacionActividadAdecuacion.new oa.adecuacionactividad_id = aa.id oa.revision_id = revision.id oa.observaciones = params[:obsDocencia] oa.actual = 1 oa.save else oa.observaciones = params[:obsDocencia] oa.save end end #Investigacion aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0, actividad_id: params[:investigacionId]).take oa= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa, revision_id: revision.id).take if(!params[:obsInvestigacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadAdecuacion.new oa.adecuacionactividad_id = aa.id oa.revision_id = revision.id oa.observaciones = params[:obsInvestigacion] oa.actual = 1 oa.save else oa.observaciones = params[:obsInvestigacion] oa.save end end #Formacion aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0, actividad_id: params[:formacionId]).take oa= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa, revision_id: revision.id).take if(!params[:obsFormacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadAdecuacion.new oa.adecuacionactividad_id = aa.id oa.revision_id = revision.id oa.observaciones = params[:obsFormacion] oa.actual = 1 oa.save else oa.observaciones = params[:obsFormacion] oa.save end end #Extension aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0, actividad_id: params[:extensionId]).take oa= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa, revision_id: revision.id).take if(!params[:obsExtension].blank?) if(oa == nil || oa =="") oa = ObservacionActividadAdecuacion.new oa.adecuacionactividad_id = aa.id oa.revision_id = revision.id oa.observaciones = params[:obsExtension] oa.actual = 1 oa.save else oa.observaciones = params[:obsExtension] oa.save end end flash[:success]="Se han creado y/o modificado las observaciones satisfactoriamente" redirect_to controller:"inicioentidad", action: "detalles_adecuacion2" else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end end end def guardar_observaciones2 if session[:usuario_id] && session[:entidad]== true if !session[:adecuacion_id].blank? @semestre = params[:semestre].to_i @cjpTipo=Usuario.find(session[:usuario_id]).tipo @vista_adecuacion = @semestre + 2 @adecuacion= Adecuacion.find(session[:adecuacion_id]) puts "holaaaaaaaaaaaaaaa" puts session[:adecuacion_id] @estatus= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id).take @cant_doc= params[:cant_docencia].to_i @cant_inv= params[:cant_investigacion].to_i @cant_for= params[:cant_formacion].to_i @cant_ext= params[:cant_extension].to_i @cant_obli= params[:cant_obligatoria].to_i @cant_otr= params[:cant_otra].to_i revision= Revision.where(usuario_id: session[:usuario_id], adecuacion_id: @adecuacion.id, estatus_id: @estatus.estatus_id, informe_id: nil).take if(revision == nil || revision =="") revision = Revision.new revision.informe_id = nil revision.usuario_id = session[:usuario_id] revision.adecuacion_id = @adecuacion.id revision.estatus_id = @estatus.estatus_id revision.fecha = Time.now revision.save else revision.fecha = Time.now revision.save end if params[:prim_part] == "si" #presentacion aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0, actividad_id: params[:presentacionId]).take oa= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa.id, revision_id: revision.id).take if(!params[:obsPresentacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadAdecuacion.new oa.adecuacionactividad_id = aa.id oa.revision_id = revision.id oa.observaciones = params[:obsPresentacion] oa.actual = 1 oa.save else oa.observaciones = params[:obsPresentacion] oa.save end end #Descripcion aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0, actividad_id: params[:descripcionId]).take oa= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa, revision_id: revision.id).take if(!params[:obsDescripcion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadAdecuacion.new oa.adecuacionactividad_id = aa.id oa.revision_id = revision.id oa.observaciones = params[:obsDescripcion] oa.actual = 1 oa.save else oa.observaciones = params[:obsDescripcion] oa.save end end end #Comienza actividades de docencia j=0 i=:doc.to_s+j.to_s @act = params[i].to_i while j < @cant_doc aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: params[:semestre].to_i, actividad_id: @act).take observacion =:[email protected]_s oa= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa, revision_id: revision.id).take if(!params[observacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadAdecuacion.new oa.adecuacionactividad_id = aa.id oa.revision_id = revision.id oa.observaciones = params[observacion] oa.actual = 1 oa.save else oa.observaciones = params[observacion] oa.save end end j= j+1 i=:doc.to_s+j.to_s @act= params[i].to_i end #Comienza actividades de investigacion j=0 i=:inv.to_s+j.to_s @act = params[i].to_i k=:result.to_s+j.to_s @result= params[k].to_i while j < @cant_inv aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: params[:semestre].to_i, actividad_id: @act).take observacion =:[email protected]_s oa= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa, revision_id: revision.id).take if(!params[observacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadAdecuacion.new oa.adecuacionactividad_id = aa.id oa.revision_id = revision.id oa.observaciones = params[observacion] oa.actual = 1 oa.save else oa.observaciones = params[observacion] oa.save end end j=j+1 i=:inv.to_s+j.to_s @act= params[i].to_i end #Comienza actividades de formaciรณn j=0 i=:for.to_s+j.to_s @act = params[i].to_i while j < @cant_for aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: params[:semestre].to_i, actividad_id: @act).take observacion =:[email protected]_s oa= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa, revision_id: revision.id).take if(!params[observacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadAdecuacion.new oa.adecuacionactividad_id = aa.id oa.revision_id = revision.id oa.observaciones = params[observacion] oa.actual = 1 oa.save else oa.observaciones = params[observacion] oa.save end end j= j+1 i=:for.to_s+j.to_s @act= params[i].to_i end #Comienzan actividades de extensiรณn j=0 i=:ext.to_s+j.to_s @act = params[i].to_i while j < @cant_ext aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: params[:semestre].to_i, actividad_id: @act).take observacion =:[email protected]_s oa= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa, revision_id: revision.id).take if(!params[observacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadAdecuacion.new oa.adecuacionactividad_id = aa.id oa.revision_id = revision.id oa.observaciones = params[observacion] oa.actual = 1 oa.save else oa.observaciones = params[observacion] oa.save end end j= j+1 i=:ext.to_s+j.to_s @act= params[i].to_i end #Comienzan Otras actividades j=0 i=:otr.to_s+j.to_s @act = params[i].to_i while j < @cant_otr aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: params[:semestre].to_i, actividad_id: @act).take observacion =:[email protected]_s oa= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa, revision_id: revision.id).take if(!params[observacion].blank?) if(oa == nil || oa =="") oa = ObservacionActividadAdecuacion.new oa.adecuacionactividad_id = aa.id oa.revision_id = revision.id oa.observaciones = params[observacion] oa.actual = 1 oa.save else oa.observaciones = params[observacion] oa.save end end j= j+1 i=:otr.to_s+j.to_s @act= params[i].to_i end flash[:success]="Se han creado y/o modificado las observaciones satisfactoriamente" if(@semestre == 0) redirect_to controller:"inicioentidad", action: "detalles_adecuacion2" end if(@semestre == 1) redirect_to controller:"inicioentidad", action: "detalles_adecuacion3" end if(@semestre == 2) redirect_to controller:"inicioentidad", action: "detalles_adecuacion4" end if(@semestre == 3) redirect_to controller:"inicioentidad", action: "detalles_adecuacion5" end if(@semestre == 4) redirect_to controller:"inicioentidad", action: "detalles_adecuacion6" end if(@semestre == 5) redirect_to controller:"inicioentidad", action: "detalles_adecuacion7" end else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end end end def mas_observaciones3 #mas obs de actividades del Adecuaciรณn if !session[:adecuacion_id].blank? @boolobs = 0 @adecuacion= Adecuacion.find(session[:adecuacion_id]) @cjpTipo=Usuario.find(session[:usuario_id]).tipo @semestre = params[:semestre].to_i @actividad_id = params[:actividad_id].to_i aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: @semestre, actividad_id: @actividad_id).take @observaciones= ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa.id) @observaciones.each do |obs| if(obs.observaciones != "") @boolobs = 1 end end @observaciones.each do |obs| rev = Revision.find(obs.revision_id) entidad = Usuarioentidad.where(usuario_id: rev.usuario_id).take if (entidad.entidad_id >= 7 && entidad.entidad_id <= 12) #comision investigacion @obs_inv = obs.observaciones #Estatus enviado a comision de investigacion elsif (entidad.entidad_id >= 14 && entidad.entidad_id <= 17) #Consejo tecnico @obs_consejoT = obs.observaciones elsif (entidad.entidad_id >= 1 && entidad.entidad_id <= 6) #Consejo de escuela @obs_consejoE = obs.observaciones elsif (entidad.entidad_id == 13) #Consejo de facultad @obs_consejoF = obs.observaciones end end @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end end def cambiar_estatusI if !params[:informe_id].blank? @informe_id = params[:informe_id].to_i rechazar = params[:rechazar].to_i @cjpTipo=Usuario.find(session[:usuario_id]).tipo informeAct = Informe.where(id: @informe_id).take session[:plan_id] = informeAct.planformacion_id adec = Adecuacion.where(planformacion_id: informeAct.planformacion_id).take session[:adecuacion_id] = adec.id if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) @document = Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: @informe_id, actual: 1).take @document.estatus = "Enviado a Consejo de Escuela" @document.save cambio_act = EstatusInforme.where(informe_id: @informe_id, actual: 1).take cambio_act.actual = 0 cambio_act.save cambio_est = EstatusInforme.new cambio_est.informe_id = @informe_id cambio_est.fecha = Time.now cambio_est.estatus_id = 8 cambio_est.actual = 1 cambio_est.save plan = Planformacion.find(session[:plan_id]) cambio_est.fecha = Time.now notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = informeAct.tutor_id notific.adecuacion_id = session[:adecuacion_id] notific.informe_id = @informe_id notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] El " + session[:nombre_informe] + " de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha sido aprobado por Comisiรณn de Investigaciรณn y fue enviada a Consejo de Escuela." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = informeAct.tutor_id notific2.adecuacion_id = session[:adecuacion_id] notific2.informe_id = @informe_id notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] El " + session[:nombre_informe] + " ha sido aprobado por Comisiรณn de Investigaciรณn y fue enviada a Consejo de Escuela." notific2.save notific3 = Notificacion.new notific3.instructor_id = plan.instructor_id notific3.tutor_id = informeAct.tutor_id notific3.adecuacion_id = session[:adecuacion_id] notific3.informe_id = @informe_id notific3.actual = 4 #Consejo de Escuela notific3.mensaje = "[" + notificacionfecha + "] Ha recibido un nuevo Informe: ' " + session[:nombre_informe]+ " ' de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + ", favor aprobar y enviar a la siguiente entidad." notific3.save user =Usuarioentidad.where(entidad_id: session[:entidad_id]).take if(user.escuela_id == 1) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 1).take elsif(user.escuela_id == 2) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 2).take elsif(user.escuela_id == 3) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 3).take elsif(user.escuela_id == 4) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 4).take elsif(user.escuela_id == 9) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 5).take elsif(user.escuela_id == 10) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 6).take end linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe&param1=" + plan.id.to_s + "&param2="+ @informe_id.to_s linkE = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe&param1=" + plan.id.to_s+ "&param2="+@informe_id.to_s+"&param3="+adec.id.to_s remitente3 = Usuario.where(id: informeAct.tutor_id).take ActionCorreo.envio_informe(remitente3, notific.mensaje,2,linkTeI,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_informe(remitente2, notific2.mensaje,1,linkTeI,@document).deliver remitente = Usuario.where(id: uentidad.usuario_id).take ActionCorreo.envio_informe(remitente, notific3.mensaje,0,linkE,@document).deliver flash[:success]="El informe se ha envรญado a consejo de escuela" elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela @document = Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: @informe_id, actual: 1).take @document.estatus = "Enviado a Consejo de Facultad" @document.save cambio_act = EstatusInforme.where(informe_id: @informe_id, actual: 1).take cambio_act.actual = 0 cambio_act.save cambio_est = EstatusInforme.new cambio_est.informe_id = @informe_id cambio_est.fecha = Time.now cambio_est.estatus_id = 4 cambio_est.actual = 1 cambio_est.save plan = Planformacion.find(session[:plan_id]) cambio_est.fecha = Time.now notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = informeAct.tutor_id notific.adecuacion_id = session[:adecuacion_id] notific.informe_id = @informe_id notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] El " + session[:nombre_informe] + " de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha sido aprobado por Consejo de Escuela y fue enviada a Consejo de Facultad." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = informeAct.tutor_id notific2.adecuacion_id = session[:adecuacion_id] notific2.informe_id = @informe_id notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] El " + session[:nombre_informe] + " ha sido aprobado por Consejo de Escuela y fue enviada a Consejo de Facultad." notific2.save notific3 = Notificacion.new notific3.instructor_id = plan.instructor_id notific3.tutor_id = informeAct.tutor_id notific3.adecuacion_id = session[:adecuacion_id] notific3.informe_id = @informe_id notific3.actual = 5 #Consejo de Facultad notific3.mensaje = "[" + notificacionfecha + "] Ha recibido un nuevo Informe: ' " + session[:nombre_informe]+ " ' de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + ", revisar." notific3.save uentidad = Usuarioentidad.where(entidad_id: 13).take remitente3 = Usuario.where(id: informeAct.tutor_id).take linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe&param1=" + plan.id.to_s + "&param2="+ @informe_id.to_s linkE = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe&param1=" + plan.id.to_s+ "&param2="+@informe_id.to_s+"&param3="+adec.id.to_s ActionCorreo.envio_informe(remitente3, notific.mensaje,2,linkTeI,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_informe(remitente2, notific2.mensaje,1,linkTeI,@document).deliver remitente = Usuario.where(id: uentidad.usuario_id).take ActionCorreo.envio_informe(remitente, notific3.mensaje,0,linkE,@document).deliver ActionCorreo.envio_informe("<EMAIL>", notific3.mensaje,0, linkE,@document).deliver flash[:success]="El informe se ha envรญado a consejo de facultad" elsif (session[:entidad_id] == 13) #Consejo de facultad bool_observaciones= 0 acts_informe = InformeActividad.where(informe_id: @informe_id) if (rechazar == 2) bool_observaciones = 1 end cambio_act = EstatusInforme.where(informe_id: @informe_id, actual: 1).take cambio_act.actual = 0 cambio_act.save cambio_est = EstatusInforme.new cambio_est.informe_id = @informe_id cambio_est.fecha = Time.now if(rechazar == 1) cambio_est.estatus_id = 9 else if bool_observaciones == 1 cambio_est.estatus_id = 5 else cambio_est.estatus_id = 1 end end cambio_est.actual = 1 cambio_est.save inf = Informe.where(id: @informe_id).take cambio_est.fecha = Time.now plan = Planformacion.find(session[:plan_id]) linkTeI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar informe&param1=" + plan.id.to_s + "&param2="+ @informe_id.to_s if(rechazar == 1) @document = Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: @informe_id, actual: 1).take @document.estatus = "Rechazado por Consejo de Facultad" @document.actual = 0 @document.save flash[:info]="El informe ha sido rechazado por consejo de facultad" notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = informeAct.tutor_id notific.adecuacion_id = session[:adecuacion_id] notific.informe_id = @informe_id notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] El " + session[:nombre_informe] + " de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha sido rechazado por Consejo de Facultad." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = informeAct.tutor_id notific2.adecuacion_id = session[:adecuacion_id] notific2.informe_id = @informe_id notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] El " + session[:nombre_informe] + " ha sido rechazado por Consejo de Facultad." notific2.save remitente3 = Usuario.where(id: informeAct.tutor_id).take ActionCorreo.envio_informe(remitente3, notific.mensaje,2,linkTeI,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_informe(remitente2, notific2.mensaje,1,linkTeI,@document).deliver cpusuario = Usuario.where(id: plan.instructor_id).take cpusuario.activo = 0 cpusuario.save elsif bool_observaciones == 1 @document = Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: @informe_id, actual: 1).take @document.estatus = "Aprobado por Consejo de Facultad con Observaciones" @document.actual = 0 @document.save flash[:info]="El informe ha sido aprobado con observaciones por consejo de facultad" notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = informeAct.tutor_id notific.adecuacion_id = session[:adecuacion_id] notific.informe_id = @informe_id notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] El " + session[:nombre_informe] + " de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha sido aprobado con observaciones por Consejo de Facultad." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = informeAct.tutor_id notific2.adecuacion_id = session[:adecuacion_id] notific2.informe_id = @informe_id notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] El " + session[:nombre_informe] + " ha sido aprobado con observaciones por Consejo de Facultad." notific2.save remitente3 = Usuario.where(id: informeAct.tutor_id).take ActionCorreo.envio_informe(remitente3, notific.mensaje,2,linkTeI,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_informe(remitente2, notific2.mensaje,1,linkTeI,@document).deliver else @document = Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: @informe_id, actual: 1).take @document.estatus = "Aprobado por Consejo de Facultad" @document.actual = 0 @document.save flash[:info]="El informe ha sido aprobado por consejo de facultad" notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = informeAct.tutor_id notific.adecuacion_id = session[:adecuacion_id] notific.informe_id = @informe_id notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] ยกFelicitaciones! El " + session[:nombre_informe] + " de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha sido aprobado por Consejo de Facultad." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = informeAct.tutor_id notific2.adecuacion_id = session[:adecuacion_id] notific2.informe_id = @informe_id notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] ยกFelicitaciones! El " + session[:nombre_informe] + " ha sido aprobado por Consejo de Facultad." notific2.save remitente3 = Usuario.where(id: informeAct.tutor_id).take ActionCorreo.envio_informe(remitente3, notific.mensaje,2,linkTeI,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_informe(remitente2, notific2.mensaje,1,linkTeI,@document).deliver end end redirect_to controller:"inicioentidad", action: "listar_informes" else flash[:info]="Seleccione un informe primero" redirect_to controller:"inicioentidad", action: "listar_informes" end end def vista_previa if !session[:plan_id].blank? session[:informe_id]=nil @cjpTipo=Usuario.find(session[:usuario_id]).tipo @fechaActual = Date.current.to_s @plan= Planformacion.find(session[:plan_id]) @fechaConcurso = @plan.fecha_inicio @usere= Usuarioentidad.where(usuario_id: @plan.instructor_id).take @escuela= Escuela.find(@usere.escuela_id) @adecuacion= Adecuacion.where(planformacion_id: @plan.id).take @adscripcion_docencia= @plan.adscripcion_docencia @adscripcion_investigacion= @plan.adscripcion_investigacion @persona= Persona.where(usuario_id: @plan.instructor_id).take @cpinstruccion = @persona.grado_instruccion @user = Usuario.find(@plan.instructor_id) @cpTutor= Persona.where(usuario_id: @plan.tutor_id).take @cpTutorEmail= Usuario.find(@plan.tutor_id).email @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @obligatoria= 'obligatoria' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] actividades = AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0) if !actividades.blank? actividades.each do |actividadAde| actividad = Actividad.find(actividadAde.actividad_id) if actividad.tipo_actividad_id == 9 @presentacion = actividad.actividad elsif actividad.tipo_actividad_id == 8 @descripcion = actividad.actividad end end else @presentacion = " " @descripcion = " " end @actividades0doc= [] @actividades0inv= [] @actividades0ext= [] @actividades0for= [] @actividades0otr= [] @actividades0= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0).all @actividades0.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades0doc.push(@act) elsif tipo==2 @actividades0inv.push(@act) elsif tipo==3 @actividades0ext.push(@act) elsif tipo==4 @actividades0for.push(@act) elsif tipo==5 @actividades0otr.push(@act) end end @actividades1doc= [] @actividades1inv= [] @actividades1ext= [] @actividades1for= [] @actividades1otr= [] @actividades1= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividades1.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades1doc.push(@act) elsif tipo==2 @actividades1inv.push(@act) elsif tipo==3 @actividades1ext.push(@act) elsif tipo==4 @actividades1for.push(@act) elsif tipo==5 @actividades1otr.push(@act) end end @actividades2doc= [] @actividades2inv= [] @actividades2ext= [] @actividades2for= [] @actividades2otr= [] @actividades2= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @actividades2.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades2doc.push(@act) elsif tipo==2 @actividades2inv.push(@act) elsif tipo==3 @actividades2ext.push(@act) elsif tipo==4 @actividades2for.push(@act) elsif tipo==5 @actividades2otr.push(@act) end end @actividades3doc= [] @actividades3inv= [] @actividades3ext= [] @actividades3for= [] @actividades3otr= [] @actividades3= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all @actividades3.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades3doc.push(@act) elsif tipo==2 @actividades3inv.push(@act) elsif tipo==3 @actividades3ext.push(@act) elsif tipo==4 @actividades3for.push(@act) elsif tipo==5 @actividades3otr.push(@act) end end @actividades4doc= [] @actividades4inv= [] @actividades4ext= [] @actividades4for= [] @actividades4otr= [] @actividades4= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all @actividades4.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades4doc.push(@act) elsif tipo==2 @actividades4inv.push(@act) elsif tipo==3 @actividades4ext.push(@act) elsif tipo==4 @actividades4for.push(@act) elsif tipo==5 @actividades4otr.push(@act) end end @actividades5doc= [] @actividades5inv= [] @actividades5ext= [] @actividades5for= [] @actividades5otr= [] @actividades5= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 5).all @actividades5.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades5doc.push(@act) elsif tipo==2 @actividades5inv.push(@act) elsif tipo==3 @actividades5ext.push(@act) elsif tipo==4 @actividades5for.push(@act) elsif tipo==5 @actividades5otr.push(@act) end end @bool_enviado = 0 if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take #Estatus enviado a comision de investigacioni if(estatusI.estatus_id != 3 && estatusI.estatus_id != 13) @bool_enviado = 1 end elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 2 && estatusI.estatus_id != 12) @bool_enviado = 1 end elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 8 && estatusI.estatus_id != 18) @bool_enviado = 1 #Estatus enviado a consejo escuela end elsif (session[:entidad_id] == 13) #Consejo de facultad estatusI = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if(estatusI.estatus_id != 4 && estatusI.estatus_id != 14) @bool_enviado = 1 end end else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end end #Cambia el estatus de la adecuaciรณn def cambiar_estatusA if !params[:adecuacion_id].blank? @adecuacion_id = params[:adecuacion_id].to_i rechazar = params[:rechazar].to_i @cjpTipo=Usuario.find(session[:usuario_id]).tipo if (session[:entidad_id] >= 7 && session[:entidad_id] <= 12) #Usuario comision cambio_act = EstatusAdecuacion.where(adecuacion_id: @adecuacion_id, actual: 1).take cambio_act.actual = 0 cambio_act.save cambio_est = EstatusAdecuacion.new cambio_est.adecuacion_id = @adecuacion_id cambio_est.fecha = Time.now cambio_est.estatus_id = 8 cambio_est.actual = 1 cambio_est.save cambio_est.fecha = Time.now adac = AdecuacionActividad.where(adecuacion_id: @adecuacion_id).all adac.each do |adaa| oa = ObservacionActividadAdecuacion.where(adecuacionactividad_id: adaa.id, actual: 1).all oa.each do |oaa| oaa.fecha = Time.now oaa.actual = 0 oaa.save end end plan= Planformacion.find(session[:plan_id]) notific = Notificacion.new @document = Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: nil, actual: 1).take @document.estatus = "Enviado a Consejo de Escuela" @document.save #Carga de Notificaciones y Correos notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = session[:adecuacion_id] notific.informe_id = nil notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] La adecuaciรณn de "+ person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha sido aprobada por Comisiรณn de Investigaciรณn y fue enviada a Consejo de Escuela." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = session[:adecuacion_id] notific2.informe_id = nil notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] Su adecuaciรณn ha sido aprobada por Comisiรณn de Investigaciรณn y fue enviada a Consejo de Escuela" notific2.save notific3 = Notificacion.new notific3.instructor_id = plan.instructor_id notific3.tutor_id = plan.tutor_id notific3.adecuacion_id = session[:adecuacion_id] notific3.informe_id = nil notific3.actual = 4 #Consejo de Escuela notific3.mensaje = "[" + notificacionfecha + "] Se ha recibido una nueva Adecuaciรณn: "+ person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + ", favor aprobar y enviar a la siguiente entidad." notific3.save #\Carga de Notificaciones y Correos user =Usuarioentidad.where(entidad_id: session[:entidad_id]).take if(user.escuela_id == 1) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 1).take elsif(user.escuela_id == 2) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 2).take elsif(user.escuela_id == 3) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 3).take elsif(user.escuela_id == 4) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 4).take elsif(user.escuela_id == 9) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 5).take elsif(user.escuela_id == 10) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 6).take end linkT = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion&param1=" + plan.id.to_s + "&param2=no" linkI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion" linkE = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion&param3=" + @adecuacion_id.to_s remitente3 = Usuario.where(id: plan.tutor_id).take ActionCorreo.envio_adecuacion(remitente3, notific.mensaje,2,linkT,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_adecuacion(remitente2, notific2.mensaje,1,linkI,@document).deliver remitente = Usuario.where(id: uentidad.usuario_id).take ActionCorreo.envio_adecuacion(remitente, notific3.mensaje,0,linkE,@document).deliver flash[:success]="La adecuaciรณn se ha envรญado a consejo de escuela" elsif (session[:entidad_id] >= 14 && session[:entidad_id] <= 17) #Consejo tecnico elsif (session[:entidad_id] >= 1 && session[:entidad_id] <= 6) #Consejo de escuela adac = AdecuacionActividad.where(adecuacion_id: @adecuacion_id).all adac.each do |adaa| oa = ObservacionActividadAdecuacion.where(adecuacionactividad_id: adaa.id, actual: 1).all oa.each do |oaa| oaa.fecha = Time.now oaa.actual = 0 oaa.save end end @document = Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: nil, actual: 1).take @document.estatus = "Enviado a Consejo de Facultad" @document.save cambio_act = EstatusAdecuacion.where(adecuacion_id: @adecuacion_id, actual: 1).take cambio_act.actual = 0 cambio_act.save cambio_est = EstatusAdecuacion.new cambio_est.adecuacion_id = @adecuacion_id cambio_est.fecha = Time.now cambio_est.estatus_id = 4 cambio_est.actual = 1 cambio_est.save cambio_est.fecha = Time.now plan= Planformacion.find(session[:plan_id]) #Carga de Notificaciones y Correos notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = session[:adecuacion_id] notific.informe_id = nil notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] La adecuaciรณn de "+ person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha sido aprobada por Consejo de Escuela y fue enviada a Consejo de Facultad." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = session[:adecuacion_id] notific2.informe_id = nil notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] Su adecuaciรณn ha sido aprobada por Consejo de Escuela y fue enviada a Consejo de Facultad" notific2.save notific3 = Notificacion.new notific3.instructor_id = plan.instructor_id notific3.tutor_id = plan.tutor_id notific3.adecuacion_id = session[:adecuacion_id] notific3.informe_id = nil notific3.actual = 5 #Consejo de Escuela notific3.mensaje = "[" + notificacionfecha + "] Se ha recibido una nueva Adecuaciรณn: "+ person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + ", Revisar." notific3.save uentidad = Usuarioentidad.where(entidad_id: 13).take linkT = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion&param1=" + plan.id.to_s + "&param2=no" linkI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion" linkE = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion&param3=" + @adecuacion_id.to_s remitente3 = Usuario.where(id: plan.tutor_id).take ActionCorreo.envio_adecuacion(remitente3, notific.mensaje,2,linkT,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_adecuacion(remitente2, notific2.mensaje,1,linkI,@document).deliver remitente = Usuario.where(id: uentidad.usuario_id).take ActionCorreo.envio_adecuacion(remitente, notific3.mensaje,0,linkE,@document).deliver ActionCorreo.envio_adecuacion("<EMAIL>", notific3.mensaje,0, linkE,@document).deliver #\Carga de Notificaciones y Correos flash[:success]="La adecuaciรณn se ha envรญado a consejo de facultad" elsif (session[:entidad_id] == 13) #Consejo de FACULTAD bool_observaciones= 0 acts_adecuacion = AdecuacionActividad.where(adecuacion_id: @adecuacion_id) if (rechazar == 2) bool_observaciones = 1 end #Consejo de facultad cambio_act = EstatusAdecuacion.where(adecuacion_id: @adecuacion_id, actual: 1).take cambio_act.actual = 0 cambio_act.save cambio_est = EstatusAdecuacion.new cambio_est.adecuacion_id = @adecuacion_id cambio_est.fecha = Time.now if(rechazar == 1) cambio_est.estatus_id = 9 else if bool_observaciones == 1 cambio_est.estatus_id = 5 else cambio_est.estatus_id = 1 end end cambio_est.actual = 1 cambio_est.save adec = Adecuacion.where(id: @adecuacion_id).take plan = Planformacion.where(id: adec.planformacion_id).take linkT = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion&param1=" + plan.id.to_s + "&param2=no" linkI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion" if(rechazar == 1) @document = Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: nil, actual: 1).take @document.estatus = "Rechazado por Consejo de Facultad" @document.actual = 0 @document.save flash[:info]="La adecuaciรณn ha sido rechazada por consejo de facultad" #Carga de Notificaciones y Correos notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = session[:adecuacion_id] notific.informe_id = nil notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] La adecuaciรณn de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha sido rechazada por Consejo de Facultad." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = session[:adecuacion_id] notific2.informe_id = nil notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] Su adecuaciรณn ha sido rechazada por Consejo de Facultad." notific2.save remitente3 = Usuario.where(id: adec.tutor_id).take ActionCorreo.envio_adecuacion(remitente3, notific.mensaje,2,linkT,@document).deliver ##CORREO AL TUTOR remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_adecuacion(remitente2, notific2.mensaje,1,linkI,@document).deliver ##CORREO AL INSTRUCTOR #\Carga de Notificaciones y Correos elsif bool_observaciones == 1 @document = Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: nil, actual: 1).take @document.estatus = "Aprobado por Consejo de Facultad con Observaciones" @document.actual = 0 @document.save flash[:info]="La adecuaciรณn ha sido aprobada con observaciones por consejo de facultad" #Carga de Notificaciones y Correos notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = session[:adecuacion_id] notific.informe_id = nil notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] La adecuaciรณn de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha sido aprobada con observaciones por Consejo de Facultad." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = session[:adecuacion_id] notific2.informe_id = nil notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] Su adecuaciรณn ha sido aprobado con observaciones por Consejo de Facultad." notific2.save remitente3 = Usuario.where(id: adec.tutor_id).take ActionCorreo.envio_adecuacion(remitente3, notific.mensaje,2,linkT,@document).deliver ##CORREO AL TUTOR remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_adecuacion(remitente2, notific2.mensaje,1,linkI,@document).deliver ##CORREO AL INSTRUCTOR #\Carga de Notificaciones y Correos else @document = Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: nil, actual: 1).take @document.estatus = "Aprobado por Consejo de Facultad" @document.actual = 0 @document.save flash[:info]="La adecuaciรณn ha sido aprobado por consejo de facultad" #Carga de Notificaciones y Correos notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = plan.tutor_id notific.adecuacion_id = session[:adecuacion_id] notific.informe_id = nil notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] ยกFelicitaciones! La adecuaciรณn de " + person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " ha sido aprobada por Consejo de Facultad." notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = plan.tutor_id notific2.adecuacion_id = session[:adecuacion_id] notific2.informe_id = nil notific2.actual = 2 notific2.mensaje = "[" + notificacionfecha + "] ยกFelicitaciones! Su adecuaciรณn ha sido aprobada por Consejo de Facultad." notific2.save remitente3 = Usuario.where(id: adec.tutor_id).take ActionCorreo.envio_adecuacion(remitente3, notific.mensaje,2,linkT,@document).deliver ##CORREO AL TUTOR remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_adecuacion(remitente2, notific2.mensaje,1,linkI,@document).deliver ##CORREO AL INSTRUCTOR #\Carga de Notificaciones y Correos end adac = AdecuacionActividad.where(adecuacion_id: @adecuacion_id).all adac.each do |adaa| oa = ObservacionActividadAdecuacion.where(adecuacionactividad_id: adaa.id, actual: 1).all oa.each do |oaa| oaa.fecha = Time.now oaa.actual = 0 oaa.save end end end redirect_to controller:"inicioentidad", action: "listar_adecuaciones" else flash[:info]="Seleccione una adecuaciรณn primero" redirect_to controller:"inicioentidad", action: "listar_adecuaciones" end end def borrar_notificaciones #Funcion para borrar las notificaciones if session[:usuario_id] && session[:entidad] == true @noti= params[:noti] @cjpTipo=Usuario.find(session[:usuario_id]).tipo notaeliminar = Notificacion.where(id: @noti ).take if notaeliminar.blank? flash[:danger] = "Ha ocurrido un error al eliminar (notificacion no existente)" else notaeliminar.destroy end redirect_to controller:"inicioentidad", action: "index" else redirect_to controller:"forminst", action: "index" end end def destroyNotifications @post = Notificacion.find(params[:id]) respond_to do |format| if @post.destroy format.html { redirect_to :back } else flash[:notice] = "Post failed to delete." format.html { redirect_to :back } end end end end<file_sep>/forminst_new1/app/controllers/documentoinformes_controller.rb class DocumentoinformesController < ApplicationController before_action :set_documentoinforme, only: [:show, :edit, :update, :destroy] # GET /documentoinformes # GET /documentoinformes.json def index @documentoinformes = Documentoinforme.all end # GET /documentoinformes/1 # GET /documentoinformes/1.json def show end # GET /documentoinformes/new def new @documentoinforme = Documentoinforme.new end # GET /documentoinformes/1/edit def edit end # POST /documentoinformes # POST /documentoinformes.json def create @documentoinforme = Documentoinforme.new(documentoinforme_params) respond_to do |format| if @documentoinforme.save format.html { redirect_to @documentoinforme, notice: 'Documentoinforme was successfully created.' } format.json { render :show, status: :created, location: @documentoinforme } else format.html { render :new } format.json { render json: @documentoinforme.errors, status: :unprocessable_entity } end end end # PATCH/PUT /documentoinformes/1 # PATCH/PUT /documentoinformes/1.json def update respond_to do |format| if @documentoinforme.update(documentoinforme_params) format.html { redirect_to @documentoinforme, notice: 'Documentoinforme was successfully updated.' } format.json { render :show, status: :ok, location: @documentoinforme } else format.html { render :edit } format.json { render json: @documentoinforme.errors, status: :unprocessable_entity } end end end # DELETE /documentoinformes/1 # DELETE /documentoinformes/1.json def destroy @documentoinforme.destroy respond_to do |format| format.html { redirect_to documentoinformes_url, notice: 'Documentoinforme was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_documentoinforme @documentoinforme = Documentoinforme.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def documentoinforme_params params.require(:documentoinforme).permit(:id, :informeId, :archivo) end end <file_sep>/forminst_new1/app/models/documento.rb class Documento < ActiveRecord::Base belongs_to :informe_actividad end<file_sep>/forminst_new1/app/models/planformacion.rb class Planformacion < ActiveRecord::Base belongs_to :usuario has_many :adecuacion has_many :prorroga has_many :informe has_many :documento_plan end<file_sep>/forminst_new1/app/controllers/escuelas_controller.rb class EscuelasController < ApplicationController before_action :set_escuela, only: [:show, :edit, :update, :destroy] # GET /escuelas # GET /escuelas.json def index @escuelas = Escuela.all end # GET /escuelas/1 # GET /escuelas/1.json def show end # GET /escuelas/new def new @escuela = Escuela.new end # GET /escuelas/1/edit def edit end # POST /escuelas # POST /escuelas.json def create @escuela = Escuela.new(escuela_params) respond_to do |format| if @escuela.save format.html { redirect_to @escuela, notice: 'Escuela was successfully created.' } format.json { render :show, status: :created, location: @escuela } else format.html { render :new } format.json { render json: @escuela.errors, status: :unprocessable_entity } end end end # PATCH/PUT /escuelas/1 # PATCH/PUT /escuelas/1.json def update respond_to do |format| if @escuela.update(escuela_params) format.html { redirect_to @escuela, notice: 'Escuela was successfully updated.' } format.json { render :show, status: :ok, location: @escuela } else format.html { render :edit } format.json { render json: @escuela.errors, status: :unprocessable_entity } end end end # DELETE /escuelas/1 # DELETE /escuelas/1.json def destroy @escuela.destroy respond_to do |format| format.html { redirect_to escuelas_url, notice: 'Escuela was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_escuela @escuela = Escuela.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def escuela_params params.require(:escuela).permit(:id, :nombre) end end <file_sep>/forminst_new1/app/views/adecuacions/index.json.jbuilder json.array!(@adecuacions) do |adecuacion| json.extract! adecuacion, :id, :id, :PlanFormacionId, :tutorId json.url adecuacion_url(adecuacion, format: :json) end <file_sep>/forminst_new1/app/views/documentoinformes/index.json.jbuilder json.array!(@documentoinformes) do |documentoinforme| json.extract! documentoinforme, :id, :id, :informeId, :archivo json.url documentoinforme_url(documentoinforme, format: :json) end <file_sep>/forminst_new1/app/models/permiso.rb class Permiso < ActiveRecord::Base has_many :permisologium end<file_sep>/forminst_new1/README.txt Para las notificaciones, el campo actual significa a donde y/o quien va dirigido esa notificaciรณn: 1._ Tutor 2._ Instructor 3._ Comisiรณn de Investigaciรณn 4._ Consejo de Escuela 5._ Consejo de Facultad<file_sep>/forminst_new1/app/views/adecuacionactividads/index.json.jbuilder json.array!(@adecuacionactividads) do |adecuacionactividad| json.extract! adecuacionactividad, :id, :id, :adecuacionId, :actividadId, :anulada, :semestre json.url adecuacionactividad_url(adecuacionactividad, format: :json) end <file_sep>/forminst_new1/app/views/prorrogas/show.json.jbuilder json.extract! @prorroga, :id, :id, :planFormacionId, :created_at, :updated_at <file_sep>/forminst_new1/test/controllers/observaciontutors_controller_test.rb require 'test_helper' class ObservaciontutorsControllerTest < ActionController::TestCase setup do @observaciontutor = observaciontutors(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:observaciontutors) end test "should get new" do get :new assert_response :success end test "should create observaciontutor" do assert_difference('Observaciontutor.count') do post :create, observaciontutor: { actual: @observaciontutor.actual, fecha: @observaciontutor.fecha, id: @observaciontutor.id, informeActividadId: @observaciontutor.informeActividadId, observacion: @observaciontutor.observacion } end assert_redirected_to observaciontutor_path(assigns(:observaciontutor)) end test "should show observaciontutor" do get :show, id: @observaciontutor assert_response :success end test "should get edit" do get :edit, id: @observaciontutor assert_response :success end test "should update observaciontutor" do patch :update, id: @observaciontutor, observaciontutor: { actual: @observaciontutor.actual, fecha: @observaciontutor.fecha, id: @observaciontutor.id, informeActividadId: @observaciontutor.informeActividadId, observacion: @observaciontutor.observacion } assert_redirected_to observaciontutor_path(assigns(:observaciontutor)) end test "should destroy observaciontutor" do assert_difference('Observaciontutor.count', -1) do delete :destroy, id: @observaciontutor end assert_redirected_to observaciontutors_path end end <file_sep>/forminst_new1/app/views/estatusinformes/index.json.jbuilder json.array!(@estatusinformes) do |estatusinforme| json.extract! estatusinforme, :id, :id, :informeId, :fecha, :estatusId, :actual json.url estatusinforme_url(estatusinforme, format: :json) end <file_sep>/forminst_new1/app/controllers/documentoplans_controller.rb class DocumentoplansController < ApplicationController before_action :set_documentoplan, only: [:show, :edit, :update, :destroy] # GET /documentoplans # GET /documentoplans.json def index @documentoplans = Documentoplan.all end # GET /documentoplans/1 # GET /documentoplans/1.json def show end # GET /documentoplans/new def new @documentoplan = Documentoplan.new end # GET /documentoplans/1/edit def edit end # POST /documentoplans # POST /documentoplans.json def create @documentoplan = Documentoplan.new(documentoplan_params) respond_to do |format| if @documentoplan.save format.html { redirect_to @documentoplan, notice: 'Documentoplan was successfully created.' } format.json { render :show, status: :created, location: @documentoplan } else format.html { render :new } format.json { render json: @documentoplan.errors, status: :unprocessable_entity } end end end # PATCH/PUT /documentoplans/1 # PATCH/PUT /documentoplans/1.json def update respond_to do |format| if @documentoplan.update(documentoplan_params) format.html { redirect_to @documentoplan, notice: 'Documentoplan was successfully updated.' } format.json { render :show, status: :ok, location: @documentoplan } else format.html { render :edit } format.json { render json: @documentoplan.errors, status: :unprocessable_entity } end end end # DELETE /documentoplans/1 # DELETE /documentoplans/1.json def destroy @documentoplan.destroy respond_to do |format| format.html { redirect_to documentoplans_url, notice: 'Documentoplan was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_documentoplan @documentoplan = Documentoplan.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def documentoplan_params params.require(:documentoplan).permit(:id, :planFormacionId, :archivo) end end <file_sep>/forminst_new1/app/controllers/administrador_controller.rb class AdministradorController < ApplicationController layout 'ly_inicio_entidad' def index session[:administrador] if session[:usuario_id]=="-2552" && session[:administrador] && session[:nombre_usuario]=="Administrador" else redirect_to controller:"forminst", action: "index" end end def agregar_secretaria session[:administrador] if session[:usuario_id]=="-2552" && session[:administrador] && session[:nombre_usuario]=="Administrador" #Todas las Entidades cpentidad = Entidad.all cpcontador = 0 @cpentidades = [] @cpentidades[cpcontador] = Array.new(2) { |i| } @cpentidades[cpcontador][0] = "Seleccione una entidad" @cpentidades[cpcontador][1] = 0 cpcontador = cpcontador + 1 cpentidad.each do |entidad| if entidad.nombre != "tutor" && entidad.nombre != "instructor" @cpentidades[cpcontador] = Array.new(2) { |i| } @cpentidades[cpcontador][0] = entidad.nombre @cpentidades[cpcontador][1] = entidad.id cpcontador = cpcontador + 1 end end #Todas las Escuelas cpescuela = Escuela.all cpcontador = 0 @cpescuelas = [] @cpescuelas[cpcontador] = Array.new(2) { |i| } @cpescuelas[cpcontador][0] = "Seleccione una escuela" @cpescuelas[cpcontador][1] = 0 cpcontador = cpcontador + 1 cpescuela.each do |escuela| if escuela.nombre != "Desconocida" @cpescuelas[cpcontador] = Array.new(2) { |i| } @cpescuelas[cpcontador][0] = escuela.nombre @cpescuelas[cpcontador][1] = escuela.id cpcontador = cpcontador + 1 end end else redirect_to controller:"forminst", action: "index" end end def guardar_secretaria session[:administrador] if session[:usuario_id]=="-2552" && session[:administrador] && session[:nombre_usuario]=="Administrador" clave = params[:CI].to_s cpusuario = Usuario.new cpusuario.user = params[:correo] cpusuario.password = <PASSWORD>(<PASSWORD>) cpusuario.ldap = 0 cpusuario.activo = 1 cpusuario.tipo = "Secretaria" cpusuario.email = params[:correo] cpusuario.save cppersona = Persona.new cppersona.usuario_id = cpusuario.id cppersona.nombres = params[:Nombre] cppersona.apellidos = params[:Apellido] cppersona.ci = params[:CI].to_s cppersona.save cpuentidad = Usuarioentidad.new cpuentidad.usuario_id = cpusuario.id cpuentidad.entidad_id = params[:jrentidades] cpuentidad.id = cpusuario.id cpuentidad.escuela_id = params[:jrescuelas] cpuentidad.save redirect_to controller:"administrador", action: "index" else redirect_to controller:"forminst", action: "index" end end def seleccionar_entidad session[:administrador] if session[:usuario_id]=="-2552" && session[:administrador] && session[:nombre_usuario]=="Administrador" #Todas las Entidades cpentidad = Entidad.all cpcontador = 0 @cpentidades = [] @cpentidades[cpcontador] = Array.new(2) { |i| } @cpentidades[cpcontador][0] = "Seleccione una entidad" @cpentidades[cpcontador][1] = 0 cpcontador = cpcontador + 1 cpentidad.each do |entidad| if entidad.nombre != "tutor" && entidad.nombre != "instructor" @cpentidades[cpcontador] = Array.new(2) { |i| } @cpentidades[cpcontador][0] = entidad.nombre @cpentidades[cpcontador][1] = entidad.id cpcontador = cpcontador + 1 end end else redirect_to controller:"forminst", action: "index" end end def modificar_email session[:administrador] if session[:usuario_id]=="-2552" && session[:administrador] && session[:nombre_usuario]=="Administrador" @entidadId = params[:jrentidades] cjpUsuarios = Usuarioentidad.where(entidad_id: params[:jrentidades]) cjpUsuarios.each do |uentidad| if Usuario.where(id: uentidad.usuario_id).take.tipo == "Institucional" $id = uentidad.usuario_id end end @email = Usuario.where(id: $id).take.user else redirect_to controller:"forminst", action: "index" end end def nuevo_participante session[:administrador] if session[:usuario_id]=="-2552" && session[:administrador] && session[:nombre_usuario]=="Administrador" @entidadId = params[:jrentidades] else redirect_to controller:"forminst", action: "index" end end def seleccionar_entidad_participante session[:administrador] if session[:usuario_id]=="-2552" && session[:administrador] && session[:nombre_usuario]=="Administrador" #Todas las Entidades cpentidad = Entidad.all cpcontador = 0 @cpentidades = [] @cpentidades[cpcontador] = Array.new(2) { |i| } @cpentidades[cpcontador][0] = "Seleccione una entidad" @cpentidades[cpcontador][1] = 0 cpcontador = cpcontador + 1 cpentidad.each do |entidad| if entidad.nombre != "tutor" && entidad.nombre != "instructor" @cpentidades[cpcontador] = Array.new(2) { |i| } @cpentidades[cpcontador][0] = entidad.nombre @cpentidades[cpcontador][1] = entidad.id cpcontador = cpcontador + 1 end end else redirect_to controller:"forminst", action: "index" end end def guardar_participante session[:administrador] if session[:usuario_id]=="-2552" && session[:administrador] && session[:nombre_usuario]=="Administrador" envio = Aenviar.new envio.entidad_id = params[:jrentidades] envio.email = params[:email] envio.save flash[:success]= "Participante guardado con exito" redirect_to controller:"administrador", action: "index" else redirect_to controller:"forminst", action: "index" end end def guardar_email session[:administrador] if session[:usuario_id]=="-2552" && session[:administrador] && session[:nombre_usuario]=="Administrador" usuario = Usuario.where(id: $id).take usuario.email = params[:email] usuario.user = params[:email] usuario.save redirect_to controller:"administrador", action: "index" else redirect_to controller:"forminst", action: "index" end end def logout reset_session redirect_to controller: "forminst", action: "index" end end <file_sep>/forminst_new1/app/models/actividadejecutada.rb class Actividadejecutada < ActiveRecord::Base belongs_to :informeactividad end<file_sep>/forminst_new1/app/views/permisologia/index.json.jbuilder json.array!(@permisologia) do |permisologium| json.extract! permisologium, :id, :id, :permisosId, :usuarioId, :attribute, :read, :write json.url permisologium_url(permisologium, format: :json) end <file_sep>/forminst_new1/app/controllers/secretarias_controller.rb class SecretariasController < ApplicationController require 'digest/sha1' layout 'ly_inicio_entidad' def index $modulo = "index" if session[:usuario_id] @nombre = session[:nombre_usuario] else redirect_to controller:"forminst", action: "index" end end def agregarTutor if session[:usuario_id] if $modulo != "agregarTutor" $cpnombre = nil $cpapellido = nil $cpci = nil $cpcorreo = nil $cptlf = nil $cpotlf = nil $cpfechanac = nil $cpdir = nil $cpgradoi = nil $cparea = nil $cpsubarea = nil $cpfechaconcurso = nil $cpjrtutores = nil $cpuad = nil $cpuai = nil end cpSecretariaID = session[:usuario_id] cpSecretaria = Usuarioentidad.where(usuario_id: cpSecretariaID).take cpSecretariaEscuela = cpSecretaria.escuela_id uentidad = Departamento.where(escuela_id: cpSecretariaEscuela) cpcontador = 0 @departamentos = [] @departamentos[cpcontador] = Array.new(2) { |i| } @departamentos[cpcontador][0] = "Seleccione un Departamento" @departamentos[cpcontador][1] = 0 cpcontador = cpcontador + 1 uentidad.each do |usuarioentidad| @departamentos[cpcontador] = Array.new(2) { |i| } @departamentos[cpcontador][0] = usuarioentidad.nombre @departamentos[cpcontador][1] = usuarioentidad.id cpcontador = cpcontador + 1 end $modulo = "agregarTutor" @nombre = session[:nombre_usuario] @personas = Persona.all session[:personas] = @personas.as_json(only: [:usuario_id, :nombres, :apellidos]) else redirect_to controller:"forminst", action: "index" end end def guarda_tutor if session[:usuario_id] haceralgo = "Si" cjprpersonas = Persona.where(ci: params[:CI]).take if !cjprpersonas.blank? haceralgo = "No" end cjprpersonas = Usuario.where(email: params[:correo]).take if !cjprpersonas.blank? haceralgo = "No" end cjprpersonas = Usuario.where(user: params[:correo]).take if !cjprpersonas.blank? haceralgo = "No" end if haceralgo == "Si" if params[:depto].to_i != 0 cpSecretariaID = session[:usuario_id] cpSecretaria = Usuarioentidad.where(usuario_id: cpSecretariaID).take cpSecretariaEscuela = cpSecretaria.escuela_id cpusuario = Usuario.new cpusuario.user = params[:correo].to_s cpusuario.password = <PASSWORD>(params[:CI]) cpusuario.ldap = 1 cpusuario.activo = 1 cpusuario.tipo = "Docente" cpusuario.email = params[:correo].to_s cpusuario.save cppersona = Persona.new cppersona.usuario_id = cpusuario.id cppersona.nombres = params[:Nombre].to_s cppersona.apellidos = params[:Apellido].to_s cppersona.fecha_nacimiento = params[:FechaNac].to_s cppersona.ci = params[:CI].to_s cppersona.telefono1 = params[:Tlf].to_s cppersona.telefono2 = params[:OTlf].to_s cppersona.direccion = params[:Dir].to_s cppersona.grado_instruccion = params[:GradoI].to_s cppersona.area = params[:Area].to_s cppersona.subarea = params[:Subarea].to_s cppersona.save cpuentidad = Usuarioentidad.new cpuentidad.usuario_id = cpusuario.id cpuentidad.entidad_id = 18 cpuentidad.id = cpusuario.id cpuentidad.escuela_id = cpSecretariaEscuela cpuentidad.departamento_id = params[:depto].to_i cpuentidad.save notific = Notificacion.new notific.instructor_id = nil notific.tutor_id = cpusuario.id notific.adecuacion_id = nil notific.informe_id = nil notific.actual = 1 notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] ยกBienvenido a FORMINST! Se ha creado su perfil de Tutor." notific.save remitente3 = Usuario.where(id: notific.tutor_id).take ActionCorreo.creacion_de_tutor(remitente3, notific.mensaje).deliver flash[:success] = "Se ha creado el tutor " + cppersona.nombres.to_s.split.map(&:capitalize).join(' ') + " " + cppersona.apellidos.to_s.split.map(&:capitalize).join(' ') + " de manera exitosa" redirect_to controller:"secretarias", action: "index" else $cpnombre = params[:Nombre] $cpapellido =params[:Apellido] $cpci = params[:CI] $cpcorreo = params[:correo] $cptlf = params[:Tlf] $cpotlf = params[:OTlf] $cpfechanac = params[:FechaNac] $cpdir = params[:Dir] $cpgradoi = params[:GradoI] $cparea = params[:Area] $cpsubarea = params[:Subarea] flash[:danger] = "Debe selecionar un departamento" redirect_to :back end else $cpnombre = params[:Nombre] $cpapellido =params[:Apellido] $cpci = params[:CI] $cpcorreo = params[:correo] $cptlf = params[:Tlf] $cpotlf = params[:OTlf] $cpfechanac = params[:FechaNac] $cpdir = params[:Dir] $cpgradoi = params[:GradoI] $cparea = params[:Area] $cpsubarea = params[:Subarea] flash[:danger] = "La cedula de identidad o el correo ya existe" redirect_to :back end else redirect_to controller:"forminst", action: "index" end end def agregarInstructor if session[:usuario_id] if $modulo != "agregarInstructor" $cpnombre = nil $cpapellido = nil $cpci = nil $cpcorreo = nil $cptlf = nil $cpotlf = nil $cpfechanac = nil $cpdir = nil $cpgradoi = nil $cparea = nil $cpsubarea = nil $cpfechaconcurso = nil $cpjrtutores = nil $cpuad = nil $cpuai = nil end $modulo = "agregarInstructor" i = 1 j = 1 nombre = "hola" cpid = 1 @nombre = session[:nombre_usuario] @personas = Persona.all session[:personas] = @personas.as_json(only: [:usuario_id, :nombres, :apellidos]) cpSecretariaID = session[:usuario_id] cpSecretaria = Usuarioentidad.where(usuario_id: cpSecretariaID).take cpSecretariaEscuela = cpSecretaria.escuela_id deptos = Departamento.where(escuela_id: cpSecretariaEscuela) cpcontador1 = 0 @departamentos = [] @departamentos[cpcontador1] = Array.new(2) { |i| } @departamentos[cpcontador1][0] = "Seleccione un Departamento" @departamentos[cpcontador1][1] = 0 cpcontador1 = cpcontador1 + 1 deptos.each do |usuarioentidad| @departamentos[cpcontador1] = Array.new(2) { |i| } @departamentos[cpcontador1][0] = usuarioentidad.nombre @departamentos[cpcontador1][1] = usuarioentidad.id cpcontador1 = cpcontador1 + 1 end uentidad = Usuarioentidad.where(escuela_id: cpSecretariaEscuela, entidad_id: 18) cpcontador = 0 cpaux = ['var1', 0] @cptutores = [] @cptutores[cpcontador] = Array.new(2) { |i| } @cptutores[cpcontador][0] = "Seleccione un tutor" @cptutores[cpcontador][1] = 0 cpcontador = cpcontador + 1 uentidad.each do |usuarioentidad| cppersona = Persona.find_by usuario_id: usuarioentidad.usuario_id @cptutores[cpcontador] = Array.new(2) { |i| } @cptutores[cpcontador][0] = cppersona.nombres.to_s.split.map(&:capitalize).join(' ') + " " + cppersona.apellidos.to_s.split.map(&:capitalize).join(' ') @cptutores[cpcontador][1] = usuarioentidad.usuario_id cpcontador = cpcontador + 1 end while i < cpcontador do nombre = @cptutores[i][0] cpid = @cptutores[i][1] j = i + 1 while j < cpcontador do if @cptutores[j][0] < nombre @cptutores[i][0] = @cptutores[j][0] @cptutores[i][1] = @cptutores[j][1] @cptutores[j][0] = nombre @cptutores[j][1] = cpid nombre = @cptutores[i][0] cpid = @cptutores[i][1] end j +=1 end i +=1 end else redirect_to controller:"forminst", action: "index" end end def guarda_instructor if session[:usuario_id] haceralgo = "Si" i = 1 j = 1 nombre = "hola" cpid = 1 cjprpersonas = Persona.where(ci: params[:CI]).take if !cjprpersonas.blank? haceralgo = "No" end cjprpersonas = Usuario.where(email: params[:correo]).take if !cjprpersonas.blank? haceralgo = "No" end cjprpersonas = Usuario.where(user: params[:correo]).take if !cjprpersonas.blank? haceralgo = "No" end if haceralgo == "Si" if params[:JRTutores].to_s != "0" && params[:depto].to_i != 0 profenti = Usuarioentidad.where(usuario_id: params[:JRTutores]).take if profenti.departamento_id == params[:depto].to_i cpelAno = params[:FechaConcurso][0..3] cpanoIncrementado = cpelAno.to_i + 2 cpGuardar = cpanoIncrementado.to_s + params[:FechaConcurso][4..params[:FechaConcurso].mb_chars.length] cpSecretariaID = session[:usuario_id] cpSecretaria = Usuarioentidad.where(usuario_id: cpSecretariaID).take cpSecretariaEscuela = cpSecretaria.escuela_id cpusuario = Usuario.new cpusuario.user = params[:correo] cpusuario.password = Digest::SHA1.hexdigest(params[:CI]) cpusuario.ldap = 1 cpusuario.activo = 1 cpusuario.tipo = "Docente" cpusuario.email = params[:correo] cpusuario.save cppersona = Persona.new cppersona.usuario_id = cpusuario.id cppersona.nombres = params[:Nombre] cppersona.apellidos = params[:Apellido] cppersona.fecha_nacimiento = params[:FechaNac] cppersona.ci = params[:CI].to_s cppersona.telefono1 = params[:Tlf] cppersona.telefono2 = params[:OTlf] cppersona.direccion = params[:Dir] cppersona.grado_instruccion = params[:GradoI] cppersona.area = params[:Area] cppersona.subarea = params[:Subarea] cppersona.save cpuentidad = Usuarioentidad.new cpuentidad.usuario_id = cpusuario.id cpuentidad.entidad_id = 19 cpuentidad.id = cpusuario.id cpuentidad.escuela_id = cpSecretariaEscuela cpuentidad.departamento_id = params[:depto].to_i cpuentidad.save cpplanformacion = Planformacion.new cpplanformacion.fecha_inicio = params[:FechaConcurso] cpplanformacion.fecha_fin = cpGuardar cpplanformacion.activo = 1 cpplanformacion.instructor_id = cpusuario.id cpplanformacion.tutor_id = params[:JRTutores] cpplanformacion.adscripcion_docencia = params[:UAD] cpplanformacion.adscripcion_investigacion = params[:UAI] cpplanformacion.save cpAdecuacion = Adecuacion.new cpAdecuacion.planformacion_id = cpplanformacion.id cpAdecuacion.tutor_id = cpplanformacion.tutor_id cpAdecuacion.fecha_creacion = cpplanformacion.fecha_inicio cpAdecuacion.fecha_modificacion = cpplanformacion.fecha_inicio cpAdecuacion.save cpEstatus_Adecuacion = EstatusAdecuacion.new cpEstatus_Adecuacion.adecuacion_id = cpAdecuacion.id cpEstatus_Adecuacion.fecha = Date.current.to_s cpEstatus_Adecuacion.estatus_id = 6 cpEstatus_Adecuacion.actual = 1 cpEstatus_Adecuacion.save cpinstructortutor = Instructortutor.where(instructor_id: cpplanformacion.instructor_id, tutor_id: params[:JRTutores]).take if cpinstructortutor.blank? cpinstructortutor = Instructortutor.new cpinstructortutor.tutor_id = params[:JRTutores] cpinstructortutor.instructor_id = cpplanformacion.instructor_id cpinstructortutor.actual = 1 cpinstructortutor.fecha_inicio = params[:FechaConcurso] else cpinstructortutor.actual = 1 end cpinstructortutor.save notific = Notificacion.new notific.instructor_id = cpusuario.id notific.tutor_id = params[:JRTutores] profe = Persona.where(usuario_id: params[:JRTutores]).take adecc = Adecuacion.where(planformacion_id: cpAdecuacion.planformacion_id).take plan = Planformacion.where(id: cpAdecuacion.planformacion_id).take notific.adecuacion_id = adecc.id notific.informe_id = nil notific.actual = 1 notificacionfecha = Date.current.to_s notific.mensaje = "[" + notificacionfecha + "] Se le ha asignado el Plan formaciรณn de " + cppersona.nombres.to_s.split.map(&:capitalize).join(' ') + " " + cppersona.apellidos.to_s.split.map(&:capitalize).join(' ') + ", recuerde crear la adecuaciรณn correspondiente y enviarla." notific.save notific2 = Notificacion.new notific2.instructor_id = cpusuario.id notific2.tutor_id = params[:JRTutores] notific2.adecuacion_id = adecc.id notific2.informe_id = nil notific2.actual = 2 notificacionfecha = Date.current.to_s notific2.mensaje = "[" + notificacionfecha + "] ยกBienvenido a FORMINST! Se le ha asignado a " + profe.nombres.to_s.split.map(&:capitalize).join(' ') + " " + profe.apellidos.to_s.split.map(&:capitalize).join(' ') + " como tutor de su Plan de formaciรณn." notific2.save linkT = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion&param1=" + cpAdecuacion.planformacion_id.to_s + "&param2=no" linkI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion" remitente3 = Usuario.where(id: notific.tutor_id).take ActionCorreo.creacion_de_instructor(remitente3, notific.mensaje,1,linkT).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.creacion_de_instructor(remitente2, notific2.mensaje,0,linkI).deliver flash[:success] = "Se ha creado el instructor " + cppersona.nombres.to_s.split.map(&:capitalize).join(' ') + " " + cppersona.apellidos.to_s.split.map(&:capitalize).join(' ') + " de manera exitosa" redirect_to controller:"secretarias", action: "index" else $cpnombre = params[:Nombre] $cpapellido =params[:Apellido] $cpci = params[:CI] $cpcorreo = params[:correo] $cptlf = params[:Tlf] $cpotlf = params[:OTlf] $cpfechanac = params[:FechaNac] $cpdir = params[:Dir] $cpgradoi = params[:GradoI] $cparea = params[:Area] $cpsubarea = params[:Subarea] $cpfechaconcurso = params[:FechaConcurso] $cpjrtutores = params[:JRTutores] $cpuad = params[:UAD] $cpuai = params[:UAI] flash[:danger] = "El tutor debe pertenecer al mismo departamento del instructor" redirect_to :back end else $cpnombre = params[:Nombre] $cpapellido =params[:Apellido] $cpci = params[:CI] $cpcorreo = params[:correo] $cptlf = params[:Tlf] $cpotlf = params[:OTlf] $cpfechanac = params[:FechaNac] $cpdir = params[:Dir] $cpgradoi = params[:GradoI] $cparea = params[:Area] $cpsubarea = params[:Subarea] $cpfechaconcurso = params[:FechaConcurso] $cpjrtutores = params[:JRTutores] $cpuad = params[:UAD] $cpuai = params[:UAI] flash[:danger] = "Seleccione Departamento y Tutor" redirect_to :back end else $cpnombre = params[:Nombre] $cpapellido =params[:Apellido] $cpci = params[:CI] $cpcorreo = params[:correo] $cptlf = params[:Tlf] $cpotlf = params[:OTlf] $cpfechanac = params[:FechaNac] $cpdir = params[:Dir] $cpgradoi = params[:GradoI] $cparea = params[:Area] $cpsubarea = params[:Subarea] $cpfechaconcurso = params[:FechaConcurso] $cpjrtutores = params[:JRTutores] $cpuad = params[:UAD] $cpuai = params[:UAI] flash[:danger] = "La cedula de identidad o el correo ya existe" redirect_to :back end else redirect_to controller:"forminst", action: "index" end end def modificarInstructor if session[:usuario_id] if $modulo != "modificarInstructor" $cpnombre = nil $cpapellido = nil $cpci = nil $cpcorreo = nil $cptlf = nil $cpotlf = nil $cpfechanac = nil $cpdir = nil $cpgradoi = nil $cparea = nil $cpsubarea = nil $cpfechaconcurso = nil $cpjrtutores = nil $cpuad = nil $cpuai = nil end @ver = params[:ver] $modulo = "modificarInstructor" i = 1 j = 1 nombre = "hola" cpid = 1 @nombre = session[:nombre_usuario] @personas = Persona.all session[:personas] = @personas.as_json(only: [:usuario_id, :nombres, :apellidos]) cpSecretariaID = session[:usuario_id] cpSecretaria = Usuarioentidad.where(usuario_id: cpSecretariaID).take cpSecretariaEscuela = cpSecretaria.escuela_id uentidad = Usuarioentidad.where(escuela_id: cpSecretariaEscuela, entidad_id: 19) cpcontador = 0 cpaux = ['var1', 0] @cptutores = [] @cptutores[cpcontador] = Array.new(2) { |i| } @cptutores[cpcontador][0] = "Seleccione un instructor" @cptutores[cpcontador][1] = 0 cpcontador = cpcontador + 1 uentidad.each do |usuarioentidad| cppersona = Persona.find_by usuario_id: usuarioentidad.usuario_id @cptutores[cpcontador] = Array.new(2) { |i| } @cptutores[cpcontador][0] = cppersona.nombres.to_s.split.map(&:capitalize).join(' ') + " " + cppersona.apellidos.to_s.split.map(&:capitalize).join(' ') @cptutores[cpcontador][1] = usuarioentidad.usuario_id cpcontador = cpcontador + 1 end while i < cpcontador do nombre = @cptutores[i][0] cpid = @cptutores[i][1] j = i + 1 while j < cpcontador do if @cptutores[j][0] < nombre @cptutores[i][0] = @cptutores[j][0] @cptutores[i][1] = @cptutores[j][1] @cptutores[j][0] = nombre @cptutores[j][1] = cpid nombre = @cptutores[i][0] cpid = @cptutores[i][1] end j +=1 end i +=1 end else redirect_to controller:"forminst", action: "index" end end def modificarInstructor2 if session[:usuario_id] if params[:JRTutores].to_s != "0" $id_tutor_seleccionado = params[:JRTutores] cppersona = Persona.find_by usuario_id: params[:JRTutores] cpusuario = Usuario.find_by id: params[:JRTutores] cpuentidad = Usuarioentidad.find_by usuario_id: params[:JRTutores] cpplanformacion = Planformacion.find_by instructor_id: params[:JRTutores] @ver = params[:ver] i = 1 j = 1 nombre = "hola" cpid = 1 @nombre = session[:nombre_usuario] @personas = Persona.all session[:personas] = @personas.as_json(only: [:usuario_id, :nombres, :apellidos]) cpSecretariaID = session[:usuario_id] cpSecretaria = Usuarioentidad.where(usuario_id: cpSecretariaID).take cpSecretariaEscuela = cpSecretaria.escuela_id uentidad = Usuarioentidad.where(escuela_id: cpSecretariaEscuela, entidad_id: 18) cpcontador = 0 cpaux = ['var1', 0] @cptutores = [] @cptutores[cpcontador] = Array.new(2) { |i| } @cptutores[cpcontador][0] = "Seleccione un tutor" @cptutores[cpcontador][1] = 0 cpcontador = cpcontador + 1 uentidad.each do |usuarioentidad| if usuarioentidad.usuario_id != cpplanformacion.tutor_id ccppersona = Persona.find_by usuario_id: usuarioentidad.usuario_id @cptutores[cpcontador] = Array.new(2) { |i| } @cptutores[cpcontador][0] = ccppersona.nombres @cptutores[cpcontador][1] = usuarioentidad.usuario_id cpcontador = cpcontador + 1 end end #informacion @tutoreDeInstructor = Persona.where(usuario_id: cpplanformacion.tutor_id).take @tutoreDeInstructorUsu = Usuario.where(id: cpplanformacion.tutor_id).take while i < cpcontador do nombre = @cptutores[i][0] cpid = @cptutores[i][1] j = i + 1 while j < cpcontador do if @cptutores[j][0] < nombre @cptutores[i][0] = @cptutores[j][0] @cptutores[i][1] = @cptutores[j][1] @cptutores[j][0] = nombre @cptutores[j][1] = cpid nombre = @cptutores[i][0] cpid = @cptutores[i][1] end j +=1 end i +=1 end $cpnombre = cppersona.nombres $cpapellido = cppersona.apellidos $cpci = cppersona.ci $cpcifija = cppersona.ci $cpcorreofijo = cpusuario.email $cpcorreo = cpusuario.email $cptlf = cppersona.telefono1 $cpotlf = cppersona.telefono2 $cpfechanac = cppersona.fecha_nacimiento $cpdir = cppersona.direccion $cpgradoi = cppersona.grado_instruccion $cparea = cppersona.area $cpsubarea = cppersona.subarea $cpfechaconcurso = cpplanformacion.fecha_inicio $cpuad = cpplanformacion.adscripcion_docencia $cpuai = cpplanformacion.adscripcion_investigacion else flash[:danger] = "Seleccione un Instructor" redirect_to :back end else redirect_to controller:"forminst", action: "index" end end def guarda_instructor_modificado if session[:usuario_id] haceralgo = "Si" i = 1 j = 1 nombre = "hola" cpid = 1 if $cpcifija.to_s != params[:CI].to_s cjprpersonas = Persona.where(ci: params[:CI]).take if !cjprpersonas.blank? haceralgo = "No" end end if $cpcorreofijo.to_s != params[:correo].to_s cjprpersonas = Usuario.where(email: params[:correo]).take if !cjprpersonas.blank? haceralgo = "No" end cjprpersonas = Usuario.where(user: params[:correo]).take if !cjprpersonas.blank? haceralgo = "No" end end if haceralgo == "Si" cpusuario = Usuario.find_by id: $id_tutor_seleccionado cpusuario.user = params[:correo].to_s cpusuario.password = params[:CI].to_s cpusuario.email = params[:correo].to_s cpusuario.save cppersona = Persona.find_by usuario_id: $id_tutor_seleccionado cppersona.nombres = params[:Nombre].to_s cppersona.apellidos = params[:Apellido].to_s cppersona.fecha_nacimiento = params[:FechaNac].to_s cppersona.ci = params[:CI].to_s cppersona.telefono1 = params[:Tlf].to_s cppersona.telefono2 = params[:OTlf].to_s cppersona.direccion = params[:Dir].to_s cppersona.grado_instruccion = params[:GradoI].to_s cppersona.area = params[:Area].to_s cppersona.subarea = params[:Subarea].to_s cppersona.save cpuentidad = Usuarioentidad.find_by usuario_id: $id_tutor_seleccionado cpuentidad.usuario_id = cpusuario.id cpuentidad.id = cpusuario.id cpuentidad.save cpplanformacion = Planformacion.find_by instructor_id: $id_tutor_seleccionado cpplanformacion.fecha_inicio = params[:FechaConcurso] cpplanformacion.adscripcion_docencia = params[:UAD] cpplanformacion.adscripcion_investigacion = params[:UAI] if params[:JRTutores].to_s != "0" cpinstructortutor = Instructortutor.where(instructor_id: cpplanformacion.instructor_id, tutor_id: cpplanformacion.tutor_id).take cpinstructortutor.actual = 0 cpinstructortutor.fecha_fin = Time.now.strftime("%Y") + "-" + Time.now.strftime("%m") + "-" + Time.now.strftime("%d") cpinstructortutor.save cpinstructortutor = Instructortutor.where(instructor_id: cpplanformacion.instructor_id, tutor_id: params[:JRTutores]).take if cpinstructortutor.blank? cpinstructortutor = Instructortutor.new cpinstructortutor.tutor_id = params[:JRTutores] cpinstructortutor.instructor_id = cpplanformacion.instructor_id cpinstructortutor.actual = 1 cpinstructortutor.fecha_inicio = Time.now.strftime("%Y") + "-" + Time.now.strftime("%m") + "-" + Time.now.strftime("%d") cpplanformacion.tutor_id = params[:JRTutores] else cpinstructortutor.actual = 1 cpplanformacion.tutor_id = params[:JRTutores] end cpinstructortutor.save pacjadecuacion = Adecuacion.where(planformacion_id: cpplanformacion.id).take pacjadecuacion.tutor_id = params[:JRTutores] pacjadecuacion.save end cpplanformacion.save cpAdecuacion = Adecuacion.find_by planformacion_id: cpplanformacion.id cpAdecuacion.fecha_creacion = cpplanformacion.fecha_inicio cpAdecuacion.save redirect_to controller:"secretarias", action: "index" else $cpnombre = params[:Nombre] $cpapellido =params[:Apellido] $cpci = params[:CI] $cpcorreo = params[:correo] $cptlf = params[:Tlf] $cpotlf = params[:OTlf] $cpfechanac = params[:FechaNac] $cpdir = params[:Dir] $cpgradoi = params[:GradoI] $cparea = params[:Area] $cpsubarea = params[:Subarea] flash[:danger] = "La cedula de identidad ya existe" redirect_to :back end else redirect_to controller:"forminst", action: "index" end end def modificarTutor if session[:usuario_id] if $modulo != "modificarTutor" $cpnombre = nil $cpapellido = nil $cpci = nil $cpcorreo = nil $cptlf = nil $cpotlf = nil $cpfechanac = nil $cpdir = nil $cpgradoi = nil $cparea = nil $cpsubarea = nil $cpfechaconcurso = nil $cpjrtutores = nil $cpuad = nil $cpuai = nil end @ver = params[:ver] $modulo = "modificarTutor" i = 1 j = 1 nombre = "hola" cpid = 1 @nombre = session[:nombre_usuario] @personas = Persona.all session[:personas] = @personas.as_json(only: [:usuario_id, :nombres, :apellidos]) cpSecretariaID = session[:usuario_id] cpSecretaria = Usuarioentidad.where(usuario_id: cpSecretariaID).take cpSecretariaEscuela = cpSecretaria.escuela_id uentidad = Usuarioentidad.where(escuela_id: cpSecretariaEscuela, entidad_id: 18) cpcontador = 0 cpaux = ['var1', 0] @cptutores = [] @cptutores[cpcontador] = Array.new(2) { |i| } @cptutores[cpcontador][0] = "Seleccione un tutor" @cptutores[cpcontador][1] = 0 cpcontador = cpcontador + 1 uentidad.each do |usuarioentidad| cppersona = Persona.find_by usuario_id: usuarioentidad.usuario_id @cptutores[cpcontador] = Array.new(2) { |i| } @cptutores[cpcontador][0] = cppersona.nombres.to_s.split.map(&:capitalize).join(' ') + " " + cppersona.apellidos.to_s.split.map(&:capitalize).join(' ') @cptutores[cpcontador][1] = usuarioentidad.usuario_id cpcontador = cpcontador + 1 end while i < cpcontador do nombre = @cptutores[i][0] cpid = @cptutores[i][1] j = i + 1 while j < cpcontador do if @cptutores[j][0] < nombre @cptutores[i][0] = @cptutores[j][0] @cptutores[i][1] = @cptutores[j][1] @cptutores[j][0] = nombre @cptutores[j][1] = cpid nombre = @cptutores[i][0] cpid = @cptutores[i][1] end j +=1 end i +=1 end else redirect_to controller:"forminst", action: "index" end end def modificarTutor2 if session[:usuario_id] if params[:JRTutores].to_s != "0" $id_tutor_seleccionado = params[:JRTutores].to_s cppersona = Persona.find_by usuario_id: params[:JRTutores].to_s cpusuario = Usuario.find_by id: params[:JRTutores].to_s cpuentidad = Usuarioentidad.find_by usuario_id: params[:JRTutores].to_s @ver = params[:ver] $cpnombre = cppersona.nombres $cpapellido = cppersona.apellidos $cpci = cppersona.ci $cpcifija = cppersona.ci $cpcorreo = cpusuario.email $cpcorreofijo = cpusuario.email $cptlf = cppersona.telefono1 $cpotlf = cppersona.telefono2 $cpfechanac = cppersona.fecha_nacimiento $cpdir = cppersona.direccion $cpgradoi = cppersona.grado_instruccion $cparea = cppersona.area $cpsubarea = cppersona.subarea else flash[:danger] = "Seleccione un Tutor" redirect_to :back end else redirect_to controller:"forminst", action: "index" end end def guarda_tutor_modificado if session[:usuario_id] haceralgo = "Si" i = 1 j = 1 nombre = "hola" cpid = 1 if $cpcifija.to_s != params[:CI].to_s cjprpersonas = Persona.where(ci: params[:CI]).take if !cjprpersonas.blank? haceralgo = "No" end end if $cpcorreofijo.to_s != params[:correo].to_s cjprpersonas = Usuario.where(email: params[:correo]).take if !cjprpersonas.blank? haceralgo = "No" end cjprpersonas = Usuario.where(user: params[:correo]).take if !cjprpersonas.blank? haceralgo = "No" end end if haceralgo == "Si" cpusuario = Usuario.find_by id: $id_tutor_seleccionado cpusuario.user = params[:correo].to_s cpusuario.password = params[:CI].to_s cpusuario.email = params[:correo].to_s cpusuario.save cppersona = Persona.find_by usuario_id: $id_tutor_seleccionado cppersona.nombres = params[:Nombre].to_s cppersona.apellidos = params[:Apellido].to_s cppersona.fecha_nacimiento = params[:FechaNac].to_s cppersona.ci = params[:CI].to_s cppersona.telefono1 = params[:Tlf].to_s cppersona.telefono2 = params[:OTlf].to_s cppersona.direccion = params[:Dir].to_s cppersona.grado_instruccion = params[:GradoI].to_s cppersona.area = params[:Area].to_s cppersona.subarea = params[:Subarea].to_s cppersona.save cpuentidad = Usuarioentidad.find_by usuario_id: $id_tutor_seleccionado cpuentidad.usuario_id = cpusuario.id cpuentidad.id = cpusuario.id cpuentidad.save redirect_to controller:"secretarias", action: "index" else $cpnombre = params[:Nombre] $cpapellido =params[:Apellido] $cpci = params[:CI] $cpcorreo = params[:correo] $cptlf = params[:Tlf] $cpotlf = params[:OTlf] $cpfechanac = params[:FechaNac] $cpdir = params[:Dir] $cpgradoi = params[:GradoI] $cparea = params[:Area] $cpsubarea = params[:Subarea] flash[:danger] = "La cedula de identidad o el correo ya existe" redirect_to :back end else redirect_to controller:"forminst", action: "index" end end def tutores_asignados if session[:usuario_id] @tutores_asig = Instructortutor.where(instructor_id: $id_tutor_seleccionado) else redirect_to controller:"forminst", action: "index" end end def logout reset_session redirect_to controller: "forminst", action: "index" end end <file_sep>/forminst_new1/test/controllers/informes_controller_test.rb require 'test_helper' class InformesControllerTest < ActionController::TestCase setup do @informe = informes(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:informes) end test "should get new" do get :new assert_response :success end test "should create informe" do assert_difference('Informe.count') do post :create, informe: { PlanFormacionId: @informe.PlanFormacionId, conclusiones: @informe.conclusiones, id: @informe.id, opinionTutor: @informe.opinionTutor, tutorId: @informe.tutorId } end assert_redirected_to informe_path(assigns(:informe)) end test "should show informe" do get :show, id: @informe assert_response :success end test "should get edit" do get :edit, id: @informe assert_response :success end test "should update informe" do patch :update, id: @informe, informe: { PlanFormacionId: @informe.PlanFormacionId, conclusiones: @informe.conclusiones, id: @informe.id, opinionTutor: @informe.opinionTutor, tutorId: @informe.tutorId } assert_redirected_to informe_path(assigns(:informe)) end test "should destroy informe" do assert_difference('Informe.count', -1) do delete :destroy, id: @informe end assert_redirected_to informes_path end end <file_sep>/forminst_new1/app/models/usuarioentidad.rb class Usuarioentidad < ActiveRecord::Base belongs_to :entidad belongs_to :usuario end<file_sep>/forminst_new1/test/controllers/observacionactividadadecuacions_controller_test.rb require 'test_helper' class ObservacionactividadadecuacionsControllerTest < ActionController::TestCase setup do @observacionactividadadecuacion = observacionactividadadecuacions(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:observacionactividadadecuacions) end test "should get new" do get :new assert_response :success end test "should create observacionactividadadecuacion" do assert_difference('Observacionactividadadecuacion.count') do post :create, observacionactividadadecuacion: { adecuacionActividadId: @observacionactividadadecuacion.adecuacionActividadId, fecha: @observacionactividadadecuacion.fecha, id: @observacionactividadadecuacion.id, observacion: @observacionactividadadecuacion.observacion, revisionId: @observacionactividadadecuacion.revisionId } end assert_redirected_to observacionactividadadecuacion_path(assigns(:observacionactividadadecuacion)) end test "should show observacionactividadadecuacion" do get :show, id: @observacionactividadadecuacion assert_response :success end test "should get edit" do get :edit, id: @observacionactividadadecuacion assert_response :success end test "should update observacionactividadadecuacion" do patch :update, id: @observacionactividadadecuacion, observacionactividadadecuacion: { adecuacionActividadId: @observacionactividadadecuacion.adecuacionActividadId, fecha: @observacionactividadadecuacion.fecha, id: @observacionactividadadecuacion.id, observacion: @observacionactividadadecuacion.observacion, revisionId: @observacionactividadadecuacion.revisionId } assert_redirected_to observacionactividadadecuacion_path(assigns(:observacionactividadadecuacion)) end test "should destroy observacionactividadadecuacion" do assert_difference('Observacionactividadadecuacion.count', -1) do delete :destroy, id: @observacionactividadadecuacion end assert_redirected_to observacionactividadadecuacions_path end end <file_sep>/forminst_new1/app/models/informeactividad.rb class Informeactividad < ActiveRecord::Base belongs_to :informe has_many :documento has_many :observacionesactividadinforme has_many :actividadejecutada has_many :observaciontutor belongs_to :actividad end<file_sep>/forminst_new1/app/views/usuarioentidads/index.json.jbuilder json.array!(@usuarioentidads) do |usuarioentidad| json.extract! usuarioentidad, :id, :id, :usuarioId, :entidadesId json.url usuarioentidad_url(usuarioentidad, format: :json) end <file_sep>/forminst_new1/app/models/documentoinforme.rb class Documentoinforme < ActiveRecord::Base belongs_to :informe end<file_sep>/forminst_new1/app/controllers/permisologia_controller.rb class PermisologiaController < ApplicationController before_action :set_permisologium, only: [:show, :edit, :update, :destroy] # GET /permisologia # GET /permisologia.json def index @permisologia = Permisologium.all end # GET /permisologia/1 # GET /permisologia/1.json def show end # GET /permisologia/new def new @permisologium = Permisologium.new end # GET /permisologia/1/edit def edit end # POST /permisologia # POST /permisologia.json def create @permisologium = Permisologium.new(permisologium_params) respond_to do |format| if @permisologium.save format.html { redirect_to @permisologium, notice: 'Permisologium was successfully created.' } format.json { render :show, status: :created, location: @permisologium } else format.html { render :new } format.json { render json: @permisologium.errors, status: :unprocessable_entity } end end end # PATCH/PUT /permisologia/1 # PATCH/PUT /permisologia/1.json def update respond_to do |format| if @permisologium.update(permisologium_params) format.html { redirect_to @permisologium, notice: 'Permisologium was successfully updated.' } format.json { render :show, status: :ok, location: @permisologium } else format.html { render :edit } format.json { render json: @permisologium.errors, status: :unprocessable_entity } end end end # DELETE /permisologia/1 # DELETE /permisologia/1.json def destroy @permisologium.destroy respond_to do |format| format.html { redirect_to permisologia_url, notice: 'Permisologium was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_permisologium @permisologium = Permisologium.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def permisologium_params params.require(:permisologium).permit(:id, :permisosId, :usuarioId, :attribute, :read, :write) end end <file_sep>/forminst_new1/app/views/resultados/index.json.jbuilder json.array!(@resultados) do |resultado| json.extract! resultado, :id, :id, :actividadId, :tipoResultadoId, :concepto json.url resultado_url(resultado, format: :json) end <file_sep>/forminst_new1/test/controllers/adecuacions_controller_test.rb require 'test_helper' class AdecuacionsControllerTest < ActionController::TestCase setup do @adecuacion = adecuacions(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:adecuacions) end test "should get new" do get :new assert_response :success end test "should create adecuacion" do assert_difference('Adecuacion.count') do post :create, adecuacion: { PlanFormacionId: @adecuacion.PlanFormacionId, id: @adecuacion.id, tutorId: @adecuacion.tutorId } end assert_redirected_to adecuacion_path(assigns(:adecuacion)) end test "should show adecuacion" do get :show, id: @adecuacion assert_response :success end test "should get edit" do get :edit, id: @adecuacion assert_response :success end test "should update adecuacion" do patch :update, id: @adecuacion, adecuacion: { PlanFormacionId: @adecuacion.PlanFormacionId, id: @adecuacion.id, tutorId: @adecuacion.tutorId } assert_redirected_to adecuacion_path(assigns(:adecuacion)) end test "should destroy adecuacion" do assert_difference('Adecuacion.count', -1) do delete :destroy, id: @adecuacion end assert_redirected_to adecuacions_path end end <file_sep>/forminst_new1/app/views/documentos/show.json.jbuilder json.extract! @documento, :id, :id, :informeActividadId, :archivo, :created_at, :updated_at <file_sep>/forminst_new1/app/views/informeactividads/index.json.jbuilder json.array!(@informeactividads) do |informeactividad| json.extract! informeactividad, :id, :id, :informeId, :actividadId json.url informeactividad_url(informeactividad, format: :json) end <file_sep>/forminst_new1/test/controllers/usuarioentidads_controller_test.rb require 'test_helper' class UsuarioentidadsControllerTest < ActionController::TestCase setup do @usuarioentidad = usuarioentidads(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:usuarioentidads) end test "should get new" do get :new assert_response :success end test "should create usuarioentidad" do assert_difference('Usuarioentidad.count') do post :create, usuarioentidad: { entidadesId: @usuarioentidad.entidadesId, id: @usuarioentidad.id, usuarioId: @usuarioentidad.usuarioId } end assert_redirected_to usuarioentidad_path(assigns(:usuarioentidad)) end test "should show usuarioentidad" do get :show, id: @usuarioentidad assert_response :success end test "should get edit" do get :edit, id: @usuarioentidad assert_response :success end test "should update usuarioentidad" do patch :update, id: @usuarioentidad, usuarioentidad: { entidadesId: @usuarioentidad.entidadesId, id: @usuarioentidad.id, usuarioId: @usuarioentidad.usuarioId } assert_redirected_to usuarioentidad_path(assigns(:usuarioentidad)) end test "should destroy usuarioentidad" do assert_difference('Usuarioentidad.count', -1) do delete :destroy, id: @usuarioentidad end assert_redirected_to usuarioentidads_path end end <file_sep>/forminst_new1/app/models/respaldo.rb class Respaldo < ActiveRecord::Base private def sanitize_filename(filename) # Get only the filename, not the whole path (for IE) # Thanks to this article I just found for the tip: http://mattberther.com/2007/10/19/uploading-files-to-a-database-using-rails return File.basename(filename) end NUM_BYTES_IN_MEGABYTE = 1048576 def file_size_under_one_mb if (this.file_contents.size.to_f / NUM_BYTES_IN_MEGABYTE) > 10 errors.add(:file, 'File size cannot be over ten megabytes.') end end end<file_sep>/forminst_new1/app/views/documentoinformes/show.json.jbuilder json.extract! @documentoinforme, :id, :id, :informeId, :archivo, :created_at, :updated_at <file_sep>/forminst_new1/app/controllers/iniciotutor_controller.rb class IniciotutorController < ApplicationController layout 'ly_inicio_tutor' def index session[:tutor] if session[:usuario_id] && session[:tutor] session[:adecuacion_id] = nil session[:plan_id] = nil session[:instructorName] = nil @nombre = session[:nombre_usuario] if not @nombre print "NO HAY USUARIO" end @notificaciones1= [] @notificaciones = Notificacion.where(tutor_id: session[:usuario_id]).all @notificaciones.each do |notificaciones| if notificaciones.actual == 1 #Caso de notificaciones del tutor @notificaciones1.push(notificaciones) end end else redirect_to controller:"forminst", action: "index" end end def logout reset_session redirect_to controller: "forminst", action: "index" end def destroyNotifications @post = Notificacion.find(params[:id]) respond_to do |format| if @post.destroy format.html { redirect_to :back } else flash[:notice] = "Post failed to delete." format.html { redirect_to :back } end end end def planformacions if session[:usuario_id] && session[:tutor] session[:adecuacion_id] = nil @persona = Persona.where(usuario_id: session[:usuario_id]).take @planformacions = Planformacion.where(tutor_id: session[:usuario_id]).order(fecha_modificacion: :desc) @nombreinstructor = [] @status = [] @cpenviado = [] @planformacions.each do |plan| @person= Persona.where(usuario_id: plan.instructor_id).take @nombreinstructor.push(@tutor = @person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @person.apellidos.to_s.split.map(&:capitalize).join(' ')) adecuacion = Adecuacion.where(planformacion_id: plan.id).take @est= EstatusAdecuacion.where(adecuacion_id: adecuacion.id, actual: 1).take if [email protected]? if @est.estatus_id == 1 @status.push("[" + @est.fecha.to_s + "]: APROBADO POR CONSEJO DE FACULTAD") @cpenviado.push(1) elsif @est.estatus_id == 2 @status.push("[" + @est.fecha.to_s + "]: ENVIADO A CONSEJO Tร‰CNICO") @cpenviado.push(1) elsif @est.estatus_id == 3 @status.push("[" + @est.fecha.to_s + "]: ENVIADO A COMISIร“N DE INVESTIGACIร“N") @cpenviado.push(1) elsif @est.estatus_id == 4 @status.push("[" + @est.fecha.to_s + "]: ENVIADO A CONSEJO DE FACULTAD") @cpenviado.push(1) elsif @est.estatus_id == 5 @status.push("[" + @est.fecha.to_s + "]: APROBADO CON OBSERVACIONES POR CONSEJO DE FACULTAD") @cpenviado.push(0) elsif @est.estatus_id == 6 @status.push("[" + @est.fecha.to_s + "]: GUARDADO") @cpenviado.push(0) elsif @est.estatus_id == 7 @status.push("[" + @est.fecha.to_s + "]: EN REVISIร“N MENOR POR COMISIร“N DE INVESTIGACIร“N") @cpenviado.push(1) elsif @est.estatus_id == 8 @status.push("[" + @est.fecha.to_s + "]: ENVIADO A CONSEJO DE ESCUELA") @cpenviado.push(1) elsif @est.estatus_id == 9 @status.push("[" + @est.fecha.to_s + "]: RECHAZADO POR CONSEJO DE FACULTAD") @cpenviado.push(1) end else flash.now[:danger] = "Ha ocurrido un error, adecuaciones sin estatus de envio" end end @nombre = session[:nombre_usuario] if not @nombre print "NO HAY USUARIO" end else redirect_to controller:"forminst", action: "index" end end def prorroga if session[:usuario_id] && session[:tutor] session[:adecuacion_id] = nil @persona = Persona.where(usuario_id: session[:usuario_id]).take @nombre = session[:nombre_usuario] @planformacion = session[:plan_id] if not @planformacion end @instructorName = session[:instructorName] if not @instructorName end if not @nombre print "NO HAY USUARIO" end else redirect_to controller:"forminst", action: "index" end end def ver_detalles_adecuacion if session[:usuario_id] && session[:tutor] if(!session[:plan_id].blank? || !params[:plan_id].blank?) if !params[:plan_id].blank? session[:plan_id] = params[:plan_id] end if params[:editar] == 'no' session[:editar]= false else session[:editar]= true end @tutoresAnteriores = Instructortutor.where(instructor_id: session[:usuario_id], actual: 0) @nombre = session[:nombre_usuario] @plan= Planformacion.find(session[:plan_id]) if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@plan.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end @inst = Persona.where(usuario_id: @plan.instructor_id).take @instructorName = @inst.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @inst.apellidos.to_s.split.map(&:capitalize).join(' ') session[:instructorName] = @instructorName @instructorName = session[:instructorName] @userentidad= Usuarioentidad.where(usuario_id: @plan.instructor_id).take @escuela= Escuela.where(id: @userentidad.escuela_id).take @persona= Persona.where(usuario_id: @plan.instructor_id).take @usuario= Usuario.find(@plan.instructor_id) @cpTutor= Persona.where(usuario_id: @plan.tutor_id).take @cpTutorEmail= Usuario.find(@plan.tutor_id).email semestre= params[:semestre].to_i if !params[:adecuacion_id].blank? session[:adecuacion_id]= params[:adecuacion_id] @adecuacion= Adecuacion.find(session[:adecuacion_id]) else @adecuacion= Adecuacion.where(planformacion_id: session[:plan_id]).take session[:adecuacion_id]= @adecuacion.id end @plan= Planformacion.find(session[:plan_id]) @userentidad= Usuarioentidad.where(usuario_id: @plan.instructor_id).take if @userentidad.escuela_id == nil @userentidad.escuela_id=12 @userentidad.save @escuela= Escuela.where(id: @userentidad.escuela_id).take else @escuela= Escuela.where(id: @userentidad.escuela_id).take end @instructor= Persona.where(usuario_id: @plan.instructor_id).take @bool_enviado = 0 estatus_adecuacion = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if (estatus_adecuacion.estatus_id != 6 && estatus_adecuacion.estatus_id != 5 && estatus_adecuacion.estatus_id != 9) @bool_enviado = 1 end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def guardar_primera_parte if session[:usuario_id] && session[:tutor] #Guardar primera parte del informe if !params[:firtsPart].blank? #Presentacion if params[:presentacionId].blank? cpActividad = Actividad.new cpActividad.tipo_actividad_id = 9 cpActividad.actividad = params[:presentacion] cpActividad.save cpActividadAdecuacion = AdecuacionActividad.new cpActividadAdecuacion.adecuacion_id = session[:adecuacion_id] cpActividadAdecuacion.actividad_id = cpActividad.id cpActividadAdecuacion.semestre = 0 cpActividadAdecuacion.save end # Descripciรณn del Perfil del Ganador del concurso if params[:descripcionId].blank? cpActividad = Actividad.new cpActividad.tipo_actividad_id = 8 cpActividad.actividad = params[:descripcion] cpActividad.save cpActividadAdecuacion = AdecuacionActividad.new cpActividadAdecuacion.adecuacion_id = session[:adecuacion_id] cpActividadAdecuacion.actividad_id = cpActividad.id cpActividadAdecuacion.semestre = 0 cpActividadAdecuacion.save end # Docencia if params[:docenciaId].blank? cpActividad = Actividad.new cpActividad.tipo_actividad_id = 1 cpActividad.actividad = params[:docencia] cpActividad.save cpActividadAdecuacion = AdecuacionActividad.new cpActividadAdecuacion.adecuacion_id = session[:adecuacion_id] cpActividadAdecuacion.actividad_id = cpActividad.id cpActividadAdecuacion.semestre = 0 cpActividadAdecuacion.save end # Investigacion if params[:investigacionId].blank? cpActividad = Actividad.new cpActividad.tipo_actividad_id = 2 cpActividad.actividad = params[:investigacion] cpActividad.save cpActividadAdecuacion = AdecuacionActividad.new cpActividadAdecuacion.adecuacion_id = session[:adecuacion_id] cpActividadAdecuacion.actividad_id = cpActividad.id cpActividadAdecuacion.semestre = 0 cpActividadAdecuacion.save end # Formaciรณn y capacitaciรณn profesional if params[:formacionId].blank? cpActividad = Actividad.new cpActividad.tipo_actividad_id = 4 cpActividad.actividad = params[:formacion] cpActividad.save cpActividadAdecuacion = AdecuacionActividad.new cpActividadAdecuacion.adecuacion_id = session[:adecuacion_id] cpActividadAdecuacion.actividad_id = cpActividad.id cpActividadAdecuacion.semestre = 0 cpActividadAdecuacion.save end # Extension if params[:extensionId].blank? cpActividad = Actividad.new cpActividad.tipo_actividad_id = 3 cpActividad.actividad = params[:extension] cpActividad.save cpActividadAdecuacion = AdecuacionActividad.new cpActividadAdecuacion.adecuacion_id = session[:adecuacion_id] cpActividadAdecuacion.actividad_id = cpActividad.id cpActividadAdecuacion.semestre = 0 cpActividadAdecuacion.save end #Editar j=0 i=:edit.to_s+j.to_s @edit= params[i].to_s while j < params[:cant_edit].to_i if @edit == "presentacion" if !params[:presentacionId].blank? cpActividad = Actividad.find(params[:presentacionId]) cpActividad.actividad = params[:presentacion] cpActividad.save end elsif @edit == "descripcion" if !params[:presentacionId].blank? cpActividad = Actividad.find(params[:descripcionId]) cpActividad.actividad = params[:descripcion] cpActividad.save end elsif @edit == "docencia" if !params[:presentacionId].blank? cpActividad = Actividad.find(params[:docenciaId]) cpActividad.actividad = params[:docencia] cpActividad.save end elsif @edit == "investigacion" if !params[:presentacionId].blank? cpActividad = Actividad.find(params[:investigacionId]) cpActividad.actividad = params[:investigacion] cpActividad.save end elsif @edit == "formacion" if !params[:presentacionId].blank? cpActividad = Actividad.find(params[:formacionId]) cpActividad.actividad = params[:formacion] cpActividad.save end elsif @edit == "extension" if !params[:presentacionId].blank? cpActividad = Actividad.find(params[:extensionId]) cpActividad.actividad = params[:extension] cpActividad.save end end j+=1 i=:edit.to_s+j.to_s @edit= params[i].to_s end end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion2 if session[:usuario_id] && session[:tutor] if(!session[:plan_id].blank?) if params[:plan_id] @planformacion = Planformacion.find(params[:plan_id]) session[:plan_id] = @planformacion.id @inst = Persona.where(usuario_id: @planformacion.instructor_id).take @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take session[:editar]= true session[:adecuacion_id]= @adecuacion.id else @planformacion = Planformacion.find(session[:plan_id]) end if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@planformacion.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take if params[:editar] == 'no' session[:editar]= false end @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if !session[:editar] && (@est.estatus_id == 6 || @est.estatus_id == 5) flash.now[:info]= "Para editar la Adecuaciรณn debe seleccionar Modificar Adecuaciรณn" end @adecuaciones = Adecuacion.where(planformacion_id: session[:plan_id]) @iddoc= 'id_docencia' @docencia='docencia' @desc='descripcion' @pres='presentacion' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @plan= Planformacion.find(session[:plan_id]) @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observacionesExtras= [] @j=0 @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) elsif tipo==8 @[email protected] @[email protected] elsif tipo==9 @[email protected] @[email protected] end end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0).all @actividadesa.each do |actade| @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @observacionesExtras[actade.id]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras[actade.id]="no" else @observacionesExtras[actade.id]="si" end end end @bool_enviado = 0 estatus_adecuacion = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if (estatus_adecuacion.estatus_id != 6 && estatus_adecuacion.estatus_id != 5 && estatus_adecuacion.estatus_id != 9) @bool_enviado = 1 end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion3 if session[:usuario_id] && session[:tutor] if(!session[:plan_id].blank?) if params[:plan_id] @planformacion = Planformacion.find(params[:plan_id]) session[:editar]= true session[:plan_id] = @planformacion.id @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take session[:adecuacion_id]= @adecuacion.id else @planformacion = Planformacion.find(session[:plan_id]) end if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@planformacion.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take if params[:editar] == 'no' session[:editar]= false end @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if !session[:editar] && (@est.estatus_id == 6 || @est.estatus_id == 5) flash.now[:info]= "Para editar la Adecuaciรณn debe seleccionar Modificar Adecuaciรณn" end @adecuaciones = Adecuacion.where(planformacion_id: session[:plan_id]) @iddoc= 'id_docencia' @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @plan= Planformacion.find(session[:plan_id]) @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observacionesExtras= [] @j=0 @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) end end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividadesa.each do |actade| @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @observacionesExtras[actade.id]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras[actade.id]="no" else @observacionesExtras[actade.id]="si" end end end @bool_enviado = 0 estatus_adecuacion = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if (estatus_adecuacion.estatus_id != 6 && estatus_adecuacion.estatus_id != 5 && estatus_adecuacion.estatus_id != 9) @bool_enviado = 1 end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion4 if session[:usuario_id] && session[:tutor] if(!session[:plan_id].blank?) @iddoc= 'id_docencia' @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if !session[:editar] && (@est.estatus_id == 6 || @est.estatus_id == 5) flash.now[:info]= "Para editar la Adecuaciรณn debe seleccionar Modificar Adecuaciรณn" end @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @plan= Planformacion.find(session[:plan_id]) @planformacion = Planformacion.find(session[:plan_id]) if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@planformacion.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observacionesExtras= [] @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) end end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @actividadesa.each do |actade| @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @observacionesExtras[actade.id]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras[actade.id]="no" else @observacionesExtras[actade.id]="si" end end end @bool_enviado = 0 estatus_adecuacion = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if (estatus_adecuacion.estatus_id != 6 && estatus_adecuacion.estatus_id != 5 && estatus_adecuacion.estatus_id != 9) @bool_enviado = 1 end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion5 if session[:usuario_id] && session[:tutor] if(!session[:plan_id].blank?) @iddoc= 'id_docencia' @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @plan= Planformacion.find(session[:plan_id]) @planformacion = Planformacion.find(session[:plan_id]) if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@planformacion.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observacionesExtras= [] @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if !session[:editar] && (@est.estatus_id == 6 || @est.estatus_id == 5) flash.now[:info]= "Para editar la Adecuaciรณn debe seleccionar Modificar Adecuaciรณn" end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all a= false b= false c= false d= false e= false @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) a = true elsif tipo==2 @actividadesainv.push(@act) b = true elsif tipo==3 @actividadesaext.push(@act) c = true elsif tipo==4 @actividadesafor.push(@act) d = true elsif tipo==5 @actividadesaotr.push(@act) e = true end end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all @actividadesa.each do |actade| @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @observacionesExtras[actade.id]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras[actade.id]="no" else @observacionesExtras[actade.id]="si" end end end if (a == true && b== true && c== true && d== true && e== true) else end @bool_enviado = 0 estatus_adecuacion = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if (estatus_adecuacion.estatus_id != 6 && estatus_adecuacion.estatus_id != 5 && estatus_adecuacion.estatus_id != 9) @bool_enviado = 1 end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion6 if session[:usuario_id] && session[:tutor] if(!session[:plan_id].blank?) @iddoc= 'id_docencia' @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @plan= Planformacion.find(session[:plan_id]) @planformacion = Planformacion.find(session[:plan_id]) if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@planformacion.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observacionesExtras= [] @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if !session[:editar] && (@est.estatus_id == 6 || @est.estatus_id == 5) flash.now[:info]= "Para editar la Adecuaciรณn debe seleccionar Modificar Adecuaciรณn" end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all if @actividadesa.blank? end @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) end end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all @actividadesa.each do |actade| @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @observacionesExtras[actade.id]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras[actade.id]="no" else @observacionesExtras[actade.id]="si" end end end @bool_enviado = 0 estatus_adecuacion = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if (estatus_adecuacion.estatus_id != 6 && estatus_adecuacion.estatus_id != 5 ) @bool_enviado = 1 end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def detalles_adecuacion7 if session[:usuario_id] && session[:tutor] if(!session[:plan_id].blank?) @iddoc= 'id_docencia' @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] @plan= Planformacion.find(session[:plan_id]) @planformacion = Planformacion.find(session[:plan_id]) if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@planformacion.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] @observacionesExtras= [] @adecuacion = Adecuacion.where(planformacion_id: session[:plan_id]).take @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if !session[:editar] && (@est.estatus_id == 6 || @est.estatus_id == 5) flash.now[:info]= "Para editar la Adecuaciรณn debe seleccionar Modificar Adecuaciรณn" end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 5).all if @actividadesa.blank? end @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividadesadoc.push(@act) elsif tipo==2 @actividadesainv.push(@act) elsif tipo==3 @actividadesaext.push(@act) elsif tipo==4 @actividadesafor.push(@act) elsif tipo==5 @actividadesaotr.push(@act) end end @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 5).all @actividadesa.each do |actade| @cpObs= ObservacionActividadAdecuacion.where(adecuacionactividad_id: actade.id).all if @cpObs.blank? @observacionesExtras[actade.id]="no" else cpBool = 0 @cpObs.each do |probar| if !probar.observaciones.blank? cpBool = 1 end end if cpBool == 0 @observacionesExtras[actade.id]="no" else @observacionesExtras[actade.id]="si" end end end @bool_enviado = 0 estatus_adecuacion = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if (estatus_adecuacion.estatus_id != 6 && estatus_adecuacion.estatus_id != 5 ) @bool_enviado = 1 end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def crear_actividad(tipo_id, descripcion, semestre, adecuacion_id) cpActividad = Actividad.new cpActividad.tipo_actividad_id = tipo_id cpActividad.actividad = descripcion cpActividad.save cpActividadAdecuacion = AdecuacionActividad.new cpActividadAdecuacion.adecuacion_id = adecuacion_id cpActividadAdecuacion.actividad_id = cpActividad.id cpActividadAdecuacion.semestre = semestre cpActividadAdecuacion.save end def guardar_adecuacion if session[:usuario_id] && session[:tutor] if(!session[:plan_id].blank? || !params[:plan_id].blank?) if !params[:plan_id].blank? session[:plan_id] = params[:plan_id] end if params[:editar] == 'no' session[:editar]= false else session[:editar]= true end @tutoresAnteriores = Instructortutor.where(instructor_id: session[:usuario_id], actual: 0) @nombre = session[:nombre_usuario] @plan= Planformacion.find(session[:plan_id]) if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@plan.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end @inst = Persona.where(usuario_id: @plan.instructor_id).take @instructorName = @inst.nombres.to_s.split.map(&:capitalize).join(' ') + " " + @inst.apellidos.to_s.split.map(&:capitalize).join(' ') session[:instructorName] = @instructorName @instructorName = session[:instructorName] @userentidad= Usuarioentidad.where(usuario_id: @plan.instructor_id).take @escuela= Escuela.where(id: @userentidad.escuela_id).take @persona= Persona.where(usuario_id: @plan.instructor_id).take @usuario= Usuario.find(@plan.instructor_id) @cpTutor= Persona.where(usuario_id: @plan.tutor_id).take @cpTutorEmail= Usuario.find(@plan.tutor_id).email semestre= params[:semestre].to_i if !params[:adecuacion_id].blank? session[:adecuacion_id]= params[:adecuacion_id] @adecuacion= Adecuacion.find(session[:adecuacion_id]) else @adecuacion= Adecuacion.where(planformacion_id: session[:plan_id]).take session[:adecuacion_id]= @adecuacion.id end @userentidad= Usuarioentidad.where(usuario_id: @plan.instructor_id).take if @userentidad.escuela_id == nil @userentidad.escuela_id=12 @userentidad.save @escuela= Escuela.where(id: @userentidad.escuela_id).take else @escuela= Escuela.where(id: @userentidad.escuela_id).take end @instructor= Persona.where(usuario_id: @plan.instructor_id).take @modifique=false @cant_delete= params[:cant_delete] @cant_edit= params[:cant_edit] @cant_doc= params[:cant_docencia] @cant_obli= params[:cant_obligatoria] @cant_inv= params[:cant_investigacion] @cant_for= params[:cant_formacion] @cant_ext= params[:cant_extension] @cant_otr= params[:cant_otra] @nombre = session[:nombre_usuario] semestre= params[:semestre].to_i @actividadesadoc= [] @actividadesainv= [] @actividadesaext= [] @actividadesafor= [] @actividadesaotr= [] j=0 if params[:primera_parte] == "si" puts "HELLOOOOOOOOOOOOOOOOOOOOOOO" #Presentacion if params[:presentacionId].blank? puts "hello" crear_actividad(9, params[:presentacion], 0, session[:adecuacion_id]) end # Descripciรณn del Perfil del Ganador del concurso if params[:descripcionId].blank? crear_actividad(8, params[:descripcion], 0, session[:adecuacion_id]) end j=0 @modifique= true i=:edit.to_s+j.to_s @edit= params[i].to_s if @edit == "presentacion" || @edit == "descripcion" while j < params[:cant_edit].to_i if @edit == "presentacion" if !params[:presentacionId].blank? cpActividad = Actividad.find(params[:presentacionId]) cpActividad.actividad = params[:presentacion] cpActividad.save end elsif @edit == "descripcion" if !params[:presentacionId].blank? cpActividad = Actividad.find(params[:descripcionId]) cpActividad.actividad = params[:descripcion] cpActividad.save end end j+=1 i=:edit.to_s+j.to_s @edit= params[i].to_s end end end if @cant_edit.to_i > 0 j=0 @modifique= true i=:edit.to_s+j.to_s @edit= params[i].to_s puts "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" while j < @cant_edit.to_i @modifique= true i=:edit.to_s+j.to_s @edit= params[i] if @edit != "presentacion" && @edit != "descripcion" @act= Actividad.find(@edit) tipo= @act.tipo_actividad_id if tipo==1 m=:[email protected]_s text= params[m] elsif tipo==2 m=:[email protected]_s text= params[m] elsif tipo==3 m=:[email protected]_s text= params[m] elsif tipo==4 m=:[email protected]_s text= params[m] elsif tipo==5 m=:[email protected]_s text= params[m] elsif tipo==7 m=:[email protected]_s text= params[m] end @act.actividad= text @adecuacion.fecha_modificacion = Time.now @plan.fecha_modificacion = Time.now @plan.save @adecuacion.save @act.save end j= j+1 i=:edit.to_s+j.to_s @edit= params[i].to_i end end if @cant_delete.to_i > 0 @modifique= true j= 0 i=:delete.to_s+j.to_s; @delete = params[i].to_i while j < @cant_delete.to_i AdecuacionActividad.where(actividad_id: @delete).destroy_all Actividad.find(@delete).destroy j = j + 1 i=:delete.to_s+j.to_s; @delete = params[i] end end j=0 i=:nuevadoc.to_s+j.to_s @docencias = params[i] while j < @cant_doc.to_i @modifique= true if @docencias!=nil && @docencias!="" a = Actividad.new a.tipo_actividad_id = 1 a.actividad = @docencias a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion.id adac.actividad_id = a.id adac.semestre = semestre @plan.fecha_modificacion = Time.now @plan.save @adecuacion.fecha_modificacion = Time.now @adecuacion.save adac.save end j = j + 1 i=:nuevadoc.to_s+j.to_s; @docencias = params[i] end j=0 i=:nuevaobli.to_s+j.to_s @obliga = params[i] #obligatorias while j < @cant_obli.to_i @modifique= true if @obliga!=nil && @obliga!="" a = Actividad.new a.tipo_actividad_id = 7 a.actividad = @obliga a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion.id adac.actividad_id = a.id adac.semestre = semestre @plan.fecha_modificacion = Time.now @plan.save @adecuacion.fecha_modificacion = Time.now @adecuacion.save adac.save end j = j + 1 i=:nuevaobli.to_s+j.to_s; @obliga = params[i] end j=0 i=:nuevainv.to_s+j.to_s @invest = params[i] while j < @cant_inv.to_i @modifique= true if @invest!=nil && @invest!="" a = Actividad.new a.tipo_actividad_id = 2 a.actividad = @invest a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion.id adac.actividad_id = a.id adac.semestre = semestre @plan.fecha_modificacion = Time.now @plan.save @adecuacion.fecha_modificacion = Time.now @adecuacion.save adac.save end j = j + 1 i=:nuevainv.to_s+j.to_s; @invest = params[i] end j=0 i=:nuevafor.to_s+j.to_s @formacion = params[i] while j < @cant_for.to_i @modifique= true if @formacion!=nil && @formacion!="" a = Actividad.new a.tipo_actividad_id = 4 a.actividad = @formacion a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion.id adac.actividad_id = a.id adac.semestre = semestre @plan.fecha_modificacion = Time.now @plan.save @adecuacion.fecha_modificacion = Time.now @adecuacion.save adac.save end j = j + 1 i=:nuevafor.to_s+j.to_s; @formacion = params[i] end j=0 i=:nuevaext.to_s+j.to_s @extension = params[i] while j < @cant_ext.to_i @modifique= true if @extension!=nil && @extension!="" a = Actividad.new a.tipo_actividad_id = 3 a.actividad = @extension a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion.id adac.actividad_id = a.id adac.semestre = semestre @plan.fecha_modificacion = Time.now @plan.save @adecuacion.fecha_modificacion = Time.now @adecuacion.save adac.save end j = j + 1 i=:nuevaext.to_s+j.to_s; @extension = params[i] end j=0 i=:nuevaotr.to_s+j.to_s @otra = params[i] while j < @cant_otr.to_i @modifique= true if @otra!=nil && @otra!="" a = Actividad.new a.tipo_actividad_id = 5 a.actividad = @otra a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion.id adac.actividad_id = a.id adac.semestre = semestre @plan.fecha_modificacion = Time.now @plan.save @adecuacion.fecha_modificacion = Time.now @adecuacion.save adac.save end j = j + 1 i=:nuevaotr.to_s+j.to_s; @otra = params[i] end if @modifique == true if semestre == 1 flash[:success]= "La adecuaciรณn fue modificada y guardada correctamente" redirect_to controller:"iniciotutor", action: "detalles_adecuacion3" elsif semestre == 2 flash[:success]= "La adecuaciรณn fue modificada y guardada correctamente" redirect_to controller:"iniciotutor", action: "detalles_adecuacion4" elsif semestre == 3 flash[:success]= "La adecuaciรณn fue modificada y guardada correctamente" redirect_to controller:"iniciotutor", action: "detalles_adecuacion5" elsif semestre == 4 flash[:success]= "La adecuaciรณn fue modificada y guardada correctamente" redirect_to controller:"iniciotutor", action: "detalles_adecuacion6" elsif semestre == 5 flash[:success]= "La adecuaciรณn fue modificada y guardada correctamente" redirect_to controller:"iniciotutor", action: "detalles_adecuacion7" elsif semestre == 0 flash[:success]= "La adecuaciรณn fue modificada y guardada correctamente" redirect_to controller:"iniciotutor", action: "detalles_adecuacion2" end end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def eliminar_adecuacion if session[:usuario_id] && session[:tutor] if(!session[:adecuacion_id].blank?) @adecuacion= Adecuacion.find(session[:adecuacion_id]) @est= EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if @est.estatus_id == 6 @documents = Document.where(adecuacion_id: session[:adecuacion_id]).all @actividadAde = AdecuacionActividad.where(adecuacion_id: @adecuacion.id).all @actividadAde.each do |actade| @elimi = Actividad.where(id: actade.actividad_id).take @elimi.destroy actade.destroy end @documents.each do |documents| documents.destroy end flash[:success]= "La adecuacion fue eliminada correctamente" else flash[:danger]= "No estรก permitido eliminar esta adecuaciรณn" end redirect_to controller:"iniciotutor", action: "ver_detalles_adecuacion" else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def vista_previa if session[:usuario_id] && session[:tutor] if(!session[:plan_id].blank?) @fechaActual = Date.current.to_s @plan= Planformacion.find(session[:plan_id]) if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@plan.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end @fechaConcurso = @plan.fecha_inicio @usere= Usuarioentidad.where(usuario_id: @plan.instructor_id).take @escuela= Escuela.find(@usere.escuela_id) @adecuacion= Adecuacion.where(planformacion_id: @plan.id).take @adscripcion_docencia= @plan.adscripcion_docencia @adscripcion_investigacion= @plan.adscripcion_investigacion @persona= Persona.where(usuario_id: @plan.instructor_id).take @cpinstruccion = @persona.grado_instruccion @user = Usuario.find(@plan.instructor_id) @cpTutor= Persona.where(usuario_id: @plan.tutor_id).take @cpTutorEmail= Usuario.find(@plan.tutor_id).email @bool_enviado = 0 estatus_adecuacion = EstatusAdecuacion.where(adecuacion_id: @adecuacion.id, actual: 1).take if (estatus_adecuacion.estatus_id != 6 && estatus_adecuacion.estatus_id != 5 && estatus_adecuacion.estatus_id != 9) @bool_enviado = 1 end @docencia='docencia' @investigacion= 'investigacion' @formacion= 'formacion' @extension= 'extension' @otra= 'otra' @nombre = session[:nombre_usuario] @instructorName = session[:instructorName] actividades = AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0) if !actividades.blank? actividades.each do |actividadAde| actividad = Actividad.find(actividadAde.actividad_id) if actividad.tipo_actividad_id == 9 @presentacion = actividad.actividad elsif actividad.tipo_actividad_id == 8 @descripcion = actividad.actividad end end else @presentacion = " " @descripcion = " " end @actividades0doc= [] @actividades0inv= [] @actividades0ext= [] @actividades0for= [] @actividades0otr= [] @actividades0= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0).all @actividades0.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades0doc.push(@act) elsif tipo==2 @actividades0inv.push(@act) elsif tipo==3 @actividades0ext.push(@act) elsif tipo==4 @actividades0for.push(@act) elsif tipo==5 @actividades0otr.push(@act) end end @actividades1doc= [] @actividades1inv= [] @actividades1ext= [] @actividades1for= [] @actividades1otr= [] @actividades1= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividades1.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades1doc.push(@act) elsif tipo==2 @actividades1inv.push(@act) elsif tipo==3 @actividades1ext.push(@act) elsif tipo==4 @actividades1for.push(@act) elsif tipo==5 @actividades1otr.push(@act) end end @actividades2doc= [] @actividades2inv= [] @actividades2ext= [] @actividades2for= [] @actividades2otr= [] @actividades2= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @actividades2.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades2doc.push(@act) elsif tipo==2 @actividades2inv.push(@act) elsif tipo==3 @actividades2ext.push(@act) elsif tipo==4 @actividades2for.push(@act) elsif tipo==5 @actividades2otr.push(@act) end end @actividades3doc= [] @actividades3inv= [] @actividades3ext= [] @actividades3for= [] @actividades3otr= [] @actividades3= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all @actividades3.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades3doc.push(@act) elsif tipo==2 @actividades3inv.push(@act) elsif tipo==3 @actividades3ext.push(@act) elsif tipo==4 @actividades3for.push(@act) elsif tipo==5 @actividades3otr.push(@act) end end @actividades4doc= [] @actividades4inv= [] @actividades4ext= [] @actividades4for= [] @actividades4otr= [] @actividades4= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all @actividades4.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @actividades4doc.push(@act) elsif tipo==2 @actividades4inv.push(@act) elsif tipo==3 @actividades4ext.push(@act) elsif tipo==4 @actividades4for.push(@act) elsif tipo==5 @actividades4otr.push(@act) end end @actividades5doc= [] @actividades5inv= [] @actividades5ext= [] @actividades5for= [] @actividades5otr= [] @actividades5= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 5).all @actividades5.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 puts "soy una actividad de docencia" puts @act.actividad @actividades5doc.push(@act) elsif tipo==2 puts "soy una actividad de investigacion" puts @act.actividad @actividades5inv.push(@act) elsif tipo==3 puts "soy una actividad de extension" puts @act.actividad @actividades5ext.push(@act) elsif tipo==4 puts "soy una actividad de formacion" puts @act.actividad @actividades5for.push(@act) end end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def cambiar_estatusA if session[:usuario_id] && session[:tutor] if(!session[:plan_id].blank?) @adecuacion_id = params[:adecuacion_id].to_i @actividades1doc= [] @actividades1inv= [] @actividades1ext= [] @actividades1for= [] @actividades1otr= [] g=0; cambio_act = EstatusAdecuacion.where(adecuacion_id: @adecuacion_id, actual: 1).take if (cambio_act.estatus_id != 6 && cambio_act.estatus_id != 5) flash[:info]="Esta adecuaciรณn ya habia sido enviada" redirect_to controller:"iniciotutor", action: "planformacions" else for semestreN in 1..4 @actividades1= AdecuacionActividad.where(adecuacion_id: @adecuacion_id, semestre: semestreN).all if @actividades1.blank? g = g + 1 else a= false b= false c= false d= false e= false @actividades1.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 a = true elsif tipo==2 b = true elsif tipo==3 c = true elsif tipo==4 d = true elsif tipo==5 e = true end end if (a && b && c && d && e) #Si todas las actividades de el semestre semestreN tienen algo escrito elsif ( a && b && c && d && !e) #Si todas las actividades de el semestre semestreN tienen algo escrito menos "otras actividades" que es opcional a = Actividad.new a.tipo_actividad_id = 5 a.actividad = "Ninguna" a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion_id adac.actividad_id = a.id adac.semestre = semestreN adac.save else g = g + 1 end end end aob = 0 a= false b= false c= false d= false e= false @actividades5= AdecuacionActividad.where(adecuacion_id: @adecuacion_id, semestre: 5).all @actividades5.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 a = true elsif tipo==2 b = true elsif tipo==3 c = true elsif tipo==4 d = true end end if (a && b && c && d) elsif ( a && c ) if(!b) a = Actividad.new a.tipo_actividad_id = 2 a.actividad = "Ninguna" a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion_id adac.actividad_id = a.id adac.semestre = 5 adac.save end if(!d) a = Actividad.new a.tipo_actividad_id = 4 a.actividad = "Ninguna" a.save adac = AdecuacionActividad.new adac.adecuacion_id = @adecuacion_id adac.actividad_id = a.id adac.semestre = 5 adac.save end else g = g + 1 end are1 = 0 are2 = 0 are3 = 0 are4 = 0 are5 = 0 are6 = 0 are7 = 0 @actividades0= AdecuacionActividad.where(adecuacion_id: @adecuacion_id, semestre: 0).all @actividades0.each do |cpActividadAdecuacion| cpActividad = Actividad.find(cpActividadAdecuacion.actividad_id) if cpActividad.tipo_actividad_id == 9 && !cpActividad.actividad.blank? are1+=1 end if cpActividad.tipo_actividad_id == 8 && !cpActividad.actividad.blank? are2+=1 end if cpActividad.tipo_actividad_id == 1 && !cpActividad.actividad.blank? are3+=1 end if cpActividad.tipo_actividad_id == 2 && !cpActividad.actividad.blank? are4+=1 end if cpActividad.tipo_actividad_id == 3 && !cpActividad.actividad.blank? are5+=1 end if cpActividad.tipo_actividad_id == 4 && !cpActividad.actividad.blank? are6+=1 end if cpActividad.tipo_actividad_id == 5 && !cpActividad.actividad.blank? are7+=1 end end if are1 == 0 || are2 == 0 || are3 == 0 || are3 == 0 || are4 == 0 || are5 == 0 || are6 == 0 || are7 == 0 g=1 end if (g != 0) if are1 == 0 || are2 == 0 || are3 == 0 || are3 == 0 || are4 == 0 || are5 == 0 || are6 == 0 if aob == 0 flash[:danger]="No puede enviar la adecuaciรณn sin haber llenado todos los semestres" else flash[:danger]="No puede enviar la adecuaciรณn sin tener al menos una actividad obligatoria de docencia e investigaciรณn" end else flash[:danger]="No puede enviar la adecuaciรณn sin estar terminada" end redirect_to controller:"iniciotutor", action: "detalles_adecuacion3" else plan = Planformacion.find(session[:plan_id]) cambio_act.actual = 0 cambio_act.save cambio_est = EstatusAdecuacion.new cambio_est.adecuacion_id = @adecuacion_id cambio_est.fecha = Time.now notific = Notificacion.new notific.instructor_id = plan.instructor_id notific.tutor_id = session[:usuario_id] notific.adecuacion_id = session[:adecuacion_id] notific.informe_id = nil notific.actual = 1 person = Persona.where(usuario_id: plan.instructor_id).take notificacionfecha = Date.current.to_s if (cambio_act.estatus_id == 6) notific.mensaje = "[" + notificacionfecha + "] La adecuaciรณn de "+ person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " se ha enviado a comisiรณn de investigaciรณn." elsif (cambio_act.estatus_id == 5) notific.mensaje = "[" + notificacionfecha + "] La adecuaciรณn de "+ person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + " se ha enviado a Consejo de Facultad para ser revisado nuevamente." end notific.save notific2 = Notificacion.new notific2.instructor_id = plan.instructor_id notific2.tutor_id = session[:usuario_id] notific2.adecuacion_id = session[:adecuacion_id] notific2.informe_id = nil notific2.actual = 2 if (cambio_act.estatus_id == 6) notific2.mensaje = "[" + notificacionfecha + "] Su adecuaciรณn se ha enviado a comisiรณn de investigaciรณn." elsif (cambio_act.estatus_id == 5) notific2.mensaje = "[" + notificacionfecha + "] Su adecuaciรณn se ha enviado a Consejo de Facultad para ser revisado nuevamente" end notific2.save notific3 = Notificacion.new notific3.instructor_id = plan.instructor_id notific3.tutor_id = session[:usuario_id] notific3.adecuacion_id = session[:adecuacion_id] notific3.informe_id = nil userr= Usuario.where(id: session[:usuario_id]).take usernoti =Usuarioentidad.where(usuario_id: userr.id).take if (cambio_act.estatus_id == 6) if(usernoti.escuela_id == 1) notific3.departamento_id = usernoti.departamento_id end notific3.actual = 3 #Comisiรณn de investigaciรณn notific3.mensaje = "[" + notificacionfecha + "] Se ha recibido una nueva Adecuaciรณn: "+ person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + ", favor revisar y enviar a la siguiente entidad." elsif (cambio_act.estatus_id == 5) notific3.actual = 5 #Enviado a Consejo de Facultad notific3.mensaje = "[" + notificacionfecha + "] Se ha recibido una nueva Adecuaciรณn: "+ person.nombres.to_s.split.map(&:capitalize).join(' ') + " " + person.apellidos.to_s.split.map(&:capitalize).join(' ') + ", favor revisar." end notific3.save notific.save respaldos = [] respaldos = Respaldo.where(adecuacion_id: @adecuacion_id, informe_id: nil).all numeroDeVersion = respaldos.size + 1 nombre = generar_pdf() nameofthefile = "#{Rails.root}/tmp/PDFs/"+nombre #nameofthefile = nombre contents = IO.binread(nameofthefile) respaldo = Respaldo.new respaldo.filename = nombre respaldo.content_type = "application/pdf" respaldo.file_contents = contents respaldo.created_at = Date.current respaldo.version = numeroDeVersion respaldo.estatus = "Enviado a Comisiรณn de Investigaciรณn" respaldo.instructor_id = plan.instructor_id respaldo.tutor_id = session[:usuario_id] respaldo.adecuacion_id = session[:adecuacion_id] respaldo.informe_id = nil respaldo.actual = 1 if (cambio_act.estatus_id == 6) cambio_est.estatus_id = 3 #Enviado a Comisiรณn de Investigaciรณn respaldo.estatus = "Enviado a Comisiรณn de Investigaciรณn" elsif (cambio_act.estatus_id == 5) cambio_est.estatus_id = 4 #Enviado a Consejo de Facultad respaldo.estatus = "Enviado a Consejo de Facultad" end respaldo.save cambio_est.actual = 1 cambio_est.save @document = Respaldo.where(id: respaldo.id).take if (cambio_act.estatus_id == 6) userr= Usuario.where(id: session[:usuario_id]).take user =Usuarioentidad.where(usuario_id: userr.id).take if(user.escuela_id == 1) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 7).take elsif(user.escuela_id == 2) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 8).take elsif(user.escuela_id == 3) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 9).take elsif(user.escuela_id == 4) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 10).take elsif(user.escuela_id == 9) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 11).take elsif(user.escuela_id == 10) uentidad = Usuarioentidad.where(escuela_id: user.escuela_id, entidad_id: 12).take end #CORREO EDITAAAAAAR linkT = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion&param1=" + plan.id.to_s + "&param2=no" linkI = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion" linkE = "http://formacion.ciens.ucv.ve/forminst?accion=mostrar adecuacion&param3=" + plan.id.to_s remitente3 = Usuario.where(id: session[:usuario_id]).take ActionCorreo.envio_adecuacion(remitente3, notific.mensaje,2,linkT,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_adecuacion(remitente2, notific2.mensaje,1,linkI,@document).deliver remitente = Usuario.where(id: uentidad.usuario_id).take ActionCorreo.envio_adecuacion(remitente, notific3.mensaje,0,linkI,@document).deliver elsif (cambio_act.estatus_id == 5) uentidad = Usuarioentidad.where(entidad_id: 13).take remitente3 = Usuario.where(id: session[:usuario_id]).take ActionCorreo.envio_adecuacion(remitente3, notific.mensaje,2, linkT,@document).deliver remitente2 = Usuario.where(id: plan.instructor_id).take ActionCorreo.envio_adecuacion(remitente2, notific2.mensaje,1, linkI,@document).deliver remitente = Usuario.where(id: uentidad.usuario_id).take ActionCorreo.envio_adecuacion(remitente, notific3.mensaje,0, linkE,@document).deliver ActionCorreo.envio_adecuacion("<EMAIL>", notific3.mensaje,0, linkE,@document).deliver end if(cambio_act.estatus_id == 5) flash[:success]="La adecuaciรณn se ha enviado a Consejo de Facultad" else flash[:success]="La adecuaciรณn se ha enviado a Comisiรณn de Investigaciรณn" end redirect_to controller:"iniciotutor", action: "planformacions" end end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def generar_pdf() # es funciรณn permite generar el documento pdf de la adecuaciรณn if(!session[:adecuacion_id].blank?) @adecuacion= Adecuacion.find(session[:adecuacion_id]) # se obtienen la informaciรณn de la adecuaciรณn seleccionada @planformacion= Planformacion.find(@adecuacion.planformacion_id) @fechaConcurso = @planformacion.fecha_inicio @id_docente= @planformacion.tutor_id # se obtiene el indicador del ususario al que corresponde la adecuaciรณn @usertutor= Usuario.find(@id_docente) # se obtiene la informaciรณn del tutor mediante la base de datos y la variable anterior @tutor= Persona.where(usuario_id: @id_docente).take @id_instructor= @planformacion.instructor_id # se toma el identificador del instructor @userinst=Usuario.find(@id_instructor) # se obtienen toda la informaciรณn del instructor @instructor= Persona.where(usuario_id: @id_instructor).take @fechaActual = Date.current.to_s @userentidad= Usuarioentidad.where(usuario_id: @planformacion.instructor_id).take if @userentidad.escuela_id == nil @userentidad.escuela_id=12 @userentidad.save @escuela= Escuela.where(id: @userentidad.escuela_id).take else @escuela= Escuela.where(id: @userentidad.escuela_id).take end @userinst2=Usuario.find(@id_docente) # se obtienen toda la informaciรณn del tutor @correot= @userinst2.user+'<EMAIL>' @correoi= @userinst.user+'@<EMAIL>' @pactv_docencia= [] @pactv_investigacion= [] @pactv_formacion= [] @pactv_extension=[] @pactv_otras=[] @sactv_docencia= [] @sactv_investigacion= [] @sactv_formacion= [] @sactv_extension=[] @sactv_otras=[] @tactv_docencia= [] @tactv_investigacion= [] @tactv_formacion= [] @tactv_extension=[] @tactv_otras=[] @cactv_docencia= [] @cactv_investigacion= [] @cactv_formacion= [] @cactv_extension=[] @cactv_otras=[] @dactv_docencia= [] @dactv_investigacion= [] @dactv_formacion= [] @dactv_extension=[] @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @pactv_docencia.push(@act) elsif tipo==2 @pactv_investigacion.push(@act) elsif tipo==3 @pactv_extension.push(@act) elsif tipo==4 @pactv_formacion.push(@act) elsif tipo==5 @pactv_otras.push(@act) end end @sactividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @sactividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @sactv_docencia.push(@act) elsif tipo==2 @sactv_investigacion.push(@act) elsif tipo==3 @sactv_extension.push(@act) elsif tipo==4 @sactv_formacion.push(@act) elsif tipo==5 @sactv_otras.push(@act) end end @tactividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all @tactividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @tactv_docencia.push(@act) elsif tipo==2 @tactv_investigacion.push(@act) elsif tipo==3 @tactv_extension.push(@act) elsif tipo==4 @tactv_formacion.push(@act) elsif tipo==5 @tactv_otras.push(@act) end end @cactividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all @cactividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @cactv_docencia.push(@act) elsif tipo==2 @cactv_investigacion.push(@act) elsif tipo==3 @cactv_extension.push(@act) elsif tipo==4 @cactv_formacion.push(@act) elsif tipo==5 @cactv_otras.push(@act) end end @cactividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 5).all @cactividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @dactv_docencia.push(@act) elsif tipo==2 @dactv_investigacion.push(@act) elsif tipo==3 @dactv_extension.push(@act) elsif tipo==4 @dactv_formacion.push(@act) end end @documents = [] @documents = Document.where(adecuacion_id: @adecuacion.id, informe_id: nil).all # se llama a la funciรณn de "pedf_adecuacion" del modelo "pdf", pasando todas las variables correspondientes respaldos = [] respaldos = Respaldo.where(adecuacion_id: @adecuacion.id, informe_id: nil).all @numeroDeVersion = respaldos.size + 1 @actividades1 = [] actividades = AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0) if !actividades.blank? actividades.each do |actividadAde| actividad = Actividad.find(actividadAde.actividad_id) @actividades1.push(actividad) end end Pdf.pdf_adecuacion(@actividades1, @planformacion, @adecuacion, @tutor, @instructor, @correoi, @correot, @escuela, @pactv_docencia, @pactv_investigacion, @pactv_extension, @pactv_formacion, @pactv_otras, @sactv_docencia, @sactv_investigacion, @sactv_extension, @sactv_formacion, @sactv_otras, @tactv_docencia, @tactv_investigacion, @tactv_extension, @tactv_formacion, @tactv_otras, @cactv_docencia, @cactv_investigacion, @cactv_extension, @cactv_formacion, @cactv_otras, @fechaActual, @fechaConcurso, @documents, @numeroDeVersion, @dactv_docencia, @dactv_investigacion, @dactv_extension, @dactv_formacion) @nombre_archivo= @instructor.ci.to_s+'-'+@fechaActual+'-adecuacionV'[email protected]_s+'.pdf' # se arma el nombre del documento act = "#{Rails.root}/tmp/PDFs" + @nombre_archivo return @nombre_archivo # se retorna el nombre del archivo else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end end def mas_observaciones3 #mas obs de actividades del informe if(!session[:adecuacion_id].blank?) @adecuacion= Adecuacion.find(session[:adecuacion_id]) @planformacion=Planformacion.find(@adecuacion.planformacion_id) if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@planformacion.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end @semestre = params[:semestre].to_i @actividad_id = params[:actividad_id].to_i aa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: @semestre, actividad_id: @actividad_id).take @observaciones = ObservacionActividadAdecuacion.where(adecuacionactividad_id: aa.id) @observaciones.each do |obs| if(obs.observaciones != "") @boolobs = 1 end end @observaciones.each do |obs| rev = Revision.find(obs.revision_id) entidad = Usuarioentidad.where(usuario_id: rev.usuario_id).take if (entidad.entidad_id >= 7 && entidad.entidad_id <= 12) #comision investigacion @obs_inv = obs.observaciones #Estatus enviado a Comisiรณn de Investigaciรณn elsif (entidad.entidad_id >= 14 && entidad.entidad_id <= 17) #Consejo tecnico @obs_consejoT = obs.observaciones elsif (entidad.entidad_id >= 1 && entidad.entidad_id <= 6) #Consejo de escuela @obs_consejoE = obs.observaciones elsif (entidad.entidad_id == 13) #Consejo de Facultad @obs_consejoF = obs.observaciones end end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end end def ver_respaldos if session[:usuario_id] && session[:tutor] if(!session[:adecuacion_id].blank?) @plan = Planformacion.where(id: session[:plan_id]).take if [email protected]? #Ver si el informe fue rachazado cpInstructor = Usuario.find(@plan.instructor_id) if (cpInstructor.activo == false) @cpBloquear = true else @cpBloquear = false end #fin end @documents = [] if !session[:informe_id].blank? @documents = Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: session[:informe_id], actual: 0).all else @documents = Respaldo.where(adecuacion_id: session[:adecuacion_id], informe_id: nil, actual: 0).all end else flash[:info]="Seleccione una adecuaciรณn" redirect_to controller:"iniciotutor", action: "planformacions" end else redirect_to controller:"forminst", action: "index" end end def show if params[:informe_id].blank? @document = Respaldo.where(adecuacion_id: params[:adecuacion_id], informe_id: nil, version: params[:version].to_i, filename: params[:namefile]).take else @document = Respaldo.where(adecuacion_id: params[:adecuacion_id], informe_id: params[:informe_id],version: params[:version].to_i, filename: params[:namefile]).take end send_data(@document.file_contents, type: @document.content_type, filename: @document.filename) end def borrar_notificaciones # if session[:usuario_id] && session[:tutor] @noti= params[:noti] notaeliminar = Notificacion.where(id: @noti ).take if notaeliminar.blank? flash[:danger] = "Ha ocurrido un error al eliminar (notificacion no existente)" else notaeliminar.destroy end redirect_to controller:"iniciotutor", action: "notificaciones" else redirect_to controller:"forminst", action: "index" end end def borrar_notificaciones1 # if session[:usuario_id] && session[:tutor] @noti= params[:noti] notaeliminar = Notificacion.where(id: @noti ).take if notaeliminar.blank? flash[:danger] = "Ha ocurrido un error al eliminar (notificaciรณn no existente)" else notaeliminar.destroy end redirect_to controller:"iniciotutor", action: "index" else redirect_to controller:"forminst", action: "index" end end def notificaciones #Ver todas las notificaciones if session[:usuario_id] && session[:tutor] @planformacions = Planformacion.where(tutor_id: session[:usuario_id]) @notificaciones1= [] @notificaciones = Notificacion.where( tutor_id: session[:usuario_id]).all @notificaciones.each do |notificaciones| if notificaciones.actual == 1 #Caso de notificaciones del tutor @notificaciones1.push(notificaciones) end end else redirect_to controller:"forminst", action: "index" end end end <file_sep>/forminst_new1/app/controllers/usuarioentidads_controller.rb class UsuarioentidadsController < ApplicationController before_action :set_usuarioentidad, only: [:show, :edit, :update, :destroy] # GET /usuarioentidads # GET /usuarioentidads.json def index @usuarioentidads = Usuarioentidad.all end # GET /usuarioentidads/1 # GET /usuarioentidads/1.json def show end # GET /usuarioentidads/new def new @usuarioentidad = Usuarioentidad.new end # GET /usuarioentidads/1/edit def edit end # POST /usuarioentidads # POST /usuarioentidads.json def create @usuarioentidad = Usuarioentidad.new(usuarioentidad_params) respond_to do |format| if @usuarioentidad.save format.html { redirect_to @usuarioentidad, notice: 'Usuarioentidad was successfully created.' } format.json { render :show, status: :created, location: @usuarioentidad } else format.html { render :new } format.json { render json: @usuarioentidad.errors, status: :unprocessable_entity } end end end # PATCH/PUT /usuarioentidads/1 # PATCH/PUT /usuarioentidads/1.json def update respond_to do |format| if @usuarioentidad.update(usuarioentidad_params) format.html { redirect_to @usuarioentidad, notice: 'Usuarioentidad was successfully updated.' } format.json { render :show, status: :ok, location: @usuarioentidad } else format.html { render :edit } format.json { render json: @usuarioentidad.errors, status: :unprocessable_entity } end end end # DELETE /usuarioentidads/1 # DELETE /usuarioentidads/1.json def destroy @usuarioentidad.destroy respond_to do |format| format.html { redirect_to usuarioentidads_url, notice: 'Usuarioentidad was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_usuarioentidad @usuarioentidad = Usuarioentidad.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def usuarioentidad_params params.require(:usuarioentidad).permit(:id, :usuarioId, :entidadesId) end end <file_sep>/forminst_new1/app/views/prorrogas/index.json.jbuilder json.array!(@prorrogas) do |prorroga| json.extract! prorroga, :id, :id, :planFormacionId json.url prorroga_url(prorroga, format: :json) end <file_sep>/forminst_new1/app/models/notificacion.rb class Notificacion < ActiveRecord::Base has_many :usuario has_one :adecuacion has_one :informe end <file_sep>/forminst_new1/app/views/documents/_document.json.jbuilder json.extract! document, :id, :filename, :content_type, :file_contents, :created_at, :updated_at, :instructor_id, :tutor_id, :adecuacion_id, :informe_id json.url document_url(document, format: :json) <file_sep>/forminst_new1/app/views/documentoplans/show.json.jbuilder json.extract! @documentoplan, :id, :id, :planFormacionId, :archivo, :created_at, :updated_at <file_sep>/forminst_new1/app/controllers/entidads_controller.rb class EntidadsController < ApplicationController before_action :set_entidad, only: [:show, :edit, :update, :destroy] # GET /entidads # GET /entidads.json def index @entidads = Entidad.all end # GET /entidads/1 # GET /entidads/1.json def show end # GET /entidads/new def new @entidad = Entidad.new end # GET /entidads/1/edit def edit end # POST /entidads # POST /entidads.json def create @entidad = Entidad.new(entidad_params) respond_to do |format| if @entidad.save format.html { redirect_to @entidad, notice: 'Entidad was successfully created.' } format.json { render :show, status: :created, location: @entidad } else format.html { render :new } format.json { render json: @entidad.errors, status: :unprocessable_entity } end end end # PATCH/PUT /entidads/1 # PATCH/PUT /entidads/1.json def update respond_to do |format| if @entidad.update(entidad_params) format.html { redirect_to @entidad, notice: 'Entidad was successfully updated.' } format.json { render :show, status: :ok, location: @entidad } else format.html { render :edit } format.json { render json: @entidad.errors, status: :unprocessable_entity } end end end # DELETE /entidads/1 # DELETE /entidads/1.json def destroy @entidad.destroy respond_to do |format| format.html { redirect_to entidads_url, notice: 'Entidad was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_entidad @entidad = Entidad.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def entidad_params params.require(:entidad).permit(:id, :nombre, :escuelaId) end end <file_sep>/forminst_new1/app/models/observacion_actividad_informe.rb class ObservacionActividadInforme < ActiveRecord::Base belongs_to :informe_actividad belongs_to :revision end <file_sep>/forminst_new1/app/views/usuarioentidads/show.json.jbuilder json.extract! @usuarioentidad, :id, :id, :usuarioId, :entidadesId, :created_at, :updated_at <file_sep>/forminst_new1/app/assets/javascripts/application.js // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require jquery-2.1.3.min //= require bootstrap //= require_tree . //= require bootstrap-datepicker //= require bootstrap-datepicker/core //= require bootstrap-datepicker/locales/bootstrap-datepicker.es.js //= require bootstrap-datepicker/locales/bootstrap-datepicker.fr.js function fecha(){ var fecha=new Date() var ano=fecha.getYear() if (ano < 1000) ano+=1900 var dia=fecha.getDay() var mes=fecha.getMonth() var diaS=fecha.getDate() if (diaS<10) diaS="0"+diaS var diassemana=new Array("Domingo","Lunes","Martes","Miรฉrcoles","Jueves","Viernes","Sabado") var meses=new Array("enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre") $('#fechamuestra').append("<h4>"+diassemana[dia]+", "+diaS+" de "+meses[mes]+" de "+ano+"</h4>") } $('#boton_enviar').click(function(e) { $(this).prop('disabled', true); $(this).addClass('disabled'); //do other stuff when a click happens });<file_sep>/forminst_new1/test/controllers/documentoplans_controller_test.rb require 'test_helper' class DocumentoplansControllerTest < ActionController::TestCase setup do @documentoplan = documentoplans(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:documentoplans) end test "should get new" do get :new assert_response :success end test "should create documentoplan" do assert_difference('Documentoplan.count') do post :create, documentoplan: { archivo: @documentoplan.archivo, id: @documentoplan.id, planFormacionId: @documentoplan.planFormacionId } end assert_redirected_to documentoplan_path(assigns(:documentoplan)) end test "should show documentoplan" do get :show, id: @documentoplan assert_response :success end test "should get edit" do get :edit, id: @documentoplan assert_response :success end test "should update documentoplan" do patch :update, id: @documentoplan, documentoplan: { archivo: @documentoplan.archivo, id: @documentoplan.id, planFormacionId: @documentoplan.planFormacionId } assert_redirected_to documentoplan_path(assigns(:documentoplan)) end test "should destroy documentoplan" do assert_difference('Documentoplan.count', -1) do delete :destroy, id: @documentoplan end assert_redirected_to documentoplans_path end end <file_sep>/forminst_new1/app/views/actividads/show.json.jbuilder json.extract! @actividad, :id, :id, :tipoActividadId, :actividad, :anulada, :created_at, :updated_at <file_sep>/forminst_new1/app/controllers/adecuacions_controller.rb class AdecuacionsController < ApplicationController def generar_pdf() # es funciรณn permite generar el documento pdf de la adecuaciรณn @adecuacion= Adecuacion.find(session[:adecuacion_id]) # se obtienen la informaciรณn de la adecuaciรณn seleccionada @planformacion= Planformacion.find(@adecuacion.planformacion_id) @fechaConcurso = @planformacion.fecha_inicio @id_docente= @planformacion.tutor_id # se obtiene el indicador del ususario al que corresponde la adecuaciรณn @usertutor= Usuario.find(@id_docente) # se obtiene la informaciรณn del tutor mediante la base de datos y la variable anterior @tutor= Persona.where(usuario_id: @id_docente).take @id_instructor= @planformacion.instructor_id # se toma el identificador del instructor @userinst=Usuario.find(@id_instructor) # se obtienen toda la informaciรณn del instructor @instructor= Persona.where(usuario_id: @id_instructor).take @fechaActual = Date.current.to_s @userentidad= Usuarioentidad.where(usuario_id: @planformacion.instructor_id).take if @userentidad.escuela_id == nil @userentidad.escuela_id=12 @userentidad.save @escuela= Escuela.where(id: @userentidad.escuela_id).take else @escuela= Escuela.where(id: @userentidad.escuela_id).take end @userinst2=Usuario.find(@id_docente) # se obtienen toda la informaciรณn del tutor @correot= @userinst2.user+'@<EMAIL>' @correoi= @userinst.user+'@<EMAIL>' @pactv_docencia= [] @pactv_investigacion= [] @pactv_formacion= [] @pactv_extension=[] @pactv_otras=[] @sactv_docencia= [] @sactv_investigacion= [] @sactv_formacion= [] @sactv_extension=[] @sactv_otras=[] @tactv_docencia= [] @tactv_investigacion= [] @tactv_formacion= [] @tactv_extension=[] @tactv_otras=[] @cactv_docencia= [] @cactv_investigacion= [] @cactv_formacion= [] @cactv_extension=[] @cactv_otras=[] @dactv_docencia= [] @dactv_investigacion= [] @dactv_formacion= [] @dactv_extension=[] @actividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 1).all @actividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @pactv_docencia.push(@act) else if tipo==2 @pactv_investigacion.push(@act) else if tipo==3 @pactv_extension.push(@act) else if tipo==4 @pactv_formacion.push(@act) else if tipo==5 @pactv_otras.push(@act) end end end end end end @sactividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 2).all @sactividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @sactv_docencia.push(@act) else if tipo==2 @sactv_investigacion.push(@act) else if tipo==3 @sactv_extension.push(@act) else if tipo==4 @sactv_formacion.push(@act) else if tipo==5 @sactv_otras.push(@act) end end end end end end @tactividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 3).all @tactividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @tactv_docencia.push(@act) else if tipo==2 @tactv_investigacion.push(@act) else if tipo==3 @tactv_extension.push(@act) else if tipo==4 @tactv_formacion.push(@act) else if tipo==5 @tactv_otras.push(@act) end end end end end end @cactividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 4).all @cactividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @cactv_docencia.push(@act) else if tipo==2 @cactv_investigacion.push(@act) else if tipo==3 @cactv_extension.push(@act) else if tipo==4 @cactv_formacion.push(@act) else if tipo==5 @cactv_otras.push(@act) end end end end end end @cactividadesa= AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 5).all @cactividadesa.each do |actade| @act= Actividad.find(actade.actividad_id) tipo= @act.tipo_actividad_id if tipo==1 @dactv_docencia.push(@act) else if tipo==2 @dactv_investigacion.push(@act) else if tipo==3 @dactv_extension.push(@act) else if tipo==4 @dactv_formacion.push(@act) end end end end end @documents = [] @documents = Document.where(adecuacion_id: @adecuacion.id, informe_id: nil).all @numeroDeVersion = nil @actividades1 = [] actividades = AdecuacionActividad.where(adecuacion_id: @adecuacion.id, semestre: 0) if !actividades.blank? actividades.each do |actividadAde| actividad = Actividad.find(actividadAde.actividad_id) @actividades1.push(actividad) end end # se llama a la funciรณn de "pedf_adecuacion" del modelo "pdf", pasando todas las variables correspondientes Pdf.pdf_adecuacion(@actividades1, @planformacion, @adecuacion, @tutor, @instructor, @correoi, @correot, @escuela, @pactv_docencia, @pactv_investigacion, @pactv_extension, @pactv_formacion, @pactv_otras, @sactv_docencia, @sactv_investigacion, @sactv_extension, @sactv_formacion, @sactv_otras, @tactv_docencia, @tactv_investigacion, @tactv_extension, @tactv_formacion, @tactv_otras, @cactv_docencia, @cactv_investigacion, @cactv_extension, @cactv_formacion, @cactv_otras, @fechaActual, @fechaConcurso, @documents, @numeroDeVersion, @dactv_docencia, @dactv_investigacion, @dactv_extension, @dactv_formacion) @nombre_archivo= @instructor.ci.to_s+'-'+@fechaActual+'-adecuacion.pdf' # se arma el nombre del documento act = "#{Rails.root}/tmp/PDFs/" + @nombre_archivo #act = @nombre_archivo #PRODUCCION send_file( act, filename: @nombre_archivo, type: "application/pdf" ) return @nombre_archivo # se retorna el nombre del archivo end #################################################################################### def descargar_pdf # esta funciรณn permite la generaciรณn y descarga del archivo PDF del documento require 'prawn' pdf = Prawn::Document.new pdf.text "Hello It's me" pdf.render_file "example.pdf" return "example.pdf" #pdf_filename = File.join(Rails.root, "example.pdf") #send_file(pdf_filename, :filename => "example.pdf", :disposition => 'inline', :type => "application/pdf") end end <file_sep>/forminst_new1/app/models/tipo_actividad.rb class TipoActividad < ActiveRecord::Base has_many :actividad has_many :tipo_resultado end <file_sep>/forminst_new1/app/views/documentoplans/index.json.jbuilder json.array!(@documentoplans) do |documentoplan| json.extract! documentoplan, :id, :id, :planFormacionId, :archivo json.url documentoplan_url(documentoplan, format: :json) end <file_sep>/forminst_new1/app/views/tiporesultados/index.json.jbuilder json.array!(@tiporesultados) do |tiporesultado| json.extract! tiporesultado, :id, :id, :tipoActividadId, :idPadre, :concepto json.url tiporesultado_url(tiporesultado, format: :json) end <file_sep>/forminst_new1/db/migrate/20150511190755_create_tipo_estatus.rb class CreateTipoEstatus < ActiveRecord::Migration def change create_table :tipo_estatus do |t| t.timestamps end end end <file_sep>/forminst_new1/app/models/tipo_estatus.rb class TipoEstatus < ActiveRecord::Base has_many :estatus_informe has_many :estatus_adecuacion has_many :revision end <file_sep>/forminst_new1/app/views/actividadejecutadas/index.json.jbuilder json.array!(@actividadejecutadas) do |actividadejecutada| json.extract! actividadejecutada, :id, :id, :descripcion, :fecha, :actual, :informeActividadId json.url actividadejecutada_url(actividadejecutada, format: :json) end <file_sep>/forminst_new1/test/controllers/adecuacionactividads_controller_test.rb require 'test_helper' class AdecuacionactividadsControllerTest < ActionController::TestCase setup do @adecuacionactividad = adecuacionactividads(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:adecuacionactividads) end test "should get new" do get :new assert_response :success end test "should create adecuacionactividad" do assert_difference('Adecuacionactividad.count') do post :create, adecuacionactividad: { actividadId: @adecuacionactividad.actividadId, adecuacionId: @adecuacionactividad.adecuacionId, anulada: @adecuacionactividad.anulada, id: @adecuacionactividad.id, semestre: @adecuacionactividad.semestre } end assert_redirected_to adecuacionactividad_path(assigns(:adecuacionactividad)) end test "should show adecuacionactividad" do get :show, id: @adecuacionactividad assert_response :success end test "should get edit" do get :edit, id: @adecuacionactividad assert_response :success end test "should update adecuacionactividad" do patch :update, id: @adecuacionactividad, adecuacionactividad: { actividadId: @adecuacionactividad.actividadId, adecuacionId: @adecuacionactividad.adecuacionId, anulada: @adecuacionactividad.anulada, id: @adecuacionactividad.id, semestre: @adecuacionactividad.semestre } assert_redirected_to adecuacionactividad_path(assigns(:adecuacionactividad)) end test "should destroy adecuacionactividad" do assert_difference('Adecuacionactividad.count', -1) do delete :destroy, id: @adecuacionactividad end assert_redirected_to adecuacionactividads_path end end <file_sep>/forminst_new1/app/models/informe.rb class Informe < ActiveRecord::Base belongs_to :usuario belongs_to :planformacion has_many :estatusinforme has_many :revision has_many :informeactividad has_many :documentoinforme belongs_to :tipo_informe end<file_sep>/forminst_new1/app/mailers/action_correo.rb class ActionCorreo < ActionMailer::Base default from: "FORMINST" def envio_informe(remitente, mensaje, id, link,document) ##ID :: 0 = ENTIDAD, 1 = INSTRUCTOR, 2 T= TUTOR @id = id @mensaje = mensaje if remitente.to_s.include? "@gmail.com" email = remitente else email = remitente.user + "@ciens.ucv.ve" end @email= email @user_email = '<EMAIL>' @link = link attachments[document.filename] = document.file_contents if (id == 0 && !(remitente.to_s.include? "@gmail.com")) ##ENTIDAD uEntidad = Usuarioentidad.where(usuario_id: remitente.id).take pertenecientes = Aenviar.where(entidad_id: uEntidad.entidad_id) nombreEntidad = Entidad.find(uEntidad.entidad_id).nombre pertenecientes.each do |email| mail(to: [@user_email,email], subject: nombreEntidad + ': Ha recibido una nueva Adecuaciรณn') end mail(to: [@user_email,@email], subject: 'Ha recibido un nuevo Informe') else ##TUTOR O INSTRUCTOR mail(to: [@user_email,@email], subject: 'Avance de Informe') end end def envio_adecuacion(remitente, mensaje, id, link,document) @id = id @mensaje = mensaje if remitente.to_s.include? "@gmail.com" email = remitente else email = remitente.user + "@ciens.ucv.ve" end @email= email @user_email = '<EMAIL>' @link = link attachments[document.filename] = document.file_contents if (id == 0 && !(remitente.to_s.include? "@gmail.com")) ##ENTIDAD uEntidad = Usuarioentidad.where(usuario_id: remitente.id).take pertenecientes = Aenviar.where(entidad_id: uEntidad.entidad_id) nombreEntidad = Entidad.find(uEntidad.entidad_id).nombre pertenecientes.each do |email| mail(to: [@user_email,email], subject: nombreEntidad + ': Ha recibido una nueva Adecuaciรณn') end mail(to: [@user_email,@email], subject: 'Ha recibido una nueva Adecuaciรณn') else ##TUTOR O INSTRUCTOR mail(to: [@user_email,@email], subject: 'Avance de Adecuaciรณn') end end def retraso_informe(remitente, mensaje, link) @mensaje = mensaje email = remitente.user + "@ciens.ucv.ve" @email= email @user_email = '<EMAIL>' @link = link mail(to: [@user_email,@email], subject: 'Recordatorio de envรญo de informe') end def creacion_de_instructor(remitente, mensaje, id, link) @id = id @mensaje = mensaje email = remitente.user + "@<EMAIL>" @email= email @user_email = '<EMAIL>' @link = link if id == 0 ##INSTRUCTOR mail(to: [@user_email,@email], subject: 'ยกBienvenido a FORMINST!') else ##TUTOR mail(to: [@user_email,@email], subject: 'Nueva Asignaciรณn de Instructor') end end def creacion_de_tutor(remitente, mensaje) @mensaje = mensaje email = remitente.user + "@ciens.ucv.ve" @email= email @link = "http://formacion.ciens.ucv.ve" @user_email = '<EMAIL>' mail(to: [@user_email,@email], subject: 'ยกBienvenido a FORMINST!') end end
04d7bb250ede6ca61010ebee844df400943ce2c4
[ "JavaScript", "Text", "Ruby" ]
135
Ruby
pedroaro/FORMINST
fce921d24bdee64bc383baf0d9edd51d0a848d79
1b30579b9e1a54696fbc83d0e1bf700105b63b40
refs/heads/master
<repo_name>Jagroop-Gill/trace-the-bug<file_sep>/rest-api/methods.js const apple = require('./apple.json'); const ontario = require('./ontario.json'); const googleOntario = require('./googleOntario.json'); const gta = ["vaughn", 'toronto', 'markham', 'mississauga', 'Brampton', 'Burlington', 'oakville', 'pickering', 'oshawa', 'ajax', 'richmond hill', 'milton', 'newmarket', 'whitby', 'aurora', 'caledon', 'halton hills']; module.exports = { filterByTrans: function(transName){ const filtered = []; apple.forEach(data =>{ if(data.transportation_type === transName){ filtered.push(data); } }); return( { name: "result", response: filtered } ); }, filterByLocationCountry: function(location){ const filtered = []; apple.forEach(data =>{ if(data.country === ""){ if(data.region.toLowerCase() === location.toLowerCase()){ filtered.push(data); } } }); return( { name: "result", response: filtered } ); }, filterByLocationState: function(location){ const filtered = []; apple.forEach(data =>{ if(data.country !== ""){ if(data.region.toLowerCase() === location.toLowerCase()){ filtered.push(data); } } }); return( { name: "result", response: filtered } ) }, filterByLocationCity: function(location){ const filtered = []; apple.forEach(data =>{ if(data.country !== ""){ if(data.region.toLowerCase() === location.toLowerCase()){ filtered.push(data); } } }); return( filtered ); }, filterOntarioByCity: function(location){ const filtered = []; ontario.map((data,i) =>{ if(i !== 0){ if(data.Reporting_PHU_City.toLowerCase() === location.toLowerCase()){ filtered.push(data); } } }); return( { name: "result", response: filtered } ) }, correlationAlg: function(city, start){ let isMatchGta = false; gta.forEach(location =>{ if(location.toLowerCase() === city.toLowerCase()){ isMatchGta = true; } }); let isMatchOtt = false; if(city === "ottawa"){ isMatchOtt = true; } if(isMatchGta){ const mobility = this.filterByLocationCity('toronto'); const applekeys = Object.keys(mobility[0]); const results = { torontoData: [], ontarioData: [], totalCases: [] }; const date = new Date(start.replace(/-/g, "/")); const firstDay = new Date(); const lastDay = new Date(); firstDay.setDate(date.getDate() - 5); lastDay.setDate(date.getDate() + 5); mobility.forEach(data =>{ applekeys.forEach(key =>{ let reg = /\d/g; if(reg.test(key)){ const cur = new Date(key.replace(/-/g, "/").replace('T00:00:00', '')) if(cur >= firstDay && cur <= lastDay){ results.torontoData.push({type: data.transportation_type, date: key, value: data[key]}); } } }) }); googleOntario.forEach(data =>{ let curDate = new Date(data.date.replace('T00:00:00', '').replace(/-/g, "/")); if(curDate >= firstDay && curDate <= lastDay){ results.ontarioData.push( { date: curDate, retail_change: data.grocery_and_pharmacy_percent_change_from_baseline, grocery_change: data.grocery_and_pharmacy_percent_change_from_baseline, parks_change: data.parks_percent_change_from_baseline, transit_change: data.transit_stations_percent_change_from_baseline, workplace_changes: data.workplaces_percent_change_from_baseline, residential_changes: data.residential_percent_change_from_baseline } ) } }); ontario.forEach(location =>{ let date = location.Accurate_Episode_Date.replace('T00:00:00', ''); let curDate = new Date(date.replace(/-/g, "/")); if((location.Reporting_PHU_City.toLowerCase() === city.toLowerCase())){ if(curDate >= firstDay && curDate <= lastDay){ results.totalCases.push({date: curDate}) } } }) return( results ); }else if(isMatchOtt){ const mobility = this.filterByLocationCity('ottawa'); const applekeys = Object.keys(mobility[0]); const results = { ottawaData: [], ontarioData: [], totalCases: [] }; const date = new Date(start.replace(/-/g, "/")); const firstDay = new Date(); const lastDay = new Date(); firstDay.setDate(date.getDate() - 5); lastDay.setDate(date.getDate() + 5); mobility.forEach(data =>{ applekeys.forEach(key =>{ let reg = /\d/g; if(reg.test(key)){ const cur = new Date(key.replace(/-/g, "/").replace('T00:00:00', '')) if(cur >= firstDay && cur <= lastDay){ results.ottawaData.push({type: data.transportation_type, date: key, value: data[key]}); } } }) }); googleOntario.forEach(data =>{ let curDate = new Date(data.date.replace('T00:00:00', '').replace(/-/g, "/")); if(curDate >= firstDay && curDate <= lastDay){ results.ontarioData.push( { date: curDate, retail_change: data.grocery_and_pharmacy_percent_change_from_baseline, grocery_change: data.grocery_and_pharmacy_percent_change_from_baseline, parks_change: data.parks_percent_change_from_baseline, transit_change: data.transit_stations_percent_change_from_baseline, workplace_changes: data.workplaces_percent_change_from_baseline, residential_changes: data.residential_percent_change_from_baseline } ) } }); ontario.forEach(location =>{ let date = location.Accurate_Episode_Date.replace('T00:00:00', ''); let curDate = new Date(date.replace(/-/g, "/")); if((location.Reporting_PHU_City.toLowerCase() === city.toLowerCase())){ if(curDate >= firstDay && curDate <= lastDay){ results.totalCases.push({date: curDate}); } } }) return( results ); }else{ const results = { ontarioData: [], totalCases: [] }; const date = new Date(start.replace(/-/g, "/")); const firstDay = new Date(); const lastDay = new Date(); firstDay.setDate(date.getDate() - 5); lastDay.setDate(date.getDate() + 5); googleOntario.forEach(data =>{ let curDate = new Date(data.date.replace('T00:00:00', '').replace(/-/g, "/")); if(curDate >= firstDay && curDate <= lastDay){ results.ontarioData.push( { date: curDate, retail_change: data.grocery_and_pharmacy_percent_change_from_baseline, grocery_change: data.grocery_and_pharmacy_percent_change_from_baseline, parks_change: data.parks_percent_change_from_baseline, transit_change: data.transit_stations_percent_change_from_baseline, workplace_changes: data.workplaces_percent_change_from_baseline, residential_changes: data.residential_percent_change_from_baseline } ) } }); ontario.forEach(location =>{ let date = location.Accurate_Episode_Date.replace('T00:00:00', ''); let curDate = new Date(date.replace(/-/g, "/")); if((location.Reporting_PHU_City.toLowerCase() === city.toLowerCase())){ if(curDate >= firstDay && curDate <= lastDay){ results.totalCases.push({date: curDate}) } } }) return( results ); } } };<file_sep>/rest-api/index.js const express = require('express'); const cors = require('cors'); const apple = require('./apple.json'); const ontario = require('./ontario.json'); const app = express(); const methods = require('./methods'); app.get('/alldata', cors(), (req, res) =>{ res.send(apple); }); app.get('/correlation/:location/:start', cors(), (req, res) =>{ const location = req.params.location; const start = req.params.start; let result = methods.correlationAlg(location, start); res.send(result); }); const port = process.env.PORT || 3001; app.listen(port, () =>{ console.log("Rest API live on " + port) });
9405d092b627f23dd10d0e34e8e772f799105fb0
[ "JavaScript" ]
2
JavaScript
Jagroop-Gill/trace-the-bug
ebcf5fdc63a0b20472b9b9e290b74957aecca56d
9ccd69f670edb373d21925191639c77e4b10aec6
refs/heads/master
<file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Text; namespace TicTacToe { class Player { public string Skin; public int Scores; public int Ox { get; set; } public int Oy { get; set; } public Player(string Symbol) { this.Skin = Symbol; } } } <file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Text; namespace TicTacToe { class Game { private string[,] Field = new string[3, 3]; public Player FirstPlayer; public Player SecondPlayer; public Player ComputerPlayer; public string Result { get; set; } public Game() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Field[i, j] = "*"; } } } public void Start() { this.FirstPlayer = new Player("0"); this.SecondPlayer = new Player("X"); this.EndlessCycle(); } private void EndlessCycle() { while (CheckOfResult()) { this.FirstUpdate(); this.SecondUpdate(); } Console.WriteLine(Result); } public void FirstUpdate() { this.Draw(); do { Console.WriteLine("First Player: Enter coordinates:\nOx from 0 to 2"); FirstPlayer.Ox = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Oy from 0 to 2"); FirstPlayer.Oy = Convert.ToInt32(Console.ReadLine()); } while (Checking(FirstPlayer.Ox, FirstPlayer.Oy)); Field[FirstPlayer.Ox, FirstPlayer.Oy] = FirstPlayer.Skin; } public void SecondUpdate() { this.Draw(); if (!CheckOfResult()) { return; } do { Console.WriteLine("Second Player: Enter coordinates:\nOx from 0 to 2"); SecondPlayer.Ox = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Oy from 0 to 2"); SecondPlayer.Oy = Convert.ToInt32(Console.ReadLine()); } while (Checking(SecondPlayer.Ox, SecondPlayer.Oy)); Field[SecondPlayer.Ox, SecondPlayer.Oy] = SecondPlayer.Skin; } public bool Checking(int x, int y) { if (0 <= x && x <= 2 && 0 <= y && y <= 2) { if (Field[x, y] == FirstPlayer.Skin || Field[x, y] == SecondPlayer.Skin) return true; else return false; } else return true; } public void Draw() { Console.Clear(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Console.Write(Field[i,j], " "); } Console.WriteLine(); } } public bool CheckOfResult() { if (CheckOfResultFirstPlayer() == false || CheckOfResultSecondPlayer() == false || CheckOfDraw() == false) { return false; } else return true; } public bool CheckOfResultFirstPlayer() { if ((Field[0,2] == Field[1,1] && Field[1,1] == Field[2,0] && Field[1,1] == FirstPlayer.Skin) || (Field[0, 0] == Field[1, 1] && Field[1, 1] == Field[2, 2] && Field[1, 1] == FirstPlayer.Skin)) { Result = "FIRST PLAYER WON !!!"; return false; } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if ((Field[i, 0] == Field[i, 1] && Field[i,1] == Field[i, 2] && Field[i, 2] == FirstPlayer.Skin) || (Field[0, j] == Field[1, j] && Field[1, j] == Field[2, j] && Field[2, j] == FirstPlayer.Skin)) { Result = "FIRST PLAYER WON !!!"; return false; } } } return true; } public bool CheckOfResultSecondPlayer() { if ((Field[0, 2] == Field[1, 1] && Field[1, 1] == Field[2, 0] && Field[1, 1] == SecondPlayer.Skin) || (Field[0, 0] == Field[1, 1] && Field[1, 1] == Field[2, 2] && Field[1, 1] == SecondPlayer.Skin)) { Result = "SECOND PLAYER WON !!!"; return false; } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if ((Field[i, 0] == Field[i, 1] && Field[i, 1] == Field[i, 2] && Field[i, 2] == SecondPlayer.Skin) || (Field[0, j] == Field[1, j] && Field[1, j] == Field[2, j] && Field[2, j] == SecondPlayer.Skin)) { Result = "SECOND PLAYER WON !!!"; return false; } } } return true; } public bool CheckOfDraw() { if (CheckOfResultFirstPlayer() && CheckOfResultSecondPlayer()) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if ( Field[i,j] != FirstPlayer.Skin || Field[i, j] != SecondPlayer.Skin) { return true; } } } Result = "IT'S DRAW !!!"; return false; } return true; } } }
d4018512ce9bf81a4ad385f0c0f528ee628c344e
[ "C#" ]
2
C#
chirchib/TicTacToe
4d81968c618363e697f1c9d16c70ebbfe6b10d76
b4c80d23962ec40387066644d6e592c5fd8624c0
refs/heads/master
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes() ?>> <head> <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" /> <title><?php global $page, $paged; wp_title( '|', true, 'right' ); // Add the blog name. bloginfo( 'name' ); // Add the blog description for the home/front page. $site_description = get_bloginfo( 'description', 'display' ); if ( $site_description && ( is_home() || is_front_page() ) ) echo " | $site_description"; // Add a page number if necessary: if ( $paged >= 2 || $page >= 2 ) echo ' | ' . sprintf( __( 'Page %s', 'designcrumbs' ), max( $paged, $page ) ); ?> </title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/> <link rel="alternate" type="application/rss+xml" title="<?php bloginfo('name'); ?> RSS" href="<?php bloginfo('rss2_url'); ?>" /> <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" /> <!-- CSS --> <style type="text/css"> a { color:<?php echo stripslashes(of_get_option('link_color')); ?>; } ul.commentlist .bypostauthor img.avatar { border:1px solid <?php echo stripslashes(of_get_option('link_color')); ?>; } </style> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" /> <?php wp_head(); //leave for plugins ?> <?php if (of_get_option('favicon') != '') { ?> <link rel="shortcut icon" href="<?php echo stripslashes(of_get_option('favicon')) ?>" /> <?php } ?> </head> <body <?php body_class(''. stripslashes(of_get_option('layout')) .' '. stripslashes(of_get_option('bg_pattern')) .' '. stripslashes(of_get_option('body_display')) .' scheme_'. stripslashes(of_get_option('color_scheme')) .''); ?>> <div id="main_wrap"> <div class="wrapper" id="header"> <div id="pre_header"></div> <div class="container"> <div id="logo_wrap"> <div id="the_logo"> <?php if (of_get_option('logo') != '') { ?> <a href="<?php echo home_url(); ?>" title="<?php bloginfo('name'); ?>" class="left the_logo"> <img src="<?php echo stripslashes(of_get_option('logo')); ?>" alt="<?php bloginfo('name'); ?>" id="logo" /> </a> <?php } else { ?> <h1><a href="<?php echo home_url(); ?>" title="<?php bloginfo('name'); ?>"><?php bloginfo('name'); ?></a></h1> <?php } ?> </div> <?php get_search_form(); ?> <div class="clear"></div> </div> <div id="clear"></div> </div> <div id="main_menu"> <div class="container"> <div id="main_menu_wrap"> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'depth' => '9' ) ); ?> <?php if (of_get_option('donate_link') != '') { ?> <a id="donate_now" class="button" href="<?php echo stripslashes(of_get_option('donate_link')); ?>" title="<?php echo stripslashes(of_get_option('donate_text')); ?>" target="_blank"><?php echo stripslashes(of_get_option('donate_text')); ?></a> <?php } ?> </div> </div> </div> </div> <div class="wrapper" id="content"> <!-- #content ends in footer.php --> <div class="container"> <file_sep><?php /** * A unique identifier is defined to store the options in the database and reference them from the theme. * By default it uses the theme name, in lowercase and without spaces, but this can be changed if needed. * If the identifier changes, it'll appear as if the options have been reset. * */ function optionsframework_option_name() { // This gets the theme name from the stylesheet (lowercase and without spaces) $themename = get_theme_data(STYLESHEETPATH . '/style.css'); $themename = $themename['Name']; $themename = preg_replace("/\W/", "", strtolower($themename) ); $optionsframework_settings = get_option('optionsframework'); $optionsframework_settings['id'] = $themename; update_option('optionsframework', $optionsframework_settings); // echo $themename; } /** * Defines an array of options that will be used to generate the settings page and be saved in the database. * When creating the "id" fields, make sure to use all lowercase and no spaces. * */ function optionsframework_options() { $heading_fonts = array("bitter" => "Bitter","droidsans" => "Droid Sans","droidserif" => "Droid Serif","franchise" => "Franchise","museo" => "Museo Slab","ubuntu" => "Ubuntu","rokkitt" => "Rokkitt"); // Pull all the categories into an array $options_categories = array(); $options_categories_obj = get_categories(); foreach ($options_categories_obj as $category) { $options_categories[$category->cat_ID] = $category->cat_name; } // Pull all the pages into an array $options_pages = array(); $options_pages_obj = get_pages('sort_column=post_parent,menu_order'); $options_pages[''] = __('Select a page:', 'designcrumbs'); foreach ($options_pages_obj as $page) { $options_pages[$page->ID] = $page->post_title; } // If using image radio buttons, define a directory path $imagepath = get_template_directory_uri() . '/images/'; $options = array(); $options[] = array( "name" => __('Basic Settings', 'designcrumbs'), "type" => "heading"); $options[] = array( "name" => __('Logo', 'designcrumbs'), "desc" => __('Upload your logo. Height should be 80px, if it is bigger, it will be resized.', 'designcrumbs'), "id" => "logo", "type" => "upload"); $options[] = array( "name" => __('Favicon', 'designcrumbs'), "desc" => __('The Favicon is the little 16x16 icon that appears next to your URL in the browser. It is not required, but recommended.', 'designcrumbs'), "id" => "favicon", "type" => "upload"); $options[] = array( "name" => __('Site Layout', 'designcrumbs'), "desc" => __('Select a layout for the site.', 'designcrumbs'), "id" => "layout", "std" => "content_left", "type" => "images", "options" => array( 'content_right' => $imagepath . '2cl.png', 'content_left' => $imagepath . '2cr.png',) ); $options[] = array( "name" => __('Body Display Style', 'designcrumbs'), "desc" => __('Choose if you want your site design to be boxed in or span the width of the browser.', 'designcrumbs'), "id" => "body_display", "std" => "body_boxed", "type" => "radio", "options" => array("body_boxed" => __('Boxed', 'designcrumbs'),"body_span" => __('Full Width', 'designcrumbs'))); $options[] = array( "name" => __('Sticky Header', 'designcrumbs'), "desc" => __('Would you like the header to stick to the top of the browser as the user scrolls down the site?', 'designcrumbs'), "id" => "sticky_header", "std" => "yes", "type" => "radio", "options" => array("yes" => __('Yes', 'designcrumbs'),"no" => __('No', 'designcrumbs'))); $options[] = array( "name" => __('Tracking Code', 'designcrumbs'), "desc" => __('Paste your Google Analytics (or other) tracking code here. This will be added into the footer template of your theme. If you need analytics, you can <a href="http://www.google.com/analytics" target="_blank">go here</a>.', 'designcrumbs'), "id" => "analytics", "std" => "", "type" => "textarea"); $options[] = array( "name" => __('Credit Where Credit Is Due', 'designcrumbs'), "desc" => __('Checking this box will give credit to <NAME> and the Campaign theme in the footer.', 'designcrumbs'), "id" => "give_credit", "std" => "1", "type" => "checkbox"); $options[] = array( "name" => "Campaign", "type" => "heading"); $options[] = array( "name" => __('Donate Button Link', 'designcrumbs'), "desc" => __('Enter the link to your donation form. This will enable a <strong>Donate</strong> button in the menu. If you want to set up a PayPal donate link, <a href="http://en.support.wordpress.com/paypal/" target="_blank">WordPress has a tutorial of how to set that up and get the link here</a>.', 'designcrumbs'), "id" => "donate_link", "std" => "", "type" => "textarea"); $options[] = array( "name" => __('Donate Button Text', 'designcrumbs'), "desc" => __('The text for your Donate button.', 'designcrumbs'), "id" => "donate_text", "std" => "Make A Donation", "type" => "text"); $options[] = array( "name" => __('"Paid For" Text', 'designcrumbs'), "desc" => __('Filling in this will make a 1px bordered box appear in the footer of the site. <strong>This is required in the USA by the FEC for political committees.</strong> <a href="http://www.fec.gov/pages/brochures/notices.shtml#disclaimers" target="_blank">Learn more here</a>.', 'designcrumbs'), "id" => "paid_for", "std" => "", "type" => "text"); $options[] = array( "name" => __('Footer Slogan', 'designcrumbs'), "desc" => __('This is for a large slogan at the top of your footer. Optional', 'designcrumbs'), "id" => "footer_slogan", "std" => "", "type" => "text"); $options[] = array( "name" => __('Fallback Image', 'designcrumbs'), "desc" => __('Upload your fallback image for the home page posts. If the post itself does not have a featured image, this one will be used. The image size should be 170px by 120px. If it\'s larger it will be cropped.', 'designcrumbs'), "id" => "campaign_fallback", "type" => "upload"); $options[] = array( "name" => __('Home Page', 'designcrumbs'), "type" => "heading"); $options[] = array( "name" => __('Slider FX', 'designcrumbs'), "desc" => __('Select your slide transition.', 'designcrumbs'), "id" => "slider_fx", "type" => "select", "std" => "fade", "options" => array("fade" => __('Fade', 'designcrumbs'),"slide" => __('Slide', 'designcrumbs'))); $options[] = array( "name" => __('Slider Time', 'designcrumbs'), "desc" => __('How long in seconds (use a whole number) would you like a slide to hold for before moving on to the next one? Setting this to 0 (zero) will not autoplay the slides. Zero is recommended if you are using videos in your slider.', 'designcrumbs'), "id" => "slider_time", "type" => "text", "class" => "mini", "std" => "8"); $options[] = array( "name" => __('Home Page Video', 'designcrumbs'), "desc" => __('Would you like a video on the home page, and if so, from where?', 'designcrumbs'), "id" => "video_type", "std" => "none", "type" => "radio", "options" => array("none" => __('None', 'designcrumbs'),"youtube" => __('YouTube', 'designcrumbs'),"vimeo" => __('Vimeo', 'designcrumbs'))); $options[] = array( "name" => __('YouTube ID', 'designcrumbs'), "desc" => __('If the YouTube link is http://www.youtube.com/watch?v=Iv69kB_e9KY, the ID is Iv69kB_e9KY.', 'designcrumbs'), "id" => "youtube_id", "std" => "", "class" => "mini", "type" => "text"); $options[] = array( "name" => __('Vimeo ID', 'designcrumbs'), "desc" => __('If the Vimeo link is http://vimeo.com/22639018, the ID is 22639018.', 'designcrumbs'), "id" => "vimeo_id", "std" => "", "class" => "mini", "type" => "text"); $options[] = array( "name" => __('Video Title', 'designcrumbs'), "desc" => __('The title to your video.', 'designcrumbs'), "id" => "video_title", "std" => "", "type" => "text"); $options[] = array( "name" => __('Video Description', 'designcrumbs'), "desc" => __('A short description about your video.', 'designcrumbs'), "id" => "video_desc", "std" => "", "type" => "textarea"); $options[] = array( "name" => __('Home Page Posts Title', 'designcrumbs'), "desc" => __('The title for your latest posts on the home page.', 'designcrumbs'), "id" => "home_posts_title", "std" => "Latest Posts", "type" => "text"); $options[] = array( "name" => __('Which Posts Should Be On The Home Page?', 'designcrumbs'), "desc" => __('Would you like the home page posts to be all posts, or posts from a specific category?', 'designcrumbs'), "id" => "home_posts_selection", "std" => "posts_all", "type" => "radio", "options" => array("posts_all" => __('All Posts', 'designcrumbs'),"posts_specific" => __('Specific Category', 'designcrumbs'))); $options[] = array( "name" => __('Home Page Posts Category', 'designcrumbs'), "desc" => __('Select the category you would like to pull posts from.', 'designcrumbs'), "id" => "home_posts_cat", "type" => "select", "options" => $options_categories); $options[] = array( "name" => __('Number of posts for the home page', 'designcrumbs'), "desc" => __('On the home page blog posts are displayed 3 wide, so this number should be a multiple of 3.', 'designcrumbs'), "id" => "home_posts_total", "std" => "3", "class" => "mini", "type" => "text"); $options[] = array( "name" => __('Styles', 'designcrumbs'), "type" => "heading"); $options[] = array( "name" => __('Color Scheme', 'designcrumbs'), "desc" => __('Select the color scheme for your header.', 'designcrumbs'), "id" => "color_scheme", "std" => "blue", "type" => "select", "options" => array("blue" => __('Blue', 'designcrumbs'),"red" => __('Red', 'designcrumbs'),"yellow" => __('Yellow', 'designcrumbs'),"green" => __('Green', 'designcrumbs'))); $options[] = array( "name" => __('Background Pattern', 'designcrumbs'), "desc" => __('Choose the overall background pattern for the site. <em>Note: this only works with the <strong>Boxed</strong> Body Display Style.</em>', 'designcrumbs'), "id" => "bg_pattern", "std" => "bg_fabric", "type" => "select", "options" => array("bg_cork" => __('Cork', 'designcrumbs'),"bg_fabric" => __('Fabric', 'designcrumbs'),"bg_freckles" => __('Freckle Squares', 'designcrumbs'),"bg_linen" => "Linen","bg_pinstripe" => __('Pinstripes', 'designcrumbs'),"bg_none" => __('None', 'designcrumbs'))); $options[] = array( "name" => __('Heading Font', 'designcrumbs'), "desc" => __('Select the font for the headings of the site.', 'designcrumbs'), "id" => "heading_font", "std" => "ubuntu", "type" => "select", "options" => $heading_fonts); $options[] = array( "name" => __('Link Color', 'designcrumbs'), "desc" => __('Select the color for your links.', 'designcrumbs'), "id" => "link_color", "std" => "", "type" => "color"); $options[] = array( "name" => __('Social Networks', 'designcrumbs'), "type" => "heading"); $options[] = array( "name" => __('Twitter', 'designcrumbs'), "desc" => __('Enter the URL to your Twitter profile.', 'designcrumbs'), "id" => "twitter", "type" => "text"); $options[] = array( "name" => __('Facebook', 'designcrumbs'), "desc" => __('Enter the URL to your Facebook profile.', 'designcrumbs'), "id" => "facebook", "type" => "text"); $options[] = array( "name" => __('Google+', 'designcrumbs'), "desc" => __('Enter the URL to your Google+ profile.', 'designcrumbs'), "id" => "google", "type" => "text"); $options[] = array( "name" => __('Flickr', 'designcrumbs'), "desc" => __('Enter the URL to your Flickr Profile.', 'designcrumbs'), "id" => "flickr", "type" => "text"); $options[] = array( "name" => __('Tumblr', 'designcrumbs'), "desc" => __('Enter the URL to your Tumblr Profile.', 'designcrumbs'), "id" => "tumblr", "type" => "text"); $options[] = array( "name" => __('YouTube', 'designcrumbs'), "desc" => __('Enter the URL to your YouTube Profile.', 'designcrumbs'), "id" => "youtube", "type" => "text"); $options[] = array( "name" => __('Vimeo', 'designcrumbs'), "desc" => __('Enter the URL to your Vimeo Profile.', 'designcrumbs'), "id" => "vimeo", "type" => "text"); $options[] = array( "name" => __('Pinterest', 'designcrumbs'), "desc" => __('Enter the URL to your Pinterest Profile.', 'designcrumbs'), "id" => "pinterest", "type" => "text"); $options[] = array( "name" => __('Instagram', 'designcrumbs'), "desc" => __('Enter the URL to your Instagram Profile.', 'designcrumbs'), "id" => "instagram", "type" => "text"); // Support $options[] = array( "name" => "Support", "type" => "heading"); $options[] = array( "name" => __('Theme Documentation & Support', 'designcrumbs'), "desc" => "<p class='dc-text'>Theme support and documentation is available for all customers. Visit the <a target='blank' href='http://support.designcrumbs.com'>Design Crumbs Support Forum</a> to get started. Simply follow the instructions on the home page to verify your purchase and get a support account.</p> <div class='dc-buttons'><a target='blank' class='dc-button help-button' href='http://support.designcrumbs.com/help_files/campaignwp/'><span class='dc-icon icon-help'>Help File</span></a><a target='blank' class='dc-button support-button' href='http://support.designcrumbs.com'><span class='dc-icon icon-support'>Support Forum</span></a><a target='blank' class='dc-button custom-button' href='http://www.designcrumbs.com/theme-customization-request'><span class='dc-icon icon-custom'>Customize Theme</span></a></div> <h4 class='heading'>More Themes by Design Crumbs</h4> <div class='embed-themes'></div> ", "type" => "info"); return $options; }<file_sep><li class="single_slide slides_container clearfix"> <div class="slide_content clearfix"> <?php if (has_post_thumbnail()) { ?> <div class="slide_image_wrap"> <?php if (get_post_meta($post->ID, '_dc_slide_text', true) != '') { ?> <div class="slide_text_overlay"> <?php echo get_post_meta($post->ID, '_dc_slide_text', true);?> </div> <?php } ?> <?php if (get_post_meta($post->ID, '_dc_slide_link', true) != '') { ?><a href="<?php echo get_post_meta($post->ID, '_dc_slide_link', true);?>" title="<?php the_title(); ?>"><?php } ?> <?php the_post_thumbnail(); ?> <?php if (get_post_meta($post->ID, '_dc_slide_link', true) != '') { ?></a><?php } ?> </div> <?php } else { ?> <?php if (get_post_meta($post->ID, '_dc_video', true) != '') { ?> <?php echo wp_oembed_get(get_post_meta($post->ID, '_dc_video', true), array('width'=>600,'height'=>300)); ?> <?php } ?> <?php } ?> </div> </li><file_sep><?php /* Campaign JS Code and stuff you need for the Campaign theme */ ?> <script type="text/javascript"> /* <![CDATA[ */ <?php if (is_front_page()) { ?> jQuery(function($) { $(window).load(function(){ // THE SLIDER $('#slides').flexslider({ start: function(slider) { if (slider.count == 1) { $('.flex-control-nav, .flex-direction-nav').hide(); } }, animation: "fade", slideshowSpeed: <?php echo stripslashes(of_get_option('slider_time')); ?>000, animationSpeed: 600, prevText: "", nextText: "", smoothHeight: true, controlNav: true, video: true, directionNav: false }); }); }); <?php } ?> jQuery(document).ready(function($){ // load mobile menu $('#main_menu ul.menu').mobileMenu(); $('select.select-menu').each(function(){ var title = $(this).attr('title'); if( $('option:selected', this).val() != '' ) title = $('option:selected',this).text(); $(this) .css({'z-index':10,'opacity':0,'-khtml-appearance':'none'}) .after('<span class="select">' + title + '</span>') .change(function(){ val = $('option:selected',this).text(); $(this).next().text(val); }) }); // Children Flyout on Menu $("#main_menu ul li ul").css({display: "none"}); // Opera Fix $("#main_menu ul li").hover(function(){ $(this).find('ul:first').css({visibility: "visible",display: "none"}).show(300); },function(){ $(this).find('ul:first').css({visibility: "hidden"}); }); // FitVids $("#content").fitVids(); <?php if ((of_get_option('sticky_header') == 'yes') && (of_get_option('body_display') == 'body_span')) { ?> $("#header").sticky({topSpacing:0}); <?php } ?> // Turn on that SlabText function slabTextHeadlines() { $('.slabload').fadeIn(1000); // fade in after it's loaded $(".slabwrap h1").slabText({ // Don't slabtext the headers if the viewport is under 380px "viewportBreakpoint":380 }); }; // give it a second to load fonts $(window).load(function() { setTimeout(slabTextHeadlines, 1000); }); // Adds class to commenters $("ul.commentlist li:not(.bypostauthor)").children(".the_comment").addClass("not_author"); // Fancybox $(".lightbox").attr('rel', 'gallery').fancybox({ 'transitionIn' : 'fade', 'transitionOut' : 'fade' }); // clean up the WP Email Capture widget $('#wp_email_capture').parent().addClass('wp_email_capture_wrap'); $('#wp_email_capture').parent().parent().parent().addClass('wp_email_slide'); $('#wp_email_capture').find('br').remove(); // put title in fields $("input[type='text']").focus(function(srcc) { if ($(this).val() == $(this)[0].title) { $(this).removeClass("wp-email-capture-active"); $(this).val(""); } }); $("input[type='text']").blur(function() { if ($(this).val() == "") { $(this).addClass("wp-email-capture-active"); $(this).val($(this)[0].title); } }); $("input[type='text']").blur(); $('#slide_widget').fadeIn(1000); // fade in after it's loaded }); /* ]]> */ </script><file_sep><?php get_header(); ?> <div id="page" class="posts-wrap"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div id="post-single" <?php post_class(); ?>> <h3 class="entry-title"> <?php the_title(); ?> </h3> <?php if ((get_post_meta($post->ID, '_dc_media_vimeo', true) != '') || (get_post_meta($post->ID, '_dc_media_youtube', true) != '')) { ?> <?php if (get_post_meta($post->ID, '_dc_media_vimeo', true) != '') { ?> <div class="vid-wrap"> <iframe src="http://player.vimeo.com/video/<?php echo get_post_meta($post->ID, '_dc_media_vimeo', true);?>?portrait=0" width="600" height="335" frameborder="0"></iframe> </div> <?php } elseif (get_post_meta($post->ID, '_dc_media_youtube', true) != '') { ?> <div class="vid-wrap"> <iframe width="600" height="335" src="http://www.youtube.com/embed/<?php echo get_post_meta($post->ID, '_dc_media_youtube', true);?>?wmode=opaque" frameborder="0" allowfullscreen></iframe> </div> <?php } ?> <?php } elseif (has_post_thumbnail()) { ?> <a href="<?php $image_id = get_post_thumbnail_id(); $image_url = wp_get_attachment_image_src($image_id,'full', true); echo $image_url[0]; ?>" class="lightbox"><?php the_post_thumbnail( 'blog_image', array('alt' => get_the_title()) ); ?></a> <?php } ?> <div class="post_meta"> <div class="blocks_wrap"> <div class="meta_block"> <span><?php _e("Post Date", "designcrumbs"); ?></span> <?php the_time('F d, Y'); ?> </div> <div class="meta_block"> <span><?php _e("Comments", "designcrumbs"); ?></span> <?php comments_popup_link( __( '0 Comments', 'designcrumbs' ), __( '1 Comment', 'designcrumbs' ), __( '% Comments', 'designcrumbs' ), 'comments-link', __('Comments Closed', 'designcrumbs')); ?> </div> <div class="meta_block"> <span><?php _e("Author", "designcrumbs"); ?></span> <?php the_author_posts_link(); ?> </div> <div class="meta_block"> <span><?php _e("Category", "designcrumbs"); ?></span> <?php the_category(', ') ?> </div> <div class="meta_block share"> <span><?php _e("Share", "designcrumbs"); ?></span> <a class="share-facebook" onclick="window.open('http://www.facebook.com/share.php?u=<?php the_permalink(); ?>','facebook','width=450,height=300,left='+(screen.availWidth/2-375)+',top='+(screen.availHeight/2-150)+'');return false;" href="http://www.facebook.com/share.php?u=<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <img src="<?php echo get_template_directory_uri(); ?>/images/socnets/share_facebook.png" alt="Share on Facebook" /> </a> <a class="share-twitter" onclick="window.open('http://twitter.com/home?status=<?php the_title(); ?> - <?php the_permalink(); ?>','twitter','width=450,height=300,left='+(screen.availWidth/2-375)+',top='+(screen.availHeight/2-150)+'');return false;" href="http://twitter.com/home?status=<?php the_title(); ?> - <?php the_permalink(); ?>" title="<?php the_title(); ?>"> <img src="<?php echo get_template_directory_uri(); ?>/images/socnets/share_twitter.png" alt="Share on Twitter" /> </a> <a class="share-google" href="https://plus.google.com/share?url=<?php the_permalink(); ?>" onclick="window.open('https://plus.google.com/share?url=<?php the_permalink(); ?>','gplusshare','width=450,height=300,left='+(screen.availWidth/2-375)+',top='+(screen.availHeight/2-150)+'');return false;" title="<?php the_title(); ?>"> <img src="<?php echo get_template_directory_uri(); ?>/images/socnets/share_google.png" alt="Share on Google+" /> </a> </div> <div class="clear"></div> </div> </div> <div class="blog-content"> <div class="entry-content" id="entry-content-single"> <?php the_content(); ?> <div class="clear"></div> <?php if (has_tag()) { ?> <div class="single-meta"> <?php the_tags( __('Tagged with ', 'designcrumbs'), ", ", " " ) ?> </div> <?php } ?> </div> </div> <div class="clear"></div> <?php my_author_box(); ?> </div><!-- end .post --> <?php comments_template('', true); ?> <?php endwhile; else: ?> <?php _e('Sorry, no posts matched your criteria', 'designcrumbs'); ?>. <?php endif; ?> <div class="clear"></div> </div><!-- end .posts-wrap --> <?php get_sidebar(); ?> <?php get_footer(); ?><file_sep><?php get_header(); ?> <div class="posts-wrap the_blog search_results"> <h3 id="search" class="page-title"> <?php /* Search Count */ $allsearch = new WP_Query("s=$s&showposts=-1"); $count = $allsearch->post_count; $string = sprintf( __('%1$s Search Results for <strong>%2$s</strong>', 'designcrumbs'), $count, get_search_query() ); echo $string; wp_reset_query(); ?> </h3> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php get_template_part( 'loop', 'post' ); ?> <?php endwhile; ?> <div class="navigation navigation-index"> <div class="nav-prev"><?php next_posts_link( __('&laquo; Older Entries', 'designcrumbs')) ?></div> <div class="nav-next"><?php previous_posts_link( __('Newer Entries &raquo;', 'designcrumbs')) ?></div> <div class="clear"></div> </div> <?php else : ?> <div class="post"> <div class="entry-content"> <?php _e("We're sorry, but", "designcrumbs"); ?> <strong><?php the_search_query() ?></strong> <?php _e("returns no results. Please try your search again, or navigate around the site with the links on top.", "designcrumbs"); ?> </div> </div> <?php endif; ?> </div><!-- end .posts-wrap --> <?php get_sidebar(); ?> <?php get_footer(); ?><file_sep> <div class="clear"></div> </div><!-- end div.container, begins in header.php --> </div><!-- end div.wrapper, begins in header.php --> </div><!-- end div#main_wrap, begins in header.php --> <div id="footer" class="wrapper"> <div class="container"> <?php if (of_get_option('footer_slogan') != '') { ?> <h1 id="footer_slogan"><?php echo stripslashes(of_get_option('footer_slogan')) ?></h1> <?php } ?> <div id="footer_widgets" class="<?php $sb_count = wp_get_sidebars_widgets(); if (count( $sb_count['Footer']) <= '5') { ?>footer_widget_count<?php count_sidebar_widgets( 'Footer' );?><?php } else { ?>footer_widget_overflow<?php } ?>"> <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer') ) : endif; ?> <div class="clear"></div> </div> <div id="post_footer"> <?php if ((of_get_option('twitter') != '') || (of_get_option('facebook') != '') || (of_get_option('google') != '') || (of_get_option('flickr') != '') || (of_get_option('vimeo') != '') || (of_get_option('youtube') != '') || (of_get_option('tumblr') != '') || (of_get_option('pinterest') != '') || (of_get_option('instagram') != '') ) { ?> <div id="socnets_wrap"> <div id="socnets"> <?php if (of_get_option('twitter') != '') { ?> <a href="<?php echo stripslashes(of_get_option('twitter')); ?>" title="Twitter" class="socnet-twitter"></a> <?php } if (of_get_option('facebook') != '') { ?> <a href="<?php echo stripslashes(of_get_option('facebook')); ?>" title="Facebook" class="socnet-facebook"></a> <?php } if (of_get_option('google') != '') { ?> <a href="<?php echo stripslashes(of_get_option('google')); ?>" title="Google+" class="socnet-google"></a> <?php } if (of_get_option('flickr') != '') { ?> <a href="<?php echo stripslashes(of_get_option('flickr')); ?>" title="Flickr" class="socnet-flickr"></a> <?php } if (of_get_option('tumblr') != '') { ?> <a href="<?php echo stripslashes(of_get_option('tumblr')); ?>" title="Tumblr" class="socnet-tumblr"></a> <?php } if (of_get_option('vimeo') != '') { ?> <a href="<?php echo stripslashes(of_get_option('vimeo')); ?>" title="Vimeo" class="socnet-vimeo"></a> <?php } if (of_get_option('youtube') != '') { ?> <a href="<?php echo stripslashes(of_get_option('youtube')); ?>" title="YouTube" class="socnet-youtube"></a> <?php } if (of_get_option('pinterest') != '') { ?> <a href="<?php echo stripslashes(of_get_option('pinterest')); ?>" title="Pinterest" class="socnet-pinterest"></a> <?php } if (of_get_option('instagram') != '') { ?> <a href="<?php echo stripslashes(of_get_option('instagram')); ?>" title="Instagram" class="socnet-instagram"></a> <?php } ?> </div> <div class="clear"></div> </div> <?php } ?> <?php if (of_get_option('paid_for') != '') { ?> <div id="paid_for"><?php echo stripslashes(of_get_option('paid_for')) ?></div> <?php } ?> <div id="site_info"> &copy; <?php echo date("Y"); ?> <?php bloginfo('name'); ?>&nbsp;&nbsp;:&nbsp; <?php if (of_get_option('give_credit') == '1') { $string = sprintf( __('<a href="%1$s" title="Campaign WordPress Theme">Campaign Theme</a> by <a href="%2$s" title="Design Crumbs">Design Crumbs</a>', 'designcrumbs'), 'http://themes.designcrumbs.com', 'http://designcrumbs.com' ); echo $string; } else { echo bloginfo('description'); } ?> </div> </div> </div> </div> <?php wp_footer(); //leave for plugins ?> <?php echo stripslashes(of_get_option('analytics')); ?> </body> </html><file_sep><?php get_header(); ?> <div id="slides_wrap"<?php $sb_count = wp_get_sidebars_widgets(); if (count( $sb_count['Home_Page_Banner']) == '0') { ?> class="home_space"<?php } ?>> <?php // START SLIDES $query_default = new WP_Query( array( 'post_type' => 'slides', 'posts_per_page' => 99, 'order' => 'desc' )); if ( $query_default->have_posts() ) : ?> <div id="slides" class="clearfix"> <div id="slide_wrap" class="clearfix"> <ul class="slides clearfix"> <?php while ( $query_default->have_posts() ) : $query_default->the_post(); ?> <?php get_template_part( 'loop', 'slide' ); ?> <?php endwhile; wp_reset_query(); ?> </ul> </div> </div> <?php endif; // END SLIDES ?> <?php /* <div id="slide_widget"> <div id="slide_widget_inner"> <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Top_Sidebar') ) : endif; ?> </div> </div> <div class="clear"></div> */ ?> </div> <?php if (count( $sb_count['Home_Page_Banner']) != '0') { ?> <div id="home_widgets"> <div id="home_widget_wrap" class="<?php $sb_count = wp_get_sidebars_widgets(); if (count( $sb_count['Home_Page_Banner']) <= '3') { ?>banner_widget_count<?php count_sidebar_widgets( 'Home_Page_Banner' );?><?php } else { ?>banner_widget_overflow<?php } ?>"> <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Home_Page_Banner') ) : endif; ?> <div class="clear"></div> </div> </div> <?php } ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php if ($post->post_content != "") { // if the post has content ?> <div id="home_content"> <div <?php post_class(); ?>> <?php the_content(); ?> <div class="clear"></div> </div> </div> <?php } ?> <?php endwhile; endif; ?> <div class="posts-wrap"> <?php if (of_get_option('video_type') != 'none') { ?> <div id="home_video_wrap"> <div id="home_video"> <?php if ((of_get_option('vimeo_id') != '') && (of_get_option('video_type') == 'vimeo')) { ?> <iframe src="http://player.vimeo.com/video/<?php echo stripslashes(of_get_option('vimeo_id')); ?>?portrait=0" width="380" height="223" frameborder="0"></iframe> <?php } if ((of_get_option('youtube_id') != '') && (of_get_option('video_type') == 'youtube')) { ?> <iframe width="380" height="223" src="http://www.youtube.com/embed/<?php echo stripslashes(of_get_option('youtube_id')); ?>?wmode=opaque" frameborder="0" allowfullscreen></iframe> <?php } ?> </div> <?php if (of_get_option('video_desc') != '') { ?> <div id="home_video_desc"> <?php if (of_get_option('video_title') != '') { ?> <h4><?php echo stripslashes(of_get_option('video_title')); ?></h4> <?php } ?> <p><?php echo stripslashes(of_get_option('video_desc')); ?></p> </div> <?php } ?> <div class="clear"></div> </div> <?php } ?> <?php wp_reset_query(); // END NEWS LOOP ?> </div> <?php get_footer(); ?><file_sep><?php // Theme Prefix: dcs_ /* ========================================= Constants ========================================= */ if(!defined('DCS_THEME_DIR')) { define('DCS_THEME_DIR', dirname(__FILE__)); } /* ========================================= File Includes ========================================= */ include(DCS_THEME_DIR . '/includes/scripts.php'); /* ========================================= General Things We Need ========================================= */ add_editor_style(); // Adds CSS to the editor to match the front end of the site. add_theme_support('automatic-feed-links'); if ( ! isset( $content_width ) ) $content_width = 590; // This is the max width of the content, thus the max width of large images that are uploaded. require_once(dirname(__FILE__) . "/includes/support/support.php"); // Load support tab // Load Language File load_theme_textdomain('designcrumbs', get_template_directory() . '/languages'); $locale = get_locale(); $locale_file = get_template_directory() . '/languages/$locale.php'; if ( is_readable($locale_file) ) require_once($locale_file); // Check for Options Framework Plugin of_check(); function of_check() { if ( !function_exists('of_get_option') ) { add_action('admin_notices', 'of_check_notice'); } } // The Admin Notice function of_check_notice() { ?> <div class='updated fade'> <p>The <strong>Options Framework plugin</strong> is required for this theme to function properly. <a href="<?php echo network_admin_url('plugin-install.php?tab=plugin-information&plugin=options-framework&TB_iframe=true&width=640&height=517'); ?>" class="thickbox onclick">Install now</a>.</p> </div> <?php } // Check for WP Email Capture dcs_wpemailcapture_check(); function dcs_wpemailcapture_check() { if ( function_exists('wp_email_capture_plugins_loaded') ) { update_option('wp_email_capture_theme_affiliate_link', 'https://www.e-junkie.com/ecom/gb.php?ii=1130727&c=ib&aff=236565&cl=24404'); } } /* =================================== Options Framework =================================== */ if ( !function_exists( 'of_get_option' ) ) { function of_get_option($name, $default = false) { $optionsframework_settings = get_option('optionsframework'); // Gets the unique option id $option_name = $optionsframework_settings['id']; if ( get_option($option_name) ) { $options = get_option($option_name); } if ( isset($options[$name]) ) { return $options[$name]; } else { return $default; } } } /* This one shows/hides the an option when a checkbox is clicked. */ add_action('optionsframework_custom_scripts', 'optionsframework_custom_scripts'); function optionsframework_custom_scripts() { ?> <script type="text/javascript"> jQuery(document).ready(function() { // adds support tab jQuery(".embed-themes").html("<iframe width='770' height='390' src='http://themes.designcrumbs.com/iframe/index.html'></iframe>"); // Checks for body style jQuery('#campaign-body_display-body_span').click(function() { jQuery('#section-sticky_header').fadeIn(400); }); jQuery('#campaign-body_display-body_boxed').click(function() { jQuery('#section-sticky_header').fadeOut(400); }); if (jQuery('#campaign-body_display-body_boxed').is(':checked')) { jQuery('#section-sticky_header').hide(); }; // Checks for home page video content jQuery('#campaign-video_type-none').click(function() { jQuery('#section-youtube_id').hide(); jQuery('#section-vimeo_id').hide(); jQuery('#section-video_title').hide(); jQuery('#section-video_desc').hide(); }); jQuery('#campaign-video_type-youtube').click(function() { jQuery('#section-vimeo_id').hide(); jQuery('#section-youtube_id').fadeIn(400); jQuery('#section-video_title').fadeIn(400); jQuery('#section-video_desc').fadeIn(400); }); jQuery('#campaign-video_type-vimeo').click(function() { jQuery('#section-youtube_id').hide(); jQuery('#section-vimeo_id').fadeIn(400); jQuery('#section-video_title').fadeIn(400); jQuery('#section-video_desc').fadeIn(400); }); if (jQuery('#campaign-video_type-none').is(':checked')) { jQuery('#section-youtube_id').hide(); jQuery('#section-vimeo_id').hide(); jQuery('#section-video_title').hide(); jQuery('#section-video_desc').hide(); }; if (jQuery('#campaign-video_type-youtube').is(':checked')) { jQuery('#section-vimeo_id').hide(); }; if (jQuery('#campaign-video_type-vimeo').is(':checked')) { jQuery('#section-youtube_id').hide(); }; // Checks for home page post cats jQuery('#campaign-home_posts_selection-posts_specific').click(function() { jQuery('#section-home_posts_cat').fadeIn(400); }); jQuery('#campaign-home_posts_selection-posts_all').click(function() { jQuery('#section-home_posts_cat').fadeOut(400); }); if (jQuery('#campaign-home_posts_selection-posts_all').is(':checked')) { jQuery('#section-home_posts_cat').hide(); }; }); </script> <?php } /* Removes the code stripping */ add_action('admin_init','optionscheck_change_santiziation', 100); function optionscheck_change_santiziation() { remove_filter( 'of_sanitize_textarea', 'of_sanitize_textarea' ); add_filter( 'of_sanitize_textarea', 'of_sanitize_textarea_custom' ); } function of_sanitize_textarea_custom($input) { global $allowedposttags; $of_custom_allowedtags["embed"] = array( "src" => array(), "type" => array(), "allowfullscreen" => array(), "allowscriptaccess" => array(), "height" => array(), "width" => array() ); $of_custom_allowedtags["script"] = array( "type" => array() ); $of_custom_allowedtags["iframe"] = array( "height" => array(), "width" => array(), "src" => array(), "frameborder" => array(), "allowfullscreen" => array() ); $of_custom_allowedtags["object"] = array( "height" => array(), "width" => array() ); $of_custom_allowedtags["param"] = array( "name" => array(), "value" => array() ); $of_custom_allowedtags = array_merge($of_custom_allowedtags, $allowedposttags); $output = wp_kses( $input, $of_custom_allowedtags); return $output; } /* =================================== Add Fancybox to linked Images =================================== */ /** * Attach a class to linked images' parent anchors * e.g. a img => a.img img */ function give_linked_images_class($html, $id, $caption, $title, $align, $url, $size, $alt = '' ){ $classes = 'lightbox'; // separated by spaces, e.g. 'img image-link' // check if there are already classes assigned to the anchor if ( preg_match('/<a.*? class=".*?">/', $html) ) { $html = preg_replace('/(<a.*? class=".*?)(".*?>)/', '$1 ' . $classes . '$2', $html); } else { $html = preg_replace('/(<a.*?)>/', '$1 class="' . $classes . '" >', $html); } return $html; } add_filter('image_send_to_editor','give_linked_images_class',10,8); /* =================================== Add Menus =================================== */ add_theme_support( 'menus' ); register_nav_menus( array( 'primary' => __( 'Main Menu', 'designcrumbs' ) ) ); /* ========================================= Featured Images ========================================= */ add_theme_support( 'post-thumbnails' ); /* ===== ADDS FEATURED IMAGE TO PAGES ===== */ add_image_size( 'blog_image', 590, 400, true ); /* ===== SETS FEATURED IMAGE SIZE ===== */ add_image_size( 'slide_image', 600, 300, true ); /* ===== SETS FEATURED IMAGE SIZE ===== */ add_image_size( 'single_latest', 170, 120, true ); /* ===== SETS FEATURED IMAGE SIZE ===== */ /* =================================== Add Slides Post Type =================================== */ register_post_type('slides', array( 'label' => __('Slides', 'designcrumbs'), 'singular_label' => __('Slide', 'designcrumbs'), 'public' => true, 'show_ui' => true, // UI in admin panel '_builtin' => false, // It's a custom post type, not built in! '_edit_link' => 'post.php?post=%d', 'capability_type' => 'post', 'hierarchical' => false, 'has_archive' => false, 'supports' => array( 'title', 'thumbnail',) )); /* ====================================================== Slide Meta Box ====================================================== */ add_filter( 'cmb_meta_boxes', 'dcs_metaboxes' ); function dcs_metaboxes( array $meta_boxes ) { $prefix = '_dc_'; $meta_boxes[] = array( 'id' => 'dc_slides_info', 'title' => __('Slide Contents (for image slide only)', 'designcrumbs'), 'pages' => array('slides'), // post type 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'fields' => array( array( 'name' => __('Slide Text', 'designcrumbs'), 'desc' => __('Enter text to be overlaid on the bottom of the slide image. Optional.', 'designcrumbs'), 'id' => $prefix . 'slide_text', 'type' => 'text' ), array( 'name' => __('Link', 'designcrumbs'), 'desc' => __('Enter a link (including the http://) if you would like the slide to link to somewhere. Optional.', 'designcrumbs'), 'id' => $prefix . 'slide_link', 'type' => 'text' ), ) ); $meta_boxes[] = array( 'id' => 'dc_slides', 'title' => __('Slide Video Embed', 'designcrumbs'), 'pages' => array('slides'), // post type 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'fields' => array( array( 'name' => __('Video oEmbed Link', 'designcrumbs'), 'desc' => __('Enter the full URL to your video. <a href="http://codex.wordpress.org/Embeds">Learn more about oEmbeds</a>.', 'designcrumbs'), 'id' => $prefix . 'video', 'type' => 'text' ), ) ); $meta_boxes[] = array( 'id' => 'dc_media', 'title' => __('Video Embeds', 'designcrumbs'), 'pages' => array('post'), // post type 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'fields' => array( array( 'name' => __('YouTube Video ID', 'designcrumbs'), 'desc' => __('If the YouTube link is http://www.youtube.com/watch?v=Iv69kB_e9KY, the ID is Iv69kB_e9KY. Enter that ID above.', 'designcrumbs'), 'id' => $prefix . 'media_youtube', 'type' => 'text' ), array( 'name' => __('Vimeo Video ID', 'designcrumbs'), 'desc' => __('If the Vimeo link is http://vimeo.com/22639018, the ID is 22639018. Enter that ID above.', 'designcrumbs'), 'id' => $prefix . 'media_vimeo', 'type' => 'text' ), ) ); return $meta_boxes; } add_action( 'init', 'dcs_initialize_cmb_meta_boxes', 9999 ); function dcs_initialize_cmb_meta_boxes() { if ( ! class_exists( 'cmb_Meta_Box' ) ) require_once 'lib/metabox/init.php'; } /* =================================== The Excerpt =================================== */ function improved_trim_excerpt($text) { global $post; if ( '' == $text ) { $text = get_the_content(''); $text = apply_filters('the_content', $text); $text = str_replace('\]\]\>', ']]&gt;', $text); $text = strip_tags($text, '<p>'); $excerpt_length = 85; $words = explode(' ', $text, $excerpt_length + 1); if (count($words)> $excerpt_length) { array_pop($words); array_push($words, '...'); $text = implode(' ', $words); } } return $text; } remove_filter('get_the_excerpt', 'wp_trim_excerpt'); add_filter('get_the_excerpt', 'improved_trim_excerpt'); /* =================================== Count How Many Widgets are in a Sidebar =================================== */ function count_sidebar_widgets( $sidebar_id, $echo = true ) { $the_sidebars = wp_get_sidebars_widgets(); if( !isset( $the_sidebars[$sidebar_id] ) ) return __( 'Invalid sidebar ID', 'designcrumbs' ); if( $echo ) echo count( $the_sidebars[$sidebar_id] ); else return count( $the_sidebars[$sidebar_id] ); } // To call it on the front end - count_sidebar_widgets( 'some-sidebar-id' ); /* ========================================= Checks for subcategories for the archives ========================================= */ // If is category or subcategory of $cat_id if (!function_exists('is_category_or_sub')) { function is_category_or_sub($cat_id = 0) { foreach (get_the_category() as $cat) { if ($cat_id == $cat->cat_ID || cat_is_ancestor_of($cat_id, $cat)) return true; } return false; } } /* ========================================= Creates function to check if single page is in child category ========================================= */ if ( ! function_exists( 'post_is_in_descendant_category' ) ) { function post_is_in_descendant_category( $cats, $_post = null ) { foreach ( (array) $cats as $cat ) { // get_term_children() accepts integer ID only $descendants = get_term_children( (int) $cat, 'category' ); if ( $descendants && in_category( $descendants, $_post ) ) return true; } return false; } } /* ========================================= Sidebars ========================================= */ if ( function_exists('register_sidebars') ) register_sidebar(array( 'name' => 'Overall_Sidebar', 'id' => 'Overall_Sidebar', 'description' => __('These widgets will show up on every page and post, including to the side of the home page.', 'designcrumbs'), 'before_widget' => '<div class="widget">', 'after_widget' => '</div>', 'before_title' => '<h4 class="widgettitle">', 'after_title' => '</h4>' )); register_sidebar(array( 'name' => 'Pages_Sidebar', 'id' => 'Pages_Sidebar', 'description' => __('These widgets will show up only on all pages, except the home page.', 'designcrumbs'), 'before_widget' => '<div class="widget">', 'after_widget' => '</div>', 'before_title' => '<h4 class="widgettitle">', 'after_title' => '</h4>' )); register_sidebar(array( 'name' => 'Blog_Sidebar', 'id' => 'Blog_Sidebar', 'description' => __('These widgets will show up in the blog and on blog posts.', 'designcrumbs'), 'before_widget' => '<div class="widget">', 'after_widget' => '</div>', 'before_title' => '<h4 class="widgettitle">', 'after_title' => '</h4>' )); register_sidebar(array( 'name' => 'Top_Sidebar', 'id' => 'Top_Sidebar', 'description' => __('You have room here for one widget to go next to the slider on the home page. It&#39;s recommended to put an email signup, such as the WP Email Capture plugin by <NAME>, or contact form here. On all other pages this widget will be displayed first in the sidebar', 'designcrumbs'), 'before_widget' => '<div class="widget">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widgettitle">', 'after_title' => '</h3>' )); register_sidebar(array( 'name' => 'Home_Page_Banner', 'id' => 'Home_Page_Banner', 'description' => __('These widgets show up in the banner just below the slider.', 'designcrumbs'), 'before_widget' => '<div class="widget">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widgettitle">', 'after_title' => '</h3>' )); register_sidebar(array( 'name' => 'Footer', 'id' => 'Footer', 'description' => __('These widgets will appear in the footer.', 'designcrumbs'), 'before_widget' => '<div class="footer_widget">', 'after_widget' => '</div>', 'before_title' => '<h6 class="widgettitle">', 'after_title' => '</h6>' )); /* =================================== User Extras =================================== */ add_action( 'show_user_profile', 'my_show_extra_profile_fields' ); add_action( 'edit_user_profile', 'my_show_extra_profile_fields' ); function my_show_extra_profile_fields( $user ) { ?> <h3><?php _e('Extra profile information', 'designcrumbs') ?></h3> <table class="form-table"> <tr> <th><label for="twitter"><?php _e('Twitter', 'designcrumbs') ?></label></th> <td> <input type="text" name="twitter" id="twitter" value="<?php echo esc_attr( get_the_author_meta( 'twitter', $user->ID ) ); ?>" class="regular-text" /><br /> <span class="description"><?php _e('Please enter your Twitter username without the @.', 'designcrumbs') ?></span> </td> </tr> </table> <?php } add_action( 'personal_options_update', 'my_save_extra_profile_fields' ); add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' ); function my_save_extra_profile_fields( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) return false; update_user_meta( $user_id, 'twitter', $_POST['twitter'] ); } function my_author_box() { ?> <div class="about_the_author"> <?php echo get_avatar( get_the_author_meta('email'), '70' ); ?> <div class="author_info"> <div class="author_title"><?php _e('This post was written by', 'designcrumbs') ?> <?php the_author_posts_link(); ?> </div> <div class="author_about"> <?php the_author_meta( 'description' ); ?> </div> <?php if (get_the_author_meta('twitter') != '' || get_the_author_meta('url') != '' ) { ?> <div class="author_links"> <?php if (get_the_author_meta('twitter') != '' ) { ?> <a href="http://twitter.com/<?php the_author_meta('twitter'); ?>" title="Follow <?php the_author_meta( 'display_name' ); ?> on Twitter"><?php _e('My Twitter', 'designcrumbs') ?> &raquo;</a> <?php } if (get_the_author_meta('url') != '' ) { ?> <a href="<?php the_author_meta('url'); ?>" title="My Website"><?php _e('My Website', 'designcrumbs') ?> &raquo;</a> <?php } ?> <div class="clear"></div> </div> <?php } // End check for twitter & url ?> </div> <div class="clear"></div> </div> <?php } /* =================================== Specific User Widget =================================== */ class featured_user_widget extends WP_Widget { //function to set up widget in admin function featured_user_widget() { $widget_ops = array( 'classname' => 'featured-user', 'description' => __('A widget that will display a specified user&#39;s gravatar, display name, bio, and link to their author post archive.', 'designcrumbs') ); $control_ops = array( 'width' => 200, 'height' => 350, 'id_base' => 'featured-user' ); parent::__construct( 'featured-user', __('Featured User', 'designcrumbs'), $widget_ops, $control_ops ); } //function to echo out widget on sidebar function widget( $args, $instance ) { extract( $args ); $title = $instance['title']; echo $before_widget; echo "<div class='featured_user'>"; // if user written title echo out if ( $title ){ echo $before_title . $title . $after_title; } //don't touch this! $userid = $instance['user_id']; //user information array //refer to http://codex.wordpress.org/Function_Reference/get_userdata $userinfo = get_userdata($userid); //user meta data //refer to http://codex.wordpress.org/Function_Reference/get_user_meta $userbio = get_user_meta($userid,'description',true); //user post url //refer to http://codex.wordpress.org/Function_Reference/get_author_posts_url $userposturl = get_author_posts_url($userid); ?> <!--Now we print out speciifc user informations to screen!--> <div class='specific_user'> <a href='<?php echo $userposturl; ?>' title='<?php echo $userinfo->display_name; ?>'> <?php echo get_avatar($userid,58); ?> </a> <strong> <a href='<?php echo $userposturl; ?>' title='<?php echo $userinfo->display_name; ?>' class='featured_user_name'> <?php echo $userinfo->display_name; ?> </a></strong> <?php echo $userbio; ?> <?php/* <a href='<?php echo $userposturl; ?>' title='<?php echo $userinfo->display_name; ?>'> View Author's Posts &raquo; </a> */ ?> <div class="clear"></div> </div> <!--end--> <?php echo '</div>'; echo $after_widget; }//end of function widget //function to update widget setting function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = strip_tags( $new_instance['title'] ); $instance['user_id'] = strip_tags( $new_instance['user_id'] ); return $instance; }//end of function update //function to create Widget Admin form function form($instance) { $instance = wp_parse_args( (array) $instance, array( 'title' => '','user_id' => '') ); $instance['title'] = $instance['title']; $instance['user_id'] = $instance['user_id']; ?> <p> <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Widget Title:', 'designcrumbs') ?></label> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $instance['title']; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'user_id' ); ?>"><?php _e('Select User:', 'designcrumbs') ?></label> <select id="<?php echo $this->get_field_id( 'user_id' );?>" name="<?php echo $this->get_field_name( 'user_id' );?>" class="widefat" style="width:100%;"> <?php $instance = $instance['user_id']; $option_list = user_get_users_list_option($instance); echo $option_list; ?> </select> </p> <?php }//end of function form($instance) }//end of Class //function to get all users function user_get_users_list_option($instance){ $output = ''; global $wpdb; $users = $wpdb->get_results("SELECT display_name, ID FROM $wpdb->users"); foreach($users as $u){ $uname = $u->display_name; $uid = $u->ID; $output .="<option value='$uid'"; if($instance == $uid){ $output.= 'selected="selected"'; } $output.= ">$uname</option>"; } return $output; } register_widget('featured_user_widget'); /* =================================== Testimonial Widget =================================== */ class TestimonialWidget extends WP_Widget { /** * Declares the TestimonialWidget class. * */ function TestimonialWidget(){ $widget_ops = array('classname' => 'widget_testimonial', 'description' => __('Displays a testimonial along with a name, company, and URL.', 'designcrumbs') ); $control_ops = array('width' => 300, 'height' => 300); parent::__construct('testimonial', __('Testimonial', 'designcrumbs'), $widget_ops, $control_ops); } /** * Displays the Widget * */ function widget($args, $instance){ extract($args); $testi_title = apply_filters('widget_title', empty($instance['testi_title']) ? '' : $instance['testi_title']); $testi_name = empty($instance['testi_name']) ? '' : $instance['testi_name']; $testi_company = empty($instance['testi_company']) ? '' : $instance['testi_company']; $testi_url = empty($instance['testi_url']) ? '' : $instance['testi_url']; $testi_testimonial = empty($instance['testi_testimonial']) ? '' : $instance['testi_testimonial']; # Before the widget echo '<div class="widget_testimonial widget">'; # The title if ( $testi_title ) echo $before_title . $testi_title . $after_title; echo '<div class="the_testimonial">'.$testi_testimonial . '</div>'; echo '<div class="the_testimonial_author">'; echo '<strong>- ' . $testi_name . '</strong>'; if ( $testi_url ) { echo '<span><a href="'.$testi_url.'" title="'.$testi_company.'">' . $testi_company . '</a></span>'; } else { echo '<span>' . $testi_company .'</span>';} echo '</div>'; echo '<div class="clear"></div>'; # After the widget echo '</div>'; } /** * Saves the widgets settings. * */ function update($new_instance, $old_instance){ $instance = $old_instance; $instance['testi_title'] = strip_tags(stripslashes($new_instance['testi_title'])); $instance['testi_name'] = strip_tags(stripslashes($new_instance['testi_name'])); $instance['testi_company'] = strip_tags(stripslashes($new_instance['testi_company'])); $instance['testi_url'] = strip_tags(stripslashes($new_instance['testi_url'])); $instance['testi_testimonial'] = strip_tags(stripslashes($new_instance['testi_testimonial'])); return $instance; } /** * Creates the edit form for the widget. * */ function form($instance){ //Defaults $testi_title = htmlspecialchars($instance['testi_title']); $testi_name = htmlspecialchars($instance['testi_name']); $testi_company = htmlspecialchars($instance['testi_company']); $testi_url = htmlspecialchars($instance['testi_url']); $testi_testimonial = htmlspecialchars($instance['testi_testimonial']); //output # Title echo '<p><label for="' . $this->get_field_name('testi_title') . '">' . __('Title (Optional):', 'designcrumbs') . '</label><input class="widefat" id="' . $this->get_field_id('testi_title') . '" name="' . $this->get_field_name('testi_title') . '" type="text" value="' . $testi_title . '" /></p>'; # Name echo '<p><label for="' . $this->get_field_name('testi_name') . '">' . __('Name:', 'designcrumbs') . '</label><input class="widefat" id="' . $this->get_field_id('testi_name') . '" name="' . $this->get_field_name('testi_name') . '" type="text" value="' . $testi_name . '" /></p>'; # Company echo '<p><label for="' . $this->get_field_name('testi_company') . '">' . __('Company:', 'designcrumbs') . '</label><input class="widefat" id="' . $this->get_field_id('testi_company') . '" name="' . $this->get_field_name('testi_company') . '" type="text" value="' . $testi_company . '" /></p>'; # URL echo '<p><label for="' . $this->get_field_name('testi_url') . '">' . __('URL:', 'designcrumbs') . '</label><input class="widefat" id="' . $this->get_field_id('testi_url') . '" name="' . $this->get_field_name('testi_url') . '" type="text" value="' . $testi_url . '" /></p>'; # Testimonial echo '<p><label for="' . $this->get_field_name('testi_testimonial') . '">' . __('The Testimonial:', 'designcrumbs') . '</label><textarea class="widefat" id="' . $this->get_field_id('testi_testimonial') . '" cols="20" rows="6" value="' . $testi_testimonial . '" name="' . $this->get_field_name('testi_testimonial') . '">' . $testi_testimonial . '</textarea></p>'; } }// END class function TestimonialInit() { register_widget('TestimonialWidget'); } add_action('widgets_init', 'TestimonialInit'); /* =================================== Text with a Button Widget =================================== */ class TextButtonWidget extends WP_Widget { /** * Declares the TextButtonWidget class. * */ function TextButtonWidget(){ $widget_ops = array('classname' => 'widget_text_button', 'description' => __('Arbitrary text or HTML along with a button.', 'designcrumbs') ); $control_ops = array('width' => 300, 'height' => 300); parent::__construct('text_button', __('Text with a Button', 'designcrumbs'), $widget_ops, $control_ops); } /** * Displays the Widget * */ function widget($args, $instance){ extract($args); $title = apply_filters('widget_title', empty($instance['title']) ? '' : $instance['title']); $the_button_text = empty($instance['the_button_text']) ? '' : $instance['the_button_text']; $the_button_link = empty($instance['the_button_link']) ? '' : $instance['the_button_link']; $button_type = empty($instance['button_type']) ? 'button' : $instance['button_type']; $the_message = empty($instance['the_message']) ? '' : $instance['the_message']; # Before the widget echo $before_widget; # The title if ( $title ) echo $before_title . $title . $after_title; echo '<div>' . $the_message . '</div><a href="' . $the_button_link . '" class="' . $button_type . '">' . $the_button_text . '</a>'; # After the widget echo $after_widget; } /** * Saves the widgets settings. * */ function update($new_instance, $old_instance){ $instance = $old_instance; $instance['title'] = strip_tags(stripslashes($new_instance['title'])); $instance['the_button_text'] = strip_tags(stripslashes($new_instance['the_button_text'])); $instance['the_button_link'] = strip_tags(stripslashes($new_instance['the_button_link'])); $instance['button_type'] = strip_tags(stripslashes($new_instance['button_type'])); $instance['the_message'] = strip_tags(stripslashes($new_instance['the_message'])); return $instance; } /** * Creates the edit form for the widget. * */ function form($instance){ //Defaults $title = htmlspecialchars($instance['title']); $the_button_text = htmlspecialchars($instance['the_button_text']); $the_button_link = htmlspecialchars($instance['the_button_link']); $button_type = htmlspecialchars($instance['button_type']); $the_message = htmlspecialchars($instance['the_message']); //output # Title echo '<label for="' . $this->get_field_name('title') . '">' . __('Title:', 'designcrumbs') . '</label><input class="widefat" id="' . $this->get_field_id('title') . '" name="' . $this->get_field_name('title') . '" type="text" value="' . $title . '" />'; # Message echo '<label for="' . $this->get_field_name('the_message') . '">' . __('The Message:', 'designcrumbs') . '</label><textarea class="widefat" id="' . $this->get_field_id('the_message') . '" cols="20" rows="6" value="' . $the_message . '" name="' . $this->get_field_name('the_message') . '">' . $the_message . '</textarea>'; # Button Text echo '<label for="' . $this->get_field_name('the_button_text') . '">' . __('Button Text:', 'designcrumbs') . '</label><input class="widefat" id="' . $this->get_field_id('the_button_text') . '" name="' . $this->get_field_name('the_button_text') . '" type="text" value="' . $the_button_text . '" />'; # Button Link echo '<label for="' . $this->get_field_name('the_button_link') . '">' . __('Button Link (including http):', 'designcrumbs') . '</label><input class="widefat" id="' . $this->get_field_id('the_button_link') . '" name="' . $this->get_field_name('the_button_link') . '" type="text" value="' . $the_button_link . '" />'; # Button Type echo '<label for="' . $this->get_field_name('button_type') . '">' . __('Button Color:', 'designcrumbs') . '</label><select class="widefat" id="' . $this->get_field_id('button_type') . '" name="' . $this->get_field_name('button_type') . '"><option value="button" '. ( ($button_type == "button") ? "selected='selected'" : "") .'>' . __('Blue', 'designcrumbs') . '</option><option value="button button_red" '. ( ($button_type == "button button_red") ? "selected='selected'" : "") .'>' . __('Red', 'designcrumbs') . '</option><option value="button button_gray" '. ( ($button_type == "button button_gray") ? "selected='selected'" : "") .'>' . __('Gray', 'designcrumbs') . '</option></select>'; } }// END class function TextButtonInit() { register_widget('TextButtonWidget'); } add_action('widgets_init', 'TextButtonInit'); /* =================================== SlabText Widget =================================== */ class SlabTextWidget extends WP_Widget { /** * Declares the SlabTextWidget class. * */ function SlabTextWidget(){ $widget_ops = array('classname' => 'widget_slabtext', 'description' => __('Text headline that forms the area it&#39;s in to make some cool typography.', 'designcrumbs') ); $control_ops = array('width' => 300, 'height' => 300); parent::__construct('slabtext', __('Slab Text', 'designcrumbs'), $widget_ops, $control_ops); } /** * Displays the Widget * */ function widget($args, $instance){ extract($args); $line1 = empty($instance['line1']) ? '' : $instance['line1']; $line2 = empty($instance['line2']) ? '' : $instance['line2']; $line3 = empty($instance['line3']) ? '' : $instance['line3']; $line4 = empty($instance['line4']) ? '' : $instance['line4']; $line5 = empty($instance['line5']) ? '' : $instance['line5']; # Before the widget echo $before_widget; echo '<div class="slabload"> <div class="slabwrap"> <h1 class="slabtextdone"> <span class="slabtext">'. strtoupper($line1) .'</span> <span class="slabtext">'. strtoupper($line2) .'</span> <span class="slabtext">'. strtoupper($line3) .'</span> <span class="slabtext">'. strtoupper($line4) .'</span> <span class="slabtext">'. strtoupper($line5) .'</span> </h1> </div> </div>'; # After the widget echo $after_widget; } /** * Saves the widgets settings. * */ function update($new_instance, $old_instance){ $instance = $old_instance; $instance['line1'] = strip_tags(stripslashes($new_instance['line1'])); $instance['line2'] = strip_tags(stripslashes($new_instance['line2'])); $instance['line3'] = strip_tags(stripslashes($new_instance['line3'])); $instance['line4'] = strip_tags(stripslashes($new_instance['line4'])); $instance['line5'] = strip_tags(stripslashes($new_instance['line5'])); return $instance; } /** * Creates the edit form for the widget. * */ function form($instance){ //Defaults $line1 = htmlspecialchars($instance['line1']); $line2 = htmlspecialchars($instance['line2']); $line3 = htmlspecialchars($instance['line3']); $line4 = htmlspecialchars($instance['line4']); $line5 = htmlspecialchars($instance['line5']); //output # Line1 echo '<label for="' . $this->get_field_name('line1') . '">' . __('Line 1:', 'designcrumbs') . '</label><input class="widefat" id="' . $this->get_field_id('line1') . '" name="' . $this->get_field_name('line1') . '" type="text" value="' . $line1 . '" />'; # Line2 echo '<label for="' . $this->get_field_name('line1') . '">' . __('Line 2:', 'designcrumbs') . '</label><input class="widefat" id="' . $this->get_field_id('line2') . '" name="' . $this->get_field_name('line2') . '" type="text" value="' . $line2 . '" />'; # Line3 echo '<label for="' . $this->get_field_name('line1') . '">' . __('Line 3:', 'designcrumbs') . '</label><input class="widefat" id="' . $this->get_field_id('line3') . '" name="' . $this->get_field_name('line3') . '" type="text" value="' . $line3 . '" />'; # Line4 echo '<label for="' . $this->get_field_name('line1') . '">' . __('Line 4:', 'designcrumbs') . '</label><input class="widefat" id="' . $this->get_field_id('line4') . '" name="' . $this->get_field_name('line4') . '" type="text" value="' . $line4 . '" />'; # Line5 echo '<label for="' . $this->get_field_name('line1') . '">' . __('Line 5:', 'designcrumbs') . '</label><input class="widefat" id="' . $this->get_field_id('line5') . '" name="' . $this->get_field_name('line5') . '" type="text" value="' . $line5 . '" />'; } }// END class function SlabTextWidget() { register_widget('SlabTextWidget'); } add_action('widgets_init', 'SlabTextWidget'); /* ====================================================== COMMENTS ====================================================== */ function custom_comment($comment, $args, $depth) { $GLOBALS['comment'] = $comment; ?> <li <?php comment_class(); ?> id="comment-<?php comment_ID( ); ?>"> <div class="the_comment"> <?php if(function_exists('get_avatar')) { echo get_avatar($comment, '50'); } ?> <div class="the_comment_author"><strong><?php comment_author_link() ?></strong> <?php _e('says', 'designcrumbs'); ?></div> <?php if ($comment->comment_approved == '0') : //message if comment is held for moderation ?> <br><em><?php _e('Your comment is awaiting moderation', 'designcrumbs'); ?>.</em><br> <?php endif; ?> <div class="the_comment_text"><?php comment_text() ?></div> <small class="commentmetadata"> <?php comment_date(get_option( 'date_format' )) ?> - <?php comment_date('g:i a') ?> - <a href="<?php comment_link() ?>" class="comment_permalink"><?php _e('Permalink', 'designcrumbs'); ?></a> </small> <div class="reply"> <?php edit_comment_link( __('Edit', 'designcrumbs'),'',' &nbsp;|&nbsp; '); ?><?php echo comment_reply_link(array('reply_text' => __('Reply', 'designcrumbs'), 'depth' => $depth, 'max_depth' => $args['max_depth'])); ?> </div> <div class="clear"></div> </div> <?php } function custom_pings($comment, $args, $depth) { $GLOBALS['comment'] = $comment; ?> <li <?php comment_class(); ?> id="comment-<?php comment_ID( ); ?>"> <?php _e('Trackback from', 'designcrumbs'); ?> <em><?php comment_author_link() ?></em> <div class="the_comment_text"><?php comment_text() ?></div> <small class="commentmetadata"> <?php comment_date(get_option( 'date_format' )) ?> </small> <div class="clear"></div> <?php }<file_sep><?php function dcs_load_scripts() { // load WP's included jQuery library wp_enqueue_script('jquery'); // global scripts wp_enqueue_script('jquery-slabtext', get_template_directory_uri() . '/includes/js/jquery.slabtext.min.js'); wp_enqueue_script('jquery-easing', get_template_directory_uri() . '/includes/js/jquery.easing.1.3.js'); wp_enqueue_script('jquery-fancybox', get_template_directory_uri() . '/includes/fancybox/jquery.fancybox.js'); wp_enqueue_script('jquery-mobilemenu', get_template_directory_uri() . '/includes/js/jquery.mobilemenu.js'); wp_enqueue_script('jquery-fitvids', get_template_directory_uri() . '/includes/js/jquery.fitvids.js'); // front page scripts if (is_front_page()) { wp_enqueue_script('jquery-slides', get_template_directory_uri() . '/includes/js/flexslider/jquery.flexslider.js'); wp_enqueue_style('css-flexslider', get_template_directory_uri() . '/includes/js/flexslider/flexslider.css'); } // sticky header if ((of_get_option('sticky_header') == 'yes') && (of_get_option('body_display') == 'body_span')) { wp_enqueue_script('jquery-sticky', get_template_directory_uri() . '/includes/js/jquery.sticky.js'); } // load singular (posts and pages) scripts if ( is_singular() ) { wp_enqueue_script( 'comment-reply' ); //enable nested comments } // global styles wp_enqueue_style('css-fancybox', get_template_directory_uri() . '/includes/fancybox/jquery.fancybox.css'); wp_enqueue_style('heading-font', get_template_directory_uri() . '/fonts/style-' . stripslashes(of_get_option('heading_font')) . '.css'); // load in footer function dcs_add_footer_js() { get_template_part('includes/js/campaignjs'); } add_action('wp_footer', 'dcs_add_footer_js'); } add_action('wp_enqueue_scripts', 'dcs_load_scripts');
6612c6c8d51644ae96aa9258ce22614d333d2fd8
[ "PHP" ]
10
PHP
JPBetley/cirofordelaware
b0180e082e54b396de7d9971a6aa18ce6ec05120
8033ea4268be8e1ef5d31cecb765f4e43d755334
refs/heads/master
<file_sep>import React from 'react'; import { Animated, Easing, Keyboard, Platform, StyleSheet, TouchableWithoutFeedback, } from 'react-native'; export class AvoidKeyboard extends React.Component { static defaultProps = { offset: height => height, autoDismiss: true, }; translateY = new Animated.Value(0); animationDuration = Platform.select({ android: 160, default: 250, }); // @ts-ignore showEvent = Platform.select({ android: 'keyboardDidShow', default: 'keyboardWillShow', }); // @ts-ignore hideEvent = Platform.select({ android: 'keyboardDidHide', default: 'keyboardWillHide', }); keyboardShowSubscription; keyboardHideSubscription; componentDidMount() { this.keyboardShowSubscription = Keyboard.addListener( this.showEvent, this.onKeyboardShow, ); this.keyboardHideSubscription = Keyboard.addListener( this.hideEvent, this.onKeyboardHide, ); } componentWillUnmount() { this.keyboardShowSubscription.remove(); this.keyboardHideSubscription.remove(); } onKeyboardShow = event => { const offset = -this.props.offset(event.endCoordinates.height); this.createTranslateAnimation({offset}).start(); }; onKeyboardHide = event => { const offset = 0; this.createTranslateAnimation({offset}).start(); }; onContainerPress = () => { Keyboard.dismiss(); }; getComponentStyle = source => { return { ...styles.container, ...styles.transform(this.translateY), ...StyleSheet.flatten(source), }; }; createTranslateAnimation = params => { const {offset} = params; return Animated.timing(this.translateY, { toValue: offset, duration: this.animationDuration, easing: Easing.linear, }); }; render() { const {style, autoDismiss, ...restProps} = this.props; const componentStyle = this.getComponentStyle(style); return ( <TouchableWithoutFeedback onPress={this.onContainerPress} disabled={!autoDismiss}> <Animated.View style={componentStyle} {...restProps} /> </TouchableWithoutFeedback> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, // @ts-ignore transform: y => ({ transform: [{translateY: y}], }), }); <file_sep>/** * Sample React Native App * https://github.com/facebook/react-native * * Generated with the UI Kitten template * https://github.com/akveo/react-native-ui-kitten * * Documentation: https://akveo.github.io/react-native-ui-kitten/docs * * @format */ import React from 'react'; import {AsyncStorage} from 'react-native'; import { ApplicationProvider, Button, Icon, IconRegistry, Layout, Text, } from 'react-native-ui-kitten'; // import {ApplicationLoader} from './src/core/appLoader/applicationLoader'; import {mapping, light as theme} from '@eva-design/eva'; import {EvaIconsPack} from '@ui-kitten/eva-icons'; import {AppNavigator} from './src/components/AppNavigator'; import FlashMessage, {showMessage} from 'react-native-flash-message'; import SplashScreen from 'react-native-splash-screen'; import axios from 'axios'; import _ from 'lodash'; /** * Use any valid `name` property from eva icons (e.g `github`, or `heart-outline`) * https://akveo.github.io/eva-icons */ function wait(timeout) { return new Promise(resolve => { setTimeout(resolve, timeout); }); } class App extends React.Component { componentDidMount() { // this.messageChecker(); AsyncStorage.setItem( 'chatContext', JSON.stringify({ chatMsno: 0, msno: 0, latestId: 0, messages: [], }), ); this.listenChatMessage(); SplashScreen.hide(); } messageChecker = async () => { AsyncStorage.getItem('user') .then(userData => { // init local messages if (userData) { var user = JSON.parse(userData); axios({ method: 'get', url: 'https://kkfriends.app/chat-list', params: { msno_view: user['msno'], }, }).then(res => { var data = res.data; var chats = JSON.stringify(data['chats']); AsyncStorage.setItem('localChatList', chats).then(() => { AsyncStorage.setItem('remoteChatList', chats); }); }); } }) .then(() => { this.listenMessageCheck().catch(e => alert(e)); }); }; listenChatMessage = async () => { while (true) { await wait(2000).then(() => { AsyncStorage.getItem('chatContext').then(chatContextJson => { var chatContext = JSON.parse(chatContextJson); if (chatContext['msno'] > 0 && chatContext['chatMsno'] > 0) { axios .get('https://kkfriends.app/chat-message-after-id', { params: { msno_view: chatContext['msno'], msno_with: chatContext['chatMsno'], id: chatContext['latestId'], }, }) .then(res => { var data = res.data; var messages = data['messages']; if (messages.length > 0) { chatContext['messages'] = chatContext['messages'].concat( messages, ); chatContext['latestId'] = messages[messages.length - 1]['id']; AsyncStorage.setItem( 'chatContext', JSON.stringify(chatContext), ); } }); } }); }); } }; listenMessageCheck = async () => { while (true) { await wait(10000).then(() => { AsyncStorage.getItem('user').then(userData => { AsyncStorage.getItem('localChatList').then(localChatList => { var user = JSON.parse(userData); axios({ method: 'get', url: 'https://kkfriends.app/chat-list', params: { msno_view: user['msno'], }, }).then(res => { var data = res.data; var local = JSON.parse(localChatList); var remote = data['chats']; if (local && remote) { if (local.length > 0 && remote.length > 0) { if (_.has(local[0], 'ts') && _.has(remote[0], 'ts')) { if ( local[0]['ts'] !== remote[0]['ts'] && remote[0]['message_latest_msno'] !== user['msno'] ) { AsyncStorage.setItem( 'localChatList', JSON.stringify(remote), ).then(res => { showMessage({ message: 'ๆ‚จๆœ‰ๆ–ฐ่จŠๆฏ', description: `${remote[0]['user_t']['name']} : ${remote[0]['message']}`, type: 'info', }); }); } } } } }); }); }); }); } }; render() { return ( <React.Fragment> <IconRegistry icons={EvaIconsPack} /> <ApplicationProvider mapping={mapping} theme={theme}> <AppNavigator /> <FlashMessage position={'top'} /> </ApplicationProvider> </React.Fragment> ); } } export default App; <file_sep>import React from 'react'; import {ActivityIndicator, StatusBar, View, AsyncStorage} from 'react-native'; export class AuthLoading extends React.Component { componentDidMount() { this.bootstrapAsync(); } bootstrapAsync = async () => { const userToken = await AsyncStorage.getItem('user'); this.props.navigation.navigate(userToken ? 'App' : 'Auth'); }; render() { return ( <View> <ActivityIndicator /> <StatusBar barStyle="default" /> </View> ); } } <file_sep>import React from 'react'; import {View} from 'react-native'; import {withStyles, Text} from 'react-native-ui-kitten'; import {ProfileParameter} from '../../profile/profileParameter'; import {ImageOverlay} from '../../common/imageOverlay'; import {textStyle} from '../../common/style'; import _ from 'lodash'; class ProfileInfoComponent extends React.Component { render() { const {themedStyle, profile} = this.props; return ( <ImageOverlay style={themedStyle.container} source={{uri: profile.photo.imageSource}}> <View style={themedStyle.infoContainer}> <Text style={themedStyle.nameLabel} category="h2"> {`${profile.firstName}\n${profile.lastName}`} </Text> <Text style={themedStyle.locationLabel} category="h6"> {profile.location} </Text> <Text style={themedStyle.jobLabel} category="h6"> {profile.job} </Text> <View style={themedStyle.parametersContainer}> <ProfileParameter hint="ๅ–œๅฅฝ่—ไบบ" value={`${profile.artists[0] ? profile.artists[0] : '<NAME>'}`} /> <ProfileParameter hint="ๅ–œๅฅฝ้กžๅž‹" value={`${profile.categories[0]}`} /> </View> <View style={themedStyle.parametersContainer}> <ProfileParameter hint="ๅ–œๅฅฝๆญŒๆ›ฒ" value={`${ _.has(profile.currentFavSongs[0], 'name') ? profile.currentFavSongs[0]['name'] : 'ๅ…จไธ–็•Œ็š„ๆœ‹ๅ‹้ƒฝ่ฎ“ๆˆ‘ๅคฑๆœ›' }`} /> </View> </View> </ImageOverlay> ); } } export const ProfileInfo = withStyles(ProfileInfoComponent, theme => ({ container: { flex: 1, }, infoContainer: { position: 'absolute', paddingHorizontal: 24, paddingBottom: 32, left: 0, right: 0, bottom: 0, }, parametersContainer: { flexDirection: 'row', justifyContent: 'space-between', marginTop: 64, }, nameLabel: { color: 'white', ...textStyle.headline, }, locationLabel: { color: 'white', ...textStyle.headline, }, jobLabel: { color: 'white', ...textStyle.headline, }, rateHintLabel: { color: 'white', }, })); <file_sep>import React from 'react'; import {Dimensions, View} from 'react-native'; import {withStyles, Text} from 'react-native-ui-kitten'; import {textStyle} from '../../components/common/style'; import {MessageContent} from './MessageContentComponent'; class LeftMessageComponent extends React.Component { render() { const {themedStyle, message, children} = this.props; return [ <View style={themedStyle.cloudContainer} key={0}> <View style={[themedStyle.triangle, themedStyle.triangleLeft]} /> <View style={[themedStyle.cloud, themedStyle.cloudLeft]}> <MessageContent message={message}>{children}</MessageContent> </View> </View>, <Text key={1} style={themedStyle.dateLabel} appearance="hint" category="c1"> {message.date} </Text>, ]; } } export const LeftMessage = withStyles(LeftMessageComponent, theme => ({ triangle: { borderLeftWidth: 10, borderRightWidth: 10, borderBottomWidth: 15, borderLeftColor: 'transparent', borderRightColor: 'transparent', backgroundColor: 'transparent', }, triangleLeft: { transform: [{rotate: '-90deg'}], borderBottomColor: theme['color-primary-default'], }, cloudContainer: { flexDirection: 'row', alignItems: 'center', }, dateLabel: textStyle.caption1, cloud: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', padding: 16, borderRadius: 8, maxWidth: Dimensions.get('window').width - 120, }, cloudLeft: { left: -3, backgroundColor: theme['color-primary-default'], marginRight: 16, }, })); <file_sep>import React from 'react'; import {View} from 'react-native'; import {Button, Text, withStyles} from 'react-native-ui-kitten'; import {SignInForm2} from '../components/SignInForm'; import {SocialAuth} from '../../auth/SocialAuth'; import {ScrollableAvoidKeyboard} from '../../common/scrollableAvoidKeyboard'; import {textStyle} from '../../common/style'; import {ImageOverlay} from '../../common/imageOverlay'; const imageSignIn4Bg = { imageSource: require('../../../../assets/img/julia-bg.jpg'), }; class SignInComponent extends React.Component { state = { formData: undefined, }; backgroundImage = imageSignIn4Bg; onForgotPasswordButtonPress = () => { this.props.onForgotPasswordPress(); }; onSignInButtonPress = () => { this.props.onSignInPress(this.state.formData); }; onSignUpButtonPress = () => { this.props.onSignUpPress(); }; onGoogleButtonPress = () => { this.props.onGooglePress(); }; onFacebookButtonPress = () => { this.props.onFacebookPress(); }; onTwitterButtonPress = () => { this.props.onTwitterPress(); }; onFormDataChange = formData => { this.setState({formData}); }; render() { const {themedStyle} = this.props; return ( <ScrollableAvoidKeyboard> <ImageOverlay style={themedStyle.container} source={this.backgroundImage.imageSource}> <View style={themedStyle.headerContainer}> <Text style={themedStyle.helloLabel} category="h1"> Welcome to KKMeet </Text> <Text style={themedStyle.signInLabel} category="s1"> Sign in to your account </Text> </View> <SignInForm2 style={themedStyle.formContainer} onForgotPasswordPress={this.onForgotPasswordButtonPress} onDataChange={this.onFormDataChange} /> <Button style={themedStyle.signInButton} textStyle={textStyle.button} size="giant" disabled={!this.state.formData} onPress={this.onSignInButtonPress}> SIGN IN </Button> <SocialAuth style={themedStyle.socialAuthContainer} iconStyle={themedStyle.socialAuthIcon} hint="Or Sign In using Social Media" onGooglePress={this.onGoogleButtonPress} onFacebookPress={this.onFacebookButtonPress} onTwitterPress={this.onTwitterButtonPress} /> <Button style={themedStyle.signUpButton} textStyle={themedStyle.signUpText} appearance="ghost" activeOpacity={0.75} onPress={this.onSignUpButtonPress}> Don't have an account? Sign Up </Button> </ImageOverlay> </ScrollableAvoidKeyboard> ); } } export const SignIn = withStyles(SignInComponent, theme => ({ container: { flex: 1, }, headerContainer: { minHeight: 216, justifyContent: 'center', alignItems: 'center', }, formContainer: { flex: 1, paddingHorizontal: 16, }, socialAuthContainer: { marginTop: 32, }, helloLabel: { color: 'white', ...textStyle.headline, }, signInLabel: { marginTop: 16, color: 'white', ...textStyle.subtitle, }, socialAuthIcon: { tintColor: 'white', }, signInButton: { marginHorizontal: 16, }, signUpButton: { marginVertical: 12, }, signUpText: { color: 'white', ...textStyle.subtitle, }, })); <file_sep>import React from 'react'; import {AsyncStorage, View, ActivityIndicator, Dimensions} from 'react-native'; import {withStyles} from 'react-native-ui-kitten'; import {PARTNER_IMGS} from '../../../core/data/default'; import {ProfileInfo} from '../components/ProfileInfo'; import _ from 'lodash'; const default_songs = [ { name: 'ๅ…จไธ–็•Œ็š„ๆœ‹ๅ‹้ƒฝ่ฎ“ๆˆ‘ๅคฑๆœ›', album_id: 66519282, album_img_url: 'https://i.kfs.io/album/global/66519282,0v1/fit/300x300.jpg', }, ]; class ProfileDemoComponent extends React.Component { state = { profile: { photo: {imageSource: ''}, about: '', firstName: '', lastName: '', gender: '', age: 0, weight: 0, height: 0, job: '', inseam: 0, email: '', phoneNumber: '0', location: '', friends: [], online: true, categories: [], artists: [], currentFavSongs: [], }, isLoaded: false, }; componentDidMount = () => { AsyncStorage.getItem('profile').then(res => { var data = JSON.parse(res); var profile = { photo: _.has(PARTNER_IMGS, data['interlocutor']['msno']) ? {imageSource: PARTNER_IMGS[data['interlocutor']['msno']]} : data['interlocutor']['photo'], about: '', firstName: data['interlocutor']['firstName'], lastName: '', gender: data['interlocutor']['gender'], age: 0, weight: 0, height: 0, job: '', inseam: 0, email: data['interlocutor']['email'], phoneNumber: '0', location: 'Taipei, Taiwan', friends: [], online: true, categories: _.has(data, 'categories') ? data['categories'] : ['R&B'], artists: _.has(data, 'artists') ? data['artists'] : ['<NAME>'], currentFavSongs: _.has(data, 'currentFavSongs') ? data['currentFavSongs'] : default_songs, }; this.setState({profile: profile, isLoaded: true}); }); }; onRateChange = value => {}; render() { if (this.state.isLoaded === true) { return ( <ProfileInfo profile={this.state.profile} onRateChange={this.onRateChange} /> ); } else { const {themedStyle} = this.props; return ( <View style={themedStyle.loadContainer}> <ActivityIndicator size="large" /> </View> ); } } } export const ProfileDemo = withStyles(ProfileDemoComponent, theme => ({ loadContainer: { height: Dimensions.get('window').height, width: Dimensions.get('window').width, justifyContent: 'center', }, })); <file_sep>import React from 'react'; import {View} from 'react-native'; import {withStyles} from 'react-native-ui-kitten'; import {getContentAlignment} from './type'; import {getMessageContent} from './MessageContent'; class ChatMessageComponent extends React.Component { render() { const {alignment, style, message, children} = this.props; const flexStyle = getContentAlignment(alignment).style(); const content = getMessageContent(alignment).view(message, children); return <View style={[flexStyle, style]}>{content}</View>; } } export const ChatMessage = withStyles(ChatMessageComponent, theme => ({})); <file_sep>import React from 'react'; import {View} from 'react-native'; import {withStyles, List, Input, Icon} from 'react-native-ui-kitten'; import {Conversation} from '../../messages/Conversation'; import {textStyle} from '../../common/style'; const SearchIconOutline = style => <Icon name="search-outline" {...style} />; class ChatListComponent extends React.Component { onConversation = index => { this.props.onConversation(index); }; ponSearchStringChange = text => { this.props.onSearchStringChange(text); }; renderItem = info => { const {themedStyle} = this.props; return ( <Conversation style={themedStyle.item} conversation={info.item} index={info.index} onConversation={this.onConversation} /> ); }; renderSearchInput = () => { const {themedStyle, searchEnabled} = this.props; return searchEnabled ? ( <Input style={themedStyle.input} textStyle={textStyle.paragraph} icon={SearchIconOutline} placeholder="Search Interlocutor..." onChangeText={this.onSearchStringChange} /> ) : null; }; render() { const {themedStyle, conversations} = this.props; return ( <View style={themedStyle.container}> {this.renderSearchInput()} <List style={themedStyle.container} data={conversations} renderItem={this.renderItem} /> </View> ); } } export const ChatList = withStyles(ChatListComponent, theme => ({ container: { flex: 1, backgroundColor: theme['background-basic-color-2'], }, item: { backgroundColor: theme['background-basic-color-1'], marginVertical: 0.5, }, input: { marginHorizontal: 16, marginVertical: 16, }, })); <file_sep>import React from 'react'; import { ScrollView, AsyncStorage, View, Alert, ActivityIndicator, } from 'react-native'; import {SafeAreaView} from 'react-navigation'; import {categorisedProfileActivity1} from '../../../core/data/profile'; import {PARTNER_IMGS} from '../../../core/data/default'; import {ProfileHeader} from '../../profile/profileHeader'; import {Profile} from '../components/ProfilePage'; import axios from 'axios'; import _ from 'lodash'; const default_songs = [ { name: 'ๅ…จไธ–็•Œ็š„ๆœ‹ๅ‹้ƒฝ่ฎ“ๆˆ‘ๅคฑๆœ›', album_id: 66519282, album_img_url: 'https://i.kfs.io/album/global/66519282,0v1/fit/300x300.jpg', }, ]; export class ProfilePageDemo extends React.Component { state = { profile: {}, socials: { followers: 0, following: 0, friends: 0, }, favorites: { artists: [], categories: [], currentFavSongs: [], }, activity: categorisedProfileActivity1, liked: false, shared: false, isLoaded: false, isSelf: false, matched: false, coverPlayList: {}, sharedPlayLists: {}, modalVisible: false, modalIndex: 0, shareModalVisible: false, }; static navigationOptions = ({navigation, screenProps}) => { const headerProps = { onBack: navigation.getParam('onBack', () => {}), }; const header = navigationProps => { return <ProfileHeader {...navigationProps} {...headerProps} />; }; return {...navigation, ...screenProps, header}; }; formatSharedPlayLists = sharedPlayLists => { var newSharedPlayLists = _.map(sharedPlayLists, playlist => { var newPlayList = { category: 'SharedPlayList', source: { imageSource: `https://i.kfs.io/album/global/${playlist['songs'][0]['album_id']},0v9/fit/300x300.jpg`, }, playlistName: playlist['name'], songs: _.map(playlist['songs'], song => { var newSong = { songName: song['song_name'], source: { imageSource: `https://i.kfs.io/album/global/${song['album_id']},0v9/fit/300x300.jpg`, }, }; return newSong; }), }; return newPlayList; }); newSharedPlayLists = { ['่ˆ‡ๆˆ‘ๅˆ†ไบซ']: newSharedPlayLists, }; return newSharedPlayLists; }; formatPlayList = playlist => { var newPlayList = _.map(playlist, song => { var formatSong = { category: 'MyPlayList', source: {imageSource: song['album_img_url']}, songName: song['song_name'], }; return formatSong; }); newPlayList = { ['ๆˆ‘็š„ๆญŒๅ–ฎ']: newPlayList, }; return newPlayList; }; formatProfile = profile => { var newProfile = { photo: { imageSource: _.has(PARTNER_IMGS, profile['msno']) ? PARTNER_IMGS[profile['msno']] : profile['img_url'], }, about: '', firstName: profile['name'], lastName: '', gender: profile['gender'], age: 0, weight: 0, height: 0, job: '', inseam: 0, email: profile['email'], phoneNumber: '0', location: 'Taipei, Taiwan', friends: [], online: true, msno: profile['msno'], }; return newProfile; }; getSocials = () => { axios({ method: 'get', url: 'https://kkfriends.app/follow-list', params: { msno: this.props.navigation.getParam('msno'), }, }).then(res => { var data = res.data; var friends = data['friends']; var followers = data['followed']; var following = data['following']; followers = followers.concat(friends); following = following.concat(friends); var socials = { followers: followers.length, following: following.length, friends: friends, }; this.setState({socials: socials}); }); }; componentDidMount() { this.props.navigation.setParams({ onBack: this.onBackPress, }); axios({ method: 'get', url: 'https://kkfriends.app/user-profile', params: { msno_view: this.props.navigation.getParam('msnoView'), msno: this.props.navigation.getParam('msno'), }, }).then(res => { AsyncStorage.getItem('profile').then(profile => { var selfProfile = JSON.parse(profile); var data = res.data; var user = data['user']; var coverPlayList = data['cover_playlist']; var favorites = data['profile']; var followStatus = data['follow_status']; var sharedPlayLists = data['shared_playlists']; sharedPlayLists = this.formatSharedPlayLists(sharedPlayLists); coverPlayList = this.formatPlayList(coverPlayList); user = this.formatProfile(user); selfProfile = selfProfile['interlocutor']; if ( this.props.navigation.getParam('msnoView') === this.props.navigation.getParam('msno') ) { this.setState({isSelf: true}); } this.getSocials(); this.getMyBoxPlaylists(); this.setState({ isLoaded: true, user: user, favorites: { artists: _.has(favorites, 'artists') ? favorites['artists'] : ['<NAME>'], categories: _.has(favorites, 'categories') ? favorites['categories'] : ['R&B'], current_fav_songs: _.has(favorites, 'current_fav_songs') ? favorites['current_fav_songs'] : default_songs, }, selfProfile: selfProfile, coverPlayList: coverPlayList, sharedPlayLists: sharedPlayLists, liked: followStatus['is_following'], matched: followStatus['is_friend'], }); }); }); } getSharedPlayLists = () => { axios({ method: 'get', url: 'https://kkfriends.app/user-profile', params: { msno: this.props.navigation.getParam('msno'), msno_view: this.props.navigation.getParam('msnoView'), }, }).then(res => { var data = res.data; var sharedPlayLists = data['shared_playlists']; sharedPlayLists = this.formatSharedPlayLists(sharedPlayLists); this.setState({ sharedPlayLists: sharedPlayLists, }); }); }; getFollowStatus = () => { axios({ method: 'get', url: 'https://kkfriends.app/user-profile', params: { msno_view: this.props.navigation.getParam('msnoView'), msno: this.props.navigation.getParam('msno'), }, }).then(res => { var data = res.data; var followStatus = data['follow_status']; this.setState({matched: followStatus['is_friend']}); }); }; onFollowPress = () => { if (this.state.liked === true) { axios({ method: 'get', url: 'https://kkfriends.app/follower-unfollow', params: { msno_f: this.props.navigation.getParam('msnoView'), msno_t: this.props.navigation.getParam('msno'), }, }) .then(res => { this.setState({liked: false}); }) .then(() => { this.getSocials(); this.getFollowStatus(); }); } else { axios({ method: 'get', url: 'https://kkfriends.app/follower-follow', params: { msno_f: this.props.navigation.getParam('msnoView'), msno_t: this.props.navigation.getParam('msno'), }, }) .then(res => { this.setState({liked: true}); }) .then(() => { this.getSocials(); this.getFollowStatus(); }); } }; getMyBoxPlaylists = () => { axios({ method: 'get', url: 'https://kkfriends.app/mybox-playlist-share', params: { msno: this.props.navigation.getParam('msnoView'), share_msno: this.props.navigation.getParam('msno'), }, }).then(res => { var data = res.data; var playlists = data['playlists']; this.setState({myBoxPlayLists: playlists}); }); }; addShareList = data => { var playlistID = data['playlistID']; axios({ method: 'get', url: 'https://kkfriends.app/playlist-share-insert', params: { owner_msno: this.props.navigation.getParam('msnoView'), share_msno: this.props.navigation.getParam('msno'), playlist_id: playlistID, }, }).then(res => { this.getSharedPlayLists(); }); }; onPlayListSelected = option => { this.addShareList(option); if (option.isShared) { Alert.alert(option.label, 'ๅˆ†ไบซ้Žๅ›‰!'); } else { Alert.alert(option.label, 'ๅทฒๅˆ†ไบซ!'); } }; onShareModalClose = () => { this.setState({shareModalVisible: false}); }; onSharedPlayListPress = index => { this.setState({modalIndex: index, modalVisible: true}); }; onSharePress = () => { this.setState({shareModalVisible: true}); }; onSwipeComplete = () => { this.setState({modalVisible: false}); }; handleNavigateBack = () => {}; onMessagePress = () => { if (this.props.navigation.getParam('stack') === 'Discover') { this.props.navigation.push('DiscoverChatScreen', { msnoFrom: this.props.navigation.getParam('msnoView'), msnoTo: this.props.navigation.getParam('msno'), onNavigateBack: this.handleNavigateBack, stack: this.props.navigation.getParam('stack'), selfProfile: this.state.selfProfile, otherProfile: this.state.user, }); } else if (this.props.navigation.getParam('stack') === 'Friends') { this.props.navigation.push('FriendChatScreen', { msnoFrom: this.props.navigation.getParam('msnoView'), msnoTo: this.props.navigation.getParam('msno'), onNavigateBack: this.handleNavigateBack, stack: this.props.navigation.getParam('stack'), selfProfile: this.state.selfProfile, otherProfile: this.state.user, }); } else if (this.props.navigation.getParam('stack') === 'Chat') { this.props.navigation.push('ChatChatScreen', { msnoFrom: this.props.navigation.getParam('msnoView'), msnoTo: this.props.navigation.getParam('msno'), onNavigateBack: this.handleNavigateBack, stack: this.props.navigation.getParam('stack'), selfProfile: this.state.selfProfile, otherProfile: this.state.user, }); } else { } }; onBackPress = () => { this.props.navigation.state.params.onNavigateBack(); this.props.navigation.goBack(null); }; onFollowersPress = () => { if (this.props.navigation.getParam('stack') === 'Discover') { this.props.navigation.push('DiscoverFollowerScreen', { msnoView: this.props.navigation.getParam('msno'), isFollower: true, stack: this.props.navigation.getParam('stack'), onBack: this.onBackPress, }); } else if (this.props.navigation.getParam('stack') === 'Chat') { this.props.navigation.push('ChatFollowerScreen', { msnoView: this.props.navigation.getParam('msno'), isFollower: true, stack: this.props.navigation.getParam('stack'), onBack: this.onBackPress, }); } else if (this.props.navigation.getParam('stack') === 'Friends') { this.props.navigation.push('FriendFollowerScreen', { msnoView: this.props.navigation.getParam('msno'), isFollower: true, stack: this.props.navigation.getParam('stack'), onBack: this.onBackPress, }); } else { } }; onFollowingPress = () => { if (this.props.navigation.getParam('stack') === 'Discover') { this.props.navigation.push('DiscoverFollowingScreen', { msnoView: this.props.navigation.getParam('msno'), isFollowing: true, stack: this.props.navigation.getParam('stack'), onBack: this.onBackPress, }); } else if (this.props.navigation.getParam('stack') === 'Chat') { this.props.navigation.push('ChatFollowingScreen', { msnoView: this.props.navigation.getParam('msno'), isFollowing: true, stack: this.props.navigation.getParam('stack'), onBack: this.onBackPress, }); } else if (this.props.navigation.getParam('stack') === 'Friends') { this.props.navigation.push('FriendFollowingScreen', { msnoView: this.props.navigation.getParam('msno'), isFollowing: true, stack: this.props.navigation.getParam('stack'), onBack: this.onBackPress, }); } else { } }; onPostsPress = () => {}; onPhotoPress = index => {}; onActivityLikePress = index => {}; render() { if (this.state.isLoaded === true) { return ( // <SafeAreaView> <ScrollView showsVerticalScrollIndicator={false}> <Profile profile={this.state.user} socials={this.state.socials} favorites={this.state.favorites} coverPlayList={this.state.coverPlayList} activity={this.state.activity} sharedPlayLists={this.state.sharedPlayLists} myBoxPlayLists={this.state.myBoxPlayLists} onFollowPress={this.onFollowPress} onShareModalClose={this.onShareModalClose} onPlayListSelected={this.onPlayListSelected} onMessagePress={this.onMessagePress} onFollowersPress={this.onFollowersPress} onFollowingPress={this.onFollowingPress} onPostsPress={this.onPostsPress} onSharePress={this.onSharePress} onPhotoPress={this.onPhotoPress} onActivityLikePress={this.onActivityLikePress} onSharedPlayListPress={this.onSharedPlayListPress} onSwipeComplete={this.onSwipeComplete} modalVisible={this.state.modalVisible} shareModalVisible={this.state.shareModalVisible} modalIndex={this.state.modalIndex} liked={this.state.liked} shared={this.state.shared} matched={this.state.matched} isSelf={this.state.isSelf} /> </ScrollView> // </SafeAreaView> ); } else { return <View />; } } } <file_sep>import React from 'react'; import {Image} from 'react-native'; import {Avatar} from 'react-native-elements'; import {withStyles, Text} from 'react-native-ui-kitten'; import {textStyle} from '../common/style'; class ProfileActivityListItemComponent extends React.Component { render() { const {style, themedStyle, source, ...restProps} = this.props; return ( <> <Avatar rounded style={[themedStyle.container, style]} // resizeMode="center" source={{uri: source.source.imageSource}} {...restProps} /> <Text>{`${source.playlistName}`}</Text> </> ); } } export const ProfileActivityListItem = withStyles( ProfileActivityListItemComponent, theme => ({ container: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 16, }, messageContainer: { // flex: 1, }, leftSection: { flexDirection: 'row', alignItems: 'center', }, avatar: { marginRight: 16, }, userLabel: textStyle.subtitle, lastMessageLabel: textStyle.caption1, dateLabel: textStyle.paragraph, rightSection: { flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', }, }), ); <file_sep>import React from 'react'; import {Dimensions, View} from 'react-native'; import {withStyles, Text} from 'react-native-ui-kitten'; import {textStyle} from '../common/style'; import {MessageContent} from './MessageContentComponent'; class RightMessageComponent extends React.Component { render() { const {themedStyle, message, children} = this.props; return [ <Text key={0} style={themedStyle.dateLabel} appearance="hint" category="c1"> {message.date} </Text>, <View style={themedStyle.cloudContainer} key={1}> <View style={[themedStyle.cloud, themedStyle.cloudRight]}> <MessageContent message={message}>{children}</MessageContent> </View> <View style={[themedStyle.triangle, themedStyle.triangleRight]} /> </View>, ]; } } export const RightMessage = withStyles(RightMessageComponent, theme => ({ triangle: { borderLeftWidth: 10, borderRightWidth: 10, borderBottomWidth: 15, borderLeftColor: 'transparent', borderRightColor: 'transparent', backgroundColor: 'transparent', }, triangleRight: { transform: [{rotate: '90deg'}], borderBottomColor: theme['text-hint-color'], }, cloudContainer: { flexDirection: 'row', alignItems: 'center', }, dateLabel: textStyle.caption1, cloud: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', padding: 16, borderRadius: 8, maxWidth: Dimensions.get('window').width - 120, }, cloudRight: { left: 3, backgroundColor: theme['text-hint-color'], marginLeft: 16, }, })); <file_sep>import React from 'react'; import { ScrollView, View, RefreshControl, AsyncStorage, ActivityIndicator, Dimensions, } from 'react-native'; import {SafeAreaView} from 'react-navigation'; import Collapsible from 'react-native-collapsible'; import {CardList} from '../components/CardList'; import {Text, withStyles, Button, Icon, List} from 'react-native-ui-kitten'; import {textStyle} from '../../common/style'; import {PARTNER_IMGS} from '../../../core/data/default'; import axios from 'axios'; import _ from 'lodash'; const StarOutline = style => <Icon name="star-outline" {...style} />; function wait(timeout) { return new Promise(resolve => { setTimeout(resolve, timeout); }); } class DiscoverDemoComponent extends React.Component { state = { profiles: [], luckyPressCollapsed: true, refreshing: false, msnoView: '', isLoaded: false, isLuckyShotsLoaded: false, discoveries: [], luckyshots: [], }; onItemPress = card => { this.props.navigation.push('DiscoverProfilePage', { msnoView: this.state.msnoView, msno: card['msno'], onNavigateBack: this.handleOnNavigateBack, stack: 'Discover', }); }; onShotItemPress = card => { this.props.navigation.push('DiscoverProfilePage', { msnoView: this.state.msnoView, onNavigateBack: this.handleOnNavigateBack, msno: card['msno'], stack: 'Discover', }); }; onLuckyPress = button => { axios({ method: 'get', url: 'https://kkfriends.app/luckyshot', params: { msno: this.state.msnoView, }, }).then(res => { var data = res.data; var luckyshots = data['data']; luckyshots = this.formatLuckyShots(luckyshots); if (this.state.luckyPressCollapsed === true) { this.setState({ luckyPressCollapsed: false, isLuckyShotsLoaded: true, luckyshots: luckyshots, }); } }); }; formatLuckyShots = luckyshots => { var newShots = _.map(luckyshots, shot => { var newShot = { photo: { imageSource: `https://i.kfs.io/album/global/${shot['album_id']},0v9/fit/300x300.jpg`, }, firstName: shot['song_name'], lastName: '', job: '', inseam: 0, email: '', phoneNumber: '', location: '', friends: [], online: true, msno: shot['luckyshot_msno'], }; return newShot; }); return newShots; }; componentDidMount = () => { AsyncStorage.getItem('user').then(res => { var data = JSON.parse(res); var msnoView = data['msno']; this.setState({msnoView: msnoView}); this.getDiscover(msnoView); }); }; getDiscover = msno => { axios({ method: 'get', url: 'https://kkfriends.app/discovery-list', params: {msno: msno}, }).then(res => { var data = res.data; var discoveries = data['discoveries']; this.setState({discoveries: discoveries, isLoaded: true}); }); }; formatUsers = users => { var newUsers = _.map(users, user => { var newUser = { photo: { imageSource: _.has(PARTNER_IMGS, user['msno']) ? PARTNER_IMGS[user['msno']] : user['img_url'], }, about: '', firstName: user['name'], lastName: '', gender: user['gender'], age: 0, weight: 0, height: 0, job: '', inseam: 0, email: user['email'], phoneNumber: '0', location: 'Taipei, Taiwan', friends: [], online: true, msno: user['msno'], }; return newUser; }); return newUsers; }; handleOnNavigateBack = () => {}; renderItem = info => { const {themedStyle} = this.props; const users = this.formatUsers(info.item['users']); return ( <> <Text style={themedStyle.pagerLabel} category="h3"> {`${info.item['reason']}`} </Text> <CardList profiles={users} onItemPress={this.onItemPress} onItemLikePress={this.onItemLikePress} onItemCommentPress={this.onItemCommentPress} /> </> ); }; onRefresh = () => { this.setState({refreshing: true}); this.componentDidMount(); this.setState({refreshing: false, luckyPressCollapsed: true}); }; onItemLikePress = card => {}; onItemCommentPress = card => {}; render() { const {themedStyle} = this.props; if (this.state.isLoaded === true) { return ( <SafeAreaView style={themedStyle.safeAreaContainer} forceInset={{bottom: 'never'}}> <ScrollView contentContainerStyle={themedStyle.container} refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this.onRefresh} /> }> {this.state.luckyPressCollapsed ? ( <View style={themedStyle.buttonSection}> <Button icon={StarOutline} style={themedStyle.button} textStyle={textStyle.button} onPress={this.onLuckyPress}> Lucky Shot </Button> </View> ) : null} <Collapsible style={themedStyle.container} collapsed={this.state.luckyPressCollapsed}> <Text style={themedStyle.pagerLabel} category="h3"> Lucky Shot </Text> <CardList profiles={this.state.luckyshots} onItemPress={this.onShotItemPress} onItemLikePress={this.onItemLikePress} onItemCommentPress={this.onItemCommentPress} /> </Collapsible> <List style={themedStyle.container} data={this.state.discoveries} renderItem={this.renderItem} /> </ScrollView> </SafeAreaView> ); } else { return ( <View style={themedStyle.loadContainer}> <ActivityIndicator size="large" /> </View> ); } } } export const DiscoverDemo = withStyles(DiscoverDemoComponent, theme => ({ container: { paddingVertical: 8, backgroundColor: theme['background-basic-color-2'], }, safeAreaContainer: { backgroundColor: theme['background-basic-color-2'], }, loadContainer: { height: Dimensions.get('window').height, width: Dimensions.get('window').width, justifyContent: 'center', }, buttonSection: { justifyContent: 'center', alignItems: 'center', backgroundColor: theme['background-basic-color-2'], }, button: { flex: 1, width: 200, }, pagerLabel: { paddingHorizontal: 16, marginVertical: 16, ...textStyle.paragraph, }, })); <file_sep>import React from 'react'; import {ImageBackground, StyleSheet, View} from 'react-native'; import {withStyles} from 'react-native-ui-kitten'; class ImageOverlayComponent extends React.Component { getOverlayColor = source => { const {themedStyle} = this.props; return source || themedStyle.overlay.backgroundColor; }; render() { const {style, themedStyle, children, ...restProps} = this.props; // @ts-ignore: overlayColor (additional style property) const { overlayColor: derivedOverlayColor, ...containerStyle } = StyleSheet.flatten(style); const overlayColor = this.getOverlayColor(derivedOverlayColor); return ( <ImageBackground style={containerStyle} {...restProps}> <View style={[themedStyle.overlay, {backgroundColor: overlayColor}]} /> {children} </ImageBackground> ); } } export const ImageOverlay = withStyles(ImageOverlayComponent, theme => ({ overlay: { backgroundColor: 'rgba(0, 0, 0, 0.45)', ...StyleSheet.absoluteFillObject, }, })); <file_sep>import React from 'react'; import { ScrollView, View, AsyncStorage, ActivityIndicator, Dimensions, } from 'react-native'; import {SafeAreaView} from 'react-navigation'; import {Text, withStyles, Button, Icon} from 'react-native-ui-kitten'; import MaterialCardWithRightButtons from '../../radio/MaterialCardWithRightButtons'; import {ProfilePlayList} from '../../radio/profilePlayList'; import {textStyle} from '../../common/style'; import axios from 'axios'; import _ from 'lodash'; const StarOutline = style => <Icon name="star-outline" {...style} />; function wait(timeout) { return new Promise(resolve => { setTimeout(resolve, timeout); }); } class RadioDemoComponent extends React.Component { state = { isLoaded: false, playlist: [], }; componentDidMount = () => { AsyncStorage.getItem('user').then(res => { var user = JSON.parse(res); this.getRadio(user['msno']); this.props.navigation.addListener('willFocus', () => { this.getRadio(user['msno']); }); }); }; getRadio = msno => { axios({ method: 'get', url: 'https://kkfriends.app/radio', params: { msno: msno, }, }).then(res => { var data = res.data; var playlist = data['playlist']; playlist = this.formatRadio(playlist); this.setState({playlist: playlist, isLoaded: true}); }); }; formatRadio = playlist => { var newPlayList = _.map(playlist, song => { var newSong = { category: 'Radio', source: {imageSource: song['album_img_url']}, name: song['song_name'], from_user: song['from_user'], }; return newSong; }); newPlayList = { ['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ']: newPlayList, }; return newPlayList; }; onPhotoPress = () => {}; renderMyPlayListElement = source => { return Object.keys(source).map(category => { if (category === 'ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ') { const categoryActivities = source[category]; return this.renderSongElement(category, categoryActivities); } }); }; renderSongElement = (category, activities) => { const {themedStyle} = this.props; return ( <View style={themedStyle.radioListContainer} key={category}> <ProfilePlayList data={activities} onItemPress={this.onPhotoPress} /> </View> ); }; render() { const {themedStyle} = this.props; if (this.state.isLoaded === true) { return ( <SafeAreaView forceInset={{bottom: 'never'}}> <ScrollView contentContainerStyle={themedStyle.container}> <View style={themedStyle.radioContainer}> <MaterialCardWithRightButtons style={themedStyle.materialCardWithRightButtons} playlist={this.state.playlist}></MaterialCardWithRightButtons> </View> <Text style={themedStyle.pagerLabel} category="h3"> ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ </Text> {this.renderMyPlayListElement(this.state.playlist)} </ScrollView> </SafeAreaView> ); } else { return ( <View style={themedStyle.loadContainer}> <ActivityIndicator size="large" /> </View> ); } } } export const RadioDemo = withStyles(RadioDemoComponent, theme => ({ container: { paddingHorizontal: 16, paddingVertical: 8, backgroundColor: theme['background-basic-color-2'], }, loadContainer: { height: Dimensions.get('window').height, width: Dimensions.get('window').width, justifyContent: 'center', }, radioListContainer: { flex: 1, }, button: { flex: 1, width: 200, }, pagerLabel: { marginVertical: 16, ...textStyle.paragraph, }, radioContainer: { justifyContent: 'center', alignItems: 'center', }, materialCardWithRightButtons: { width: 328, height: 266, borderRadius: 25, }, })); <file_sep>import React from 'react'; import { createAppContainer, SafeAreaView, createSwitchNavigator, } from 'react-navigation'; import {createBottomTabNavigator} from 'react-navigation-tabs'; import {createStackNavigator} from 'react-navigation-stack'; import { BottomNavigation, BottomNavigationTab, Layout, Text, Icon, } from 'react-native-ui-kitten'; import {ProfileDemo} from './screens/containers/ProfileDemo'; import {DiscoverDemo} from './screens/containers/DiscoverDemo'; import {ChatListDemo} from './screens/containers/ChatListDemo'; import {ChatDemoComponent} from './screens/containers/ChatDemo'; import {ProfilePageDemo} from './screens/containers/ProfilePageDemo'; import {FriendListDemo} from './screens/containers/FriendListDemo'; import {RadioDemo} from './screens/containers/RadioDemo'; import {AuthDemo} from './screens/containers/AuthDemo'; import {AuthLoading} from './screens/components/AuthLoading'; // React Navigation also requires installing additional dependencies: // // npm i react-navigation react-navigation-tabs react-native-reanimated react-native-gesture-handler // // Then install it for ios: // // cd ios && pod install const TabBarComponent = ({navigation}) => { const onSelect = index => { const {[index]: selectedTabRoute} = navigation.state.routes; navigation.navigate(selectedTabRoute.routeName); }; const ProfileIcon = style => <Icon name="person-outline" {...style} />; const CompassIcon = style => <Icon name="compass-outline" {...style} />; const FriendIcon = style => <Icon name="people-outline" {...style} />; const ChatIcon = style => <Icon name="message-circle-outline" {...style} />; const RadioIcon = style => <Icon name="radio-outline" {...style} />; return ( <SafeAreaView forceInset={{bottom: 'always', top: 'never'}}> <BottomNavigation selectedIndex={navigation.state.index} onSelect={onSelect}> <BottomNavigationTab title="Profile" icon={ProfileIcon} /> <BottomNavigationTab title="Discover" icon={CompassIcon} /> <BottomNavigationTab title="Friends" icon={FriendIcon} /> <BottomNavigationTab title="Chat" icon={ChatIcon} /> <BottomNavigationTab title="Radio" icon={RadioIcon} /> </BottomNavigation> </SafeAreaView> ); }; const ChatStack = createStackNavigator({ ChatList: { screen: ChatListDemo, navigationOptions: {headerShown: false}, }, ChatChatScreen: { screen: ChatDemoComponent, }, ChatProfilePage: { screen: ProfilePageDemo, }, ChatFollowingScreen: { screen: FriendListDemo, }, ChatFollowerScreen: { screen: FriendListDemo, }, }); ChatStack.navigationOptions = ({navigation}) => { if (navigation.state.index !== 0) { var tabBarVisible = false; } else { var tabBarVisible = true; } return {tabBarVisible}; }; const DiscoverStack = createStackNavigator({ Discover: {screen: DiscoverDemo, navigationOptions: {headerShown: false}}, DiscoverProfilePage: { screen: ProfilePageDemo, }, DiscoverChatScreen: { screen: ChatDemoComponent, }, DiscoverFollowingScreen: { screen: FriendListDemo, }, DiscoverFollowerScreen: { screen: FriendListDemo, }, }); DiscoverStack.navigationOptions = ({navigation}) => { if (navigation.state.index !== 0) { var tabBarVisible = false; } else { var tabBarVisible = true; } return {tabBarVisible}; }; const FriendsStack = createStackNavigator({ Friends: {screen: FriendListDemo, navigationOptions: {headerShown: false}}, FriendProfilePage: { screen: ProfilePageDemo, }, FriendChatScreen: { screen: ChatDemoComponent, }, FriendFollowingScreen: { screen: FriendListDemo, }, FriendFollowerScreen: { screen: FriendListDemo, }, }); FriendsStack.navigationOptions = ({navigation}) => { if (navigation.state.index !== 0) { var tabBarVisible = false; } else { var tabBarVisible = true; } return {tabBarVisible}; }; const TabNavigator = createBottomTabNavigator( { Profile: ProfileDemo, Discover: DiscoverStack, Friends: FriendsStack, Chat: ChatStack, Radio: RadioDemo, }, { tabBarComponent: TabBarComponent, initialRouteName: 'Discover', }, ); const AuthStack = createStackNavigator({ Auth: {screen: AuthDemo, navigationOptions: {headerShown: false}}, }); const AppStack = createStackNavigator({ App: {screen: TabNavigator, navigationOptions: {headerShown: false}}, }); const AppNavigatorStack = createSwitchNavigator( { AuthLoadingScreen: AuthLoading, Auth: {screen: AuthStack}, App: AppStack, }, {initialRouteName: 'AuthLoadingScreen'}, ); export const AppNavigator = createAppContainer(AppNavigatorStack); <file_sep>import React from 'react'; import { ScrollView, AsyncStorage, View, ActivityIndicator, Dimensions, } from 'react-native'; import {Divider} from 'react-native-elements'; import {SafeAreaView} from 'react-navigation'; import {FriendList} from '../components/FriendList'; import {PARTNER_IMGS} from '../../../core/data/default'; import {FriendListHeader} from '../../friends/friendListHeader'; import {withStyles, Text} from 'react-native-ui-kitten'; import {textStyle} from '../../common/style'; import axios from 'axios'; import _ from 'lodash'; class FriendListDemoComponent extends React.Component { state = { // friends: conversations, searchEnabled: false, followers: [], following: [], friends: [], isLoaded: false, }; static navigationOptions = ({navigation, screenProps}) => { const headerProps = { onBack: navigation.getParam('onBack'), }; const header = navigationProps => { return navigation.state.routeName === 'Friends' ? null : ( <FriendListHeader {...navigationProps} {...headerProps} /> ); }; return {...navigation, ...screenProps, header}; }; componentDidMount = () => { this.props.navigation.addListener('willFocus', () => { if (this.props.navigation.state.routeName === 'Friends') { this.getFriendList(); } }); AsyncStorage.getItem('user').then(res => { var data = JSON.parse(res); var msnoView = data['msno']; this.setState({msnoView: msnoView}); }); if (this.props.navigation.getParam('isFollowing') === true) { axios({ method: 'get', url: 'https://kkfriends.app/follow-list', params: { msno: this.props.navigation.getParam('msnoView'), }, }).then(res => { var data = res.data; var friends = data['friends']; var following = data['following']; following = this.formatFollowList(following); friends = this.formatFollowList(friends); var followingList = following.concat(friends); this.setState({following: followingList, isLoaded: true}); }); } else if (this.props.navigation.getParam('isFollower') === true) { axios({ method: 'get', url: 'https://kkfriends.app/follow-list', params: { msno: this.props.navigation.getParam('msnoView'), }, }).then(res => { var data = res.data; var friends = data['friends']; var followers = data['followed']; followers = this.formatFollowList(followers); friends = this.formatFollowList(friends); var followedList = followers.concat(friends); this.setState({followers: followedList, isLoaded: true}); }); } else { this.getFriendList(); } }; getFriendList = () => { AsyncStorage.getItem('user').then(res => { var user = JSON.parse(res); axios({ method: 'get', url: 'https://kkfriends.app/follow-list', params: { msno: user['msno'], }, }).then(res => { var data = res.data; var friends = data['friends']; var followers = data['followed']; var following = data['following']; friends = this.formatFollowList(friends); followers = this.formatFollowList(followers); following = this.formatFollowList(following); this.setState({ followers: followers, following: following, friends: friends, isLoaded: true, }); }); }); }; formatFollowList = followList => { var newFollowList = _.map(followList, user => { var newUser = { interlocutor: { photo: { imageSource: _.has(PARTNER_IMGS, user['msno']) ? PARTNER_IMGS[user['msno']] : user['img_url'], }, about: '', firstName: user['name'], lastName: '', gender: user['gender'], age: 0, weight: 0, height: 0, job: '', inseam: 0, email: user['email'], phoneNumber: '0', location: 'Taipei, Taiwan', friends: [], online: true, msno: user['msno'], }, }; return newUser; }); return newFollowList; }; handleOnNavigateBack = () => { AsyncStorage.getItem('user').then(res => { var user = JSON.parse(res); this.getFriendList(user['msno']); }); }; onProfileFollowingPress = index => { var profile = this.state.following[index]['interlocutor']; if (this.props.navigation.getParam('isFollower') === true) { if (this.props.navigation.getParam('stack') === 'Discover') { this.props.navigation.push('DiscoverProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: this.props.navigation.getParam('stack'), // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollower: true, }); } else if (this.props.navigation.getParam('stack') === 'Chat') { this.props.navigation.push('ChatProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: this.props.navigation.getParam('stack'), // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollower: true, }); } else { this.props.navigation.push('FriendProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: 'Friends', // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollower: true, }); } } else if (this.props.navigation.getParam('isFollowing') === true) { if (this.props.navigation.getParam('stack') === 'Discover') { this.props.navigation.push('DiscoverProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: this.props.navigation.getParam('stack'), onNavigateBack: () => {}, isFollowing: true, }); } else if (this.props.navigation.getParam('stack') === 'Chat') { this.props.navigation.push('ChatProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: this.props.navigation.getParam('stack'), // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollowing: true, }); } else { this.props.navigation.push('FriendProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: 'Friends', // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollowing: true, }); } } else { if (this.props.navigation.getParam('stack') === 'Discover') { this.props.navigation.push('DiscoverProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], onNavigateBack: this.handleOnNavigateBack, stack: this.props.navigation.getParam('stack'), }); } else if (this.props.navigation.getParam('stack') === 'Chat') { this.props.navigation.push('ChatProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], onNavigateBack: this.handleOnNavigateBack, stack: this.props.navigation.getParam('stack'), }); } else { this.props.navigation.push('FriendProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], onNavigateBack: this.handleOnNavigateBack, stack: 'Friends', }); } } }; onProfileFollowerPress = index => { var profile = this.state.followers[index]['interlocutor']; if (this.props.navigation.getParam('isFollower') === true) { if (this.props.navigation.getParam('stack') === 'Discover') { this.props.navigation.push('DiscoverProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: this.props.navigation.getParam('stack'), // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollower: true, }); } else if (this.props.navigation.getParam('stack') === 'Chat') { this.props.navigation.push('ChatProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: this.props.navigation.getParam('stack'), // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollower: true, }); } else { this.props.navigation.push('FriendProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: 'Friends', // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollower: true, }); } } else if (this.props.navigation.getParam('isFollowing') === true) { if (this.props.navigation.getParam('stack') === 'Discover') { this.props.navigation.push('DiscoverProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: this.props.navigation.getParam('stack'), onNavigateBack: () => {}, isFollowing: true, }); } else if (this.props.navigation.getParam('stack') === 'Chat') { this.props.navigation.push('ChatProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: this.props.navigation.getParam('stack'), // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollowing: true, }); } else { this.props.navigation.push('FriendProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: 'Friends', // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollowing: true, }); } } else { if (this.props.navigation.getParam('stack') === 'Discover') { this.props.navigation.push('DiscoverProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], onNavigateBack: this.handleOnNavigateBack, stack: this.props.navigation.getParam('stack'), }); } else if (this.props.navigation.getParam('stack') === 'Chat') { this.props.navigation.push('ChatProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], onNavigateBack: this.handleOnNavigateBack, stack: this.props.navigation.getParam('stack'), }); } else { this.props.navigation.push('FriendProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], onNavigateBack: this.handleOnNavigateBack, stack: 'Friends', }); } } }; onProfilePress = index => { if (this.props.navigation.getParam('isFollower') === true) { var profile = this.state.followers[index]['interlocutor']; } else if (this.props.navigation.getParam('isFollowing') === true) { var profile = this.state.following[index]['interlocutor']; } else { var profile = this.state.friends[index]['interlocutor']; } if (this.props.navigation.getParam('isFollower') === true) { if (this.props.navigation.getParam('stack') === 'Discover') { this.props.navigation.push('DiscoverProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: this.props.navigation.getParam('stack'), // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollower: true, }); } else if (this.props.navigation.getParam('stack') === 'Chat') { this.props.navigation.push('ChatProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: this.props.navigation.getParam('stack'), // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollower: true, }); } else { this.props.navigation.push('FriendProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: 'Friends', // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollower: true, }); } } else if (this.props.navigation.getParam('isFollowing') === true) { if (this.props.navigation.getParam('stack') === 'Discover') { this.props.navigation.push('DiscoverProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: this.props.navigation.getParam('stack'), onNavigateBack: () => {}, isFollowing: true, }); } else if (this.props.navigation.getParam('stack') === 'Chat') { this.props.navigation.push('ChatProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: this.props.navigation.getParam('stack'), // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollowing: true, }); } else { this.props.navigation.push('FriendProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], stack: 'Friends', // onNavigateBack: this.handleOnNavigateBack, onNavigateBack: () => {}, isFollowing: true, }); } } else { if (this.props.navigation.getParam('stack') === 'Discover') { this.props.navigation.push('DiscoverProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], onNavigateBack: this.handleOnNavigateBack, stack: this.props.navigation.getParam('stack'), }); } else if (this.props.navigation.getParam('stack') === 'Chat') { this.props.navigation.push('ChatProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], onNavigateBack: this.handleOnNavigateBack, stack: this.props.navigation.getParam('stack'), }); } else { this.props.navigation.push('FriendProfilePage', { msnoView: this.state.msnoView, msno: profile['msno'], onNavigateBack: this.handleOnNavigateBack, stack: 'Friends', }); } } }; onMessagePress = index => { AsyncStorage.getItem('profile').then(res => { var selfProfile = JSON.parse(res); if (this.props.navigation.getParam('isFollower') === true) { var profile = this.state.followers[index]['interlocutor']; } else if (this.props.navigation.getParam('isFollowing') === true) { var profile = this.state.following[index]['interlocutor']; } else { var profile = this.state.friends[index]['interlocutor']; } selfProfile = selfProfile['interlocutor']; this.props.navigation.push('FriendChatScreen', { msnoFrom: this.state.msnoView, msnoTo: profile['msno'], selfProfile: selfProfile, otherProfile: profile, onNavigateBack: this.handleOnNavigateBack, stack: 'Friends', }); }); }; render() { if (this.state.isLoaded === true) { if (this.props.navigation.getParam('isFollower') === true) { return ( <SafeAreaView forceInset={{bottom: 'never', top: 'never'}}> <ScrollView> <FriendList searchEnabled={this.state.searchEnabled} friends={this.state.followers} onProfile={this.onProfilePress} onMessagePress={this.onMessagePress} isFollow={true} /> </ScrollView> </SafeAreaView> ); } else if (this.props.navigation.getParam('isFollowing') === true) { return ( <SafeAreaView forceInset={{top: 'never'}}> <ScrollView> <FriendList searchEnabled={this.state.searchEnabled} friends={this.state.following} onProfile={this.onProfilePress} onMessagePress={this.onMessagePress} isFollow={true} /> </ScrollView> </SafeAreaView> ); } else { const {themedStyle} = this.props; return ( <SafeAreaView forceInset={{bottom: 'never'}}> <ScrollView> <Text style={themedStyle.pagerLabel}>ๆœ‹ๅ‹ๆธ…ๅ–ฎ</Text> <FriendList searchEnabled={this.state.searchEnabled} friends={this.state.friends} onProfile={this.onProfilePress} onMessagePress={this.onMessagePress} isFollow={false} /> <Divider /> <Text style={themedStyle.pagerLabel}>ๆˆ‘่ฟฝ้šจ็š„ไบบ</Text> <FriendList searchEnabled={this.state.searchEnabled} friends={this.state.following} onProfile={this.onProfileFollowingPress} onMessagePress={this.onMessagePress} isFollow={true} /> <Divider /> <Text style={themedStyle.pagerLabel}>่ฟฝ้šจๆˆ‘็š„ไบบ</Text> <FriendList searchEnabled={this.state.searchEnabled} friends={this.state.followers} onProfile={this.onProfileFollowerPress} onMessagePress={this.onMessagePress} isFollow={true} /> </ScrollView> </SafeAreaView> ); } } else { const {themedStyle} = this.props; return ( <View style={themedStyle.loadContainer}> <ActivityIndicator size="large" /> </View> ); } } } export const FriendListDemo = withStyles(FriendListDemoComponent, theme => ({ loadContainer: { height: Dimensions.get('window').height, width: Dimensions.get('window').width, justifyContent: 'center', }, pagerLabel: { paddingHorizontal: 16, marginVertical: 16, ...textStyle.paragraph, }, })); <file_sep>import React from 'react'; import { withStyles, Avatar, TopNavigation, TopNavigationAction, Icon, } from 'react-native-ui-kitten'; import {SafeAreaView} from 'react-navigation'; const ArrowIosBackFill = style => { return <Icon {...style} name="arrow-ios-back" />; }; class FriendListHeaderComponent extends React.Component { onBack = () => { this.props.onBack(); }; // onProfile = () => { // const {interlocutor, onProfile} = this.props; // onProfile(interlocutor); // }; renderLeftControl = () => { return ( <TopNavigationAction icon={ArrowIosBackFill} onPress={this.onBack} /> ); }; // renderProfileAvatar = () => { // const {interlocutor} = this.props; // return <Avatar source={interlocutor.photo.imageSource} />; // }; // renderRightControls = () => { // const {themedStyle} = this.props; // return ( // <TopNavigationAction // icon={this.renderProfileAvatar} // onPress={this.onProfile} // /> // ); // }; // renderInterlocutorProps = () => { // const {interlocutor, lastSeen} = this.props; // return ( // interlocutor && { // title: `${interlocutor.firstName} ${interlocutor.lastName}`, // subtitle: `Last seen ${lastSeen}`, // rightControls: this.renderRightControls(), // } // ); // }; render() { const {themedStyle} = this.props; return ( <SafeAreaView forceInset={{bottom: 'never'}} style={themedStyle.container}> <TopNavigation alignment="center" leftControl={this.renderLeftControl()} // {...this.renderInterlocutorProps()} /> </SafeAreaView> ); } } export const FriendListHeader = withStyles( FriendListHeaderComponent, theme => ({ container: { backgroundColor: theme['background-basic-color-1'], }, }), ); <file_sep>import React from 'react'; import {AsyncStorage, View} from 'react-native'; import {ChatHeader} from '../../messages/ChatHeader'; import {Chat} from '../components/Chat'; import axios from 'axios'; import _ from 'lodash'; import moment from 'moment'; function wait(timeout) { return new Promise(resolve => { setTimeout(resolve, timeout); }); } export class ChatDemoComponent extends React.Component { state = { newMessageText: '', realConversation: { interlocutor: '', lastSeen: '', messages: [], }, }; static navigationOptions = ({navigation, screenProps}) => { const headerProps = { interlocutor: navigation.getParam('interlocutor'), lastSeen: navigation.getParam('lastSeen', 'today'), onBack: navigation.getParam('onBack', () => {}), onProfile: navigation.getParam('onProfile', () => {}), }; const header = navigationProps => { return <ChatHeader {...navigationProps} {...headerProps} />; }; return {...navigation, ...screenProps, header}; }; // checkNewMessages = async () => { // axios // .get('https://kkfriends.app/chat-message-before-id', { // params: { // msno_view: this.props.navigation.getParam('msnoFrom'), // msno_with: this.props.navigation.getParam('msnoTo'), // id: 9999999999, // }, // }) // .then(res => { // var data = res.data; // var messages = data['messages']; // }); // }; syncMessages = () => { AsyncStorage.getItem('chatContext').then(chatContextJson => { var chatContext = JSON.parse(chatContextJson); if ( chatContext['messages'].length !== this.state.realConversation['messages'].length ) { var messages = chatContext['messages']; var formatMessages = _.map(messages, msg => { var date = moment(msg['ts'] * 1000); formatDate = date.format('HH:mm A'); var formatMsg = { author: msg['msno_f'] === this.props.navigation.getParam('msnoFrom') ? this.props.navigation.getParam('selfProfile') : this.props.navigation.getParam('otherProfile'), text: msg['message'], date: formatDate, ts: date, read: true, delivered: true, }; return formatMsg; }); if (formatMessages.length !== 0) { var newestMsg = formatMessages[0]; var formatConversation = { interlocutor: this.props.navigation.getParam('otherProfile'), lastSeen: newestMsg.ts.fromNow(), messages: formatMessages, }; this.props.navigation.setParams({ interlocutor: formatConversation.interlocutor, lastSeen: formatConversation.lastSeen, onBack: this.onBackPress, onProfile: this.onProfilePress, }); this.setState({ realConversation: formatConversation, }); } else { } } else if ( chatContext['messages'].length === this.state.realConversation['messages'].length && this.state.realConversation['messages'].length === 0 ) { this.props.navigation.setParams({ interlocutor: this.props.navigation.getParam('otherProfile'), onBack: this.onBackPress, onProfile: this.onProfilePress, }); } else { } }); }; callChatAPI = () => { axios .get('https://kkfriends.app/chat-message-before-id', { params: { msno_view: this.props.navigation.getParam('msnoFrom'), msno_with: this.props.navigation.getParam('msnoTo'), id: 9999999999, }, }) .then(res => { var data = res.data; var messages = data['messages']; AsyncStorage.setItem( 'chatContext', JSON.stringify({ chatMsno: this.props.navigation.getParam('msnoTo'), msno: this.props.navigation.getParam('msnoFrom'), latestId: messages.length > 0 ? messages[0]['id'] : 0, messages: messages.reverse(), }), ).then(() => { this.syncMessages(); }); }); }; handleOnNavigateBack = () => {}; componentDidMount() { this.callChatAPI(); this.syncView(); } syncView = async () => { while (true) { await wait(2000).then(() => { this.syncMessages(); }); } }; onProfilePress = profile => { if (this.props.navigation.getParam('stack') === 'Discover') { this.props.navigation.push('DiscoverProfilePage', { msnoView: this.props.navigation.getParam('msnoFrom'), msno: this.props.navigation.getParam('msnoTo'), onNavigateBack: this.handleOnNavigateBack, stack: this.props.navigation.getParam('stack'), }); } else if (this.props.navigation.getParam('stack') === 'Chat') { this.props.navigation.push('ChatProfilePage', { msnoView: this.props.navigation.getParam('msnoFrom'), msno: this.props.navigation.getParam('msnoTo'), onNavigateBack: this.handleOnNavigateBack, stack: this.props.navigation.getParam('stack'), }); } else if (this.props.navigation.getParam('stack') === 'Friends') { this.props.navigation.push('FriendProfilePage', { msnoView: this.props.navigation.getParam('msnoFrom'), msno: this.props.navigation.getParam('msnoTo'), onNavigateBack: this.handleOnNavigateBack, stack: this.props.navigation.getParam('stack'), }); } else { } }; onNewMessageChange = newMessageText => { this.setState({newMessageText}); }; onMessageAddPress = () => { var dateNow = moment(Date.now()); var dateFormat = dateNow.format('HH:mm A'); const newMessage = { author: this.props.navigation.getParam('selfProfile'), text: this.state.newMessageText, date: dateFormat, ts: dateNow, read: false, delivered: false, }; const conversationCopy = this.state.realConversation; conversationCopy.messages.push(newMessage); axios({ method: 'post', url: 'https://kkfriends.app/chat-post-message', data: { msno_f: this.props.navigation.getParam('msnoFrom'), msno_t: this.props.navigation.getParam('msnoTo'), message: this.state.newMessageText, }, }).then(res => { this.setState({ realConversation: conversationCopy, newMessageText: '', }); }); }; onBackPress = () => { AsyncStorage.setItem( 'chatContext', JSON.stringify({ chatMsno: 0, msno: 0, latestId: 0, messages: [], }), ).then(() => { this.props.navigation.state.params.onNavigateBack(); this.props.navigation.goBack(null); }); }; render() { return ( <Chat selfProfile={this.props.navigation.getParam('selfProfile')} otherProfile={this.props.navigation.getParam('otherProfile')} conversation={this.state.realConversation} newMessage={this.state.newMessageText} onNewMessageChange={this.onNewMessageChange} onMessageAdd={this.onMessageAddPress} /> ); } } <file_sep>import React from 'react'; import {withStyles, Icon} from 'react-native-ui-kitten'; const DoneAllIconOutline = style => <Icon name="done-all-outline" {...style} />; const messageIcons = { ['read']: { icon(style) { return DoneAllIconOutline({ ...style.messageIndicatorIcon, ...style.messageIndicatorIconRead, }); }, }, ['delivered']: { icon(style) { return DoneAllIconOutline({ ...style.messageIndicatorIcon, ...style.messageIndicatorIconDelivered, }); }, }, }; export class MessageIconComponent extends React.Component { defineMessageStatus(read, delivered) { if (read) { return 'read'; } else if (delivered && !read) { return 'delivered'; } else { return null; } } render() { const {themedStyle, message} = this.props; const messageStatus = this.defineMessageStatus( message.read, message.delivered, ); const iconProvider = messageIcons[messageStatus]; return iconProvider ? iconProvider.icon(themedStyle) : null; } } export const MessageIcon = withStyles(MessageIconComponent, theme => ({ messageIndicatorIcon: { width: 13, height: 8, marginRight: 4, }, messageIndicatorIconRead: { tintColor: theme['color-primary-default'], }, messageIndicatorIconDelivered: { tintColor: theme['text-hint-color'], }, })); <file_sep>import React from 'react'; import {TouchableOpacity} from 'react-native'; import {Text, withStyles} from 'react-native-ui-kitten'; import {DiscoverActivityBar} from '../../discover/discoverActivityBar'; import {DiscoverTips} from '../../discover/discoverTips'; import {ImageOverlay} from '../../common/imageOverlay'; import {textStyle} from '../../common/style'; class CardListItemComponent extends React.Component { constructor(props) { super(props); this.state = { filled: false, }; this.onLikeButtonPress = this.onLikeButtonPress.bind(this); } onPress = () => { this.props.onPress(this.props.profile); }; onCommentsButtonPress = () => { this.props.onCommentPress(this.props.profile); }; onLikeButtonPress = () => { if (this.state.filled === true) { this.setState({filled: false}); } else { this.setState({filled: true}); } this.props.onLikePress(this.props.profile); }; render() { const {style, themedStyle, profile, ...restProps} = this.props; return ( <TouchableOpacity activeOpacity={0.9} {...restProps} style={[themedStyle.container, style]} onPress={this.onPress}> <ImageOverlay style={themedStyle.image} source={{uri: profile.photo.imageSource}}> <Text style={themedStyle.titleLabel} category="h4"> {`${profile.firstName} ${profile.lastName}`} </Text> <DiscoverTips style={themedStyle.tipsContainer}> {`${profile.job}`} </DiscoverTips> <DiscoverActivityBar style={themedStyle.activityContainer} textStyle={themedStyle.activityBarLabel} comments={0} likes={profile.likes} filled={this.state.filled} onCommentPress={this.onCommentsButtonPress} onLikePress={this.onLikeButtonPress} /> </ImageOverlay> </TouchableOpacity> ); } } export const CardListItem = withStyles(CardListItemComponent, theme => ({ container: { minHeight: 300, borderRadius: 12, overflow: 'hidden', }, tipsContainer: { marginTop: 16, }, activityContainer: { marginTop: 48, }, image: { flex: 1, paddingHorizontal: 16, paddingTop: 24, paddingBottom: 16, }, titleLabel: { maxWidth: 192, color: 'white', ...textStyle.headline, }, activityBarLabel: { color: 'white', }, })); <file_sep>import React from 'react'; import {withStyles} from 'react-native-ui-kitten'; import {ActivityBar} from '../common/activityBar'; import {CommentsButton} from '../common/commentsButton'; import {LikeButton} from '../common/likeButton'; import {ReactionBar} from '../common/reactionBar'; class DiscoverActivityBarComponent extends React.Component { render() { const { themedStyle, textStyle, comments, likes, filled, onCommentPress, onLikePress, children, ...restProps } = this.props; return ( <ActivityBar {...restProps}> {children} <ReactionBar> {/* <CommentsButton textStyle={textStyle} activeOpacity={0.75} onPress={onCommentPress}> {`${comments}`} </CommentsButton> */} {/* <LikeButton textStyle={textStyle} activeOpacity={0.75} filled={filled} onPress={onLikePress}> {`${likes}`} </LikeButton> */} </ReactionBar> </ActivityBar> ); } } export const DiscoverActivityBar = withStyles( DiscoverActivityBarComponent, theme => ({}), ); <file_sep>export const profile = { photo: {imageSource: require('../../../assets/img/sean.jpg')}, about: "Hi! My name is Sean. I'm 41 and I live in Taipei." + " I'm interested in photography, coding.", firstName: 'Sean', lastName: 'Chang', gender: 'Male', age: 27, weight: 60, height: 176, job: 'Data Scientist', email: '<EMAIL>', phoneNumber: '+886 980648096', location: 'Taipei, Taiwan.', friends: [profile1, profile2], onLine: false, }; export const profiles = [profile, profile, profile]; export const profile1 = { photo: {imageSource: require('../../../assets/img/bot.png')}, about: "Hi! My name is Jen. I'm 41 and I live in Atlanta." + " I'm interested in swag, rap.", firstName: 'Bot', lastName: '', gender: 'Female', age: 25, weight: 48, height: 174, job: 'Bot', inseam: 44, email: '<EMAIL>', phoneNumber: '+375 44 123 12 12', location: 'Berlin, Germany', friends: [profile, profile2], onLine: false, }; export const profile2 = { photo: {imageSource: require('../../../assets/img/bot.png')}, about: "Hi! My name is Jen. I'm 41 and I live in Atlanta." + " I'm interested in swag, rap.", firstName: 'Bot', lastName: '', gender: 'Female', age: 25, weight: 48, height: 174, job: 'Bot', inseam: 44, email: '<EMAIL>', phoneNumber: '+375 44 123 12 12', location: 'Berlin, Germany', friends: [profile, profile1], onLine: false, }; export const profile3 = { photo: {imageSource: require('../../../assets/img/bot.png')}, about: "Hi! My name is Jen. I'm 41 and I live in Atlanta." + " I'm interested in swag, rap.", firstName: 'Bot', lastName: '', gender: 'Female', age: 25, weight: 48, height: 174, job: 'Bot', inseam: 44, email: '<EMAIL>', phoneNumber: '+375 44 123 12 12', location: 'Berlin, Germany', friends: [profile, profile2], onLine: false, }; export const profile4 = { photo: {imageSource: require('../../../assets/img/bot.png')}, about: "Hi! My name is Jen. I'm 41 and I live in Atlanta." + " I'm interested in swag, rap.", firstName: 'Bot', lastName: '', gender: 'Female', age: 25, weight: 48, height: 174, job: 'Bot', inseam: 44, email: '<EMAIL>', phoneNumber: '+375 44 123 12 12', location: 'Berlin, Germany', friends: [profile, profile2], onLine: false, }; export const profile5 = { photo: {imageSource: require('../../../assets/img/bot.png')}, about: "Hi! My name is Jen. I'm 41 and I live in Atlanta." + " I'm interested in swag, rap.", firstName: 'Bot', lastName: '', gender: 'Female', age: 25, weight: 48, height: 174, job: 'Bot', inseam: 44, email: '<EMAIL>', phoneNumber: '+375 44 123 12 12', location: 'Berlin, Germany', friends: [profile, profile2], onLine: false, }; export const profile6 = { photo: {imageSource: require('../../../assets/img/bot.png')}, about: "Hi! My name is Jen. I'm 41 and I live in Atlanta." + " I'm interested in swag, rap.", firstName: 'Bot', lastName: '', gender: 'Female', age: 25, weight: 48, height: 174, job: 'Bot', inseam: 44, email: '<EMAIL>', phoneNumber: '+375 44 123 12 12', location: 'Berlin, Germany', friends: [profile, profile2], onLine: false, }; export const profile7 = { photo: {imageSource: require('../../../assets/img/bot.png')}, about: "Hi! My name is Jen. I'm 41 and I live in Atlanta." + " I'm interested in swag, rap.", firstName: 'Bot', lastName: '', gender: 'Female', age: 25, weight: 48, height: 174, job: 'Bot', inseam: 44, email: '<EMAIL>', phoneNumber: '+375 44 123 12 12', location: 'Berlin, Germany', friends: [profile, profile2], onLine: false, }; export const profile8 = { photo: {imageSource: require('../../../assets/img/bot.png')}, about: "Hi! My name is Jen. I'm 41 and I live in Atlanta." + " I'm interested in swag, rap.", firstName: 'Bot', lastName: '', gender: 'Female', age: 25, weight: 48, height: 174, job: 'Bot', inseam: 44, email: '<EMAIL>', phoneNumber: '+375 44 123 12 12', location: 'Berlin, Germany', friends: [profile, profile2], onLine: false, }; export const profile9 = { photo: {imageSource: require('../../../assets/img/bot.png')}, about: "Hi! My name is Jen. I'm 41 and I live in Atlanta." + " I'm interested in swag, rap.", firstName: 'Bot', lastName: '', gender: 'Female', age: 25, weight: 48, height: 174, job: 'Bot', inseam: 44, email: '<EMAIL>', phoneNumber: '+375 44 123 12 12', location: 'Berlin, Germany', friends: [profile, profile2], onLine: false, }; export const profile10 = { photo: {imageSource: require('../../../assets/img/bot.png')}, about: "Hi! My name is Jen. I'm 41 and I live in Atlanta." + " I'm interested in swag, rap.", firstName: 'Bot', lastName: '', gender: 'Female', age: 25, weight: 48, height: 174, job: 'Bot', inseam: 44, email: '<EMAIL>', phoneNumber: '+375 44 123 12 12', location: 'Berlin, Germany', friends: [profile, profile2], onLine: false, }; export const profileSocials1 = { followers: 1500, following: 86, posts: 116, }; export const profileFavorites = { artists: ['Julia'], categories: ['R&B'], }; export const categorisedProfileActivity1 = { ['่ˆ‡ๆˆ‘ๅˆ†ไบซ']: [ { category: 'Sharing', source: { imageSource: require('../../../assets/img/image-feed-travel-1.jpg'), }, }, { category: 'Sharing', source: { imageSource: require('../../../assets/img/image-feed-travel-1.jpg'), }, }, { category: 'Sharing', source: { imageSource: require('../../../assets/img/image-feed-travel-1.jpg'), }, }, { category: 'Sharing', source: { imageSource: require('../../../assets/img/image-feed-travel-1.jpg'), }, }, { category: 'Sharing', source: { imageSource: require('../../../assets/img/image-feed-travel-1.jpg'), }, }, ], ['ๆˆ‘็š„ๆญŒๅ–ฎ']: [ { category: 'MyPlayList', source: { imageSource: require('../../../assets/img/sean.jpg'), }, }, { category: 'MyPlayList', source: { imageSource: require('../../../assets/img/sean.jpg'), }, }, { category: 'MyPlayList', source: { imageSource: require('../../../assets/img/sean.jpg'), }, }, { category: 'MyPlayList', source: { imageSource: require('../../../assets/img/sean.jpg'), }, }, { category: 'MyPlayList', source: { imageSource: require('../../../assets/img/sean.jpg'), }, }, ], // ['Style']: [ // { // category: 'Style', // source: { // imageSource: require('../../../assets/img/image-feed-travel-1.jpg'), // }, // }, // { // category: 'Style', // source: { // imageSource: require('../../../assets/img/image-feed-travel-1.jpg'), // }, // }, // { // category: 'Style', // source: { // imageSource: require('../../../assets/img/image-feed-travel-1.jpg'), // }, // }, // { // category: 'Style', // source: { // imageSource: require('../../../assets/img/image-feed-travel-1.jpg'), // }, // }, // { // category: 'Style', // source: { // imageSource: require('../../../assets/img/image-feed-travel-1.jpg'), // }, // }, // ], }; <file_sep>import React from 'react'; import {View} from 'react-native'; import {withStyles} from 'react-native-ui-kitten'; class ReactionBarComponent extends React.Component { render() { const {themedStyle, style, ...restProps} = this.props; return <View {...restProps} style={[themedStyle.container, style]} />; } } export const ReactionBar = withStyles(ReactionBarComponent, theme => ({ container: { flexDirection: 'row', }, })); <file_sep>import React from 'react'; import {LeftMessage} from './LeftMessage'; import {RightMessage} from './RightMessage'; const messageContents = { ['row-left']: { view(message, children) { return <LeftMessage message={message}>{children}</LeftMessage>; }, }, ['row-right']: { view(message, children) { return <RightMessage message={message}>{children}</RightMessage>; }, }, }; export function getMessageContent(alignment) { return messageContents[alignment]; } <file_sep>import React from 'react'; import {View} from 'react-native'; import {withStyles, List, ListItem} from 'react-native-ui-kitten'; import {ProfilePlayListItem} from './profilePlayListItem'; // @ts-ignore (override `renderItem` prop) class ProfilePlayListComponent extends React.Component { onItemPress = index => { this.props.onItemPress(index); }; renderItem = info => { const {themedStyle} = this.props; return ( <ProfilePlayListItem style={[themedStyle.item]} song={info.item} onPress={this.onItemPress} /> ); }; render() { const {contentContainerStyle, themedStyle, ...restProps} = this.props; return ( <View style={themedStyle.container}> <List showsHorizontalScrollIndicator={false} {...restProps} contentContainerStyle={[themedStyle.container, contentContainerStyle]} renderItem={this.renderItem} /> </View> ); } } export const ProfilePlayList = withStyles(ProfilePlayListComponent, theme => ({ container: {}, itemContainer: { paddingHorizontal: 0, paddingVertical: 0, marginHorizontal: 8, borderRadius: 8, overflow: 'hidden', }, item: { // width: 120, // height: 100, marginVertical: 0.5, }, })); <file_sep>const containerRow = { flexDirection: 'row', alignItems: 'center', }; const placements = { ['row-left']: { style() { return { ...containerRow, justifyContent: 'flex-start', }; }, }, ['row-right']: { style() { return { ...containerRow, justifyContent: 'flex-end', }; }, }, }; export function getContentAlignment(value) { return placements[value]; }<file_sep>import React from 'react'; import {View} from 'react-native'; import {withStyles, Button, Icon} from 'react-native-ui-kitten'; import {textStyle} from '../../common/style'; import {ValidationInput} from '../../common/validationInput'; import {NameValidator, PasswordValidator} from '../../../core/validators'; const EyeOffIconFill = style => { return <Icon {...style} name="eye-off" />; }; const PersonIconFill = style => { return <Icon {...style} name="person" />; }; class SignInForm2Component extends React.Component { state = { username: undefined, password: <PASSWORD>, }; componentDidUpdate(prevProps, prevState) { const oldFormValid = this.isValid(prevState); const newFormValid = this.isValid(this.state); const isStateChanged = this.state !== prevState; const becomeValid = !oldFormValid && newFormValid; const becomeInvalid = oldFormValid && !newFormValid; const remainValid = oldFormValid && newFormValid; if (becomeValid) { this.props.onDataChange(this.state); } else if (becomeInvalid) { this.props.onDataChange(undefined); } else if (isStateChanged && remainValid) { this.props.onDataChange(this.state); } } onForgotPasswordButtonPress = () => { this.props.onForgotPasswordPress(); }; onUsernameInputTextChange = username => { this.setState({username}); }; onPasswordInputTextChange = password => { this.setState({password}); }; isValid = value => { const {username, password} = value; return username !== undefined && password !== undefined; }; render() { const {style, themedStyle, ...restProps} = this.props; return ( <View style={[themedStyle.container, style]} {...restProps}> <View style={themedStyle.formContainer}> <ValidationInput textStyle={textStyle.paragraph} placeholder="User Name" icon={PersonIconFill} validator={NameValidator} onChangeText={this.onUsernameInputTextChange} /> <ValidationInput style={themedStyle.passwordInput} textStyle={textStyle.paragraph} placeholder="<PASSWORD>" icon={EyeOffIconFill} secureTextEntry={true} validator={PasswordValidator} onChangeText={this.onPasswordInputTextChange} /> <View style={themedStyle.forgotPasswordContainer}> <Button style={themedStyle.forgotPasswordButton} textStyle={themedStyle.forgotPasswordText} appearance="ghost" activeOpacity={0.75} onPress={this.onForgotPasswordButtonPress}> Forgot your password? </Button> </View> </View> </View> ); } } export const SignInForm2 = withStyles(SignInForm2Component, theme => ({ container: {}, forgotPasswordContainer: { flexDirection: 'row', justifyContent: 'flex-end', }, passwordInput: { marginTop: 16, }, forgotPasswordButton: { paddingHorizontal: 0, }, forgotPasswordText: { fontSize: 15, color: theme['text-hint-color'], ...textStyle.subtitle, }, })); <file_sep>import React from 'react'; import {ImageProps, View, ViewProps} from 'react-native'; import {withStyles, Text} from 'react-native-ui-kitten'; import {textStyle} from '../common/style'; class DiscoverTipsComponent extends React.Component { renderIconElement = style => { return this.props.icon(style); }; render() { const {style, themedStyle, icon, children} = this.props; return ( <View style={[themedStyle.container, style]}> {icon ? this.renderIconElement(themedStyle.icon) : null} <Text style={themedStyle.text}>{children}</Text> </View> ); } } export const DiscoverTips = withStyles(DiscoverTipsComponent, theme => ({ container: { flexDirection: 'row', }, icon: { width: 20, height: 20, marginRight: 18, tintColor: 'white', }, text: { color: 'white', ...textStyle.subtitle, }, })); <file_sep>import React, {Component} from 'react'; import {StyleSheet, View, Image, TouchableOpacity, Text} from 'react-native'; import MaterialCommunityIconsIcon from 'react-native-vector-icons/MaterialCommunityIcons'; export default class MaterialCardWithRightButtons extends React.Component { state = { playing: false, currentIndex: 0, playlist: this.props.playlist, image: this.props.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'][0]['source']['imageSource'], songName: this.props.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'][0]['name'], }; onNext = () => { if (this.state.currentIndex < this.state.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'].length) { this.setState({ currentIndex: this.state.currentIndex + 1, image: this.state.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'][this.state.currentIndex + 1][ 'source' ]['imageSource'], songName: this.state.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'][ this.state.currentIndex + 1 ]['name'], }); } }; onPrevious = () => { if (this.state.currentIndex < this.state.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'].length) { this.setState({ currentIndex: this.state.currentIndex + 1, image: this.state.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'][this.state.currentIndex - 1][ 'source' ]['imageSource'], songName: this.state.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'][ this.state.currentIndex - 1 ]['name'], }); } }; setPlaying = () => { if (this.state.playing === true) { this.setState({playing: false}); } else { this.setState({playing: true}); } }; render() { return ( <View style={[styles.container, this.props.style]}> <Image source={{uri: this.state.image}} style={styles.cardItemImagePlace}></Image> <View style={styles.buttonGroup}> <TouchableOpacity style={styles.leftBtn} onPress={this.onPrevious}> <MaterialCommunityIconsIcon name="skip-previous" style={styles.icon1}></MaterialCommunityIconsIcon> </TouchableOpacity> {this.state.playing ? ( <TouchableOpacity style={styles.centerBtn} onPress={() => this.setPlaying()}> <MaterialCommunityIconsIcon name="pause" style={styles.icon2}></MaterialCommunityIconsIcon> </TouchableOpacity> ) : ( <TouchableOpacity style={styles.centerBtn} onPress={() => this.setPlaying()}> <MaterialCommunityIconsIcon name="play" style={styles.icon2}></MaterialCommunityIconsIcon> </TouchableOpacity> )} <TouchableOpacity style={styles.rightBtn} onPress={this.onNext}> <MaterialCommunityIconsIcon name="skip-next" style={styles.icon3}></MaterialCommunityIconsIcon> </TouchableOpacity> </View> <Text style={styles.songName}>{`${this.state.songName}`}</Text> {/* <Text style={styles.artistName}>Artist name</Text> */} </View> ); } } // function MaterialCardWithRightButtons(props) { // const [playing, setPlaying] = React.useState(false); // const [currentIndex, setCurrentIndex] = React.useState(0); // const [image, setImage] = React.useState( // props.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'][0]['source']['imageSource'], // ); // const [songName, setSongName] = React.useState( // props.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'][0]['name'], // ); // onNext = () => { // if (currentIndex < props.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'].length) { // setCurrentIndex(currentIndex + 1); // setImage( // props.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'][currentIndex]['source']['imageSource'], // ); // setSongName(props.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'][currentIndex]['name']); // } // }; // onPrevious = () => { // if (currentIndex !== 0) { // setCurrentIndex(currentIndex - 1); // setImage( // props.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'][currentIndex]['source']['imageSource'], // ); // setSongName(props.playlist['ๆœ‹ๅ‹็ต„ๆˆ้›ปๅฐ'][currentIndex]['name']); // } // }; // return ( // <View style={[styles.container, props.style]}> // <Image source={{uri: image}} style={styles.cardItemImagePlace}></Image> // <View style={styles.buttonGroup}> // <TouchableOpacity style={styles.leftBtn} onPress={onPrevious}> // <MaterialCommunityIconsIcon // name="skip-previous" // style={styles.icon1}></MaterialCommunityIconsIcon> // </TouchableOpacity> // {playing ? ( // <TouchableOpacity // style={styles.centerBtn} // onPress={() => setPlaying(false)}> // <MaterialCommunityIconsIcon // name="pause" // style={styles.icon2}></MaterialCommunityIconsIcon> // </TouchableOpacity> // ) : ( // <TouchableOpacity // style={styles.centerBtn} // onPress={() => setPlaying(true)}> // <MaterialCommunityIconsIcon // name="play" // style={styles.icon2}></MaterialCommunityIconsIcon> // </TouchableOpacity> // )} // <TouchableOpacity style={styles.rightBtn} onPress={onNext}> // <MaterialCommunityIconsIcon // name="skip-next" // style={styles.icon3}></MaterialCommunityIconsIcon> // </TouchableOpacity> // </View> // <Text style={styles.songName}>{`${songName}`}</Text> // {/* <Text style={styles.artistName}>Artist name</Text> */} // </View> // ); // } const styles = StyleSheet.create({ container: { backgroundColor: '#FFF', flexWrap: 'nowrap', elevation: 3, borderRadius: 2, borderColor: '#CCC', borderWidth: 1, shadowOffset: { height: 2, width: -2, }, shadowColor: '#000', shadowOpacity: 0.1, shadowRadius: 1.5, overflow: 'hidden', }, cardItemImagePlace: { flex: 1, backgroundColor: '#ccc', minHeight: 210, }, buttonGroup: { flexDirection: 'row', alignSelf: 'flex-end', padding: 8, }, leftBtn: { marginRight: 8, marginLeft: 8, padding: 8, }, icon1: { fontSize: 24, color: '#000', opacity: 0.5, }, centerBtn: { marginRight: 8, marginLeft: 8, padding: 8, }, icon2: { fontSize: 24, color: '#000', opacity: 0.5, }, rightBtn: { marginRight: 8, marginLeft: 8, padding: 8, }, icon3: { fontSize: 24, color: '#000', opacity: 0.5, }, songName: { top: 210, left: 16, color: '#121212', position: 'absolute', fontFamily: 'roboto-regular', }, artistName: { top: 244, left: 69, color: 'rgba(74,74,74,1)', position: 'absolute', opacity: 0.82, fontFamily: 'roboto-regular', }, }); // export default MaterialCardWithRightButtons; <file_sep>import React from 'react'; import { ScrollView, AsyncStorage, ActivityIndicator, Dimensions, View, } from 'react-native'; import {withStyles} from 'react-native-ui-kitten'; import {SafeAreaView} from 'react-navigation'; import {ChatList} from '../components/ChatList'; import {PARTNER_IMGS} from '../../../core/data/default'; import axios from 'axios'; import moment from 'moment'; import _ from 'lodash'; class ChatListDemoComponent extends React.Component { state = { // conversations: conversations, conversations: [], rawConversations: [], searchEnabled: false, msnoView: '', }; componentDidMount() { AsyncStorage.getItem('user').then(res => { var user = JSON.parse(res); this.setState({msnoView: user['msno']}); this.getChatList(user['msno']); this.props.navigation.addListener('willFocus', () => this.getChatList(user['msno']), ); }); } handleOnNavigateBack = () => { AsyncStorage.getItem('user').then(res => { var user = JSON.parse(res); this.setState({msnoView: user['msno'], selfProfile: user}); this.getChatList(user['msno']); }); }; getChatList = selfMsno => { axios .get('https://kkfriends.app/chat-list', { params: { msno_view: selfMsno, }, }) .then(res => { var data = res.data; var chats = data['chats']; this.setState({rawConversations: chats}); var formatChats = _.map(chats, chat => { var date = moment(chat['ts'] * 1000); formatDate = date.format('HH:mm A'); var user = this.formatProfile(chat['user_t']); var formatChat = { interlocutor: user, messages: [ { author: user, date: formatDate, text: chat['message'], read: false, delivered: false, }, ], }; return formatChat; }); this.setState({conversations: formatChats, isLoaded: true}); }); }; formatProfile = profile => { var newProfile = { photo: { imageSource: _.has(PARTNER_IMGS, profile['msno']) ? PARTNER_IMGS[profile['msno']] : profile['img_url'], }, about: '', firstName: profile['name'], lastName: '', gender: profile['gender'], age: 0, weight: 0, height: 0, job: '', inseam: 0, email: profile['email'], phoneNumber: '0', location: 'Taipei, Taiwan', friends: [], online: true, msno: profile['msno'], }; return newProfile; }; onConversationPress = index => { this.props.navigation.push('ChatChatScreen', { msnoFrom: this.state.msnoView, msnoTo: this.state.rawConversations[index]['msno_t'], onNavigateBack: this.handleOnNavigateBack, stack: 'Chat', selfProfile: this.state.selfProfile, otherProfile: this.state.conversations[index]['interlocutor'], }); }; render() { const {themedStyle} = this.props; if (this.state.isLoaded) { return ( <SafeAreaView forceInset={{bottom: 'never'}}> <ScrollView> <ChatList searchEnabled={this.state.searchEnabled} conversations={this.state.conversations} onConversation={this.onConversationPress} /> </ScrollView> </SafeAreaView> ); } else { return ( <View style={themedStyle.loadContainer}> <ActivityIndicator size={'large'} /> </View> ); } } } export const ChatListDemo = withStyles(ChatListDemoComponent, theme => ({ loadContainer: { height: Dimensions.get('window').height, width: Dimensions.get('window').width, justifyContent: 'center', }, })); <file_sep>import React from 'react'; import {Dimensions} from 'react-native'; import {withStyles} from 'react-native-ui-kitten'; import Carousel from 'react-native-snap-carousel'; import {CardListItem} from './CardListItem'; class CardListComponent extends React.Component { onItemPress = profile => { this.props.onItemPress(profile); }; onItemLikePress = profile => { this.props.onItemLikePress(profile); }; onItemCommentPress = profile => { this.props.onItemCommentPress(profile); }; renderItem = (info, index) => { const {themedStyle} = this.props; return ( <CardListItem style={themedStyle.item} profile={info.item} onPress={this.onItemPress} onLikePress={this.onItemLikePress} onCommentPress={this.onItemCommentPress} /> ); }; render() { const {themedStyle, profiles} = this.props; return ( <Carousel style={themedStyle.container} ref={c => { this._carousel = c; }} data={profiles} renderItem={this.renderItem} sliderWidth={Dimensions.get('window').width} itemWidth={Dimensions.get('window').width - 60} /> ); } } export const CardList = withStyles(CardListComponent, theme => ({ container: { // paddingHorizontal: -16, // paddingVertical: 8, backgroundColor: theme['background-basic-color-2'], }, item: { marginVertical: 8, backgroundColor: theme['background-basic-color-1'], }, })); <file_sep>import React from 'react'; import {TouchableOpacity} from 'react-native'; import {withStyles, Text, Icon} from 'react-native-ui-kitten'; const HeartIconFill = style => <Icon name="heart" {...style} />; const HeartIconOutline = style => <Icon name="heart-outline" {...style} />; class LikeButtonComponent extends React.Component { render() { const { style, themedStyle, textStyle, children, filled, ...restProps } = this.props; return ( <TouchableOpacity style={[themedStyle.container, style]} {...restProps}> {filled ? HeartIconFill(themedStyle.icon) : HeartIconOutline(themedStyle.icon)} <Text style={[themedStyle.valueLabel, textStyle]} category="p2"> {children} </Text> </TouchableOpacity> ); } } export const LikeButton = withStyles(LikeButtonComponent, theme => ({ container: { flexDirection: 'row', alignItems: 'center', }, icon: { width: 36, height: 36, tintColor: theme['color-danger-default'], }, valueLabel: { marginHorizontal: 8, }, })); <file_sep>import React from 'react'; import {withStyles, Text} from 'react-native-ui-kitten'; import {textStyle} from '../common/style'; class MessageContentComponent extends React.Component { render() { const {themedStyle, message, children} = this.props; if (message.text) { return <Text style={themedStyle.messageLabel}>{message.text}</Text>; } else if (children) { return children; } else { return null; } } } export const MessageContent = withStyles(MessageContentComponent, theme => ({ messageLabel: { color: 'white', ...textStyle.paragraph, }, })); <file_sep>import React from 'react'; import {Platform, View} from 'react-native'; import {Button, Input, List, withStyles, Icon} from 'react-native-ui-kitten'; import {ChatMessage} from '../../messages/ChatMessage'; import {profile1, profile2} from '../../../core/data/profile'; import {AvoidKeyboard} from '../../common/avoidKeyboard'; import {textStyle} from '../../common/style'; import {StringValidator} from '../../../core/validators'; const MicIconFill = style => <Icon name="mic" {...style} />; const PaperPlaneIconFill = style => <Icon name="paper-plane" {...style} />; const PlusIconFill = style => <Icon name="plus" {...style} />; class ChatComponent extends React.Component { listRef = React.createRef(); onListContentSizeChange = () => { setTimeout(() => this.listRef.current.scrollToEnd({animated: true}), 0); }; onNewMessageChange = text => { this.props.onNewMessageChange(text); }; onMessageAdd = () => { this.props.onMessageAdd(); }; shouldRenderSendButton = () => { const {newMessage} = this.props; return StringValidator(newMessage); }; createUiMessages = () => { const {conversation} = this.props; return conversation.messages.map(message => { if (message.author === this.props.otherProfile) { return { ...message, alignment: 'row-left', }; } else if (message.author === this.props.selfProfile) { return { ...message, alignment: 'row-right', }; } }); }; renderMessage = info => { const {themedStyle} = this.props; return ( <ChatMessage style={themedStyle.message} index={info.index} message={info.item} alignment={info.item.alignment} /> ); }; renderSendMessageButton = () => { const {themedStyle} = this.props; return ( <Button style={themedStyle.addMessageButton} appearance="ghost" size="large" icon={PaperPlaneIconFill} onPress={this.onMessageAdd} /> ); }; keyboardOffset = height => { return Platform.select({ ios: height, android: 0, }); }; render() { const {themedStyle, newMessage} = this.props; const sendMessageButtonElement = this.shouldRenderSendButton() ? this.renderSendMessageButton() : null; return ( <AvoidKeyboard style={themedStyle.container} autoDismiss={false} offset={this.keyboardOffset}> <List ref={this.listRef} contentContainerStyle={themedStyle.chatContainer} data={this.createUiMessages()} onContentSizeChange={this.onListContentSizeChange} renderItem={this.renderMessage} /> <View style={themedStyle.inputContainer}> <Button style={themedStyle.addMessageButton} textStyle={textStyle.button} icon={PlusIconFill} onPress={() => {}} /> <Input icon={MicIconFill} style={themedStyle.messageInput} textStyle={textStyle.paragraph} value={newMessage} placeholder="Message..." onChangeText={this.onNewMessageChange} /> {sendMessageButtonElement} </View> </AvoidKeyboard> ); } } export const Chat = withStyles(ChatComponent, theme => ({ container: { flex: 1, backgroundColor: theme['background-basic-color-2'], }, chatContainer: { paddingHorizontal: 16, paddingVertical: 12, }, message: { marginVertical: 12, }, inputContainer: { padding: 16, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', backgroundColor: theme['background-basic-color-1'], }, addMessageButton: { width: 26, height: 26, borderRadius: 26, }, messageInput: { flex: 1, marginHorizontal: 8, }, })); <file_sep>import React from 'react'; import {View} from 'react-native'; import {withStyles} from 'react-native-ui-kitten'; class ActivityBarComponent extends React.Component { render() { const {style, themedStyle, children, ...restProps} = this.props; return ( <View style={[themedStyle.container, style]} {...restProps}> {children} </View> ); } } export const ActivityBar = withStyles(ActivityBarComponent, theme => ({ container: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', }, }));
298e5792aa48d76005af6ef52a0d64660f54e787
[ "JavaScript" ]
36
JavaScript
henryliou/kkmeet
83ef8494491adf50ab8e496e69aed10cf149196c
c329cfef21cb6998f3193098874b70cf573063d6
refs/heads/master
<file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { NavbarComponent } from './components/navbar/navbar.component'; import { QuizComponent } from './components/quiz/quiz.component'; import { RegisterComponent } from './components/register/register.component'; import { ResultComponent } from './components/result/result.component'; import {DashComponent} from './components/dash/dash.component'; const routes: Routes = [ { path : 'register' , component : RegisterComponent}, { path : 'result' , component : ResultComponent}, { path : 'quiz' , component : QuizComponent}, { path : 'dash' , component : DashComponent}, { path : '' , redirectTo : '/register' , pathMatch: 'full'}, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
d675050a5a0880f43cfd2126f732ea529ec662f4
[ "TypeScript" ]
1
TypeScript
achiradesilva123/Quiz-Demo
3e49ef6d67c4adc4969e89c78337d371f2151994
bd78c56a2387d42a31e1314c14d708b30b92b931
refs/heads/master
<file_sep> <div class="tile" style="height: 500px;"> <div class="content-title"> <div class="div"> <p id="_count-task"><?php echo(isset($_task)?count($_task):'0')?> cรดng viแป‡c</p> </div> <button class="btn btn-primary header-btn" type="button" id="_btn-task">Cรดng viแป‡c</button> </div> <div class="hide" id="_form-task"> <form id="f_task"> <input class="width-100per font-size-14" type="text" name="title" placeholder="Tiรชu ฤ‘แป cรดng viแป‡c" required=""> <input type="hidden" name="taskmaster" value="<?php echo($this->uri->segment(4))?>"> <input type="hidden" name="ticketid" value="<?php echo($this->uri->segment(3))?>"> <ul class="nav nav-tabs no-margin"> <li class="nav-item"> <a class="tsk-link active show" data-toggle="tab" href="#tab1"><i class="fa fa-user"></i></a> </li> <li class="nav-item hide"> <a class="tsk-link" data-toggle="tab" href="#tab2"><i class="fa fa-align-left"></i></a> </li> <li class="nav-item hide"> <a class="tsk-link" data-toggle="tab" href="#tab3"><i class="fa fa-paperclip"></i></a> </li> </ul> <div class="tab-content" id="myTabContent"> <div class="tab-pane fade active show" id="tab1"> <div class="hole"> <div class="col-md--4 padding-right-5"> <label class="tsk-label">Nhรณm phแปฅ trรกch</label> <select data-placeholder="Chแปn nhรณm phแปฅ trรกch..." class="tck-select my-chosen" name="tic"> <option value=""></option> <?php if (isset($l_agentgroup)) { foreach ($l_agentgroup as $key => $value) { echo '<option value="'.$value['groupid'].'">'.$value['groupname'].'</option>'; } } ?> </select> </div> <div class="col-md--4 padding-right-5"> <label class="tsk-label">Phรขn loแบกi</label> <select class="tck-select" name="tasktype" id="level_1"> <?php if (isset($l_type)) { foreach ($l_type as $key => $value) { echo '<option value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class="col-md--4 padding-right-5"> <label class="tsk-label">ฤแป™ ฦฐu tiรชn</label> <select class="tck-select" name="priority"> <option value="1">Thฦฐแปng</option> <option value="1">Cao</option> <option value="1">Khแบฉn cแบฅp</option> </select> </div> <div class="col-md--4 padding-right-5"> <label class="tsk-label">Phแปฅ trรกch</label> <select data-placeholder="Chแปn ngฦฐแปi phแปฅ trรกch..." class="tck-select my-chosen" name="pic"> <option value=""></option> <?php if (isset($l_age)) { foreach ($l_age as $cus) { if ($cus['custname']!='') { echo('<option value="'.$cus['custid'].'" data-group="'.$cus['groupid'].'">'.$cus['custname'].'</option>'); } } } ?> </select> </div> <div class="col-md--4 padding-right-5"> <label class="tsk-label">Chi tiแบฟt CV</label> <select class="tck-select" name="taskdetail" id="level_2"> <?php if (isset($l_detail)) { foreach ($l_detail as $key => $value) { $c=''; if (isset($l_type[0]['code']) && $value['ref1']!=$l_type[0]['code']) { $c="hide"; } echo '<option class="'.$c.'" ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class="col-md--4 padding-right-5"> </div> <div class="col-md--4 padding-right-5"> <label class="tsk-label">Ngร y yรชu cแบงu</label> <input class="tck-input" type="" name="req_date" > </div> <div class="col-md--4 padding-right-5"> <label class="tsk-label">Ngร y hแบนn</label> <input class="tsk-input" type="" name="due_date" > </div> <div class="col-md--4 margin-top-20 padding-right-5"> <button type="submit" class="btn btn-gray float-right margin-top-10"> <i class="fa fa-share"></i> Lฦฐu </button> <button type="button" id="_cancel" class="btn btn-default float-right margin-top-10 margin-right-5"> <i class="fa fa-times"></i> Hแปงy </button> </div> </div> </div> <div class="tab-pane fade" id="tab2"> <div class="hole"> <div class="col-md-12"> <label class="tsk-label">Ghi chรบ</label> <textarea></textarea> </div> <div class="col-md-12"> <button type="submit" class="btn btn-gray float-right margin-top-10"> <i class="fa fa-share"></i> Lฦฐu </button> <button type="button" id="_cancel" class="btn btn-default float-right margin-top-10 margin-right-5"> <i class="fa fa-share"></i> Hแปงy </button> </div> </div> </div> <div class="tab-pane fade" id="tab3"> <div class="hole"> <div class="col-md-6"> <label class="tsk-label">ฤรญnh kรจm file</label> <input type="file" name=""> </div> <div class="col-md-12"> <button type="submit" class="btn btn-gray float-right margin-top-10"> <i class="fa fa-times"></i> Lฦฐu </button> <button type="submit" class="btn btn-default float-right margin-top-10 margin-right-5"> <i class="fa fa-share"></i> Hแปงy </button> </div> </div> </div> </div> </form> </div> <div class="table-responsive"> <table class="table" id="_tb-task"> <tbody> <?php if (isset($_task)) { foreach ($_task as $key => $value) { $class = '';$icon=''; if ($value['status']=='O') { $class = 'label-circle label-default span-default';$icon = 'fa fa-check'; }elseif ($value['status']=='W') { $class = 'label-circle label-warning span-warning';$icon = 'fa fa-exclamation'; }elseif ($value['status']=='C') { $class = 'label-circle span-success';$icon = 'fa fa-check'; } ?> <tr class="border-bot-1"> <td width="200"> <span class="<?php echo($class)?>"> <i class="<?php echo($icon)?>"></i> </span> <div class="flex" style="float:right;margin-top:-5px"> <div class="task-user-name" style="width:100%"><?php echo($value['picname']!=''?$value['picname']:$value['ticname'])?></div> </div> </td> <td> <a class="new_tab" onclick="addTab('<?php echo(base_url('task/detail/'.$value['taskid']))?>','#<?php echo($value['taskid'])?>')" href="#"><?php echo($value['title'])?></a> </td> <td width="120"><?php echo date('d-m-Y H:i',strtotime($value['duedate']))?></td> </tr> <?php }} ?> </tbody> </table> </div> </div><file_sep><script type="text/javascript"> var dayCompare = new Date("2000-01-01T00:00:00"); $(document).ready( function () { loadFirst(); }); function selectCity(obj){ var $id = obj.value; $('.gicungdc').remove(); $.ajax({ url: '<?php echo base_url()?>user/selectCity', type: 'POST', dataType: 'JSON', data: {id_city : $id}, }) .done(function(data) { for (var i = 0; i < data.length; i++) { $('#dodulieu').after('<option class="gicungdc" value="'+data[i]['id_district']+'">'+data[i]['name']+'</option>'); } }) .fail(function() { console.log("error"); }) } function selectDistrict(obj){ var $id = obj.value; $('.gicungdc1').remove(); $.ajax({ url: '<?php echo base_url()?>user/selectDistrict', type: 'POST', dataType: 'JSON', data: {id_district : $id}, }) .done(function(data) { for (var i = 0; i < data.length; i++) { $('#dodulieu1').after('<option selected class="gicungdc1" value="'+data[i]['id_ward']+'">'+data[i]['name']+'</option>'); } }) .fail(function() { console.log("error"); }) } $('#demoNotify').click(function(){ $.notify({ title: "Update Complete : ", message: "Something cool is just updated!", icon: 'fa fa-check' , url: 'https://github.com/mouse0270/bootstrap-notify', target: '_blank' },{ // settings element: 'body', position: null, type: "info", allow_dismiss: true, newest_on_top: false, showProgressbar: false, placement: { from: "top", align: "right" }, offset: { x: 10, y: 40 }, spacing: 10, z_index: 1031, delay: 5000, timer: 1000, url_target: '_blank', mouse_over: null, animate: { enter: 'animated fadeInDown', exit: 'animated fadeOutUp' }, onShow: null, onShown: null, onClose: null, onClosed: null, icon_type: 'class', template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' + '<button type="button" aria-hidden="true" class="close" data-notify="dismiss">ร—</button>' + '<span data-notify="icon"></span> ' + '<span data-notify="title">{1}</span> ' + '<span data-notify="message">{2}</span>' + '<div class="progress" data-notify="progressbar">' + '<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' + '</div>' + '<a href="{3}" target="{4}" data-notify="url"></a>' + '</div>' }); }); $('#demoSwal').click(function(){ swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, confirmButtonText: "Yes, delete it!", cancelButtonText: "No, cancel plx!", closeOnConfirm: false, closeOnCancel: false }, function(isConfirm) { if (isConfirm) { swal("Deleted!", "Your imaginary file has been deleted.", "success"); } else { swal("Cancelled", "Your imaginary file is safe :)", "error"); } }); }); $('#demoModal').click(function(){ var modal = $( '<div class="modal fade">\ <div class="modal-dialog" role="document">\ <div class="modal-content">\ <div class="modal-header">\ <h5 class="modal-title">Ghรฉp vร o mแป™t ngฦฐแปi khรกc</h5>\ <button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">ร—</span></button>\ </div>\ <div class="modal-body">\ <div class="flex">\ <div class="div user-call-pad col-sm-5">\ <p class="phone-name"><img class="user-avatar phone-avatar" src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phแบกm</p>\ <p class="phone-num header-desc field-click-able">038 8485 4949</p>\ <p class="phone-time header-desc field-click-able">00 : 00 : 25</p>\ </div>\ <div class="row col-sm-7">\ <div class="col-md-3">\ <span class="user-history-label span-danger">O</span>\ <span>5</span>\ </div>\ <div class="col-md-3">\ <span class="user-history-label span-warning">P</span>\ <span>5</span>\ </div>\ <div class="col-md-3">\ <span class="user-history-label span-success">S</span>\ <span>5</span>\ </div>\ <div class="col-md-3">\ <span class="user-history-label span-info">R</span>\ <span>5</span>\ </div>\ <div class="col-md-3">\ <span class="fa fa-phone user-history-icon span-default"></span>\ <span>5</span>\ </div>\ <div class="col-md-3">\ <span class="fa fa-comment user-history-icon span-default"></span>\ <span>5</span>\ </div>\ <div class="col-md-3">\ <span class="fa fa-file-alt user-history-icon span-default"></span>\ <span>5</span>\ </div>\ </div>\ </div>\ <p>Tรฌm ngฦฐแปi cแบงn ghรฉp</p>\ <div id="call-input">\ <input class="form-control margin-top-10 margin-bot-5" type="text" name="" placeholder="Phone Number or name">\ </div>\ <div class="flex">\ <div class="div user-call-pad col-sm-6">\ <p class="phone-name"><img class="user-avatar phone-avatar" src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phแบกm</p>\ <p class="phone-num header-desc field-click-able">038 8485 4949</p>\ <p class="phone-time header-desc field-click-able">00 : 00 : 25</p>\ </div>\ <div class="div user-call-pad col-sm-6">\ <p class="phone-name"><img class="user-avatar phone-avatar" src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phแบกm</p>\ <p class="phone-num header-desc field-click-able">038 8485 4949</p>\ <p class="phone-time header-desc field-click-able">00 : 00 : 25</p>\ </div>\ </div>\ </div>\ <div class="modal-footer">\ <button class="btn btn-primary btn-89" type="button" data-dismiss="modal">Hแปงy</button>\ <button class="btn btn-secondary btn-89" type="button">Ghรฉp</button>\ </div>\ </div>\ </div>\ </div>'); modal.modal("show").on("hidden", function(){ modal.remove(); }); }); function formatNumber (num) { return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") } function arrayContains(needle, arrhaystack) { return (arrhaystack.indexOf(needle) > -1); } function formatDMY(dd,mm,yyyy) { if(dd<10){ dd='0'+dd; } if(mm<10){ mm='0'+mm; } var today = dd+'/'+mm+'/'+yyyy; return today; } function loadFirst(){ $.fn.dataTable.moment('DD/MM/YYYY'); var arrayCheck = []; var contractid = '<?php echo $this->uri->segment(3) ?>'; $('.nav-tabs') .scrollingTabs({ enableSwiping: true }) .on('ready.scrtabs', function() { $('.tab-content').show(); }); $.ajax({ url: 'http://crm.tavicosoft.com/api/get_erp_token/C0001', type: 'GET', dataType: 'JSON' }) .done(function(data) { var json = jQuery.parseJSON(data); // $(".a_contractid").attr('href','http://demo.tavicosoft.com/connectdb/loginprovider?opid=<?php echo $this->input->get('opid') ?>&returnUrl=%2F%23PCT&token='+json.result.data+'&dataseg=contractid%3D<?php echo $trade[0]['contractid'] ?>%26action%3DV'); $(".a_contractid").attr('href','http://demo.tavicosoft.com/connectdb/loginprovider?opid=C0001@AGT&returnUrl=%2F%23PCT&token='+json.result.data+'&dataseg=contractid%3D<?php echo $trade[0]['contractid'] ?>%26action%3DV'); $(".a_custid").attr('href','http://demo.tavicosoft.com/connectdb/loginprovider?opid=<?php echo $this->input->get('opid') ?>&returnUrl=%2F%23NAD&token='+json.result.data+'&dataseg=nadcode%3D<?php echo $trade[0]['clientcode'] ?>%26action%3DV'); }) .fail(function() { console.log('Load Fail!!!'); }) $('#table-1-ticketcontract').DataTable({ "paging": false, "info": false, "searching": false, "scrollY": "235px", "scrollX": true, "scrollCollapse": true, "bAutoWidth": true, "ajax": "<?php echo base_url() ?>user/loadTicketContract/"+contractid, dom: "Bfrtip", "processing": true, 'language':{ "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />", "processing": "" } }); $.ajax('http://crm.tavicosoft.com/api/get_list_contract',{ 'data': JSON.stringify({ "reportcode":"crmContract01e", "limit":25, "start":0, "queryFilters":{"contractid":contractid} }), 'type': 'POST', 'processData': false, 'contentType': 'application/json' }) .done(function(data) { $('#div-content-1').css("background","none"); var obj = jQuery.parseJSON(data); if(obj.result.data.length >0) { var data_html=''; for (var i = 0; i < obj.result.data.length; i++) { if(obj.result.data[i].name !== null) { var name = obj.result.data[i].name; }else{var name ='';} if(obj.result.data[i].gender !== null) { var gender = obj.result.data[i].gender; }else{var gender ='';} if(obj.result.data[i].birthday !== null) { var birthday = obj.result.data[i].birthday+"/"+obj.result.data[i].birthmonth+"/"+obj.result.data[i].birthyear; }else{var birthday ='';} if(obj.result.data[i].telephone !== null) { var telephone = obj.result.data[i].telephone; }else{var telephone ='';} if(obj.result.data[i].email !== null) { var email = obj.result.data[i].email; }else{var email ='';} if(obj.result.data[i].idcard !== null) { var idcard = obj.result.data[i].idcard; }else{var idcard ='';} if(obj.result.data[i].issueddate !== null) { var t3 = new Date(obj.result.data[i].issueddate); if(t3 > dayCompare) { var issueddate = formatDMY(t3.getDate(),t3.getMonth()+1,t3.getFullYear()); }else{var issueddate = ''} }else{var issueddate ='';} if(obj.result.data[i].issuedplace !== null) { var issuedplace = obj.result.data[i].issuedplace; }else{var issuedplace ='';} if(obj.result.data[i].residencyaddress !== null) { var residencyaddress = obj.result.data[i].residencyaddress; }else{var residencyaddress ='';} if(obj.result.data[i].contactaddress !== null) { var contactaddress = obj.result.data[i].contactaddress; }else{var contactaddress ='';} if(obj.result.data[i].title !== null) { var title = obj.result.data[i].title; }else{var title ='';} if(obj.result.data[i].bankaccountno !== null) { var bankaccountno = obj.result.data[i].bankaccountno; }else{var bankaccountno ='';} if(obj.result.data[i].bankname !== null) { var bankname = obj.result.data[i].bankname; }else{var bankname ='';} if(obj.result.data[i].nationalily !== null) { var nationalily = obj.result.data[i].nationalily; }else{var nationalily ='';} if(obj.result.data[i].cellphone !== null) { var cellphone = obj.result.data[i].cellphone; }else{var cellphone ='';} if(obj.result.data[i].authorizedletter !== null) { var authorizedletter = obj.result.data[i].authorizedletter; }else{var authorizedletter ='';} if(obj.result.data[i].company !== null) { var company = obj.result.data[i].company; }else{var company ='';} if(obj.result.data[i].remarks !== null) { var remarks = obj.result.data[i].remarks; }else{var remarks ='';} data_html+='<div class="row">\ <div class="col-md-4">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Hแป vร  Tรชn: </strong></label>\ <label for="exampleInputName2">'+name+'</label>\ </div>\ </div>\ <div class="col-md-4">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Giแป›i tรญnh: </strong></label>\ <label for="exampleInputName2">'+gender+'</label>\ </div>\ </div>\ <div class="col-md-4">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Ngร y sinh: </strong></label>\ <label for="exampleInputName2">'+birthday+'</label>\ </div>\ </div>\ </div>\ <div class="row">\ <div class="col-md-6">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Sแป‘ ฤ‘iแป‡n thoแบกi: </strong></label>\ <label for="exampleInputName2">'+telephone+'</label>\ </div>\ </div>\ <div class="col-md-6">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Email: </strong></label>\ <label for="exampleInputName2">'+email+'</label>\ </div>\ </div>\ </div>\ <div class="row">\ <div class="col-md-4">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Sแป‘ CMND: </strong></label>\ <label for="exampleInputName2">'+idcard+'</label>\ </div>\ </div>\ <div class="col-md-4">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Ngร y cแบฅp: </strong></label>\ <label for="exampleInputName2">'+issueddate+'</label>\ </div>\ </div>\ <div class="col-md-4">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Nฦกi cแบฅp: </strong></label>\ <label for="exampleInputName2">'+issuedplace+'</label>\ </div>\ </div>\ </div>\ <div class="row">\ <div class="col-md-12">\ <div class="form-group">\ <label for="exampleInputName2"><strong>ฤแป‹a chแป‰ thฦฐแปng trรบ: </strong></label>\ <label for="exampleInputName2">'+residencyaddress+'</label>\ </div>\ </div>\ </div>\ <div class="row">\ <div class="col-md-12">\ <div class="form-group">\ <label for="exampleInputName2"><strong>ฤแป‹a chแป‰ liรชn lแบกc: </strong></label>\ <label for="exampleInputName2">'+contactaddress+'</label>\ </div>\ </div>\ </div>\ <div class="row">\ <div class="col-md-4">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Chแปฉc vแปฅ: </strong></label>\ <label for="exampleInputName2">'+title+'</label>\ </div>\ </div>\ <div class="col-md-4">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Sแป‘ TKNH: </strong></label>\ <label for="exampleInputName2">'+bankaccountno+'</label>\ </div>\ </div>\ <div class="col-md-4">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Ngรขn hร ng: </strong></label>\ <label for="exampleInputName2">'+bankname+'</label>\ </div>\ </div>\ </div>\ <div class="row">\ <div class="col-md-4">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Quแป‘c gia: </strong></label>\ <label for="exampleInputName2">'+nationalily+'</label>\ </div>\ </div>\ <div class="col-md-4">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Sแป‘ DTDD: </strong></label>\ <label for="exampleInputName2">'+cellphone+'</label>\ </div>\ </div>\ \ <div class="col-md-4">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Giแบฅy uแปท quyแปn: </strong></label>\ <label for="exampleInputName2">'+authorizedletter+'</label>\ </div>\ </div>\ \ </div>\ <div class="row">\ <div class="col-md-12">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Cรดng ty: </strong></label>\ <label for="exampleInputName2">'+company+'</label>\ </div>\ </div>\ \ </div>\ \ <div class="row">\ <div class="col-md-12">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Ghi chรบ: </strong></label>\ <label for="exampleInputName2">'+remarks+'</label>\ </div>\ </div>\ </div>'; } $('#div-content-1').html(data_html); } }) .fail(function() { console.log("error"); }) $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { var contractid = '<?php echo $this->uri->segment(3) ?>'; var target = $(e.target).attr("alt") ; var check = arrayContains(target,arrayCheck); if(check == true) { return; } else{arrayCheck.push(target);} if(target == "crmContract01b") { $('#table-1-history').DataTable({ "paging": false, "info": false, "searching": false, "scrollX": true, "scrollCollapse": true, "bAutoWidth": true, "ajax": "<?php echo base_url() ?>user/getHistory/"+contractid, dom: "Bfrtip", "processing": true, 'language':{ "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />", "processing": "" } }); } else if(target == "crmContract01c"){ $('#table-1-congno').DataTable({ "paging": false, "info": false, "searching": false, "scrollX": true, "scrollCollapse": true, "bAutoWidth": true, dom: "Bfrtip", "processing": true, 'language':{ "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />", "processing": "" }, "ajax": '<?php echo base_url() ?>user/getCongnoThanhtoan/'+contractid }); } else if(target == "crmContract01d"){ $('#table-1-gift').DataTable({ "paging": false, "info": false, "searching": false, "scrollY": "235px", "scrollX": true, "scrollCollapse": true, "bAutoWidth": true, "ajax": "<?php echo base_url() ?>user/getGift/"+contractid, dom: "Bfrtip", "processing": true, 'language':{ "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />", "processing": "" } }); } else if(target == "crmContract01f"){ $('#table-1-buss').DataTable({ "paging": false, "info": false, "searching": false, "scrollY": "235px", "scrollX": true, "scrollCollapse": true, "bAutoWidth": true, "ajax": "<?php echo base_url() ?>user/getBussEmployee/"+contractid, dom: "Bfrtip", "processing": true, 'language':{ "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />", "processing": "" } }); } else if(target == "crmContract01h"){ $('#table-1-notes').DataTable({ "paging": false, "info": false, "searching": false, "scrollY": "235px", "scrollX": true, "scrollCollapse": true, "bAutoWidth": true, "ajax": "<?php echo base_url() ?>user/getNotes/"+contractid, dom: "Bfrtip", "processing": true, 'language':{ "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />", "processing": "" } }); } else if(target == "crmContract01g") { $.ajax('http://crm.tavicosoft.com/api/get_list_contract',{ 'data': JSON.stringify({ "reportcode":target, "limit":25, "start":0, "queryFilters":{"contractid":contractid} }), 'type': 'POST', 'processData': false, 'contentType': 'application/json' }) .done(function(data) { var obj = jQuery.parseJSON(data); $("#div-content-6").css('background', 'none'); if(obj.result.data.length >0){ if (obj.result.data[0].duedate !== null) { var t2 = new Date(obj.result.data[0].duedate); if(t2 > dayCompare) { var duedate = formatDMY(t2.getDate(),t2.getMonth()+1,t2.getFullYear()); } else{var duedate = '';} }else{ var duedate = "";} if (obj.result.data[0].adjustdate !== null) { var t2 = new Date(obj.result.data[0].adjustdate); if(t2 > dayCompare) { var adjustdate = formatDMY(t2.getDate(),t2.getMonth()+1,t2.getFullYear()); }else{var adjustdate ='';} }else{ var adjustdate = "";} if (obj.result.data[0].value0 !== null) { var value0 = formatNumber(obj.result.data[0].value0); }else{ var value0 = "";} if (obj.result.data[0].value3 !== null) { var value3 = formatNumber(obj.result.data[0].value3); }else{ var value3 = "";} if (obj.result.data[0].value1 !== null) { var value1 = formatNumber(obj.result.data[0].value1); }else{ var value1 = "";} if (obj.result.data[0].value2 !== null) { var value2 = formatNumber(obj.result.data[0].value2); }else{ var value2 = "";} if (obj.result.data[0].pptarea !== null) { var pptarea = obj.result.data[0].pptarea; }else{ var pptarea = "";} if (obj.result.data[0].contractvalue !== null) { var contractvalue = formatNumber(obj.result.data[0].contractvalue); }else{ var contractvalue = "";} if (obj.result.data[0].comments !== null) { var comments = obj.result.data[0].comments; }else{ var comments = "";} $('#div-content-6').html('<div class="row">\ <div class="col-md-6">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Ngร y ฤc: </strong></label>\ <label for="exampleInputName2">'+ // obj.result.data[0].adjustdate adjustdate +'</label>\ </div>\ </div>\ <div class="col-md-6">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Giรก bรกn chฦฐa VAT: </strong></label>\ <label for="exampleInputName2">'+ value0+'</label>\ </div>\ </div>\ </div>\ <div class="row">\ <div class="col-md-6">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Ngร y ฤ‘แบฟn hแบกn: </strong></label>\ <label for="exampleInputName2">'+duedate+'</label>\ </div>\ </div>\ <div class="col-md-6">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Thuแบฟ VAT: </strong></label>\ <label for="exampleInputName2">'+ value1 +'</label>\ </div>\ </div>\ </div>\ </div>\ <div class="row">\ <div class="col-md-6">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Diแป‡n tรญch: </strong></label>\ <label for="exampleInputName2">'+ pptarea +'</label>\ </div>\ </div>\ <div class="col-md-6">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Phรญ bแบฃo trรฌ: </strong></label>\ <label for="exampleInputName2">'+value2+'</label>\ </div>\ </div>\ </div>\ <div class="row">\ <div class="col-md-6">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Giรก trแป‹ hแปฃp ฤ‘แป“ng: </strong></label>\ <label for="exampleInputName2">'+ contractvalue+'</label>\ </div>\ </div>\ <div class="col-md-6">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Giรก trแป‹ quyแปn SDฤ:</strong></label>\ <label for="exampleInputName2">'+value3 +'</label>\ </div>\ </div>\ </div>\ <div class="row">\ <div class="col-md-12">\ <div class="form-group">\ <label for="exampleInputName2"><strong>Ghi chรบ: </strong></label>\ <label for="exampleInputName2">'+ comments +'</label>\ </div>\ </div>\ </div>'); } }).fail(function() { console.log("error"); }) } }); $("a[data-toggle=\"tab\"]").on("shown.bs.tab", function (e) { $($.fn.dataTable.tables(true)).DataTable().columns.adjust(); }); } </script> <style> ::-webkit-scrollbar { width: 0px; height: 4px; background: transparent; } ::-webkit-scrollbar-thumb { background: #56b8b6; } </style><file_sep><?php $handle = fopen("log.txt","a+"); var_dump($_REQUEST); $data = json_decode(file_get_contents('php://input'), true); var_dump($data); $raw = json_encode($data); fwrite($handle,$raw."\n\t"); fclose($handle); echo "</br>Here</br>"; $ch = curl_init("http://crm.tavicosoft.com:3000/call"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $raw); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json' )); $result = curl_exec($ch); var_dump($result); ?><file_sep><?php //<NAME> //Ngร y : 10-09-09 //Custid : <NAME> , duy nhแบฅt defined('BASEPATH') OR exit('No direct script access allowed'); class M_user extends CI_Model { /*Xแปฉ lรฝ tแบฅt cแบฃ logic cแปงa user แปŸ ฤ‘รขy*/ public function __construct() { parent::__construct(); } //API URL Gแปi lแบฅy dแปฑ liแป‡u DB private $url_api_db = "http://test.tavicosoft.com/crm/index.php/"; //Lแบฅy user bแบฑng custid public function getUserByCustId($custid,$dataAuth){ $user = $this->cache->memcached->get('user_'.$custid); //$user = null; if (!$user){ $user = file_get_contents($this->url_api_db.'customer/getcustomerbycustid/'.urlencode($custid).''); $this->cache->memcached->save('user_'.$custid,$user, 86400); } return json_decode($user,true); } public function getTicketById($ticketid){ //$result = $this->cache->memcached->get('ticket_'.$ticketid); if (!$result){ $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/search?search=&ticketid='.$ticketid.''); $this->cache->memcached->save('ticket_'.$ticketid,$result, 86400); } return $result; } public function updateUser($custid,$dataUpdate,$dataAuth){ $this->cache->memcached->delete('user_'.$custid); } }<file_sep>#!/bin/bash /usr/bin/pm2 stop ~/callevent/server.js <file_sep><form id="insertUserVal" method="POST" role="form"> <input type="hidden" name="log_groupid" id="log_groupid" value="<?php echo $detail[0]['groupid'] ?>"> <input type="hidden" name="opid" id="opid" value="<?php echo $detail[0]['opid']?>"> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-10"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Phรขn quyแปn</label> <select id="roleid" class="control-label col-md-8 no-border no-padding margin-left-10" <?php $var = $this->session->userdata; $roleid = $var['roleid']; if($roleid =='2'){echo 'disabled';} ?>> <?php foreach ($role_list as $key => $value) { ?> <option value="<?php echo $key ?>" ><?php echo $value?></option> <?php } ?> </select> </div> <input type='hidden' custid='<?php echo $detail[0]['custid'] ?>' id="cusit_id" /> <div class=""> <label class="control-label user-label col-md-3 no-padding">Nhรณm</label> <select class="control-label col-md-8 no-border no-padding margin-left-10 grouplist" id="groupid" name="groupid"> <?php foreach ($group_list as $value) { ?> <option value="<?php echo $value['groupid'] ?>" ><?php echo $value['groupname']?></option> <?php } ?> </select> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-10"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Hแป vร  Tรชn</label> <label class="control-label col-md-8 no-padding-right"> <input name="custname" id="custname" class="col-md-12 no-padding font-size-12" minlength="4" maxlength="30" value="<?php echo $detail[0]['custname'] ?>"> </label> </div> <div class="" <?php if($detail[0]['roleid'] !='3'){echo 'hidden';} ?>> <label class="control-label user-label col-md-3 no-padding">Danh xฦฐng</label> <select name="gender"class="control-label col-md-8 no-border no-padding margin-left-10" id="gender"> <option value="M">ร”ng</option> <option value="F">Bร </option> </select> </div> <div class="" <?php if($detail[0]['roleid'] !='3'){echo 'hidden';} ?>> <label class="control-label user-label col-md-3 no-padding">CMND/Passport:</label> <label class="control-label col-md-8 no-padding-right"> <input type="text" name="idcard" id="idcard" class="col-md-12 no-padding font-size-12" value="<?php echo $detail[0]['idcard'] ?>" required minlength="8" /> </label> </div> <div class="" <?php if($detail[0]['roleid'] !='3'){echo 'hidden';} ?>> <label class="control-label user-label col-md-3 no-padding">Ngร y sinh:</label> <label class="control-label col-md-8 no-padding-right"> <input name="fullbirthday" id="fullbirthday" class="col-md-12 no-padding font-size-12" value="<?php echo $detail[0]['fullbirthday'] ?>"> </label> </div> <div class="break-line margin-bot-5"></div> <div class=""> <label class="control-label user-label col-md-3 no-padding">ฤiแป‡n thoแบกi</label> <label class="control-label col-md-8 no-padding-right"> <input <?php if($detail[0]['roleid']== '3'){ echo ''; } else{echo 'readonly';} ?> minlength="10" maxlength="11" name="telephone" id="telephone" class="col-md-12 no-padding font-size-12" value="<?php echo $detail[0]['telephone'] ?>"> </label> <input type="hidden" name="listtelephone" id="listtelephone" value="<?php echo $detail[0]['telephonelist'] ?>"> <?php if($detail[0]['telephonelist'] != ''){ ?> <label class="control-label user-label col-md-3 no-padding"></label> <label class="control-label col-md-8 no-padding-right"> <?php $arrayTelephone = explode(",",$detail[0]['telephonelist']); if(count($arrayTelephone) >0) { foreach ($arrayTelephone as $rows) { ?> <div class="row"> <input class="col-md-9 padding-left-15 font-size-12" value="<?php echo $rows ?>"> <a href="#" onclick="removephone('<?php echo $rows ?>','<?php echo $detail[0]['telephonelist'];?>','<?php echo $detail[0]['roleid'];?>','<?php echo $detail[0]['groupid'];?>')"><i class="fas fa-times-circle fa-md float-right margin-top-3" style="margin-right: 2px"></i></a> <!--<a href="#"><i class="fas fa-arrow-circle-up fa-md float-right margin-top-3"></i></a>--> </div> <?php }}} ?> </label> </div> <?php if($detail[0]['queue']!=null ){?> <div class="div-queue"> <label class="control-label user-label col-md-3 no-padding">Hร ng chแป cuแป™c gแปi</label> <select class="control-label col-md-8 no-border no-padding margin-left-10" id="queue"> <option <?php if($detail[0]['queue'] == '21114'){echo 'selected';} ?> value="21114" >Chuyแปƒn nhฦฐแปฃng hแปฃp ฤ‘แป“ng</option> <option <?php if($detail[0]['queue'] == '21115'){echo 'selected';} ?> value="21115" >Thanh toรกn vay</option> <option <?php if($detail[0]['queue'] == '21121'){echo 'selected';} ?> value="21121" >Tiแบฟng Anh</option> <option <?php if($detail[0]['queue'] == '21116'){echo 'selected';} ?> value="21116" >Khรกc</option> </select> <input type="hidden" id="queue_old" value="<?php echo $detail[0]['queue'] ?>"> </div> <?php } ?> <div class=""> <label class="control-label user-label col-md-3 no-padding"></label> <label class="control-label col-md-8 no-padding-right field-click-able"><a data-toggle="modal" data-target="#insertPhone">+ Thรชm sแป‘ liรชn lแบกc</a></label> </div> <div class="break-line margin-bot-5"></div> <div class=""> <label class="control-label user-label col-md-3 no-padding">E-mail</label> <label class="control-label col-md-8 no-padding-right"> <input name="email" id="email" minlength="4" maxlength="30" type="email" class="col-md-9 no-padding font-size-12" value="<?php echo $detail[0]['email'] ?>"> </label> <?php if($detail[0]['emaillist'] != ''){ ?> <label class="control-label user-label col-md-3 no-padding"></label> <label class="control-label col-md-8 no-padding-right"> <?php $arrayEmail = explode(",",$detail[0]['emaillist']); if(count($arrayEmail) >0) { foreach ($arrayEmail as $rows) { ?> <div class="row"> <input class="col-md-9 padding-left-15 font-size-12" value="<?php echo $rows ?>"> <a href="#" onclick="removeemail('<?php echo $rows ?>','<?php echo $detail[0]['emaillist'];?>','<?php echo $detail[0]['roleid'];?>','<?php echo $detail[0]['groupid'];?>')"><i class="fas fa-times-circle fa-md float-right margin-top-3" style="margin-right: 2px"></i></a> <!--<a href="#" ><i class="fas fa-arrow-circle-up fa-md float-right margin-top-3"></i></a>--> </div> <?php }}} ?> </label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding"></label> <label class="control-label col-md-8 no-padding-right field-click-able"><a data-toggle="modal" data-target="#insertEmail">+ Thรชm ฤ‘แป‹a chแป‰ e-mail</a></label> </div> <div class="break-line margin-bot-5"></div> <div class="div-address" <?php if($detail[0]['roleid'] !='3'){echo 'hidden';} ?>> <?php if (count($address) == 0) { ?> <label class="control-label user-label col-md-3 no-padding">ฤแป‹a chแป‰</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12" value=""> </label> <?php } for ($i=0; $i < count($address); $i++) { if($address[$i]['hidden'] != 1 && $address[$i]['mainaddress'] == 1){ ?> <label class="control-label user-label col-md-3 no-padding">ฤแป‹a chแป‰</label> <label class="control-label col-md-8 no-padding-right"> <input onclick="openModalEdit( '<?php echo $address[$i]['label'] ?>', '<?php echo $address[$i]['city'] ?>', '<?php echo $address[$i]['district'] ?>', '<?php echo $address[$i]['ward'] ?>', '<?php echo $address[$i]['street'] ?>', '<?php echo $address[$i]['address'] ?>', '<?php echo $address[$i]['addressid'] ?>' )" class="col-md-12 no-padding font-size-12" value="<?php echo $address[$i]['label'] ?>" data-toggle="tooltip" data-placement="right" title="<?php echo $address[$i]['fulladdress'] ?>"> </label> <?php }} for ($i=0; $i < count($address); $i++) { if($address[$i]['hidden'] != 1 && $address[$i]['mainaddress'] == 0){ ?> <label class="control-label user-label col-md-3 no-padding"></label> <label class="control-label col-md-7 no-padding-right"> <input onclick="openModalEdit( '<?php echo $address[$i]['label'] ?>', '<?php echo $address[$i]['city'] ?>', '<?php echo $address[$i]['district'] ?>', '<?php echo $address[$i]['ward'] ?>', '<?php echo $address[$i]['street'] ?>', '<?php echo $address[$i]['address'] ?>', '<?php echo $address[$i]['addressid'] ?>' )" class="col-md-12 no-padding font-size-12" value="<?php echo $address[$i]['label'] ?>" data-toggle="tooltip" data-placement="right" title="<?php echo $address[$i]['fulladdress'] ?>"> </label> <a href="#" onclick="removeAddress('<?php echo $address[$i]['addressid'] ?>')"><i class="fas fa-times-circle fa-md float-right margin-top-3" style="margin-right: 2px"></i></a> <?php }} ?> </div> <div class="" <?php if($detail[0]['roleid'] !='3'){echo 'hidden';} ?>> <label class="control-label user-label col-md-3 no-padding"> </label> <label class="control-label col-md-8 no-padding-right field-click-able"><a data-toggle="modal" data-target="#updateAddress">+ Thรชm ฤ‘แป‹a chแป‰</a></label> </div> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ghi chรบ</label> <label class="control-label col-md-8 no-padding-right"> <input name="comments" id="comments" class="col-md-12 no-padding font-size-12" value="<?php echo $detail[0]['comments'] ?>" maxlength="30"> </label> </div> </div> </form> <form id="dataExt" method="POST" role="form"> <?php if($detail[0]['extinfo'] !=null) { $data = json_decode($detail[0]['extinfo'],true); } else{$data = null;} ?> <div class="tile p-0 padding-5 margin-bot-5 div-bonus" <?php if($detail[0]['roleid'] !='3'){echo 'hidden';} ?>> <div class="tile-body padding-left-10"> <?php if(count($list_ext)>0){ foreach ($list_ext as $value) { if($value['formid'] == 'user' && $value['status'] == '1'){ ?> <div class=""> <label class="control-label user-label col-md-3 no-padding"> <?php echo $value['fieldname'] ?> </label> <?php if($value['fieldtype'] == 'T') { $dataReal=''; if($data !=null) { foreach ($data as $extkey => $extvalue){ if($extkey == $value['fieldcode']){ $dataReal = $extvalue; break; }else{$dataReal = '';}}}?> <label class="control-label col-md-8 no-padding-right"> <input name="<?php echo $value['fieldcode'] ?>" id="<?php echo $value['fieldcode'] ?>" class="col-md-12 no-padding font-size-12 available" value="<?php echo $dataReal ?>" placeholder="<?php echo $value['fieldname'] ?>"> </label> <?php }else if($value['fieldtype'] == 'D'){ ?> <select name="<?php echo $value['fieldcode'] ?>" class="control-label col-md-8 no-border no-padding margin-left-10" id="<?php echo $value['fieldcode'] ?>"> <?php foreach ($list_codic as $material) { if($material['category'] == $value['datasource'] && $material['status'] =='W'){ ?> <option <?php if(count($data)>0) { foreach ($data as $extkey => $extvalue){ if($extvalue == $material['code']) { echo 'selected'; break; } }} ?> value="<?php echo $material['code'] ?>"><?php echo $material['name'] ?></option> <?php }}?> </select> <?php } ?> </div> <?php }}} ?> </form> </div> </div> <div> <div class="fc-corner-right"> <div class="fc-button-group" style="float:right"> <button type="submit" id="updateUser" class="btn btn-primary float-right margin-bot-5 btn-update"><i class="fa fa-share"></i>Lฦฐu thรดng tin</button> </div> </div> </div> <div class="padding-5 margin-bot-5" style="margin-top: 40px"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ngร y tแบกo</label> <label class="control-label col-md-8 no-padding-right"><?php if($detail[0]['createddate'] !=null) { echo date("d/m/Y", strtotime($detail[0]['createddate']));} ?></label> </div> </div> <?php try { $id = isset($_GET['cusid']) ? $_GET['cusid'] :'' ; }catch(exception $Ex) { $id = ''; } if($id == '') { $id = strval($_GET['phone']); } $idcard = strval($_GET['idcard']); $roleid = strval($_GET['roleid']); ?> <div class="modal fade" id="insertPhone" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 5%" role="document"> <div class="modal-content"> <!--<form method="post" enctype="multipart/form-data" action="<?php echo base_url().'user/insertPhoneList/?cusid='.$id.'&idcard='.$idcard.'&roleid='.$roleid ?>">--> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Thรชm sแป‘ ฤ‘iแป‡n thoแบกi</h4> <button type="button" class="close" data-dismiss="modal" aria-label="ฤรณng"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class="form-group"> <label for="exampleInputEmail1">Sแป‘ ฤiแป‡n Thoแบกi</label> <input type="text" class="form-control" name="telephonelist" id="telephonelist" name="tvcdb" placeholder="-Sแป‘ ฤ‘iแป‡n thoแบกi"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">ฤรณng</button> <button type="button" class="btn btn-primary btn-add-phone" onclick="addTelephone('<?php echo $id ?>','<?php echo $idcard ?>','<?php echo $roleid ?>','<?php echo $detail[0]['groupid'];?>')"><i class=""></i>Thรชm</button> </div> <!--</form>--> </div> </div> </div> <div class="modal fade" id="insertEmail" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 5%" role="document"> <div class="modal-content"> <!--<form method="post" enctype="multipart/form-data" action="">--> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Thรชm email</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <input type="hidden" name="listemail" id="listemail" value="<?php echo $detail[0]['emaillist'] ?>"> <div class="form-group"> <label for="exampleInputEmail1">Email</label> <input type="email" class="form-control" name="email" id="emailadd" name="tvcdb" placeholder="-Email"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">ฤรณng</button> <button type="button" class="btn btn-primary" onclick="addEmail('<?php echo $id ?>','<?php echo $idcard ?>','<?php echo $roleid ?>','<?php echo $detail[0]['groupid'];?>')">Thรชm</button> </div> <!--</form>--> </div> </div> </div> <div class="modal fade" id="updateAddress" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 5%; width: 31%" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Thรชm ฤ‘แป‹a chแป‰</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class="form-group"> <label class="control-label col-md-12 no-padding-right"> <input class="col-md-12 no-padding font-size-12" placeholder="Nhแบญp nhรฃn ฤ‘แป‹a chแป‰" maxlength="30" style=" border-bottom: 1px solid #DBDBDB;" id="label"> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Quแป‘c gia: </label> <label class="control-label col-md-8 no-padding-right"> <input list="l_country" placeholder="Quแป‘c Gia" value="Viแป‡t Nam" name="country" id="country" class="col-md-12 no-padding font-size-12"> <datalist id="l_country"> <option>Viแป‡t Nam</option> </datalist> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Tแป‰nh / Thร nh Phแป‘: </label> <label class="control-label col-md-8 no-padding-right"> <input list="l_city" placeholder="Tแป‰nh / Thร nh Phแป‘" id="city" name="city" class="col-md-12 no-padding font-size-12"> <datalist id="l_city"> <?php if(isset($city)){ foreach ($city as $rows) { ?> <option id-city="<?php echo $rows->id_city?>" value="<?php echo $rows->name?>"></option> <?php }} ?> </datalist> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Quแบญn / Huyแป‡n: </label> <label class="control-label col-md-8 no-padding-right"> <input list="l_distr" placeholder="Quแบญn / Huyแป‡n" id="district" name="district" class="col-md-12 no-padding font-size-12"> <datalist id="l_distr"> </datalist> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Phฦฐแปng / Xรฃ: </label> <label class="control-label col-md-8 no-padding-right"> <input list="l_ward" placeholder="Phฦฐแปng / Xรฃ" id="ward" name="ward" class="col-md-12 no-padding font-size-12"> <datalist id="l_ward"> </datalist> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Tรชn ฤ‘ฦฐแปng: </label> <label class="control-label col-md-8 no-padding-right"> <input placeholder="<NAME>" value="" id="street" class="col-md-12 no-padding font-size-12" id="fulladdresstemp" placeholder="ฤแป‹a chแป‰" maxlength="30" name="fulladdress"> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Sแป‘ nhร : </label> <label class="control-label col-md-8 no-padding-right"> <input placeholder="Sแป‘ nhร " id="address" value="" class="col-md-12 no-padding font-size-12" placeholder="ฤแป‹a chแป‰" maxlength="30" name="fulladdress"> </label> </div> </div> <div class="modal-footer" style="background: #f5f5f5"> <button type="button" class="btn btn-gray-white float-right" data-dismiss="modal">ฤรณng</button> <button type="button" class="btn btn-gray-black float-right btn-addfulladdress" data-dismiss="modal"><i class=""></i>Lฦฐu</button> </div> </div> </div> </div> <div class="modal fade" id="updateIdcard" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 5%; width: 31%" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">CMND/ID</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Loแบกi hรฌnh: </label> <label class="control-label col-md-8 no-padding-right"> <input list="l_type" placeholder="Loแบกi hรฌnh" name="type" class="col-md-12 no-padding font-size-12" value="CMND"> <datalist id="l_type"> <option data-value="cmnd">CMND</option> <option data-value="passport">Passport</option> </datalist> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Sแป‘: </label> <label class="control-label col-md-8 no-padding-right"> <input type="text" placeholder="Sแป‘" name="idcard" id="idcard_modal" class="col-md-12 no-padding font-size-12" value="<?php echo $detail[0]['idcard'] ?>" /> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Ngร y cแบฅp: </label> <label class="control-label col-md-8 no-padding-right"> <input placeholder="Ngร y cแบฅp" name="issueddate" class="col-md-12 no-padding font-size-12" id="issueddate" value="<?php echo $detail[0]['issueddate']; ?>"> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Nฦกi cแบฅp: </label> <label class="control-label col-md-8 no-padding-right"> <input list="l_city" placeholder="Nฦกi cแบฅp" name="issuedplace" class="col-md-12 no-padding font-size-12" id="issuedplace" value="<?php echo $detail[0]['issuedplace'] ?>"> <datalist id="l_city"> </datalist> </label> </div> </div> <div class="modal-footer" style="background: #f5f5f5"> <button type="button" class="btn btn-gray-white float-right" data-dismiss="modal">ฤรณng</button> <button type="button" class="btn btn-primary float-right btn-update-idcard"><i class=""></i>Lฦฐu</button> </div> </div> </div> </div> <div class="modal fade" id="updateFullAddress" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 5%; width: 31%" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Sแปญa ฤ‘แป‹a chแป‰</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <input type="hidden" name="" id="addressid" value=""> <div class="form-group"> <label class="control-label col-md-12 no-padding-right"> <input class="col-md-12 no-padding font-size-12" placeholder="Nhแบญp nhรฃn ฤ‘แป‹a chแป‰" maxlength="30" style=" border-bottom: 1px solid #DBDBDB;" id="label_edit"> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Quแป‘c gia: </label> <label class="control-label col-md-8 no-padding-right"> <input list="l_country" placeholder="Quแป‘c Gia" value="Viแป‡t Nam" name="country" id="country_edit" class="col-md-12 no-padding font-size-12"> <datalist id="l_country"> <option>Viแป‡t Nam</option> </datalist> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Tแป‰nh / Thร nh Phแป‘: </label> <label class="control-label col-md-8 no-padding-right"> <input list="l_city" placeholder="Tแป‰nh / Thร nh Phแป‘" id="city_edit" name="city" class="col-md-12 no-padding font-size-12"> <datalist id="l_city"> <?php if(isset($city)){ foreach ($city as $rows) { ?> <option id-city="<?php echo $rows->id_city?>" value="<?php echo $rows->name?>"></option> <?php }} ?> </datalist> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Quแบญn / Huyแป‡n: </label> <label class="control-label col-md-8 no-padding-right"> <input list="l_distr" placeholder="Quแบญn / Huyแป‡n" id="district_edit" name="district" class="col-md-12 no-padding font-size-12"> <datalist id="l_distr"> </datalist> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Phฦฐแปng / Xรฃ: </label> <label class="control-label col-md-8 no-padding-right"> <input list="l_ward" placeholder="Phฦฐแปng / Xรฃ" id="ward_edit" name="ward" class="col-md-12 no-padding font-size-12"> <datalist id="l_ward"> </datalist> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Tรชn ฤ‘ฦฐแปng: </label> <label class="control-label col-md-8 no-padding-right"> <input placeholder="<NAME>" value="" id="street_edit" class="col-md-12 no-padding font-size-12" id="fulladdresstemp" placeholder="ฤแป‹a chแป‰" maxlength="30" name="fulladdress"> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Sแป‘ nhร : </label> <label class="control-label col-md-8 no-padding-right"> <input placeholder="Sแป‘ nhร " id="address_edit" value="" class="col-md-12 no-padding font-size-12" placeholder="ฤแป‹a chแป‰" maxlength="30" name="fulladdress"> </label> </div> </div> <div class="modal-footer" style="background: #f5f5f5"> <button type="button" class="btn btn-gray-white float-right" data-dismiss="modal">ฤรณng</button> <button type="button" class="btn btn-gray-black float-right btn-updatefulladdress"><i class=""></i>Lฦฐu</button> </div> </div> </div> </div> <div class="modal fade" id="modalDeleteAddress" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 7%" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Xoรก ฤแป‹a Chแป‰</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <p class="bg-danger" style="padding: 10px;color: #FFF;" >Bแบกn cรณ chแบฏc muแป‘n xoรก khรดng?</p> <input type="hidden" id="addressid_delete" name="addressid_delete"> </div> <div class="modal-footer"> <button type="button" class="btn btn-gray-white float-right" data-dismiss="modal">ฤรณng</button> <button type="button" onclick="deleteAddress()" class="btn btn-delete btn-danger"><i class=""></i>Xoรก</button> </div> </div> </div> </div><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-3 no-padding padding-left-10 col-md-22"> <div class="padding-5 margin-bot-5"> <div class="clearfix"> <div> <h5 class="tile-title folder-head font-size-12 font-weight-500">Phรขn chia phiแบฟu <a href="javascript:window.location.reload();" ><i class="fa fa-sync-alt fa-md float-right margin-top-3"></i></a></h5> </div> <ul class="nav nav-pills flex-column margin-left-5"> <li> <a id="a_appbarticket" class="dropdown-item no-padding margin-top-bot-10 border-radius-3 active show" role="tab" data-toggle="tab" href="#" onclick="locphieu('<?php echo $custid;?>','0',false);"> <p class="no-padding no-margin padding-left-right-10"> Phiแบฟu chฦฐa xแปญ lรฝ cแปงa tรดi <label class="float-right"> <?php /* $i = 0; if(count($result['data'])>0 && $result['code']==1) { //&& $value['hidden'] == '0' foreach ($result['data'] as $value) { if($value['status'] ==0 && $value['agentcurrent']==$custid && $value['status'] != 9) { $i++; } } } echo $i; */ echo $phieuchuaxuly; ?> </label></p> </a> </li> <li> <a id="a_appbarticket" class="dropdown-item no-padding margin-top-bot-10 border-radius-3" role="tab" data-toggle="tab" href="#" onclick="locphieu('<?php echo $custid;?>','4',false);"> <p class="no-padding no-margin padding-left-right-10"> Phiแบฟu ฤ‘รฃ hoร n thร nh <label class="float-right"> <?php /* $i = 0; if(count($result['data'])>0 && $result['code']==1) { foreach ($result['data'] as $value) { if($value['status'] == 4 && $value['agentcurrent']==$custid && $value['status'] != 9) { $i++; } } } echo $i; */ echo $phieudahoanthanh; ?> </label></p> </a> </li> <li> <a id="a_appbarticket" class="dropdown-item no-padding margin-top-bot-10 border-radius-3" role="tab" data-toggle="tab" href="#" onclick="locphieu('<?php echo $custid;?>','-1',true);"> <p class="no-padding no-margin padding-left-right-10"> Phiแบฟu liรชn quan <label class="float-right"> <?php /* $i = 0; if(count($result['data'])>0 && $result['code']==1) { foreach ($result['data'] as $value) { if(($value['agentcreated']==$custid || strpos($value['ticketusers'], $custid) !== false) && $value['status'] != 9) { $i++; } } } echo $i; */ echo $phieulienquan; ?> </label></p> </a> </li> <li> <a id="a_appbarticket" class="dropdown-item no-padding margin-top-bot-10 border-radius-3" role="tab" data-toggle="tab" href="#" onclick="locphieu('<?php echo $custid;?>','-1',false);"> <p class="no-padding no-margin padding-left-right-10"> Toร n bแป™ phiแบฟu cแปงa tรดi <label class="float-right"> <?php /* $i = 0; if(count($result['data'])>0 && $result['code']==1) { foreach ($result['data'] as $value) { if($value['agentcurrent'] == $custid && $value['status'] != 9) { $i++; } } } echo $i; */ echo $toanbophieu; ?> </label></p> </a> </li> <li> <a id="a_appbarticket" class="dropdown-item no-padding margin-top-bot-10 border-radius-3" role="tab" data-toggle="tab" href="#" onclick="loctheonhom(0);"> <p class="no-padding no-margin padding-left-right-10"> Toร n bแป™ phiแบฟu cแปงa nhรณm <label class="float-right"> <?php echo isset($counter['count_group'])?$counter['count_group']:'0'?> </label></p> </a> </li> <li> <a id="a_appbarticket" class="dropdown-item no-padding margin-top-bot-10 border-radius-3" role="tab" data-toggle="tab" href="#" onclick="loctheonhom(1);"> <p class="no-padding no-margin padding-left-right-10"> Phiแบฟu cแปงa nhรณm chฦฐa xแปญ lรฝ <label class="float-right"> <?php echo isset($counter['count_group_status'])?$counter['count_group_status']:'0'?> </label></p> </a> </li> </ul> </div> </div> </div> <iframe class="iframesearch" id="iframesearch" style="width: 78%;height:1000px;display: block; border: none;" src="<?php echo base_url() ?>search/rightSearchTicket/?search=&agentcreated=&agentcurrent=<?php echo $custid;?>&priority=&status=0&lienquan=false"></iframe> </div> </main> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 5%" role="document"> <div class="modal-content"> <form name="insertTicket" class="insertTicket" action="<?php echo base_url().'ticket/insertTicket' ?>" method="POST" enctype='multipart/form-data'> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Tแบกo phiแบฟu thแปง cรดng </h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">ร—</span></button> </div> <div class="modal-body"> <div class="form-group"> <label for="exampleInputEmail1">Tvcdb</label> <input type="text" class="form-control" id="tvcdb" name="tvcdb" placeholder="Tvcdb"> </div> <div class="form-group"> <label for="exampleInputEmail1">Ticket Id</label> <input type="text" class="form-control" id="ticketid" name="ticketid" placeholder="Ticket Id"> </div> <div class="form-group"> <label for="exampleInputEmail1">Customer Id</label> <select class="control-label col-md-12 no-padding-right" name="custid"> <?php if(count($customer['data'])>0) { foreach ($customer['data'] as $rows) { ?> <option value="<?php echo $rows['custid'] ?>"><?php echo $rows['custname'] ?></option> <?php }} ?> </select> </div> <div class="form-group"> <label for="exampleInputEmail1">Priority</label> <input type="text" class="form-control" id="priority" name="priority" placeholder="Priority"> </div> <div class="form-group"> <label for="exampleInputEmail1">Title</label> <input type="text" class="form-control" id="title" name="title" placeholder="Title"> </div> <div class="form-group"> <label for="exampleInputEmail1">Loแบกi phiแบฟu</label> <select class="control-label col-md-12 no-padding-right" name="status"> <option value="1">Phiแบฟu chฦฐa xแปญ lรฝ cแปงa tรดi</option> <option value="2">Phiแบฟu ฤ‘ang xแปญ lรฝ cแปงa tรดi</option> <option value="3">Phiแบฟu chฦฐa phรขn phแป‘i</option> <option value="4">Phiแบฟu chฦฐa xแปญ lรฝ cแปงa nhรณm</option> <option value="5">Phiแบฟu ฤ‘ang xแปญ lรฝ cแปงa nhรณm</option> <option value="6">Toร n bแป™ phiแบฟu cแปงa nhรณm</option> </select> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary ">Tแบกo Phiแบฟu</button> </div> </form> </div> </div> </div> <file_sep><main class="app-content padding-5 no-padding-right"> <form id="all-in"><input type="hidden" name="taskid" value="<?php echo($record[0]['taskid'])?>"> <div class="row"> <div class="col-md-3 no-padding padding-left-15 height-1024"> <div class="tile p-0 padding-5 margin-bot-5 z-index-103"> <div class="tile-body padding-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngฦฐแปi yรชu cแบงu</label> <select disabled="" data-placeholder="Chแปn ngฦฐแปi yรชu cแบงu..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen crm-control" name="taskmaster" log="Ngฦฐแปi yรชu cแบงu" old-value="<?php echo($record[0]['taskmaster'])?>"> <option value="" ></option> <?php if (isset($l_cus)) { foreach ($l_cus as $cus) { if ($cus['custname']!='') { $s = ''; if ($record[0]['taskmaster']==$cus['custid']) { $s = 'selected'; } echo('<option '.$s.' value="'.$cus['custid'].'">'.$cus['custname'].'</option>'); } } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Nhรณm phแปฅ trรกch</label> <select data-placeholder="Chแปn nhรณm phแปฅ trรกch..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen crm-control" name="tic" log="Nhรณm phแปฅ trรกch" old-value="<?php echo($record[0]['tic'])?>"> <option value=""></option> <?php if (isset($l_agentgroup)) { foreach ($l_agentgroup as $key => $value) { $s = ''; if ($record[0]['tic']==$value['groupid']) { $s = 'selected'; } echo '<option '.$s.' value="'.$value['groupid'].'">'.$value['groupname'].'</option>'; } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Phแปฅ trรกch</label> <select data-placeholder="Chแปn ngฦฐแปi phแปฅ trรกch..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen crm-control" name="pic" log="Phแปฅ trรกch" old-value="<?php echo($record[0]['pic'])?>"> <option value=""></option> <?php if (isset($l_age)) { foreach ($l_age as $cus) { if ($cus['custname']!='') { $s = ''; if ($record[0]['pic']==$cus['custid']) { $s = 'selected'; } echo('<option '.$s.' value="'.$cus['custid'].'" data-group="'.$cus['groupid'].'">'.$cus['custname'].'</option>'); } } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Phiแบฟu liรชn quan</label> <select data-placeholder="Chแปn phiแบฟu liรชn quan..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen crm-control" name="ticketid" log="Phiแบฟu liรชn quan" old-value="<?php echo($record[0]['ticketid'])?>"> <option value=""></option> <?php if (isset($l_ticket)) { foreach ($l_ticket as $cus) { $s = ''; if ($record[0]['ticketid']==$cus['ticketid']) { $s = 'selected'; } echo('<option '.$s.' value="'.$cus['ticketid'].'">'.$cus['ticketid'].'</option>'); } } ?> </select> </div> <div class="hide"> <label class="control-label user-label col-md-4 no-padding">CCs</label> <select class="control-label col-md-8 no-border no-padding margin-left-10" name="ccs"> <option value="1">ccs</option> </select> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5 z-index-102"> <div class="tile-body padding-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">ฤแป™ ฦฐu tiรชn</label> <select class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" name="priority" log="ฤแป™ ฦฐu tiรชn" old-value="<?php echo($record[0]['priority'])?>"> <option value="1" <?php if($record[0]['priority']==1) echo "selected";?>>Thฦฐแปng</option> <option value="2" <?php if($record[0]['priority']==2) echo "selected";?>>Cao</option> <option value="3" <?php if($record[0]['priority']==3) echo "selected";?>>Khแบฉn cแบฅp</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">ฤแป™ nghiรชm trแปng</label> <select class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" name="severity" log="ฤแป™ nghiรชm trแปng" old-value="<?php echo($record[0]['severity'])?>"> <option value="1" <?php if($record[0]['severity']==1) echo "selected";?>>Thฦฐแปng</option> <option value="2" <?php if($record[0]['severity']==2) echo "selected";?>>Cao</option> <option value="3" <?php if($record[0]['severity']==3) echo "selected";?>>Khแบฉn cแบฅp</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Trแบกng thรกi</label> <select class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" name="status" log="Trแบกng thรกi" old-value="<?php echo($record[0]['status'])?>"> <option value="O" <?php if($record[0]['status']=="O") echo "selected";?>>Chแป xรกc nhแบญn</option> <option value="W" <?php if($record[0]['status']=="W") echo "selected";?>>ฤang xแปญ lรฝ</option> <option value="C" <?php if($record[0]['status']=="C") echo "selected";?>>Hoร n thร nh</option> <option value="X" <?php if($record[0]['status']=="X") echo "selected";?>>Hแปงy</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ghi chรบ T.thรกi</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12 crm-control" placeholder="Nhแบญp ghi chรบ..." name="statusnote" value="<?php echo $record[0]['statusnote']?>" log="Ghi chรบ T.thรกi" old-value="<?php echo($record[0]['statusnote'])?>"> </label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5 z-index-101"> <div class="tile-body padding-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Phรขn loแบกi</label> <select class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" log="Phรขn loแบกi" name="tasktype" id="level_1" old-value="<?php echo($record[0]['tasktype'])?>"> <?php if (isset($l_type) && !empty($l_type)) { foreach ($l_type as $key => $value) { $sel = ''; if ($record[0]['tasktype']==$value['code']) { $sel = 'selected'; } echo '<option '.$sel.' value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Chi tiแบฟt CV</label> <select class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" name="taskdetail" log="Chi tiแบฟt CV" id="level_2" old-value="<?php echo($record[0]['taskdetail'])?>"> <?php if (isset($l_detail)) { foreach ($l_detail as $key => $value) { $sel = ''; if ($record[0]['taskdetail']==$value['code']) { $sel = 'selected'; } $c=''; if ($value['ref1']!=$record[0]['tasktype']) { $c="hide"; } echo '<option class="'.$c.'" '.$sel.' ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class="break-line margin-bot-5"></div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngร y yรชu cแบงu</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12 crm-control" log="Ngร y yรชu cแบงu" placeholder="dd-mm-yy hh:ii" name="req_date" value="<?php echo date('d-m-Y h:i',strtotime($record[0]['requestdate']))?>" old-value="<?php echo date('d-m-Y h:i',strtotime($record[0]['requestdate']))?>"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Thแปi hแบกn OLA</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12 crm-control" log="Thแปi hแบกn OLA" placeholder="dd-mm-yy hh:ii" name="ola_date" value="<?php echo date('d-m-Y h:i',strtotime($record[0]['sla']))?>" old-value="<?php echo date('d-m-Y h:i',strtotime($record[0]['sla']))?>"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngร y hแบนn</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12 crm-control" log="Ngร y hแบนn" placeholder="dd-mm-yy hh:ii" name="due_date" value="<?php echo date('d-m-Y h:i',strtotime($record[0]['duedate']))?>" old-value="<?php echo date('d-m-Y h:i',strtotime($record[0]['duedate']))?>"> </label> </div> <div class="break-line margin-bot-5"></div> <div class="hide"> <label class="control-label user-label col-md-4 no-padding">ฤแบฟm ngฦฐแปฃc</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12" placeholder="sแป‘ ngร y"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Hoร n thร nh</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12 crm-control" log="Hoร n thร nh" placeholder="dd-mm-yy hh:ii" name="fns_date" value="<?php echo date('d-m-Y h:i',strtotime($record[0]['finishdate']))?>" old-value="<?php echo date('d-m-Y h:i',strtotime($record[0]['finishdate']))?>"> </label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5 z-index-100 hide"> <div class="tile-body padding-left-right-10"> <div class="row margin-top-5 height-100"> <label class="control-label user-label col-md-4 no-padding">File ฤ‘รญnh kรจm</label> <label class="control-label col-md-8 no-padding-right"> </label> </div> </div> </div> <input type="hidden" name="changelog"> </div> <div class="col-md-7 no-padding padding-left-5"> <div class="tile no-margin-bot"> <div class="content-title"> <div class="div margin-bot-10 width-100per"> <h5 class="flex"> <i class="fa fa-lg fa-file-alt header-icon"></i> <input class="font-size-18 width-100per crm-control" type="text" required="" name="title" placeholder="Tiรชu ฤ‘แป Cรดng viแป‡c" value="<?php echo $record[0]['title'];?>" log="Tiรชu ฤ‘แป" old-value="<?php echo $record[0]['title'];?>"> <button class="btn btn-primary" type="button" id="btn-accept" taskid="<?php echo $this->uri->segment(3) ?>"> <i class="fa fa-share"></i> Tiแบฟp nhแบญn</button> </h5> <p class="header-desc field-click-able"> <!-- <input class="font-size-12" type="text" name="explain" placeholder="Diแป…n giแบฃi"> --> </p> </div> </div> <div class="break-line margin-bot-5"></div> <div class="row"> <div class="col-md-12 comment-wrap"> <div class="photo"> <img class="avatar" src="<?php echo($this->session->userdata('avatar'));?>"> <input type="hidden" name="avatar" value="<?php echo($this->session->userdata('avatar'));?>"> </div> <div class="comment-block"> <!-- <p class="no-margin">Trแบฃ lแปi</p> --> <div class="status-upload"> <form> <!-- <ul> <li><a title="" data-toggle="tooltip" data-placement="bottom" data-original-title="Text"><i class="fa fa-font"></i></a></li> <li><a title="" data-toggle="tooltip" data-placement="bottom" data-original-title="File"><i class="fa fa-paperclip"></i></a></li> </ul> --> <!-- <button type="submit" class="btn btn-success green"><i class="fa fa-share"></i> Share</button> --> <textarea name="cmt" placeholder="Nhแบญp bแบฅt kแปณ mแป™t nแป™i dung?"></textarea> </form> </div><!-- Status Upload --> <button type="submit" class="btn btn-gray float-right margin-top-5 margin-bot-5"><i class="fa fa-share"></i> Lฦฐu thay ฤ‘แป•i </button> </div> </div> </div> </div> <div class="comments"> <p>Lแป‹ch sแปญ cรดng viแป‡c</p> <?php if (isset($comment)) { foreach ($comment as $key => $value) { ?> <div> <div class="comment-wrap"> <div class="photo"> <img class="avatar" src="<?php echo($value['avatar'])?>"> </div> <div class="comment-block padding-5"> <p class="comment-text"><?php echo($value['custname'])?></p> <p class="comment-text"><?php echo($value['tskaction'])?></p> <p class="comment-text"><?php echo($value['comments'])?></p> <div class="bottom-comment"> <div class="comment-date"><?php echo($value['changelog'])?></div> </div> </div> </div> <ul class="app-breadcrumb breadcrumb react-comment"> <p class="margin-right-30"><?php echo date('d-m-Y h:i',strtotime($value['createddate']))?></p> <!-- <li class="breadcrumb-item"><a href="#">Phแบฃn hแป“i</a></li> --> <!-- <li class="breadcrumb-item"><a href="#">Tแบกo cรดng viแป‡c</a></li> --> </ul> </div> <?php }} ?> </div> </div> </form> </main><file_sep><script type="text/javascript"> $(document).ready(function(){ $('.knl-caret').click(function(){ var caret = $('.fa-angle-double-down'); if (caret.length>0) { $('.knl-caret').removeClass('fa-angle-double-down'); $('.knl-caret').addClass('fa-angle-double-up'); }else{ $('.knl-caret').addClass('fa-angle-double-down'); $('.knl-caret').removeClass('fa-angle-double-up'); } $(".knl-board").slideToggle("slow"); }); $('i.search-knowledge').click(function(){ var text = $('input[name="knl_text"]').val(); search(text,'','',''); }); $('#knl-btn-back').click(function(){ $('.knl-content').css('display','none'); $('#knl_list').css('display','block'); }); $('input[name="knl_text"]').keypress(function(e){ if(e.keyCode==13){ // if user is hitting enter var text = $('input[name="knl_text"]').val(); search(text,'','',''); } }); }); function search(text='',type='',group='',detail=''){ var query = '?'; if (text!='') {query+=('search='+text);} if (type!='') {query+=('tickettype='+type);} if (group!='') {query+=('groupid='+group);} if (detail!='') {query+=('categoryid='+detail);} if ($('.knl-caret').hasClass('fa-angle-double-up')) {$('.knl-caret').trigger('click');} var url = '<?php echo base_url().'knowledge/fulltext'?>'+query; if (query!='' && query.length<=100) { $('.knl-content').css('display','none'); $('#knl_list').html('ฤang tแบฃi dแปฏ liแป‡u...').css('display','block'); $.ajax({ url: url, type: 'GET', dataType: 'JSON' }) .done(function(data) { console.log(data); var div = ''; if(data){ for (var i = 0; i < data.length; i++) { div+='<p><a style="cursor: pointer; color: #009688" onclick="showDetailKnowledge('+data[i]['id']+')">#'+data[i]['title']+'</a></p>'; // if (i==2) {break;} } if (div!='') { $('#knl_list').html(div).css('display','block'); }else{ $('#knl_list').html('Khรดng tรฌm thแบฅy kแบฟt quแบฃ nร o.'); } }else {$('#knl_list').html('Khรดng tรฌm thแบฅy kแบฟt quแบฃ nร o.');} }) .fail(function() { parent.alertLog('Cแบฃnh bรกo',"Lแป—i hแป‡ thแป‘ng",'warning'); }); }else if(query.length>100){ parent.alertLog('Cแบฃnh bรกo',"Chiแปu dร i khรดng phรน hแปฃp",'warning'); }else{ parent.alertLog('Cแบฃnh bรกo',"Vui lรฒng ฤ‘iแปn tแปซ khรณa",'warning'); } } </script><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Knowledge extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url','json_output')); } public function index() { $_data = []; $json_data = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/select/') ; $knowledge['news'] = json_decode($json_data,true)['data']; $agent = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getcustomerbyroleid/2'); $knowledge['agent'] = json_decode($agent,true)['data']; $l_group = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/knwgroup'); $knowledge['l_group'] = json_decode($l_group,true)['data']; $l_cate = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/knwdetail'); $knowledge['l_cate'] = json_decode($l_cate,true)['data']; $l_type = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/tcktype'); $knowledge['l_type'] = json_decode($l_type,true)['data']; $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['mainview'] = $this->load->view('knowledge/knowledge', $knowledge , TRUE); $_data['script'] = $this->load->view('script/script_knowledge', NULL, TRUE); $this->load->view('dashboard',$_data); } public function detail($action = 'add',$id ='') { $_script = []; if($action =='add') { $_script['action'] = 'add'; } $_data = []; $data=[]; if($action=='edit') { $json_data = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/select/'.$id); $data['knowledge'] = json_decode($json_data,true)['data']; } $l_group = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/knwgroup'); $data['l_group'] = json_decode($l_group,true)['data']; $l_cate = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/knwdetail'); $data['l_cate'] = json_decode($l_cate,true)['data']; $l_type = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/tcktype'); $data['l_type'] = json_decode($l_type,true)['data']; $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['mainview'] = $this->load->view('knowledge/detail', $data , TRUE); $_data['script'] = $this->load->view('script/ckeditor', $_script, TRUE); $this->load->view('dashboard',$_data); } public function detailKnowledge() { $id = $this->input->post('id'); $json_data = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/select/'.$id) ; echo $json_data; } public function insertKnowledge() { $var = $this->session->userdata; $log_custid = $var['custid']; $log_roleid = $var['roleid']; $log_groupid = $var['groupid']; $data = $this->input->post(); $postdata = http_build_query([ 'log_groupid' => $log_groupid, 'title' => isset($data['title'])?$data['title']:null, 'article' => isset($data['article'])?$data['article']:null, 'groupid' => isset($data['group'])?$data['group']:null, 'categoryid' => isset($data['cate'])?$data['cate']:null, 'hidden' => isset($data['status'])?$data['status']:null, 'tickettype' => isset($data['type'])?$data['type']:null, 'createby' => $this->session->userdata('custid'), 'ticketprioty' => isset($data['ticketprioty'])?$data['ticketprioty']:null ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/insert',false,$context) ; echo $result; } public function updateKnowledge() { $var = $this->session->userdata; $log_custid = $var['custid']; $log_roleid = $var['roleid']; $log_groupid = $var['groupid']; $data = $this->input->post(); $postdata = http_build_query([ 'log_groupid' => $log_groupid, 'title' => isset($data['title'])?$data['title']:null, 'article' => isset($data['article'])?$data['article']:null, 'groupid' => isset($data['group'])?$data['group']:null, 'categoryid' => isset($data['cate'])?$data['cate']:null, 'hidden' => isset($data['status'])?$data['status']:null, 'tickettype' => isset($data['type'])?$data['type']:null, 'ticketprioty' => isset($data['ticketprioty'])?$data['ticketprioty']:null ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/update/'.$data['id'],false,$context) ; echo $result; } public function search() { $get = $this->input->get(); $query = '?'; foreach ($get as $key => $value) { $v = ''; if (($key=='categoryid' || $key=='tickettype' || $key=='groupid') && $value == "all") { $v = ''; }else{ $v = $value; } $query.=$key.'='.rawurlencode($v).'&'; } $json_data = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/search'.$query); $knowledge['news'] = json_decode($json_data,true)['data']; $l_group = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/knwgroup'); $knowledge['l_group'] = json_decode($l_group,true)['data']; $l_cate = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/knwdetail'); $knowledge['l_cate'] = json_decode($l_cate,true)['data']; $l_type = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/tcktype'); $knowledge['l_type'] = json_decode($l_type,true)['data']; $_data['script'] = $this->load->view('script/script_knowledge', NULL, TRUE); $_data['mainview'] = $this->load->view('knowledge/iframe', $knowledge , TRUE); $this->load->view('dashboard',$_data); // echo $query; } public function fulltext() { $get = $this->input->get(); $query = '?'; foreach ($get as $key => $value) { $query.=$key.'='.rawurlencode($value).'&'; } $json_data = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/search'.$query); $knowledge = json_decode($json_data,true)['data']; json_output(200,$knowledge); } }<file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-2 col-md-18 no-padding padding-left-10"> <?php echo isset($left)?$left:'' ?> </div> <div class="col-md-7 col-md-64 no-padding padding-left-1"> <iframe class="iframesetting" id="iframesetting" style="width: 100%;display: block; border: none;height: 100vh" src="<?php echo base_url().'setting/viewUser' ?>"></iframe> </div> <div class="col-md-2 col-md-18 no-padding padding-left-5"> <?php echo isset($right)?$right:'' ?> </div> </div> </main><file_sep><?php $custidCustomer = $this->input->get('cusid'); $var = $this->session->userdata; $agentcurrent = $var['custid']; $groupid = $var['groupid']; ?> <div class="tile"> <div class="content-title"> <div class="div"> <h5><img class="user-avatar" src="<?php echo $user[0]['avatar'] ?>" alt="User Image" onerror="this.src='https://www.freewebmentor.com/default-avatar.png'"> <?php echo $user[0]['custname'] ?></h5> </div> <button class="btn btn-blank" id="btn-plus-ticket" onclick="insertTicket('<?php echo $custidCustomer ?>','<?php echo $agentcurrent ?>','<?php echo $groupid ?>')" type="button"><i class="fas fa-plus"></i> Phiแบฟu hแป— trแปฃ </button> <button id="demoSwal" style="display: none;" class="btn btn-blank" type="button">+ Phiแบฟu hแป— trแปฃ </button> <button id="demoNotify" style="display: none;" type="hidden" class="btn btn-blank" type="button">+ Thรดng bรกo </button> <button id="demoModal" style="display: none;" type="hidden" class="btn btn-blank" type="button">+ Modal </button> </div> <div class="bs-component"> <ul class="nav nav-tabs"> <li class="nav-item"> <a class="user-tab active show" id="tab1" data-toggle="tab" href="#tab-content-1">Giao dแป‹ch (<?php $i = 0; if(count($trade)>0) { foreach ($trade as $value) { $i++; }} echo $i; ?>)</a> </li> <li class="nav-item"> <a class="user-tab" id="tab2" data-toggle="tab" href="#tab-content-2">Phiแบฟu (<?php echo count($ticket); ?>)</a> </li> </ul> <div class="tab-content" id="myTabContent"> <div class="tab-pane fade" id="tab-content-2"> <div class="table-responsive" style="height: 400px" id="div-content-2"> <table class="table" id="table-1-ticket"> <thead class="no-border-top"> <tr> <th width="9%">ID</th> <th width="20%">Tiรชu ฤ‘แป</th> <th width="6.8%">Ngร y y/cแบงu</th> <th width="20%">Ngฦฐแปi p/trรกch</th> <th width="9%">Ngร y c/nhแบญt</th> </tr> </thead> <tbody> <?php if(count($ticket) >0) { foreach ($ticket as $rows) { /* if(( $rows['custid'] == $agentcurrent ||strpos($rows['ticketusers'],$agentcurrent)!==false || $groupid == $rows['groupid'] ) && $rows['hidden'] =='0') { */ ?> <tr class="border-bot-1"> <td> <a onclick="addTab('<?php echo base_url().'ticket/detail/'.$rows['ticketid'].'/'.$rows['custid'] ?>','#<?php echo $rows['ticketid'] ?>')" href="#"> <span class="id-label span-danger">O</span> #<?php echo $rows['ticketid'] ?></a> </td> <td> <?php echo $rows['title'] ?> </td> <td> <?php echo date("d/m/Y", strtotime($rows['createat'])); ?> </td> <td><?php echo $rows['name'] ?></td> <td> <?php echo date("d/m/Y", strtotime($rows['lastupdate'])); ?></td> </tr> <?php //} }} ?> </tbody> </table> </div> </div> <div class="tab-pane fade" id="tab-content-3"> <p>Phiแบฟu liรชn quan.</p> </div> <div class="tab-pane fade active show" id="tab-content-1"> <div class="table-responsive" id="div-content-1" style="height: 294px;"> <table class="table table-striped table-bordered" cellspacing="0" id="table-1-contract"> <thead> <tr> <th width="60px">Mรฃ GD</th> <th width="80px">Tรฌnh trแบกng</th> <th width="90px">Mรฃ cฤƒn hแป™</th> <th width="73px">Ngร y bแบฏt ฤ‘แบงu</th> <th width="75px">Ngร y hiแป‡u lแปฑc</th> <th width="250px">Ghi chรบ</th> </tr> </thead> </table> </div> </div> </div> </div> </div><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-2 col-md-22 padding-left-15"> <?php echo isset($left)?$left:'' ?> </div> <div class="col-md-7 padding-left-1"> <?php echo isset($center)?$center:'' ?> </div> <div class="col-md-2 col-md-18 padding-left-5"> </div> </div> </main> <!-- <main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-3 no-padding padding-left-15"> <div class="tile p-0 padding-5 margin-bot-5 height-1024"> <div class="tile-body padding-left-10 vertical-top" id="search_area"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giai ฤ‘oแบกn</label> <select name="name" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_1"> <option value="all" selected="">Tแบฅt cแบฃ</option> </select> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Trแบกng thรกi</label> <select name="status" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_2"> <option value="W" selected="">Working</option> <option value="C" selected="">Closed</option> </select> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ghi chรบ</label> <label class="control-label col-md-8 no-padding-right"> <textarea class="col-md-12 no-padding font-size-12 control-textarea" placeholder="Nhแบญp bแบฅt kแปณ mแป™t nแป™i dung..."></textarea> </label> </div> <div class="flex offset-10 margin-top-10"> <button id="btn-search" class="btn btn-primary float-right" type="button">Lฦฐu</button> </div> </div> </div> </div> <div class="col-md-6 col-md-78 no-padding padding-left-5"> </div> </div> </main> --><file_sep>function removeTab() { var id = window.top.$(".nav-tabs").children().length; var idtab = window.top.$(".nav-tabs").find("li > a.active").attr('href'); var idnavbar = window.top.$(".nav-tabs").find("li > a.active").parent(); $(idnavbar).remove(); $(idtab).remove(); window.top.$('.nav-tabs li:nth-child(' + (id-1) + ') a').click(); } function addTab(link,title,checkInsert) { var x = Math.floor((Math.random() * 999) + 1); var id = window.top.$(".nav-tabs").children().length; var idtab = window.top.arrayTab[x]; window.top.arrayTab.splice(x, 1); var ulChildren = window.top.$(".nav-tabs").children(); var link = link; var title = title; var checkLink = false; if(checkInsert == true) { window.top.$( ".nav-link" ).removeClass( "active" ); window.top.$( ".tab-pane" ).removeClass( "active" ); //think about it ;) window.top.$('.nav-tabs li:nth-child('+id+')').after('<li class="nav-item width-170 role="presentation"">\ <a class="nav-link active show" name="'+link+'" role="tab" data-toggle="tab" href="#'+idtab+'" title="'+title+'" >\ <i class="fas fa-tags"></i> \ <span class="">'+title+'</span> </a><span class="fa fa-times" aria-hidden="true"></span>\ </li>'); window.top.$('.tab-content').append('<div class="tab-pane active" id="' + idtab + '"><iframe id="myiframe1" class="myiframe" name="myiframe'+id+'" src="'+link+'" frameborder="0"></iframe></div>'); var widthsub = window.top.$('.nav-insert').width() * 2; var width = window.top.$('#lengthmenu').width() - widthsub; if(id >4) { window.top.$("ul.nav-tabs li").each(function(){ $(this).attr('style', 'width:'+width/(id+1)+'px !important;'); }); } else{ window.top.$("ul.nav-tabs li").each(function(){ $(this).attr('style', 'width:170px !important;'); }); } var i = id+1; window.top.$('.nav-tabs li:nth-child(' + i + ') a').click(); return; } for(var i = 0; i < id ;i++) { if(ulChildren[i].children[0].nodeName.toLowerCase() === 'a'){ if(link == ulChildren[i].children[0].name) { checkLink = true; var j = i+1; window.top.$('.nav-tabs li:nth-child(' + j + ') a').click(); break; } } } if(checkLink == true) { return; } else{ window.top.$( ".nav-link" ).removeClass( "active" ); window.top.$( ".tab-pane" ).removeClass( "active" ); //think about it ;) window.top.$('.nav-tabs li:nth-child('+id+')').after('<li class="nav-item width-170 role="presentation"">\ <a class="nav-link active show" name="'+link+'" role="tab" data-toggle="tab" href="#'+idtab+'" title="'+title+'" >\ <i class="fas fa-tags"></i> \ <span class="">'+title+'</span> </a><span class="fa fa-times" aria-hidden="true"></span>\ </li>'); window.top.$('.tab-content').append('<div class="tab-pane active" id="' + idtab + '"><iframe id="myiframe1" class="myiframe" name="myiframe'+id+'" src="'+link+'" frameborder="0"></iframe></div>'); var widthsub = window.top.$('.nav-insert').width() * 2; var width = window.top.$('#lengthmenu').width() - widthsub; if(id >4) { window.top.$("ul.nav-tabs li").each(function(){ $(this).attr('style', 'width:'+width/(id+1)+'px !important;'); }); } else{ window.top.$("ul.nav-tabs li").each(function(){ $(this).attr('style', 'width:170px !important;'); }); } var i = id+1; window.top.$('.nav-tabs li:nth-child(' + i + ') a').click(); } } <file_sep> <script type="text/javascript"> $(document).ready(function(){ $('#ck-edit').click(function(){ var stt = $('#content').attr('ck-edit'); var title = $('#knl-title')[0].innerText;$('#knl-title').html('<input name="title" autofocus value="'+title+'">'); console.log(title); if(stt && stt == 'close'){ console.log('ck-edit is now close'); var ck = CKEDITOR.replace( 'content' ,{ filebrowserBrowseUrl : '<?=base_url()?>ckfinder/ckfinder.html', filebrowserImageBrowseUrl : '<?=base_url()?>ckfinder/ckfinder.html?type=Images', filebrowserFlashBrowseUrl : '<?=base_url()?>ckfinder/ckfinder.html?type=Flash', filebrowserUploadUrl : '<?=base_url()?>ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files', filebrowserImageUploadUrl : '<?=base_url()?>ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images', filebrowserFlashUploadUrl : '<?=base_url()?>ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash', allowedContent: true, disableAutoInline: true, toolbarStartupExpanded : false, toolbarCanCollapse: false, width: '100%', height: 700, }); ck.on( 'change', function( evt ) { // getData() returns CKEditor's HTML content. $('#content').html(evt.editor.getData()); }); if (ck) { $('#content').attr('ck-edit','open'); $(this).css('display','none'); $('#ck-save').css('display','block'); } }else { console.log('ck-edit is now open yet'); } }); $('#ck-save').click(function(){ var stt = $('#content').attr('ck-edit'); var action = $(this).attr('action'); var id = '<?php echo $this->uri->segment(4) ?>'; var title = $('#knl-title').find('input').val();$('#knl-title').html(title); var content = $('#content').html(); var group = $('select[name="group"]').val(); var cate = $('select[name="cate"]').val(); var type = $('select[name="type"]').val(); var status = $('select[name="status"]').val(); var ticketprioty = $('select[name="ticketprioty"]').val(); console.log(title); if(stt && stt == 'open'){ console.log('ck-edit is now open'); var aInst = CKEDITOR.instances; console.log(aInst); for (var key in aInst){ CKEDITOR.instances[key].destroy(); } $('#content').attr('ck-edit','close'); $(this).css('display','none'); $('#ck-edit').css('display','block'); }else { console.log('ck-edit is now not close yet'); } if(action =='add') { var url = '<?php echo base_url().'knowledge/insertKnowledge' ?>'; } else{ var url = '<?php echo base_url().'knowledge/updateKnowledge' ?>'; } $.ajax({ url: url, type: 'POST', dataType: 'JSON', data: {id:id,title:title,article: content,group:group,cate:cate,type:type,status:status,ticketprioty:ticketprioty}, }) .done(function(data) { if(data.code==0){ alert('') } alert(data.message); /* location.href= '<?php echo base_url().'/ticket/detail/' ?>'+data.data; // alert('<?php echo base_url().'/ticket/detail/' ?>'+data.data); */ }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng,vui lรฒng liรชn hแป‡ admin ฤ‘แปƒ ฤ‘ฦฐแปฃc hแป— trแปฃ'); }); }); var action = '<?php echo isset($action)?$action:'' ?>'; if(action !='') { $('#ck-edit').trigger('click'); } var tickettype = $('select#level_1').val(); if (tickettype!='') { $('select#level_2 option').each(function(){ var ref1 = $(this).attr('ref1'); if (ref1==tickettype) {$(this).removeClass('hide').addClass('show');} else{$(this).addClass('hide').removeClass('show');} }); $('select#level_2 option.show:first').prop('selected',true); } var groupid = $('select#level_2').val(); if (groupid!='') { $('select#level_3 option').each(function(){ var ref2 = $(this).attr('ref2'); if (ref2==groupid) {$(this).removeClass('hide').addClass('show');} else{$(this).addClass('hide').removeClass('show');} }); $('select#level_3 option.show:first').prop('selected',true); } $('select#level_1').change(function(){ var val = $(this).val(); if(val){ $('select#level_2 option, select#level_3 option').each(function(){ var ref1 = $(this).attr('ref1'); if (ref1==val) { $(this).removeClass('hide').addClass('show'); }else{ $(this).addClass('hide').removeClass('show'); } }); }else{ $('select#level_2 option, select#level_3 option').each(function(){ $(this).removeClass('hide').addClass('show'); }); } $('select#level_2 option.show:first').prop('selected',true); $('select#level_3 option.show:first').prop('selected',true); }); $('select#level_2').change(function(){ var val = $(this).val(); if(val){ $('select#level_3 option').each(function(){ var ref2 = $(this).attr('ref2'); if (ref2==val) { $(this).removeClass('hide').addClass('show'); }else{ $(this).addClass('hide').removeClass('show'); } }); }else{ $('select#level_3 option').each(function(){ $(this).removeClass('hide').addClass('show'); }); } $('select#level_3 option.show:first').prop('selected',true); }); }); </script><file_sep> <?php if(count($listticketlog) >0) { foreach ($listticketlog as $rows) { ?> <div class="padding-left-right-10"> <div class="comment-wrap"> <div class="photo"> <div class="avatar" style="background-image: url('<?php echo 'http://crm.tavicosoft.com/api/avatar/'.$rows['useraction'] ?>')"></div> </div> <div class="comment-block padding-5"> <p class="comment-text" style="font-weight: 600"><?php echo $rows['custname'] ?></p> <p class="comment-text"><?php echo $rows['cmt']?></p> <p class="comment-text"><?php echo $rows['action']?></p> <?php if(strlen($rows['srcrecord'])>5){ ?> <audio controls> <source src="<?php echo $rows['srcrecord'] ?>" type="audio/ogg"> Your browser does not support the audio tag. </audio> <?php } ?> <div class="bottom-comment"> <div class="comment-date"><?php echo $rows['changelog']?></div> </div> </div> </div> <ul class="app-breadcrumb breadcrumb react-comment"> <p class="margin-right-30"><?php echo date('d-m-Y H:i',strtotime($rows['createdat'])); ?></p> </ul> </div> <?php }} ?><file_sep><form method="POST" id="dataUpdateGroup"> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-10"> <input type="hidden" name="groupid" value="<?php echo $gdetail['groupid'];?>" id="groupid"/> <div class=""> <label class="control-label user-label col-md-4 no-padding">Tรชn nhรณm</label> <label class="control-label col-md-7 no-padding-right"> <input class="col-md-12 no-padding font-size-12" name="groupname" value="<?php echo $gdetail['groupname']?>" placeholder="Tรชn nhรณm" id="custname" required="" minlength="4" maxlength="30"> </label> </div> <div class=""> <label class="control-label user-label col-md-4 no-padding">Trแบกng thรกi</label> <select class="control-label col-md-7 no-border no-padding margin-left-10" id="status" name="status"> <option value="0" <?php if($gdetail['status']==0){echo "selected";} ?>>Khรดng hoแบกt ฤ‘แป™ng</option> <option value="1" <?php if($gdetail['status']==1){echo "selected";} ?>>ฤang hoแบกt ฤ‘แป™ng</option> </select> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-10"> <div class=""> <label class="control-label user-label col-md-4 no-padding"></label> <label class="control-label col-md-7 no-padding-right"> <label class="control-label user-label2 col-md-3 no-padding">Xem</label> <label class="control-label user-label2 col-md-3 no-padding">Thรชm</label> <label class="control-label user-label2 col-md-3 no-padding">Sแปญa</label> </label> </div> <div class=""> <label class="control-label user-label col-md-4 no-padding">Phiแบฟu</label> <!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="ticketrule" id="ticketrule"> <option value="0" >Khรดng</option> <option value="1" >Xem/Sแปญa</option> </select> --> <label class="control-label col-md-7 no-padding-right"> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['ticketrule'], 0,1) == '1') echo 'checked'; ?> name="viewticket" id="viewticket" value="1"></label> <input id='viewtickethidden' type='hidden' value='0' name='viewticket'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['ticketrule'], 1,1) == '1') echo 'checked'; ?> name="addticket" id="addticket" value="1"></label> <input id='addtickethidden' type='hidden' value='0' name='addticket'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['ticketrule'], 2,1) == '1') echo 'checked'; ?> name="editticket" id="editticket" value="1"></label> <input id='edittickethidden' type='hidden' value='0' name='editticket'> </label> </div> <div class=""> <label class="control-label user-label col-md-4 no-padding">Ngฦฐแปi dรนng</label> <!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="userrule" id="userrule"> <option value="0">Khรดng</option> <option value="1">Xem/Sแปญa</option> </select> --> <label class="control-label col-md-7 no-padding-right"> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['userrule'], 0,1) == '1') echo 'checked'; ?> name="viewuser" id="viewuser" value="1"></label> <input id='viewuserhidden' type='hidden' value='0' name='viewuser'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['userrule'], 1,1) == '1') echo 'checked'; ?> name="adduser" id="adduser" value="1"></label> <input id='adduserhidden' type='hidden' value='0' name='adduser'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['userrule'], 2,1) == '1') echo 'checked'; ?> name="edituser" id="edituser" value="1"></label> <input id='edituserhidden' type='hidden' value='0' name='edituser'> </label> </div> <div class=""> <label class="control-label user-label col-md-4 no-padding">Cรดng viแป‡c</label> <!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="taskrule" id="taskrule"> <option value="0">Khรดng</option> <option value="1">Xem/Sแปญa</option> </select> --> <label class="control-label col-md-7 no-padding-right"> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['taskrule'], 0,1) == '1') echo 'checked'; ?> name="viewtask" id="viewtask" value="1"></label> <input id='viewtaskhidden' type='hidden' value='0' name='viewtask'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['taskrule'], 1,1) == '1') echo 'checked'; ?> name="addtask" id="addtask" value="1"></label> <input id='addtaskhidden' type='hidden' value='0' name='addtask'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['taskrule'], 2,1) == '1') echo 'checked'; ?> name="edittask" id="edittask" value="1"></label> <input id='edittaskhidden' type='hidden' value='0' name='edittask'> </label> </div> <div class=""> <label class="control-label user-label col-md-4 no-padding">Thฦฐ viแป‡n</label> <!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="knowledgerule" id="knowledgerule"> <option value="0">Khรดng</option> <option value="1">Xem/Sแปญa</option> </select> --> <label class="control-label col-md-7 no-padding-right"> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['knowledgerule'], 0,1) == '1') echo 'checked'; ?> name="viewknowledge" disabled="" id="viewknowledge" value="1"></label> <input id='viewknowledgehidden' type='hidden' value='1' name='viewknowledge'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['knowledgerule'], 1,1) == '1') echo 'checked'; ?> name="addknowledge" id="addknowledge" value="1"></label> <input id='addknowledgehidden' type='hidden' value='0' name='addknowledge'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['knowledgerule'], 2,1) == '1') echo 'checked'; ?> name="editknowledge" id="editknowledge" value="1"></label> <input id='editknowledgehidden' type='hidden' value='0' name='editknowledge'> </label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-10"> <label class="control-label col-md-4 no-padding" style="font-size: 12px;font-weight: 500;color: rgb(118, 121, 116);"><i class="far fa-window-maximize"></i> View </label> <div class=""> <label class="control-label user-label col-md-5 no-padding">Xem tแบฅt cแบฃ phiแบฟu</label> <label class="control-label col-md-6 no-padding-right"> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php foreach ($groupdetail['data'] as $key) { if($key['groupid'] == $gdetail['groupid']) { echo 'checked'; break; } } ?> name="viewpermission" id="viewpermission" value="1"></label> <input id='viewpermissionhidden' type='hidden' value='0' name='viewpermission'> <?php $temp = ""; foreach ($groupdetail['data'] as $key) { if($key['groupid'] == $gdetail['groupid']) { $temp = '1'; break; }else{ $temp = '0'; } } ?> <input type="hidden" name="oldpermission" id="oldpermission" value="<?php echo $temp ?>"> </label> </div> </div> </div> <div class="fc-corner-right"> <div class="fc-button-group" style="float:right"> <button type="button" class="btn btn-primary float-right margin-bot-5" id="btn-uploadgu" onclick="updateGroup()"><i class="fa fa-share"></i>Lฦฐu thรดng tin</button> </div> </div> </form><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Dashboard extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url')); } public function index() { if($this->input->post('custid', TRUE) != '') { $this->session->set_userdata('custid', $this->input->post('custid', TRUE)); $this->session->set_userdata('telephone', $this->input->post('telephone', TRUE)); $this->session->set_userdata('custname',$this->input->post('custname',TRUE)); $this->session->set_userdata('groupid',$this->input->post('groupid', TRUE)); $this->session->set_userdata('avatar',$this->input->post('avatar', TRUE)); $this->session->set_userdata('roleid',$this->input->post('roleid', TRUE)); $this->session->set_userdata('idcard',$this->input->post('idcard', TRUE)); } if(!$this->session->userdata("custid"))//If already logged in { redirect(base_url('login')); } $_data = []; //Role Admin -> go to Setting if($this->input->post('roleid', TRUE) == 1){ $_data['link'] = 'setting'; $_data['tab_title'] = "Setting"; }else{ $var = $this->session->userdata; $roleid = $var['roleid']; if($roleid == 1) { $_data['link'] = 'setting'; $_data['tab_title'] = "Setting"; } else { $_data['link'] = 'ticket'; $_data['tab_title'] = "Ticket"; } } $_data['navbar'] = $this->load->view('navbar/navbar', $_data, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['mainview'] = $this->load->view('dashboard', NULL , TRUE); $_data['script2'] = $this->load->view('script/script_call', NULL, TRUE); $_data['nodejs'] = $this->load->view('node/dashboard', NULL, TRUE); $_data['script'] = $this->load->view('script/script', NULL , TRUE); $this->load->view('master',$_data); } public function user() { $_data = []; $_data['link'] = 'user'; $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['mainview'] = $this->load->view('dashboard', NULL , TRUE); $this->load->view('master',$_data); } public function changePassword() { $data = $this->input->post(); $postdata = http_build_query([ 'custid' => $this->session->userdata('custid'), 'old_pass'=> isset($data['old_pass'])?$data['old_pass']:null, 'new_pass'=> isset($data['new_pass'])?$data['new_pass']:null ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/changepass',false,$context); echo $result; } } /* End of file Dashboard.php */ /* Location: ./application/controllers/Dashboard.php */ ?><file_sep><form id="insertUserVal" method="POST" role="form"> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Phรขn quyแปn (<span style="color: red">*</span>)</label> <select name="roleid" class="control-label col-md-8 no-border no-padding margin-left-10" id="roleid" onchange="selectGroup(this)" required=""> <option selected="true" disabled="true" value="">--Chแปn Phรขn Quyแปn--</option> <?php foreach ($role_list as $key => $value) { ?> <option value="<?php echo $key ?>" ><?php echo $value?></option> <?php } ?> </select> </div> <div class="div-group flex"> <label class="control-label user-label col-md-4 no-padding">Nhรณm (<span style="color: red">*</span>)</label> <select name="groupid" class="control-label col-md-8 no-border no-padding margin-left-10 grouplist" id="groupid" required=""> <option selected="true" disabled="true" value="">--Chแปn Nhรณm Quyแปn--</option> <?php foreach ($group_list as $value) { ?> <option value="<?php echo $value['groupid'] ?>" ><?php echo $value['groupname']?></option> <?php } ?> </select> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Hแป vร  Tรชn</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhแบญp hแป tรชn" name="custname" id="custname"> </label> </div> <div class="div-danhxung flex"> <label class="control-label user-label col-md-4 no-padding">Danh xฦฐng</label> <select class="control-label col-md-8 no-border no-padding margin-left-10" name="gender" id="gender"> <option value="M">ร”ng</option> <option value="F">Bร </option> </select> </div> <div class="div-cmnd flex"> <label class="control-label user-label col-md-4 no-padding">CMND/Passport (<span style="color: red">*</span>):</label> <label class="control-label col-md-7 no-padding-right"> <input name="idcard_modal" id="idcard_modal" required="" class="col-md-12 no-padding font-size-12" value="" placeholder="Nhแบญp cmnd" required minlength="8"> </label> </div> <div class="div-ngaysinh flex"> <label class="control-label user-label col-md-4 no-padding">Ngร y sinh:</label> <label class="control-label col-md-8 no-padding-right"> <input id="fullbirthday" name="fullbirthday" placeholder="dd-mm-yy" class="col-md-12 no-padding font-size-12" value=""> </label> </div> <div class="break-line margin-bot-5"></div> <div class="div-phone flex"> <label class="control-label user-label col-md-4 no-padding">ฤiแป‡n thoแบกi</label> <label class="control-label col-md-8 no-padding-right"> <input id="telephone" name="telephone" class="col-md-12 no-padding font-size-12" value="" placeholder="Nhแบญp sdt chรญnh"> </label> </div> <div class="break-line margin-bot-5"></div> <div class="div-email flex"> <label class="control-label user-label col-md-4 no-padding">E-mail</label> <label class="control-label col-md-8 no-padding-right"> <input id="email" name="email" type="email" class="col-md-12 no-padding font-size-12" value="" placeholder="Nhแบญp email chรญnh"> </label> </div> <div class="break-line margin-bot-5"></div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">ฤแป‹a chแป‰</label> <label class="control-label col-md-8 no-padding-right"> <input list="l_country" placeholder="Quแป‘c Gia" value="Viแป‡t Nam" name="country" class="col-md-12 no-padding font-size-12"> <datalist id="l_country"> <option>Viแป‡t Nam</option> </datalist> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding"></label> <label class="control-label col-md-8 no-padding-right"> <input list="l_city" placeholder="Tแป‰nh / Thร nh Phแป‘" name="city" class="col-md-12 no-padding font-size-12"> <datalist id="l_city"> <?php if(isset($city)){ foreach ($city as $rows) { ?> <option id-city="<?php echo $rows->id_city?>" value="<?php echo $rows->name?>"></option> <?php }} ?> </datalist> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding"></label> <label class="control-label col-md-8 no-padding-right"> <input list="l_distr" placeholder="Quแบญn / Huyแป‡n" name="district" class="col-md-12 no-padding font-size-12"> <datalist id="l_distr"> </datalist> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding"></label> <label class="control-label col-md-8 no-padding-right"> <input list="l_ward" placeholder="Phฦฐแปng / Xรฃ" name="ward" class="col-md-12 no-padding font-size-12"> <datalist id="l_ward"> </datalist> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding"></label> <label class="control-label col-md-8 no-padding-right"> <input name="street" class="col-md-12 no-padding font-size-12" placeholder="ฤฦฐแปng"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding"></label> <label class="control-label col-md-8 no-padding-right"> <input name="address" class="col-md-12 no-padding font-size-12" placeholder="Sแป‘ nhร "> </label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5 div-ghichu"> <div class="tile-body padding-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Tags</label> <label class="control-label col-md-8 no-padding-right"> <input name="tag" id="tag" class="col-md-12 no-padding font-size-12 available" value="" placeholder="Tags"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ghi chรบ</label> <label class="control-label col-md-8 no-padding-right"> <input name="comments" id="comments" class="col-md-12 no-padding font-size-12 available" value="" placeholder="Nhแบญp ghi chรบ"> </label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5 div-bonus"> <div class="tile-body padding-right-10"> <?php foreach ($list_ext as $value) { if($value['formid'] == 'user' && $value['status'] == '1' ){ ?> <div class="flex"> <label class="control-label user-label col-md-4 no-padding"> <?php echo $value['fieldname'] ?> </label> <?php if($value['fieldtype'] == 'T') {?> <label class="control-label col-md-8 no-padding-right"> <input name="ext[<?php echo $value['fieldcode'] ?>]" id="<?php echo $value['fieldcode'] ?>" class="col-md-12 no-padding font-size-12 available" value="" placeholder="<?php echo $value['fieldname'] ?>"> </label> <?php }else if($value['fieldtype'] == 'D'){?> <select name="ext[<?php echo $value['fieldcode'] ?>]" class="control-label col-md-8 no-border no-padding margin-left-10" id="<?php echo $value['fieldcode'] ?>"> <?php foreach ($list_codic as $material) { if($material['category'] == $value['datasource'] && $material['status'] =='W'){ ?> <option value="<?php echo $material['code'] ?>"><?php echo $material['name'] ?></option> <?php }}?> </select> <?php } ?> </div> <?php }} ?> </div> </div> <div class="fc-corner-right"> <div class="fc-button-group" style="float:right"> <button type="submit" id="btn-save" class="btn btn-primary float-right margin-bot-5"> <i class="fa fa-share"></i> Lฦฐu thรดng tin</button> </div> </div> <div class="modal fade" id="updateIdcard" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 5%; width: 31%" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">CMND/ID</h4> <button type="button" onclick="cancelAddress()" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Loแบกi hรฌnh: </label> <label class="control-label col-md-8 no-padding-right"> <input list="l_type" placeholder="Loแบกi hรฌnh" id="type" name="type" class="col-md-12 no-padding font-size-12" value=""> <datalist id="l_type"> <option data-value="cmnd">CMND</option> <option data-value="passport">Passport</option> </datalist> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Sแป‘: </label> <label class="control-label col-md-8 no-padding-right"> <input type="text" placeholder="Sแป‘" name="idcard" id="idcard" class="col-md-12 no-padding font-size-12" value="" /> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Ngร y cแบฅp: </label> <label class="control-label col-md-8 no-padding-right"> <input placeholder="Ngร y cแบฅp" name="issueddate" class="col-md-12 no-padding font-size-12" id="issueddate" value=""> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Nฦกi cแบฅp: </label> <label class="control-label col-md-8 no-padding-right"> <input list="l_city" placeholder="Nฦกi cแบฅp" name="issuedplace" class="col-md-12 no-padding font-size-12" id="issuedplace" value=""> <datalist id="l_city"> </datalist> </label> </div> </div> <div class="modal-footer" style="background: #f5f5f5"> <button type="button" class="btn btn-gray-white float-right" onclick="cancelAddress()" data-dismiss="modal">Huแปท</button> <button type="button" class="btn btn-primary float-right" onclick="valueAddress()"><i class=""></i>Lฦฐu</button> </div> </div> </div> </div> </form> <file_sep><script src="<?php echo base_url('callevent/node_modules/socket.io-client/dist/socket.io.js');?>"></script> <script> $(document).ready(function(){ var socket = io.connect( 'http://'+window.location.hostname+':3000' ),clientid; socket.on('connect', function () { clientid = socket.id; socket.emit('new_client', { name: getRandomName(), phone: getRandomNumber(), id: clientid }); }); $.post("http://"+window.location.hostname+":3000/call",{name: getRandomName(),phone: getRandomNumber()}, function(data){ if(data==='yes'){ alert("login success"); } }); socket.on('prv_event',function(data){ console.log(data); $('#dropdown-btn').trigger('click'); }); function getRandomName() { const arr = ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"]; return arr[Math.floor(Math.random() * arr.length)]; } function getRandomNumber() { const arr = ["2455","7895","1230","4587","7849","2368","7842","8953","7412","5687"]; return arr[Math.floor(Math.random() * arr.length)]; } }); </script><file_sep><?php error_reporting(0); ini_set('display_errors', 0); defined('BASEPATH') OR exit('No direct script access allowed'); class Ticket extends CI_Controller { private $_init = []; public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url','json_output')); $this->load->model(array('M_api','M_user')); $var = $this->session->userdata; $groupid = $var['groupid']; $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $this->_init['start'] = $start; //Kiแปƒm tra quyแปn vแป›i chแปฉc nฤƒng user $var = $this->session->userdata; $groupid = $var['groupid']; $group = $this->M_api->getlistgroup_array($groupid); $this->_init['isViewTicket'] = substr($group['ticketrule'], 0,1); $this->_init['isInertTicket'] = substr($group['ticketrule'], 1,1); $this->_init['isUpdateTicket'] = substr($group['ticketrule'], 2,1); } public function index() { $data1['error'] = 0; $_data = []; $var = $this->session->userdata; $custid = $var['custid']; if($this->_init['isViewTicket']==0){ $_data['mainview'] = $this->load->view('404',null , TRUE); $this->load->view('dashboard',$_data); return; } $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/getticketbycustid/'.$custid); $data['custid'] = $custid; $data['result'] = json_decode($json,TRUE); $phieuchuaxuly = 0; $phieudahoanthanh = 0; $phieulienquan = 0; $toanbophieu = 0; if(count($data['result']['data'])>0 && $data['result']['code']==1) { //&& $value['hidden'] == '0' foreach ($data['result']['data'] as $value) { if($value['status'] ==0 && $value['agentcurrent']==$custid && $value['status'] != 9) { $phieuchuaxuly++; } if($value['status'] == 4 && $value['agentcurrent']==$custid && $value['status'] != 9) { $phieudahoanthanh++; } if(($value['agentcreated']==$custid || strpos($value['ticketusers'], $custid) !== false) && $value['status'] != 9) { $phieulienquan++; } if($value['agentcurrent'] == $custid && $value['status'] != 9) { $toanbophieu++; } } } $data['phieuchuaxuly'] = $phieuchuaxuly; $data['phieudahoanthanh'] = $phieudahoanthanh; $data['phieulienquan'] = $phieulienquan; $data['toanbophieu'] = $toanbophieu; $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/countticket/'.$this->session->userdata('groupid').'/1'); $data['counter'] = json_decode($json,true)['data']; $_data['script'] = $this->load->view('script/script_ticket', NULL, TRUE); $_data['mainview'] = $this->load->view('ticket/ticket', $data , TRUE); $this->load->view('dashboard',$_data); } public function detail(){ if($this->_init['isViewTicket']==0){ $_data['mainview'] = $this->load->view('404',null , TRUE); $this->load->view('dashboard',$_data); return; } $var = $this->session->userdata; $custid = $var['custid']; $roleid = $var['roleid']; $groupid = $var['groupid']; $ticketid = $this->uri->segment(3); $json_ticket = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/selectByTicketid/'.$ticketid.''); $data['ticket'] = $ticket_detail = json_decode($json_ticket,TRUE); $ticket_detail = $ticket_detail['data'][0]; $ticket_users = $ticket_detail['ticketusers']; $agentcurrent = $ticket_detail['agentcurrent']; //Xแปญ lรฝ viแป‡c nhแบญn phiแบฟu $data['update'] = false; if($custid == $agentcurrent){ $data['update'] = true; } $extinfo = json_decode($ticket_detail['extension'],true); $data['extinfo'] = $extinfo; $data['ticketdetail'] = $ticket_detail; $list_user_support_ticket = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/getuserbylistid?listid='.$ticket_users); $list_user_support_ticket = json_decode($list_user_support_ticket,true); $data['userssuppot'] = $list_user_support_ticket['data']; // get the stage of ticket $l_dtsrc = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select'); $data['l_dtsrc'] = json_decode($l_dtsrc,true)['data']; //extend data $l_ext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/select/ticket'); $data['l_ext'] = json_decode($l_ext,true)['data']; $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getcustomerbycustid/'.$data['ticket']['data'][0]['custid']); $right['customer'] = json_decode($json,TRUE)['data']; $script = []; $script['param']['idcard'] = $right['customer'][0]['idcard']; $script['param']['opid'] = $right['customer'][0]['opid']; $_body = []; $_body['left'] = $this->load->view('ticket/left/t_info', $data, TRUE); $_body['right'] = $this->load->view('ticket/right/t_history', $right, TRUE); $_body['center'] = $this->load->view('ticket/center/t_body', $data, TRUE); $script['update'] = $data['update']; $_data = []; $_data['script'] = $this->load->view('script/script_update_ticket', $script, TRUE); $_data['script2'] = $this->load->view('script/knowledge', NULL, TRUE); $_data['mainview'] = $this->load->view('ticket/ticket_detail', $_body , TRUE); $this->load->view('dashboard',$_data); } public function view_ticket_log($ticketid){ $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/selectTicketLog/'.$ticketid.''); $data['listticketlog'] = json_decode($json,TRUE)['data']; $_data['mainview'] = $this->load->view('ticket/ticketlog/log', $data , TRUE); $this->load->view('dashboard',$_data); } public function view_ticket_task($ticketid){ $data = []; //list agent $list_user = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/getcustomerbyroleid/2?pagesize=700'); $data['l_age'] = json_decode($list_user,true)['data']; //group agent $_jsongroup = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/group'); $data['l_agentgroup'] = json_decode($_jsongroup,true)['data']; $l_type = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/tasktype'); $data['l_type'] = json_decode($l_type,true)['data']; $l_detail = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/taskdetail'); $data['l_detail'] = json_decode($l_detail,true)['data']; $res = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/gettask?ticketid='.$ticketid); $data['_task'] = json_decode($res,true)['data']; $_data['script'] = $this->load->view('ticket/task/script', NULL , TRUE); $_data['mainview'] = $this->load->view('ticket/task/task', $data , TRUE); $this->load->view('dashboard',$_data); } public function recent_ticket($custid='',$agentcurrent='',$idcard=''){ $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/selectTicketLimited/'.$custid.'/'.$agentcurrent); $res = json_decode($json,true)['data']; $out = []; $out['data'] = []; for ($i=0; $i < count($res); $i++) { foreach ($res[$i] as $key => $value) { if ($key=='ticketid') { $href = base_url().'ticket/detail/'.$value.'/'.$custid.'/'.$idcard; $onclick = "addTab('".$href."','#".$value."')"; $out['data'][$i][] = "<a onclick=".$onclick." href='#'>#".$value. "</a>"; }elseif ($key=='title') { $out['data'][$i][] = $this->limit_text($value,8); } }; } json_output(200,$out); } public function recent_contract($idcard='',$opid=''){ $macanho = ''; $maduan = ''; $out = []; $out['data'] = []; if($idcard !='') { $data1 = array( 'reportcode'=>'crmContract01', 'limit'=>25, 'start'=>0, 'queryFilters'=>array( 'idcard'=> $idcard ) ); $result1 = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/api/get_list_contract",$data1); $_json1 = json_decode($result1,true); $_json3 = json_decode($_json1,true); $res = $_json3["result"]["data"]; for ($i=0; $i < count($res); $i++) { foreach ($res[$i] as $key => $value) { if ($key=='contractid') { $href = base_url().'user/contract/'.$value.'?opid='.$opid; $onclick = "addTab('".$href."','".$value."')"; $out['data'][$i][] = "<a onclick=".$onclick." href='#'>#".$value. "</a>"; $maduan = $value; }elseif ($key=='status' ||$key=='property') { $out['data'][$i][] = $value; if($key=='property') { $onclick = "fillExtTicket('".$maduan."','".$value."')"; $out['data'][$i][] = "<a onclick=".$onclick." href='#' data-toggle='tooltip' data-placement='left' title='Chแปn vร o phiแบฟu'><i class='fas fa-cloud-upload-alt'></i></a>"; } } }; } } json_output(200,$out); } public function getrecentticket() { $idcard = $this->input->post('idcard'); $data1 = array( 'reportcode'=>'crmContract01', 'limit'=>3, 'start'=>0, 'queryFilters'=>array( 'idcard'=> $idcard ) ); $result1 = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/api/get_list_contract",$data1); // var_dump($result); $_json1 = json_decode($result1,true); $_json3 = json_decode($_json1,true); $knowledge['contract'] = $_json3["result"]["data"]; echo json_encode($knowledge); } public function test_detail(){ $_body = []; $_body['left'] = $this->load->view('ticket/left/test_left', NULL, TRUE); $_body['right'] = $this->load->view('ticket/right/test_right', NULL, TRUE); $_body['center'] = $this->load->view('ticket/center/test_center', NULL, TRUE); $_data = []; // $_data['script'] = $this->load->view('script/script_update_ticket', null, TRUE); // $_data['script2'] = $this->load->view('script/knowledge', NULL, TRUE); $_data['mainview'] = $this->load->view('ticket/ticket_detail', $_body , TRUE); $this->load->view('dashboard',$_data); } public function test_left_detail(){ // get the stage of ticket $data['l_dtsrc'] = $this->_init['l_dtsrc']; // get the stage of ticket $data['l_stage'] = $this->_init['l_stage']; // get the type ticket $data['l_type'] = $this->_init['l_type']; //extend data $data['l_ext'] = $this->_init['l_ext']; $_data = []; $_data['mainview'] = $this->load->view('ticket/left/t_insert', $data , TRUE); $this->load->view('dashboard',$_data); } public function contract(){ $_body = []; $_body['top'] = $this->load->view('user/top/ud_breadcrumb', NULL, TRUE); $_body['left'] = $this->load->view('user/left/ud_contract', NULL, TRUE); $_body['right'] = $this->load->view('user/right/ud_history', NULL, TRUE); $_body['center'] = $this->load->view('user/center/ud_contract', NULL, TRUE); $_data = []; $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['mainview'] = $this->load->view('user/user_detail', $_body , TRUE); $this->load->view('master',$_data); } //insert ticket public function viewInsert() { //get list cus $data = []; $knowledge['view'] = 'insert'; // get the stage of ticket $l_dtsrc = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select'); $data['l_dtsrc'] = json_decode($l_dtsrc,true)['data']; //extend data $l_ext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/select/ticket'); $data['l_ext'] = json_decode($l_ext,true)['data']; $_body = []; $_body['left'] = $this->load->view('ticket/left/t_insert', $data, TRUE); $_body['right'] = $this->load->view('ticket/right/t_history', $knowledge, TRUE); $_body['center'] = $this->load->view('ticket/center/t_insert', null, TRUE); $_data = []; $_data['script'] = $this->load->view('script/script_insert_ticket', null, TRUE); $_data['script2'] = $this->load->view('script/knowledge', null, TRUE); $_data['mainview'] = $this->load->view('ticket/ticket_insert', $_body , TRUE); $this->load->view('dashboard',$_data); // $time = microtime(); // $time = explode(' ', $time); // $time = $time[1] + $time[0]; // $finish = $time; // $total_time = round(($finish - $this->_init['start']), 4); // echo 'Page generated in '.$total_time.' seconds.'; } public function aj_insert_ticket(){ $post = $this->input->post(); $var = $this->session->userdata; $data_ext = isset($post['ext'])?json_encode($post['ext']):null; $ticket = []; $ticket['log_groupid'] = $var['groupid']; $ticket['agentcurrent'] = isset($post['agentcurrent'])?$post['agentcurrent']:''; $ticket['agentgroup'] = isset($post['agentgroup'])?$post['agentgroup']:''; $ticket['agentcreated'] = $var['custid']; $ticket['custid'] = isset($post['customer'])?$post['customer']:''; $ticket['contractid'] = isset($post['contractid'])?$post['contractid']:''; $ticket['ticketchannel'] = isset($post['ticketchannel'])?$post['ticketchannel']:''; $ticket['priority'] = isset($post['priority'])?$post['priority']:''; $ticket['extension'] = $data_ext!=null?$data_ext:null; $ticket['status'] = 0; $ticket['sla'] = isset($post['sla'])?date('Y-m-d H:i:s',strtotime($post['sla'])):''; $ticket['status'] = isset($post['ticketstatus'])?$post['ticketstatus']:''; $ticket['duedate'] = isset($post['duedate'])?date('Y-m-d H:i:s',strtotime($post['duedate'])):''; $ticket['finishdate'] = isset($post['finishdate'])?date('Y-m-d H:i:s',strtotime($post['finishdate'])):''; $ticket['requestdate'] = isset($post['requestdate'])?date('Y-m-d H:i:s',strtotime($post['requestdate'])):''; $ticket['firstreply'] = isset($post['firstreply'])?date('Y-m-d H:i:s',strtotime($post['firstreply'])):''; $ticket['levelticket'] = isset($post['levelticket'])?$post['levelticket']:''; $ticket['categoryid'] = isset($post['categoryid'])?$post['categoryid']:''; $ticket['groupid'] = isset($post['groupid'])?$post['groupid']:''; $ticket['tickettype'] = isset($post['tickettype'])?$post['tickettype']:''; $ticket['ticketusers'] = $ticket['agentcurrent'].','.($ticket['agentcurrent']!=$var['custid']?$var['custid']:''); $ticket['title'] = isset($post['title'])?$post['title']:''; $ticket['transref'] = isset($post['transref'])?$post['transref']:''; // var_dump($ticket); $postdata = http_build_query($ticket); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/insert',false,$context); echo $result; $_res = json_decode($result,true); if (isset($_res['code']) && $_res['code'] == 1 && isset($post['cmt']) && $post['cmt'] !='') { $log['action'] = ""; $log['useraction'] = $var['custid']; $log['cmt'] = isset($post['cmt'])?$post['cmt']:''; $log['ticketid'] = $_res['data']; $_result = $this->aj_insert_ticket_log($log); // echo $_result; } } public function aj_update_ticket() { $post = $this->input->post(); //var_dump($post); $var = $this->session->userdata; $data_ext = isset($post['ext'])?json_encode($post['ext']):null; $ticket = []; $tid = $ticket['ticketid'] = isset($post['ticketid'])?$post['ticketid']:'-1'; // $ticket['log_custid'] = $var['custid']; // $ticket['log_roleid'] = $var['roleid']; $ticket['log_groupid'] = $var['groupid']; $ticket['agentgroup'] = isset($post['agentgroup'])?$post['agentgroup']:'-1'; $ticket['agentcurrent'] = isset($post['agentcurrent'])?$post['agentcurrent']:'-1'; $ticket['title'] = isset($post['title'])?$post['title']:'-1'; $ticket['ticketchannel'] = isset($post['ticketchannel'])?$post['ticketchannel']:'-1'; $ticket['priority'] = isset($post['priority'])?$post['priority']:'-1'; $ticket['extension'] = $data_ext!=null?$data_ext:'-1'; $ticket['sla'] = isset($post['sla'])?date('Y-m-d H:i:s',strtotime($post['sla'])):'-1'; $ticket['status'] = isset($post['ticketstatus'])?$post['ticketstatus']:'-1'; $ticket['duedate'] = isset($post['duedate'])?date('Y-m-d H:i:s',strtotime($post['duedate'])):'-1'; $ticket['finishdate'] = isset($post['finishdate'])?date('Y-m-d H:i:s',strtotime($post['finishdate'])):'-1'; $ticket['requestdate'] = isset($post['requestdate'])?date('Y-m-d H:i:s',strtotime($post['requestdate'])):'-1'; $ticket['firstreply'] = isset($post['firstreply'])?date('Y-m-d H:i:s',strtotime($post['firstreply'])):'-1'; $ticket['levelticket'] = isset($post['levelticket'])?$post['levelticket']:'-1'; $ticket['tickettype'] = isset($post['tickettype'])?$post['tickettype']:'-1'; $ticket['categoryid'] = isset($post['categoryid'])?$post['categoryid']:'-1'; $ticket['groupid'] = isset($post['groupid'])?$post['groupid']:'-1'; $ticket['ticketusers'] = isset($post['ticketusers'])?$this->check_exist($post['ticketusers'],$ticket['agentcurrent']):'-1'; $ticket['title'] = isset($post['title'])?$post['title']:'-1'; $ticket['transref'] = isset($post['transref'])?$post['transref']:'-1'; foreach ($ticket as $key => $value) { if ($value == '-1') { unset($ticket[$key]); } } // var_dump($ticket); $postdata = http_build_query($ticket); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/update/'.$tid,false,$context); echo $result; $_res = json_decode($result,true); if (isset($_res['code']) && $_res['code'] == 1 && ((isset($post['cmt']) && $post['cmt'] !='')||(isset($post['changelog'])&&$post['changelog']!=''))) { if ($post['cmt']=='') { $log['action'] = "Cแบญp nhแบญt phiแบฟu"; }else{ $log['action'] = ""; } $log['useraction'] = $var['custid']; $log['cmt'] = isset($post['cmt'])?$post['cmt']:''; $log['changelog'] = isset($post['changelog'])?$post['changelog']:''; $log['ticketid'] = $tid; $_result = $this->aj_insert_ticket_log($log); // echo $_result; } } private function check_exist($string,$find){ $result = strpos($string,$find); if(!$result){ return $string.','.$find; }else{ return $string; } } public function aj_insert_ticket_log($log){ $postdata = http_build_query($log); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/insert_ticketlog/',false,$context); return $result; } public function updateTicketLog() { $ticketid = $this->input->post('ticketid'); $cmt = $this->input->post('cmt'); $action = ""; $postdata = http_build_query([ 'action' => $action, 'useraction'=> $this->session->userdata('custid'), 'cmt'=>$cmt, 'ticketid' => $ticketid, ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/insert_ticketlog/'.'',false,$context); echo $result; } public function get_to_my_ticket($tckid){ $var = $this->session->userdata; $log_groupid = $var['groupid']; $ticket = []; $ticket['log_groupid'] = $log_groupid; $ticket['agentcurrent'] = $this->session->userdata['custid']; $ticket['agentgroup'] = $this->session->userdata['groupid']; $ticket['ticketid'] = $tckid; $ticket['status'] = 0; $postdata = http_build_query($ticket); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/update/'.$tckid,false,$context); echo $result; $_res = json_decode($result,true); if (isset($_res['code']) && $_res['code'] == 1) { $log['action'] = "Tiแบฟp nhแบญp phiแบฟu"; $log['useraction'] = $this->session->userdata['custid']; $log['cmt'] = ''; $log['changelog'] = 'Ngฦฐแปi phแปฅ trรกch: '.$this->session->userdata['custname']; $log['ticketid'] = $tckid; $_result = $this->aj_insert_ticket_log($log); // echo $_result; } } public function deleteTicket() { $ticketid = $this->input->post('ticketid'); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Api/ticket/delete/'.$ticketid.''); header('location:../ticket'); // var_dump($ticketid); } public function getIdCard() { $var = $this->session->userdata; $custid = $var['custid']; $roleid = $var['roleid']; $telephone = $this->input->post('telephone'); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/search?action=search_customer&telephone='.$telephone.'&roleid='.$roleid); echo $result; } public function getIdCardTicket() { $ticketid = $this->input->post('ticketid'); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/selectByTicketid/'.$ticketid); echo $result; } private function limit_text($text, $limit) { if (str_word_count($text, 0) > $limit) { $words = str_word_count($text, 2); $pos = array_keys($words); $text = substr($text, 0, $pos[$limit]) . '...'; } return $text; } } <file_sep><div class="col-md-100 no-padding padding-left-5"> <div class="tile height-1024"> <div class="table-responsive"> <table class="table" id="table-1-searchticket"> <thead class="no-border-top"> <tr> <th width="100">ID</th> <th width="250">Tรชn phiแบฟu</th> <th width="130px">Ngฦฐแปi yรชu cแบงu</th> <th width="130px">Ngฦฐแปi phแปฅ trรกch</th> <th width="75px">Nguแป“n phiแบฟu</th> <th width="70px">ฤแป™ ฦฐu tiรชn</th> <th width="69px">Tรฌnh trแบกng</th> </tr> </thead> <tbody> <?php if(count($result['data']) >0&& $result['code']==1) { foreach ($result['data'] as $rows) { ?> <tr class="border-bot-1"> <td> <a class="buttonsearchiframe" onclick="addTab('<?php echo base_url().'ticket/detail/'.$rows['ticketid'].'/'.$rows['custid'].'/'.$rows['idcard'] ?>','#<?php echo $rows['ticketid'] ?>')" href="#" title=""> <span class="id-label span-warning">P</span> #<?php echo $rows['ticketid'] ?> </a> </td> <td> <?php echo $rows['title'] ?> </td> <td><?php if(isset($rows['agentcreatedname'])){ echo $rows['agentcreatedname'];} ?></td> <td><?php if(isset($rows['name'])){ echo $rows['name'];} ?></td> <td><?php if ($rows['ticketchannel']==2) {echo "ฤiแป‡n thoแบกi";} elseif ($rows['ticketchannel']==1) {echo "Trแปฑc tiแบฟp";} elseif ($rows['ticketchannel']==3) {echo "Email";} elseif ($rows['ticketchannel']==4) {echo "Chat";} else {echo "Khรดng xรกc ฤ‘แป‹nh";} ?></td> <td><?php if ($rows['priority']==1) {echo "Thฦฐแปng";} elseif ($rows['priority']==2) {echo "Cao";} elseif ($rows['priority']==3) {echo "Khแบฉn cแบฅp";} else {echo "Khรดng xรกc ฤ‘แป‹nh";} ?></td> <td><?php if ($rows['status']==9) {echo "Hแปงy";} elseif ($rows['status']==0) {echo "ฤang xแปญ lรฝ";} elseif ($rows['status']==4) {echo "Hoร n thร nh";} else {echo "Khรดng xรกc ฤ‘แป‹nh";} ?></td> </tr> <?php }} ?> </tbody> </table> </div> </div> </div><file_sep><script type="text/javascript"> $(document).ready(function(){ $('#form-user').on('submit',function(){ $('#form-user').validate({ rules: { name: { required: true }, email: { required: true } }, invalidHandler: function(event, validator) { var errors = validator.numberOfInvalids(); // <- NUMBER OF INVALIDS console.log(errors); }, submitHandler: function(f) { // f.submit(); }, showErrors: function(errorMap, errorList) { var errors = this.numberOfInvalids(); // <- NUMBER OF INVALIDS console.log(errorMap); $.each(errorMap, function(key, value) { console.log(key); var parent = $('[name="' + key + '"]').parent(); console.log(parent); }); this.defaultShowErrors(); // <- ENABLE default MESSAGES } }); return false; }); }); </script><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-2 col-md-22 padding-left-15"> <?php echo isset($left)?$left:'' ?> </div> <div class="col-md-7 padding-left-1"> <!-- <?php echo isset($center)?$center:'' ?> --> <iframe class="iframeQueue" id="iframeQueue" style="min-height: 1024px;width: 100%; border: none;" src="<?php echo base_url() ?>queue/rightFilter?queue=21114"></iframe> </div> <div class="col-md-2 col-md-18 padding-left-5"> </div> </div> </main> <file_sep><script type="text/javascript"> $(document).ready(function(){ $('#modalDelete').on('shown.bs.modal', function (e) { var code = $(e.relatedTarget).data('code'); $(e.currentTarget).find('input[name="codedelete"]').val(code); var category = $(e.relatedTarget).data('category'); $(e.currentTarget).find('input[name="categorydelete"]').val(category); }); $('#modalUpdate').on('shown.bs.modal', function (e) { var code = $(e.relatedTarget).data('code'); $(e.currentTarget).find('input[name="code"]').val(code); var category = $(e.relatedTarget).data('category'); $(e.currentTarget).find('input[name="category"]').val(category); var name = $(e.relatedTarget).data('name'); $(e.currentTarget).find('input[name="name"]').val(name); var status = $(e.relatedTarget).data('status'); $(e.currentTarget).find('select[name="status"]').val(status); var comments = $(e.relatedTarget).data('comments'); $(e.currentTarget).find('textarea[name="comments"]').val(comments); var ref1 = $(e.relatedTarget).data('ref1'); $(e.currentTarget).find('select[name="ref1_update"]').val(ref1); if(ref1 !='') { var obj = document.getElementById("ref1_update"); var ref2 = $(e.relatedTarget).data('ref2'); if(ref2 !=null) { getGroupRef2(obj,'ref2_update',ref2); } } }); }) function deleteButton() { var category = $('#categorydelete').val(); var code = $('#codedelete').val(); var action = 'delete'; $.ajax({ url: '<?php echo base_url().'groupuser/updateDatasource' ?>', type: 'POST', dataType: 'JSON', data: {category:category,code:code,action:action}, }) .done(function(data) { if(data.code==1){ window.location.reload(); }else{ alert(data.message); } }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); } function updateButton() { var category = $('#category').val(); var code = $('.code').val(); var name = $('.nameField').val(); var status = $('#status').val(); var comments = $('#comments').val(); var ref1 = $('#ref1_update').val(); var ref2 = $('#ref2_update').val(); var action = 'update'; if(comments == '') { comments = ' '; } $.ajax({ url: '<?php echo base_url().'groupuser/updateDatasource' ?>', type: 'POST', dataType: 'JSON', data: {category:category,code:code,name:name,action:action,status:status,comments:comments,ref1:ref1,ref2:ref2}, }) .done(function(data) { if(data.code==1){ window.location.reload(); }else{ alert(data.message); } }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); } function insertSelectBox() { var code = $('#code').val(); var name = $('#name').val(); var category = $('#category').val(); var comments = $('#comments_insert').val(); var ref1 = $('#ref1_insert').val(); var ref2 = $('#ref2_insert').val(); $.ajax({ url: '<?php echo base_url().'groupuser/insertSelectBox' ?>', type: 'POST', dataType: 'JSON', data: {code:code,name:name,category:category,comments:comments,ref1:ref1,ref2:ref2}, }) .done(function(data) { if(data.code==1){ window.location.reload(); }else if(data.data.indexOf("PRIMARY KEY constraint 'PK_crcodedictionary") !== -1){ alert("Trรนng mรฃ. Vui lรฒng nhแบญp lแบกi mรฃ"); } }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); } function changeiFrameIssueGroup() { var ref1 = $('#codictionary_issuegroup').val(); document.getElementById('iframeIssueGroup').src = "<?php echo base_url() ?>issuegroup/rightFilter?ref1="+ref1; } function changeiFrameIssueDetail() { var ref1 = $('#codictionary_issuegroup').val(); var ref2 = $('#codictionary_issuegrouptype').val(); document.getElementById('iframeIssueDetail').src = "<?php echo base_url() ?>issuedetail/rightFilter?ref1="+ref1+"&ref2="+ref2; } function changeiFrameDetailWork() { var ref1 = $('#codictionary_typework').val(); document.getElementById('iframeDetailWork').src = "<?php echo base_url() ?>detailwork/rightFilter?ref1="+ref1; } function getGroup(obj,id) { var value = obj.value; $.ajax({ url: '<?php echo base_url() ?>issuedetail/getIssueGroupByType', type: 'POST', dataType: 'JSON' }) .done(function(data){ var data_html = ''; for (var i = 0; i < data.data.length; i++) { if(data.data[i].ref1 == value) { data_html+='<option value="'+data.data[i].code+'">'+data.data[i].name+'</option>'; } } $('#'+id+'').html('<option value="-1">Tแบฅt cแบฃ</option>\ '+data_html+''); }) .fail(function(){ }); } function getGroupRef2(obj,id,ref2) { var value = obj.value; $.ajax({ url: '<?php echo base_url() ?>issuedetail/getIssueGroupByType', type: 'POST', dataType: 'JSON' }) .done(function(data){ var data_html = ''; for (var i = 0; i < data.data.length; i++) { if(data.data[i].ref1 == value) { data_html+='<option value="'+data.data[i].code+'">'+data.data[i].name+'</option>'; } } $('#'+id+'').html(data_html); $('#'+id+'').val(ref2); }) .fail(function(){ }); } </script><file_sep><script type="text/javascript"> $(document).ready( function () { $( "#idcard_modal" ).click(function() { $('#updateIdcard').modal('toggle'); $('#updateIdcard').on('shown.bs.modal', function (e) { $('#issueddate').datetimepicker({timepicker:false, format:'d/m/Y'}); }) }); $('#table-1-create-user').DataTable({ "paging": true, "language": { "paginate": { "previous": "Trฦฐแป›c", "next":"Sau" } }, "columns": [ { "width": "20%" }, { "width": "20%" }, { "width": "20%" }, { "width": "20%" }, { "width": "20%" } ], "info": false, "searching": false, "scrollY": "100%", "iDisplayLength": 25, "scrollX": true, "bLengthChange": false, "scrollCollapse": true }).columns.adjust().draw(); $('form#insertUserVal').on('submit',function(){ var formData = new FormData($(this)[0]); for (var [key, value] of formData.entries()) { // console.log(key, value); } var name = formData.get('custname'); $(this).find('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner'); $.ajax({ type: "POST", url: "<?php echo base_url().'user/aj_validate';?>", data: formData, dataType:'json', contentType: false, cache: false, processData:false, beforeSend: function() { }, success: function(data) { $('#btn-save').prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); if(data.code==0){ // swal("Cแบฃnh bรกo !", data.message, "warning"); // parent.alertLog("Cแบฃnh bรกo !", data.message, "warning"); var string = "B\u1ea1n thu\u1ed9c nh\u00f3m"; if(data.data == null) { swal("Cแบฃnh bรกo !", data.message, "warning"); return; } swal({ title: "Cแบฃnh bรกo !", text: data.message, type: 'warning', showCancelButton: true, confirmButtonText: 'Tiแบฟp tแปฅc !', cancelButtonText: 'Huแปท', buttons: true, dangerMode: true, },function(willDelete){ if (willDelete) { insertUser(formData,name); } }); }else{ insertUser(formData,name); } }, error: function(xhr, status, error) { console.log(error); } }); return false; }); $('#fullbirthday').datetimepicker({timepicker:false,format:'d/m/Y'}); $('input[name=city]').on('keyup',function(){ var val = $(this).val(); var opt = $('datalist#l_city').find('option[value="'+val+'"]'); if (opt.length>0) { var idcity = opt.attr('id-city'); $.ajax({ url: '<?php echo base_url()?>user/selectCity', type: 'POST', dataType: 'JSON', data: {id_city : idcity}, }) .done(function(data) { var l_r = ''; for (var i = 0; i < data.length; i++) { l_r+='<option value="'+data[i]['name']+'" id="'+data[i]['id_district']+'"></option>'; } $('datalist#l_distr').html(l_r); }) .fail(function() { console.log("error"); }) } }); $('input[name=district').on('keyup',function(){ var val = $(this).val(); var opt = $('datalist#l_distr').find('option[value="'+val+'"]'); if (opt.length>0) { var id = opt.attr('id'); $.ajax({ url: '<?php echo base_url()?>user/selectDistrict', type: 'POST', dataType: 'JSON', data: {id_district : id}, }) .done(function(data) { var l_r = ''; for (var i = 0; i < data.length; i++) { l_r+='<option value="'+data[i]['name']+'" id="'+data[i]['id_ward']+'"></option>'; } $('datalist#l_ward').html(l_r); }) .fail(function() { console.log("error"); }) } }); }); function selectDistrict(obj){ var $id = obj.value; $('.gicungdc1').remove(); $.ajax({ url: '<?php echo base_url()?>user/selectDistrict', type: 'POST', dataType: 'JSON', data: {id_district : $id}, }) .done(function(data) { // console.log(data.loaisp); for (var i = 0; i < data.length; i++) { $('#dodulieu1').after('<option title="'+data[i]['name']+'" class="gicungdc1" value="'+data[i]['id_ward']+'">'+data[i]['name']+'</option>'); } }) .fail(function() { console.log("error"); }) } function selectGroup(obj){ var $id = obj.value; $('.div-add').remove(); $('.group_item').remove(); $('.div-queue').remove(); if($id != 3) { $('.div-ghichu').hide(); $('.div-bonus').hide(); $('.div-cmnd').hide(); $('.div-address').hide(); $('.div-danhxung').hide(); $('.div-ngaysinh').hide(); document.querySelector('#idcard_modal').required = false; document.querySelector('#email').required = false; if($id == 2){ $('.div-phone').after('<div class="div-queue">\ <label class="control-label user-label col-md-3 no-padding">Hร ng chแป cuแป™c gแปi</label>\ <select class="control-label col-md-8 no-border no-padding margin-left-10" id="queue">\ <option value="21114" >Chuyแปƒn nhฦฐแปฃng hแปฃp ฤ‘แป“ng</option>\ <option value="21115" >Thanh toรกn vay</option>\<option value="21121" >Tiแบฟng Anh</option>\ <option value="21116" >Khรกc</option>\ </select>\ </div>'); } $('.div-group').after('<div class="div-add">\ <label class="control-label user-label col-md-3 no-padding">ID:</label>\ <label class="control-label col-md-8 no-padding-right">\ <input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhแบญp ID" minlength="5" maxlength="10" id="custid" name="custid">\ </label>\ </div>\ <div class="div-add">\ <label class="control-label user-label col-md-3 no-padding">Password:</label>\ <label class="control-label col-md-8 no-padding-right">\ <input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhแบญp Password" type="password" id="password" name="password">\ </label>\ </div>\ '); } else{ $('.div-ghichu').show(); $('.div-bonus').show(); $('.div-cmnd').show(); $('.div-address').show(); $('.div-danhxung').show(); $('.div-ngaysinh').show(); } } function valueAddress() { var idcard = $('#idcard').val(); $('#idcard_modal').val(idcard); $('#updateIdcard').modal('toggle'); } function cancelAddress() { $('#idcard_modal').val(''); $('#idcard').val(''); $('#type').val(''); $('#issueddate').val(''); $('#issuedplace').val(''); $('#updateIdcard').modal('toggle'); } function insertUser(formData,name) { $.ajax({ type: "POST", url: "<?php echo base_url().'user/aj_insert';?>", data: formData, dataType:'json', contentType: false, cache: false, processData:false, beforeSend: function() { }, success: function(data) { $('#btn-save').prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); if(data.code==0){ // swal("Cแบฃnh bรกo !", data.message, "warning"); parent.alertLog("Cแบฃnh bรกo !", data.message, "warning"); }else{ // swal("Thร nh cรดng !", "Thรชm ngฦฐแปi dรนng thร nh cรดng.", "success"); parent.alertLog("Thร nh cรดng !", "Thรชm ngฦฐแปi dรนng thร nh cรดng.", "success"); var tab = window.top.$('div.tab-pane.active').attr('id'); window.top.$('li a.nav-link[href="#'+tab+'"]').find('span').html(name); $.ajax({ url: '<?php echo base_url() ?>user/getUserByRecodeId', type: 'POST', dataType: 'JSON', data: {id: data.data} }) .done(function(data1){ window.location.href = "<?php echo base_url()?>user/detail/?cusid="+data1.data[0].custid+"&idcard="+data1.data[0].idcard+"&roleid="+data1.data[0].roleid; }) .fail(function(){ }); } }, error: function(xhr, status, error) { console.log(error); } }); } </script><file_sep> <form id="form-ticket"> <div class="tile p-0 padding-5 margin-bot-5 z-index-100"> <div class="tile-body padding-left-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngฦฐแปi yรชu cแบงu (<span style="color: red;">*</span>)</label> <select data-placeholder="Chแปn ngฦฐแปi yรชu cแบงu..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="customer"> <option value="" ></option> <?php if (isset($l_cus)) { foreach ($l_cus as $cus) { if ($cus['custname']!='') { $s=''; if ($this->uri->segment(4)!='' && $this->uri->segment(4)==$cus['custid']) { $s='selected'; } echo('<option value="'.$cus['custid'].'">'.$cus['custname'].'</option>'); } } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngฦฐแปi tแบกo(<span style="color: red;">*</span>)</label> <label class="control-label col-md-7 no-padding-right"> <input type="" readonly="" name="" value="<?php echo $this->session->userdata('custname')?>"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Nhรณm phแปฅ trรกch(<span style="color: blue;">*</span>)</label> <select data-placeholder="Chแปn nhรณm phแปฅ trรกch..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="agentgroup"> <option value=""></option> <?php if (isset($l_agentgroup)) { foreach ($l_agentgroup as $key => $value) { echo '<option value="'.$value['groupid'].'">'.$value['groupname'].'</option>'; } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Phแปฅ trรกch (<span style="color: blue;">*</span>)</label> <select data-placeholder="Chแปn ngฦฐแปi phแปฅ trรกch..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="agentcurrent"> <option value=""></option> <?php if (isset($l_age)) { foreach ($l_age as $cus) { if ($cus['custname']!='') { $s=''; if ($this->session->userdata('custid')!='' && $this->session->userdata('custid')==$cus['custid']) { $s='selected'; } echo('<option value="'.$cus['custid'].'" data-group="'.$cus['groupid'].'">'.$cus['custname'].'</option>'); } } } ?> </select> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Nguแป“n phiแบฟu</label> <select name="ticketchannel" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control"> <option value="1">Trแปฑc tiแบฟp</option> <option value="2">ฤiแป‡n thoแบกi</option> <option value="3">Email</option> <option value="4">Chat</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Mแปฉc ฦฏu tiรชn</label> <select name="priority" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control"> <option value="1">Thฦฐแปng</option> <option value="2">Cao</option> <option value="3">Khแบฉn cแบฅp</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Tรฌnh trแบกng</label> <select readonly="" name="ticketstatus" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control"> <option value="1">Tแบกo mแป›i</option> <option value="0" disabled="">ฤang xแปญ lรฝ</option> <option value="4" disabled="">Hoร n thร nh</option> <option value="9" disabled="">Hแปงy</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Giai ฤ‘oแบกn</label> <select name="levelticket" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control"> <?php if (isset($l_stage) && !empty($l_stage)) { foreach ($l_stage as $key => $value) { echo '<option value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Phรขn loแบกi</label> <select name="tickettype" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="level_1"> <?php if (isset($l_type) && !empty($l_type)) { foreach ($l_type as $key => $value) { echo '<option value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Nhรณm vแบฅn ฤ‘แป</label> <select name="groupid" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="level_2"> <?php if (isset($l_group) && !empty($l_group)) { foreach ($l_group as $key => $value) { echo '<option ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Chi tiแบฟt Vฤ</label> <select name="categoryid" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="level_3"> <?php if (isset($l_cate) && !empty($l_cate)) { foreach ($l_cate as $key => $value) { echo '<option ref1="'.$value['ref1'].'" ref2="'.$value['ref2'].'" value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class="break-line margin-bot-5"></div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngร y yรชu cแบงu</label> <label class="control-label col-md-7 no-padding-right"> <input name="requestdate" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngร y phแบฃn hแป“i</label> <label class="control-label col-md-8 no-padding-right"> <input name="firstreply" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Thแปi hแบกn SLA</label> <label class="control-label col-md-8 no-padding-right"> <input name="sla" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii"> </label> </div> <div class="break-line margin-bot-5"></div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngร y hแบนn</label> <label class="control-label col-md-8 no-padding-right"> <input name="duedate" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngร y hoร n thร nh</label> <label class="control-label col-md-8 no-padding-right"> <input name="finishdate" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii"> </label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Mรฃ giao dแป‹ch</label> <label class="control-label col-md-8 no-padding-right"> <input name="transref" class="col-md-12 no-padding font-size-12 crm-control" placeholder="" value="<?php echo($this->uri->segment(3))?>"> </label> </div> <div class="break-line margin-bot-5"></div> <?php if (isset($l_ext)) { foreach ($l_ext as $key => $value) { $f = isset($value['fieldcode'])?$value['fieldcode']:''; $n = isset($value['fieldname'])?$value['fieldname']:''; $v = isset($extinfo[$value['fieldcode']])?$extinfo[$value['fieldcode']]:''; $d = '<div class="flex"> <label class="control-label user-label col-md-4 no-padding">'.$n.'</label>'; if (isset($value['fieldtype']) && $value['fieldtype']=='T') { if($this->uri->segment(3) !=null && $value['fieldcode'] =='magd') { $d.=' <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12 crm-ext" log="'.$n.'" value="'.$this->uri->segment(3).'" name="ext['.$f.']"> </label> '; } else{ $d.=' <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12 crm-ext" log="'.$n.'" value="'.$v.'" name="ext['.$f.']"> </label> '; } }elseif(isset($value['fieldtype']) && $value['fieldtype']=='D'){ $d.='<select class="control-label col-md-8 no-border no-padding margin-left-10 crm-ext" log="'.$n.'" name="ext['.$f.']">'; if (isset($value['datasource']) && isset($l_dtsrc)) { foreach ($l_dtsrc as $ky => $vl) { if ($vl['category'] == $value['datasource']) { $sel = ''; if ($v==$vl['code']) { $sel = 'selected'; } $d.='<option '.$sel.' value="'.$vl['code'].'">'.$vl['name'].'</option>'; } } }else{ $d.='<option>(Dแปฏ liแป‡u bแป‹ lแป—i)</option>'; } $d.='</select>'; }else{ $d.='<label>ฤang cแบญp nhแบญt</label>'; } $d.='</div>'; echo ($d); } } ?> </div> </div><file_sep><?php error_reporting(0); ini_set('display_errors', 0); // defined('BASEPATH') OR exit('No direct script access allowed'); class User extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url')); $this->load->model('M_api'); $this->load->model('M_user'); $this->load->model('M_data_API'); $this->load->driver('cache'); $dayCompare = strtotime('2000-01-01T00:00:00'); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $this->_init['start'] = $start; $arrContextOptions=array( "ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false, ), ); $_jsongroup = $this->M_api->getListGroupCache(); $this->_init['_jsongroup'] = json_decode($_jsongroup,true); $_jsoncity = $this->cache->memcached->get('_jsoncity'); if(!$_jsoncity){ $_jsoncity = json_decode(file_get_contents('https://hungminhits.com/api/list_city',false, stream_context_create($arrContextOptions))) ; $this->cache->memcached->save('_jsoncity',$_jsoncity, 86400); } $this->_init['_jsoncity'] = $_jsoncity; $_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/select/user'); $this->_init['_jsonlistext'] = json_decode($_jsonlistext,true); $_jsonlistcodic = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/'); $this->_init['_jsonlistcodic'] = json_decode($_jsonlistcodic,true); //Kiแปƒm tra quyแปn vแป›i chแปฉc nฤƒng user $var = $this->session->userdata; $groupid = $var['groupid']; $group = $this->M_api->getlistgroup_array($groupid); $this->_init['isViewUser'] = substr($group['userrule'], 0,1); $this->_init['isInserUser'] = substr($group['userrule'], 1,1); $this->_init['isUpdateUser'] = substr($group['userrule'], 2,1); } public function index() { $_body = []; $_body['left'] = $this->load->view('user/left/ud_dashboard_left',null,TRUE); $_body['right'] = $this->load->view('user/right/ud_dashboard_right', null, TRUE); $_body['center'] = $this->load->view('user/center/ud_dashboard_center', null, TRUE); $_data = []; $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE); $_data['mainview'] = $this->load->view('user/user', $_body , TRUE); $this->load->view('dashboard',$_data); } public function testContract() { $idcard = $this->input->get('idcard'); $opid = $this->input->get('opid'); $this->M_data_API->getContractByIdcard($idcard,$opid); } public function detail(){ $var = $this->session->userdata; $user_seassion = $this->session->userdata; $custid_login = $user_seassion['custid']; if(isset($_GET['cusid'])){ $_cusid = $_GET['cusid']; } else { $_cusid = ''; } if($this->_init['isViewUser']==0 && $custid_login!=$_cusid){ $_data['mainview'] = $this->load->view('404',null , TRUE); $this->load->view('dashboard',$_data); return; } $_body = []; $customer = []; if(isset($_GET['phone'])){ $_phone = $_GET['phone']; } else { $_phone = ''; } if(isset($_GET['roleid'])){ $_roleid = $_GET['roleid']; } else { $_roleid = ''; } //Get Thong tin dia chi $customer['city'] = $this->_init['_jsoncity']; //Get thรดng tin khรกch hร ng dแปฑa vร o id hoแบทc sแป‘ phone $roleid = $user_seassion['roleid']; $groupid = $user_seassion['groupid']; if(isset($_GET['action'])) { if($_GET['action'] == 'profile') { $roleid = '1'; } else { $roleid = $var['roleid']; } } else { $roleid = $var['roleid']; } //Data Auth, tแบฅt cแบฃ ฤ‘แปu phแบฃi sแปญ dแปฅng : custid cแปงa agent ฤ‘ang login, roleid, groupdid $dataAuth = []; $_jsonuser = $this->M_user->getUserByCustId($_cusid,$dataAuth); //Kiแบฟm tra User if($_jsonuser['code']==1){ $_dataContract['user'] = $_jsonuser['data']; }else{ $data["msg"] = "Mรฃ khรกch hร ng khรดng tแป“n tแบกi"; $_data['mainview'] = $this->load->view('404',$data , TRUE); $this->load->view('dashboard',$_data); return; } //Get thรดng tin ticket dแปฑa vร o cusid $_jsonticket = json_decode(file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/select/'.$_cusid.'?agentid='.$custid_login.'&groupid='.$groupid), true); $_dataContract['ticket'] = $_jsonticket['data']; $_dataContract['trade'] = array(); //Get thรดng tin cuแป™c gแปi tแปซ SDT $roleid = $var['roleid']; $role_list = array(); // if($roleid==1){ $role_list['1']="<NAME>"; $role_list['2']="<NAME>"; // } $role_list['3']="Khรกch hร ng"; //Get List ฤแป‹a chแป‰ //Group List $group_list = $this->_init['_jsongroup']; $customer['role_list'] = $role_list; $right['role_list'] = $role_list; $customer['group_list'] = $group_list['data']; $right['group_list'] = $group_list['data']; $customer['detail'] = $_jsonuser['data']; $list_ext = $this->_init['_jsonlistext']; $customer['list_ext'] = $list_ext['data']; $right['list_ext'] = $list_ext['data']; $list_codic = $this->_init['_jsonlistcodic']; $customer['list_codic'] = $list_codic['data']; $_jsonaddress = json_decode(file_get_contents('http://test.tavicosoft.com/crm/index.php/api/address/'.$_cusid.''), true); $_jsonhistory = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/user_history/'.$_cusid.''); $_jsonhistory_data= json_decode($_jsonhistory,true); $right['history'] = $_jsonhistory_data['data']; $customer['address'] = $_jsonaddress['data']; $_body['top'] = $this->load->view('user/top/ud_breadcrumb', NULL, TRUE); $_body['left'] = $this->load->view('user/left/ud_info',$customer,TRUE); $_body['right'] = $this->load->view('user/right/ud_history', $right, TRUE); $_body['center'] = $this->load->view('user/center/ud_body', $_dataContract, TRUE); $_data = []; $_data['link'] = 'user/detail'; $_data['script'] = $this->load->view('script/script_user_info', NULL, TRUE); $_data['mainview'] = $this->load->view('user/user_detail', $_body , TRUE); $this->load->view('dashboard',$_data); } public function getAddressApi() { $custid = $this->input->post('custid'); $_jsonaddress = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/address/'.$custid.''); echo $_jsonaddress; } public function getHistoryUser() { $_cusid = $this->input->post('custid'); $_jsonhistory = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/user_history/'.$_cusid.''); echo $_jsonhistory; } public function create(){ $arrContextOptions=array( "ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false, ), ); $_jsoncity = json_decode(file_get_contents('https://hungminhits.com/api/list_city',false, stream_context_create($arrContextOptions))) ; $var = $this->session->userdata; $roleid = $var['roleid']; $role_list = array(); if($roleid==1){ $role_list['1']="<NAME>"; $role_list['2']="Chuyรชn Viรชn"; } $role_list['3']="Khรกch hร ng"; //Group List $_jsongroup = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/group'); $group_list = json_decode($_jsongroup,true); $_data = []; $_jsonlistcodic = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/'); $list_codic = json_decode($_jsonlistcodic,true); $_data['list_codic'] = $list_codic['data']; $_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/select/user'); $list_ext = json_decode($_jsonlistext,true); $_data['list_ext'] = $list_ext['data']; $_data['role_list'] = $role_list; $_data['group_list'] = $group_list['data']; $_data['list_ext'] = $list_ext['data']; $_data['city'] = $_jsoncity; $_body = []; $_body['top'] = $this->load->view('user/top/ud_breadcrumb', NULL, TRUE); $_body['left'] = $this->load->view('user/left/ud_info_create', $_data, TRUE); $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['script'] = $this->load->view('script/script_user_info_create', NULL, TRUE); $_data['mainview'] = $this->load->view('user/user_create', $_body , TRUE); $this->load->view('dashboard',$_data); } public function getCongnoThanhtoan() { $contractid = $this->uri->segment(3); $this->M_data_API->getCongnoThanhtoan($contractid); } public function getHistory() { $contractid = $this->uri->segment(3); $this->M_data_API->getHistory($contractid); } public function getGift() { $contractid = $this->uri->segment(3); $this->M_data_API->getGift($contractid); } public function getBussEmployee() { $contractid = $this->uri->segment(3); $this->M_data_API->getBussEmployee($contractid); } public function getNotes() { $contractid = $this->uri->segment(3); $this->M_data_API->getNotes($contractid); } public function contract(){ $data['contractid'] = $this->uri->segment(3); //a $data = array( 'reportcode'=>'crmContract01a', 'limit'=>25, 'start'=>0, 'queryFilters'=>array( 'contractid'=> $data['contractid'] ) ); $result = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/api/get_list_contract",$data); $_json = json_decode($result,true); $_json2 = json_decode($_json,true); $data_left['trade'] = $_json2["result"]["data"]; $data['ticket_bottom'] = array('data' => [] ); $right['history'] =[]; $_body = []; $_body['top'] = $this->load->view('user/top/ud_breadcrumb', NULL, TRUE); $_body['left'] = $this->load->view('user/left/ud_contract', $data_left, TRUE); //$_body['right'] = $this->load->view('user/right/ud_history', $right, TRUE); $_body['center'] = $this->load->view('user/center/ud_contract', $data, TRUE); $_data = []; $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['script'] = $this->load->view('script/script_user', NULL, TRUE); $_data['mainview'] = $this->load->view('user/user_detail', $_body , TRUE); $this->load->view('dashboard',$_data); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $this->_init['start']), 4); // echo 'Page generated in '.$total_time.' seconds.'; } public function loadTicketContract() { $contractid = $this->uri->segment(3); $seassion_user = $this->session->userdata; $this->M_data_API->loadTicketContract($contractid,$seassion_user); } public function insertPhoneList() { //Phรขn quyแปn if($this->_init['isUpdateUser']==0){ $data['code'] = 0; $data['message'] = 'Bแบกn thuแป™c nhรณm khรดng cรณ chแปฉc nฤƒng sแปญa ngฦฐแปi dรนng'; $data['data'] = null; echo json_encode($data); return; } $data = $this->input->post(); $__data = $data['ext']; $__data1 = parse_str($__data, $get_array); //$__extinfo = json_encode($get_array); $custid = isset($data['custid'])?$data['custid']:null; $phone = isset($data['phone'])?$data['phone']:null; $phonelist = isset($data['telephonelist'])?$data['telephonelist']:null; $pos = strpos($phonelist, $phone); $listphone = $phonelist; if ($pos === false) { if(strlen($listphone) == 0){ $listphone = $phone; }else{ $listphone .= ",".$phone; } } $var = $this->session->userdata; $log_custid = $custid; $log_roleid = $data['roleid']; $log_groupid = $data['groupid']; $postdata = http_build_query([ 'log_custid' => $log_custid, 'log_roleid' => $log_roleid, 'log_groupid' => $log_groupid, 'telephonelist' => $listphone, //'action' => 'deletephone', //'extinfo' => $__extinfo ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/update/'.$custid,false,$context); $dataAuth = []; $this->M_user->updateUser($data['custid'],$postdata,$dataAuth); echo $result; /* $post = $this->input->post(); $__data = $post['ext']; $__data1 = parse_str($__data, $get_array); $__extinfo = json_encode($get_array); $thunhap = json_encode($__data); $postdata = http_build_query([ 'telephonelist' => $post['telephonelist'], 'extinfo' => $__extinfo, 'log_custid' => $post['custid'], 'log_groupid' => $post['groupid'], 'log_roleid'=> $post['roleid'] ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $dataAuth = []; $this->M_user->updateUser($post['custid'],$postdata,$dataAuth); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/update/'.$post['custid'].'',false,$context); echo $result; */ // var_dump($post['custid']); } public function insertEmailList() { if($this->_init['isUpdateUser']==0){ $data['code'] = 0; $data['message'] = 'Bแบกn thuแป™c nhรณm khรดng cรณ chแปฉc nฤƒng sแปญa ngฦฐแปi dรนng'; $data['data'] = null; echo json_encode($data); return; } $data = $this->input->post(); $__data = $data['ext']; $__data1 = parse_str($__data, $get_array); //$__extinfo = json_encode($get_array); $custid = isset($data['custid'])?$data['custid']:null; $email = isset($data['email'])?$data['email']:null; $emaillist = isset($data['emaillist'])?$data['emaillist']:null; $pos = strpos($emaillist, $email); $listemailnew = $emaillist; if ($pos === false) { if(strlen($listemailnew) == 0){ $listemailnew = $email; }else{ $listemailnew .= ",".$email; } } $var = $this->session->userdata; $log_custid = $custid; $log_roleid = $data['roleid']; $log_groupid = $data['groupid']; $postdata = http_build_query([ 'log_custid' => $log_custid, 'log_roleid' => $log_roleid, 'log_groupid' => $log_groupid, 'emaillist' => $listemailnew, //'extinfo' => $__extinfo ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/update/'.$custid,false,$context); $dataAuth = []; $this->M_user->updateUser($data['custid'],$postdata,$dataAuth); echo $result; /* $post = $this->input->post(); $__data = $post['ext']; $__data1 = parse_str($__data, $get_array); $__extinfo = json_encode($get_array); $thunhap = json_encode($__data); $postdata = http_build_query([ 'emaillist' => $post['emaillist'], 'extinfo' => $__extinfo, 'log_custid' => $post['custid'], 'log_groupid' => $post['groupid'], 'log_roleid'=> $post['roleid'] ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/update/'.$post['custid'].'',false,$context); $dataAuth = []; $this->M_user->updateUser($post['custid'],$postdata,$dataAuth); echo $result; */ } public function selectCity() { $id_city = $this->input->post('id_city'); $arrContextOptions=array( "ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false, ), ); $_jsoncity = json_decode(file_get_contents('https://hungminhits.com/api/list_district/'.$id_city.'',false, stream_context_create($arrContextOptions))) ; $city = $_jsoncity; echo json_encode($city); } public function selectDistrict() { $id_district = $this->input->post('id_district'); $arrContextOptions=array( "ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false, ), ); $_jsoncity = json_decode(file_get_contents('https://hungminhits.com/api/list_ward/'.$id_district.'',false, stream_context_create($arrContextOptions))) ; $city = $_jsoncity; echo json_encode($city); } public function getListExt() { $_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/select/user'); echo $_jsonlistext; } public function getSSLPage($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSLVERSION,3); $result = curl_exec($ch); curl_close($ch); return $result; } public function getGroupByRoleId() { $roleid = $this->input->post('roleid'); $arrContextOptions=array( "ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false, ), ); $_jsongroup = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/group/'.$roleid); echo $_jsongroup; } public function updateUser() { $var = $this->session->userdata; $useraction = $var['custid']; $userrole = $var['roleid']; if($this->_init['isUpdateUser']==0 && $userrole!=1){ $data['code'] = 0; $data['message'] = 'Bแบกn thuแป™c nhรณm khรดng cรณ chแปฉc nฤƒng sแปญa ngฦฐแปi dรนng'; $data['data'] = null; echo json_encode($data); return; } $data = $this->input->post(); $__data= $this->input->post('ext'); $__data1 = parse_str($__data, $get_array); $__extinfo = json_encode($get_array); $thunhap = json_encode($__data); $dataAuth = []; $issueddate = null; if(isset($data['issueddate'])){ //$issueddate = str_replace("/", "-",$data['issueddate']); $issueddate = $data['issueddate']; } //$issueddate = isset($data['issueddate'])?$data['issueddate']:null; $postdata = http_build_query([ 'custid' => isset($data['custid'])?$data['custid']:null, 'roleid' => isset($data['roleid'])?$data['roleid']:null, 'groupid' => isset($data['groupid'])?$data['groupid']:null, 'custname' =>isset($data['custname'])?$data['custname']:null, 'gender' =>isset($data['gender'])?$data['gender']:null, 'idcard' => isset($data['idcard'])?$data['idcard']:null, 'fullbirthday' => isset($data['fullbirthday'])?$data['fullbirthday']:null, 'telephone' =>isset($data['telephone'])?$data['telephone']:null, 'email' => isset($data['email'])?$data['email']:null, 'log_custid' =>$useraction, 'log_roleid' =>$var['roleid'], 'log_groupid' =>$var['groupid'], // 'city' => isset($data['city'])?$data['city']:null, // 'district' =>isset($data['district'])?$data['district']:null, // 'ward' =>isset($data['ward'])?$data['ward']:null, // 'address' => isset($data['address'])?$data['address']:null, 'comments' =>isset($data['comments'])?$data['comments']:null, 'queue'=> isset($data['queue'])?$data['queue']:null, 'extinfo'=> $__extinfo, 'issueddate' =>$issueddate, 'issuedplace' =>isset($data['issuedplace'])?$data['issuedplace']:null // 'fulladdress'=> isset($data['fulladdress'])?$data['fulladdress']:null ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $this->M_user->updateUser($data['custid'],$postdata,$dataAuth); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/update/'.$data['custid'],false,$context); $queue = isset($data['queue'])?$data['queue']:null; if($queue !=null) { /* $postdata_queue = http_build_query([ 'extension' =>$data['telephone'], 'queue' => $data['queue'] ]); $opts_queue = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata_queue ) ); $context_queue = stream_context_create($opts_queue); $result_queue_login = file_get_contents('http://test.tavicosoft.com/crm/index.php/queue/loginQueue',false,$context_queue); $postdata_logout = http_build_query([ 'extension' =>$data['telephone'], 'queue' => $data['queueold'] ]); $opts_logout = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata_logout ) ); $context_logout = stream_context_create($opts_logout); $result_queue_logout = file_get_contents('http://test.tavicosoft.com/crm/index.php/queue/logoutQueue',false,$context_logout); */ } echo $result; } public function aj_insert(){ $post = $this->input->post(); //Lฦฐu Custid Khi ngฦฐแปi dแปฅng tแบกo //Tแปฑ tแบกo Custid khi ngฦฐแปi dรนng ฤ‘แปƒ trแป‘ng if(isset($post['custid'])){ $custid = $post['custid']; }else{ $custid = $this->M_api->gen_custid(); } $var = $this->session->userdata; $useraction = $var['custid']; $userrole = $var['roleid']; if($this->_init['isInserUser']==0&& $userrole!=1){ $data['code'] = 0; $data['message'] = 'Bแบกn thuแป™c nhรณm khรดng cรณ chแปฉc nฤƒng thรชm ngฦฐแปi dรนng'; $data['data'] = null; echo json_encode($data); return; } $password = isset($post['password'])?$post['password']:''; $password = md5($password); $res_data = array( 'custid' =>$custid, 'roleid' =>isset($post['roleid'])?$post['roleid']:'', 'groupid' =>isset($post['groupid'])?$post['groupid']:'', 'custname' =>isset($post['custname'])?$post['custname']:'', 'gender' =>isset($post['gender'])?$post['gender']:'', 'fullbirthday' =>isset($post['fullbirthday'])?$post['fullbirthday']:'', 'comments' =>isset($post['comments'])?$post['comments']:'', 'extinfo' =>isset($post['ext'])?json_encode($post['ext']):'', 'password' =>$<PASSWORD>, 'queue' =>isset($post['queue'])?$post['queue']:'' ); if(isset($post['email'])){ $res_data['email']=$post['email']; } if(isset($post['telephone'])){ $res_data['telephone']=$post['telephone']; } if(isset($post['idcard'])){ $res_data['idcard']=$post['idcard']; } if(isset($post['issueddate'])){ $res_data['issueddate']=$post['issueddate']; } if(isset($post['issuedplace'])){ $res_data['issuedplace']=$post['issuedplace']; } // var_dump($res_data); foreach ($res_data as $key => $value) { if ($value=='') { unset($res_data[$key]); } } $postdata = http_build_query($res_data); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/insert',false,$context); echo $result; $res_re = json_decode($result,true); $address = array( 'custid' => $custid, 'country' =>isset($post['country'])?$post['country']:'', 'city' =>isset($post['city'])?$post['city']:'', 'district' =>isset($post['district'])?$post['district']:'', 'ward' =>isset($post['ward'])?$post['ward']:'', 'street' =>isset($post['street'])?$post['street']:'', 'address' =>isset($post['address'])?$post['address']:'', 'label' =>"ฤแป‹a chแป‰ thฦฐแปng trรบ" ); $address['fulladdress'] = $address['address'].', '.$address['street'].', '.$address['ward'].', '.$address['district'].', '.$address['city'].', '.$address['country']; if ($res_re['code']==1) { $addLog = array(); $r_addr = $this->api_save_address($address,$addLog); } } public function aj_validate(){ $var = $this->session->userdata; $useraction = $var['custid']; $userrole = $var['roleid']; if($this->_init['isInserUser']==0&& $userrole!=1){ $data['code'] = 0; $data['message'] = 'Bแบกn thuแป™c nhรณm khรดng cรณ chแปฉc nฤƒng thรชm ngฦฐแปi dรนng'; $data['data'] = null; echo json_encode($data); return; } $phone = ""; $email = ""; $idcard = ""; $post = $this->input->post(); if(isset($post['email'])){ $email=$post['email']; } if(isset($post['telephone'])){ $phone=$post['telephone']; } if(isset($post['idcard'])){ $idcard=$post['idcard']; } $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/validate?phone='.$phone.'&email='.$email.'&idcard='.$idcard); echo $result; } public function aj_insert_bonus_address() { //Phรขn quyแปn if($this->_init['isUpdateUser']==0){ $data['code'] = 0; $data['message'] = 'Bแบกn thuแป™c nhรณm khรดng cรณ chแปฉc nฤƒng sแปญa ngฦฐแปi dรนng'; $data['data'] = null; echo json_encode($data); return; } $post = $this->input->post(); $address = array( 'custid' => isset($post['custid'])?$post['custid']:'', 'country' =>isset($post['country'])?$post['country']:'', 'city' =>isset($post['city'])?$post['city']:'', 'district' =>isset($post['district'])?$post['district']:'', 'ward' =>isset($post['ward'])?$post['ward']:'', 'street' =>isset($post['street'])?$post['street']:'', 'address' =>isset($post['address'])?$post['address']:'', 'label' =>isset($post['label'])?$post['label']:'' ); $address['fulladdress'] = $address['address'].', '.$address['street'].', '.$address['ward'].', '.$address['district'].', '.$address['city'].', '.$address['country']; $arrayLog = array( 'custid' => $post['custid'], 'roleid' =>isset($post['roleid'])?$post['roleid']:'', 'groupid' =>isset($post['groupid'])?$post['groupid']:'', 'action' => "Thรชm ฤ‘แป‹a chแป‰", 'dataaction' => json_encode($address) ); $r_addr = $this->api_save_address($address,$arrayLog); echo $r_addr; } public function aj_update_bonus_address() { //Phรขn quyแปn if($this->_init['isUpdateUser']==0){ $data['code'] = 0; $data['message'] = 'Bแบกn thuแป™c nhรณm khรดng cรณ chแปฉc nฤƒng sแปญa ngฦฐแปi dรนng'; $data['data'] = null; echo json_encode($data); return; } $post = $this->input->post(); $address = array( 'custid' => isset($post['custid'])?$post['custid']:'', 'country' =>isset($post['country'])?$post['country']:'', 'city' =>isset($post['city'])?$post['city']:'', 'district' =>isset($post['district'])?$post['district']:'', 'ward' =>isset($post['ward'])?$post['ward']:'', 'street' =>isset($post['street'])?$post['street']:'', 'address' =>isset($post['address'])?$post['address']:'', 'label' =>isset($post['label'])?$post['label']:'' ); $address['fulladdress'] = $address['address'].', '.$address['street'].', '.$address['ward'].', '.$address['district'].', '.$address['city'].', '.$address['country']; $arrayLog = array( 'custid' => $post['custid'], 'roleid' =>isset($post['roleid'])?$post['roleid']:'', 'groupid' =>isset($post['groupid'])?$post['groupid']:'', 'action' => "Sแปญa ฤ‘แป‹a chแป‰", 'id' => $post['addressid'], 'dataaction' => json_encode($address) ); $r_addr = $this->api_update_address($address,$post['addressid'],$arrayLog); echo $r_addr; } public function aj_delete_address() { //Phรขn quyแปn if($this->_init['isUpdateUser']==0){ $data['code'] = 0; $data['message'] = 'Bแบกn thuแป™c nhรณm khรดng cรณ chแปฉc nฤƒng sแปญa ngฦฐแปi dรนng'; $data['data'] = null; echo json_encode($data); return; } $var = $this->session->userdata; $log_custid = $var['custid']; $log_roleid = $var['roleid']; $log_groupid = $var['groupid']; $post = $this->input->post('addressid'); $data = array( 'custid' => $log_custid, 'roleid' =>$log_roleid, 'groupid' =>$log_groupid ); $data['action'] = "Xรณa ฤ‘แป‹a chแป‰"; $data['dataaction'] = ""; $data['id'] = $post; $postdata = http_build_query($data); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/insert_LogAddress',false,$context); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/delete/'.$post,false,$context); echo $result; } public function api_delete_address($data,$addressid){ $postdata = http_build_query($data); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/delete/'.$addressid,false,$context); return $result; } public function api_save_address($data,$dataLog){ if(count($dataLog)>0) { $postdata1 = http_build_query($dataLog); $opts1 = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata1 ) ); $context1 = stream_context_create($opts1); $result1 = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/insert_LogAddress',false,$context1); } $postdata = http_build_query($data); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/insert',false,$context); return $result; } public function api_update_address($data,$addressid,$dataLog){ //Phรขn quyแปn if($this->_init['isUpdateUser']==0){ $data['code'] = 0; $data['message'] = 'Bแบกn thuแป™c nhรณm khรดng cรณ chแปฉc nฤƒng sแปญa ngฦฐแปi dรนng'; $data['data'] = null; echo json_encode($data); return; } $postdata1 = http_build_query($dataLog); $opts1 = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata1 ) ); $context1 = stream_context_create($opts1); $result1 = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/insert_LogAddress',false,$context1); $postdata = http_build_query($data); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/update/'.$addressid,false,$context); return $result1; } // public function updateUserEmailList() { //Phรขn quyแปn if($this->_init['isUpdateUser']==0){ $data['code'] = 0; $data['message'] = 'Bแบกn thuแป™c nhรณm khรดng cรณ chแปฉc nฤƒng sแปญa ngฦฐแปi dรนng'; $data['data'] = null; echo json_encode($data); return; } $data = $this->input->post(); $__data = $data['ext']; $__data1 = parse_str($__data, $get_array); //$__extinfo = json_encode($get_array); $custid = isset($data['custid'])?$data['custid']:null; $email = isset($data['email'])?$data['email']:null; $emaillist = isset($data['emaillist'])?$data['emaillist']:null; $array_email = explode(',', $emaillist); $listemailnew = ''; $sizearray = count($array_email); for($i =0;$i< $sizearray;$i++){ if($array_email[$i]==$email){ unset($array_email[$i]); }else{ if(strlen($listemailnew) == 0){ $listemailnew = $array_email[$i]; }else{ $listemailnew.= ','.$array_email[$i]; } } } $var = $this->session->userdata; $log_custid = $custid; $log_roleid = $data['roleid']; $log_groupid = $data['groupid']; $postdata = http_build_query([ 'log_custid' => $log_custid, 'log_roleid' => $log_roleid, 'log_groupid' => $log_groupid, 'emaillist' => $listemailnew, 'action' => 'deleteemail', //'extinfo' => $__extinfo ]); //var_dump(expression) $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/update/'.$custid,false,$context); $dataAuth = []; $this->M_user->updateUser($data['custid'],$postdata,$dataAuth); echo $result; } public function updateUserPhoneList() { //Phรขn quyแปn if($this->_init['isUpdateUser']==0){ $data['code'] = 0; $data['message'] = 'Bแบกn thuแป™c nhรณm khรดng cรณ chแปฉc nฤƒng sแปญa ngฦฐแปi dรนng'; $data['data'] = null; echo json_encode($data); return; } $data = $this->input->post(); $__data = $data['ext']; $__data1 = parse_str($__data, $get_array); $__extinfo = json_encode($get_array); $custid = isset($data['custid'])?$data['custid']:null; $phone = isset($data['phone'])?$data['phone']:null; $phonelist = isset($data['phonelist'])?$data['phonelist']:null; $array_phone = explode(',', $phonelist); $listphone = ''; $sizearray = count($array_phone); for($i =0;$i< $sizearray;$i++){ if($array_phone[$i]==$phone){ unset($array_phone[$i]); }else{ if(strlen($listphone) == 0){ $listphone = $array_phone[$i]; }else{ $listphone.= ','.$array_phone[$i]; } } } $var = $this->session->userdata; $log_custid = $custid; $log_roleid = $data['roleid']; $log_groupid = $data['groupid']; $postdata = http_build_query([ 'log_custid' => $log_custid, 'log_roleid' => $log_roleid, 'log_groupid' => $log_groupid, 'telephonelist' => $listphone, 'action' => 'deletephone', 'extinfo' => $__extinfo ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/update/'.$custid,false,$context); $dataAuth = []; $this->M_user->updateUser($data['custid'],$postdata,$dataAuth); echo $result; } public function updateAddress() { //Phรขn quyแปn if($this->_init['isUpdateUser']==0){ $data['code'] = 0; $data['message'] = 'Bแบกn thuแป™c nhรณm khรดng cรณ chแปฉc nฤƒng sแปญa ngฦฐแปi dรนng'; $data['data'] = null; echo json_encode($data); return; } $data = $this->input->post(); $addressid = $data['addressid']; unset($data['addressid']); $var = $this->session->userdata; $log_custid = $var['custid']; $log_roleid = $var['roleid']; $log_groupid = $var['groupid']; //$data['log_custid'] => $log_custid; $postdata = http_build_query($data); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/update/'.$addressid,false,$context); echo $result; } public function searchUser() { $keyword1 = $this->input->post('keyword'); $keyword = urlencode($keyword1); $_jsonSearch = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/search?action=search_customer&roleid=1&search='.$keyword); echo $_jsonSearch; } public function getUserByRecodeId() { $var = $this->session->userdata; $roleid = $var['roleid']; $post = $this->input->post("id"); $_jsonUser = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyid?id='.$post); echo $_jsonUser; } public function viewUserHistory() { $_cusid = $_GET['cusid']; $role_list = array(); $role_list['1']="<NAME>"; $role_list['2']="Chuyรชn Viรชn"; $role_list['3']="Khรกch hร ng"; $group_list = $this->_init['_jsongroup']; $right['role_list'] = $role_list; $right['group_list'] = $group_list['data']; $list_ext = $this->_init['_jsonlistext']; $right['list_ext'] = $list_ext['data']; $_jsonhistory = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/user_history/'.$_cusid.''); /* echo 'http://test.tavicosoft.com/crm/index.php/api/user_history/'.$_cusid.''; exit; */ $_jsonhistory_data= json_decode($_jsonhistory,true); $right['history'] = $_jsonhistory_data['data']; $_data['mainview'] = $this->load->view('user/right/ud_history', $right, TRUE); $this->load->view('dashboard',$_data); } } ?><file_sep><form method="POST" id="dataInsertGroup" action="<?php echo base_url().'groupuser/groupuserinsert' ?>"> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-10"> <input type="hidden" value="" id="groupid"/> <div class=""> <label class="control-label user-label col-md-4 no-padding">Tรชn nhรณm</label> <label class="control-label col-md-7 no-padding-right"> <input class="col-md-12 no-padding font-size-12" value="" placeholder="<NAME>" name="groupname" id="custname" required="" minlength="4"> <input type="hidden" class="col-md-12 no-padding font-size-12" value="-1" placeholder="" name="roleid" id="roleid" required="" minlength="4"> </label> </div> <div class=""> <label class="control-label user-label col-md-4 no-padding">Trแบกng thรกi</label> <select class="control-label col-md-7 no-border no-padding margin-left-10" name="status" id="status"> <option value="0">Khรดng hoแบกt ฤ‘แป™ng</option> <option value="1">ฤang hoแบกt ฤ‘แป™ng</option> </select> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-10"> <div class=""> <label class="control-label user-label col-md-4 no-padding"></label> <label class="control-label col-md-7 no-padding-right"> <label class="control-label user-label2 col-md-3 no-padding">Xem</label> <label class="control-label user-label2 col-md-3 no-padding">Thรชm</label> <label class="control-label user-label2 col-md-3 no-padding">Sแปญa</label> </label> </div> <div class=""> <label class="control-label user-label col-md-4 no-padding">Phiแบฟu</label> <!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="ticketrule" id="ticketrule"> <option value="0" >Khรดng</option> <option value="1" >Xem/Sแปญa</option> </select> --> <label class="control-label col-md-7 no-padding-right"> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="viewticket" id="viewticket" value="1"></label> <input id='viewtickethidden' type='hidden' value='0' name='viewticket'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="addticket" id="addticket" value="1"></label> <input id='addtickethidden' type='hidden' value='0' name='addticket'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="editticket" id="editticket" value="1"></label> <input id='edittickethidden' type='hidden' value='0' name='editticket'> </label> </div> <div class=""> <label class="control-label user-label col-md-4 no-padding">Ngฦฐแปi dรนng</label> <!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="userrule" id="userrule"> <option value="0">Khรดng</option> <option value="1">Xem/Sแปญa</option> </select> --> <label class="control-label col-md-7 no-padding-right"> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="viewuser" id="viewuser" value="1"></label> <input id='viewuserhidden' type='hidden' value='0' name='viewuser'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="adduser" id="adduser" value="1"></label> <input id='adduserhidden' type='hidden' value='0' name='adduser'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="edituser" id="edituser" value="1"></label> <input id='edituserhidden' type='hidden' value='0' name='edituser'> </label> </div> <div class=""> <label class="control-label user-label col-md-4 no-padding">Cรดng viแป‡c</label> <!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="taskrule" id="taskrule"> <option value="0">Khรดng</option> <option value="1">Xem/Sแปญa</option> </select> --> <label class="control-label col-md-7 no-padding-right"> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="viewtask" id="viewtask" value="1"></label> <input id='viewtaskhidden' type='hidden' value='0' name='viewtask'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="addtask" id="addtask" value="1"></label> <input id='addtaskhidden' type='hidden' value='0' name='addtask'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="edittask" id="edittask" value="1"></label> <input id='edittaskhidden' type='hidden' value='0' name='edittask'> </label> </div> <div class=""> <label class="control-label user-label col-md-4 no-padding">Thฦฐ viแป‡n</label> <!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="knowledgerule" id="knowledgerule"> <option value="0">Khรดng</option> <option value="1">Xem/Sแปญa</option> </select> --> <label class="control-label col-md-7 no-padding-right"> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="viewknowledge" id="viewknowledge" checked="" disabled="" value="1"></label> <input id='viewknowledgehidden' type='hidden' value='1' name='viewknowledge'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="addknowledge" id="addknowledge" value="1"></label> <input id='addknowledgehidden' type='hidden' value='0' name='addknowledge'> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="editknowledge" id="editknowledge" value="1"></label> <input id='editknowledgehidden' type='hidden' value='0' name='editknowledge'> </label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-10"> <label class="control-label col-md-4 no-padding" style="font-size: 12px;font-weight: 500;color: rgb(118, 121, 116);"><i class="far fa-window-maximize"></i> View </label> <div class=""> <label class="control-label user-label col-md-4 no-padding">Xem tแบฅt cแบฃ phiแบฟu</label> <label class="control-label col-md-7 no-padding-right"> <label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="viewpermission" id="viewpermission" value="1"></label> <input id='viewpermissionhidden' type='hidden' value='0' name='viewpermission'> </label> </div> </div> </div> <div class="fc-corner-right"> <div class="fc-button-group" style="float:right"> <button type="button" class="btn btn-primary float-right margin-bot-5 btn-creategroupuser"><i class="fa fa-share"></i>Lฦฐu thรดng tin</button> </div> </div> </form><file_sep><div class="tile height-1024"> <div class="content-title"> <div class="div"> <h5>Trฦฐแปng dแปฏ liแป‡u Phiแบฟu hแป— trแปฃ</h5> </div> </div> <p class="margin-top-10 no-margin-bot">Trฦฐแปng dแปฏ liแป‡u ngฦฐแปi dรนng cho phรฉp ฤ‘แป‹nh nghฤฉa cรกc trฦฐแปng dแปฏ liแป‡u(fields) bแป• sung cรกc thรดng tin Phiแบฟu hแป— trแปฃ, cรกc trฦฐแปng dแปฏ liแป‡u nร y chแป‰ cรณ thแปƒ dรนng cho mแปฅc ฤ‘รญch phรขn tรญch PIVOT hoแบทc Bรกo cรกo quแบฃn trแป‹ ฤ‘ฦฐแปฃc thiแบฟt kแบฟ dร nh riรชng cho, khรดng รกp dแปฅng cho bรกo cรกo, bแบฃng ฤ‘iแปu khiแปƒn (dashboard) vร  ฤ‘แป“ thแป‹ mแบทc ฤ‘แป‹nh cแปงa hแป‡ thแป‘ng.</p> <div class="row" style="margin-top: 50px;"> <div class="col-md-5"> <span><b>Trฦฐแปng dแปฏ liแป‡u hiแป‡n tแบกi (<?php echo count($list_ext) ?>)</b></span> </div> <div class="col-md-7"> <div style="float: right;"> <button type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right" data-toggle="modal" data-target="#myModal1">Thรชm</button> </div> </div> </div> <div class="bs-component margin-top-10"> <?php if(count($list_ext) >0) { foreach ($list_ext as $value) { ?> <a style="cursor: pointer;" class="user-name" onclick="addTab('<?php echo base_url()?>groupuser/fielddetail/<?php echo $value['fieldcode'] ?>/<?php echo $value['fieldtype'] ?>/<?php echo $value['datasource'] ?>','<?php echo $value['fieldname'] ?>')"> <div class="component-fields"> <?php if($value['fieldtype'] == 'T') { $icon = 'fas fa-font'; } else{ $icon = 'far fa-caret-square-down'; } ?> <i class="<?php echo $icon ?>"></i> <span class="title_tab" style="padding-left: 6px"><?php echo $value['fieldname'] ?></span> </div> </a> <?php }} ?> </div> </div> <div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document" style="margin-top: 8%"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Thรชm trฦฐแปng dแปฏ liแป‡u Phiแบฟu hแป— trแปฃ</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class="form-group"> <label for="exampleInputEmail1">Kiแปƒu dแปฏ liแป‡u</label> <select class="form-control" id="fieldtype" name="fieldtype" onchange="selectType(this)"> <option selected="" class="group_item" value="T">Text</option> <option class="group_item" value="D">Drop down list</option> </select> </div> <div class="form-group"> <label for="exampleInputEmail1">Mรฃ trฦฐแปng</label> <input type="text" class="form-control" name="fieldcode" id="fieldcode" placeholder="-Mรฃ trฦฐแปng"> </div> <div class="form-group extendbottom"> <label for="exampleInputEmail1">Tรชn trฦฐแปng</label> <input type="text" class="form-control" name="fieldname" id="fieldname" placeholder="-Tรชn trฦฐแปng"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">ฤรณng</button> <button type="button" class="btn btn-primary" onclick="insertExtUser('ticket')">Thรชm</button> </div> </div> </div> </div><file_sep><div class="div-info-customer"> <?php if(isset($customer)){ ?> <div class="tile p-0 padding-5 margin-bot-5"> <div class="content-title user-history"> <div class="width-100per"> <p class="flex"> <img onclick="addTab('<?php echo base_url()."user/detail/?cusid=".$customer[0]['custid']."&idcard=".$customer[0]['idcard']."&roleid=".$customer[0]['roleid']?>','<?php echo $customer[0]['custname'] ?>')" class="user-avatar" src="<?php echo $customer[0]['avatar']; ?>" alt="User Image"><?php echo $customer[0]['custname'];?> - <?php echo $customer[0]['groupname'];?> </p> <p class="header-desc field-click-able"> Ngร y tแบกo: <?php echo date("d/m/Y", strtotime($customer[0]['createddate']));?> </p> <p class="margin-left-50"> Sแป‘ ฤ‘iแป‡n thoแบกi: <a href="#" onclick="parent.iframe_click('<?php echo($customer[0]['telephone'])?>','<?php echo($this->uri->segment(3))?>')" id="user_phone_number"> <?php echo($customer[0]['telephone'])?> </a> </p> </div> </div> </div> <?php } ?> </div> <div class="div-recent-ticket <?php echo(isset($view)?'hide':'')?>"> <div class="tile p-0 padding-5 margin-bot-5"> <p class="no-margin">Phiแบฟu gแบงn nhแบฅt</p> <div class="table-responsive"> <table class="table" id="table-22"> <thead class="hide"> <tr> <th></th> <th></th> </tr> </thead> </table> </div> </div> </div> <div class="div-contract <?php echo(isset($view)?'hide':'')?>"> <div class="tile p-0 padding-5 margin-bot-5"> <p class="no-margin">Danh sรกch giao dแป‹ch</p> <div class="table-responsive"> <table class="table" id="table-23"> <thead class="hide"> <tr> <th></th> <th></th> <th></th> </tr> </thead> </table> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5 toggle-up"> <p>Thฦฐ viแป‡n kiแบฟn thแปฉc <i class="fa fa-angle-double-up knl-caret"></i> </p> <div class="flex margin-top-12 padding-right-5"> <button class="btn btn_blank" id="knl-btn-back" type="button"> <i class="fa fa-arrow-left"></i> </button> <div class="knl-input-group flex"> <input name="knl_text" class="width-100per" type="text"> <i class="fa fa-search search-knowledge"></i> </div> </div> <div class="knl-board hide margin-top-5"> <div id="knl_list" class="padding-5"> </div> <div class="knl-content hide padding-5"> </div> </div> </div><file_sep><script type="text/javascript"> $(document).ready(function(){ $('#login_form').on('submit',function(){ var cur = $(this); var formData = new FormData($(this)[0]); for (var [key, value] of formData.entries()) { // console.log(key, value); } cur.find('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spinner fa-spin'); $.ajax({ type: "POST", url: "<?php echo base_url().'login/post_login'?>", data: formData, dataType:'json', contentType: false, cache: false, processData:false, beforeSend: function() { }, success: function(data) { cur.find('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-sign-in'); if(data.message == "Success"){ window.location.href = "<?php echo base_url().'login/login'?>"; }else{ swal("Lแป—i !", "Sai tรชn ฤ‘ฤƒng nhแบญp hoแบทc mแบญt khแบฉu.", "error"); } }, error: function(xhr, status, error) { cur.find('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-sign-in'); // swal("Lแป—i !", "Vui lรฒng kiแปƒm tra lแบกi mแบกng.", "error"); console.log(error); } }); return false; }); }); </script><file_sep><div class="tile height-1024"> <div class="content-title"> <div class="div"> <h5><?php echo $gdetail['groupname']?></h5> </div> </div> <div class="bs-component"> <div class="table-responsive" style="height: 1024px"> <table class="table" id="table"> <tbody> <?php if(count($useringroup)>0){ ?> <?php foreach ($useringroup as $user) { ?> <tr> <td width="5%"> <img class="user-avatar" src="<?php echo $user['avatar'];?>" alt="User Image"> </td> <td width="50% "> <a class="user-name" style="cursor: pointer;" onclick="addTab('<?php echo base_url().'user/detail/?cusid='.$user['custid'].'&idcard='.$user['idcard'].'&roleid='.$user['roleid'] ?>','<?php echo $user['custname'];?>')"><?php echo $user['custname'];?></a> <p class=""><!--3--></p> </td> <td width="13%"><?php echo $user['telephone'];?></td> <td width="13%"><?php echo $user['email'];?></td> </tr> <?php }}else{ echo "Chฦฐa cรณ ngฦฐแปi dรนng nร o trong nhรณm"; } ?> </tbody> </table> </div> </div> </div> <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Groupuser extends CI_Controller { public function __construct() { parent::__construct(); //Do your magic here $this->load->library(array('session')); $this->load->helper(array('url')); $this->load->model('M_api'); } public function index() { $_body = []; $_data = []; $group_data = $this->M_api->getlistgroup(); $data['listgroup'] = json_decode($group_data,true)['data']; $__jsonCount = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/countgroupid'); $_jsonGroupDetail = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/countgroupid'); $data['countPeople'] = json_decode($__jsonCount,true)['data']; $_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE); $_data['script2'] = $this->load->view('script/script_group_edit', NULL, TRUE); $_data['mainview'] = $this->load->view('groupuser/center/gu_info', $data , TRUE); $this->load->view('dashboard',$_data); } public function fielduser() { $_data = []; $_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/selectall/user'); $list_ext = json_decode($_jsonlistext,true); $customer['list_ext'] = $list_ext['data']; $_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE); $_data['mainview'] = $this->load->view('groupuser/center/gu_fielduser', $customer , TRUE); $this->load->view('dashboard',$_data); } public function fielddetail() { $list_extend['list_ext'] = []; $list_extend['detail'] =[]; $fieldtype = $this->uri->segment(4); if($fieldtype == 'D') { $datasource = $this->uri->segment(5); $_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/'.$datasource); $list_ext = json_decode($_jsonlistext,true); $list_extend['list_ext'] = $list_ext['data']; } $fieldcode = $this->uri->segment(3); $_jsondetail = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/getextdatabycode/'.$fieldcode); $list_field = json_decode($_jsondetail,true); $list_detail['detail'] = $list_field['data']; $list_extend['detail'] = $list_field['data']; $_body = []; $_body['left'] = $this->load->view('groupuser/left/gu_left_field',$list_detail,TRUE); $_body['center'] = $this->load->view('groupuser/center/gu_center_field', $list_extend, TRUE); $_data = []; $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE); $_data['mainview'] = $this->load->view('groupuser/gu_main', $_body , TRUE); $this->load->view('dashboard',$_data); } public function fieldticket() { $_data = []; $_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/selectall/ticket'); $list_ext = json_decode($_jsonlistext,true); $customer['list_ext'] = $list_ext['data']; $_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE); $_data['mainview'] = $this->load->view('groupuser/center/gu_fieldticket', $customer , TRUE); $this->load->view('dashboard',$_data); } public function groupuserdetail() { $groupid=$this->input->get('groupid'); $_body = []; $group = []; $group_detail = $this->M_api->getlistgroup($groupid); $group['gdetail'] = json_decode($group_detail,true)['data'][0]; $_jsongrdetail = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/select_groupdetail'); $group['groupdetail'] = json_decode($_jsongrdetail,true); $customerbygroup = $this->M_api->getlistcustomerbygroupid($group['gdetail']['groupid']); $group['useringroup'] = json_decode($customerbygroup,true)['data']; $_body['left'] = $this->load->view('groupuser/left/gu_left_groupuser',$group,TRUE); $_body['center'] = $this->load->view('groupuser/center/gu_center_groupuser', $group, TRUE); $_data = []; $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['script'] = $this->load->view('script/script_group_edit', NULL, TRUE); $_data['script2'] = $this->load->view('script/script_dashboard', NULL, TRUE); $_data['mainview'] = $this->load->view('groupuser/gu_main', $_body , TRUE); $this->load->view('dashboard',$_data); } public function updategroup(){ $data = $this->input->post(); $groupid = $data['groupid']; $ticketrule = $this->input->post('ticketrule'); $ticketrule = $data['viewticket'].$data['addticket'].$data['editticket']; $userrule = $data['viewuser'].$data['adduser'].$data['edituser']; $taskrule = $data['viewtask'].$data['addtask'].$data['edittask']; $knowledgerule = '1'.$data['addknowledge'].$data['editknowledge']; $postdata = http_build_query([ 'ticketrule'=>$ticketrule, 'userrule'=>$userrule, 'taskrule'=>$taskrule, 'knowledgerule'=>$knowledgerule, 'status'=>$data['status'], 'groupname'=>$data['groupname'] ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/update/'.$groupid.'',false,$context); $viewpermission = $data['viewpermission']; $viewpermissionold = $data['oldpermission']; if($viewpermission != $viewpermissionold) { if($viewpermission == 1) { $postdata1 = http_build_query([ 'groupid' => $groupid, 'viewid' => '1' ]); $opts1 = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata1 ) ); $context1 = stream_context_create($opts1); $result1 = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/insert_groupdetail',false,$context1); } else{ $result2 = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/delete_groupdetail/'.$groupid,false); } } echo $result; // var_dump($data); } public function groupuserinsert() { $data =$this->input->post(); $ticketrule = $data['viewticket'].$data['addticket'].$data['editticket']; $userrule = $data['viewuser'].$data['adduser'].$data['edituser']; $taskrule = $data['viewtask'].$data['addtask'].$data['edittask']; $knowledgerule = '1'.$data['addknowledge'].$data['editknowledge']; $postdata = http_build_query(['groupname' => $data['groupname'], 'tvcdb' => 'AGT', 'roleid' =>$data['roleid'], 'status' =>$data['status'], 'userrule' =>$userrule, 'ticketrule'=>$ticketrule, 'taskrule'=>$taskrule, 'knowledgerule'=>$knowledgerule]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/GroupTest/insert',false,$context); $viewpermission = $data['viewpermission']; if($viewpermission == 1) { $arrayResult = json_decode($result,true); // echo $arrayResult['data']; $postdata1 = http_build_query([ 'groupid' => $arrayResult['data'], 'viewid' => '1' ]); $opts1 = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata1 ) ); $context1 = stream_context_create($opts1); $result1 = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/insert_groupdetail',false,$context1); } echo $result; } public function viewInsertGroup() { $_body = []; $group = []; $_body['left'] = $this->load->view('groupuser/left/gu_left_creategroup',null,TRUE); $_data = []; $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['script'] = $this->load->view('script/script_create_groupuser', NULL, TRUE); $_data['mainview'] = $this->load->view('groupuser/gu_insert', $_body , TRUE); $this->load->view('dashboard',$_data); } public function postData($array,$url) { $postdata = http_build_query([ $array ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents($url,false,$context) ; return $result; } public function insertFieldUser() { $data= $this->input->post(); $postdata = http_build_query([ 'tvcdb' => 'AGT', 'status'=>'1', 'fieldtype' => isset($data['fieldtype'])?$data['fieldtype']:'', 'formid' => isset($data['formid'])?$data['formid']:'', 'fieldcode' =>isset($data['fieldcode'])?$data['fieldcode']:'', 'datasource' =>isset($data['datasource'])?$data['datasource']:'', 'fieldname' =>isset($data['fieldname'])?$data['fieldname']:'']); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/insert',false,$context); $__data1 = parse_str($data['dataExt'], $get_array); if($data['dataExt'] !=null) { for ($i=0; $i <count($get_array['code']) ; $i++) { $postdata_codic = http_build_query([ 'code' => $get_array['code'][$i], 'name' => $get_array['name'][$i], 'status' =>'W', 'category' =>$data['datasource'], 'tvcdb' =>'AGT']); $opts_codic = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata_codic ) ); $context_codic = stream_context_create($opts_codic); $result_codic = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/insert',false,$context_codic); } } echo $result; } public function insertSelectBox() { $data = $this->input->post(); $postdata = http_build_query([ 'code' => $data['code'], 'name' => $data['name'], 'status' => isset($data['status'])?$data['status']:'W', 'category' =>$data['category'], 'comments' =>isset($data['comments'])?$data['comments']:'', 'ref1' => isset($data['ref1'])?$data['ref1']:'', 'ref2' => isset($data['ref2'])?$data['ref2']:'', 'tvcdb' =>'AGT']); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/insert',false,$context); echo $result; } public function updateFields() { $data = $this->input->post(); $postdata = http_build_query([ 'fieldcode' => $data['fieldcode'], 'fieldname' => $data['fieldname'], 'status' =>$data['status']]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/update/'.$data['fieldcode'],false,$context); echo $result; } public function updateCodictionary() { $data = $this->input->post(); if($data['action'] == 'delete') { $status = 'C'; } else { $status = 'W'; } $postdata = http_build_query([ 'code' => $data['code'], 'category' => $data['category'], 'status' =>$status, 'name'=> isset($data['name'])?$data['name']:null ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/update/'.$data['category'].'/'.$data['code'],false,$context); echo $result; } public function updateDatasource() { $data = $this->input->post(); $postdata = http_build_query([ 'code' => $data['code'], 'category' => $data['category'], 'status' =>$data['status'], 'comments' => $data['comments'], 'name'=> isset($data['name'])?$data['name']:'', 'ref1' =>isset($data['ref1'])?$data['ref1']:'', 'ref2' =>isset($data['ref2'])?$data['ref2']:'' ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/update/'.$data['category'].'/'.$data['code'],false,$context); echo $result; } } /* End of file Groupuser.php */ /* Location: ./application/controllers/Groupuser.php */ ?><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Login extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url')); //$this->load->model(array('M_data')); } public function index() { if($this->session->userdata("custid"))//If already logged in { redirect(base_url('dashboard')); } $_data = []; $_data['script'] = $this->load->view('script/script_login', NULL, TRUE); $this->load->view('login/login',$_data); } public function login(){ if($this->session->userdata("custid"))//If already logged in { redirect(base_url('dashboard')); } $data['error'] = 0; redirect(base_url('login')); } public function post_login() { $username = $this->input->post('username'); $password = $this->input->post('password'); $postdata = http_build_query([ 'username' => $username, 'password' => $<PASSWORD> ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Api/login',false,$context); $response = json_decode($result,true); if (isset($response['data'])) { $this->session->set_userdata('custid',$response['data'][0]['custid']); $this->session->set_userdata('groupid',$response['data'][0]['groupid']); $this->session->set_userdata('telephone',$response['data'][0]['telephone']); $this->session->set_userdata('custname',$response['data'][0]['custname']); $this->session->set_userdata('avatar',$response['data'][0]['avatar']); $this->session->set_userdata('roleid',$response['data'][0]['roleid']); $this->session->set_userdata('idcard',$response['data'][0]['idcard']); } echo $result; } public function logout() { $this->session->sess_destroy(); redirect(base_url('login')); } public function connect(){ // phpinfo(); $otherdb = $this->load->database('sqlsvr12', TRUE); $query = $otherdb->select('*')->get('crcustomer')->result_array(); var_dump($query); } }<file_sep><?php error_reporting(0); ini_set('display_errors', 0); defined('BASEPATH') OR exit('No direct script access allowed'); class M_data_API extends CI_Model { public function __construct() { parent::__construct(); $this->dayCompare = strtotime('2000-01-01T00:00:00'); } public function loadTicketContract($contractid,$user_seassion) { $custid = $user_seassion['custid']; $roleid = $user_seassion['roleid']; $groupid = $user_seassion['groupid']; $json_ticket_bottom = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/getticketbytransref/'.$contractid.'?custid='.$custid.'&groupid='.$groupid); $data['trade_cntt'] = json_decode($json_ticket_bottom,true)['data']; $text = ''; for ($i=0; $i < count($data['trade_cntt']); $i++) { $timeCreate = preg_replace('/\s/', 'T',$data['trade_cntt'][$i]['createat']); $timeUpdate = preg_replace('/\s/', 'T',$data['trade_cntt'][$i]['lastupdate']); if(strtotime($timeCreate) > $this->dayCompare) { $createat = date("d/m/Y",strtotime($timeCreate)); }else{$createat='';} if(strtotime($timeUpdate) > $this->dayCompare) { $lastupdate = date("d/m/Y",strtotime($timeUpdate)); }else{$lastupdate='';} $href = ''.base_url().'ticket/detail/'.$data['trade_cntt'][$i]['ticketid'].'/'.$data['trade_cntt'][$i]['custid'].''; $onclick = "addTab('".$href."','".$data['trade_cntt'][$i]['ticketid']."')"; if($i == (count($data['trade_cntt'])-1)) { $text .= '[ "<a onclick='.$onclick.' href=\'#\'><span class=\'id-label span-danger\'>O</span> #' .$data['trade_cntt'][$i]['ticketid']. '</a>", "'.$data['trade_cntt'][$i]['title'].'", "'.$createat.'", "'.$data['trade_cntt'][$i]['name'].'", "'.$lastupdate.'" ]'; } else { $text .= '[ "<a onclick='.$onclick.' href=\'#\'><span class=\'id-label span-danger\'>O</span> #' .$data['trade_cntt'][$i]['ticketid']. '</a>", "'.$data['trade_cntt'][$i]['title'].'", "'.$createat.'", "'.$data['trade_cntt'][$i]['name'].'", "'.$lastupdate.'" ], '; } } echo '{ "data": [ '.$text.' ] }'; } public function getContractByIdcard($idcard,$opid) { $array['data'] = []; if($idcard != '') { $data_contractc = array( 'reportcode'=>'crmContract01', 'limit'=>25, 'start'=>0, 'queryFilters'=>array( 'idcard'=> $idcard ) ); $result_contractc = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/dev/api/get_list_contract",$data_contractc); $_json_contractc = json_decode($result_contractc,true); $_json2_contractc = json_decode($_json_contractc,true); $data['trade_cntt'] = $_json2_contractc["result"]["data"]; $text = ''; for ($i=0; $i < count($data['trade_cntt']); $i++) { if(strtotime($data['trade_cntt'][$i]['startdate']) > $this->dayCompare) { $startdate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['startdate'])); }else{$startdate='';} if(strtotime($data['trade_cntt'][$i]['effectivedate']) > $this->dayCompare) { $effectivedate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['effectivedate'])); }else{$effectivedate='';} $href = ''.base_url().'user/contract/'.$data['trade_cntt'][$i]['contractid'].'?opid='.$opid.''; $onclick = "addTab('".$href."','".$data['trade_cntt'][$i]['contractid']."')"; $_arr = ["<a onclick=".$onclick." href='#'>".$data['trade_cntt'][$i]['contractid']. "</a>","".$data['trade_cntt'][$i]['status']."","".$data['trade_cntt'][$i]['property']."","".$startdate."","".$effectivedate."","".$data['trade_cntt'][$i]['notes'].""]; array_push($array['data'],$_arr); } } echo json_encode($array); } public function getCongnoThanhtoan($contractid) { $data_contractc = array( 'method' => 'getReturnData', 'reportcode'=>'crmContract01c', 'limit'=>25, 'start'=>0, 'queryFilters'=>array( 'contractid'=> $contractid ) ); $result_contractc = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/dev/api/get_list_contract",$data_contractc); $_json_contractc = json_decode($result_contractc,true); $_json2_contractc = json_decode($_json_contractc,true); $data['trade_cntt'] = $_json2_contractc["result"]["data"]; $text = ''; for ($i=0; $i < count($data['trade_cntt']); $i++) { $data['trade_cntt'][$i]['transdate'] = str_replace("/", "-", $data['trade_cntt'][$i]['transdate']); $data['trade_cntt'][$i]['duedate'] = str_replace("/", "-", $data['trade_cntt'][$i]['duedate']); if(strtotime($data['trade_cntt'][$i]['transdate']) > $this->dayCompare) { $transdate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['transdate'])); }else{$transdate='';} if(strtotime($data['trade_cntt'][$i]['duedate']) > $this->dayCompare) { $duedate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['duedate'])); }else{$duedate='';} if($i == (count($data['trade_cntt'])-1)) { $text .= '[ "'.$data['trade_cntt'][$i]['revenuetype'].'", "'.$data['trade_cntt'][$i]['value0'].'", "'.$data['trade_cntt'][$i]['value4'].'", "'.$transdate.'", "'.$duedate.'", "'.number_format(abs($data['trade_cntt'][$i]['amount'])).'", "'.$data['trade_cntt'][$i]['extdescription1'].'", "'.$data['trade_cntt'][$i]['allocation'].'", "'.$data['trade_cntt'][$i]['anal_r9'].'" ]'; } else { $text .= '[ "'.$data['trade_cntt'][$i]['revenuetype'].'", "'.$data['trade_cntt'][$i]['value0'].'", "'.$data['trade_cntt'][$i]['value4'].'", "'.$transdate.'", "'.$duedate.'", "'.number_format(abs($data['trade_cntt'][$i]['amount'])).'", "'.$data['trade_cntt'][$i]['extdescription1'].'", "'.$data['trade_cntt'][$i]['allocation'].'", "'.$data['trade_cntt'][$i]['anal_r9'].'" ], '; } } echo '{ "data": [ '.$text.' ] }'; } public function getHistory($contractid) { $data_contractc = array( 'method' => 'qry', 'reportcode'=>'crmContract01b', 'limit'=>25, 'start'=>0, 'queryFilters'=>array( 'contractid'=> $contractid ) ); $result_contractc = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/dev/api/get_list_contract",$data_contractc); $_json_contractc = json_decode($result_contractc,true); $_json2_contractc = json_decode($_json_contractc,true); $data['trade_cntt'] = $_json2_contractc["result"]["data"]; $text = ''; for ($i=0; $i < count($data['trade_cntt']); $i++) { if(strtotime($data['trade_cntt'][$i]['statusdate']) > $this->dayCompare) { $statusdate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['statusdate'])); }else{$statusdate='';} if($i == (count($data['trade_cntt'])-1)) { $name = 0; if(isset($data['trade_cntt'][$i]['name'])){ $name = $data['trade_cntt'][$i]['name']; } $name1 = 0; if(isset($data['trade_cntt'][$i]['name1'])){ $name1 = $data['trade_cntt'][$i]['name1']; } $text .= '[ "'.$data['trade_cntt'][$i]['status'].'", "'.$statusdate.'", "'.number_format($name).'", "'.number_format($name1).'", "'.$data['trade_cntt'][$i]['remarks'].'" ]'; } else { $text .= '[ "'.$data['trade_cntt'][$i]['status'].'", "'.$statusdate.'", "'.$data['trade_cntt'][$i]['name'].'", "'.$data['trade_cntt'][$i]['name1'].'", "'.$data['trade_cntt'][$i]['remarks'].'" ], '; } } echo '{ "data": [ '.$text.' ] }'; } public function getGift($contractid) { $data_contractc = array( 'method' => 'qry', 'reportcode'=>'crmContract01d', 'limit'=>25, 'start'=>0, 'queryFilters'=>array( 'contractid'=> $contractid ) ); $result_contractc = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/dev/api/get_list_contract",$data_contractc); $_json_contractc = json_decode($result_contractc,true); $_json2_contractc = json_decode($_json_contractc,true); $data['trade_cntt'] = $_json2_contractc["result"]["data"]; $text = ''; for ($i=0; $i < count($data['trade_cntt']); $i++) { if(strtotime($data['trade_cntt'][$i]['promotiondate']) > $this->dayCompare) { $promotiondate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['promotiondate'])); }else{$promotiondate='';} if($i == (count($data['trade_cntt'])-1)) { $text .= '[ "'.$promotiondate.'", "'.$data['trade_cntt'][$i]['description'].'", "'.number_format($data['trade_cntt'][$i]['quantity']).'", "'.number_format(abs($data['trade_cntt'][$i]['amount'])).'", "'.$data['trade_cntt'][$i]['remarks'].'" ]'; } else { $text .= '[ "'.$promotiondate.'", "'.$data['trade_cntt'][$i]['description'].'", "'.$data['trade_cntt'][$i]['quantity'].'", "'.$data['trade_cntt'][$i]['amount'].'", "'.$data['trade_cntt'][$i]['remarks'].'" ], '; } } echo '{ "data": [ '.$text.' ] }'; } public function getBussEmployee($contractid) { $data_contractc = array( 'method' => 'qry', 'reportcode'=>'crmContract01f', 'limit'=>25, 'start'=>0, 'queryFilters'=>array( 'contractid'=> $contractid ) ); $result_contractc = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/dev/api/get_list_contract",$data_contractc); $_json_contractc = json_decode($result_contractc,true); $_json2_contractc = json_decode($_json_contractc,true); $data['trade_cntt'] = $_json2_contractc["result"]["data"]; $text = ''; for ($i=0; $i < count($data['trade_cntt']); $i++) { if($i == (count($data['trade_cntt'])-1)) { $text .= '[ "'.$data['trade_cntt'][$i]['name'].'", "'.$data['trade_cntt'][$i]['name1'].'", "'.number_format((float)$data['trade_cntt'][$i]['commissionrate'],5,'.','').'", "'.$data['trade_cntt'][$i]['remarks'].'" ]'; } else { $text .= '[ "'.$data['trade_cntt'][$i]['name'].'", "'.$data['trade_cntt'][$i]['name1'].'", "'.number_format((float)$data['trade_cntt'][$i]['commissionrate'],5,'.','').'", "'.$data['trade_cntt'][$i]['remarks'].'" ], '; } } echo '{ "data": [ '.$text.' ] }'; } public function getNotes($contractid) { $data_contractc = array( 'method' => 'qry', 'reportcode'=>'crmContract01h', 'limit'=>25, 'start'=>0, 'queryFilters'=>array( 'contractid'=> $contractid ) ); $result_contractc = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/dev/api/get_list_contract",$data_contractc); $_json_contractc = json_decode($result_contractc,true); $_json2_contractc = json_decode($_json_contractc,true); $data['trade_cntt'] = $_json2_contractc["result"]["data"]; $text = ''; for ($i=0; $i < count($data['trade_cntt']); $i++) { if(strtotime($data['trade_cntt'][$i]['eventdate']) > $this->dayCompare) { $eventdate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['eventdate'])); }else{$eventdate='';} if($i == (count($data['trade_cntt'])-1)) { $text .= '[ "'.$data['trade_cntt'][$i]['eventtype'].'", "'.$eventdate.'", "'.$data['trade_cntt'][$i]['eventstatus'].'", "'.$data['trade_cntt'][$i]['name'].'", "'.$data['trade_cntt'][$i]['notes'].'" ]'; } else { $text .= '[ "'.$data['trade_cntt'][$i]['eventtype'].'", "'.$eventdate.'", "'.$data['trade_cntt'][$i]['eventstatus'].'", "'.$data['trade_cntt'][$i]['name'].'", "'.$data['trade_cntt'][$i]['notes'].'" ], '; } } echo '{ "data": [ '.$text.' ] }'; } } /* End of file M_data_API.php */ /* Location: ./application/models/M_data_API.php */ ?><file_sep><?php $type = $this->uri->segment(4); ?> <div class="tile height-1024"> <div class="content-title"> <div class="div"> <h5>Danh sรกch dแปฏ liแป‡u trฦฐแปng: <?php echo isset($detail[0]['fieldname'])?$detail[0]['fieldname']:'' ?></h5> </div> </div> <div style="float: right;"> <button <?php if($type == 'T'){echo 'hidden';} ?> type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right" data-toggle="modal" data-target="#myModal">Thรชm</button> </div> <div class="bs-component" style="margin-top: 55px"> <?php if ($type == 'T'){ echo '<div class="component-fields"> <i class="fas fa-align-justify"></i> <span class="title_tab" style="padding-left: 6px">Text</span> </div>'; } ?> <?php if(count($list_ext)>0){ foreach ($list_ext as $value) { ?> <div class="component-fields"> <i class="fas fa-align-justify"></i> <span class="title_tab" style="padding-left: 6px"><?php echo $value['name'] ?></span> <a class="user-name" style="cursor: pointer;float: right;" data-toggle="modal" data-target="#modalDelete" data-code="<?php echo $value['code'] ?>" data-category="<?php echo $value['category'] ?>"><i class="far fa-trash-alt"></i></a> <a class="user-name" style="cursor: pointer;float: right; margin-right: 15px" data-toggle="modal" data-target="#modalUpdate" data-code="<?php echo $value['code'] ?>" data-category="<?php echo $value['category'] ?>" data-name="<?php echo $value['name'] ?>"><i class="fas fa-edit"></i></a> </div> <?php }}?> </div> </div> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document" style="margin-top: 5%"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Dropdown Options</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class="form-group optionbottom"> <label for="exampleInputEmail1">Mรฃ trฦฐแปng</label> <input type="text" class="form-control" name="code" id="code" placeholder="-Mรฃ trฦฐแปng"> </div> <div class="form-group extendbottom"> <label for="exampleInputEmail1">Tรชn trฦฐแปng</label> <input type="text" class="form-control" name="name" id="name" placeholder="-Tรชn trฦฐแปng"> </div> <input type="hidden" name="category" id="category" value="<?php echo $this->uri->segment(5) ?>"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">ฤรณng</button> <button type="button" onclick="insertSelectBox()" class="btn btn-primary">Thรชm</button> </div> </div> </div> </div> <div class="modal fade" id="modalDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 7%" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Xoรก Option</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <p class="bg-danger" style="padding: 10px;color: #FFF;" >Bแบกn cรณ chแบฏc muแป‘n xoรก khรดng?</p> <input type="hidden" id="categorydelete" name="categorydelete"> <input type="hidden" id="codedelete" name="codedelete"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">ฤรณng</button> <button type="button" onclick="deleteButton()" class="btn btn-danger">Xoรก</button> </div> </div> </div> </div> <div class="modal fade" id="modalUpdate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 7%" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Sแปญa Option</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class="form-group"> <label for="exampleInputEmail1">Tรชn SelectBox:</label> <input type="text" class="form-control nameField" id="nameField" name="name" placeholder="Tรชn SelectBox"> </div> <input type="hidden" id="category" name="category"> <input type="hidden" class="code" id="code" name="code"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">ฤรณng</button> <button type="button" onclick="updateButton()" class="btn btn-primary">Sแปญa</button> </div> </div> </div> </div><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-12 margin-bot-10 margin-top-5 margin-left-10"> <?php echo isset($top) ? $top : ''; ?> </div> <div class="col-md-2 col-md-24 no-padding padding-left-15"> <?php echo isset($left) ? $left : ''; ?> </div> <div class="col-md-6 no-padding padding-left-5"> <?php echo isset($center) ? $center : ''; ?> </div> <div class="col-md-3 no-padding padding-left-5 padding-top-10 padding-right-10"> <?php if($this->input->get('cusid') !=''){ ?> <iframe class="iframehistory" id="iframehistory" style="width: 100%;height:1000px;display: block; border: none;" src="<?php echo base_url() ?>user/viewUserHistory?cusid=<?php echo strval($this->input->get('cusid')) ?>"></iframe> <?php } ?> <!-- <?php echo isset($right) ? $right : ''; ?> --> </div> </div> </main><file_sep><div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-10"> <div class=""> <label class="control-label user-label col-md-4 no-padding">Tรชn trฦฐแปng</label> <?php if (count($detail)>0) { $fieldname = $detail[0]['fieldname']; $fieldcode = $detail[0]['fieldcode']; $status = $detail[0]['status']; }else{$fieldname=''; $status ='';} ?> <label class="control-label col-md-7 no-padding-right"> <input class="col-md-12 no-padding font-size-12" value="<?php echo $fieldname ?>" placeholder="Nhแบญp hแป tรชn" id="fieldname" required="" minlength="4" maxlength="30"> <input type="hidden" class="col-md-12 no-padding font-size-12" value="<?php echo $fieldcode ?>" placeholder="Nhแบญp hแป tรชn" id="fieldcode" required="" minlength="4" maxlength="30"> </label> </div> <div class=""> <label class="control-label user-label col-md-4 no-padding">Loแบกi nhแบญp liแป‡u</label> <?php $type = $this->uri->segment(4); if($type == 'T'){ $typeInput = 'Text'; } else{ $typeInput = 'SelectBox';} ?> <label class="control-label col-md-7 no-padding-right"> <input readonly class="col-md-12 no-padding font-size-12" value="<?php echo $typeInput ?>" placeholder="Nhแบญp hแป tรชn" id="type" required="" minlength="4" maxlength="30"> </label> </div> <div class=""> <label class="control-label user-label col-md-4 no-padding">Trแบกng thรกi</label> <label class="control-label col-md-7 no-padding-right"> <select class="control-label col-md-12 no-border no-padding" id="status"> <option <?php if ($status!='1'){echo 'selected';} ?> value="0">Khรดng hoแบกt ฤ‘แป™ng</option> <option <?php if ($status=='1'){echo 'selected';} ?> value="1">ฤang hoแบกt ฤ‘แป™ng</option> </select> </label> </div> </div> </div> <div class="fc-corner-right"> <div class="fc-button-group" style="float:right"> <button type="submit" onclick="uddateFields()" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right btn-createuser">Lฦฐu thรดng tin</button> </div> </div><file_sep><?php // error_reporting(0); // ini_set('display_errors', 0); defined('BASEPATH') OR exit('No direct script access allowed'); class Search extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url')); $this->load->model(array('M_api')); } public function index() { $_data = []; $body = []; $list_user = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyroleid/3'); $body['listuser'] = json_decode($list_user,true)['data']; $list_agent = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyroleid/2'); $body['listagent'] = json_decode($list_agent,true)['data']; $_data['script'] = $this->load->view('script/script_search', NULL, TRUE); $_data['mainview'] = $this->load->view('search/search', $body , TRUE); $this->load->view('dashboard',$_data); } public function rightSearch() { $get = $this->input->get(); $query = '?'; foreach ($get as $key => $value) { $value = str_replace('#', '', $value); $value = str_replace(' .', ' ', $value); $query.=$key.'='.urlencode(trim($value)).'&'; } $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/search'.$query); $data['result'] = json_decode($json,true); $_data['script'] = $this->load->view('script/script_search', NULL, TRUE); $_data['mainview'] = $this->load->view('search/right_search', $data , TRUE); $this->load->view('dashboard',$_data); } public function rightSearchTicket() { $agent = $_GET['agentcurrent']; $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/getticketinfo/'.$agent.'/700'); $lienquan = $_GET['lienquan']; $data['lienquan'] = $lienquan; $data['agentcurrent'] = $agent; $data['result'] = json_decode($json,true); $data['status'] = $_GET['status']; $_data['script'] = $this->load->view('script/script_search', NULL, TRUE); $_data['mainview'] = $this->load->view('search/right_search_ticket', $data , TRUE); $this->load->view('dashboard',$_data); } public function ticketByType($type){ $data = []; $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/getticketbyagentgroup/'.$this->session->userdata('groupid').'/'.$type); $data['result'] = json_decode($json,true)['data']; $_data['script'] = $this->load->view('script/script_search', NULL, TRUE); $_data['mainview'] = $this->load->view('search/ticket_by_status', $data , TRUE); $this->load->view('dashboard',$_data); } public function rightSearchTicketInput() { $get = $this->input->get(); $query = '?'; foreach ($get as $key => $value) { $value = str_replace('#', '', $value); //$value = str_replace(' .', ' ', $value); //$value = preg_replace('/[^a-zA-Z0-9-_\.]/','', $value); $query.=$key.'='.rawurlencode(trim($value)).'&'; } $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/search'.$query); $var = $this->session->userdata; $custidLogin = $var['custid']; $data['agentcurrent'] = $custidLogin; $data['result'] = json_decode($json,true); if(isset($_GET['status'])){ $data['status'] = $_GET['status']; }else{ $data['status'] = -1; } $_data['script'] = $this->load->view('script/script_search', NULL, TRUE); $_data['mainview'] = $this->load->view('search/right_search_ticket_input', $data , TRUE); $this->load->view('dashboard',$_data); // echo ('http://test.tavicosoft.com/crm/index.php/ticket/search'.$query); } }<file_sep><iframe src="<?php echo(base_url('ticket/test_left_detail'))?>"></iframe><file_sep><script type="text/javascript"> $(function () { $('[data-toggle="tooltip"]').tooltip() }) var dayCompare = new Date("2000-01-01T00:00:00"); $(document).ready( function () { loadFirst(); $( "#idcard" ).click(function() { $('#updateIdcard').modal('show'); $('#updateIdcard').on('shown.bs.modal', function (e) { /* $('#issueddate').datetimepicker({timepicker:false, format:'d/m/Y'}); */ }) }); }); function insertTicket(custCustomer,custid,groupid) { $('#btn-plus-ticket').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner'); var arrayext = []; $.ajax({ url: "<?php echo base_url().'ticket/aj_insert_ticket';?>", dataType:'json', type : "POST", data: {agentcurrent: custid, customer: custCustomer, groupid: groupid, agentgroup: groupid} }) .done(function(data){ if(data.code==0){ parent.alertLog("Cแบฃnh bรกo !", data.message, "warning"); $('#btn-plus-ticket').prop('disabled',false).find('i').removeClass(); $('#btn-plus-ticket').prop('disabled',false).find('i').addClass('fas fa-plus'); }else{ $('#btn-plus-ticket').prop('disabled',false).find('i').removeClass(); $('#btn-plus-ticket').prop('disabled',false).find('i').addClass('fas fa-plus'); // alert("thรชm thร nh cรดng."); parent.alertLog("Thร nh cรดng !", "Thรชm phiแบฟu thร nh cรดng.", "success"); // var tab = window.top.$('div.tab-pane.active').attr('id'); // window.top.$('li a.nav-link[href="#'+tab+'"]').find('span').html('#'+data.data); // location.href= '<?php echo base_url().'/ticket/detail/';?>'+data.data; parent.addTab('<?php echo base_url().'/ticket/detail/';?>'+data.data,'#'+data.data); } }) .fail(function(){ console.log("Error"); }); } function loadFirst() { $('#roleid').val('<?php echo $detail[0]['roleid'] ?>'); $('#gender').val('<?php echo $detail[0]['gender'] ?>'); var load_roleid = $('#roleid').val(); var idcard = '<?php echo $detail[0]['idcard'] ?>'; var opid = $('#opid').val(); loadGroup(load_roleid); $('input[name=city]').on('keyup',function(){ var val = $(this).val(); var opt = $('datalist#l_city').find('option[value="'+val+'"]'); if (opt.length>0) { var idcity = opt.attr('id-city'); $.ajax({ url: '<?php echo base_url()?>user/selectCity', type: 'POST', dataType: 'JSON', data: {id_city : idcity}, }) .done(function(data) { var l_r = ''; for (var i = 0; i < data.length; i++) { l_r+='<option value="'+data[i]['name']+'" id="'+data[i]['id_district']+'"></option>'; } $('datalist#l_distr').html(l_r); }) .fail(function() { console.log("error"); }) } }); $('input[name=district').on('keyup',function(){ var val = $(this).val(); var opt = $('datalist#l_distr').find('option[value="'+val+'"]'); if (opt.length>0) { var id = opt.attr('id'); $.ajax({ url: '<?php echo base_url()?>user/selectDistrict', type: 'POST', dataType: 'JSON', data: {id_district : id}, }) .done(function(data) { var l_r = ''; for (var i = 0; i < data.length; i++) { l_r+='<option value="'+data[i]['name']+'" id="'+data[i]['id_ward']+'"></option>'; } $('datalist#l_ward').html(l_r); }) .fail(function() { console.log("error"); }) } }); var table_contract = $('#table-1-contract').DataTable({ "paging": false, "info": false, "searching": false, "scrollY": "235px", "scrollX": true, "scrollCollapse": true, "ajax": '<?php echo base_url() ?>user/testContract?idcard='+idcard+'&opid='+opid+'', dom: "Bfrtip", "processing": true, 'language':{ "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />", "processing": "" }, "initComplete": function(settings, json){ var info = this.api().page.info(); console.log('Total records', info.recordsTotal); console.log('Displayed records', info.recordsDisplay); $("#tab1").text('Giao dแป‹ch ('+info.recordsDisplay+')'); this.fnAdjustColumnSizing(true); } }); $('.btn-update-idcard').click(function(){ $('.btn-update-idcard').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner'); var custid = '<?php echo strval($_GET['cusid']) ?>'; var roleid = $('#roleid').val(); var groupid = $('#groupid').val(); var idcard = $('#idcard_modal').val(); var issueddate = $('#issueddate').val(); var issuedplace = $('#issuedplace').val(); $.ajax({ url: '<?php echo base_url()?>user/updateUser', type: 'POST', dataType: 'JSON', data: {roleid : roleid, groupid: groupid,custid:custid,idcard: idcard, issueddate: issueddate, issuedplace: issuedplace, ext:$('#dataExt').serialize()}, }) .done(function(data){ $('.btn-update-idcard').prop('disabled',false).find('i').removeClass(); $('#updateIdcard').modal('toggle'); parent.notification("Lฦฐu CMND thร nh cรดng!!!"); $('#idcard').val($('#idcard_modal').val()); $('#idcard').attr('value', $('#idcard_modal').val()); var iframe = document.getElementById('iframehistory'); iframe.src = iframe.src; }) .fail(function(){ parent.notification("Lฦฐu CMND thแบฅt bแบกi!!!"); }) }); $('.btn-update').click(function(){ $('#updateUser').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner'); var custid = '<?php echo strval($_GET['cusid']) ?>'; var roleid = $('#roleid').val(); var groupid = $('#groupid').val(); var custname = $('#custname').val(); // var idcard = $('#idcard').val(); var fullbirthday = $('#fullbirthday').val(); var gender = $('#gender').val(); var telephone = $('#telephone').val(); var email = $('#email').val(); var country = $('#country').val(); var city = $('#city').val(); var district = $('#district').val(); var ward = $('#ward').val(); var text = ''; var address = $('#address').val(); var comments = $('#comments').val(); var thunhap = $('#thunhap').val(); var fulladdress = $('#fulladdress').val(); // var custid = $('#custid').val(); var password = $('#password').val(); var queue = $('#queue').val(); var queueold = $('#queue_old').val(); $.ajax({ url: '<?php echo base_url()?>user/updateUser', type: 'POST', dataType: 'JSON', data: {roleid : roleid, groupid: groupid, custname:custname,idcard:idcard,fullbirthday:fullbirthday,telephone:telephone,email:email,country:country,city:city,district:district,ward:ward,address:address,comments:comments,thunhap:thunhap,gender:gender,fulladdress: fulladdress,custid:custid,password:<PASSWORD>,queue:queue,queueold:queueold, ext:$('#dataExt').serialize()}, }) .done(function(data) { $('#updateUser').prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); if(data.message =='Success') { // location.reload(); parent.notification("Cแบญp nhแบญt thร nh cรดng"); //update // loadHistory(); var iframe = document.getElementById('iframehistory'); iframe.src = iframe.src; } else{ parent.alertLog("Cแบฃnh bรกo !", data.message, "warning"); //parent.notification(data.message); } }) .fail(function() { $('#updateUser').prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); parent.notification("Sแปญa thรดng tin thแบฅt bแบกi"); }) }); $('#insertUserVal').submit(function(e){ e.preventDefault(); }); $('#fullbirthday').datetimepicker({timepicker:false, format:'d/m/Y'}); $('#issueddate').datetimepicker({timepicker:false, format:'d/m/Y'}); $("a[data-toggle=\"tab\"]").on("shown.bs.tab", function (e) { $($.fn.dataTable.tables( true ) ).css('width', '100%'); $($.fn.dataTable.tables(true)).DataTable().columns.adjust(); }); } function keyUpAddress(obj) { text = obj.value; fulladdress = text; $('#fulladdresstemp').val(fulladdress); } function selectCity(obj){ var $id = obj.value; city = obj.options[obj.selectedIndex].text; fulladdress = text+ ' '+ 'Thร nh phแป‘ '+city; $('#fulladdresstemp').val(fulladdress); // alert(fulladdress); $('.gicungdc').remove(); $.ajax({ url: '<?php echo base_url()?>user/selectCity', type: 'POST', dataType: 'JSON', data: {id_city : $id}, }) .done(function(data) { for (var i = 0; i < data.length; i++) { $('#dodulieu').after('<option title="'+data[i]['name']+'" class="gicungdc" value="'+data[i]['id_district']+'">'+data[i]['name']+'</option>'); } }) .fail(function() { console.log("error"); }) } function selectDistrict(obj){ var $id = obj.value; district = obj.options[obj.selectedIndex].text; fulladdress =text+ ' '+ district+' '+city; $('#fulladdresstemp').val(fulladdress); // alert(fulladdress); $('.gicungdc1').remove(); $.ajax({ url: '<?php echo base_url()?>user/selectDistrict', type: 'POST', dataType: 'JSON', data: {id_district : $id}, }) .done(function(data) { for (var i = 0; i < data.length; i++) { $('#dodulieu1').after('<option title="'+data[i]['name']+'" class="gicungdc1" value="'+data[i]['id_ward']+'">'+data[i]['name']+'</option>'); } }) .fail(function() { console.log("error"); }) } function selectWard(obj){ var $id = obj.value; ward = obj.options[obj.selectedIndex].text; fulladdress =text+ ' '+ ward+' '+district+' '+city; $('#fulladdresstemp').val(fulladdress); } function updateUser(obj) { var id = obj.title; var data = $('#'+id+'').val(); $.ajax({ url: '<?php echo base_url()?>user/selectDistrict', type: 'POST', dataType: 'JSON', data: {id_district : $id}, }) .done(function(data) { for (var i = 0; i < data.length; i++) { $('#dodulieu1').after('<option title="'+data[i]['name']+'" selected class="gicungdc1" value="'+data[i]['id_ward']+'">'+data[i]['name']+'</option>'); } }) .fail(function() { console.log("error"); }) } function selectGroup(obj){ var $id = obj.value; $('.div-add').remove(); $('.group_item').remove(); $.ajax({ url: '<?php echo base_url()?>user/getGroupByRoleId', type: 'POST', dataType: 'JSON', data: {roleid : $id}, }) .done(function(data) { data =data.data; if(data[0]['roleid'] == 3) { for (var i = 0; i < data.length; i++) { console.log(data[0]['roleid']); $('.grouplist').append('<option selected class="group_item" value="'+data[i]['groupid']+'">'+data[i]['groupname']+'</option>'); } } else{ for (var i = 0; i < data.length; i++) { console.log(data[0]['roleid']); $('.grouplist').append('<option selected class="group_item" value="'+data[i]['groupid']+'">'+data[i]['groupname']+'</option>'); } $('.div-group').after('<div class="div-add">\ <label class="control-label user-label col-md-3 no-padding">ID:</label>\ <label class="control-label col-md-8 no-padding-right">\ <input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhแบญp ID" id="custid" name="custid">\ </label>\ </div>\ <div class="div-add">\ <label class="control-label user-label col-md-3 no-padding">Password:</label>\ <label class="control-label col-md-8 no-padding-right">\ <input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhแบญp Password" type="password" id="password" name="password">\ </label>\ </div>\ ') } }) .fail(function() { console.log("error"); }) } function loadGroup(roleid) { var $id = roleid; $('.div-add').remove(); $('.group_item').remove(); $.ajax({ url: '<?php echo base_url()?>user/getGroupByRoleId', type: 'POST', dataType: 'JSON', data: {roleid : $id}, }) .done(function(data) { data =data.data; if(data[0]['roleid'] == 3) { for (var i = 0; i < data.length; i++) { console.log(data[0]['roleid']); $('.grouplist').append('<option selected class="group_item" value="'+data[i]['groupid']+'">'+data[i]['groupname']+'</option>'); } } else{ for (var i = 0; i < data.length; i++) { $('.grouplist').append('<option selected class="group_item" value="'+data[i]['groupid']+'">'+data[i]['groupname']+'</option>'); } $('.div-group').after('<div class="div-add">\ <label class="control-label user-label col-md-3 no-padding">ID:</label>\ <label class="control-label col-md-8 no-padding-right">\ <input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhแบญp ID" id="custid" name="custid">\ </label>\ </div>\ <div class="div-add">\ <label class="control-label user-label col-md-3 no-padding">Password:</label>\ <label class="control-label col-md-8 no-padding-right">\ <input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhแบญp Password" type="<PASSWORD>" id="password" name="password">\ </label>\ </div>\ ') } $('#groupid').val('<?php echo $detail[0]['groupid'] ?>'); }) .fail(function() { console.log("error"); }) } function removeemail($email, $emaillist,roleid,groupid){ var custid = $('#cusit_id').attr('custid'); $.ajax({ url: '<?php echo base_url()?>user/updateUserEmailList', type: 'POST', dataType: 'JSON', data: {custid : custid,email:$email,emaillist:$emaillist,ext:$('#dataExt').serialize(),roleid:roleid,groupid:groupid}, }) .done(function(data) { if(data.code==1){ window.location.reload(); }else{ parent.alertLog("Cแบฃnh bรกo !", data.message, "warning"); } }) .fail(function() { parent.alertLog("Cแบฃnh bรกo !", "Xรณa Email Thแบฅt Bแบกi", "warning"); }) } function removephone($phone, $phonelist,roleid,groupid){ var custid = $('#cusit_id').attr('custid'); $.ajax({ url: '<?php echo base_url()?>user/updateUserPhoneList', type: 'POST', dataType: 'JSON', data: {custid : custid,phone:$phone,phonelist:$phonelist,ext:$('#dataExt').serialize(),roleid:roleid,groupid:groupid}, }) .done(function(data) { if(data.code==1){ window.location.reload(); }else{ parent.alertLog("Cแบฃnh bรกo !", data.message, "warning"); } }) .fail(function() { parent.alertLog("Cแบฃnh bรกo !", "Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ admin : PHONE", "warning"); }) } $('.btn-addfulladdress').click(function(){ $('.btn-addfulladdress').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner'); var custid = '<?php echo strval($_GET['cusid']) ?>'; var roleid = '<?php echo strval($_GET['roleid']) ?>'; var groupid = $('#log_groupid').val(); var addid = $(this).attr('addid'); var country = $('#country').val(); var city = $('#city').val(); var district = $('#district').val(); var ward = $('#ward').val(); var street = $('#street').val(); var address = $('#address').val(); var label = $('#label').val(); $.ajax({ url: '<?php echo base_url()?>user/aj_insert_bonus_address', type: 'POST', dataType: 'JSON', data: {custid: custid, city:city,district:district,ward:ward,street:street,address: address,label:label,roleid:roleid,groupid:groupid}, }) .done(function(data) { if(data.code==1){ $.ajax({ url: '<?php echo base_url()?>user/getAddressApi', type: 'POST', dataType: 'JSON', data: {custid: custid}, }) .done(function(data){ $('.btn-addfulladdress').prop('disabled',false).find('i').removeClass(); parent.notification("Thรชm ฤ‘แป‹a chแป‰ thร nh cรดng!!!"); $('#updateAddress').modal('toggle'); var data_html = ''; var j = 0; for (var i = 0; i < data.data.length; i++) { if(data.data[i].hidden != 1) { if(j==0) { var label_diachi = "ฤแป‹a chแป‰"; }else{ var label_diachi = '';} var label = "'"+data.data[i].label+"'"; var city = "'"+data.data[i].city+"'"; var district = "'"+data.data[i].district+"'"; var ward = "'"+data.data[i].ward+"'"; var street = "'"+data.data[i].street+"'"; var address = "'"+data.data[i].address+"'"; var addressid = "'"+data.data[i].addressid+"'"; data_html +='<label class="control-label user-label col-md-3 no-padding">'+label_diachi+'</label>\ <label class="control-label col-md-7 no-padding-right">\ <input onclick="openModalEdit(\ '+label+',\ '+city+',\ '+district+',\ '+ward+',\ '+street+',\ '+address+',\ '+addressid+'\ )" class="col-md-12 no-padding font-size-12" value="'+data.data[i].label+'">\ </label>\ <a href="#" onclick="removeAddress('+addressid+')"><i class="fas fa-times-circle fa-md float-right margin-top-3" style="margin-right: 2px"></i></a>\ '; j++; } } $('.div-address').html(data_html); $('#country').val(""); $('#city').val(""); $('#district').val(""); $('#ward').val(""); $('#street').val(""); $('#address').val(""); $('#label').val(""); var iframe = document.getElementById('iframehistory'); iframe.src = iframe.src; }).fail(function(){ parent.alertLog("Cแบฃnh bรกo !", "Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ admin", "warning"); }) }else{ parent.alertLog("Cแบฃnh bรกo !", data.message, "warning"); } }) .fail(function() { parent.alertLog("Cแบฃnh bรกo !", "Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ admin", "warning"); }) }); $('.btn-updatefulladdress').click(function(){ $('.btn-updatefulladdress').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner'); var custid = '<?php echo strval($_GET['cusid']) ?>'; var addressid = $('#addressid').val(); var roleid = '<?php echo strval($_GET['roleid']) ?>'; var groupid = $('#log_groupid').val(); // var country = $('#country_edit').val(); var city = $('#city_edit').val(); var district = $('#district_edit').val(); var ward = $('#ward_edit').val(); var street = $('#street_edit').val(); var address = $('#address_edit').val(); var label = $('#label_edit').val(); $.ajax({ url: '<?php echo base_url()?>user/aj_update_bonus_address', type: 'POST', dataType: 'JSON', data: {city:city,district:district,ward:ward,street:street,address: address,label:label,addressid:addressid,roleid:roleid,groupid:groupid,custid:custid}, }) .done(function(data) { if(data.code==1){ $.ajax({ url: '<?php echo base_url()?>user/getAddressApi', type: 'POST', dataType: 'JSON', data: {custid: custid}, }) .done(function(data){ $('.btn-updatefulladdress').prop('disabled',false).find('i').removeClass(); parent.notification("Thรชm ฤ‘แป‹a chแป‰ thร nh cรดng!!!"); $('#updateFullAddress').modal('toggle'); var data_html = ''; var j = 0; for (var i = 0; i < data.data.length; i++) { if(data.data[i].hidden != 1) { if(j==0) { var label_diachi = "ฤแป‹a chแป‰"; }else{ var label_diachi = '';} var label = "'"+data.data[i].label+"'"; var city = "'"+data.data[i].city+"'"; var district = "'"+data.data[i].district+"'"; var ward = "'"+data.data[i].ward+"'"; var street = "'"+data.data[i].street+"'"; var address = "'"+data.data[i].address+"'"; var addressid = "'"+data.data[i].addressid+"'"; data_html +='<label class="control-label user-label col-md-3 no-padding">'+label_diachi+'</label>\ <label class="control-label col-md-7 no-padding-right">\ <input onclick="openModalEdit(\ '+label+',\ '+city+',\ '+district+',\ '+ward+',\ '+street+',\ '+address+',\ '+addressid+'\ )" class="col-md-12 no-padding font-size-12" value="'+data.data[i].label+'">\ </label>\ <a href="#" onclick="removeAddress('+addressid+')"><i class="fas fa-times-circle fa-md float-right margin-top-3" style="margin-right: 2px"></i></a>\ '; j++; } } $('.div-address').html(data_html); var iframe = document.getElementById('iframehistory'); iframe.src = iframe.src; // alert(data_html); }).fail(function(){ parent.alertLog("Cแบฃnh bรกo !", "Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ admin", "warning"); }) }else{ parent.alertLog("Cแบฃnh bรกo !", data.message, "warning"); } }) .fail(function() { parent.alertLog("Cแบฃnh bรกo !", "Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ admin", "warning"); }) }); function openModalEdit(label,city,district,ward,street,address,addressid) { $('#updateFullAddress').modal('toggle'); $('#updateFullAddress').on('shown.bs.modal', function (e) { $('#label_edit').val(label); $('#city_edit').val(city); $('#district_edit').val(district); $('#ward_edit').val(ward); $('#street_edit').val(street); $('#address_edit').val(address); $('#addressid').val(addressid); }); } function formatDMY(dd,mm,yyyy) { if(dd<10){ dd='0'+dd; } if(mm<10){ mm='0'+mm; } var today = dd+'/'+mm+'/'+yyyy; return today; } function formatHMS(hh,mm,ss) { if(hh<10){ hh='0'+hh; } if(mm<10){ mm='0'+mm; } if(ss<10){ ss='0'+ss; } var today = hh+':'+mm+':'+ss; return today; } function removeAddress(addressid) { $('#modalDeleteAddress').modal('toggle'); $('#modalDeleteAddress').on('shown.bs.modal', function (e) { $('#addressid_delete').val(addressid); }); } function deleteAddress() { var custid = '<?php echo strval($_GET['cusid']) ?>'; $('.btn-danger').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner'); var addressid = $('#addressid_delete').val(); $.ajax({ url: '<?php echo base_url()?>user/aj_delete_address', type: 'POST', dataType: 'JSON', data: {addressid: addressid}, }) .done(function(data){ if(data.code == 1) { $.ajax({ url: '<?php echo base_url()?>user/getAddressApi', type: 'POST', dataType: 'JSON', data: {custid: custid}, }) .done(function(data){ $('.btn-danger').prop('disabled',false).find('i').removeClass(); var iframe = document.getElementById('iframehistory'); iframe.src = iframe.src; parent.notification("ฤรฃ xoรก ฤ‘แป‹a chแป‰!!!"); $('#modalDeleteAddress').modal('toggle'); var data_html = ''; var j = 0; for (var i = 0; i < data.data.length; i++) { if(data.data[i].hidden != 1) { if(j==0) { var label_diachi = "ฤแป‹a chแป‰"; }else{ var label_diachi = '';} var label = "'"+data.data[i].label+"'"; var city = "'"+data.data[i].city+"'"; var district = "'"+data.data[i].district+"'"; var ward = "'"+data.data[i].ward+"'"; var street = "'"+data.data[i].street+"'"; var address = "'"+data.data[i].address+"'"; var addressid = "'"+data.data[i].addressid+"'"; data_html +='<label class="control-label user-label col-md-3 no-padding">'+label_diachi+'</label>\ <label class="control-label col-md-7 no-padding-right">\ <input onclick="openModalEdit(\ '+label+',\ '+city+',\ '+district+',\ '+ward+',\ '+street+',\ '+address+',\ '+addressid+'\ )" class="col-md-12 no-padding font-size-12" value="'+data.data[i].label+'">\ </label>\ <a href="#" onclick="removeAddress('+addressid+')"><i class="fas fa-times-circle fa-md float-right margin-top-3" style="margin-right: 2px"></i></a>\ '; j++; } } $('.div-address').html(data_html); // alert(data_html); }).fail(function(){ parent.notification("Xoรก ฤ‘แป‹a chแป‰ khรดng thร nh cรดng!!!"); }) } }) .fail(function(){ }); } /* $('.btn-update-idcard').click(function(){ $('.btn-update-idcard').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner'); var custid = '<?php echo strval($_GET['cusid']) ?>'; var roleid = $('#roleid').val(); var groupid = $('#groupid').val(); var idcard = $('#idcard_modal').val(); var issueddate = $('#issueddate').val(); var issuedplace = $('#issuedplace').val(); $.ajax({ url: '<?php echo base_url()?>user/updateUser', type: 'POST', dataType: 'JSON', data: {roleid : roleid, groupid: groupid,custid:custid,idcard: idcard, issueddate: issueddate, issuedplace: issuedplace, ext:$('#dataExt').serialize()}, }) .done(function(data){ $('.btn-update-idcard').prop('disabled',false).find('i').removeClass(); $('#updateIdcard').modal('toggle'); parent.notification("Lฦฐu CMND thร nh cรดng!!!"); $('#idcard').val(idcard); }) .fail(function(){ parent.notification("Lฦฐu CMND thแบฅt bแบกi!!!"); }) }); */ function addTelephone(id,idcard,roleid,groupid) { $('.btn-add-phone').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner'); var listtelephone = $('#listtelephone').val(); var phone = $('#telephonelist').val(); /* if(listtelephone.length == 0) { var listphone = telephonelist; } else{ var listphone = listtelephone+','+telephonelist; } */ $.ajax({ url: '<?php echo base_url()?>user/insertPhoneList', type: 'POST', dataType: 'JSON', data: {phone:phone, telephonelist: listtelephone,custid:id,idcard:idcard,roleid:roleid,ext:$('#dataExt').serialize(),groupid:groupid}, }) .done(function(data){ $('.btn-add-phone').prop('disabled',false).find('i').removeClass(); if(data.code==1){ window.location.reload(); }else{ parent.alertLog("Cแบฃnh bรกo !", data.message, "warning"); } }) .fail(function(){ $('.btn-add-phone').prop('disabled',false).find('i').removeClass(); parent.alertLog("Cแบฃnh bรกo !", "Thรชm sแป‘ ฤ‘iแป‡n thoแบกi phแปฅ thแบฅt bแบกi", "warning"); }); } function addEmail(id,idcard,roleid,groupid) { var listemail = $('#listemail').val(); var emaillist = $('#emaillist').val(); var email = $('#emailadd').val(); /* if(listemail.length == 0) { var listmail = emaillist; } else{ var listmail = listemail+','+emaillist; } */ $.ajax({ url: '<?php echo base_url()?>user/insertEmailList', type: 'POST', dataType: 'JSON', data: {email: email,emaillist: listemail,custid:id,idcard:idcard,roleid:roleid,ext:$('#dataExt').serialize(),groupid:groupid}, }) .done(function(data){ if(data.code==1){ window.location.reload(); }else{ parent.alertLog("Cแบฃnh bรกo !", data.message, "warning"); } }) .fail(function(){ parent.alertLog("Cแบฃnh bรกo !", "Thรชm Email Thแบญt Bแบกi", "warning"); }); } //Tooltip </script><file_sep><script type="text/javascript"> $(document).ready(function(){ loadFirst(); }); function loadFirst() { $('#table-1-searchticket').DataTable({ "paging": true, "language": { "paginate": { "previous": "Trฦฐแป›c", "next":"Sau" } }, "ordering": false, "info": false, "searching": false, "scrollY": "100%", // "scrollX": true, "bLengthChange": false, "iDisplayLength": 25, "scrollCollapse": true }).columns.adjust().draw(); $('#table-1-searchuser').DataTable({ "paging": true, "language": { "paginate": { "previous": "Trฦฐแป›c", "next":"Sau" } }, "columns":[ { "width": "20%" }, { "width": "20%" }, { "width": "20%" }, { "width": "20%" }, { "width": "20%" } ], "ordering": false, "info": false, "searching": false, "scrollY": "100%", // "scrollX": true, "bLengthChange": false, "iDisplayLength": 25, "scrollCollapse": true }).columns.adjust().draw(); keyPress('search'); keyPress('custname'); keyPress('custid'); keyPress('telephone'); keyPress('email'); keyPress('mapping1'); keyPressTicket('searchticket'); keyPressTicket('answerInput'); keyPressTicket('agentInput'); $('#search_customer').click(function(){ searchCustomer(); }); $('#search_ticket').click(function(){ searchTicket(); }); } function searchCustomer() { var search1 = $('#search').val(); var search = encodeURI(search1); var custname = $('#custname').val(); var custid = $('#custid').val(); var telephone = $('#telephone').val(); var email = $('#email').val(); var mapping1 = $('#mapping1').val(); document.getElementById('iframesearch').src = "<?php echo base_url().'search/rightSearch/?search=' ?>"+search+"&custname="+custname+"&idcard="+custid+"&telephone="+telephone+"&email="+email+"&mapping1="+mapping1+"&roleid=<?php echo($this->session->userdata('roleid'))?>"; } function searchTicket() { var searchticket = encodeURI($('#searchticket').val()); if($('#answerInput').val().length > 5){ var customer = $('#customer').val(); }else{ var customer = ''; } if($('#agentInput').val().length > 5){ var agentcurrent = $('#agentcurrent').val(); }else{ var agentcurrent = ''; } var priority = $('#priority').val(); var status = $('#status').val(); var ticketchannel = $('#ticketchannel').val(); document.getElementById('iframesearch').src = "<?php echo base_url().'search/rightSearchTicketInput/?search='?>"+searchticket+"&customer="+customer+"&agentcurrent="+agentcurrent+"&priority="+priority+"&status="+status+"&ticketchannel="+ticketchannel+"&custid=<?php echo($this->session->userdata('custid'))?>&groupid=<?php echo($this->session->userdata('groupid'))?>"; } function keyPress(id) { $('#'+id+'').keypress(function(e1){ if(e1.keyCode==13){ // if user is hitting enter searchCustomer(); } }); } function keyPressTicket(id) { $('#'+id+'').keypress(function(e1){ if(e1.keyCode==13){ // if user is hitting enter searchTicket(); } }); } /* function deleteTextboxSearch() { $('#searchticket').val(''); $('#search').val(''); $('#search').removeAttr('minLength'); $('#searchticket').removeAttr('maxLength'); $('#search').removeAttr('minLength'); $('#searchticket').removeAttr('maxLength'); } function checkKeyPressTicket(id) { if($('#ticketchannel').val() != '' || $('#priority').val() != '' || $('#status').val() != '' || $('#answerInput').val() != "" || $('#agentInput').val() != "" ) { $('#'+id+'').val(""); $('#'+id+'').prop('minLength', 0); $('#'+id+'').prop('maxLength', 0); if($('#'+id+'').val() == "") { $('#'+id+'').prop('minLength', 0); $('#'+id+'').prop('maxLength', 0); } } else { $('#'+id+'').removeAttr('minLength'); $('#'+id+'').removeAttr('maxLength'); } } function checkKeyPressUser(id) { if($('#custname').val() != "" || $('#custid').val() != "" || $('#telephone').val() != "" || $('#email').val() != "" || $('#mapping1').val() != "" ) { $('#'+id+'').val(""); $('#'+id+'').prop('minLength', 0); $('#'+id+'').prop('maxLength', 0); if($('#'+id+'').val() == "") { $('#'+id+'').prop('minLength', 0); $('#'+id+'').prop('maxLength', 0); } } else { $('#'+id+'').removeAttr('minLength'); $('#'+id+'').removeAttr('maxLength'); } } */ </script><file_sep><script type="text/javascript"> function updateGroup() { // var groupid = $('#groupid').val(); // var ticketrule = $('#ticketrule').val(); // var taskrule = $('#taskrule').val(); // var userrule = $('#userrule').val(); // var knowledgerule = $('#knowledgerule').val(); // var status = $('#status').val(); $('#btn-uploadgu').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner'); getValueCheckbox("viewticket","viewtickethidden"); getValueCheckbox("addticket","addtickethidden"); getValueCheckbox("editticket","edittickethidden"); getValueCheckbox("viewuser","viewuserhidden"); getValueCheckbox("adduser","adduserhidden"); getValueCheckbox("edituser","edituserhidden"); getValueCheckbox("viewtask","viewtaskhidden"); getValueCheckbox("addtask","addtaskhidden"); getValueCheckbox("edittask","edittaskhidden"); getValueCheckbox("viewknowledge","viewknowledgehidden"); getValueCheckbox("addknowledge","addknowledgehidden"); getValueCheckbox("editknowledge","editknowledgehidden"); getValueCheckbox("viewpermission","viewpermissionhidden"); $.ajax({ url: '<?php echo base_url().'groupuser/updategroup' ?>', type: 'POST', dataType: 'JSON', // data: {groupid:groupid,ticketrule:ticketrule,taskrule:taskrule,userrule:userrule,knowledgerule:knowledgerule,status:status}, data : $('#dataUpdateGroup').serialize(), }) .done(function(data) { if(data.code==1){ $('#btn-uploadgu').prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); window.location.reload(); }else{ alert(data.message); } }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); } function getValueCheckbox(name,namehidden) { if(document.getElementById(name).checked) { document.getElementById(namehidden).disabled = true; } } </script><file_sep><main class="app-content padding-5 no-padding-right"> <!-- <div class="row"> <div class="col-md-2 col-md-18 no-padding padding-left-10"> </div> <div class="col-md-7 col-md-64 no-padding padding-left-1"> <p> Bแบกn khรดng cรณ quyแปn truy cแบญp chแปฉc nฤƒng nร y </p> </div> <div class="col-md-2 col-md-18 no-padding padding-left-5"> </div> </div> --> <div class="sweet-alert showSweetAlert visible" data-custom-class="" data-has-cancel-button="false" data-has-confirm-button="true" data-allow-outside-click="false" data-has-done-function="false" data-animation="pop" data-timer="null" style="display: block; margin-top: -156px;"><div class="sa-icon sa-error animateErrorIcon" style="display: block;"> <span class="sa-x-mark animateXMark"> <span class="sa-line sa-left"></span> <span class="sa-line sa-right"></span> </span> </div><div class="sa-icon sa-warning" style="display: none;"> <span class="sa-body"></span> <span class="sa-dot"></span> </div><div class="sa-icon sa-info" style="display: none;"></div><div class="sa-icon sa-success" style="display: none;"> <span class="sa-line sa-tip"></span> <span class="sa-line sa-long"></span> <div class="sa-placeholder"></div> <div class="sa-fix"></div> </div><div class="sa-icon sa-custom" style="display: none;"></div><h2>Lแป—i !</h2> <?php if(isset($msg)){ ?> <p style="display: block;"><?php echo $msg; ?></p> <?php }else{ ?> <p style="display: block;">Bแบกn khรดng cรณ quyแปn truy cแบญp vร o chแปฉc nฤƒng nร y.</p> <?php }?> <fieldset> <input type="text" tabindex="3" placeholder=""> <div class="sa-input-error"></div> </fieldset><div class="sa-error-container"> <div class="icon">!</div> <p>Not valid!</p> </div><div class="sa-button-container"> <button class="cancel" tabindex="2" style="display: none; box-shadow: none;">Cancel</button> <div class="sa-confirm-button-container"> <div></div> <div></div> <div></div> </div> </div> </div></div> </main><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-12 margin-bot-10 margin-top-5 margin-left-10"> <?php echo isset($top) ? $top : ''; ?> </div> <div class="col-md-24 no-padding padding-left-15"> <?php echo isset($left) ? $left : ''; ?> </div> <div class="col-md-2 col-md-22 no-padding padding-left-5 padding-top-10 padding-right-10"> <?php echo isset($right) ? $right : ''; ?> </div> </div> </main><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Node extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url')); } public function index() { $_data = []; $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['nodejs'] = $this->load->view('node/dashboard', NULL, TRUE); $_data['mainview'] = $this->load->view('node/view', NULL , TRUE); $this->load->view('master',$_data); } public function detail(){ $_body = []; $_body['top'] = $this->load->view('user/top/ud_breadcrumb', NULL, TRUE); $_body['left'] = $this->load->view('user/left/ud_info', NULL, TRUE); $_body['right'] = $this->load->view('user/right/ud_history', NULL, TRUE); $_body['center'] = $this->load->view('user/center/ud_body', NULL, TRUE); $_data = []; $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['script'] = $this->load->view('script/script', NULL, TRUE); $_data['nodejs'] = $this->load->view('node/node', NULL, TRUE); $_data['mainview'] = $this->load->view('user/user_detail', $_body , TRUE); $this->load->view('master',$_data); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Call extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url')); } public function getSSLPage($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSLVERSION,3); $result = curl_exec($ch); curl_close($ch); return $result; } public function index() { $mitek_url = 'https://api-popupcontact-02.mitek.vn/api/v1/call'; $secret = 'ac97db2cca493ad87045946aed59eb29'; $extension = '7101'; $phone = '0933961912'; // $json = $this->getSSLPage($mitek_url.'/clicktocall?secret='.$secret.'&extension='.$extension.'&phone='.$phone.''); // $json= $this->getSSLPage('https://api-popupcontact-02.mitek.vn/api/v1/call/getstatusagent?secret=ac97db2cca493ad87045946aed59eb29&extension=2300&phone=2300'); // $data['result'] = json_decode($json,TRUE); $data['result'] = $this->getSSLPage('https://api-popupcontact-02.mitek.vn/api/v1/call/clicktocall?secret=ac97db2cca493ad87045946aed59eb29&extension=2300&phone=2300'); $_data['mainview'] = $this->load->view('call/call', $data , TRUE); $this->load->view('dashboard',$_data);; } } /* End of file Call.php */ /* Location: ./application/controllers/Call.php */ ?><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Task extends CI_Controller { private $_init = []; public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url')); $this->load->model(array('M_api')); //get list of ticket id $res = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/selectticket'); $this->_init['l_ticket'] = json_decode($res,true)['data']; // get the type ticket $l_type = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/tasktype'); $this->_init['l_type'] = json_decode($l_type,true)['data']; //Kiแปƒm tra quyแปn vแป›i chแปฉc nฤƒng user $var = $this->session->userdata; $groupid = $var['groupid']; $group = $this->M_api->getlistgroup_array($groupid); $this->_init['isViewTask'] = substr($group['taskrule'], 0,1); $this->_init['isInertTask'] = substr($group['taskrule'], 1,1); $this->_init['isUpdateTask'] = substr($group['taskrule'], 2,1); } public function index() { if($this->_init['isViewTask']==0){ $_data['mainview'] = $this->load->view('404',null , TRUE); $this->load->view('dashboard',$_data); return; } $data = []; $res = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/gettask?pic='.$this->session->userdata('custid').'&tic='.$this->session->userdata('groupid')); $data['record'] = json_decode($res,true)['data']; $_data = []; $_data['script'] = $this->load->view('task/s_task', null, TRUE); $_data['mainview'] = $this->load->view('task/task', $data , TRUE); $this->load->view('dashboard',$_data); } public function create() { $data = []; $data['l_ticket'] = $this->_init['l_ticket']; $data['l_type'] = $this->_init['l_type']; $l_detail = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/taskdetail'); $data['l_detail'] = json_decode($l_detail,true)['data']; $list_user = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyroleid/3'); $data['l_cus'] = json_decode($list_user,true)['data']; $list_user = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyroleid/2'); $data['l_age'] = json_decode($list_user,true)['data']; //group agent $_jsongroup = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/group'); $data['l_agentgroup'] = json_decode($_jsongroup,true)['data']; $_data = []; $_data['script'] = $this->load->view('task/s_insert', null, TRUE); $_data['mainview'] = $this->load->view('task/new', $data , TRUE); $this->load->view('dashboard',$_data); } public function detail($taskid) { if($this->_init['isViewTask']==0){ $_data['mainview'] = $this->load->view('404',null , TRUE); $this->load->view('dashboard',$_data); return; } $data = []; $data['l_ticket'] = $this->_init['l_ticket']; $data['l_type'] = $this->_init['l_type']; //group agent $_jsongroup = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/group'); $data['l_agentgroup'] = json_decode($_jsongroup,true)['data']; $l_detail = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/taskdetail'); $data['l_detail'] = json_decode($l_detail,true)['data']; $list_user = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyroleid/3'); $data['l_cus'] = json_decode($list_user,true)['data']; $list_user = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyroleid/2'); $data['l_age'] = json_decode($list_user,true)['data']; $res = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/select/'.$taskid); $data['record'] = json_decode($res,true)['data']; $res = file_get_contents('http://test.tavicosoft.com/crm/index.php/taskdetail/select/'.$taskid); $data['comment'] = json_decode($res,true)['data']; // var_dump($data); $_data = []; $_data['script'] = $this->load->view('task/s_update', null, TRUE); $_data['mainview'] = $this->load->view('task/detail', $data , TRUE); $this->load->view('dashboard',$_data); } public function de_tail($recordid) { $data = []; $data['l_ticket'] = $this->_init['l_ticket']; $data['l_type'] = $this->_init['l_type']; $list_user = json_decode($this->M_api->getlistcustomer(0),true); $data['l_cus'] = $list_user['data']; $res = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/gettask?recordid='.$recordid); $data['record'] = json_decode($res,true)['data']; $res = file_get_contents('http://test.tavicosoft.com/crm/index.php/taskdetail/select/'.$data['record'][0]['taskid']); $data['comment'] = json_decode($res,true)['data']; // var_dump($data); $_data = []; $_data['script'] = $this->load->view('task/s_update', null, TRUE); $_data['mainview'] = $this->load->view('task/detail', $data , TRUE); $this->load->view('dashboard',$_data); } public function ticket() { $_data = []; $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['mainview'] = $this->load->view('task/ticket', NULL , TRUE); $this->load->view('master',$_data); } public function aj_api_insert(){ $post = $this->input->post(); //var_dump($post); $var = $this->session->userdata; $log_groupid = $var['groupid']; $req_data = []; $taskid = $req_data['taskid'] = $this->M_api->gen_taskid(); //Dnah cho phรขn quyแปn $req_data['log_groupid'] = $log_groupid; $req_data['status'] = isset($post['status'])?$post['status']:'O'; $req_data['taskmaster'] = isset($post['taskmaster'])?$post['taskmaster']:''; $req_data['pic'] = isset($post['pic'])?$post['pic']:''; $req_data['tic'] = isset($post['tic'])?$post['tic']:''; $req_data['ticketid'] = isset($post['ticketid'])?$post['ticketid']:''; $req_data['tasktype'] = isset($post['tasktype'])?$post['tasktype']:''; $req_data['requestdate'] = isset($post['req_date'])?date('Y-m-d H:i:s',strtotime($post['req_date'])):''; $req_data['sla'] = isset($post['ola_date'])?date('Y-m-d H:i:s',strtotime($post['ola_date'])):''; $req_data['duedate'] = isset($post['due_date'])?date('Y-m-d H:i:s',strtotime($post['due_date'])):''; $req_data['priority'] = isset($post['priority'])?$post['priority']:''; $req_data['severity'] = isset($post['severity'])?$post['severity']:''; $req_data['finishdate'] = isset($post['fns_date'])?date('Y-m-d H:i:s',strtotime($post['fns_date'])):''; $req_data['title'] = isset($post['title'])?$post['title']:''; $req_data['createdby'] = isset($var['custid'])?$var['custid']:''; $req_data['statusnote'] = isset($post['statusnote'])?$post['statusnote']:''; $req_data['taskdetail'] = isset($post['taskdetail'])?$post['taskdetail']:''; // var_dump($req_data); $postdata = http_build_query($req_data); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/insert',false,$context); $_res = json_decode($result,true); if (isset($_res['code']) && $_res['code'] == 1 && isset($post['cmt']) && $post['cmt'] !='') { $log['taskid'] = $taskid; $log['tvcdb'] = "AGT"; $log['tskaction'] = ""; $log['comments'] = $post['cmt']; $log['avatar'] = isset($post['avatar'])?$post['avatar']:''; $log['changelog'] = ''; $log['createdby'] = isset($var['custid'])?$var['custid']:''; $_result = $this->task_log($log); } echo $result; } public function aj_api_update(){ $post = $this->input->post(); $var = $this->session->userdata; $log_groupid = $var['groupid']; $req_data = []; $taskid = isset($post['taskid'])?$post['taskid']:''; //Dnah cho phรขn quyแปn $req_data['log_groupid'] = $log_groupid; $req_data['status'] = isset($post['status'])?$post['status']:'O'; $req_data['taskmaster'] = isset($post['taskmaster'])?$post['taskmaster']:''; $req_data['pic'] = isset($post['pic'])?$post['pic']:''; $req_data['tic'] = isset($post['tic'])?$post['tic']:''; $req_data['ticketid'] = isset($post['ticketid'])?$post['ticketid']:''; $req_data['tasktype'] = isset($post['tasktype'])?$post['tasktype']:''; $req_data['requestdate'] = isset($post['req_date'])?date('Y-m-d H:i:s',strtotime($post['req_date'])):''; $req_data['sla'] = isset($post['ola_date'])?date('Y-m-d H:i:s',strtotime($post['ola_date'])):''; $req_data['duedate'] = isset($post['due_date'])?date('Y-m-d H:i:s',strtotime($post['due_date'])):''; $req_data['priority'] = isset($post['priority'])?$post['priority']:''; $req_data['severity'] = isset($post['severity'])?$post['severity']:''; $req_data['finishdate'] = isset($post['fns_date'])?date('Y-m-d H:i:s',strtotime($post['fns_date'])):''; $req_data['title'] = isset($post['title'])?$post['title']:''; $req_data['statusnote'] = isset($post['statusnote'])?$post['statusnote']:''; $req_data['taskdetail'] = isset($post['taskdetail'])?$post['taskdetail']:''; // $req_data['createdby'] = isset($var['custid'])?$var['custid']:''; // var_dump($req_data); if ($req_data['ticketid']=="") { $req_data['ticketid']="0"; } // var_dump($req_data); $postdata = http_build_query($req_data); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/update/'.$taskid,false,$context); $_res = json_decode($result,true); if (isset($_res['code']) && $_res['code'] == 1 && ( (isset($post['changelog'])&&$post['changelog']!='')||(isset($post['cmt'])&&$post['cmt']!='') ) ) { $log['taskid'] = $taskid; $log['tskaction'] = isset($post['action'])?$post['action']:"Cแบญp nhแบญt cรดng viแป‡c"; $log['comments'] = isset($post['cmt'])?$post['cmt']:''; if ($log['comments']!='') { $log['tskaction'] = ''; } $log['avatar'] = isset($post['avatar'])?$post['avatar']:''; $log['changelog'] = isset($post['changelog'])?$post['changelog']:''; $log['createdby'] = isset($var['custid'])?$var['custid']:''; $_result = $this->task_log($log); } echo $result; } public function get_to_my_task($taskid){ $var = $this->session->userdata; $log_groupid = $var['groupid']; $task = []; //Danh cho phรขn quyแปn $task['log_groupid'] = $log_groupid; $task['pic'] = $this->session->userdata['custid']; $task['tic'] = $this->session->userdata['groupid']; $task['status'] = 'W'; $postdata = http_build_query($task); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/update/'.$taskid,false,$context); echo $result; $_res = json_decode($result,true); if (isset($_res['code']) && $_res['code'] == 1) { $log['taskid'] = $taskid; $log['tskaction'] = "Tiแบฟp nhแบญn cรดng viแป‡c."; $log['comments'] = ''; $log['avatar'] = $this->session->userdata('avatar'); $log['changelog'] = 'Phแปฅ trรกch: '.$this->session->userdata('custname').' | Trแบกng thรกi: ฤang xแปญ lรฝ |'; $log['createdby'] = $this->session->userdata('custid');; $_result = $this->task_log($log); // echo $_result; } } private function task_log($log){ $postdata = http_build_query($log); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/taskdetail/insert',false,$context); return $result; } }<file_sep><div class="tile height-1024"> <div class="content-title"> <div class="div"> <h5>Nhรณm Ngฦฐแปi dรนng</h5> </div> </div> <p class="margin-top-10 no-margin-bot">Nhรณm ngฦฐแปi dรนng giรบp phรขn quyแปn vแป cรกc chแปฉc nฤƒng trong hแป‡ thแป‘ng bao gแป“m quyแปn Xem hoแบทc Sแปญa, ngoร i ra viแป‡c phรขn nhรณm ngฦฐแปi dรนng cรฒn hแป— trแปฃ cho cรกc bรกo cรกo vแป hiแป‡u quแบฃ cรดng viแป‡c theo nhรณm. Viแป‡c phแบฃn hแป“i ngฦฐแปi dรนng.</p> <div class="row" style="margin-top: 50px;"> <div class="col-md-5"> <span><b>Nhรณm ngฦฐแปi dรนng hiแป‡n tแบกi trong hแป‡ thแป‘ng</b></span> </div> <div class="col-md-7"> <div style="float: right;"> <button type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right" onclick="addTab('<?php echo base_url()?>groupuser/viewInsertGroup','Thรชm nhรณm ngฦฐแปi dรนng')">Thรชm</button> </div> </div> </div> <div class="bs-component margin-top-10"> <div class="table-responsive"> <table class="table" id="table-1"> <thead class="no-border-top"> <tr> <th><b>Nhรณm</b></th> <th><b>Thร nh viรชn nhรณm</b></th> <th><b>Quyแปn cแปงa nhรณm</b></th> <th><b>Trแบกng thรกi</b></th> </tr> </thead> <tbody> <?php foreach ($listgroup as $group) { ?> <tr> <td><a style="cursor: pointer;" class="user-name" onclick="addTab('<?php echo base_url()?>groupuser/groupuserdetail?groupid=<?php echo $group['groupid']; ?>','<?php echo $group['groupname']; ?>')"><?php echo $group['groupname'];?></a></td> <?php $totalPeople = '0 Ngฦฐแปi'; foreach ($countPeople as $count) { if($count['groupid'] == $group['groupid']) { $totalPeople = $count['total'].' Ngฦฐแปi'; break; } else { $totalPeople = '0 Ngฦฐแปi'; } } ?> <td id="countpeople"> <?php echo $totalPeople ?> </td> <td> <!-- <?php if($group['ticketrule']==1){ echo 'Xem/Sแปญa yรชu cแบงu phiแบฟu<br>'; }?> <?php if($group['userrule']==1){ echo 'Xem/Sแปญa ngฦฐแปi dรนng<br>'; }?> <?php if($group['taskrule']==1){ echo 'Xem/Sแปญa cรดng viแป‡c<br>'; }?> <?php if($group['knowledgerule']==1){ echo 'Xem/Sแปญa thฦฐ viแป‡n kiแบฟn thแปฉc'; }?> --> <?php if(strpos($group['ticketrule'],'1') !== false) { $ruleticket = changTitle(0,substr($group['ticketrule'], 0,1))." ".changTitle(1,substr($group['ticketrule'], 1,1))." ".changTitle(2,substr($group['ticketrule'], 2,1))." Phiแบฟu</br>"; }else{$ruleticket = "";} if(strpos($group['userrule'],'1') !== false) { $ruleuser = changTitle(0,substr($group['userrule'], 0,1))." ".changTitle(1,substr($group['userrule'], 1,1))." ".changTitle(2,substr($group['userrule'], 2,1))." Ngฦฐแปi dรนng</br>"; }else{$ruleuser = "";} if(strpos($group['taskrule'],'1') !== false) { $ruletask = changTitle(0,substr($group['taskrule'], 0,1))." ".changTitle(1,substr($group['taskrule'], 1,1))." ".changTitle(2,substr($group['taskrule'], 2,1))." Cรดng viแป‡c</br>"; }else{$ruletask = "";} if(strpos($group['knowledgerule'],'1') !== false) { $ruleknowledge = changTitle(0,substr($group['knowledgerule'], 0,1))." ".changTitle(1,substr($group['knowledgerule'], 1,1))." ".changTitle(2,substr($group['knowledgerule'], 2,1))." Thฦฐ viแป‡n</br>"; }else{$ruleknowledge = "";} echo $ruleticket. $ruleuser. $ruletask. $ruleknowledge; ?> </td> <td><?php if($group['status']==1){ echo 'ฤang hoแบกt ฤ‘แป™ng'; }else{echo 'Khรดng hoแบกt ฤ‘แป™ng';}?></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <?php function changTitle($position,$rule) { if($rule == 1 && $position == 0) { return "Xem"; } else if($rule ==1 && $position == 1) { return "Thรชm"; } else if($rule ==1 && $position == 2) { return "Xoรก"; } else{ return ""; } } ?><file_sep>#!/bin/bash /usr/bin/pm2 start ~/callevent/server.js <file_sep><form id="form-ticket"> <div class="tile p-0 padding-5 margin-bot-5 z-index-100"> <div class="tile-body padding-left-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngฦฐแปi yรชu cแบงu(<span style="color: red;">*</span>)</label> <label class="control-label col-md-8 no-padding-right"> <input disabled class="col-md-12 no-padding font-size-12" value="<?php echo $ticket['data'][0]['custname'];?>"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngฦฐแปi tแบกo(<span style="color: red;">*</span>)</label> <label class="control-label col-md-8 no-padding-right"> <input disabled="" class="col-md-12 no-padding font-size-12" value="<?php echo $ticket['data'][0]['agentcreatedname'];?>"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Nhรณm phแปฅ trรกch(<span style="color: blue;">*</span>)</label> <select name="agentgroup" data-placeholder="Chแปn nhรณm phแปฅ trรกch..." log="Nhรณm phแปฅ trรกch" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control my-chosen" old-value="<?php echo($ticket['data'][0]['agentgroup'])?>"> <option value=""></option> <?php if (isset($l_agentgroup) && !empty($l_agentgroup)) { foreach ($l_agentgroup as $key => $value) { $sel = ''; if ($value['groupid']==$ticket['data'][0]['agentgroup']) { $sel = 'selected'; } echo '<option '.$sel.' value="'.$value['groupid'].'">'.$value['groupname'].'</option>'; } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Phแปฅ trรกch(<span style="color: blue;">*</span>)</label> <select data-placeholder="Chแปn ngฦฐแปi phแปฅ trรกch..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen crm-control" name="agentcurrent" log="Phแปฅ trรกch" old-value="<?php echo($ticket['data'][0]['agentcurrent'])?>"> <option value=""></option> <?php if (isset($l_age)) { foreach ($l_age as $cus) { if ($cus['custname']!='') { $s=''; if ($ticket['data'][0]['agentcurrent']==$cus['custid']) { $s='selected'; } echo('<option '.$s.' value="'.$cus['custid'].'" data-group="'.$cus['groupid'].'">'.$cus['custname'].'</option>'); } } } ?> </select> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Nguแป“n phiแบฟu</label> <select name="ticketchannel" log="Nguแป“n phiแบฟu" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="ticketchannel" old-value="<?php echo($ticket['data'][0]['ticketchannel'])?>"> <option value="1" <?php if($ticket['data'][0]['ticketchannel']==1){echo "selected";} ?>>Trแปฑc tiแบฟp</option> <option value="2" <?php if($ticket['data'][0]['ticketchannel']==2){echo "selected";} ?>>ฤiแป‡n thoแบกi</option> <option value="3" <?php if($ticket['data'][0]['ticketchannel']==3){echo "selected";} ?>>Email</option> <option value="4" <?php if($ticket['data'][0]['ticketchannel']==4){echo "selected";} ?>>Chat</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Mแปฉc ฦฏu tiรชn</label> <select name="priority" log="Mแปฉc ฦฐu tiรชn" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="priority" old-value="<?php echo($ticket['data'][0]['priority'])?>"> <option value="1" <?php if($ticket['data'][0]['priority']==1){echo "selected";} ?>>Thฦฐแปng</option> <option value="2" <?php if($ticket['data'][0]['priority']==2){echo "selected";} ?>>Cao</option> <option value="3" <?php if($ticket['data'][0]['priority']==3){echo "selected";} ?>>Khแบฉn cแบฅp</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Tรฌnh trแบกng</label> <select name="ticketstatus" log="Tรฌnh trแบกng" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="ticketstatus" old-value="<?php echo($ticket['data'][0]['status'])?>"> <option value="1" <?php if($ticket['data'][0]['status']==1){echo "selected";} ?>>Tแบกo mแป›i</option> <option value="0" <?php if($ticket['data'][0]['status']==0){echo "selected";} ?>>ฤang xแปญ lรฝ</option> <option value="4" <?php if($ticket['data'][0]['status']==4){echo "selected";} ?>>Hoร n thร nh</option> <option value="9" <?php if($ticket['data'][0]['status']==9){echo "selected";} ?>>Hแปงy</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Giai ฤ‘oแบกn</label> <select name="levelticket" log="Giai ฤ‘oแบกn" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="levelticket" old-value="<?php echo($ticket['data'][0]['levelticket'])?>"> <?php if (isset($l_stage) && !empty($l_stage)) { foreach ($l_stage as $key => $value) { $sel = ''; if (isset($ticket['data'][0]['levelticket']) && $value['code']==$ticket['data'][0]['levelticket']) { $sel = 'selected'; } echo '<option '.$sel.' value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Phรขn loแบกi</label> <select name="tickettype" log="Phรขn loแบกi" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="level_1" old-value="<?php echo($ticket['data'][0]['tickettype'])?>"> <?php if (isset($l_type) && !empty($l_type)) { foreach ($l_type as $key => $value) { $sel = ''; if (isset($ticket['data'][0]['tickettype']) && $value['code']==$ticket['data'][0]['tickettype']) { $sel = 'selected'; } echo '<option '.$sel.' value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Nhรณm vแบฅn ฤ‘แป</label> <select name="groupid" log="Nhรณm vแบฅn ฤ‘แป" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="level_2" value="" old-value="<?php echo($ticket['data'][0]['groupid'])?>"> <?php if (isset($l_group) && !empty($l_group)) { foreach ($l_group as $key => $value) { $sel = ''; if (isset($ticket['data'][0]['groupid']) && $value['code']==$ticket['data'][0]['groupid']) { $sel = 'selected'; } echo '<option '.$sel.' ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Chi tiแบฟt Vฤ</label> <select name="categoryid" id="level_3" log="Chi tiแบฟt Vฤ" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" old-value="<?php echo($ticket['data'][0]['categoryid'])?>"> <?php if (isset($l_cate) && !empty($l_cate)) { foreach ($l_cate as $key => $value) { $sel = ''; if (isset($ticket['data'][0]['categoryid']) && $value['code']==$ticket['data'][0]['categoryid']) { $sel = 'selected'; } echo '<option '.$sel.' ref1="'.$value['ref1'].'" ref2="'.$value['ref2'].'" value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class="break-line margin-bot-5"></div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngร y yรชu cแบงu</label> <label class="control-label col-md-8 no-padding-right"> <input name="requestdate" log="Ngร y yรชu cแบงu" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii" value="<?php echo isset($ticket['data'][0]['requestdate'])?date("d-m-Y H:i", strtotime($ticket['data'][0]['requestdate'])):'';?>" old-value="<?php echo date("d-m-Y H:i", strtotime($ticket['data'][0]['requestdate']));?>"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngร y phแบฃn hแป“i</label> <label class="control-label col-md-8 no-padding-right"> <input name="firstreply" log="Ngร y phแบฃn hแป“i" id="lastupdate" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii" value="<?php echo isset($ticket['data'][0]['firstreply'])?date("d-m-Y H:i", strtotime($ticket['data'][0]['firstreply'])):'';?>" old-value="<?php echo date("d-m-Y H:i", strtotime($ticket['data'][0]['firstreply']));?>"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Thแปi hแบกn SLA</label> <label class="control-label col-md-8 no-padding-right"> <input name="sla" log="Thแปi hแบกn SLA" id="sla" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii" value="<?php echo isset($ticket['data'][0]['sla'])?date("d-m-Y H:i", strtotime($ticket['data'][0]['sla'])):'';?>" old-value="<?php echo date("d-m-Y H:i", strtotime($ticket['data'][0]['sla']));?>"> </label> </div> <div class="break-line margin-bot-5"></div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngร y hแบนn</label> <label class="control-label col-md-8 no-padding-right"> <input name="duedate" log="Ngร y hแบนn" id="duedate" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii" value="<?php echo isset($ticket['data'][0]['duedate'])?date("d-m-Y H:i", strtotime($ticket['data'][0]['duedate'])):'';?>" old-value="<?php echo date("d-m-Y H:i", strtotime($ticket['data'][0]['duedate']));?>"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngร y hoร n thร nh</label> <label class="control-label col-md-8 no-padding-right"> <input name="finishdate" log="Ngร y hoร n thร nh" id="finishdate" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii" value="<?php echo isset($ticket['data'][0]['finishdate'])?date("d-m-Y H:i",strtotime($ticket['data'][0]['finishdate'])):'';?>" old-value="<?php echo date("d-m-Y H:i", strtotime($ticket['data'][0]['finishdate']));?>"> </label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Mรฃ giao dแป‹ch</label> <label class="control-label col-md-8 no-padding-right"> <input name="transref" log="Mรฃ giao dแป‹ch" class="col-md-12 no-padding font-size-12 crm-control" placeholder="" value="<?php echo $ticket['data'][0]['transref'];?>"> </label> </div> <div class="break-line margin-bot-5"></div> <?php if (isset($l_ext)) { foreach ($l_ext as $key => $value) { $f = isset($value['fieldcode'])?$value['fieldcode']:''; $n = isset($value['fieldname'])?$value['fieldname']:''; $v = isset($extinfo[$value['fieldcode']])?$extinfo[$value['fieldcode']]:''; $d = '<div class="flex"> <label class="control-label user-label col-md-4 no-padding">'.$n.'</label>'; if (isset($value['fieldtype']) && $value['fieldtype']=='T') { $d.=' <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12 crm-ext" log="'.$n.'" value="'.$v.'" old-value="'.$v.'" name="ext['.$f.']"> </label> '; }elseif(isset($value['fieldtype']) && $value['fieldtype']=='D'){ $d.='<select class="control-label col-md-8 no-border no-padding margin-left-10 crm-ext" log="'.$n.'" old-value="'.$v.'" name="ext['.$f.']">'; if (isset($value['datasource']) && isset($l_dtsrc)) { foreach ($l_dtsrc as $ky => $vl) { if ($vl['category'] == $value['datasource']) { $sel = ''; if ($v==$vl['code']) { $sel = 'selected'; } $d.='<option '.$sel.' value="'.$vl['code'].'">'.$vl['name'].'</option>'; } } }else{ $d.='<option>(Dแปฏ liแป‡u bแป‹ lแป—i)</option>'; } $d.='</select>'; }else{ $d.='<label>ฤang cแบญp nhแบญt</label>'; } $d.='</div>'; echo ($d); } } ?> </div> </div> <div class="content-title user-history user-support" style="bottom:inherit"> <p>Hแป— trแปฃ cho phiแบฟu:</p> <input type="hidden" name="ticketusers" value="<?php echo $ticketdetail['ticketusers'];?>"/> <div class="div margin-left-10"> <?php if (isset($userssuppot))foreach ($userssuppot as $item_user) {?> <a class="buttonsearchiframe" onclick="addTab('<?php echo base_url()."user/detail/?cusid=".$item_user['custid']."&idcard=".$item_user['idcard']."&roleid=".$item_user['roleid']?>','<?php echo $item_user['custname'] ?>')" href="#" title=""><img class="user-avatar" src="<?php echo $item_user['avatar']?>" alt="User Image" title="<?php echo $item_user['custname'] ?>"></a> <?php } ?> </div> </div> <!-- <button type="button" class="btn btn-gray margin-top-5 float-right" onclick="fillExtTicket()"> Ghi nhแบญn </button> --><file_sep><script type="text/javascript"> $(document).ready(function(){ $('a.dropdown-item:first').trigger('click'); var h = $('table.dataTable').find('tfoot'); var _a = h.attr('status-a'); $('label#_a').html(_a); var _o = h.attr('status-o'); $('label#_o').html(_o); var _w = h.attr('status-w'); $('label#_w').html(_w); var _c = h.attr('status-c'); $('label#_c').html(_c); var _ga = h.attr('status-ga'); $('label#_ga').html(_ga); var _go = h.attr('status-go'); $('label#_go').html(_go); }); var table = $('#table-1').DataTable({ "paging": true, "language": { "paginate": { "previous": "Trฦฐแป›c", "next":"Sau" } }, "columnDefs": [ { "targets": 5, "visible": true, "searchable": true }, { "targets": 6, "visible": true, "searchable": true } ], "ordering": false, "info": false, "searching": true, "search": {regex: true}, "scrollY": "100%", "bLengthChange": false, "iDisplayLength": 25, "scrollCollapse": true }); $('a.dropdown-item').click(function(){ var type = $(this).find('label').attr('id'); var str = $(this).find('p').text(); // console.log(str); $('#_type').html(str.replace(/[0-9]/g, '')); // $('#_all').html($(this).find('label').html()+" Cรดng viแป‡c"); table.columns().search("").draw(); switch (type){ case '_o': table.columns(4).search("Chแป xรกc nhแบญn").columns(6).search('<?php echo($this->session->userdata('custid'))?>').draw(); break; case '_w': table.columns(4).search("ฤang xแปญ lรฝ").columns(6).search('<?php echo($this->session->userdata('custid'))?>').draw(); break; case '_c': table.columns(4).search("Hoร n thร nh").columns(6).search('<?php echo($this->session->userdata('custid'))?>').draw(); break; case '_a': table.columns(6).search('<?php echo($this->session->userdata('custid'))?>').draw(); break; case '_ga': table.columns(5).search('<?php echo($this->session->userdata('groupid'))?>').draw(); break; case '_go': table.columns(5).search('<?php echo($this->session->userdata('groupid'))?>').columns(6).search('^$',true,false).draw(); break; default: break; } }); </script><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-2 col-md-18 no-padding padding-left-10"> <?php echo isset($left)?$left:'' ?> </div> <div class="col-md-7 col-md-64 no-padding padding-left-1"> <?php echo isset($center)?$center:'' ?> </div> <div class="col-md-2 col-md-18 no-padding padding-left-5"> <?php echo isset($right)?$right:'' ?> </div> </div> </main><file_sep><script type="text/javascript"> function showNewTab(sdt) { var id = window.top.$(".nav-tabs").children().length; var ulChildren = window.top.$(".nav-tabs").children(); var link = '<?php echo base_url().'user/detail' ?>+sdt'; var title = sdt; var checkLink = false; for(var i = 0; i < id ;i++) { if(ulChildren[i].children[0].nodeName.toLowerCase() === 'a'){ if(title == ulChildren[i].children[0].title) { checkLink = true; var j = i+1; window.top.$('.nav-tabs li:nth-child(' + j + ') a').click(); break; } } } if(checkLink == true) { return; } else { window.top.$( ".nav-link" ).removeClass( "active" ); window.top.$( ".tab-pane" ).removeClass( "active" ); //think about it ;) window.top.$('.nav-menu li:last-child').after('<li class="nav-item ">\ <a class="nav-link active show" role="tab" data-toggle="tab" href="#tab'+id+'" title="'+title+'" >\ <i class="fas fa-user-circle"></i> \ <span class="title_tab">'+title+'</span> </a><span class="fa fa-times-circle" aria-hidden="true"></span>\ </li>'); window.top.$('.tab-content').append('<div class="tab-pane active" id="tab' + id + '"><iframe id="myiframe1" class="myiframe" name="myiframe'+id+'" src="'+link+'" frameborder="0"></iframe></div>'); var i = id+1; window.top.$('.nav-tabs li:nth-child(' + i + ') a').click(); // window.top.document.getElementById("myiframe1").src = $(this).attr('title'); } } </script><file_sep><script type="text/javascript"> $(document).ready(function(){ $('.div-recent-ticket,.div-contract').css('display','none'); $('input[name=sla],input[name=duedate],input[name=finishdate],input[name=firstreply],input[name=requestdate]'). datetimepicker({format:'d-m-Y H:i'}); var tickettype = $('select[name=tickettype]').val(); if (tickettype!='') { $('select[name=groupid] option').each(function(){ var ref1 = $(this).attr('ref1'); if (ref1==tickettype) {$(this).removeClass('hide').addClass('show');} else{$(this).addClass('hide').removeClass('show');} }); } var groupid = $('select[name=groupid]').val(); if (groupid!='') { $('select[name=categoryid] option').each(function(){ var ref2 = $(this).attr('ref2'); if (ref2==groupid) {$(this).removeClass('hide').addClass('show');} else{$(this).addClass('hide').removeClass('show');} }); } $('select#level_1').change(function(){ var val = $(this).val(); if(val){ search('',val,'',''); $('select#level_2 option, select#level_3 option').each(function(){ var ref1 = $(this).attr('ref1'); if (ref1==val) { $(this).removeClass('hide').addClass('show'); }else{ $(this).addClass('hide').removeClass('show'); } }); }else{ $('select#level_2 option, select#level_3 option').each(function(){ $(this).removeClass('hide').addClass('show'); }); } $('select#level_2 option.show:first').prop('selected',true); $('select#level_3 option.show:first').prop('selected',true); }); $('select#level_2').change(function(){ var val = $(this).val(); if(val){ search('','',val,''); $('select#level_3 option').each(function(){ var ref2 = $(this).attr('ref2'); if (ref2==val) { $(this).removeClass('hide').addClass('show'); }else{ $(this).addClass('hide').removeClass('show'); } }); }else{ $('select#level_3 option').each(function(){ $(this).removeClass('hide').addClass('show'); }); } $('select#level_3 option.show:first').prop('selected',true); }); $('select#level_3').change(function(){ var val = $(this).val(); if (val) {search('','','',val);} }); $('.my-chosen').chosen({ width:'105%', disable_search_threshold: 9, no_results_text: "Khรดng tรฌm thแบฅy: ", allow_single_deselect: true }); $('select[name=agentgroup]').change(function(){ var val = $(this).val(); if(val){ $('select[name=agentcurrent] option').each(function(){ var group = $(this).attr('data-group'); if (val==group) {$(this).prop('disabled',false);} else{$(this).prop('disabled',true);} }); $('select[name=agentcurrent] option:disabled(not):first').prop('selected',true); }else{ $('select[name=agentcurrent] option').each(function(){ $(this).prop('disabled',false); }); } $('.my-chosen').trigger('chosen:updated'); }); }); $('#form-ticket').on('submit',function(){ var formData = new FormData($(this)[0]); var error = []; for (var [key, value] of formData.entries()) { // console.log(key, value); switch(key){ case 'customer': if (value=='') { error[key] = "1"; parent.alertLog('Cแบฃnh bรกo','Vui lรฒng chแปn ngฦฐแปi yรชu cแบงu.','warning'); } break; case 'agentgroup': if (value=='' && formData.get('agentcurrent') == '') { error[key] = '1'; parent.alertLog('Cแบฃnh bรกo','Bแบกn phแบฃi nhแบญp 1 trong 2 thรดng tin: Nhรณm phแปฅ trรกch, Ngฦฐแปi phแปฅ trรกch.','warning'); }else if (value=='' && formData.get('agentcurrent') !='') { var agent = $('select[name=agentcurrent]').find('option:selected').attr('data-group'); console.log(agent); if (agent) {formData.set('agentgroup',agent)} } break; default: break; } } if (!jQuery.isEmptyObject(error)) { var msg = ''; for (let key in error){ msg+= error[key]+"\n"; } console.log(msg); }else{ $('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner'); $.ajax({ type: "POST", url: "<?php echo base_url().'ticket/aj_insert_ticket';?>", data: formData, dataType:'json', contentType: false, cache: false, processData:false, beforeSend: function() { }, success: function(data) { if(data.code==0){ $('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); parent.alertLog("Cแบฃnh bรกo !", data.message, "warning"); }else{ // alert("thรชm thร nh cรดng."); parent.alertLog("Thร nh cรดng !", "Thรชm phiแบฟu thร nh cรดng.", "success"); var tab = window.top.$('div.tab-pane.active').attr('id'); window.top.$('li a.nav-link[href="#'+tab+'"]').find('span').html('#'+data.data); location.href= '<?php echo base_url().'/ticket/detail/';?>'+data.data; } }, error: function(xhr, status, error) { console.log(error); $(this).prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); } }); } return false; }); function showDetailKnowledge(id){ var show = $('.knl-caret'); if (show.hasClass('fa-angle-double-up')) {$('.knl-caret').trigger('click');} $('#knl_list').css('display','none'); $('.knl-content').html("ฤang tแบฃi dแปฏ liแป‡u...").css('display','block'); $.ajax({ url: '<?php echo base_url().'knowledge/detailKnowledge' ?>', type: 'POST', dataType: 'JSON', data: {id:id}, }) .done(function(data) { $('.knl-content').html(data.data[0].article).css('display','block'); }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); } </script><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-2 col-md-22 no-padding padding-left-15"> <div class="tile p-0 padding-5 margin-bot-5 height-1024"> <div class="tile-body padding-left-right-10"> <ul class="nav nav-tabs no-margin-left"> <li class="nav-item"> <a class="user-tab active show" data-toggle="tab" href="#tab-content-1">Ngฦฐแปi dรนng</a> </li> <?php $var = $this->session->userdata; if ($var['roleid'] != '1') { ?> <li class="nav-item"> <a class="user-tab" data-toggle="tab" href="#tab-content-2">Phiแบฟu</a> </li> <?php } ?> </ul> <div class="tab-content" id="myTabContent"> <div id="tab-content-1" class="tab-pane fade active show"> <div> <input onkeyup="checkKeyPressUser('search')" class="form-control margin-top-10 margin-bot-5" type="text" id="search" name="search" placeholder="Nhแบญp thรดng tin ngฦฐแปi dรนng ฤ‘แปƒ tรฌm kiแบฟm"> <p class="font-size-8 field-click-able">Tรฌm theo bแป™ lแปc</p> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Tรชn</label> <label class="control-label col-md-8 no-padding-right"> <input onkeypress="deleteTextboxSearch()" class="col-md-12 no-padding font-size-12" id="custname" placeholder="-"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">CMND</label> <label class="control-label col-md-8 no-padding-right"><input onkeypress="deleteTextboxSearch()" class="col-md-12 no-padding font-size-12" id="custid" placeholder="-"></label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">ฤiแป‡n thoแบกi</label> <label class="control-label col-md-8 no-padding-right"><input onkeypress="deleteTextboxSearch()" class="col-md-12 no-padding font-size-12" id="telephone" placeholder="-"></label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Email</label> <label class="control-label col-md-8 no-padding-right"><input onkeypress="deleteTextboxSearch()" class="col-md-12 no-padding font-size-12" id="email" placeholder ="-"></label></label> </div> <div class="break-line margin-bot-5"></div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Mรฃ cฤƒn hแป™:</label> <label class="control-label col-md-8 no-padding-right"><input onkeypress="deleteTextboxSearch()" class="col-md-12 no-padding font-size-12" id="mapping1" placeholder ="-"></label></label> </div> <div class="offset-9 margin-top-10"> <button id="search_customer" class="btn btn-primary float-right" type="button">Tรฌm kiแบฟm</button> </div> </div> <div id="tab-content-2" class="tab-pane fade"> <div> <input onkeyup="checkKeyPressTicket('searchticket')" class="form-control margin-top-10 margin-bot-5" type="text" name="searchticket" id="searchticket" placeholder="Nhแบญp tiรชu ฤ‘แป phiแบฟu ฤ‘แปƒ tรฌm kiแบฟm"> <p class="font-size-8 field-click-able">Tรฌm theo bแป™ lแปc</p> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngฦฐแปi yรชu cแบงu</label> <label class="control-label col-md-8 no-padding-right"> <input list="suggestionList" id="answerInput" placeholder="Ngฦฐแปi yรชu cแบงu" class="col-md-12 no-padding font-size-12"> <datalist id="suggestionList"> <?php foreach ($listuser as $user) { ?> <option data-value="<?php echo $user['custid']?>"><?php echo $user['custname']?></option> <?php } ?> </datalist> <input type="hidden" id="customer"> <script type="text/javascript"> document.querySelector('#answerInput').addEventListener('input', function(e) { var input = e.target, list = input.getAttribute('list'), options = document.querySelectorAll('#' + list + ' option'), hiddenInput = document.getElementById('customer'), inputValue = input.value; hiddenInput.value = inputValue; // $('#searchticket').val(''); // $('#search').val(''); for(var i = 0; i < options.length; i++) { var option = options[i]; if(option.innerText === inputValue) { hiddenInput.value = option.getAttribute('data-value'); break; }else{ hiddenInput.value=""; } } }); </script> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Phแปฅ trรกch</label> <label class="control-label col-md-8 no-padding-right"> <input list="suggestionListAgent" id="agentInput" placeholder="Ngฦฐแปi phแปฅ trรกch" class="col-md-12 no-padding font-size-12"> <datalist id="suggestionListAgent"> <?php foreach ($listagent as $user) { ?> <option data-value="<?php echo $user['custid']?>"><?php echo $user['custname']?></option> <?php } ?> </datalist> <input type="hidden" id="agentcurrent"> <script type="text/javascript"> document.querySelector('#agentInput').addEventListener('input', function(e) { var input = e.target, list = input.getAttribute('list'), options = document.querySelectorAll('#' + list + ' option'), hiddenInput = document.getElementById('agentcurrent'), inputValue = input.value; hiddenInput.value = inputValue; // $('#searchticket').val(''); // $('#search').val(''); for(var i = 0; i < options.length; i++) { var option = options[i]; if(option.innerText === inputValue) { hiddenInput.value = option.getAttribute('data-value'); break; }else{ hiddenInput.value=""; } } }); </script> </label> </div> <div class="break-line margin-bot-5"></div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Nguแป“n phiแบฟu</label> <select id="ticketchannel" onchange="deleteTextboxSearch()" class="no-border control-label col-md-8 no-padding-right"> <option value="" selected>Chแปn nguแป“n phiแบฟu</option> <option value="1">Trแปฑc tiแบฟp</option> <option value="2">ฤiแป‡n thoแบกi</option> <option value="3">Email</option> <option value="4">Chat</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Mแปฉc ฦฐu tiรชn</label> <select onchange="deleteTextboxSearch()" class="no-border control-label col-md-8 no-padding-right" id="priority" name="priority"> <option value="" selected>Chแปn mแปฉc ฦฐu tiรชn</option> <!-- <option value="0">Thแบฅp</option> --> <option value="1">Thฦฐแปng</option> <option value="2">Cao</option> <option value="3">Khแบฉn cแบฅp</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Tรฌnh trแบกng</label> <select onchange="deleteTextboxSearch()" class="no-border control-label col-md-8 no-padding-right" id="status" name="status"> <option value="" selected>Chแปn tรฌnh trแบกng</option> <option value="1">Tแบกo mแป›i</option> <option value="0">ฤang xแปญ lรฝ</option> <option value="4">Hoร n thร nh</option> </select> </div> <div class="offset-9 margin-top-10"> <button id="search_ticket" class="btn btn-primary float-right" type="button">Tรฌm kiแบฟm</button> </div> </div> </div> </div> </div> </div> <div class="frame relative" style="width: 78%;"> <iframe class="iframesearch" id="iframesearch" style="width: 100%; border: none;" src=""></iframe> <div class="absolute hide" style="width: 100%; height: 100%;"> <i class="fa fa-spinner fa-spin" style="font-size: 28px; position: absolute; top: 20%; left: 48%;"></i> </div> </div> </div> </main><file_sep><header class="app-header"> <div class="row" style="width: 100%"> <div id="lengthmenu" class="col-md-11"> <ul class="nav nav-tabs nav-menu main-nav nav-inline" role="tablist"> <?php $var = $this->session->userdata; $roleid = $var['roleid']; if($roleid == '1') { $title_first = 'Cร i ฤ‘แบทt'; $icon_first = 'fas fa-user-circle'; $link = base_url().'setting'; } else{ $title_first = 'Phiแบฟu'; $icon_first = 'fas fa-file-alt'; $link = base_url().'ticket'; } ?> <li class="nav-item width-170" role="presentation"> <a name="<?php echo $link ?>" class="nav-link active show" role="tab" data-toggle="tab" href="#1000" title="<?php echo $title_first ?>"> <i class="<?php echo $icon_first ?>"></i> <span class="title_tab"> <?php echo $title_first ?></span></a><span class="fa fas fa-times" aria-hidden="true"></span> </li> </ul> <ul class="nav-insert nav-inline"> <li class="dropdown dropdown-left" id="li-main"> <a class="nav-link" aria-expanded="false" href="#add" data-toggle="dropdown"><i class="fa fa-plus fa-lg"></i></a> <ul class="dropdown-menu settings-menu dropdown-menu-right"> <?php if ($var['roleid'] != '1') { ?> <li><a class="dropdown-item" alt="insert" onclick="addTab('<?php echo base_url().'ticket/viewInsert/' ?>','Thรชm Phiแบฟu',true)" href="#"><i class="fa fa-file-alt fa-fw"></i> Thรชm Phiแบฟu</a></li> <?php } ?> <li><a class="dropdown-item" alt="insert" onclick="addTab('<?php echo base_url().'user/create' ?>','Thรชm KH/Ngฦฐแปi dรนng',true)" href="#"><i class="fa fa-user fa-lg"></i> Thรชm KH/Ngฦฐแปi dรนng</a></li> <li><a class="dropdown-item" alt="insert" onclick="addTab('<?php echo base_url().'task/create' ?>','Thรชm Cรดng viแป‡c',true)" href="#"><i class="fa fa-tasks fa-lg"></i> Thรชm Cรดng Viแป‡c</a></li> </ul> </li> </ul> </div> <div class="col-md-1"> <ul class="app-nav"> <li class="dropdown"> <a class="app-nav__item" href="#" data-toggle="dropdown" aria-label="Show notifications"> <span class="fa-stack fa-sm"><i class="fa fa-circle fa-stack-2x text-primary"></i><i class="fa fa-bell fa-stack-1x fa-inverse"></i></span> </a> <ul class="app-notification dropdown-menu dropdown-menu-right"> <li class="app-notification__title">You have 4 new notifications.</li> <div class="app-notification__content"> <li><a class="app-notification__item" href="javascript:;"><span class="app-notification__icon"><span class="fa-stack fa-lg"><i class="fa fa-circle fa-stack-2x text-primary"></i><i class="fa fa-envelope fa-stack-1x fa-inverse"></i></span></span> <div> <p class="app-notification__message">Lisa sent you a mail</p> <p class="app-notification__meta">2 min ago</p> </div></a></li> <li><a class="app-notification__item" href="javascript:;"><span class="app-notification__icon"><span class="fa-stack fa-lg"><i class="fa fa-circle fa-stack-2x text-danger"></i><i class="fa fa-hdd-o fa-stack-1x fa-inverse"></i></span></span> <div> <p class="app-notification__message">Mail server not working</p> <p class="app-notification__meta">5 min ago</p> </div></a></li> <li><a class="app-notification__item" href="javascript:;"><span class="app-notification__icon"><span class="fa-stack fa-lg"><i class="fa fa-circle fa-stack-2x text-success"></i><i class="fa fa-money fa-stack-1x fa-inverse"></i></span></span> <div> <p class="app-notification__message">Transaction complete</p> <p class="app-notification__meta">2 days ago</p> </div></a></li> </div> <li class="app-notification__footer"><a href="#">See all notifications.</a></li> </ul> </li> <!-- phone --> <li class="dropdown"> <a class="app-nav__item" href="#" id="dropdown-btn" aria-label="Open Profile Menu"> <span class="fa-stack fa-sm"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-phone fa-stack-1x fa-inverse"></i> </span> </a> <div id="phone-chat" class="dropdown-menu settings-menu dropdown-menu-right" extension=""> <div id="c-chanel" class="margin-left-right-5"> <label id="channel" channel="" class="control-label col-md-6 no-padding">Kรชnh thoแบกi</label> <div id="status-selection" class="active status-online"> <span class="status-circle"></span> <p>Online</p> <i class="fa fa-caret-down fa-md float-right"></i> </div> <div id="status-options" class="info-area"> <ul> <li id="status-online" class="active margin-top-5"><span class="status-circle"></span> <p>Online</p></li> <li id="status-away"><span class="status-circle"></span> <p>Away</p></li> <li id="status-busy"><span class="status-circle"></span> <p>Busy</p></li> <li id="status-offline"><span class="status-circle"></span> <p>Offline</p></li> </ul> </div> <div class="break-line margin-bot-5"></div> </div> <div id="c-phone-option" class="margin-right-5 margin-left-5"> <i class="fa fa-phone fa-md col-md-1 margin-top-3 margin-left--5 font-size-18"></i> <label class="col-md-4 no-padding">1900 8888</label> <i class="fa fa-th fa-md float-right margin-top-3" id="key-board"></i> </div> <div id="c-call-header" class="div user-call-pad hide"> <p class="phone-name" id="u-name"><img id="u-avatar" class="user-avatar phone-avatar" src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image"><NAME></p> <p id="u-phone" class="phone-num header-desc field-click-able">038 8485 4949</p> <p id="u-time" class="phone-time header-desc field-click-able">00 : 00 : 25</p> <p id="u-ticket" class="text-center margin-top--10">Phiแบฟu: #47748</p> </div> <div class="break-line margin-bot-5"></div> <div id="call-search" class="hide margin-bot-3"> <div class="search-input-group flex"> <i class="fa fa-search search-icon margin-right-5"></i> <input placeholder="Nhแบญp tรชn hoแบทc sแป‘ ฤ‘iแป‡n thoแบกi" id="user-call-search" class="width-100per" type="text"> <i class="fa fa-backspace search-destroy hide"></i> </div> </div> <div id="call-input"> <div class="info-area search-result"> <i class="fa fa-times float-right margin-right-5 margin-top-5 call-input-close icon-hover"></i> <ul id="s-rst" class="no-list-style" action="call"> <p class="type first font-size-10 no-margin">Khรกch hร ng</p> <li class="s-rst-li"> <div class="s-rst-user"> <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phแบกm</p> <p class="user-num field-click-able">01663288281</p> <span class="status"></span> </div> </li> <li class="s-rst-li"> <div class="s-rst-user"> <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phแบกm</p> <p class="user-num field-click-able">2304</p> <span class="status"></span> </div> </li> <p class="type font-size-10 no-margin">Khรกch hร ng</p> <li class="s-rst-li"> <div class="s-rst-user"> <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phแบกm</p> <p class="user-num field-click-able">2303</p> </div> </li> </ul> </div> </div> <div id="has-call-pad" class="text-center relative"> <div id="call-log" class="info-area search-result"> <!-- <p class="type first font-size-10 no-margin hide">Cuแป™c gแปi gแบงn ฤ‘รขy</p> <ul id="s-rst" class="no-list-style hide" action="call"> <li class="s-rst-li"> <div class="s-rst-user"> <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phแบกm</p> <p class="user-num field-click-able">01663288281 <span class="float-right margin-right-40">ticket: #1234</span> </p> <span class="status"></span> </div> </li> <li class="s-rst-li"> <div class="s-rst-user"> <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phแบกm</p> <p class="user-num field-click-able">01663288281 <span class="float-right margin-right-40">ticket: #1234</span> </p> <span class="status"></span> </div> </li> <li class="s-rst-li"> <div class="s-rst-user"> <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phแบกm</p> <p class="user-num field-click-able">01663288281 <span class="float-right margin-right-40">ticket: #1234</span> </p> <span class="status"></span> </div> </li> <li class="s-rst-li"> <div class="s-rst-user"> <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phแบกm</p> <p class="user-num field-click-able">01663288281 <span class="float-right margin-right-40">ticket: #1234</span> </p> <span class="status"></span> </div> </li> <li class="s-rst-li"> <div class="s-rst-user"> <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phแบกm</p> <p class="user-num field-click-able">01663288281</p> <span class="status"></span> </div> </li> <li class="s-rst-li"> <div class="s-rst-user"> <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phแบกm</p> <p class="user-num field-click-able">01663288281</p> <span class="status"></span> </div> </li> </ul> --> <div class="num-pad absolute"> <div class="span4"> <div class="num"> <div class="txt"> 1 </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 2 <span class="small"> <p> ABC</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 3 <span class="small"> <p> DEF</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 4 <span class="small"> <p> GHI</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 5 <span class="small"> <p> JKL</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 6 <span class="small"> <p> MNO</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 7 <span class="small"> <p> PQRS</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 8 <span class="small"> <p> TUV</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 9 <span class="small"> <p> WXYZ</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> * </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 0 <span class="small"> <p> +</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> # </div> </div> </div> </div> </div> <div id="num-pad" class="num-pad absolute hide"> <div class="span4"> <div class="num"> <div class="txt"> 1 </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 2 <span class="small"> <p> ABC</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 3 <span class="small"> <p> DEF</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 4 <span class="small"> <p> GHI</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 5 <span class="small"> <p> JKL</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 6 <span class="small"> <p> MNO</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 7 <span class="small"> <p> PQRS</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 8 <span class="small"> <p> TUV</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 9 <span class="small"> <p> WXYZ</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> * </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> 0 <span class="small"> <p> +</p> </span> </div> </div> </div> <div class="span4"> <div class="num"> <div class="txt"> # </div> </div> </div> </div> <p id="c-title"></p> <div class="loader"> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> <p id="c-avatar" class="margin-top-10"> <img class="user-avatar" src="" alt="User Image"> </p> <p id="c-name" class="no-margin"><NAME></p> <p id="c-number" class="field-click-able">091 234 6688</p> <p id="c-time" class="field-click-able"></p> <p id="c-record" class="field-click-able hide">00 : 00 : 00</p> <p id="c-option-1" class="font-size-8">Mแป›i: 5 - ฤang xแปญ lรฝ: 1 - ฤรณng: 2 - Liรชn quan: 0</p> <p id="c-option-2" class="font-size-8">Cuแป™c gแปi: 6 - Email: 0 - Chat: 0</p> <p id="c-ticket">Phiแบฟu: #47748</p> <div id="c-hang-up" class="col-md-12 flex margin-top-10 margin-bot-5"> <div class="col-md-4"> <div class="call-action"> <img src="<?=base_url('images/icons/1.png')?>"> </div> </div> <div class="col-md-4"> <div class="call-action"> <img src="<?=base_url('images/icons/2.png')?>"> </div> </div> <div class="col-md-4"> <div class="call-action"> <img id="direct-call" src="<?=base_url('images/icons/3.png')?>"> </div> </div> </div> <div class="clearfix"> </div> <div id="are-b-end" class="col-md-12 no-padding"> <a href="#" class="btn btn-danger btn-block flatbtn margin-top-10">Kแบฟt thรบc</a> </div> <div id="are-b-has" class="col-md-12 flex no-padding font-size-12"> <!-- <div class="col-md-6 no-padding padding-right-5"> <a id="accept-call" href="#" class="btn btn-primary btn-block flatbtn margin-top-10">Chแบฅp nhแบญn</a> </div> --> <div class="col-md-12 no-padding"> <a id="deny-call" href="#" class="btn btn-danger btn-block flatbtn margin-top-10">Tแปซ chแป‘i</a> </div> </div> <div id="are-b-call" class="col-md-12 no-padding"> <a href="#" class="btn btn-primary btn-block flatbtn margin-top-10">Gแปi</a> </div> <div id="are-b-direct" class="col-md-12 flex no-padding font-size-12"> <div class="col-md-6 no-padding padding-right-5"> <a id="deny-direct" href="#" class="btn btn-danger btn-block flatbtn margin-top-10">Hแปงy chuyแปƒn</a> </div> <div class="col-md-6 no-padding"> <a id="call-direct" href="#" class="btn btn-primary btn-block flatbtn margin-top-10">Chuyแปƒn tiแบฟp</a> </div> </div> <div id="are-b-close" class="col-md-12 no-padding hide"> <a id="close-call" href="#" class="btn btn-gray btn-block flatbtn margin-top-10">ฤรณng</a> </div> </div> </div> </li> <!-- User Menu--> <li class="dropdown"> <a class="app-nav__item" href="#" data-toggle="dropdown" aria-label="Open Profile Menu"> <?php $var1 = $this->session->userdata; $custid = $var1['custid']; $idcard = $var1['idcard']; $roleid = $var1['roleid']; ?> <img class="app-nav__user-avatar" src=" <?php $var = $this->session->userdata; if($var['avatar'] != 'null') { echo $var['avatar']; } else{ echo 'https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg';} ?>" alt="User Image"> </a> <ul class="dropdown-menu settings-menu dropdown-menu-right"> <li><a class="dropdown-item" onclick="addTab('<?php echo base_url().'user/detail/?cusid='.$custid.'&idcard='.$idcard.'&roleid='.$roleid.'&action=profile'?>','Profile')"><i class="fa fa-user fa-lg"></i> Hแป“ sฦก</a></li> <li><a class="dropdown-item" data-toggle="modal" data-target="#modalChangePass" href="#"><i class="fas fa-sync-alt fa-lg"></i></i> ฤแป•i mแบญt khแบฉu</a></li> <li><a class="dropdown-item" href="<?=base_url('login/logout')?>"><i class="fas fa-sign-out-alt fa-lg"></i> ฤฤƒng xuแบฅt</a></li> </ul> </li> </ul> </div> </div> </header> <div class="modal fade" id="modalChangePass" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">ฤแป•i mแบญt khแบฉu</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <form id="formChangePass"> <div class="modal-body"> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Mแบญt khแบฉu cลฉ: </label> <label class="control-label col-md-8 no-padding-right"> <input type="<PASSWORD>" placeholder="<PASSWORD>" id="old_pass" name="old_pass" required="" class="col-md-12 no-padding font-size-12"> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Mแบญt khแบฉu mแป›i: </label> <label class="control-label col-md-8 no-padding-right"> <input type="password" required="" placeholder="<PASSWORD>" id="new_pass" name="new_pass" class="col-md-12 no-padding font-size-12"> </label> </div> <div class="form-group"> <label class="control-label user-label col-md-3 no-padding">Xรกc nhแบญn mแบญt khแบฉu mแป›i: </label> <label class="control-label col-md-8 no-padding-right"> <input type="password" required="" placeholder="X<PASSWORD> m<PASSWORD>" id="confirm_pass" name="confirm_pass" class="col-md-12 no-padding font-size-12"> </label> </div> </div> <div class="modal-footer" style="background: #f5f5f5"> <button type="button" class="btn btn-gray-white float-right" data-dismiss="modal">ฤรณng</button> <button type="submit" class="btn btn-gray-black float-right" id="btn_changepass"><i class=""></i>ฤแป•i</button> </div> </form> </div> </div> </div><file_sep><div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-10"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Phรขn loแบกi: </label> <select name="status" class="control-label col-md-8 no-border no-padding margin-left-10" id="codictionary_typework"> <option value="-1" selected="">Tแบฅt cแบฃ</option> <?php foreach ($list_ext_type as $key) { ?> <option value="<?php echo $key['code'] ?>"><?php echo $key['name'] ?></option> <?php } ?> </select> </div> </div> </div> <div class="fc-corner-right"> <div class="fc-button-group" style="float:right"> <button type="button" onclick="changeiFrameDetailWork()" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right btn-createuser">Lแปc thรดng tin</button> </div> </div><file_sep><aside class="app-sidebar"> <div class="app-sidebar__user"><img src="<?=base_url('images/icons/agi-logo.png')?>"> <div> <p class="app-sidebar__user-name"><NAME></p> <p class="app-sidebar__user-designation">Frontend Developer</p> </div> </div> <ul class="app-menu"> <li> <a class="app-menu__item" onclick="addTab('<?= base_url('search') ?>','Tรฌm kiแบฟm')" target="myiframetext" href="#" title="" alt="search"> <img src="<?=base_url('images/icons/timkiem.png')?>"> <span class="app-menu__label">Tรฌm kiแบฟm</span> </a> </li> <?php $var = $this->session->userdata; $roleid = $var['roleid']; if($roleid == '1') { $title_first = 'Cร i ฤ‘แบทt'; $alt_first = 'setting'; $icon_first = 'fas fa-user-circle'; $link = 'setting'; } else{ $title_first = 'Phiแบฟu'; $alt_first = 'ticket'; $icon_first = 'fas fa-file-alt'; $link = 'ticket'; } ?> <?php $var = $this->session->userdata; $roleid = $var['roleid']; if($roleid != '1'){?> <li> <a class="app-menu__item active" onclick="addTab('<?= base_url($link) ?>','<?php echo $title_first ?>')" target="myiframetext" href="#"> <img src="<?=base_url('images/icons/list.png')?>"> <span class="app-menu__label">Ticket</span> </a> </li> <?php } ?> <li> <a class="app-menu__item click_navtab" onclick="addTab('<?= base_url('knowledge') ?>','Thฦฐ viแป‡n kiแบฟn thแปฉc')" target="myiframetext" href="#" alt="knowledge"> <img src="<?=base_url('images/icons/6.png')?>"> <span class="app-menu__label">Thฦฐ viแป‡n kiแบฟn thแปฉc</span> </a> </li> <li> <a class="app-menu__item click_navtab" onclick="addTab('<?= base_url('task') ?>','Cรดng viแป‡c')" target="myiframetext" href="#" alt="task"> <img src="<?=base_url('images/icons/7.png')?>"> <span class="app-menu__label">Cรดng viแป‡c</span> </a> </li> <!-- <li class="treeview"> <a class="app-menu__item" href="#" data-toggle="treeview"> <i class="app-menu__icon fa fa-edit"></i> <span class="app-menu__label">Datasource</span> <i class="treeview-indicator fa fa-angle-right"></i> </a> <ul class="treeview-menu"> <li> <a class="treeview-item" href="#" onclick="addTab('<?= base_url('datastage') ?>','Giai ฤ‘oแบกn')"> <i class="icon fa fa-circle-o"></i> Giai ฤ‘oแบกn</a> </li> <li> <a class="treeview-item" href="#" onclick="addTab('<?= base_url('issuetype') ?>','Phรขn loแบกi')"> <i class="icon fa fa-circle-o"></i> Phรขn loแบกi</a> </li> <li> <a class="treeview-item" href="#" onclick="addTab('<?= base_url('issuegroup') ?>','Nhรณm vแบฅn ฤ‘แป')"> <i class="icon fa fa-circle-o"></i> Nhรณm vแบฅn ฤ‘แป</a> </li> <li> <a class="treeview-item" href="#" onclick="addTab('<?= base_url('issuedetail') ?>','Chi tiแบฟt vแบฅn ฤ‘แป')"> <i class="icon fa fa-circle-o"></i> Chi tiแบฟt vแบฅn ฤ‘แป</a> </li> </ul> </li> --> <?php $var = $this->session->userdata; $roleid = $var['roleid']; if($roleid == '1'){?> <li> <a class="app-menu__item active click_navtab" onclick="addTab('<?= base_url($link) ?>','<?php echo $title_first ?>')" target="myiframetext" target="myiframetext" href="#" alt="<?php echo $alt_first ?>"> <img src="<?=base_url('images/icons/8.png')?>"> <span class="app-menu__label">Cร i ฤ‘แบทt</span> </a> </li> <?php } ?> </ul> </aside> <div class="app-sidebar__overlay" data-toggle="sidebar"></div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Setting extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url')); $this->load->model('M_api'); } public function index() { $_body = []; $_body['left'] = $this->load->view('user/left/ud_dashboard_left',null,TRUE); $_body['right'] = $this->load->view('user/right/ud_dashboard_right', null, TRUE); // $_body['center'] = $this->load->view('user/center/ud_dashboard_center', $data, TRUE); $_data = []; $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); $_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE); $_data['script2'] = $this->load->view('script/script_group_user', NULL, TRUE); $_data['mainview'] = $this->load->view('user/user', $_body , TRUE); $this->load->view('dashboard',$_data); } public function viewUser() { $var = $this->session->userdata(); $roleid = $var['roleid']; $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/search?roleid='.$roleid); $data['user'] = json_decode($json,TRUE)['data']; $_data = []; $_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE); $_data['script2'] = $this->load->view('script/script_group_user', NULL, TRUE); $_data['mainview'] = $this->load->view('user/center/ud_dashboard_center', $data , TRUE); $this->load->view('dashboard',$_data); } public function viewGroupUser() { $_data = []; $_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE); $_data['script2'] = $this->load->view('script/script_group_user', NULL, TRUE); $_data['mainview'] = $this->load->view('groupuser/center/gu_center_detail', null , TRUE); $this->load->view('dashboard',$_data); } public function searchUser() { $keywordPost = $this->input->post('keyword'); $keyword = urlencode($keywordPost); $_jsonSearch = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/search?roleid=1&search='.$keyword); echo $_jsonSearch; } public function getSSLPage($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSLVERSION,3); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); curl_close($ch); return $result; } } ?><file_sep><?php class M_api extends CI_Model { private $url_api_db = "http://test.tavicosoft.com/crm/index.php/api/"; private $ClientId = 'API@AGT'; private $SecurityKey = "<KEY>"; private $TvcToken = "C49D0F74-286D-4180-ABA1-D0F37685E8C4"; public function __construct() { parent::__construct(); $this->load->helper(array('date')); $this->load->driver('cache'); } public function execute_tvc_api($url,$action,$method,$data,$type="rpc",$tid="1"){ $req_data = array( "action" => $action, "method" => $method, "data" => $data, "type" => $type, "tid" => $tid ); $raw_data = json_encode($req_data); $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $raw_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json;charset=uft-8', 'ClientId: '.$this->ClientId, 'SecurityKey: '.$this->SecurityKey, 'TvcToken: '.$this->TvcToken )); // echo($raw_data); $result = curl_exec($ch); return $result; // var_dump($data_string); } public function execute_normal_api($url,$data){ $raw_data = json_encode($data); $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $raw_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json' )); // echo($raw_data); $result = curl_exec($ch); return $result; } public function gen_custid(){ $datestring = '%Y%m%d%h%i%s'; $now = time(); $time = mdate($datestring, $now); $ran = rand(100,999); return $time.$ran; } public function gen_taskid(){ $datestring = '%h%i%s'; $now = time(); $time = mdate($datestring, $now); $ran = rand(1000,9999); return $time.$ran; } public function getlistcustomer($roleid=0){ $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/getcustomerbyroleid/'.$roleid.'?pagesize=1000'); return $result; } public function getlistcustomerbygroupid($groupid=0){ $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/getcustomerbygroupid/'.$groupid.'?pagesize=1000'); return $result; } public function getlistgroup($groupid=''){ $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/selectbygroupid/'.$groupid); return $result; } public function getlistgroup_array($groupid=''){ //$result = $this->cache->memcached->get('crm_groupdetail_'.$groupid); $result = ""; if (!$result){ $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/selectbygroupid/'.$groupid); //$this->cache->memcached->save('crm_groupdetail_'.$groupid,$result, 86400); } $result_array = json_decode($result,true); if($result_array['code']==1){ if($groupid!=''){ return $result_array['data'][0]; } return $result_array['data']; }else{ return []; } } public function getListGroupCache(){ //$result = $this->cache->memcached->get('crm_group'); $result = ""; if (!$result){ $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/group'); //$this->cache->memcached->save('crm_group',$result, 86400); } return $result; } public function getTicketById($ticketid){ //$result = $this->cache->memcached->get('ticket_'.$ticketid); if (!$result){ $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/search?search=&ticketid='.$ticketid.''); $this->cache->memcached->save('ticket_'.$ticketid,$result, 86400); } return $result; } }<file_sep><?php $type = "D"; ?> <?php $ref1 = $this->input->get('ref1'); $ref2 = $this->input->get('ref2'); ?> <div class="tile height-1024"> <div class="content-title"> <div class="div"> <h5>Danh sรกch dแปฏ liแป‡u trฦฐแปng: Nhรณm chi tiแบฟt vแบฅn ฤ‘แป</h5> </div> </div> <div style="float: right;"> <button <?php if($type == 'T'){echo 'hidden';} ?> type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right" data-toggle="modal" data-target="#myModal">Thรชm</button> </div> <div class="bs-component" style="margin-top: 55px"> <?php if ($type == 'T'){ echo '<div class="component-fields"> <i class="fas fa-align-justify"></i> <span class="title_tab" style="padding-left: 6px">Text</span> </div>'; } ?> <?php if(count($list_ext)>0){ foreach ($list_ext as $value) { if(($ref1 ==-1 && $ref2 == -1) || (($value['ref1'] == $ref1 && $value['ref2'] ==$ref2) || ($value['ref1'] == $ref1 && $ref2 == -1))) { ?> <div class="component-fields" style="<?php if($value['status'] == 'C') echo ' background-color: #d88375 !important'; ?>"> <i class="<?php if($value['status'] == 'W') echo 'fas fa-align-justify'; else{echo 'fas fa-ban';} ?>" style="<?php if($value['status'] == 'C') echo 'color: #FFF;'; ?>"></i> <span class="title_tab" style="padding-left: 6px; <?php if($value['status'] == 'C') echo 'color: #FFF;'; ?> "><?php echo $value['name'] ?></span> <a class="user-name" style="cursor: pointer;float: right;<?php if($value['status'] == 'C') echo 'color: #FFF !important;'; ?>" data-toggle="modal" data-target="#modalUpdate" data-code="<?php echo $value['code'] ?>" data-category="<?php echo $value['category'] ?>" data-name="<?php echo $value['name'] ?>" data-status="<?php echo $value['status'] ?>" data-comments="<?php echo $value['comments'] ?>" data-ref1="<?php echo $value['ref1'] ?>" data-ref2="<?php echo $value['ref2'] ?>"><i class="fas fa-edit"></i></a> </div> <?php }}}?> </div> </div> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document" style="margin-top: 5%"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Dropdown Options</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class=""> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Phรขn loแบกi:</label> <select name="ref1_insert" onchange="getGroup(this,'ref2_insert')" class="control-label col-md-8 col-sm-8 no-border no-padding" id="ref1_insert"> <option value="" selected="" disabled="">Chแปn phรขn loแบกi</option> <?php foreach ($list_ext_type as $key) { ?> <option value="<?php echo $key['code'] ?>"><?php echo $key['name'] ?></option> <?php } ?> </select> </div> <div class=""> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Nhรณm vแบฅn ฤ‘แป:</label> <select name="ref2_insert" class="control-label col-md-8 col-sm-8 no-border no-padding" id="ref2_insert"> <option value="" selected="" disabled="">Chแปn nhรณm Vฤ</option> </select> </div> <div class="optionbottom"> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Mรฃ Chi tiแบฟt Vฤ: </label> <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left"> <input type="text" class="col-md-12 no-padding font-size-12" name="code" id="code" placeholder="-Mรฃ trฦฐแปng"></label> </div> <div class="form-group extendbottom"> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Chi tiแบฟt Vฤ: </label> <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left"> <input type="text" class="col-md-12 no-padding font-size-12" name="name" id="name" placeholder="-Tรชn trฦฐแปng"></label> </div> <!-- <div class=""> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Hoแบกt ฤ‘แป™ng:</label> <select name="status_insert" class="control-label col-md-8 col-sm-8 no-border no-padding" id="status_insert"> <option value="W">Hoแบกt ฤแป™ng</option> <option value="C">Khรดng Hoแบกt ฤแป™ng</option> </select> </div> --> <div class=""> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Ghi chรบ:</label> <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left"> <textarea class="col-md-12 no-padding font-size-12 control-textarea" placeholder="Nhแบญp bแบฅt kแปณ mแป™t nแป™i dung..." id="comments_insert"></textarea> </label> </div> <input type="hidden" name="category" id="category" value="knwdetail"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">ฤรณng</button> <button type="button" onclick="insertSelectBox()" class="btn btn-primary">Thรชm</button> </div> </div> </div> </div> <div class="modal fade" id="modalDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 7%" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Xoรก Option</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <p class="bg-danger" style="padding: 10px;color: #FFF;" >Bแบกn cรณ chแบฏc muแป‘n xoรก khรดng?</p> <input type="hidden" id="categorydelete" name="categorydelete"> <input type="hidden" id="codedelete" name="codedelete"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">ฤรณng</button> <button type="button" onclick="deleteButton()" class="btn btn-danger">Xoรก</button> </div> </div> </div> </div> <div class="modal fade" id="modalUpdate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 7%" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Sแปญa Option</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class=""> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Phรขn loแบกi:</label> <select name="ref1_update" onchange="getGroup(this,'ref2_update')" class="control-label col-md-8 col-sm-8 no-border no-padding" id="ref1_update"> <?php foreach ($list_ext_type as $key) { ?> <option value="<?php echo $key['code'] ?>"><?php echo $key['name'] ?></option> <?php } ?> </select> </div> <div class=""> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Nhรณm vแบฅn ฤ‘แป:</label> <select name="ref2_update" class="control-label col-md-8 col-sm-8 no-border no-padding" id="ref2_update"> </select> </div> <div class=""> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Tรชn:</label> <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left"> <input type="text" class="col-md-12 no-padding font-size-12 nameField" id="nameField" name="name" placeholder="Tรชn"></label> </div> <div class=""> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Hoแบกt ฤ‘แป™ng:</label> <select name="status" class="control-label col-md-8 col-sm-8 no-border no-padding" id="status"> <option value="W">Hoแบกt ฤแป™ng</option> <option value="C">Khรดng Hoแบกt ฤแป™ng</option> </select> </div> <div class=""> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Ghi chรบ:</label> <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left"> <textarea class="col-md-12 no-padding font-size-12 control-textarea" placeholder="Nhแบญp bแบฅt kแปณ mแป™t nแป™i dung..." id="comments" name="comments"></textarea> </label> </div> <input type="hidden" id="category" name="category"> <input type="hidden" class="code" id="code" name="code"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">ฤรณng</button> <button type="button" onclick="updateButton()" class="btn btn-primary">Sแปญa</button> </div> </div> </div> </div><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-12 margin-bot-10 margin-top-5 margin-left-10"> <?php echo isset($top) ? $top : ''; ?> </div> <div class="col-md-3 col-md-24 no-padding padding-left-15 height-1024"> <?php echo isset($left) ? $left : ''; ?> </div> <div class="col-md-6 no-padding padding-left-5"> <?php echo isset($center) ? $center : ''; ?> </div> <div class="col-md-3 no-padding padding-left-5 relative height-1024"> <?php echo isset($right) ? $right : ''; ?> </div> </div> </main><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Typework extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url')); $this->load->model('M_api'); } public function index() { $list_extend['list_ext'] = []; $list_extend['detail'] =[]; $fieldtype = 'D'; if($fieldtype == 'D') { $datasource = 'tasktype'; $_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/selectall/'.$datasource); $list_ext = json_decode($_jsonlistext,true); $list_extend['list_ext'] = $list_ext['data']; } $_body = []; $_body['center'] = $this->load->view('datasource/typework/tw_center', $list_extend, TRUE); $_data = []; $_data['script'] = $this->load->view('script/script_datastage', NULL, TRUE); $_data['mainview'] = $this->load->view('datasource/datastage/form', $_body , TRUE); $this->load->view('dashboard',$_data); } } /* End of file Typework.php */ /* Location: ./application/controllers/Typework.php */ ?><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-2 col-md-22 padding-left-15"> <?php echo isset($left)?$left:'' ?> </div> <div class="col-md-7 padding-left-1"> <iframe class="iframeIssueGroup" id="iframeIssueGroup" style="min-height: 1024px;width: 100%; border: none;" src="<?php echo base_url() ?>issuegroup/rightFilter?ref1=-1"></iframe> </div> <div class="col-md-2 col-md-18 padding-left-5"> </div> </div> </main><file_sep><div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Mรฃ giao dแป‹ch:</label> <label class="control-label col-md-8 no-padding-right col-brk-8"><a class="a_contractid" id="a_contractid" href="#" target="_blank"><?php echo $trade[0]['contractid'] ?></a></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Tรฌnh trแบกng</label> <label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['status'] ?></label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Mรฃ KH</label> <label class="control-label col-md-8 no-padding-right"><a class="a_custid" id="a_custid" href="#" target="_blank"><?php echo $trade[0]['clientcode'] ?></a></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">BฤS</label> <label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['property'] ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Sร n</label> <label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['name'] ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">NV phแปฅ trรกch</label> <label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['name2'] ?></label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ngร y bแบฏt ฤ‘แบงu</label> <label class="control-label col-md-8 no-padding-right"><?php if($trade[0]['startdate'] !=null) { echo date("d/m/Y", strtotime($trade[0]['startdate']));} ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ngร y kแบฟt thรบc</label> <label class="control-label col-md-8 no-padding-right">22/06/2018</label> </div> <div class="break-line margin-bot-5"></div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก trแป‹ Hฤ</label> <label class="control-label col-md-8 no-padding-right"><?php echo number_format($trade[0]['contractvalue']) ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก chฦฐa VAT</label> <label class="control-label col-md-8 no-padding-right"><?php echo number_format($trade[0]['value0']) ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Thuแบฟ VAT</label> <label class="control-label col-md-8 no-padding-right"><?php echo number_format($trade[0]['value1']) ?></label> </div> <div class="break-line margin-bot-5"></div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Phรญ bแบฃo trรฌ</label> <label class="control-label col-md-8 no-padding-right"><?php echo number_format($trade[0]['value2']) ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">GT Q SDฤ</label> <label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value3']) ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก tรญnh VAT</label> <label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value4']) ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Phรญ tฦฐ vแบฅn</label> <label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value5']) ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก trแป‹ CK</label> <label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value6']) ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก trแป‹ cแปc</label> <label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value7']) ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก chuแบฉn <br> chฦฐa VAT</label> <label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value8']) ?></label> </div> <div class="break-line margin-bot-5"></div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Tแป•ng GT Hฤ</label> <label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value9']) ?></label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Loแบกi vay</label> <label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['anal_pct8'] ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ngรขn hร ng</label> <label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['name1'] ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Chแปฉng tแปซ NH</label> <label class="control-label col-md-8 no-padding-right"></label> </div> <div class="break-line margin-bot-5"></div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก trแป‹ vay</label> <label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['loanvalue'] ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ngร y vay</label> <label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['loandate'] ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ghi chรบ vay</label> <label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['loannotes'] ?></label> <label class="control-label user-label col-md-3 no-padding">Ngร y kรฝ</label> <label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['anal_pct7'] ?></label> </div> <div class="break-line margin-bot-5"></div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Sแป‘ Hฤ cแปc</label> <label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['anal_pct8'] ?></label> <label class="control-label user-label col-md-3 no-padding">Sแป‘ Hฤ</label> <label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['anal_pct9'] ?></label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ghi chรบ</label> <label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['notes'] ?></label> </div> </div> </div><file_sep><div class="tile height-1024"> <div class="content-title"> <div class="div"> <h5>Ngฦฐแปi dรนng</h5> </div> <ul class="app-breadcrumb breadcrumb"> <li class="breadcrumb-item"><a style="cursor: pointer;" onclick="addTab('<?php echo base_url().'user/create' ?>','Thรชm User')">Thรชm</a></li> </ul> </div> <p class="margin-top-10 no-margin-bot">Ngฦฐแปi dรนng lร  nhแปฏng ngฦฐแปi tฦฐฦกng tรกc vแป›i hแป‡ thแป‘ng AGI CRM, bao gแป“m chuyรชn viรชn cแปงa AGI vร  khรกch hร ng cแปงa AGI, hแป tฦฐฦกng tรกc thรดng qua chแปง thแปƒ lร  Phiแบฟu hแป— trแปฃ (Tickets). Bแบกn cรณ thแปƒ tแบกo cรกc trฦฐแปng thรดng tin mแปŸ rแป™ng vร  phรขn nhรณm ฤ‘แปƒ quแบฃn lรฝ ngฦฐแปi dรนng ฤ‘ฦฐแปฃc tแป‘t hฦกn.</p> <div class="row margin-top-10"> <div class="form-group col-md-6 no-padding-right"> <input id="keyword" class="form-control" type="text" placeholder="Nhแบญp tแปซ khรณa..."> </div> <div class="form-group col-md-3 align-self-end padding-left-1"> <button class="btn btn-primary" onclick="search()" type="button">Tรฌm kiแบฟm</button> <img src="<?php echo base_url().'images/loader.gif' ?>" style="display: none;" id="loading"> </div> </div> <ul class="app-breadcrumb breadcrumb"> <p class="margin-right-10 font-size-12">Lแปc nhanh:</p> <!-- <li class="breadcrumb-item"><a class="user-name" style="cursor: pointer;" onclick="searchRoleid('3')">Khรกch hร ng</a></li> --> <li class="breadcrumb-item"><a class="user-name" style="cursor: pointer;" onclick="searchRoleid('2')">Chuyรชn viรชn</a></li> <li class="breadcrumb-item"><a class="user-name" style="cursor: pointer;" onclick="searchRoleid('1')">Quแบฃn trแป‹ viรชn</a></li> </ul> <div class="content-search"> <div class="table-responsive"> <table class="table" id="tableUser"> <thead> <tr> <th></th> <th>Hแป tรชn</th> <th>SฤT</th> <th>Email</th> </tr> </thead> <tbody> <?php foreach ($user as $value) { ?> <tr> <td width="40px"> <img class="user-avatar" src="<?php echo $value['avatar'] ?>" alt="User Image"> </td> <td width="252px"> <a class="user-name" style="cursor: pointer;" onclick="addTab('<?php echo base_url().'user/detail/?cusid='.$value['custid'].'&idcard='.$value['idcard'].'&roleid='.$value['roleid'] ?>','<?php echo $value['custname'] ?>')"><?php echo $value['custname'] ?></a> <p class=""><?php echo $value['groupname'] ?></p> </td> <td width="229px"><?php echo $value['telephone'] ?></td> <td width="218px"><?php echo $value['email'] ?></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div><file_sep><div class="col-md-100 no-padding padding-left-5"> <div class="tile height-1024"> <div class="table-responsive"> <table class="table" id="table-1-searchuser"> <thead class="no-border-top"> <tr> <th>Tรชn</th> <th>Sแป‘ CMND</th> <th>Sแป‘ ฤ‘iแป‡n thoแบกi</th> <th>Email</th> <th>Cแบญp nhแบญt lแบงn cuแป‘i</th> </tr> </thead> <tbody> <?php if(count($result['data']) >0) { foreach ($result['data'] as $rows) { ?> <tr class="border-bot-1"> <td width="250"> <a class="buttonsearchiframe" onclick="addTab('<?php echo base_url().'user/detail/?cusid='.$rows['custid'].'&idcard='.$rows['idcard'].'&roleid='.$rows['roleid'] ?>','<?php echo $rows['custname'] ?>')" href="#" title=""> <?php echo strtoupper(mb_convert_case($rows['custname'],MB_CASE_UPPER,'UTF-8')) ?> </a> </td> <td><?php echo $rows['idcard'] ?></td> <td><?php echo $rows['telephone'] ?></td> <td><?php echo $rows['email'] ?></td> <td><?php if($rows['lastupdate']!=null && strtotime($rows['lastupdate'])>strtotime('2000/01/01')) { echo date("d/m/Y H:i:s", strtotime($rows['lastupdate']));} ?></td> </tr> <?php }} ?> </tbody> </table> </div> </div> </div><file_sep> <div class="tile no-margin-bot"> <div class="content-title"> <div class="div width-100per"> <h5 class="flex"><i class="fa fa-lg fa-file-alt header-icon"></i> <input style="width: 80% " name="title" class="no-padding font-size-18 width-95per crm-control" log="Tiรชu ฤ‘แป" placeholder="Nhแบญp tiรชu ฤ‘แป phiแบฟu hแป— trแปฃ" value="<?php echo $ticket['data'][0]['title'] ?>" old-value="<?php echo $ticket['data'][0]['title'] ?>"> </h5> <div class="btn-group absolute" role="group" style="right: 10px;top: 15px;"> <button class="btn btn-primary" type="button" id="btn-accept" tckid="<?php echo $this->uri->segment(3) ?>"> <i class="fa fa-share"></i> Tiแบฟp nhแบญn</button> <button class="btn btn-primary dropdown-toggle" id="btnGroupDrop1" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button> <div class="dropdown-menu dropdown-menu-right" x-placement="bottom-end"> <a class="dropdown-item" href="#" tck-id="<?php echo $ticket['data'][0]['ticketid'] ?>" tck-stt="<?php echo $ticket['data'][0]['status'] ?>" tck-title="<?php echo $ticket['data'][0]['title'] ?>" id="btn-ticket-merge">Ghรฉp phiแบฟu</a> <a class="dropdown-item" href="javascript:window.location.reload();"><i class="fa fa-sync-alt fa-md float-right margin-top-3"></i>Refresh phiแบฟu</a> </div> </div> </div> </div> <div class="break-line margin-bot-5"></div> <div class="row"> <div class="col-md-12 comment-wrap"> <div class="photo"> <img class="avatar" src="<?php echo($this->session->userdata('avatar')!=''?$this->session->userdata('avatar'):'https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg')?>"> </div> <div class="comment-block"> <div class="status-upload"> <input type="hidden" name="ticketid" value="<?php echo $this->uri->segment(3)?>"> <input type="hidden" name="changelog"> <textarea name="cmt" placeholder="Nhแบญp ghi chรบ" ></textarea> </div><!-- Status Upload --> <button type="<?php if($update){ echo "submit";}else{ echo "button";}?>" title="<?php echo $this->uri->segment(3) ?>" class="btn btn-gray margin-top-5 float-right <?php if($update){ echo "btn-updateAction";}else{ echo "btn-updateActionUpdate";}?>"> <i class="fa fa-share"></i> Ghi nhแบญn </button> </div> </div> </div> </div> </form> <div class="comments no-padding"> <ul class="nav nav-tabs no-margin margin-bot-5"> <li class="nav-item"> <a class="user-tab active show" data-toggle="tab" href="#tab-content-1">Lแป‹ch sแปญ phiแบฟu</a> </li> <li class="nav-item"> <a class="user-tab" data-toggle="tab" href="#tab-content-2">Cรดng viแป‡c</a> </li> </ul> <div class="tab-content" id="myTabContent"> <div class="tab-pane fade active show" id="tab-content-1"> <iframe name="tck_log" class="no-border" style="width: 100%; height: 500px;" src="<?php echo(base_url('ticket/view_ticket_log/'.$this->uri->segment(3)))?>"></iframe> </div> <div class="tab-pane fade" id="tab-content-2"> <iframe name="tck_task" class="no-border" style="width: 100%; height: 500px;" src="<?php echo(base_url('ticket/view_ticket_task/'.$this->uri->segment(3).'/'.$ticket['data'][0]['custid']))?>"></iframe> </div> </div> </div> <file_sep><script type="text/javascript"> var tic = $('select[name=tic]').val(); if (tic!='') { $('select[name=pic] option').each(function(){ var group = $(this).attr('data-group'); if (tic==group) {$(this).prop('disabled',false);} else{$(this).prop('disabled',true);} }); } if (tic && tic!='<?php echo($this->session->userdata('groupid'))?>') { $('#btn-accept').remove(); $('.crm-control,.crm-ext,button[type=submit]').prop('disabled',true); } var pic = $('select[name=pic]').val(); if (pic) { if (pic!='<?php echo $this->session->userdata('custid');?>') { $('.crm-control,.crm-ext,button[type=submit]').prop('disabled',true); } $('#btn-accept').remove(); }else{ $('.crm-control,.crm-ext,button[type=submit]').prop('disabled',true); } $('input[name=req_date],input[name=ola_date],input[name=due_date],input[name=fns_date]').datetimepicker({format:'Y-m-d h:i'}); $('.my-chosen').chosen({ width:'105%', disable_search_threshold: 9, no_results_text: "Khรดng tรฌm thแบฅy: ", allow_single_deselect: true }); $('select[name=tic]').change(function(){ var val = $(this).val(); if(val){ $('select[name=pic] option').each(function(){ var group = $(this).attr('data-group'); if (val==group) {$(this).prop('disabled',false);} else{$(this).prop('disabled',true);} }); $('select[name=pic] option:disabled(not):first').prop('selected',true); }else{ $('select[name=pic] option').each(function(){ $(this).prop('disabled',false); }); } $('.my-chosen').trigger('chosen:updated'); }); $('select#level_1').change(function(){ var val = $(this).val(); if(val){ $('select#level_2 option').each(function(){ var ref1 = $(this).attr('ref1'); if (ref1==val) { $(this).removeClass('hide').addClass('show'); }else{ $(this).addClass('hide').removeClass('show'); } }); }else{ $('select#level_2 option').each(function(){ $(this).removeClass('hide').addClass('show'); }); } $('select#level_2 option.show:first').prop('selected',true); var log = $('select#level_2').attr('log'); var old_value = $('select#level_2').attr('old-value'); var new_value = $('select#level_2').val(); if (log) { var text = $('select#level_2').find('option:selected').text(); if (old_value === new_value) {deletelog(log);}else{changelog(log,text);} } }); $(document).on('change','.crm-control',function(){ var log = $(this).attr('log'); var old_value = $(this).attr('old-value'); var new_value = $(this).val(); if (log) { var text = $(this).find('option:selected').text(); if (!text) { text = $(this).val(); } if (old_value === new_value) {deletelog(log);}else{changelog(log,text);} } }); $('#btn-accept').click(function(){ var cur = $(this); var taskid = $(this).attr('taskid'); if (taskid) cur.prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner'); $.ajax({ url: '<?php echo base_url().'task/get_to_my_task/'?>'+taskid, type: 'POST', dataType: 'JSON', }) .done(function(data) { if(data.code==1){ parent.notification('Tiแบฟp nhแบญn cรดng viแป‡c thร nh cรดng.'); window.location.reload(); }else{ parent.alertLog('Lแป—i',data.message,'danger'); // alert(data.message); } }) .fail(function() { cur.prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); parent.alertLog('Lแป—i',"Lแป—i kแบฟt nแป‘i.",'danger'); }); }); $('#all-in').on('submit',function(){ var form = new FormData($(this)[0]); var url = '<?php echo(base_url().'task/aj_api_update');?>'; var error = []; for (var [key, value] of form.entries()) { // console.log(key, value); switch(key){ case 'taskmaster': if (value=='') { error[key] = "1"; parent.alertLog('Cแบฃnh bรกo','Vui lรฒng chแปn ngฦฐแปi yรชu cแบงu.','warning'); } break; case 'tic': if (value=='' && form.get('pic') == '') { error[key] = '1'; parent.alertLog('Cแบฃnh bรกo','Bแบกn phแบฃi nhแบญp 1 trong 2 thรดng tin: Nhรณm phแปฅ trรกch, Ngฦฐแปi phแปฅ trรกch.','warning'); }else if (value=='' && form.get('pic') !='') { var agent = $('select[name=pic]').find('option:selected').attr('data-group'); console.log(agent); if (agent) {form.set('tic',agent)} } break; default: break; } } if (!jQuery.isEmptyObject(error)) { var msg = ''; for (let key in error){ msg+= error[key]+"\n"; } console.log(msg); }else{ var button_luu = $(this); $(this).find('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner'); $.ajax({ type: "POST", url: url, data: form, dataType:'json', contentType: false, cache: false, processData:false, success: function(data) { if (data.code==1) { window.location.reload(); }else{ button_luu.find('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); parent.alertLog('Cแบฃnh bรกo',data.message,'warning'); } }, error: function(xhr, status, error) { console.log(error); } }); } return false; }); function changelog(log,text){ var oldchange = $('input[name=changelog]').val(); var newchange = ''; var arr_log = oldchange.split('|'); if (arr_log.length>0) { for (var i = 0; i < arr_log.length; i++) { // console.log(arr_log[i]); if(arr_log[i]!= ' ' && arr_log[i]!= '' && arr_log[i].indexOf(log) == -1){ newchange += arr_log[i].trim()+" | "; } } } newchange += log+': '+text+" | "; console.log(newchange); $('input[name=changelog]').val(newchange); return false; } function deletelog(log){ var oldchange = $('input[name=changelog]').val(); var newchange = ''; var arr_log = oldchange.split('|'); if (arr_log.length>0) { for (var i = 0; i < arr_log.length; i++) { // console.log(arr_log[i]); if(arr_log[i]!= ' ' && arr_log[i]!= '' && arr_log[i].indexOf(log) == -1){ newchange += arr_log[i].trim()+" | "; } } } console.log(newchange); $('input[name=changelog]').val(newchange); return false; } </script><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-2 col-md-22 no-padding padding-left-15"> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-10" id="search_area"> <div> <input class="form-control margin-top-10 margin-bot-5" type="text" name="s_text" placeholder="Tรฌm kiแบฟm bร i viแบฟt"> <p class="font-size-8 field-click-able">Tรฌm theo bแป™ lแปc</p> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Phรขn loแบกi</label> <select name="s_type" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_1"> <option value="all" selected="" all="true">Tแบฅt cแบฃ</option> <?php if (isset($l_type) && !empty($l_type)) { foreach ($l_type as $key => $value) { echo '<option value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Nhรณm vแบฅn ฤ‘แป</label> <select name="s_group" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_2"> <option value="all" selected="" all="true">Tแบฅt cแบฃ</option> <?php if (isset($l_group) && !empty($l_group)) { foreach ($l_group as $key => $value) { echo '<option ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Chi tiแบฟt Vฤ</label> <select name="s_cate" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_3"> <option value="all" selected="" all="true">Tแบฅt cแบฃ</option> <?php if (isset($l_cate) && !empty($l_cate)) { foreach ($l_cate as $key => $value) { echo '<option ref1="'.$value['ref1'].'" ref2="'.$value['ref2'].'" value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class="break-line margin-bot-5"></div> <div class=""> <label class="control-label user-label col-md-3 no-padding">ฤฤƒng bแปŸi</label> <select name="s_createby" class="control-label col-md-8 no-border no-padding margin-left-10"> <option value="" selected="">Tแบฅt cแบฃ</option> <?php if (isset($agent) && !empty($agent)) { foreach ($agent as $key => $value) { echo '<option value="'.$value['custid'].'">'.$value['custname'].'</option>'; } } ?> </select> </div> <div class=""> <label class="control-label col-md-8 no-padding-right"></label> <label class="control-label col-md-8 no-padding-right"></label> <button id="btn-search" class="btn btn-primary float-right" type="button">Tรฌm kiแบฟm</button> <label class="control-label col-md-8 no-padding-right"></label> </div> </div> </div> </div> <div class="col-md-6 col-md-78 no-padding padding-left-5"> <iframe class="iframesearch" id="iframesearch" src="<?php echo base_url() ?>knowledge/search/?search="></iframe> </div> </div> </main><file_sep><div class="tile no-margin-bot"> <div class="content-title"> <?php $contractid = $this->uri->segment(3); $custidCustomer = $this->uri->segment(4) ; ?> <button class="btn btn-blank insert-manual" alt="insert" onclick="addTab('<?php echo base_url().'ticket/viewInsert/'.$contractid.'/'.$custidCustomer ?>','Thรชm Ticket',true)" type="button">+ Phiแบฟu hแป— trแปฃ </button> </div> <div class="bs-component margin-top-10 tab-table-contract"> <ul class="nav nav-tabs nav-user" role="tablist"> <li class="nav-item" role="presentation"> <a class="user-tab active show" alt="crmContract01e" data-toggle="tab" href="#tab-content-1">Thร nh viรชn</a> </li> <li class="nav-item" role="presentation"> <a class="user-tab" data-toggle="tab" alt="crmContract01b" href="#tab-content-2">Lแป‹ch sแปญ trแบกng thรกi</a> </li> <li class="nav-item" role="presentation"> <a class="user-tab" data-toggle="tab" alt="crmContract01c" href="#tab-content-3">Cรดng nแปฃ/Thanh toรกn</a> </li> <li class="nav-item" role="presentation"> <a class="user-tab" data-toggle="tab" alt="crmContract01d" href="#tab-content-4">KM/Quร  tแบทng</a> </li> <li class="nav-item" role="presentation"> <a class="user-tab" data-toggle="tab" alt="crmContract01f" href="#tab-content-5">NV Kinh doanh</a> </li> <li class="nav-item" role="presentation"> <a class="user-tab" alt="crmContract01g" data-toggle="tab" href="#tab-content-6">ฤiแปu chแป‰nh hแปฃp ฤ‘แป“ng</a> </li> <li class="nav-item" role="presentation"> <a class="user-tab" data-toggle="tab" alt="crmContract01h" href="#tab-content-7">Ghi chรบ</a> </li> </ul> <div class="tab-content" id="myTabContent"> <div class="tab-pane fade active show" id="tab-content-1"> <div class="table-responsive" id="div-content-1" style="height: 294px;background:url(<?php echo base_url() ?>/images/ajax-loading.gif) center center no-repeat"> </div> </div> <div class="tab-pane fade" id="tab-content-2"> <div class="table-responsive" id="div-content-2" style="height: 294px;"> <table class="table table-striped table-bordered" id="table-1-history"> <thead class="no-border-top"> <tr> <th width="71px">HH/DV</th> <th width="123px">Ngร y</th> <th width="67px">Sแป‘ lฦฐแปฃng</th> <th width="65px">Giรก trแป‹</th> <th width="323px">Ghi chรบ</th> </tr> </thead> <tbody> </table> </div> </div> <div class="tab-pane fade" id="tab-content-3"> <table class="table table-striped table-bordered" id="table-1-congno"> <thead class="no-border-top"> <tr> <th width="46px">Loแบกi NK</th> <th width="19px">HฤC</th> <th width="38px">HฤMB</th> <th width="50px">Ngร y NV</th> <th width="50px">Ngร y ฤH</th> <th width="55px">S.tiแปn</th> <th width="220px">Diแป…n Giแบฃi</th> <th width="18px">PB</th> <th width="450px">Tiแบฟn ฤแป™</th> </tr> </thead> <tbody> </tbody> </table> </div> <div class="tab-pane fade" id="tab-content-4"> <div class="table-responsive" id="div-content-4" style="height: 294px;"> <table class="table table-striped table-bordered" id="table-1-gift"> <thead class="no-border-top"> <tr> <th width="71px">Ngร y</th> <th width="123px">HH/DV</th> <th width="67px">Sแป‘ lฦฐแปฃng</th> <th width="85px">Giรก trแป‹</th> <th width="323px">Ghi chรบ</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <div class="tab-pane fade" id="tab-content-5"> <div class="table-responsive" id="div-content-5" style="height: 294px;"> <table class="table table-striped table-bordered" id="table-1-buss"> <thead class="no-border-top"> <tr> <th width="195px">Nhรขn viรชn</th> <th width="117px">Sร n</th> <th width="83px">Tแป‰ lแป‡ thฦฐแปŸng</th> <th width="255px">Ghi chรบ</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <div class="tab-pane fade" id="tab-content-6"> <div class="table-responsive" id="div-content-6" style="height: 294px;background:url(<?php echo base_url() ?>/images/ajax-loading.gif) center center no-repeat"> </div> </div> <div class="tab-pane fade" id="tab-content-7"> <div class="table-responsive" class="div-content-7" id="div-content-7" style="height: 294px;"> <table class="table table-striped table-bordered" id="table-1-notes"> <thead class="no-border-top"> <tr> <th width="81px">Loแบกi ghi chรบ</th> <th width="93px">Ngร y ghi chรบ</th> <th width="71px">Tรฌnh trแบกng</th> <th width="169px">Nhรขn viรชn</th> <th width="235px">Nแป™i dung</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> </div> </div> </div> <div class="tile height-429 margin-top-7"> <div> <button type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right">Ticket</button> </div> <div class="bs-component margin-top-10"> <div class="table-responsive" style="height: 396px;" id="div-table-ticket"> <table class="table table-striped table-bordered" id="table-1-ticketcontract"> <thead class="no-border-top"> <tr> <th width="60px">ID</th> <th width="160px">Tแปฑa ฤ‘แป</th> <th width="100px">Ngร y yรชu cแบงu</th> <th width="112px">Ngฦฐแปi phแปฅ trรกch</th> <th width="110px">Cแบญp nhแบญt lแบงn cuแป‘i</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> </div><file_sep> <div class="tile no-margin-bot"> <div class="content-title"> <div class="div width-100per"> <h5 class="flex"> <i class="fa fa-lg fa-file-alt header-icon"></i> <input name="title" class="no-padding font-size-18 width-95per" placeholder="Nhแบญp tiรชu ฤ‘แป phiแบฟu hแป— trแปฃ" required=""> </h5> </div> </div> <div class="break-line margin-bot-5"></div> <div class="row"> <div class="col-md-12 comment-wrap"> <div class="photo"> <img class="avatar" src="<?php echo($this->session->userdata('avatar')!=''?$this->session->userdata('avatar'):'https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg')?>"> </div> <div class="comment-block"> <div class="status-upload"> <input type="hidden" name="ticketid" value="<?php echo $this->uri->segment(3)?>"> <input type="hidden" name="contractid" value="<?php echo $this->uri->segment(4)?>"> <textarea name="cmt" placeholder="ฤแปƒ lแบกi thรดng tin ghi chรบ cho phiแบฟu"></textarea> </div><!-- Status Upload --> <button type="submit" class="btn btn-gray float-right margin-top-5"> <i class="fa fa-share"></i> Ghi nhแบญn </button> </div> </div> </div> </div> </form><file_sep><!DOCTYPE html> <html lang="en"> <head> <title>Customer Relationship Managerment</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Main CSS--> <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/main.css"> <!-- Font-icon css--> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Customer CSS--> <link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.bootstrap.min.css"> <link rel="stylesheet" href="<?php echo base_url() ?>css/jquery.scrolling-tabs.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/chosen.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/customer.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/customer2.css"> </head> <body class="app sidebar-mini rtl sidenav-toggled"> <!-- <?php $dayCompare = strtotime('2000-01-01T00:00:00');?> --> <?php echo isset($mainview) ? $mainview : ''; ?> <!-- Essential javascripts for application to work--> <script src="<?=base_url()?>js/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.3/js/responsive.bootstrap.min.js"></script> <script type="text/javascript" src="http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script> <script type="text/javascript" src="//cdn.datatables.net/plug-ins/1.10.19/sorting/datetime-moment.js"></script> <script src="<?=base_url()?>js/popper.min.js"></script> <script src="<?=base_url()?>js/bootstrap.min.js"></script> <script src="<?=base_url()?>js/main.js"></script> <script src="<?=base_url()?>js/main2.js"></script> <script src="<?=base_url()?>js/plugins/pace.min.js"></script> <script src="<?=base_url()?>js/plugins/chosen.jquery.js"></script> <script type="text/javascript" src="<?=base_url()?>js/plugins/chart.js"></script> <script type="text/javascript" src="<?=base_url()?>js/plugins/sweetalert.min.js"></script> <script src="<?php echo base_url() ?>datetimepicker-master/build/jquery.datetimepicker.full.min.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>datetimepicker-master/jquery.datetimepicker.css"/> <script src="<?php echo base_url() ?>js/jquery.scrolling-tabs.js"></script> <script type="text/javascript" src="<?=base_url()?>js/plugins/jquery.validate.min.js"></script> <script type="text/javascript" src="<?=base_url()?>ckeditor/ckeditor.js"></script> <script type="text/javascript" src="<?=base_url()?>ckfinder/ckfinder.js"></script> <?php echo isset($script) ? $script : ''; ?> <?php echo isset($script2) ? $script2 : ''; ?> </body> </html><file_sep><main class="app-content padding-5 no-padding-right"> <form id="all-in"> <div class="row"> <div class="col-md-3 no-padding padding-left-15 height-1024"> <div class="tile p-0 padding-5 margin-bot-5 z-index-103"> <div class="tile-body padding-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngฦฐแปi yรชu cแบงu</label> <select data-placeholder="Chแปn ngฦฐแปi yรชu cแบงu..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="taskmaster"> <option value="" ></option> <?php if (isset($l_cus)) { foreach ($l_cus as $cus) { if ($cus['custname']!='') { echo('<option value="'.$cus['custid'].'">'.$cus['custname'].'</option>'); } } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Nhรณm phแปฅ trรกch</label> <select data-placeholder="Chแปn nhรณm phแปฅ trรกch..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="tic"> <option value=""></option> <?php if (isset($l_agentgroup)) { foreach ($l_agentgroup as $key => $value) { echo '<option value="'.$value['groupid'].'">'.$value['groupname'].'</option>'; } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Phแปฅ trรกch</label> <select data-placeholder="Chแปn ngฦฐแปi phแปฅ trรกch..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="pic"> <option value=""></option> <?php if (isset($l_age)) { foreach ($l_age as $cus) { if ($cus['custname']!='') { echo('<option value="'.$cus['custid'].'" data-group="'.$cus['groupid'].'">'.$cus['custname'].'</option>'); } } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Phiแบฟu liรชn quan</label> <select data-placeholder="Chแปn phiแบฟu liรชn quan..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="ticketid"> <option value=""></option> <?php if (isset($l_ticket)) { foreach ($l_ticket as $cus) { echo('<option value="'.$cus['ticketid'].'">'.$cus['ticketid'].'</option>'); } } ?> </select> </div> <div class="hide"> <label class="control-label user-label col-md-4 no-padding">CCs</label> <select class="control-label col-md-8 no-border no-padding margin-left-10" name="ccs"> <option value="1">ccs</option> </select> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5 z-index-102"> <div class="tile-body padding-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">ฤแป™ ฦฐu tiรชn</label> <select class="control-label col-md-8 no-border no-padding margin-left-10" name="priority"> <option value="1">Thฦฐแปng</option> <option value="2">Cao</option> <option value="3">Khแบฉn cแบฅp</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">ฤแป™ nghiรชm trแปng</label> <select class="control-label col-md-8 no-border no-padding margin-left-10" name="severity"> <option value="1">Thฦฐแปng</option> <option value="2">Cao</option> <option value="3">Khแบฉn cแบฅp</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Trแบกng thรกi</label> <select class="control-label col-md-8 no-border no-padding margin-left-10" name="status"> <option value="O" selected="">MแปŸ</option> <option value="W" disabled="">ฤang xแปญ lรฝ</option> <option value="C" disabled="">Hoร n thร nh</option> <option value="X" disabled="">Hแปงy</option> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ghi chรบ T.thรกi</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12" placeholder="Nhแบญp ghi chรบ..." name="statusnote"> </label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5 z-index-101"> <div class="tile-body padding-right-10"> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Phรขn loแบกi</label> <select class="control-label col-md-8 no-border no-padding margin-left-10" name="tasktype" id="level_1"> <?php if (isset($l_type)) { foreach ($l_type as $key => $value) { echo '<option value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Chi tiแบฟt CV</label> <select class="control-label col-md-8 no-border no-padding margin-left-10" name="taskdetail" id="level_2"> <?php if (isset($l_detail)) { foreach ($l_detail as $key => $value) { $c=''; if (isset($l_type[0]['code']) && $value['ref1']!=$l_type[0]['code']) { $c="hide"; } echo '<option class="'.$c.'" ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> <div class="break-line margin-bot-5"></div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngร y yรชu cแบงu</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12" placeholder="dd-mm-yy hh:ii" name="req_date"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Thแปi hแบกn OLA</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12" placeholder="dd-mm-yy hh:ii" name="ola_date"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Ngร y hแบนn</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12" placeholder="dd-mm-yy hh:ii" name="due_date"> </label> </div> <div class="break-line margin-bot-5"></div> <div class=" hide"> <label class="control-label user-label col-md-4 no-padding">ฤแบฟm ngฦฐแปฃc</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12" placeholder="sแป‘ ngร y"> </label> </div> <div class="flex"> <label class="control-label user-label col-md-4 no-padding">Hoร n thร nh</label> <label class="control-label col-md-8 no-padding-right"> <input class="col-md-12 no-padding font-size-12" placeholder="dd-mm-yy hh:ii" name="fns_date"> </label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5 z-index-100 hide"> <div class="tile-body padding-left-right-10"> <div class="row margin-top-5 height-100"> <label class="control-label user-label col-md-4 no-padding">File ฤ‘รญnh kรจm</label> <label class="control-label col-md-8 no-padding-right"> </label> </div> </div> </div> </div> <div class="col-md-7 no-padding padding-left-5"> <div class="tile no-margin-bot"> <div class="content-title"> <div class="div margin-bot-10 width-100per"> <h5 class="flex"> <i class="fa fa-lg fa-file-alt header-icon"></i> <input class="font-size-18 width-100per" type="text" required="" name="title" placeholder="Tiรชu ฤ‘แป Cรดng viแป‡c"> </h5> <p class="header-desc field-click-able"> <!-- <input class="font-size-12" type="text" name="explain" placeholder="Diแป…n giแบฃi"> --> </p> </div> <!-- <button class="btn btn-blank header-btn btn-caret" type="button"><i class="fa fa-caret-down fa-md float-right"></i></button> --> </div> <div class="break-line margin-bot-5"></div> <div class="row"> <div class="col-md-12 comment-wrap"> <div class="photo"> <img class="avatar" src="<?php echo($this->session->userdata('avatar'));?>"> <input type="hidden" name="avatar" value="<?php echo($this->session->userdata('avatar'));?>"> </div> <div class="comment-block"> <!-- <p class="no-margin">Trแบฃ lแปi</p> --> <div class="status-upload"> <!-- <ul class="hide"> <li><a title="" data-toggle="tooltip" data-placement="bottom" data-original-title="Text"><i class="fa fa-font"></i></a></li> <li><a title="" data-toggle="tooltip" data-placement="bottom" data-original-title="File"><i class="fa fa-paperclip"></i></a></li> </ul> --> <textarea name="cmt" placeholder="Nhแบญp bแบฅt kแปณ mแป™t nแป™i dung?"></textarea> </div><!-- Status Upload --> <button type="submit" class="btn btn-gray float-right margin-top-5 margin-bot-5"> <i class="fa fa-share"></i> Lฦฐu </button> </div> </div> </div> </div> <div class="comments"> <p>Lแป‹ch sแปญ cรดng viแป‡c</p> </div> </div> </form> </main><file_sep><?php var_dump($token) ?> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-right-10"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Loแบกi hรฌnh</label> <label class="control-label col-md-8 no-padding-right col-brk-8">Giao dแป‹ch dแปฑ รกn An Gia Garden</label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Tรฌnh trแบกng</label> <label class="control-label col-md-8 no-padding-right">TLY_HDMB</label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-right-10"> <div class=""> <label class="control-label user-label col-md-3 no-padding">BฤS</label> <label class="control-label col-md-8 no-padding-right">AAG-A11-12</label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Sร n</label> <label class="control-label col-md-8 no-padding-right">Danh Khรดi V</label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-right-10"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ngร y bแบฏt ฤ‘แบงu</label> <label class="control-label col-md-8 no-padding-right">22/05/2018</label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ngร y kแบฟt thรบc</label> <label class="control-label col-md-8 no-padding-right">22/06/2018</label> </div> <div class="break-line margin-bot-5"></div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก trแป‹ Hฤ</label> <label class="control-label col-md-8 no-padding-right">996,911,000</label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก chฦฐa VAT</label> <label class="control-label col-md-8 no-padding-right">910,000,235</label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Thuแบฟ VAT</label> <label class="control-label col-md-8 no-padding-right">90,000,000</label> </div> <div class="break-line margin-bot-5"></div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Phรญ bแบฃo trรฌ</label> <label class="control-label col-md-8 no-padding-right">18,000,210</label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">GT Q SDฤ</label> <label class="control-label col-md-8 no-padding-righte"></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก tรญnh VAT</label> <label class="control-label col-md-8 no-padding-righte"></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Phรญ tฦฐ vแบฅn</label> <label class="control-label col-md-8 no-padding-righte"></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก trแป‹ CK</label> <label class="control-label col-md-8 no-padding-righte"></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก trแป‹ cแปc</label> <label class="control-label col-md-8 no-padding-righte">30,000,000</label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก chuแบฉn <br> chฦฐa VAT</label> <label class="control-label col-md-8 no-padding-righte"></label> </div> <div class="break-line margin-bot-5"></div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Tแป•ng GT Hฤ</label> <label class="control-label col-md-8 no-padding-righte">1,017,000,000</label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-right-10"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Loแบกi vay</label> <label class="control-label col-md-8 no-padding-right"></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ngรขn hร ng</label> <label class="control-label col-md-8 no-padding-right"></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Chแปฉng tแปซ NH</label> <label class="control-label col-md-8 no-padding-right"></label> </div> <div class="break-line margin-bot-5"></div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Giรก trแป‹ vay</label> <label class="control-label col-md-8 no-padding-right"></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ngร y vay</label> <label class="control-label col-md-8 no-padding-right"></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ghi chรบ vay</label> <label class="control-label col-md-8 no-padding-right"></label> </div> <div class="break-line margin-bot-5"></div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Sแป‘ Hฤ vay</label> <label class="control-label col-md-8 no-padding-right">33/Hฤ-AGG-DKS</label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ngร y kรฝ</label> <label class="control-label col-md-8 no-padding-right"></label> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-right-10"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ghi chรบ</label> <label class="control-label col-md-8 no-padding-right">L/v qua email, khรดng gแปญi bแบฅt cแปฉ thฦฐ gรฌ vแป nhร </label> </div> </div> </div><file_sep><script type="text/javascript"> $('input[name=req_date],input[name=ola_date],input[name=due_date],input[name=fns_date]').datetimepicker({format:'Y-m-d h:i'}); $('.my-chosen').chosen({ width:'105%', disable_search_threshold: 9, no_results_text: "Khรดng tรฌm thแบฅy: ", allow_single_deselect: true }); $('select[name=tic]').change(function(){ var val = $(this).val(); if(val){ $('select[name=pic] option').each(function(){ var group = $(this).attr('data-group'); if (val==group) {$(this).prop('disabled',false);} else{$(this).prop('disabled',true);} }); $('select[name=pic] option:disabled(not):first').prop('selected',true); }else{ $('select[name=pic] option').each(function(){ $(this).prop('disabled',false); }); } $('.my-chosen').trigger('chosen:updated'); }); $('select#level_1').change(function(){ var val = $(this).val(); if(val){ $('select#level_2 option').each(function(){ var ref1 = $(this).attr('ref1'); if (ref1==val) { $(this).removeClass('hide').addClass('show'); }else{ $(this).addClass('hide').removeClass('show'); } }); }else{ $('select#level_2 option').each(function(){ $(this).removeClass('hide').addClass('show'); }); } $('select#level_2 option.show:first').prop('selected',true); }); $('#all-in').on('submit',function(){ var form = new FormData($(this)[0]); var url = '<?php echo(base_url().'task/aj_api_insert');?>'; var error = []; for (var [key, value] of form.entries()) { // console.log(key, value); switch(key){ case 'taskmaster': if (value=='') { error[key] = "1"; parent.alertLog('Cแบฃnh bรกo','Vui lรฒng chแปn ngฦฐแปi yรชu cแบงu.','warning'); } break; case 'tic': if (value=='' && form.get('pic') == '') { error[key] = '1'; parent.alertLog('Cแบฃnh bรกo','Bแบกn phแบฃi nhแบญp 1 trong 2 thรดng tin: Nhรณm phแปฅ trรกch, Ngฦฐแปi phแปฅ trรกch.','warning'); }else if (value=='' && form.get('pic') !='') { var agent = $('select[name=pic]').find('option:selected').attr('data-group'); console.log(agent); if (agent) {form.set('tic',agent)} } break; default: break; } } if (!jQuery.isEmptyObject(error)) { var msg = ''; for (let key in error){ msg+= error[key]+"\n"; } console.log(msg); }else{ var button_insert = $(this); $(this).find('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner'); $.ajax({ type: "POST", url: url, data: form, dataType:'json', contentType: false, cache: false, processData:false, success: function(data) { if (data.code==1) { window.location.reload(); parent.alertLog('Thร nh cรดng',"ฤรฃ tแบกo cรดng viแป‡c",'success'); }else{ button_insert.find('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); parent.alertLog('Cแบฃnh bรกo',data.message,'warning'); } }, error: function(xhr, status, error) { parent.alertLog('Cแบฃnh bรกo',"Lแป—i kแบฟt nแป‘i.",'warning'); console.log(error); } }); } return false; }); </script><file_sep><div class="col-md-100 no-padding padding-left-5"> <div class="tile height-1024"> <div class="table-responsive"> <table class="table" id="table-1-searchticket"> <thead class="no-border-top"> <tr> <th width="100">ID</th> <th width="250">Tรชn phiแบฟu</th> <th width="130px">Ngฦฐแปi yรชu cแบงu</th> <th width="130px">Ngฦฐแปi phแปฅ trรกch</th> <th width="60px">ฤแป™ ฦฐu tiรชn</th> <th width="50">ฤแบฟn hแบกn</th> <th width="50">Ngร y tแบกo</th> <!-- <th width="50">Cแบญp nhแบญt</th> --> </tr> </thead> <tbody> <?php if(count($result) == 0) { $result = []; } foreach ($result as $rows) { ?> <tr class="border-bot-1"> <td> <a class="buttonsearchiframe" onclick="addTab('<?php echo base_url().'ticket/detail/'.$rows['ticketid'].'/'.$rows['custid'].'/'.$rows['idcard'] ?>','#<?php echo $rows['ticketid'] ?>')" href="#"> <span class="id-label span-warning">P</span> #<?php echo $rows['ticketid'] ?> </a> </td> <td> <?php echo $rows['title'] ?> </td> <td><?php if(isset($rows['custname'])){ echo $rows['custname'];} ?></td> <td><?php if(isset($rows['agentcurrentname'])){ echo $rows['agentcurrentname'];} ?></td> <td><?php if ($rows['priority']==1) {echo "Thฦฐแปng";} elseif ($rows['priority']==2) {echo "Cao";} elseif ($rows['priority']==3) {echo "Khแบฉn cแบฅp";} else {echo "Khรดng xรกc ฤ‘แป‹nh";} ?></td> <td><?php echo date("d/m/Y H:i:s", strtotime($rows['duedate']));?></td> <td><?php echo date("d/m/Y H:i:s", strtotime($rows['createat']));?></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-3 no-padding padding-left-10 col-md-22"> <div class="padding-5 margin-bot-5"> <div class="clearfix"> <div> <h5 class="tile-title folder-head font-size-12 font-weight-500">Phรขn chia Cรดng viแป‡c <a href=""><i class="fa fa-sync-alt fa-md float-right margin-top-3"></i></a></h5> </div> <ul class="nav nav-pills flex-column margin-left-5 margin-right-5"> <li> <a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10"> Cรดng viแป‡c chฦฐa xแปญ lรฝ cแปงa tรดi <label class="float-right" id="_o"></label></p> </a> </li> <li> <a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10"> Cรดng viแป‡c ฤ‘ang xแปญ lรฝ cแปงa tรดi <label class="float-right" id="_w"></label></p> </a> </li> <li> <a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10"> Cรดng viแป‡c ฤ‘รฃ hoร n thร nh <label class="float-right" id="_c"></label></p> </a> </li> <li> <a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10"> Toร n bแป™ Cรดng viแป‡c cแปงa tรดi <label class="float-right" id="_a"></label></p> </a> </li> <li> <a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10"> Toร n bแป™ cรดng viแป‡c cแปงa nhรณm <label class="float-right" id="_ga"></label></p> </a> </li> <li> <a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10"> Cรดng viแป‡c cแปงa nhรณm chฦฐa xแปญ lรฝ <label class="float-right" id="_go"></label></p> </a> </li> </ul> </div> </div> </div> <div class="col-md-8 no-padding padding-left-1 col-md-78"> <div class="tile height-1024"> <div class="content-title"> <div class="div"> <h5 id="_type">Toร n bแป™ Cรดng viแป‡c cแปงa tรดi</h5> </div> </div> <div class="table-responsive"> <table class="table" id="table-1"> <thead class="no-border"> <tr> <th>ID Task</th> <th>Tแปฑa ฤ‘แป</th> <th>Ngร y yรชu cแบงu</th> <th>Mแปฉc ฤ‘แป™ ฦฐu tiรชn</th> <th>Trแบกng thรกi cรดng viแป‡c</th> <th>Nhรณm</th> <th>Phแปฅ trรกch</th> <th>Ngร y ฤ‘แบฟn hแบกn</th> </tr> </thead> <tbody> <?php $_a=0;$_o=0;$_w=0;$_c=0;$_ga=0;$_go=0; if (isset($record)) { foreach ($record as $key => $value) { ?> <tr class="border-bot-1"> <td width="150"> <span class="id-label span-warning">T</span> <a class="new_tab" onclick="addTab('<?php echo(base_url('task/detail/'.$value['taskid']));?>','<?php echo('#'.$value['taskid']);?>')" href="#">#<?php echo($value['taskid']);?></a> </td> <td width="250"> <?php echo($value['title']);?> </td> <td><?php echo date('d-m-Y',strtotime($value['requestdate']));?></td> <td> <?php switch ($value['priority']) { case '1': echo("Thฦฐแปng"); break; case '2': echo("Cao"); break; case '3': echo("Khแบฉn cแบฅp"); break; default: echo("Khรดng xรกc ฤ‘แป‹nh"); break; } ?> </td> <td> <?php if ($value['pic']==$this->session->userdata('custid')) {$_a++;} switch ($value['status']) { case 'O': echo("Chแป xรกc nhแบญn"); if ($value['pic']==$this->session->userdata('custid')) {$_o++;} break; case 'W': echo("ฤang xแปญ lรฝ"); if ($value['pic']==$this->session->userdata('custid')) {$_w++;} break; case 'C': echo("Hoร n thร nh"); if ($value['pic']==$this->session->userdata('custid')) {$_c++;} break; case 'X': echo("Hแปงy"); break; default: echo("Khรดng xรกc ฤ‘แป‹nh"); break; } ?> </td> <td> <?php switch ($value['tic']) { case $this->session->userdata('groupid'): $_ga++; if ($value['pic']=='') { $_go++; } echo $value['tic']; break; default: echo $value['tic']; break; } ?> </td> <td> <?php echo $value['pic']; ?> </td> <td><?php echo date('d-m-Y',strtotime($value['duedate']));?></td> </tr> <?php }} ?> </tbody> <tfoot class="no-border" status-o="<?php echo($_o);?>" status-w="<?php echo($_w);?>" status-c="<?php echo($_c);?>" status-ga="<?php echo($_ga);?>" status-go="<?php echo($_go);?>" status-a="<?php echo($_a);?>"> </tfoot> </table> </div> </div> </div> </div> </main><file_sep><?php class M_data extends CI_Model { var $otherdb; public function __construct() { parent::__construct(); $this->otherdb = $this->load->database('sqlsvr12', TRUE); } function record_exists($record,$table) { $this->db->where($record); $query = $this->db->get($table); if ($query->num_rows() > 0){ return true; } else{ return false; } } function key_record_exists($key,$record,$table) { $this->db->where($key,$record); $query = $this->db->get($table); if ($query->num_rows() > 0){ return true; } else{ return false; } } function null_key($match,$key,$table) { $this->db->select($key); $this->db->where($match); $this->db->where($key.'!=',''); $query = $this->db->get($table); if ($query->num_rows() > 0){ return false; } else{ return true; } } function load_field_table($table){ return $this->db->list_fields($table); } function select_option($select,$match,$table){ $this->db->select($select) ->from($table) ->where($match); $query = $this->db->get(); return $query->result_array(); } function select_row_limit($select,$match,$table,$start,$numrow){ $this->db->select($select) ->from($table) ->where($match) ->limit($numrow,$start); $query = $this->db->get(); return $query->result_array(); } function update($match,$data,$table){ $result = $this->db->where($match) ->update($table,$data); return $result; } function insert($data,$table) { $this->db->insert($table, $data); return $this->db->insert_id(); } function get_all_row($table){ $this->db->select() ->from($table); $query = $this->db->get(); return $query->result_array(); } function get_row($match,$table){ $this->db->select() ->from($table) ->where($match); $query = $this->db->get(); return $query->result_array(); } function select_row($where,$orwhere,$table){ $this->db->select(); $this->db->from($table); $this->db->where($where); if(!empty($orwhere))$this->db->or_where($orwhere); $query = $this->db->get(); return $query->result_array(); } function user_login($username, $password, $table) { $pass = md5($<PASSWORD>); $sql = "SELECT * FROM $table WHERE (custid = '$username' OR email = '$username' OR telephone = '$username') AND password = <PASSWORD>'"; $query = $this->otherdb->query($sql); if (!$query) { return $this->otherdb->error(); } return $query->result_array(); } public function uploadfile($file,$name){ // var_dump($file); $config['upload_path'] = '../upload/'; $config['allowed_types'] = 'jpg|jpeg|png|gif'; $config['file_name'] = $file[$name]['name']; $this->load->library('upload', $config); $this->upload->initialize($config); if ($this->upload->do_upload($name)) { $uploadData = $this->upload->data(); var_dump($uploadData); return $this->config->item('file_upload_url').$uploadData['file_name']; echo "file upload success!! "; } else{ var_dump($this->upload->display_errors()); return false; } } public function array_to_string($array,$index_key,$index_value){ $string = ''; // var_dump($array); foreach ($array as $key => $value) { $string.=$value[$index_key].':'.$value[$index_value].';'; } return substr($string, 0, strlen($string)-1); } public function count_row($select,$where,$table,$join,$order_by,$like,$or_like){ $this->db->select($select); $this->db->from($table); if(!empty($join)){ foreach ($join as $key => $value) { $this->db->join($value['table'],$value['match']); } } $this->db->where($where); if(!empty($like))$this->db->like($like); if(!empty($or_like))$this->db->or_like($or_like); $this->db->order_by($order_by['colname'],$order_by['typesort']); $query = $this->db->get(); return $query->num_rows(); } function select_row_option($select,$where,$table,$join,$limit,$order_by,$like,$or_like){ $this->db->select($select); $this->db->from($table); if(!empty($join)){ foreach ($join as $key => $value) { $this->db->join($value['table'],$value['match']); } } $this->db->where($where); if(!empty($like))$this->db->like($like); if(!empty($or_like))$this->db->or_like($or_like); if(!empty($order_by))$this->db->order_by($order_by['colname'],$order_by['typesort']); if(!empty($limit))$this->db->limit($limit['numrow'],$limit['start']); $query = $this->db->get(); return $query->result_array(); } function toPermission($array){ $arr = []; if (!empty($array)) { for ($i=0; $i < count($array); $i++) { $arr[$array[$i]['to_table']][$array[$i]['id_rights']] = $array[$i]['active']; } } return $arr; } function trans_insert_baohiem($data1,$data2){ $this->db->trans_start(); $id = $this->insert($data2,'customer'); var_dump($id); $data1['id_customer'] = $id; $this->insert($data1,'pre_traff'); if($this->db->trans_status() === FALSE){ $this->db->trans_rollback(); return false; }else{ $this->db->trans_complete(); return true; } } function trans_insert_user($user_acc,$user_info){ $this->db->trans_start(); $id = $this->insert($user_info,'user_info'); $user_acc['user_info'] = $id; $this->insert($user_acc,'users'); if($this->db->trans_status() === FALSE){ $this->db->trans_rollback(); return false; }else{ $this->db->trans_complete(); return true; } } public function send_sms($phone,$text){ try { $client = new SoapClient('http://g3g4.vn:8008/smsws/services/SendMT?wsdl'); $content = array( 'username' => 'globalsafe1', 'password' => '<PASSWORD>', 'receiver' => $phone, 'content' => $text, 'loaisp' => '2', 'brandname' => 'GLOBALSAFE', 'target' => '123456', ); $quote = $client->sendSMS($content); return $quote->return; } catch (Exception $e) { return $e->getMessage(); } } } <file_sep><div class="tile height-1024 p-0 padding-5"> <div> <h5 class="tile-title folder-head"><i class="fa fa-user fa-fw"></i> Ngฦฐแปi dรนng</h5> </div> <div class="tile-body padding-left-right-10 fon-size-14"> <ul class="nav nav-pills flex-column mail-nav"> <li> <a style="cursor: pointer;" class="dropdown-item no-padding margin-top-bot-10 border-radius-3" onclick="clickChangeIframe('<?php echo base_url()?>setting/viewUser')"> <p class="no-padding no-margin padding-left-right-10"> Ngฦฐแปi dรนng</p> </a> </li> <li> <a style="cursor: pointer;" class="dropdown-item no-padding margin-bot-10 border-radius-3" onclick="clickChangeIframe('<?php echo base_url()?>groupuser')"> <p class="no-padding no-margin padding-left-right-10"> Nhรณm ngฦฐแปi dรนng</p> </a> </li> <li> <a style="cursor: pointer;" class="dropdown-item no-padding margin-bot-10 border-radius-3" onclick="clickChangeIframe('<?php echo base_url()?>groupuser/fielduser')"> <p class="no-padding no-margin padding-left-right-10"> Trฦฐแปng dแปฏ liแป‡u ngฦฐแปi dรนng</p> </a> </li> </ul> </div> <div> <h5 class="tile-title folder-head"><i class="fa fa-file-alt fa-fw"></i> Phiแบฟu hแป— trแปฃ</h5> </div> <div class="tile-body padding-left-right-10 fon-size-14"> <ul class="nav nav-pills flex-column mail-nav"> <li> <a style="cursor: pointer;" class="dropdown-item no-padding margin-bot-10 border-radius-3" onclick="clickChangeIframe('<?php echo base_url()?>groupuser/fieldticket')"> <p class="no-padding no-margin padding-left-right-10"> Trฦฐแปng dแปฏ liแป‡u Phiแบฟu hแป— trแปฃ</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10"> Mแบซu phiแบฟu hแป— trแปฃ</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10"> Thแบป (Tags)</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10"> Macros</p> </a> </li> </ul> </div> <div> <h5 class="tile-title folder-head"><i class="fas fa-database"></i> DataSource</h5> </div> <div class="tile-body padding-left-right-10 fon-size-14"> <ul class="nav nav-pills flex-column mail-nav"> <li> <a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>typework','Loแบกi cรดng viแป‡c')"> <p class="no-padding no-margin padding-left-right-10"> Loแบกi cรดng viแป‡c</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>detailwork','Chi tiแบฟt cรดng viแป‡c')"> <p class="no-padding no-margin padding-left-right-10"> Chi tiแบฟt cรดng viแป‡c</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>datastage','Giai ฤ‘oแบกn')"> <p class="no-padding no-margin padding-left-right-10"> Giai ฤ‘oแบกn</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>issuetype','Phรขn loแบกi')"> <p class="no-padding no-margin padding-left-right-10"> Phรขn loแบกi</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>issuegroup','Nhรณm vแบฅn ฤ‘แป')"> <p class="no-padding no-margin padding-left-right-10"> Nhรณm vแบฅn ฤ‘แป</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>issuedetail','Chi tiแบฟt vแบฅn ฤ‘แป')"> <p class="no-padding no-margin padding-left-right-10"> Chi tiแบฟt vแบฅn ฤ‘แป</p> </a> </li> </ul> </div> <div> <h5 class="tile-title folder-head"><i class="fa fa-signal fa-fw"></i> Kรชnh tฦฐฦกng tรกc</h5> </div> <div class="tile-body padding-left-right-10 fon-size-14"> <ul class="nav nav-pills flex-column mail-nav"> <li> <a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10"> E-mail</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10"> Phone</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10"> Chat</p> </a> </li> </ul> </div> <div> <h5 class="tile-title folder-head"><i class="fa fa-briefcase fa-fw"></i>Nghiแป‡p vแปฅ</h5> </div> <div class="tile-body padding-left-right-10 fon-size-14"> <ul class="nav nav-pills flex-column mail-nav"> <li> <a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10">Cam kแบฟt dแป‹ch vแปฅ (SLA)</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10">Phรขn chia phiแบฟu</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10">Triggers</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10">Automations</p> </a> </li> </ul> </div> <div> <h5 class="tile-title folder-head"><i class="fa fa-sliders-h fa-fw"></i>Cร i ฤ‘แบทt</h5> </div> <div class="tile-body padding-left-right-10 fon-size-14"> <ul class="nav nav-pills flex-column mail-nav"> <li> <a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10">Tร i khoแบฃn</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10">Bแบฃo mแบญt</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10">Phiแบฟu hแป— trแปฃ</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#"> <p class="no-padding no-margin padding-left-right-10">CV CSKH</p> </a> </li> <li> <a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>queue','Hร ng chแป')"> <p class="no-padding no-margin padding-left-right-10"> Hร ng chแป</p> </a> </li> </ul> </div> </div><file_sep><script type="text/javascript"> $(document).ready(function(){ $('#table-1-knowledge').DataTable({ "paging": true, "language": { "paginate": { "previous": "Trฦฐแป›c", "next":"Sau" } }, "columns": [ { "width": "18%" }, { "width": "17%" }, { "width": "10%" }, { "width": "15%" }, { "width": "10%" }, { "width": "10%" }, { "width": "10%" } ], "info": false, "ordering": false, "searching": false, "scrollY": "100%", "iDisplayLength": 15, "scrollX": true, "bLengthChange": false, "scrollCollapse": true }).columns.adjust().draw(); var tickettype = $('select#level_1').val(); if (tickettype!='') { $('select#level_2 option').each(function(){ var ref1 = $(this).attr('ref1'); if (ref1==tickettype) {$(this).removeClass('hide').addClass('show');} else{$(this).addClass('hide').removeClass('show');} }); $('select#level_2 option.show:first').prop('selected',true); } var groupid = $('select#level_2').val(); if (groupid!='') { $('select#level_3 option').each(function(){ var ref2 = $(this).attr('ref2'); if (ref2==groupid) {$(this).removeClass('hide').addClass('show');} else{$(this).addClass('hide').removeClass('show');} }); $('select#level_3 option.show:first').prop('selected',true); } $('select#level_1').change(function(){ var val = $(this).val(); $('select#level_2 option:first').prop('selected',true); $('select#level_3 option:first').prop('selected',true); if(val){ $('select#level_2 option, select#level_3 option').each(function(){ var ref1 = $(this).attr('ref1'); var all = $(this).attr('all'); if (ref1==val || all || val=="all") { $(this).removeClass('hide'); }else{ $(this).addClass('hide'); } }); }else{ $('select#level_2 option, select#level_3 option').each(function(){ var all = $(this).attr('all'); if (!all) { $(this).removeClass('hide'); } }); } }); $('select#level_2').change(function(){ var val = $(this).val(); var all = $(this).find('option:selected').attr('all'); var ref1 = $('select#level_1').val(); $('select#level_3 option:first').prop('selected',true); if(val){ $('select#level_3 option').each(function(){ var ref2 = $(this).attr('ref2'); var all = $(this).attr('all'); if (ref2==val || all || val=="all") { $(this).removeClass('hide'); }else{ $(this).addClass('hide'); } }); }else if(all){ $('select#level_3 option').each(function(){ var val1 = $(this).attr('ref1'); var all = $(this).attr('all'); if (ref1==val1 || all || val=='all') { $(this).removeClass('hide'); }else{ $(this).addClass('hide'); } }); }else{ $(this).removeClass('hide'); } }); }); $('#btn-search').click(function(){ // alert($(this).attr('id')); var text = $('#search_area input[name="s_text"]').val(); var group = $('#search_area select[name="s_group"]').val(); var cate = $('#search_area select[name="s_cate"]').val(); var type = $('#search_area select[name="s_type"]').val(); var createby = $('#search_area select[name="s_createby"]').val(); if (text.length>50) { alert('Khรดng ฤ‘ฦฐแปฃc nhแบญp quรก 50 kรฝ tแปฑ.'); }else{ document.getElementById('iframesearch').src = "<?php echo base_url().'knowledge/search/?groupid='?>"+group+"&categoryid="+cate+"&tickettype="+type+"&createby="+createby+"&search="+text; } }); </script><file_sep><script type="text/javascript"> $(document).ready(function(){ $('#tableUser').DataTable({ "paging": true, "language": { "paginate": { "previous": "Trฦฐแป›c", "next":"Sau" } }, "order": false, "info": false, "searching": false, "scrollY": "100%", "scrollX": true, "bLengthChange": false, "scrollCollapse": true }).columns.adjust().draw(); $('#keyword').keypress(function(e1){ if(e1.keyCode==13){ // if user is hitting enter search(); } }); }); function search() { $('#loading').attr('style', 'display: initial;width: 30px; height: 30px;'); var keyword = $('#keyword').val(); $.ajax({ url: '<?php echo base_url()?>setting/searchUser', type: 'POST', dataType: 'JSON', data: {keyword : keyword}, }) .done(function(data) { $('#loading').attr('style', 'display:none'); var data_html = ''; for(var i = 0;i<data.data.length;i++) { var custid = data.data[i].custid; var idcard = data.data[i].idcard; var roleid = data.data[i].roleid; var url1 = '<?php echo base_url() ?>user/detail/?cusid='+custid+'&idcard='+idcard+'&roleid='+roleid; var url = "'"+url1+"'"; var custname = "'"+data.data[i].custname+"'"; data_html+= '<tr>\ <td width="40px">\ <img class="user-avatar" src="'+data.data[i].avatar+'" alt="User Image">\ </td>\ <td width="252px">\ <a class="user-name" style="cursor: pointer;" onclick="addTab('+url+','+custname+')">'+data.data[i].custname+'</a>\ <p class="">'+data.data[i].groupname+'</p>\ </td>\ <td width="229px">'+data.data[i].telephone+'</td>\ <td width="218px">'+data.data[i].email+'</td>\ </tr>'; } $('.content-search').html('<div class="table-responsive">\ <table class="table" id="tableUser">\ <thead>\ <tr>\ <th></th>\ <th>Hแป tรชn</th>\ <th>SฤT</th>\ <th>Email</th>\ </tr>\ </thead>\ <tbody>'+data_html+'\ </tbody>\ </table>\ </div>'); $('#tableUser').DataTable({ "paging": true, "language": { "paginate": { "previous": "Trฦฐแป›c", "next":"Sau" } }, "order": false, "info": false, "searching": false, "scrollY": "100%", "scrollX": true, "bLengthChange": false, "scrollCollapse": true }).columns.adjust().draw(); }) .fail(function() { console.log('error'); $('#loading').attr('style', 'display:none'); }) } function searchRoleid(roleid) { $('#loading').attr('style', 'display: initial;width: 30px; height: 30px;'); var keyword = ''; $.ajax({ url: '<?php echo base_url()?>setting/searchUser', type: 'POST', dataType: 'JSON', data: {keyword : keyword}, }) .done(function(data) { $('#loading').attr('style', 'display:none'); var data_html = ''; for(var i = 0;i<data.data.length;i++) { if(data.data[i].roleid == roleid) { var custid = data.data[i].custid; var idcard = data.data[i].idcard; var url1 = '<?php echo base_url() ?>user/detail/?cusid='+custid+'&idcard='+idcard+'&roleid='+roleid; var url = "'"+url1+"'"; var custname = "'"+data.data[i].custname+"'"; data_html+= '<tr>\ <td width="40px">\ <img class="user-avatar" src="'+data.data[i].avatar+'" alt="User Image">\ </td>\ <td width="252px">\ <a class="user-name" style="cursor: pointer;" onclick="addTab('+url+','+custname+')">'+data.data[i].custname+'</a>\ <p class="">'+data.data[i].groupname+'</p>\ </td>\ <td width="229px">'+data.data[i].telephone+'</td>\ <td width="218px">'+data.data[i].email+'</td>\ </tr>'; } } $('.content-search').html('<div class="table-responsive">\ <table class="table" id="tableUser">\ <thead>\ <tr>\ <th></th>\ <th>Hแป tรชn</th>\ <th>SฤT</th>\ <th>Email</th>\ </tr>\ </thead>\ <tbody>'+data_html+'\ </tbody>\ </table>\ </div>'); $('#tableUser').DataTable({ "paging": true, "language": { "paginate": { "previous": "Trฦฐแป›c", "next":"Sau" } }, "order": false, "info": false, "searching": false, "scrollY": "100%", "bLengthChange": false, "scrollX": true, "scrollCollapse": true }).columns.adjust().draw(); }) .fail(function() { alert("Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ admin"); }) } function clickChangeIframe(src) { document.getElementById('iframesetting').src = src; } </script><file_sep><div class="timeline"> <?php $array = array("gray","red","green","yellow"); $i = 0; if(count($history)>0) { foreach ($history as $value) { if($i >3) { $i=0; } ?> <div class="entry"> <div class="title <?php echo $array[$i] ?>"> <p class="time-detail"><?php if($value['createdat'] !=null) { echo date("G:i:s", strtotime($value['createdat']));} ?></p> <p class="date-detail"><?php if($value['createdat'] !=null) { echo date("d/m/Y", strtotime($value['createdat']));} ?></p> </div> <div class="body"> <p class="margin-bot-3"><?php echo $value['action'] ?></p> <p class="no-margin-bot"> <?php $log_type = $value['typelog']; if($log_type=='T'){ $link = base_url()."ticket/detail/".$value['ticketid']; ?> <a href="#" onclick="parent.addTab('<?php echo $link;?>','#<?php echo $value['ticketid'] ?>')">#<?php echo $value['ticketid'] ?></a><br> <?php echo $value['changelog']; } $data = json_decode($value['changelog'],true); if(count($data)>0) { $labelaction = ''; foreach ($data as $key => $value) { if($key == "custname") { echo "Hแป vร  tรชn: ".$value."<br />"; } if($key == "gender") { echo "Giแป›i tรญnh: ".switchGender($value)."<br />"; } if($key == "telephone") { echo "Sแป‘ ฤ‘iแป‡n thoแบกi: ".$value."<br />"; } if($key == "fullbirthday") { echo "Ngร y Sinh: ".$value."<br />"; } if($key == "email") { echo "Email: ".$value."<br />"; } if($key == "comments") { echo "Ghi chรบ: ".$value."<br />"; } if($key == "roleid") { echo "Phรขn quyแปn: ".switchRoleId($value,$role_list)."<br />"; } if($key == "groupid") { echo "Nhรณm: ".switchGroupId($value,$group_list)."<br />"; } if($key == "extinfo") { echo switchExtField($value,$list_ext); } if($key == "idcard") { echo "CMND: ".$value."<br />"; } if($key == "issueddate") { echo "Ngร y cแบฅp: ".$value."<br />"; } if($key == "issuedplace") { echo "Nฦกi cแบฅp: ".$value."<br />"; } if($key == "action") { if($value == "deletephone") { $labelaction = "Xoรก SฤT: "; } else { $labelaction = "Xoรก Email: "; } } if($key == "telephonelist") { foreach ($value as $key1 => $data1) { if(count($data) == 2) { echo "Xรณa SฤT: ".$data1; break; } else { echo "Thรชm SDT: ".$labelaction.=$data1; } } } if($key == "emaillist") { foreach ($value as $key1 => $data1) { if(count($data) == 2) { echo "Xรณa Email: ".$data1; break; } else { echo "Thรชm Email: ".$labelaction.=$data1; } } } /* if($key == "emaillist") { foreach ($value as $key1 => $data1) { $labelaction = $data1; } if(count($data) == 2) { echo "Thรชm Email: ".$labelaction; } } */ if($key == "city") { echo "Thร nh phแป‘: ".$value."<br />" ; } if($key == "district") { echo "Quแบญn/ Huyแป‡n: ".$value."<br />" ; } if($key == "ward") { echo "Phฦฐแปng/ Xรฃ: ".$value."<br />" ; } if($key == "street") { echo "ฤฦฐแปng: ".$value."<br />" ; } if($key == "address") { echo "Sแป‘ nhร : ".$value."<br />" ; } if($key == "label") { echo "Nhรฃn ฤ‘แป‹a chแป‰: ".$value."<br />" ; } } } ?></p> </div> </div> <?php $i++;}} ?> </div> <?php function switchGender($value1) { if($value1 == "M") { return "Nam"; } else{ return "Nแปฏ"; } } function switchRoleId($value1,$role_list) { if(count($role_list)>0) { foreach ($role_list as $key => $value) { if($value1 == $key) { return $value; } } } } function switchGroupId($value1,$group_list) { if(count($group_list)>0){ foreach ($group_list as $value) { if($value1 == $value['groupid']) { return $value['groupname']; } } } } function switchExtField($extfields,$list_ext) { $text = ""; if(count($extfields)>0) { foreach ($extfields as $key => $value) { foreach ($list_ext as $value1) { if($key == $value1['fieldcode']) { $text.= $value1['fieldname'].": ".$value."</br>"; } } } } return $text; } ?><file_sep><main class="app-content col-md-100 no-padding no-margin"> <div class="tile height-1024"> <div class="offset-10 col-md-2 margin-bot-10"> <?php $link = base_url().'knowledge/detail'; $title = 'Thรชm Knowledge'; ?> <button onclick="addTab('<?php echo $link?>','<?php echo $title ?>')" class="btn btn-primary float-right" id="ck-edit" type="button"> Thรชm mแป›i </button> </div> <div class="table-responsive"> <table class="table" id="table-1-knowledge"> <thead class="no-border-top"> <tr> <th>Chแปง ฤ‘แป</th> <th>Phรขn loแบกi</th> <th width="100">Nhรณm vแบฅn ฤ‘แป</th> <th>Chi tiแบฟt Vฤ</th> <th>ฤฤƒng bแปŸi</th> <th>Ngร y ฤ‘ฤƒng</th> <th>Trแบกng thรกi</th> </tr> </thead> <tbody> <?php if(!empty($news)){ foreach ($news as $key => $value) { ?> <tr class="border-bot-1"> <?php $linkUpdate= base_url().'knowledge/detail/edit/'.$value['id']; $titleUpdate = 'Cแบญp nhแบญt Knowledge '.$value['id']; ?> <td><a onclick="addTab('<?php echo $linkUpdate ?>','<?php echo $titleUpdate ?>')" href="#"><?php echo $value['title'] ?></a></td> <td> <?php if (isset($l_type) && !empty($l_type)) { $exi = 'Khรดng xรกc ฤ‘แป‹nh'; foreach ($l_type as $k => $v) { if ($value['tickettype']==$v['code']) { $exi = $v['name']; break; } } echo $exi; } ?> </td> <td> <?php if (isset($l_group) && !empty($l_group)) { $exi = 'Khรดng xรกc ฤ‘แป‹nh'; foreach ($l_group as $k => $v) { if ($value['groupid']==$v['code']) { $exi = $v['name']; break; } } echo $exi; } ?> </td> <td> <?php if (isset($l_cate) && !empty($l_cate)) { $exi = 'Khรดng xรกc ฤ‘แป‹nh'; foreach ($l_cate as $k => $v) { if ($value['categoryid']==$v['code']) { $exi = $v['name']; break; } } echo $exi; } ?> </td> <td><?php echo($value['custname']); ?></td> <td><?php echo date("d-m-Y", strtotime($value['createdat'])); ?></td> <td><?php if($value['hidden']=='0')echo "ฤang hoแบกt ฤ‘แป™ng"; else echo "Ngฦฐng hoแบกt ฤ‘แป™ng"; ?></td> <!-- <td><?php echo($value['hidden']); ?></td> --> </tr> <?php }} else echo("the data is empty"); ?> </tbody> </table> </div> </div> </main><file_sep><?php $type = "D"; $queue = $this->input->get('queue'); ?> <div class="tile height-1024"> <div class="content-title"> <div class="div"> <h5>Danh sรกch hร ng chแป: <?php echo nameTitle($queue) ?></h5> </div> </div> <div style="float: right;"> <button <?php if($type == 'T'){echo 'hidden';} ?> type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right" data-toggle="modal" data-target="#myModal">Thรชm</button> </div> <div class="bs-component" style="margin-top: 55px"> <?php if ($type == 'T'){ echo '<div class="component-fields"> <i class="fas fa-align-justify"></i> <span class="title_tab" style="padding-left: 6px">Text</span> </div>'; } ?> <?php if(count($extension)>0){ foreach ($extension as $value) { ?> <div class="component-fields" style=""> <i class="fas fa-align-justify" style=""></i> <span class="title_tab" style="padding-left: 6px; "><?php echo $value['extension']." (ฦฏu tiรชn: ".$value['status'].")" ?></span> <!-- <a class="user-name" style="cursor: pointer;float: right; margin-right: 15px" data-toggle="modal" data-target="#modalUpdate" data-telephone="<?php echo $value['extension'] ?>" data-queue="<?php echo $value['queuecode'] ?>" data-status="<?php echo $value['status'] ?>"><i class="fas fa-edit"></i></a> --> <a class="user-name" style="cursor: pointer;float: right;" data-toggle="modal" data-target="#modalDelete" data-telephone="<?php echo $value['extension'] ?>" data-queue="<?php echo $value['queuecode'] ?>"><i class="fas fa-sign-out-alt"></i></a> </div> <?php }}?> </div> </div> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document" style="margin-top: 5%"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Thรชm Extension:</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class=""> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Hร ng ฤ‘แปฃi:</label> <select name="ref1_insert" onchange="getGroup(this,'ref2_insert')" class="control-label col-md-8 col-sm-8 no-border no-padding" id="queue_login"> <option value="<?php echo $queue ?>" selected=""><?php echo nameTitle($queue) ?></option> </select> </div> <div class="form-group extendbottom"> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Sแป‘ ฤ‘iแป‡n thoแบกi: </label> <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left"> <input type="text" class="col-md-12 no-padding font-size-12" name="telephone_login" id="telephone_login" placeholder="-SฤT"></label> </div> <div class="form-group extendbottom"> <label class="control-label user-label col-md-3 col-sm-3 no-padding">ฤแป™ ฦฐu tiรชn: </label> <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left"> <input type="text" class="col-md-12 no-padding font-size-12" name="status_insert" id="status_insert" placeholder="-ฤแป™ ฦฐu tiรชn"></label> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">ฤรณng</button> <button type="button" onclick="loginButton()" class="btn btn-primary">Thรชm</button> </div> </div> </div> </div> <div class="modal fade" id="modalDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 7%" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">ฤฤƒng Xuแบฅt Hร ng chแป</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <p class="bg-danger" style="padding: 10px;color: #FFF;" >Bแบกn cรณ chแบฏc muแป‘n ฤ‘ฤƒng xuแบฅt khรดng?</p> <input type="hidden" id="telephone" name="telephone"> <input type="hidden" id="queue" name="queue"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">ฤรณng</button> <button type="button" onclick="logoutButton()" class="btn btn-danger">ฤฤƒng xuแบฅt</button> </div> </div> </div> </div> <div class="modal fade" id="modalUpdate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" style="margin-top: 7%" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Sแปญa Option</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class=""> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Hร ng ฤ‘แปฃi:</label> <select name="ref1_insert" onchange="getGroup(this,'ref2_insert')" class="control-label col-md-8 col-sm-8 no-border no-padding" id="queue_login"> <option value="<?php echo $queue ?>" selected=""><?php echo nameTitle($queue) ?></option> </select> </div> <div class="form-group extendbottom"> <label class="control-label user-label col-md-3 col-sm-3 no-padding">Sแป‘ ฤ‘iแป‡n thoแบกi: </label> <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left"> <input type="text" class="col-md-12 no-padding font-size-12" name="telephone_update" id="telephone_update" placeholder="-SฤT"></label> </div> <div class="form-group extendbottom"> <label class="control-label user-label col-md-3 col-sm-3 no-padding">ฤแป™ ฦฐu tiรชn: </label> <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left"> <input type="text" class="col-md-12 no-padding font-size-12" name="status_update" id="status_update" placeholder="-ฤแป™ ฦฐu tiรชn"></label> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">ฤรณng</button> <button type="button" onclick="updateButton()" class="btn btn-primary">Sแปญa</button> </div> </div> </div> </div> <?php function nameTitle($value) { if($value == "21114") { return "Chuyแปƒn nhฦฐแปฃng hแปฃp ฤ‘แป“ng"; } else if($value == "21115") { return "Thanh toรกn vay"; } else if($value == "21116") { return "Khรกc"; } else if($value == "21121") { return "Tiแบฟng Anh"; } } ?><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-2 col-md-22 padding-left-15"> <?php echo isset($left)?$left:'' ?> </div> <div class="col-md-7 padding-left-1"> <?php echo isset($center)?$center:'' ?> </div> <div class="col-md-2 col-md-18 padding-left-5"> </div> </div> </main><file_sep><script src="<?php echo base_url('callevent/node_modules/socket.io-client/dist/socket.io.js');?>"></script> <script> var timer=null,record=null; $(document).ready(function(){ var socket = io.connect( 'http://'+window.location.hostname+':3000' ,{ query: "custid=C0001<?php echo($this->session->userdata('telephone')!=null?'&phone='.$this->session->userdata('telephone'):'')?>" }); socket.on('connect', function () { clientid = socket.id; $('#phone-chat').attr('extension',"<?php echo($this->session->userdata('telephone')!=null?$this->session->userdata('telephone'):'')?>"); // socket.emit('new_client', { // name: getRandomName(), // phone: getRandomNumber(), // id: clientid // }); }); socket.on( 'new_connect', function( data ) { console.log(data); }); socket.on('object_event',function(data){ // console.log(data); }); // $.post( // "http://"+window.location.hostname+":3000/call", // { // name: getRandomName(), // phone: getRandomNumber() // }, // function(data){ // console.log(data); // }); function getRandomName() { const arr = ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"]; return arr[Math.floor(Math.random() * arr.length)]; } function getRandomNumber() { const arr = ["2455","7895","1230","4587","7849","2368","7842","8953","7412","5687"]; return arr[Math.floor(Math.random() * arr.length)]; } socket.on( 'disconnect_client', function( data ) { console.log(data); $("#node-view").find('button[id="'+data.client+'"]').remove(); }); socket.on( 'new_client', function( data ) { console.log(data); $("#node-view").append('<button class="btn btn-primary btn-call" type="button" id="'+data.id+'">'+data.name+' - '+data.phone+'</button> '); }); socket.on('e_ringing',function(data){ console.log(data); // save_call_log("call","ringing",data); var phone = data.fromnumber; var p_data = {}; $('#phone-chat').css('display','block'); hideScreen(0,p_data); start_timer('#has-call-pad #c-time'); p_data['phone'] = phone; p_data['channel'] = data.channel; $.ajax({ type: "GET", url: 'http://'+window.location.hostname+'/api/get_infor_user/'+phone, dataType: "json", success: function(data){ if (data.data!=null) { var rec = data.data[0]; console.log(rec); p_data['avatar'] = rec.avatar; p_data['custname'] = rec.custname; p_data['custid'] = rec.custid; p_data['idcard'] = rec.idcard; p_data['phone_act'] = 'newtab'; hideScreen(0,p_data); }else{ p_data['avatar'] = null; p_data['custname'] = "---"; p_data['phone_act'] = 'newuser'; hideScreen(0,p_data); } },error: function(xhr, status, error) { console.log(error); p_data['avatar'] = null; p_data['custname'] = "---"; p_data['phone_act'] = 'newuser'; hideScreen(0,p_data); } }); }); socket.on('e_answered',function(data){ console.log('e_answered'); console.log(data); // save_call_log("call","answered",data); var phone = data.fromnumber; var callrefid = data.callrefid; var p_data = {}; var act = $('#has-call-pad #c-number').attr('act'); var custid = $('#has-call-pad #c-number').attr('custid'); var cname = $('#has-call-pad #c-name').html(); var idcard = $('#has-call-pad #c-name').attr('idcard'); console.log(act+'-'+custid+'-'+phone+'-'+cname+'-'+idcard); p_data['phone'] = phone; p_data['channel'] = data.channel; p_data['custid'] = custid; $('#phone-chat').css('display','block'); hideScreen(1,p_data); start_record('#has-call-pad #c-record'); if (act) { if (act=='newtab'&&custid) { addTab('<?php echo base_url().'user/detail/?cusid='?>'+custid+'&idcard='+idcard+'&roleid=3',cname); $.ajax({ type: "POST", url: 'http://'+window.location.hostname+'/api/aj_crm_isrt_ticket/', dataType: "json", data:{ ticketchanel:2, agentcreated:'<?php echo($this->session->userdata('custid'))?>', custid:custid, priority:1, phone:phone, callrefid:callrefid, queue:data.queue }, success: function(data){ console.log(data); p_data['ticket'] = data.data; hideScreen(1,p_data); showTicketTab(data.data); },error: function(xhr, status, error) { console.log(error); alert(error); } }); }else if(act=='newuser'){ $.ajax({ type: "GET", url: 'http://'+window.location.hostname+'/api/aj_tvc_isrt_user/'+phone, dataType: "json", success: function(data){ addTab('<?php echo base_url().'user/detail/?cusid='?>'+data.custid+'&idcard='+phone+'&roleid=3',phone); if (data.code==1) { showNewTab(phone); $.ajax({ type: "POST", url: 'http://'+window.location.hostname+'/api/aj_crm_isrt_ticket/', dataType: "json", data:{ ticketchanel:2, agentcreated:'<?php echo($this->session->userdata('custid'))?>', custid:data.custid, priority:1, phone:phone, queue:data.queue, callrefid:callrefid }, success: function(data){ console.log(data); p_data['ticket'] = data.data; hideScreen(1,p_data); showTicketTab(data.data); },error: function(xhr, status, error) { console.log(error); alert(error); } }); } },error: function(xhr, status, error) { console.log(error); alert(error); } }); } } }); // e_answered event socket.on('e_completed',function(data){ console.log('e_completed'); console.log(data); save_call_log("call","completed",data); // $('#phone-chat').css('display','block'); // hideScreen(1,data.fromnumber); var phone = data.fromnumber; var tonum = data.tonumber; var callrefid = data.callrefid; var record = data.recording_file; var duration = data.billsec; var custid = $('#has-call-pad #c-number').attr('custid'); var ticketid = $('#has-call-pad #c-ticket').attr('ticketid'); console.log(ticketid); $.ajax({ type: "POST", url: 'http://'+window.location.hostname+'/api/aj_crm_isrt_tcklog/', dataType: "json", data:{ ticketid:ticketid, agentcreated:'<?php echo($this->session->userdata('custid'))?>', custid:custid, phone:phone, callrefid:callrefid, record:record, duration:duration, tonum:tonum }, success: function(data){ console.log(data); },error: function(xhr, status, error) { console.log(error); alert(error); } }); }); socket.on('e_misscall',function(data){ console.log('e_misscall'); console.log(data); save_call_log("call","misscall",data); $('#phone-chat').css('display','block'); hideScreen(5,data.fromnumber); }); socket.on('e_hangup',function(data){ console.log('e_hangup'); console.log(data); // save_call_log("call","hangup",data); $('#phone-chat').css('display','block'); hideScreen(5,data.fromnumber); }); socket.on('e_customer_hangup',function(data){ console.log('e_customer_hangup'); console.log(data); // save_call_log("call","hangup",data); $('#phone-chat').css('display','block'); hideScreen(5,data.fromnumber); }); socket.on('e_customer_answered',function(data){ console.log('e_cusomter_answered'); console.log(data); // save_call_log("call","answered",data); var phone = data.tonumber; var extension = data.fromnumber; var p_data = {}; p_data['phone'] = phone; p_data['channel'] = data.channel; p_data['ticket'] = ""; p_data['calltype'] = "Cuแป™c gแปi ฤ‘i"; if (extension=='<?php echo($this->session->userdata('telephone'));?>') { $('#phone-chat').css('display','block'); hideScreen(9,p_data); } stop_timer(); start_record('#has-call-pad #c-record'); }); socket.on('e_misscall_outbound',function(data){ console.log(data); save_call_log("call","misscall",data); hideScreen(5); }); socket.on('e_completed_outbound',function(data){ console.log(data); save_call_log("call","completed",data); var phone = data.fromnumber; var tonum = data.tonumber; var callrefid = data.callrefid; var record = data.recording_file; var duration = data.billsec; var custid = $('#has-call-pad #c-number').attr('custid'); var ticketid = $('#has-call-pad #c-ticket').attr('ticketid'); console.log(ticketid); $.ajax({ type: "POST", url: 'http://'+window.location.hostname+'/api/aj_crm_isrt_tcklog/', dataType: "json", data:{ ticketid:ticketid, agentcreated:'<?php echo($this->session->userdata('custid'))?>', custid:custid, phone:phone, callrefid:callrefid, record:record, duration:duration, tonum:tonum }, success: function(data){ console.log(data); },error: function(xhr, status, error) { console.log(error); alert(error); } }); }); socket.on('e_ringing_outbound',function(data){ console.log(data); // save_call_log("call","ringing",data); var p_data = []; p_data['phone'] = data.tonumber; p_data['channel'] = data.channel; p_data['avatar'] = null; p_data['custname'] = "---"; p_data['ticket'] = ""; hideScreen(8,p_data); start_timer('#has-call-pad #c-time'); }); socket.on('e_not_inuse',function(data){ console.log(data); var status = $('#phone-chat').css("display"); console.log(status); if (status == "block") { console.log(status); hideScreen(5); } }); $(document).on('click','#c-number',function(){ }); $('input#user-call-search').on('keyup',function(){ var val = $(this).val(); if (val!='') { $('i.search-destroy').css('display','block'); }else{ $('i.search-destroy').css('display','none'); } }); $('i.search-destroy').click(function(){ var input = $('input#user-call-search').val(); if (input.length>0) { var newlength = input.length-1; $('input#user-call-search').val(input.substr(0, newlength)).focus(); if (newlength==0) { $('i.search-destroy').css('display','none'); } } }); $('i.search-icon').click(function(){ var text = $('input#user-call-search').val(); if (text.length>0){ console.log(text); $('#call-input').css('display','block'); }else{ $('#call-input').css('display','none'); } }); $('i.call-input-close').click(function(){ $('#call-input').css('display','none'); }); $(document).on('click','.btn-call',function(){ var id = $(this).attr('id'); socket.emit('to_target',id,{event:"ringing"}); }); $(document).on('click','#deny-call,#are-b-end a',function(){ var channel = $('#c-chanel #channel').attr('channel'); stop_timer(); start_record(); if (channel!='Kรชnh thoแบกi') { console.log(channel); $.ajax({ type: "GET", url: 'http://'+window.location.hostname+'/api/aj_mitek_hang_up/'+channel, dataType: "json", success: function(data){ console.log(data); },error: function(xhr, status, error) { console.log(error); } }); }else{ hideScreen(5,{}); } }); $(document).on('click','#are-b-call a',function(){ var extension = $('#phone-chat').attr('extension'); var phone = $('#user-call-search').val(); var p_data = []; if (phone) { stop_timer(); p_data['phone'] = phone; p_data['channel'] = ''; p_data['avatar'] = null; p_data['custname'] = "---"; // p_data['ticket'] = ""; // p_data['phone_act'] = 'newuser'; hideScreen(7,p_data); api_call_to_number(extension,phone); $.ajax({ type: "GET", url: 'http://'+window.location.hostname+'/api/get_infor_user/'+phone, dataType: "json", success: function(data){ if (data.data!=null) { var rec = data.data[0]; console.log(rec); p_data['avatar'] = rec.avatar; p_data['custname'] = rec.custname; p_data['custid'] = rec.custid; p_data['phone_act'] = 'newtab'; hideScreen(7,p_data); } },error: function(xhr, status, error) { console.log(error); } }); } }); $("#status-options ul li").click(function(){ $("#status-options ul li").each(function(){ if ($(this).hasClass('active')) { $(this).removeClass('active'); } }); $(this).addClass('active'); var stt = $(this).attr('id'); var txt = $(this).find('p').html(); $("#status-selection").removeClass().addClass(stt).find('p').html(txt); }); $(document).on('click','.s-rst-li',function(){ var act = $(this).closest('ul').attr('action'); var extension = $('#phone-chat').attr('extension'); var phone = $(this).find('.user-num').html(); var channel = $('#c-chanel #channel').attr('channel'); if (act=='call') { hideScreen(7); api_call_to_number(extension,phone); }else if(act=='tranfer'){ api_tranfer_to_extension(phone,channel); hideScreen(3); } }); $(document).on('click','#direct-call',function(){ var p_data = {}; p_data['channel'] = $('#c-chanel #channel').attr('channel'); p_data['avatar'] = $('#has-call-pad').find('#c-avatar').find('img').attr('src'); p_data['custname'] = $('#has-call-pad').find('#c-name').html(); p_data['phone'] = $('#has-call-pad').find('#c-number').html(); hideScreen(2,p_data); }); $(document).on('click','#key-board',function(){ var pad = $('#num-pad'); if (pad.hasClass('hide')) { pad.removeClass('hide'); $(this).addClass('icon-active'); }else{ pad.addClass('hide'); $(this).removeClass('icon-active'); } }); $(document).on('click','#deny-direct',function(){ hideScreen(2,p_data); }); $(document).on('click','#call-direct',function(){ }); }); function api_call_to_number(extension,phone){ $.ajax({ type: "GET", url: 'http://'+window.location.hostname+'/api/aj_mitek_clicktocall/'+extension+'/'+phone, dataType: "json", success: function(data){ console.log(data); },error: function(xhr, status, error) { console.log(error); } }); } function api_tranfer_to_extension(extension,channel){ $.ajax({ type: "GET", url: 'http://'+window.location.hostname+'/api/aj_mitek_tranfer/'+extension+'/'+channel, dataType: "json", success: function(data){ console.log(data); },error: function(xhr, status, error) { console.log(error); } }); } function start_timer(element){ var time = 0; stop_timer(); timer = setInterval(countdown, 1000); function countdown() { if (time > 59 ) { clearTimeout(timer); }else{ time++; $(element).html('Thแปi gian chแป: '+time+' s'); } } } function stop_timer(){ if (timer!=null) {clearTimeout(timer);timer=null} } function stop_record(){ if (record!=null) {clearTimeout(record);record=null} } function start_record(element){ var timer = 0, minutes, seconds; stop_record(); record = setInterval(function () { minutes = parseInt(timer / 60, 10) seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; $(element).html(minutes + ":" + seconds); if (++timer > 300) { timer = 0; } }, 1000); } function save_call_log(object,event,data){ $.ajax({ type: "POST", url: 'http://'+window.location.hostname+'/api/save_call_log/', dataType: "json", data:{ value:data, object:object, event:event }, success: function(data){ console.log(data); },error: function(xhr, status, error) { console.log(error); alert(error); } }); } function iframe_click(number=undefined,ticket=undefined){ var extension = $('#phone-chat').attr('extension'); if (number && ticket) { api_call_to_number(extension,number); var p_data = []; p_data['phone'] = number; p_data['channel'] = ''; p_data['avatar'] = null; p_data['custname'] = "---"; p_data['ticket'] = ticket; // p_data['phone_act'] = 'newuser'; $('#phone-chat').css("display","block"); hideScreen(7,p_data); $.ajax({ type: "GET", url: 'http://'+window.location.hostname+'/api/get_infor_user/'+number, dataType: "json", success: function(data){ if (data.data!=null) { var rec = data.data[0]; console.log(rec); p_data['avatar'] = rec.avatar; p_data['custname'] = rec.custname; p_data['custid'] = rec.custid; p_data['phone_act'] = 'newtab'; hideScreen(7,p_data); } },error: function(xhr, status, error) { console.log(error); } }); } } </script> <!-- https://api-popupcontact-02.mitek.vn/api/v1/call --> <!-- ac97db2cca493ad87045946aed59eb29 --> <file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Main CSS--> <link rel="stylesheet" type="text/css" href="css/main.css"> <link rel="stylesheet" type="text/css" href="css/customer.css"> <!-- Font-icon css--> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <title>Customer Relationship Management</title> <script src="https://www.google.com/recaptcha/api.js?hl=vi"></script> </head> <body class="height-1024"> <section class="material-half-bg"> <div class="cover"></div> </section> <section class="login-content"> <div class="logo"> <!-- <h1>Vali</h1> --> <img src="images/logo.png"> </div> <div class="row login-box col-xl-12"> <div class="col-xl-6 border-right-offset"> <div class="offset-2 col-xl-8"> <form id="login_form"> <h3 class="login-head"> <img src="images/tavicoCRM.png"> </h3> <div class="form-group"> <label class="control-label login-label">Tรชn ฤ‘ฤƒng nhแบญp</label> <input class="form-control login-input" name="username" type="text" required="" placeholder="Username" autofocus> </div> <div class="form-group"> <label class="control-label login-label">Mแบญt khแบฉu</label> <input class="form-control login-input" name="password" type="<PASSWORD>" required="" placeholder="<PASSWORD>"> </div> <!-- <div class ="form-group lgin"> <div class="g-recaptcha" data-sitekey="<KEY>"></div> </div> --> <div class="form-group"> <p class="text-danger alert-danger"><?php if($this->session->flashdata('message')){echo($this->session->flashdata('message'));}?></p> </div> <div class="form-group btn-container"> <!-- <button type="button" class="btn btn-primary btn-block" onclick="checkCaptcha()"><i class="fa fa-sign-in fa-lg fa-fw"></i>Log in</button> --> <!--<button type="submit" class="btn btn-primary btn-block"><i class="fa fa-sign-in fa-lg fa-fw"></i>Log in</button>--> <button class="btn btn-primary btn-block btn_login" type="submit"><i class="fa fa-sign-in"></i>Log in</button> </div> <div class="form-group"> <!-- <p class="text-danger alert-danger"><?php if($this->session->flashdata('message')){echo($this->session->flashdata('message'));}?></p> --> <!-- <div class="utility"> <div class="animated-checkbox"> <label> <input name="remember_me" type="checkbox"><span class="label-text">Stay Signed in</span> </label> </div> <p class="semibold-text mb-2"><a href="#" data-toggle="flip">Quรชn mแบญt khแบฉu ?</a></p> <p class="semibold-text mb-2"><a href="#" data-toggle="flip">Chฦฐa cรณ tร i khoแบฃn ?</a></p> </div> --> <p class="semibold-text mb-2"><a href="#" data-toggle="flipppp">Quรชn mแบญt khแบฉu ?</a></p> <p class="semibold-text mb-2"><a href="#" data-toggle="flipppp">Chฦฐa cรณ tร i khoแบฃn ?</a></p> </div> </form> <form class="forget-form" action=""> <h3 class="login-head"><i class="fa fa-lg fa-fw fa-lock"></i>Forgot Password ?</h3> <div class="form-group"> <label class="control-label">EMAIL</label> <input class="form-control" type="text" placeholder="Email"> </div> <div class="form-group btn-container"> <button class="btn btn-primary btn-block"><i class="fa fa-unlock fa-lg fa-fw"></i>RESET</button> </div> <div class="form-group mt-3"> <p class="semibold-text mb-0"><a href="#" data-toggle="flip"><i class="fa fa-angle-left fa-fw"></i> Back to Login</a></p> </div> </form> </div> </div> <div class="col-xl-6 text-center"> <h5 class="margin-top-50">THE FRIENDLY <a href="">CUSTOMER SERVICE</a> SYSTEM</h5> <p class="no-margin-bot">Smart help desk support via e-mail, telephony, chatting and moreโ€ฆ</p> <p>CLICK TO DISCOVER AWESOME FEATURE</p> <img class="clearfix" src="images/people.png"> </div> </div> </section> <form method="post" action="<?php echo base_url() ?>dashboard" id="myForm" > <input type="hidden" name="custid" id="custid"> <input type="hidden" name="groupid" id="groupid"> <input type="hidden" name="telephone" id="telephone"> <input type="hidden" name="username" id="username1"> <input type="hidden" name="password" id="<PASSWORD>"> <input type="hidden" name="custname" id="custname"> <input type="hidden" name="avatar" id="avatar"> <input type="hidden" name="roleid" id="roleid"> <input type="hidden" name="idcard" id="idcard"> </form> <!-- Essential javascripts for application to work--> <script src="js/jquery-3.2.1.min.js"></script> <script src="js/popper.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/main.js"></script> <script type="text/javascript" src="<?=base_url()?>js/plugins/sweetalert.min.js"></script> <!-- The javascript plugin to display page loading on top--> <script src="js/plugins/pace.min.js"></script> <?php echo isset($script) ? $script : ''; ?> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <head> <title>Customer Relationship Managerment</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Main CSS--> <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/main.css"> <!-- Font-icon css--> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Customer CSS--> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> <link rel="stylesheet" href="<?php echo base_url() ?>css/jquery.scrolling-tabs.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/customer.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/customer2.css"> </head> <body class="app sidebar-mini rtl sidenav-toggled"> <!-- Navbar--> <?php echo isset($navbar) ? $navbar : ''; ?> <!-- Sidebar menu--> <?php echo isset($sidebar) ? $sidebar : ''; ?> <?php if(isset($link)){ ?> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="1000"> <iframe id="myiframe" class="myiframe" name="myiframe" src="<?php echo base_url().$link ?>" frameborder="0"></iframe> </div> </div> <?php } ?> <div class="holds-the-iframe"> <script type="text/javascript"> var arrayTab = []; for(var i = 100; i<1000;i++) { arrayTab.push(i); } </script> <iframe id="myiframetext" width="0" height="0" class="myiframetext" name="myiframetext" src="<?php echo base_url().$link ?>" frameborder="0"></iframe> </div> <!-- Essential javascripts for application to work--> <script src="<?=base_url()?>js/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="<?=base_url()?>js/popper.min.js"></script> <script src="<?=base_url()?>js/bootstrap.min.js"></script> <script src="<?=base_url()?>js/main.js"></script> <script src="<?=base_url()?>js/main2.js"></script> <!-- The javascript plugin to display page loading on top--> <script src="<?=base_url()?>js/plugins/pace.min.js"></script> <!-- Page specific javascripts--> <script type="text/javascript" src="<?=base_url()?>js/plugins/chart.js"></script> <script type="text/javascript" src="<?=base_url()?>js/plugins/bootstrap-notify.min.js"></script> <script type="text/javascript" src="<?=base_url()?>js/plugins/sweetalert.min.js"></script> <script src="<?php echo base_url() ?>js/jquery.scrolling-tabs.js"></script> <?php echo isset($script2) ? $script2 : ''; ?> <!-- <------------------script --> <?php echo isset($script) ? $script : ''; ?> <?php echo isset($nodejs) ? $nodejs : ''; ?> </body> </html><file_sep><script type="text/javascript"> $('.btn-creategroupuser').click(function(){ $('.btn-creategroupuser').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner'); getValueCheckbox("viewticket","viewtickethidden"); getValueCheckbox("addticket","addtickethidden"); getValueCheckbox("editticket","edittickethidden"); getValueCheckbox("viewuser","viewuserhidden"); getValueCheckbox("adduser","adduserhidden"); getValueCheckbox("edituser","edituserhidden"); getValueCheckbox("viewtask","viewtaskhidden"); getValueCheckbox("addtask","addtaskhidden"); getValueCheckbox("edittask","edittaskhidden"); getValueCheckbox("viewknowledge","viewknowledgehidden"); getValueCheckbox("addknowledge","addknowledgehidden"); getValueCheckbox("editknowledge","editknowledgehidden"); getValueCheckbox("viewpermission","viewpermissionhidden"); $.ajax({ url: '<?php echo base_url()?>groupuser/groupuserinsert', type: 'POST', dataType: 'JSON', data: $('#dataInsertGroup').serialize(), // data: $('#insertUserVal').serialize(), }) .done(function(data) { if(data.message =='Success') { alert('Thรชm nhรณm ngฦฐแปi dรนng thร nh cรดng'); $('.btn-creategroupuser').prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); location.reload(); } else{ alert(data.message); } }) .fail(function() { alert('Thรชm nhรณm ngฦฐแปi dรนng thแบฅt bแบกi'); }) }); function getValueCheckbox(name,namehidden) { if(document.getElementById(name).checked) { document.getElementById(namehidden).disabled = true; } } </script><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Queue extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url')); $this->load->model('M_api'); } public function index() { $_body = []; $_body['left'] = $this->load->view('datasource/queue/qu_left',null,TRUE); $_data = []; $_data['script'] = $this->load->view('script/script_queue', NULL, TRUE); $_data['mainview'] = $this->load->view('datasource/queue/form', $_body , TRUE); $this->load->view('dashboard',$_data); } public function rightFilter() { $list_extend['list_ext'] = []; $queue = $this->input->get('queue'); // $postdata = http_build_query([ // 'queue' => $queue, // 'secret' => 'ac97db2cca493ad87045946aed59eb29' // ]); // $opts = array('http' => // array( // 'method' => 'POST', // 'header' => 'Content-type: application/x-www-form-urlencoded', // 'content' => $postdata // ) // ); // $context = stream_context_create($opts); // $result = file_get_contents('https://api-prod.mipbx.vn/api/v1/call/getExtensionInQueue',false,$context); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/queue/select?queuecode='.$queue); $list_extend['extension'] = json_decode($result,true)['data']; $_data['script'] = $this->load->view('script/script_queue', NULL, TRUE); $_data['mainview'] = $this->load->view('datasource/queue/qu_center', $list_extend, TRUE); $this->load->view('dashboard',$_data); // echo $result; } public function loginQueue() { $secret = 'ac97db2cca493ad87045946aed59eb29'; $data = $this->input->post(); $extension = $data['telephone']; $queue = $data['queue']; $status = $data['status']; // // $secret = $frm['secret']; if ($extension == NULL || $queue == NULL || $secret == NULL) { $data['code'] = 0; $data['message'] = 'Failed'; $data['data'] = null; echo json_encode($data); }else{ $postfields = array('extension'=>$extension, 'queue'=>$queue, 'secret' => 'ac97db2cca493ad87045946aed59eb29' , 'penalty'=>$status); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api-prod.mipbx.vn/api/v1/call/loginQueue'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_POST, 1); // Edit: prior variable $postFields should be $postfields; curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only! $result = curl_exec($ch); $err = curl_error($ch); curl_close($ch); if ($err) { echo "cURL Error #:" . $err; } else { // var_dump($postfields); echo $result; } } $arrayResult = json_decode($result,true); if( ($arrayResult['code'] != '400') || ($arrayResult['code'] == '200' && $arrayResult['result']['response'] != "Error")) { $postdata = http_build_query([ 'queuecode' => $queue, 'extension' => $extension, 'status' => $status ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result1 = file_get_contents('http://test.tavicosoft.com/crm/index.php/queue/insert',false,$context); } } public function logoutQueue() { $secret = 'ac97db2cca493ad87045946aed59eb29'; $data = $this->input->post(); $extension = $data['telephone']; $queue = $data['queue']; // $secret = $frm['secret']; if ($extension == NULL || $queue == NULL || $secret == NULL) { $data['code'] = 0; $data['message'] = 'Failed'; $data['data'] = null; echo json_encode($data); }else{ $postfields = array('extension'=>$extension, 'queue'=>$queue, 'secret' => 'ac97db2cca493ad87045946aed59eb29'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api-prod.mipbx.vn/api/v1/call/logoutQueue'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_POST, 1); // Edit: prior variable $postFields should be $postfields; curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only! $result = curl_exec($ch); $err = curl_error($ch); curl_close($ch); if ($err) { echo "cURL Error #:" . $err; } else { echo $result; } } $arrayResult = json_decode($result,true); if( ($arrayResult['code'] == 200)) { $result1 = file_get_contents('http://test.tavicosoft.com/crm/index.php/queue/delete?queuecode='.$queue.'&extension='.$extension); } } } /* End of file Queue.php */ /* Location: ./application/controllers/Queue.php */ ?><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-12 margin-bot-10 margin-top-5 margin-left-10"> <div class="fc-left"> <div class="fc-button-group hide"> <button type="button" class="fc-month-button fc-button fc-state-default fc-corner-left">Bร i viแบฟt</button><button type="button" class="fc-agendaWeek-button fc-button fc-state-default">Quy trรฌnh</button><button type="button" class="fc-agendaWeek-button fc-button fc-state-default">Thanh lรฝ</button><button type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right">Thanh lรฝ hแปฃp ฤ‘แป“ng cแปc</button> </div> </div> </div> <div class="col-md-2 col-md-22 no-padding padding-left-15"> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-10"> <div class=""> <label class="control-label user-label col-md-3 no-padding">Phรขn loแบกi</label> <select name="type" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_1" value="<?php echo isset($knowledge[0]['tickettype'])?$knowledge[0]['tickettype']:'' ?>"> <?php if (isset($l_type) && !empty($l_type)) { foreach ($l_type as $key => $value) { $sel = ''; if (isset($knowledge[0]['tickettype']) && $value['code']==$knowledge[0]['tickettype']) { $sel = 'selected'; } echo '<option '.$sel.' value="'.$value['code'].'">'.$value['name'].'</option>'; } # code... } ?> </select> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Nhรณm vแบฅn ฤ‘แป</label> <select name="group" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_2" value="<?php echo isset($knowledge[0]['groupid'])?$knowledge[0]['groupid']:'' ?>"> <?php if (isset($l_group) && !empty($l_group)) { foreach ($l_group as $key => $value) { $sel = ''; if (isset($knowledge[0]['groupid']) && $value['code']==$knowledge[0]['groupid']) { $sel = 'selected'; } echo '<option '.$sel.' ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>'; } # code... } ?> </select> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Chi tiแบฟt Vฤ</label> <select name="cate" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_3" value="<?php echo isset($knowledge[0]['categoryid'])?$knowledge[0]['categoryid']:'' ?>"> <?php if (isset($l_cate) && !empty($l_cate)) { foreach ($l_cate as $key => $value) { $sel = ''; if (isset($knowledge[0]['categoryid']) && $value['code']==$knowledge[0]['categoryid']) { $sel = 'selected'; } echo '<option '.$sel.' ref1="'.$value['ref1'].'" ref2="'.$value['ref2'].'" value="'.$value['code'].'">'.$value['name'].'</option>'; } } ?> </select> </div> </div> </div> <div class="tile p-0 padding-5 margin-bot-5"> <div class="tile-body padding-left-10"> <div class="hide"> <label class="control-label user-label col-md-3 no-padding">Quyแปn sแปญa</label> <label class="control-label col-md-8 col-71 no-padding-right"> <input name="right" class="col-md-12 no-padding font-size-12" list="i-right" value=""> <datalist id="i-right"> <option value="0">Tแบฅt cแบฃ mแปi ngฦฐแปi</option> </datalist> </label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Tag</label> <select name="ticketprioty" class="control-label col-md-8 no-border no-padding margin-left-10" value="<?php echo isset($knowledge[0]['ticketprioty'])?$knowledge[0]['ticketprioty']:'' ?>"> <?php if (isset($knowledge[0]['ticketprioty'])) { if ($knowledge[0]['ticketprioty']=='0') { echo '<option value="0" selected>Thฦฐแปng</option><option value="1">Cao</option><option value="2">Khแบฉn cแบฅp</option>'; }elseif ($knowledge[0]['ticketprioty']=='1') { echo '<option value="0">Thฦฐแปng</option><option selected value="1">Cao</option><option value="2">Khแบฉn cแบฅp</option>'; }elseif ($knowledge[0]['ticketprioty']=='2') { echo '<option value="0">Thฦฐแปng</option><option value="1">Cao</option><option selected value="2">Khแบฉn cแบฅp</option>'; } }else{ echo '<option value="0">Thฦฐแปng</option><option value="1">Cao</option><option value="2">Khแบฉn cแบฅp</option>'; } ?> </select> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Trแบกng thรกi</label> <select name="status" class="control-label col-md-8 no-border no-padding margin-left-10" value="<?php echo isset($knowledge[0]['hidden'])?$knowledge[0]['hidden']:'' ?>"> <?php if (isset($knowledge[0]['ticketprioty'])) { if ($knowledge[0]['hidden']=='0') { echo '<option value="0" selected>ฤang hoแบกt ฤ‘แป™ng</option><option value="1">Ngฦฐng hoแบกt ฤ‘แป™ng</option>'; }elseif ($knowledge[0]['hidden']=='1') { echo '<option value="0">ฤang hoแบกt ฤ‘แป™ng</option><option selected value="1">Ngฦฐng hoแบกt ฤ‘แป™ng</option>'; } }else{ echo '<option value="0">ฤang hoแบกt ฤ‘แป™ng</option><option value="1">Ngฦฐng hoแบกt ฤ‘แป™ng</option>'; } ?> </select> </div> </div> </div> <div class="padding-5 margin-bot-5 padding-left-10"> <div class=""> <label class="control-label user-label col-md-3 no-padding">ฤฤƒng bแปŸi</label> <label class="control-label col-md-8 no-padding-right"><?php echo isset($knowledge[0]['custname'])?$knowledge[0]['custname']:'' ?></label> </div> <div class=""> <label class="control-label user-label col-md-3 no-padding">Ngร y ฤ‘ฤƒng</label> <label class="control-label col-md-8 no-padding-right"><?php echo isset($knowledge[0]['createdat'])?date("d-m-Y", strtotime($knowledge[0]['createdat'])):'' ?></label> </div> <div class="clearfix hide"> <label class="control-label user-label col-md-3 no-padding">Cแบญp nhแบญt</label> <label class="control-label col-md-8 no-padding-right no-margin-top">hh:mm dd/mm/yyyy</label> </div> </div> </div> <div class="col-md-6 col-md-56 no-padding padding-left-5"> <div class="tile height-1024"> <div class="content-title"> <div class="div width-100per"> <h5 id="knl-title"><?php echo isset($knowledge[0]['title'])?$knowledge[0]['title']:'' ?> <input type="hidden" name="title" value=""> </h5> </div> </div> <div class="bs-component"> <div class="row"> <div class="offset-10 col-md-2 margin-bot-10"> <button class="btn btn-primary float-right" id="ck-edit" type="button"> Chแป‰nh sแปญa </button> <button action="<?php if($this->uri->segment(3)!='') { echo $this->uri->segment(3); } else { echo 'add'; } ?>" class="btn btn-primary float-right hide" id="ck-save" type="button"> Lฦฐu </button> </div> </div> <div id="content" ck-edit="close"> <div class="knc-content"> <!-- Kham pha --> <?php echo isset($knowledge[0]['article'])?$knowledge[0]['article']:'' ?> </div> </div> </div> </div> </div> <div class="col-md-3 col-md-22 no-padding padding-left-5 padding-top-10 hide"> <div class="timeline"> <div class="entry"> <div class="title gray"> <p class="time-detail">hh:mm:ss</p> <p class="date-detail">dd/mm/yyyy</p> </div> <div class="body"> <p class="margin-bot-3">System - Hแป‡ thแป‘ng</p> <p class="no-margin-bot">User History in only two line, User History only in two line. Thanks !!</p> </div> </div> <div class="entry"> <div class="title red"> <p class="time-detail">hh:mm:ss</p> <p class="date-detail">dd/mm/yyyy</p> </div> <div class="body"> <p class="margin-bot-3">System - Hแป‡ thแป‘ng</p> <p class="no-margin-bot">User History in only two line, User History only in two line. Thanks !!</p> </div> </div> <div class="entry"> <div class="title green"> <p class="time-detail">hh:mm:ss</p> <p class="date-detail">dd/mm/yyyy</p> </div> <div class="body"> <p class="margin-bot-3">System - Hแป‡ thแป‘ng</p> <p class="no-margin-bot">User History in only two line, User History only in two line. Thanks !!</p> </div> </div> <div class="entry"> <div class="title yellow"> <p class="time-detail">hh:mm:ss</p> <p class="date-detail">dd/mm/yyyy</p> </div> <div class="body"> <p class="margin-bot-3">System - Hแป‡ thแป‘ng</p> <p class="no-margin-bot">User History in only two line, User History only in two line. Thanks !!</p> </div> </div> </div> </div> </div> </main><file_sep><?php $lq = $this->input->get('lienquan'); ?> <div class="col-md-100 no-padding padding-left-5"> <div class="tile height-1024"> <div class="table-responsive"> <table class="table" id="table-1-searchticket"> <thead class="no-border-top"> <tr> <th width="100">ID</th> <th width="250">Tรชn phiแบฟu</th> <th width="130px">Ngฦฐแปi yรชu cแบงu</th> <th width="130px">Ngฦฐแปi phแปฅ trรกch</th> <th width="60px">ฤแป™ ฦฐu tiรชn</th> <th width="50">ฤแบฟn hแบกn</th> <th width="50">Ngร y tแบกo</th> <!-- <th width="50">Cแบญp nhแบญt</th> --> </tr> </thead> <tbody> <?php if(count($result['data']) >0&& $result['code']==1) { $i =0; foreach ($result['data'] as $rows) { if($lq == 'false') { if(($rows['status']==$status && $rows['agentcurrent']==$agentcurrent && $rows['status'] != 9) || ($status==-1 && $rows['agentcurrent']==$agentcurrent && $rows['status'] != 9 )){ ?> <tr class="border-bot-1"> <td> <a class="buttonsearchiframe" onclick="addTab('<?php echo base_url().'ticket/detail/'.$rows['ticketid'].'/'.urlencode($rows['custid']).'/'.urlencode($rows['idcard']) ?>','#<?php echo $rows['ticketid'] ?>')" href="#"> <span class="id-label span-warning">P</span> #<?php echo $rows['ticketid'] ?> </a> </td> <td> <?php echo $rows['title'] ?> </td> <td><?php if(isset($rows['custname'])){ echo $rows['custname'];} ?></td> <td><?php if(isset($rows['agentcurrentname'])){ echo $rows['agentcurrentname'];} ?></td> <td><?php if ($rows['priority']==1) {echo "Thฦฐแปng";} elseif ($rows['priority']==2) {echo "Cao";} elseif ($rows['priority']==3) {echo "Khแบฉn cแบฅp";} else {echo "Khรดng xรกc ฤ‘แป‹nh";} ?></td> <td> <?php if (strtotime($rows['duedate'])>strtotime("2000/01/01")) echo date("d/m/Y H:i:s", strtotime($rows['duedate']));?> </td> <td><?php if (strtotime($rows['duedate'])>strtotime("2000/01/01")) echo date("d/m/Y H:i:s", strtotime($rows['createat']));?></td> </tr> <?php }}else{ if(($rows['agentcreated'] == $agentcurrent && $rows['status']!= 9) || (strpos($rows['ticketusers'], $agentcurrent) !== false && $rows['status']!= 9)){?> <tr class="border-bot-1"> <td> <a class="buttonsearchiframe" onclick="addTab('<?php echo base_url().'ticket/detail/'.$rows['ticketid'].'/'.urlencode($rows['custid']).'/'.urlencode($rows['idcard']) ?>','#<?php echo $rows['ticketid'] ?>')" href="#" title=""> <span class="id-label span-warning">P</span> #<?php echo $rows['ticketid'] ?> </a> </td> <td> <?php echo $rows['title'] ?> </td> <td><?php if(isset($rows['custname'])){ echo $rows['custname'];} ?></td> <td><?php if(isset($rows['agentcurrentname'])){ echo $rows['agentcurrentname'];} ?></td> <td><?php if ($rows['priority']==1) {echo "Thฦฐแปng";} elseif ($rows['priority']==2) {echo "Cao";} elseif ($rows['priority']==3) {echo "Khแบฉn cแบฅp";} else {echo "Khรดng xรกc ฤ‘แป‹nh";} ?></td> <td><?php if (strtotime($rows['duedate'])>strtotime("2000/01/01")) echo date("d/m/Y H:i:s", strtotime($rows['duedate']));?></td> <td><?php if (strtotime($rows['duedate'])>strtotime("2000/01/01")) echo date("d/m/Y H:i:s", strtotime($rows['createat']));?></td> </tr> <?php }}}} ?> </tbody> </table> </div> </div> </div><file_sep><script type="text/javascript"> $(document).ready(function(){ $('#modalDelete').on('shown.bs.modal', function (e) { var code = $(e.relatedTarget).data('code'); $(e.currentTarget).find('input[name="codedelete"]').val(code); var category = $(e.relatedTarget).data('category'); $(e.currentTarget).find('input[name="categorydelete"]').val(category); }); $('#modalUpdate').on('shown.bs.modal', function (e) { var code = $(e.relatedTarget).data('code'); $(e.currentTarget).find('input[name="code"]').val(code); var category = $(e.relatedTarget).data('category'); $(e.currentTarget).find('input[name="category"]').val(category); var name = $(e.relatedTarget).data('name'); $(e.currentTarget).find('input[name="name"]').val(name); }); }); function insertExtUser(formid) { var fieldtype = $('#fieldtype').val(); var fieldcode = $('#fieldcode').val(); var fieldname = $('#fieldname').val(); var datasource = $('#datasource').val(); var dataExt = $('#dataExt').serialize(); $.ajax({ url: '<?php echo base_url().'groupuser/insertFieldUser' ?>', type: 'POST', dataType: 'JSON', data: {fieldtype:fieldtype,fieldcode:fieldcode,fieldname:fieldname,formid:formid,dataExt : dataExt,datasource:datasource}, }) .done(function(data) { if(data.code==1){ window.location.reload(); }else{ alert(data.message); } }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); } function selectType(obj) { $('.optionD').remove(); var id = obj.value; if(id == 'D') { $('.extendbottom').append('<form id="dataExt" method="POST" role="form"><div class="optionD">\ <div class="form-group">\ <label for="exampleInputEmail1">Mรฃ nguแป“n dแปฏ liแป‡u</label>\ <input type="text" class="form-control" name="datasource" id="datasource" placeholder="-Mรฃ nguแป“n dแปฏ liแป‡u">\ </div>\ <div class="form-group optionbottom">\ <label for="exampleInputEmail1">Dropdown Options</label>\ <div class="">\ <label class="control-label user-label col-md-2 no-padding">Mรฃ trฦฐแปng:</label>\ <label class="control-label col-md-8 no-padding-right">\ <input name="code[]" class="form-control" placeholder="Mรฃ trฦฐแปng">\ </label>\ </div>\ <div class="">\ <label class="control-label user-label col-md-2 no-padding">Tรชn trฦฐแปng:</label>\ <label class="control-label col-md-8 no-padding-right">\ <input name="name[]" class="form-control" placeholder="Tรชn trฦฐแปng">\ </label>\ </div>\ \ </div>\ <div class="addoption">\ <label class="control-label user-label col-md-3 no-padding"></label>\ <label class="control-label col-md-8 no-padding-right field-click-able"><a onclick="addOption()" style="cursor: pointer;" class="user-name">+ Thรชm Option</a></label>\ </div></div></form>'); } } function addOption() { $('.addoption').before('<div class="optionD">\ <div class="form-group optionbottom">\ <label for="exampleInputEmail1">Options</label>\ <div class="">\ <label class="control-label user-label col-md-2 no-padding">Mรฃ trฦฐแปng:</label>\ <label class="control-label col-md-8 no-padding-right">\ <input name="code[]" class="form-control" placeholder="Mรฃ trฦฐแปng">\ </label>\ </div>\ <div class="">\ <label class="control-label user-label col-md-2 no-padding">Tรชn trฦฐแปng:</label>\ <label class="control-label col-md-8 no-padding-right">\ <input name="name[]" class="form-control" placeholder="Tรชn trฦฐแปng">\ </label>\ </div>\ \ </div>\ </div>'); } function insertSelectBox() { var code = $('#code').val(); var name = $('#name').val(); var category = $('#category').val(); $.ajax({ url: '<?php echo base_url().'groupuser/insertSelectBox' ?>', type: 'POST', dataType: 'JSON', data: {code:code,name:name,category:category}, }) .done(function(data) { if(data.code==1){ window.location.reload(); }else{ alert(data.message); } }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); } $('#udpategroup_btn').click(function(){ var groupid = $('#groupid').val(); var ticketrule = $('#ticketrule').val(); var taskrule = $('#taskrule').val(); var userrule = $('#userrule').val(); var knowledgerule = $('#knowledgerule').val();var status = $('#status').val() $.ajax({ url: '<?php echo base_url().'groupuser/updategroup' ?>', type: 'POST', dataType: 'JSON', data: {groupid:groupid,ticketrule:ticketrule,taskrule:taskrule,userrule:userrule,knowledgerule:knowledgerule,status:status}, }) .done(function(data) { if(data.code==1){ window.location.reload(); }else{ alert(data.message); } }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); }); function uddateFields() { var fieldcode = $('#fieldcode').val(); var fieldname = $('#fieldname').val(); var status = $('#status').val(); $.ajax({ url: '<?php echo base_url().'groupuser/updateFields' ?>', type: 'POST', dataType: 'JSON', data: {fieldcode:fieldcode,fieldname:fieldname,status:status}, }) .done(function(data) { if(data.code==1){ window.location.reload(); }else{ alert(data.message); } }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); } function deleteButton() { var category = $('#categorydelete').val(); var code = $('#codedelete').val(); var action = 'delete'; $.ajax({ url: '<?php echo base_url().'groupuser/updateCodictionary' ?>', type: 'POST', dataType: 'JSON', data: {category:category,code:code,action:action}, }) .done(function(data) { if(data.code==1){ window.location.reload(); }else{ alert(data.message); } }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); } function updateButton() { var category = $('#category').val(); var code = $('.code').val(); var name = $('.nameField').val(); var action = 'update'; $.ajax({ url: '<?php echo base_url().'groupuser/updateCodictionary' ?>', type: 'POST', dataType: 'JSON', data: {category:category,code:code,name:name,action:action}, }) .done(function(data) { if(data.code==1){ window.location.reload(); }else{ alert(data.message); } }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); } </script><file_sep><?php if(!$update){ ?> <script type="text/javascript"> $("#form-ticket *").attr("disabled", "disabled").off('click'); </script> <?php } ?> <script type="text/javascript"> $(document).ready(function(){ search('','','',''); }); var tic = $('select[name=agentgroup]').val(); if (tic!='') { $('select[name=agentcurrent] option').each(function(){ var group = $(this).attr('data-group'); if (tic==group) {$(this).prop('disabled',false);} else{$(this).prop('disabled',true);} }); } var tickettype = $('select[name=tickettype]').val(); if (tickettype!='') { $('select[name=groupid] option').each(function(){ var ref1 = $(this).attr('ref1'); if (ref1==tickettype) {$(this).removeClass('hide').addClass('show');} else{$(this).addClass('hide').removeClass('show');} }); $('select[name=groupid] option.show:first').prop('selected',true); } var groupid = $('select[name=groupid]').val(); if (groupid!='') { $('select[name=categoryid] option').each(function(){ var ref2 = $(this).attr('ref2'); if (ref2==groupid) {$(this).removeClass('hide').addClass('show');} else{$(this).addClass('hide').removeClass('show');} }); $('select[name=categoryid] option.show:first').prop('selected',true); } $('input[name=sla],input[name=duedate],input[name=finishdate],input[name=firstreply],input[name=requestdate]'). datetimepicker({format:'d-m-Y H:i'}); var rights = $('select[name=ticketstatus] option:selected').attr('value'); if (rights==4 || rights==9) { $('.crm-control,.crm-ext,textarea,.btn-updateAction,.btn-updateActionUpdate,#btnGroupDrop1').prop('disabled',true); } var agentcurrent = $('select[name=agentcurrent]').val(); if (agentcurrent) { $('#btn-accept').remove(); }else{ $('.crm-control,.crm-ext,btnGroupDrop1').prop('disabled',true); } $('select[name=ticketchannel],select[name=priority],select[name=ticketstatus]').select2(); $('select[name=agentgroup]').select2({ placeholder: "Chแปn nhรณm phแปฅ trรกch...", allowClear: true, ajax: { url: "<?php echo(base_url('api/search_group'));?>", type: "post", dataType: 'json', delay: 250, data: function (params) { return { searchTerm: params.term // search term }; }, processResults: function (response) { return { results: response }; }, cache: true } }); $('select[name=agentcurrent]').select2({ placeholder: "Chแปn ngฦฐแปi phแปฅ trรกch...", allowClear: true, ajax: { url: "<?php echo(base_url('api/search_agent'));?>", type: "post", dataType: 'json', delay: 250, data: function (params) { var tic = $('select[name=agentgroup]').val(); return { groupid:tic, searchTerm: params.term // search term }; }, processResults: function (response) { return { results: response }; }, cache: true } }); $('select[name=levelticket]').select2({ placeholder: "Chแปn giai ฤ‘oแบกn...", allowClear: true, minimumResultsForSearch: -1, ajax: { url: "<?php echo(base_url('api/search_stage'));?>", type: "post", dataType: 'json', delay: 250, data: function (params) { return { searchTerm: params.term // search term }; }, processResults: function (response) { return { results: response }; }, cache: true } }); $('select[name=tickettype]').select2({ placeholder: "Chแปn phรขn loแบกi...", allowClear: true, minimumResultsForSearch: -1, ajax: { url: "<?php echo(base_url('api/search_issue_type'));?>", type: "post", dataType: 'json', delay: 250, data: function (params) { return { searchTerm: params.term // search term }; }, processResults: function (response) { return { results: response }; }, cache: true } }); $('select[name=groupid]').select2({ placeholder: "Chแปn nhรณm vแบฅn ฤ‘แป...", minimumResultsForSearch: -1, allowClear: true, ajax: { url: "<?php echo(base_url('api/search_issue_group'));?>", type: "post", dataType: 'json', delay: 250, data: function (params) { var p = $('select[name=tickettype]').val(); return { ref1:p, searchTerm: params.term // search term }; }, processResults: function (response) { return { results: response }; }, cache: true } }); $('select[name=categoryid]').select2({ placeholder: "Chแปn chi tiแบฟt vแบฅn ฤ‘แป...", minimumResultsForSearch: -1, allowClear: true, ajax: { url: "<?php echo(base_url('api/search_issue_detail'));?>", type: "post", dataType: 'json', delay: 250, data: function (params) { var p = $('select[name=groupid]').val(); return { ref2:p, searchTerm: params.term // search term }; }, processResults: function (response) { return { results: response }; }, cache: true } }); $('#form-ticket').on('submit',function(){ var formData = new FormData($(this)[0]); var error = []; for (var [key, value] of formData.entries()) { // console.log(key, value); } if (formData.get('agentgroup')==undefined && formData.get('agentcurrent')==undefined) { error[key] = '1'; parent.alertLog('Cแบฃnh bรกo','Bแบกn phแบฃi nhแบญp 1 trong 2 thรดng tin: Nhรณm phแปฅ trรกch, Ngฦฐแปi phแปฅ trรกch.','warning'); } if (!jQuery.isEmptyObject(error)) { var msg = ''; for (let key in error){ msg+= error[key]+"\n"; } console.log(msg); }else{ $('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner'); $.ajax({ type: "POST", url: "<?php echo base_url().'ticket/aj_insert_ticket';?>", data: formData, dataType:'json', contentType: false, cache: false, processData:false, beforeSend: function() { }, success: function(data) { if(data.code==0){ $('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); parent.alertLog("Cแบฃnh bรกo !", data.message, "warning"); }else{ // alert("thรชm thร nh cรดng."); parent.alertLog("Thร nh cรดng !", "Thรชm phiแบฟu thร nh cรดng.", "success"); var tab = window.top.$('div.tab-pane.active').attr('id'); window.top.$('li a.nav-link[href="#'+tab+'"]').find('span').html('#'+data.data); location.href= '<?php echo base_url().'/ticket/detail/';?>'+data.data; } }, error: function(xhr, status, error) { console.log(error); $(this).prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); } }); } return false; }); $('select[name=tickettype]').change(function(){ var val = $(this).val(); if (val) {search('',val,'','');} }); $('select[name=groupid]').change(function(){ var val = $(this).val(); if (val) {search('','',val,'');} }); $('select[name=categoryid]').change(function(){ var val = $(this).val(); if (val) {search('','','',val);} }); $('#table-23').DataTable( { "ajax": "<?php echo base_url('ticket/recent_contract/'.$param['idcard']);?>", "paging": false, "info": false, "searching": false, "scrollY": false, "scrollX": false, "scrollCollapse": false, "ordering": false, "processing": true, 'language':{ "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />" }, "initComplete": function(settings, json){ this.find('thead').css("display","none"); this.fnAdjustColumnSizing(true); $(this).find('tbody td').css('padding','2px 8px'); $(function () { $('[data-toggle="tooltip"]').tooltip() }) } }); $('#table-22').DataTable( { "ajax": "<?php echo base_url('ticket/recent_ticket/'.$this->uri->segment(4).'/'.$this->session->userdata('custid').'/'.$param['idcard'])?>", "paging": false, "info": false, "searching": false, "scrollY": false, "scrollX": false, "scrollCollapse": false, "ordering": false, "processing": true, 'language':{ "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />" }, "initComplete": function(settings, json){ this.find('thead').css("display","none"); this.fnAdjustColumnSizing(true); $(this).find('tbody td').css('padding','2px 8px'); } }); $(document).on('change','.crm-control,.crm-ext',function(){ // $('.btn-updateAction').html('<i class="fa fa-share"></i> Cแบญp nhแบญt phiแบฟu'); var log = $(this).attr('log'); var old_value = $(this).attr('old-value'); var new_value = $(this).val(); if (log) { var text = $(this).find('option:selected').text(); if (!text) { text = $(this).val(); } if (old_value === new_value) {deletelog(log);}else{changelog(log,text);} } }); $('.btn-updateActionUpdate').click(function(){ var cur = $(this); var ticketid = $(this).attr('title'); var cmt= $('textarea[name=cmt]').val(); if (cmt=='') { parent.alertLog('Cแบฃnh bรกo','Bแบกn chฦฐa nhแบญp ghi chรบ cho phiแบฟu.','warning'); }else{ cur.prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner'); $.ajax({ url: '<?php echo base_url().'ticket/updateTicketLog' ?>', type: 'POST', dataType: 'JSON', data: {cmt:cmt,ticketid:ticketid}, }) .done(function(data) { cur.prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); if(data.code==1){ $('#action').val(''); var iframe = window.tck_log; iframe.location.reload(); parent.notification("OK"); iframe.onload = function() { alert('myframe is loaded'); }; // before setting 'src' }else{ alert(data.message); } }) .fail(function() { cur.prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); } }); $('#form-ticket').on('submit',function(){ var formData = new FormData($(this)[0]); var error = []; for (var [key, value] of formData.entries()) { // console.log(key, value); switch(key){ case 'customer': if (value=='') { error[key] = "1"; parent.alertLog('Cแบฃnh bรกo','Vui lรฒng chแปn ngฦฐแปi yรชu cแบงu.','warning'); } break; case 'agentgroup': if (value=='' && formData.get('agentcurrent') == '') { error[key] = '1'; parent.alertLog('Cแบฃnh bรกo','Bแบกn phแบฃi nhแบญp 1 trong 2 thรดng tin: Nhรณm phแปฅ trรกch, Ngฦฐแปi phแปฅ trรกch.','warning'); }else if (value=='' && formData.get('agentcurrent') !='') { var agent = $('select[name=agentcurrent]').find('option:selected').attr('data-group'); console.log(agent); if (agent) {formData.set('agentgroup',agent)} } break; default: break; } } if (!jQuery.isEmptyObject(error)) { var msg = ''; for (let key in error){ msg+= error[key]+"\n"; } console.log(msg); }else{ $('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner'); $.ajax({ type: "POST", url: "<?php echo base_url().'ticket/aj_update_ticket';?>", data: formData, dataType:'json', contentType: false, cache: false, processData:false, beforeSend: function() { }, success: function(data) { if(data.code==0){ $('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); parent.alertLog("Cแบฃnh bรกo !", data.message, "warning"); }else{ // alert("thรชm thร nh cรดng."); parent.notification("Ok."); window.location.reload(); } }, error: function(xhr, status, error) { console.log(error); $(this).prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); } }); } return false; }); $('#btn-ticket-merge').click(function(){ var old_ticketid = $(this).attr('tck-id'),new_ticketid=''; var old_status = $(this).attr('tck-stt'); var old_title = $(this).attr('tck-title'); var stt_cls = "danger",stt_txt = "OPEN"; if (old_status==0) {stt_cls="warning";stt_txt="PENDDING"} if (old_status==4) {stt_cls="success";stt_txt="SUCCESS"} var modal = createModal(); modal.modal("show").on("hidden", function(){ modal.remove(); }); $.ajax({ url: '<?php echo base_url().'api/aj_tck_id_title';?>', type: 'GET', dataType: 'JSON', }) .done(function(data) { if(data){ // console.log(data); var option = ''; for (var i = 0; i < data.length; i++) { option += '<option status="'+data[i]['status']+'" value="'+data[i]['ticketid']+'">'+data[i]['title']+'</option>'; } modal.find('.modal-body') .html('<div class="table-responsive">\ <table class="table margin-bot-5 table1" id="table-1">\ <tbody>\ <tr class="no-border">\ <td class="no-border" width="150">\ <span class="id-label span-'+stt_cls+'">'+stt_txt+'</span> #Ticket '+old_ticketid+'\ </td>\ <td class="no-border">\ '+old_title+'\ </td>\ \ </tr>\ </tbody>\ </table>\ </div>\ <p>Tรฌm phiแบฟu cแบงn ghรฉp</p>\ <div id="call-input">\ <input class="form-control margin-top-10 margin-bot-5" type="number" placeholder="Nhแบญp mรฃ phiแบฟu ฤ‘ฦฐแปฃc ghรฉp" list="tck_lst">\ <datalist id="tck_lst">\ '+option+'\ </datalist>\ </div>\ <div class="table-responsive">\ <table class="table margin-bot-5 table2" id="table-1">\ <tbody>\ </tbody>\ </table>\ </div>'); modal.find('input').on('keyup',function(){ var val = $(this).val(); var opt = modal.find('option[value="'+val+'"]'); console.log(opt); if (opt.length>0) { var tck_id = new_ticketid = opt.attr('value'); var tck_title = opt.html(); var tck_stt = opt.attr('status'); var stt_cls = "danger",stt_txt = "OPEN"; if (tck_stt==0) {stt_cls="warning";stt_txt="PENDDING"} if (tck_stt==4) {stt_cls="success";stt_txt="SUCCESS"} modal.find('.modal-body table.table2 tbody'). html('<tr class="no-border">\ <td class="no-border" width="150">\ <span class="id-label span-'+stt_cls+'">'+stt_txt+'</span> #Ticket '+tck_id+'\ </td>\ <td class="no-border">\ '+tck_title+'\ </td>\ </tr>'); }else{ new_ticketid = ''; modal.find('.modal-body table.table2 tbody'). html(''); } }); modal.find('button#submit').click(function(){ var cur = $(this); if (new_ticketid=='') { parent.alertLog('Cแบฃnh bรกo','Vui lรฒng chแปn 1 ticket','warning'); }else{ modal.find('button').prop('disabled',true); cur.find('i').addClass('fa fa-spinner fa-spin'); $.ajax({ url: '<?php echo base_url().'api/aj_merge_ticket';?>', type: 'POST', dataType: 'JSON', data: {oldticket:old_ticketid,newticket:new_ticketid}, }) .done(function(data) { console.log(data); if (data.code==1) { console.log('ok'); modal.find('button').prop('disabled',false); modal.find('button#remove').click(); parent.notification("Ghรฉp phiแบฟu thร nh cรดng"); window.location.reload(); }else{ modal.find('button').prop('disabled',false); cur.find('i').removeClass('fa fa-spinner fa-spin'); } }) .fail(function() { modal.find('button').prop('disabled',false); cur.find('i').removeClass('fa fa-spinner fa-spin'); alert('error'); }); } }); } }) .fail(function() { parent.alertLog('Cแบฃnh bรกo','Lแป—i kแบฟt nแป‘i.','warning'); }); }); $('#btn-accept').click(function(){ var cur = $(this); var tckid = $(this).attr('tckid'); if (tckid) cur.prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner'); $.ajax({ url: '<?php echo base_url().'ticket/get_to_my_ticket/'?>'+tckid, type: 'POST', dataType: 'JSON', }) .done(function(data) { if(data.code==1){ parent.notification('Tiแบฟp nhแบญn phiแบฟu thร nh cรดng.'); window.location.reload(); }else{ parent.alertLog('Lแป—i',data.message,'danger'); // alert(data.message); } }) .fail(function() { cur.prop('disabled',false).find('i').removeClass().addClass('fa fa-share'); alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); }); function createModal(){ var modal = $( '<div class="modal fade">\ <div class="modal-dialog" role="document" style="top:15%;">\ <div class="modal-content">\ <div class="modal-header">\ <h5 class="modal-title">Ghรฉp vร o mแป™t phiแบฟu khรกc</h5>\ <button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">ร—</span></button>\ </div>\ <div class="modal-body relative">\ <i class="fa fa-spinner fa-spin" style="position:absolute;top:30%;left:49%;font-size:18px;"></i>\ </div>\ <div class="modal-footer">\ <button class="btn btn-primary btn-89" type="button" id="remove" data-dismiss="modal">Hแปงy</button>\ <button class="btn btn-secondary btn-89" type="button" id="submit"><i></i>Ghรฉp</button>\ </div>\ </div>\ </div>\ </div>'); return modal; } function changelog(log,text){ var oldchange = $('input[name=changelog]').val(); var newchange = ''; var arr_log = oldchange.split('|'); if (arr_log.length>0) { for (var i = 0; i < arr_log.length; i++) { // console.log(arr_log[i]); if(arr_log[i]!= ' ' && arr_log[i]!= '' && arr_log[i].indexOf(log) == -1){ newchange += arr_log[i].trim()+" | "; } } } newchange += log+': '+text+" | "; console.log(newchange); $('input[name=changelog]').val(newchange); return false; } function deletelog(log){ var oldchange = $('input[name=changelog]').val(); var newchange = ''; var arr_log = oldchange.split('|'); if (arr_log.length>0) { for (var i = 0; i < arr_log.length; i++) { // console.log(arr_log[i]); if(arr_log[i]!= ' ' && arr_log[i]!= '' && arr_log[i].indexOf(log) == -1){ newchange += arr_log[i].trim()+" | "; } } } console.log(newchange); $('input[name=changelog]').val(newchange); return false; } function fillExtTicket(magd,idcanho) { $('input[name="transref"]').val(magd); $('input[name="ext[duan]"]').val(magd.substring(0, 3)); $('input[name="ext[canho]"]').val(idcanho); $('[data-toggle="tooltip"]').tooltip('hide'); } function showDetailKnowledge(id){ var show = $('.knl-caret'); if (show.hasClass('fa-angle-double-up')) {$('.knl-caret').trigger('click');} $('#knl_list').css('display','none'); $('.knl-content').html("ฤang tแบฃi dแปฏ liแป‡u...").css('display','block'); $.ajax({ url: '<?php echo base_url().'knowledge/detailKnowledge' ?>', type: 'POST', dataType: 'JSON', data: {id:id}, }) .done(function(data) { $('.knl-content').html(data.data[0].article).css('display','block'); }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); } </script> <file_sep><?php // error_reporting(0); // ini_set('display_errors', 0); defined('BASEPATH') OR exit('No direct script access allowed'); class Issuetype extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url')); $this->load->model('M_api'); } public function index(){ $list_extend['list_ext'] = []; $list_extend['detail'] =[]; $fieldtype = 'D'; if($fieldtype == 'D') { $datasource = 'tcktype'; $_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/selectall/'.$datasource); $list_ext = json_decode($_jsonlistext,true); $list_extend['list_ext'] = $list_ext['data']; } $_body = []; $_body['left'] = $this->load->view('datasource/issuetype/it_left',null,TRUE); $_body['center'] = $this->load->view('datasource/issuetype/it_center', $list_extend, TRUE); $_data = []; $_data['script'] = $this->load->view('script/script_datastage', NULL, TRUE); $_data['mainview'] = $this->load->view('datasource/issuetype/form', $_body , TRUE); $this->load->view('dashboard',$_data); } }<file_sep><?php ob_start(); class Api extends CI_Controller{ public $menu = array(); public function __construct() { parent::__construct(); $this->load->library(array('session')); $this->load->helper(array('url','json_output')); $this->load->model(array('M_api')); } public function get_erp_token($loginid=''){ if ($loginid=='') { $result = null; json_output(200,$result); }else{ $url = "https://demo.tavicosoft.com/DirectRouter/Index"; $action = 'ConnectDB'; $method = 'loginToken'; $data = array(array( 'loginid'=>$loginid ) ); $type='rpc'; $tid=1; $result = $this->M_api->execute_tvc_api($url,$action,$method,$data,$type,$tid); // var_dump($result); json_output(200,$result); } } public function get_list_contract(){ // $post = $this->input->post(); $post = json_decode(file_get_contents('php://input'), true); // var_dump($post); if (empty($post)) { json_output(200,'null'); }else{ $reportcode = isset($post['reportcode'])?$post['reportcode']:''; $action = isset($post['action'])?$post['action']:'FrmFdReport'; $method = isset($post['method'])?$post['method']:'qry'; $limit = isset($post['limit'])?$post['limit']:25; $start = isset($post['start'])?$post['start']:0; $queryFilters['contractid'] = isset($post['queryFilters']['contractid'])?$post['queryFilters']['contractid']:''; $queryFilters['property'] = isset($post['queryFilters']['property'])?$post['queryFilters']['property']:''; $queryFilters['clientname'] = isset($post['queryFilters']['clientname'])?$post['queryFilters']['clientname']:''; $queryFilters['idcard'] = isset($post['queryFilters']['idcard'])?$post['queryFilters']['idcard']:''; $queryFilters['telephone'] = isset($post['queryFilters']['telephone'])?$post['queryFilters']['telephone']:''; $queryFilters['email'] = isset($post['queryFilters']['email'])?$post['queryFilters']['email']:''; $queryFilters['address'] = isset($post['queryFilters']['address'])?$post['queryFilters']['address']:''; $url = "https://demo.tavicosoft.com/DirectRouter/Index"; $data = array(array( 'reportcode'=>$reportcode, 'limit'=>$limit, 'start'=>$start, 'queryFilters'=>array( array('name'=>'contractid','value'=>$queryFilters['contractid']), array('name'=>'property','value'=>$queryFilters['property']), array('name'=>'clientname','value'=>$queryFilters['clientname']), array('name'=>'idcard','value'=>$queryFilters['idcard']), array('name'=>'telephone','value'=>$queryFilters['telephone']), array('name'=>'email','value'=>$queryFilters['email']), array('name'=>'address','value'=>$queryFilters['address']) )) ); $type='rpc'; $tid=1; $result = $this->M_api->execute_tvc_api($url,$action,$method,$data,$type,$tid); // var_dump($result); json_output(200,$result); }} public function get_infor_user($phone){ $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/select/'.$phone); $data = json_decode($json,true); json_output(200,$data); } public function get_normal_api(){ $data = array( 'reportcode'=>'crmContract01f', 'limit'=>25, 'start'=>0, 'method'=>'qry', 'queryFilters'=>array( 'contractid'=>'AGR00333', 'property'=>'', 'clientname'=>'', 'idcard'=>'', 'telephone'=>'', 'email'=>'', 'address'=>'' ) ); $result = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/api/get_list_contract",$data); // var_dump($result); json_output(200,json_decode($result,true)); } public function aj_tvc_isrt_user($telephone=''){ $custid = $this->M_api->gen_custid(); $postdata = http_build_query([ 'custid'=>$custid, 'custname'=>$telephone, 'telephone'=>$telephone, 'idcard'=>$telephone, 'email'=>$telephone, 'groupid'=>3, 'roleid'=>3 ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/insert',false,$context); $array = json_decode($result,true); // var_dump($result); $array[0]['custid'] = $custid; json_output(200,$array); } public function aj_crm_isrt_ticket(){ // var_dump($this->input->post()); $var = $this->session->userdata; $log_groupid = $var['groupid']; $ticketchanel = $this->input->post('ticketchanel'); $priority = $this->input->post('priority'); $custid = $this->input->post('custid'); $phone = $this->input->post('phone'); $callrefid = $this->input->post('callrefid'); $agentcreated = $this->input->post('agentcreated'); $queue = $this->input->post('queue'); $tickettype = '1'; if ($queue) { //tieng anh if ($queue=='21121') { $tickettype='1'; } if ($queue=='21114') { $tickettype='1'; } if ($queue=='21115') { $tickettype='2'; } if ($queue=='21116') { $tickettype='3'; } } $postdata = http_build_query([ 'ticketchannel' => $ticketchanel, 'agentcreated' => $agentcreated, 'agentcurrent' => $agentcreated, 'custid' => $custid, 'priority' => $priority, 'title' =>'Hแป— trแปฃ khรกch hร ng '.$phone, 'ticketusers' => $agentcreated, 'callrefid' => $callrefid, 'tickettype' => $tickettype, 'log_groupid' => $log_groupid ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); // var_dump($postdata); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/insert',false,$context); // var_dump($result); json_output(200,json_decode($result,true)); } public function aj_crm_isrt_tcklog(){ // var_dump($this->input->post()); $ticketid = $this->input->post('ticketid'); $phone = $this->input->post('phone'); $callrefid = $this->input->post('callrefid'); $agentcreated = $this->input->post('agentcreated'); $record = $this->input->post('record'); $duration = $this->input->post('duration'); $tonum = $this->input->post('tonum'); $postdata = http_build_query([ 'ticketid' => $ticketid, 'action' => 'Lฦฐu record tแปซ cuแป™c gแปi '.$phone, 'useraction' => $agentcreated, 'srcrecord' => $record, 'changelog' => 'From: '.$phone.' | To: '.$tonum.' | Duration: '.$duration.'s', 'callrefid' => $callrefid ]); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); // var_dump($postdata); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/insert_ticketlog',false,$context); // var_dump($result); json_output(200,json_decode($result,true)); } public function aj_mitek_hang_up($SIP,$channel){ $curl = curl_init(); $url = 'https://apipbx03.micxm.vn/api/v1/call/hangup?channel='.$SIP.'/'.$channel.'&secret=ac97db2cca493ad87045946aed59eb29'; curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => array( "Cache-Control: no-cache" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { json_output(400,$err); } else { json_output(200,json_decode($response,true)); } } public function aj_mitek_agt_stt($extension){ $json = file_get_contents('https://apipbx03.micxm.vn/api/v1/call/getstatusagent?extension='.$extension); $data = json_decode($json,true); json_output(200,$data); } public function aj_mitek_tranfer($extension,$SIP,$channel){ $json = file_get_contents('https://apipbx03.micxm.vn/api/v1/call/transferCall?extension='.$extension.'&channel='.$SIP.'/'.$channel.'&secret=ac97db2cca493ad87045946aed59eb29'); // echo ('https://apipbx03.micxm.vn/api/v1/call/transferCall?extension='.$extension.'&channel='.$SIP.'/'.$channel.'&secret=ac97db2cca493ad87045946aed59eb29'); $data = json_decode($json,true); json_output(200,$data); } public function aj_mitek_clicktocall($extension,$phone){ $json = file_get_contents('https://apipbx03.micxm.vn/api/v1/call/clicktocall?extension='.$extension.'&phone='.$phone.'&secret=ac97db2cca493ad87045946aed59eb29'); $data = json_decode($json,true); json_output(200,$data); } public function avatar($cusid){ $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/search?action=search_customer&search=&custid='.$cusid.'&telephone=&roleid=1'); $data = json_decode($json,true); if($data['code']==1){ $avatar = $data['data'][0]['avatar']; redirect($avatar, 'location'); }else{ redirect('https://s3.amazonaws.com/uifaces/faces/twitter/dancounsell/128.jpg', 'location'); } } public function getlistormuser(){ // $post = $this->input->post(); $post = json_decode(file_get_contents('php://input'), true); $url = "https://demo.tavicosoft.com/DirectRouter/Index"; $action = 'FrmFdReport'; $method = 'getReturnData'; $data = array(array( 'reportcode'=>'crmCustomer01', 'limit'=>400, 'start'=>0) ); $type='rpc'; $tid=1; $result = $this->M_api->execute_tvc_api($url,$action,$method,$data,$type,$tid); $result_array = json_decode($result,true); // var_dump($result_array['result']); $data = $result_array['result']['data']; echo count($data); foreach ($data as $user) { $user['custid'] = $this->M_api->gen_custid(); $user['groupid'] = 3; $user['roleid'] = 3; foreach ($user as $key => $value) { // echo $key.'=>'.$value.'<br>'; if ($key=='email'||$key=='idcard') { if ($user['email']=='') { $user['email']=$user['idcard']; } // echo $key.'=>'.$value.'<br>'; } if ($value==null) { $user[$key]==''; } } $postdata = http_build_query($user); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/insert',false,$context); $array = json_decode($result,true); // var_dump($user); var_dump($array); // json_output(200,$array); // var_dump($user); echo "<br>"; // exit; # code... } // json_output(200,$data); } public function save_call_log(){ $post = $this->input->post(); $event = isset($post['event'])?$post['event']:''; $object = isset($post['object'])?$post['object']:''; $value = isset($post['value'])?$post['value']:[]; $mitek = []; $mitek['callRefId'] = array(isset($value['callrefid'])?$value['callrefid']:''); $mitek['startDate'] = isset($value['calldate'])?date('Y-m-d H:i:s',strtotime($value['calldate'])):''; $mitek['endDate'] = isset($value['endtime'])?date('Y-m-d H:i:s',strtotime($value['endtime'])):''; $mitek['secret'] = 'ac97db2cca493ad87045946aed59eb29'; $raw_data = json_encode($mitek); $ch = curl_init('https://api-prod.mipbx.vn/api/dev/cdr/getCallsLog'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $raw_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json;charset=uft-8' )); $result = curl_exec($ch); // var_dump($mitek); $response = json_decode($result,true); if (isset($response[0])) { $rs = $this->save_call_info($response[0]); echo $rs; }else{ json_output(200,array('code'=>1,'message'=>'Lแบฅy dแปฏ liแป‡u tแปซ mitek thแบฅt bแบกi.')); exit; } } private function save_call_info($value){ $push = []; $push['callRefId'] = isset($value['callRefId'])?$value['callRefId']:''; $push['callStartTime'] = isset($value['callStartTime'])?date('Y-m-d H:i:s',strtotime(str_replace('/','-',$value['callStartTime']))):''; $push['duration'] = isset($value['duration'])?$value['duration']:''; $push['billSec'] = isset($value['billSec'])?$value['billSec']:''; $push['src'] = isset($value['src'])?$value['src']:''; $push['dst'] = isset($value['dst'])?$value['dst']:''; $push['callStatus'] = isset($value['callStatus'])?$value['callStatus']:''; $push['createdby'] = $this->session->userdata('custid'); foreach ($push as $k => $v) { if ($v=='') { unset($push[$k]); } } // var_dump($push); $postdata = http_build_query($push); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/callinfo/insertcallinfo',false,$context); return $result; } // private function save_call_info($value){ // $push = []; // $push['callrefid'] = isset($value['recid'])?$value['recid']:''; // $push['calldate'] = isset($value['callDate'])?date('Y-m-d H:i:s',strtotime(str_replace('/','-',$value['callDate']))):''; // $push['starttime'] = isset($value['startTime'])?date('Y-m-d H:i:s',strtotime(str_replace('/','-',$value['startTime']))):''; // $push['endtime'] = isset($value['endTime'])?date('Y-m-d H:i:s',strtotime(str_replace('/','-',$value['endTime']))):''; // $push['duration'] = isset($value['duration'])?$value['duration']:''; // $push['billsec'] = isset($value['billSec'])?$value['billSec']:''; // $push['waittime'] = isset($value['waitTime'])?$value['waitTime']:''; // $push['recordingfile'] = isset($value['recFile'])?$value['recFile']:''; // $push['queue'] = isset($value['queue'])?$value['queue']:''; // $push['fromnumber'] = isset($value['src'])?$value['src']:''; // $push['tonumber'] = isset($value['dst'])?$value['dst']:''; // $push['status'] = isset($value['disposition'])?$value['disposition']:''; // $push['calltype'] = isset($value['calltype'])?$value['calltype']:''; // $push['transfercallrefid'] = isset($value['transfercallrefid'])?$value['transfercallrefid']:''; // $push['transferidto'] = isset($value['dstForward'])?$value['dstForward']:''; // $push['extension'] = isset($value['cnam'])?$value['cnam']:''; // $push['extensiontransferto'] = isset($value['extensiontransferto'])?$value['extensiontransferto']:''; // $push['createdby'] = $this->session->userdata('custid'); // foreach ($push as $k => $v) { // if ($v=='') { // unset($push[$k]); // } // } // // var_dump($push); // $postdata = http_build_query($push); // $opts = array('http' => // array( // 'method' => 'POST', // 'header' => 'Content-type: application/x-www-form-urlencoded', // 'content' => $postdata // ) // ); // $context = stream_context_create($opts); // $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/callinfo/insert',false,$context); // return $result; // } public function aj_tck_id_title(){ $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/sl_tck_by_match/ticketid.title.status/'.$this->session->userdata('custid')); $data = json_decode($json,true)['data']; json_output(200,$data); } public function aj_merge_ticket(){ $post = $this->input->post(); $oldticket = isset($post['oldticket'])?$post['oldticket']:''; $newticket = isset($post['newticket'])?$post['newticket']:''; if ($oldticket!='' && $newticket!='') { $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/mergeticket/'.$oldticket.'/'.$newticket); // $data = json_decode($json,true); echo $json; }else{ json_output(200,"expected argument."); } } // public function save_call_log(){ // $post = $this->input->post(); // $event = isset($post['event'])?$post['event']:''; // $object = isset($post['object'])?$post['object']:''; // $value = isset($post['value'])?$post['value']:[]; // $push = []; // $push['event'] = $event; // $push['object'] = $object; // $push['callrefid'] = isset($value['callrefid'])?$value['callrefid']:''; // $push['calldate'] = isset($value['calldate'])?$value['calldate']:''; // $push['starttime'] = isset($value['starttime'])?$value['starttime']:''; // $push['endtime'] = isset($value['endtime'])?$value['endtime']:''; // $push['duration'] = isset($value['duration'])?$value['duration']:''; // $push['billsec'] = isset($value['billsec'])?$value['billsec']:''; // $push['waittime'] = isset($value['waittime'])?$value['waittime']:''; // $push['recordingfile'] = isset($value['recording_file'])?$value['recording_file']:''; // $push['queue'] = isset($value['queue'])?$value['queue']:''; // $push['fromnumber'] = isset($value['fromnumber'])?$value['fromnumber']:''; // $push['tonumber'] = isset($value['tonumber'])?$value['tonumber']:''; // $push['status'] = isset($value['status'])?$value['status']:''; // $push['calltype'] = isset($value['calltype'])?$value['calltype']:''; // $push['transfercallrefid'] = isset($value['transfercallrefid'])?$value['transfercallrefid']:''; // $push['transferidto'] = isset($value['transferidto'])?$value['transferidto']:''; // $push['extension'] = isset($value['extension'])?$value['extension']:''; // $push['extensiontransferto'] = isset($value['extensiontransferto'])?$value['extensiontransferto']:''; // $push['createdby'] = $this->session->userdata('custid'); // foreach ($push as $k => $v) { // if ($v=='') { // unset($push[$k]); // } // } // // var_dump($push); // $postdata = http_build_query($push); // $opts = array('http' => // array( // 'method' => 'POST', // 'header' => 'Content-type: application/x-www-form-urlencoded', // 'content' => $postdata // ) // ); // $context = stream_context_create($opts); // $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/callinfo/insert',false,$context); // echo $result; // } } // { // "secret":"ac97db2cca493ad87045946aed59eb29", // "startDate": "2018-08-01 00:00:00", // "endDate": "2018-09-06 17:11:24", // "extensions": [ // "2300", // "2301", // "2302", // "2303", // "2304", // "2305", // "2306", // "2307", // "2308", // "2309" // ], // "search": "", // "sorts": { // "calldate": "desc" // }, // "page": 1, // "recordsOnPage": 10, // "dsts": [], // "srcs": [], // "dispositions": [], // "getList": true, // "typeFilter": "total" // }<file_sep><script type="text/javascript"> function locphieu($custid,$status,$lienquan){ document.getElementById('iframesearch').src = "<?php echo base_url()?>search/rightSearchTicket/?search=&agentcreated=&agentcurrent="+$custid+"&priority=&status="+$status+"&lienquan="+$lienquan; } function loctheonhom(type){ document.getElementById('iframesearch').src = "<?php echo base_url()?>search/ticketByType/"+type; } </script><file_sep><main class="app-content padding-5 no-padding-right"> <div class="row"> <div class="col-md-2 col-md-22 padding-left-15"> <?php echo isset($left)?$left:'' ?> </div> <div class="col-md-7 padding-left-1"> <?php echo isset($center)?$center:'' ?> </div> <div class="col-md-2 col-md-18 padding-left-5"> <div class="tile"> <h5>Cแบญp nhแบญt</h5> <p class="margin-top-10 no-margin-bot">Cแบญp nhแบญt thรดng tin khรกch hร ng ฤ‘รฃ cรณ trรชn hแป‡ thแป‘ng OMS, viแป‡c ฤ‘แป“ng bแป™ ฤ‘ฦฐแปฃc thแปฑc hiแป‡n sau mแป—i 05 phรบt. ฤแปƒ ฤ‘แบฃm bแบฃo dแปฏ liแป‡u lร  mแป›i nhแบฅt, ngฦฐแปi dรนng cรณ thแปƒ ฤ‘แป“ng bแป™ chแปง ฤ‘แป™ng bแบฑng lแป‡nh dฦฐแป›i ฤ‘รขy.</p> <a href="#">- ฤแป“ng bแป™ Thรดng tin khรกch hร ng...</a> </div> </div> </div> </main><file_sep><script type="text/javascript"> $(".nav-tabs").on("click", "a", function (e) { e.preventDefault(); if (!$(this).hasClass('add-contact')) { $(this).tab('show'); } }) .on("click", ".fa-times", function () { var id = $(".nav-tabs").children().length; // alert(id); var widthsub = window.top.$('.nav-insert').width() * 2; var width = window.top.$('#lengthmenu').width() - widthsub; if(id >4) { $("ul.nav-tabs li").each(function(){ $(this).attr('style', 'width:'+width/(id)+'px !important;'); }); } else{ $("ul.nav-tabs li").each(function(){ $(this).attr('style', 'width:170px !important;'); }); } if(id >1) { var anchor = $(this).siblings('a'); $(anchor.attr('href')).remove(); $(this).parent().remove(); $('.nav-tabs li:nth-child(' + (id-1) + ') a').click(); } }); $('#udpategroup_btn').click(function(){ var groupid = $('#groupid').val(); var ticketrule = $('#ticketrule').val(); var taskrule = $('#taskrule').val(); var userrule = $('#userrule').val(); var knowledgerule = $('#knowledgerule').val();var status = $('#status').val() $.ajax({ url: '<?php echo base_url().'groupuser/updategroup' ?>', type: 'POST', dataType: 'JSON', data: {groupid:groupid,ticketrule:ticketrule,taskrule:taskrule,userrule:userrule,knowledgerule:knowledgerule,status:status}, }) .done(function(data) { if(data.code==1){ window.location.reload(); }else{ alert(data.message); } }) .fail(function() { alert('Lแป—i hแป‡ thแป‘ng, vui lรฒng liรชn hแป‡ Admin'); }); }); $('a.app-menu__item').click(function(){ $('a.app-menu__item').removeClass("active"); $(this).addClass("active"); }); $('#formChangePass').on('submit',function(){ // e.preventDefault(); if($('#new_pass').val() != $('#confirm_pass').val()) { swal("Khรดng trรนng !", "Mแบญt khแบฉu mแป›i vร  xรกc nhแบญn khรดng trรนng.", "error"); } else{ var formData = new FormData($(this)[0]); $('#btn_changepass').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner'); $.ajax({ url: '<?php echo base_url() ?>dashboard/changePassword', dataType: 'JSON', type: 'POST', contentType: false, cache: false, processData:false, data: formData }) .done(function(data){ if(data.code == 1) { $('#btn_changepass').prop('disabled',false).find('i').removeClass(); swal("Thร nh cรดng !", data.message, "success"); $('#modalChangePass').modal('toggle'); $('#old_pass').val(''); $('#new_pass').val(''); $('#confirm_pass').val(''); } else{ $('#btn_changepass').prop('disabled',false).find('i').removeClass(); swal("Lแป—i !", data.message, "error"); } }) .fail(function(){ }); } return false; }); </script><file_sep><script type="text/javascript"> $(document).ready(function(){ $('#modalDelete').on('shown.bs.modal', function (e) { var telephone = $(e.relatedTarget).data('telephone'); $(e.currentTarget).find('input[name="telephone"]').val(telephone); var queue = $(e.relatedTarget).data('queue'); $(e.currentTarget).find('input[name="queue"]').val(queue); }); $('#modalUpdate').on('shown.bs.modal', function (e) { var telephone = $(e.relatedTarget).data('telephone'); $(e.currentTarget).find('input[name="telephone_update"]').val(telephone); var status_update = $(e.relatedTarget).data('status'); $(e.currentTarget).find('input[name="status_update"]').val(status_update); }); }) function changeiFrameQueue() { var ref1 = $('#queue_code').val(); document.getElementById('iframeQueue').src = "<?php echo base_url() ?>queue/rightFilter?queue="+ref1; } function logoutButton() { var telephone = $('#telephone').val(); var queue = $('#queue').val(); $.ajax({ url: '<?php echo base_url() ?>queue/logoutQueue', type: 'POST', dataType: 'JSON', data : {telephone: telephone, queue:queue} }) .done(function(data){ if(data.code == 200) { window.location.reload(); } }) .fail(function(){ alert("Lแป—i hแป‡ thแป‘ng xin vui lรฒng liรชn hแป‡ admin!!"); }); } function loginButton() { var telephone = $('#telephone_login').val(); var queue = $('#queue_login').val(); var status = $('#status_insert').val(); $.ajax({ url: '<?php echo base_url() ?>queue/loginQueue', type: 'POST', dataType: 'JSON', data : {telephone: telephone, queue:queue, status:status} }) .done(function(data){ if(data.code == 200) { if (data.result.response == "Error" && data.result.message.indexOf("ready there")) { alert('Sแป‘ ฤ‘iแป‡n thoแบกi ฤ‘รฃ แปŸ hร ng ฤ‘แปฃi nร y!!'); } else if(data.result.response == "Success") { window.location.reload(); } } else if(data.code ==400) { if (data.message.indexOf("not valid")) { alert('Sแป‘ ฤ‘iแป‡n thoแบกi hoแบทc hร ng ฤ‘แปฃi khรดng hแปฃp lแป‡!!'); } } }) .fail(function(){ }); } </script>
c2245e106ca21daf6ae350f746907e8f1f3cb8c2
[ "JavaScript", "PHP", "Shell" ]
103
PHP
nguyenquangsang160596/crm_hungminh
e4df09c0de49b7150a4478f0278ed1a4e1850fda
d785c5207f4c26d704c7843a91b2d2732a786f64
refs/heads/master
<file_sep>package com.boolea.interfazdistribuida; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView mTvAutor; private TextView mTvTitulo; private TextView mTvNoticia; private TextView mTvFecha; private int countNoticia = 0; @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); cambiarNoticia(null); } private void initView () { mTvAutor = findViewById(R.id.tv_autor); mTvFecha = findViewById(R.id.tv_fecha); mTvNoticia = findViewById(R.id.tv_noticia_descripcion); mTvTitulo = findViewById(R.id.tv_titulo); } public void cambiarNoticia (View view) { if (countNoticia % 2 == 0) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); } countNoticia++; } }
b652eaab4bab8c777e420b463bc99a91231f1438
[ "Java" ]
1
Java
oscarito9410/Interfazdistribuida
f6ae01c559e43c7875b3558573535c71452a16e0
bd50976469e2ce57a5752409014057e7c9da82eb
refs/heads/master
<repo_name>crisgonzalez94/laravel-red-social<file_sep>/app/Http/Controllers/UserController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; //Esta la necesitamos para enviar archivos a la vista use Illuminate\Http\Response; //Dependencias para la subida de archivos use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\File; class UserController extends Controller{ public function __construct(){ //Midleware de atuenticacion $this->middleware('auth'); } public function config(){ return view('user.config'); } /*=============================================================================*/ /*Metodo Actualizar usuario*/ public function update(Request $req){ //Datos actuales del usuario loggeado $user = \Auth::user(); $id = $user->id; /*Validar los campos*/ $validate = $this->validate($req , [ 'name' => 'required|string|max:100', 'surname' => 'required|string|max:200', //propiedad unica (solo permitiendo que sea igual al nick del usuario) 'nick' => 'required|string|max:100|unique:users,nick,'.$id, //email 'email' => 'required|email|max:255|unique:users,email,'.$id, ]); /*Recoger los datos del formulario*/ $name = $req->input('name'); $surname = $req->input('surname'); $nick = $req->input('nick'); $email = $req->input('email'); //Asignar nuevos valores en la base de datos $user->name = $name; $user->surname = $surname; $user->nick = $nick; $user->email = $email; echo $nick; //Recibir imagen $image = $req->file('image'); if($image){ //Creamos un nombre para la imagen (en este caso tiempo + nombre de usuario) $image_path = time().$user->nick.".jpg"; //Guardar el archivo en el servidor especificando el disco a guardar Storage::disk('users')->put($image_path , File::get($image) ); //Guardar el dato del path en la base de datos $user->image = $image_path; } $user->update(); //Retornar alguna ruta (utilizando el name de la ruta) return redirect()->route('config') /*Esto creara una session llamada message que podremos detectarla con la vista */ ->with(['message'=>'Usuario actualizado']); } /*=============================================================================*/ /*=============================================================================*/ //Metodo para mostrar el avatar public function getImage($filename){ $file = Storage::disk('users')->get($filename); return new Response($file , 200); } /*=============================================================================*/ } <file_sep>/app/Http/Controllers/ImageController.php <?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; use Illuminate\Http\Request; //Esta la necesitamos para enviar archivos a la vista use Illuminate\Http\Response; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\File; //Modelo de Image use App\Image; class ImageController extends Controller { public function __construct(){ //Midleware de atuenticacion $this->middleware('auth'); } public function create(){ return view('image.create'); } public function save(Request $req){ //Datos del usuario loggeado $user = \Auth::user(); $user_id = $user->id; $validate = $this->validate($req , [ 'description' => 'required', 'image_path' => 'required|mimes:jpg,png,gif,jpeg' ]); //Obtenemos la imagen $image = $req->file('image_path'); if($image){ //Le damos un nombre a la imagen para que sea unico $image_path = time().$user->nick.'.jpg'; $description = $req->input('description'); //Guardar imagen Storage::disk('images')->put($image_path , File::get($image) ); //Guardar el path del imagen al usuario } $image = DB::table('images')->insert(array( 'user_id' => $user_id, 'image_path' => $image_path, 'description' => $description )); //Retornar alguna ruta (utilizando el name de la ruta) return redirect()->route('home')->with([ 'message' => 'La foto ha sido subida correctamente' ]); } /*============================================================================*/ //Pintar las imagenes del muro public function print($filename){ $file = Storage::disk('images')->get($filename); return new Response($file , 200); } //Controla una pagina donde se va a abrir una pagina completa para la imagen public function detail($id){ $image = Image::find($id); return view ('image.detail' , [ 'image' => $image ]); } }<file_sep>/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; //Importar el modelo de imagenes use App\Image; class HomeController extends Controller{ /** * Create a new controller instance. * @return void */ public function __construct(){ $this->middleware('auth'); } /** * Show the application dashboard. * @return \Illuminate\Contracts\Support\Renderable */ public function index(){ //Obtenemos las imagenes de la db //Para una carga normal se utiliza el metodo get() //pero como es paginacion usamos paginate(cantidad elem por paginas) $images = Image::orderBy('id' , 'desc')->paginate(2); //Retornamos a la vista enviando las imagenes return view('home' , [ 'images' => $images ]); } }<file_sep>/app/Http/Controllers/CommentController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class CommentController extends Controller{ //Funcion para comentar public function create(Request $req){ $current_date = date('Y-m-d H:i:s'); //Obtener el id de la imagen a comentar $image_id = $req->input('image_id'); //id del usuario loggeado $user_id = $req->input('user_id'); //comentario $content = $req->input('content'); //Validar comentario $validate = $this->validate($req , [ 'image_id' => 'required | integer', 'content' => 'required | string | min:1 ' ]); $save = DB::table('comments')->insert(array( 'user_id' => $user_id, 'image_id' => $image_id, 'content' => $content, 'created_at' => $current_date )); //Retornar alguna ruta (utilizando el name de la ruta) return redirect()->route('image.detail' , ['id' => $image_id])->with([ 'message' => 'Su comentario se aรฑadio con exito.' ]); } public function delete($comment_id , $image_id){ echo "comment_id: ".$comment_id."<br>"; echo "image_id: ".$image_id."<br>"; $delete = DB::table('comments')->where('id' , '=' , $comment_id )->delete(); return redirect()->route('image.detail' , ['id' => $image_id])->with([ 'message' => 'Su comentario se borro con exito.' ]); } } <file_sep>/database/database.sql CREATE DATABASE red_social; USE red_social; CREATE TABLE IF NOT EXISTS users( id INT(255) AUTO_INCREMENT NOT NULL, role VARCHAR(20), name VARCHAR(100), surname VARCHAR(200), nick VARCHAR(100), email VARCHAR(255), password VARCHAR(255), image VARCHAR(255), created_at DATETIME, updated_at DATETIME, remember_token VARCHAR(255), CONSTRAINT pk_users PRIMARY KEY (id) )Engine=InnoDb; CREATE TABLE IF NOT EXISTS images( id INT(255) AUTO_INCREMENT NOT NULL, user_id INT(255), image_path VARCHAR(255), description TEXT, created_at DATETIME, updated_at DATETIME, CONSTRAINT pk_images PRIMARY KEY (id), CONSTRAINT fk_images_users FOREIGN KEY (user_id) REFERENCES users(id) )Engine=InnoDb; CREATE TABLE IF NOT EXISTS comments( id INT(255) AUTO_INCREMENT NOT NULL, user_id INT(255), image_id INT(255), content TEXT, created_at DATETIME, updated_at DATETIME, CONSTRAINT pk_comments PRIMARY KEY (id), CONSTRAINT fk_comments_users FOREIGN KEY (user_id) REFERENCES users(id), CONSTRAINT fk_comments_images FOREIGN KEY (image_id) REFERENCES images(id) )Engine=InnoDb; CREATE TABLE IF NOT EXISTS likes( id INT(255) AUTO_INCREMENT NOT NULL, user_id INT(255), image_id INT(255), created_at DATETIME, updated_at DATETIME, CONSTRAINT pk_users PRIMARY KEY (id), CONSTRAINT fk_likes_users FOREIGN KEY (user_id) REFERENCES users(id), CONSTRAINT fk_likes_images FOREIGN KEY (image_id) REFERENCES images(id) )Engine=InnoDb; /*=============================================================================================== Users ==============================================================================================*/ INSERT INTO users VALUES( NULL, 'user' , 'Victor' , 'Robles' , 'victorroblesweb' , '<EMAIL>' , '12345678', null , CURTIME() , CURTIME() , NULL ); INSERT INTO users VALUES( NULL, 'user' , 'Juan' , 'Lopez' , 'juanlopez' , '<EMAIL>' , '12345678', null , CURTIME() , CURTIME() , NULL ); INSERT INTO users VALUES( NULL, 'user' , 'Manolo' , 'Garcia' , 'manologarcia' , '<EMAIL>' , '12345678', null , CURTIME() , CURTIME() , NULL ); /*=============================================================================================== Images ==============================================================================================*/ INSERT INTO images VALUES( null, 1, 'test.jpg', 'Descripcion de prueba 1', CURTIME(), CURTIME() ); INSERT INTO images VALUES( null, 1, 'playa.jpg', 'Descripcion de prueba 2', CURTIME(), CURTIME() ); INSERT INTO images VALUES( null, 1, 'arena.jpg', 'Descripcion de prueba 3', CURTIME(), CURTIME() ); INSERT INTO images VALUES( null, 3, 'familia.jpg', 'Descripcion de prueba 4', CURTIME(), CURTIME() ); /*=============================================================================================== Comments ==============================================================================================*/ INSERT INTO comments VALUES( null, 1, 4, 'Buena foto de familia', CURTIME(), CURTIME() ); INSERT INTO comments VALUES( null, 2, 1, 'Buena foto de playa', CURTIME(), CURTIME() ); INSERT INTO comments VALUES( null, 2, 4, 'Que bueno', CURTIME(), CURTIME() ); /*=============================================================================================== Likes ==============================================================================================*/ INSERT INTO likes VALUES( NULL , 1, 4, CURTIME(), CURTIME() ); INSERT INTO likes VALUES( NULL , 2, 4, CURTIME(), CURTIME() ); INSERT INTO likes VALUES( NULL , 3, 1, CURTIME(), CURTIME() ); INSERT INTO likes VALUES( NULL , 3, 2, CURTIME(), CURTIME() );<file_sep>/routes/web.php <?php use App\Image; //Importar controlladores use App\Http\Controllers\UserController; use App\Http\Controllers\ImageController; use App\Http\Controllers\CommentController; Route::get('/', 'HomeController@index')->name('home'); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); //Rutas para editar usuario Route::get('/configuracion' , [UserController::class , 'config'])->name('config'); Route::post('/user/edit' , [UserController::class , 'update'])->name('user.update'); //Ruta para cargar el avatar Route::get('/user/avatar/{filename}', [UserController::class , 'getImage'])->name('user.avatar'); //Ruta para administrar las imagenes Route::get('/image/create' , [ImageController::class , 'create'])->name('image.create'); Route::post('/image/save' , [ImageController::class , 'save'])->name('image.save'); //Rutas para cargar las imagenes en el muro Route::get('image/print/{filename}' , [ImageController::class , 'print'])->name('image.print'); //Ruta para abrir la pagina detallada de la imagen Route::get('image/detail/{id}' , [ImageController::class , 'detail'])->name('image.detail'); //Ruta para comentar Route::post('comment/create' , [CommentController::class , 'create'])->name('comment.create'); Route::get('comment/delete/{comment_id}/{image_id}' , [CommentController::class , 'delete'])->name('comment.delete');
76f7bc2f00a7f73cbafc9f7fb0a7390bd98c85be
[ "SQL", "PHP" ]
6
PHP
crisgonzalez94/laravel-red-social
461921fdcbf672b236d09f6c8eb1dbdc10a35cea
1f843e1f046348ae5136c891d32e2edf97513a01
refs/heads/master
<file_sep>rootProject.name = 'priorityq' <file_sep>package ie.jgriffin.priorityq.model.impl; import ie.jgriffin.priorityq.model.WorkOrder; import org.joda.time.DateTime; import org.joda.time.Seconds; /** * Created by jgriffin on 18/04/2017. * <p> * Computes the rank for any given WorkOrder object. Accepts a reference DateTime object in its constructor to ensure that all time computations performed by this instance reference the same instant in time. */ public class RankComputer { /* * This reference DateTime is used to ensure that all time computations performed by this instance reference the * same instant in time. */ private final DateTime referenceDateTime; /** * Constructs a new instance of RankComputer. * * @param referenceDateTime This reference DateTime is used to ensure that all time computations performed by this instance reference the same instant in time. */ public RankComputer(DateTime referenceDateTime) { this.referenceDateTime = referenceDateTime; } /** * Computes the rank for the passed WorkOrderImpl. * * @param workOrder The WorkOrder to compute the ranking for. * @return a double representing the ranking for the WorkOrder. */ public Double compute(WorkOrder workOrder) { long workOrderId = workOrder.getId(); long managementOverrideRemainder = workOrderId % RankConstants.MANAGEMENT_OVERRIDE; if (managementOverrideRemainder == 0) { return computeSecondsElapsed(workOrder); } else if (managementOverrideRemainder % RankConstants.VIP_FACTOR == 0) { return computeVIPRank(workOrder); } else if (managementOverrideRemainder % RankConstants.PRIORITY_FACTOR == 0) { return computePriorityRank(workOrder); } else { return computeSecondsElapsed(workOrder); } } /** * Computes how many seconds have elapsed since the WorkOrder was placed in the queue. * * @param workOrder The WorkOrder to compare to the reference DateTime to compute how many seconds have elapsed. * @return The number of seconds that have elapsed from the reference DateTime. */ private double computeSecondsElapsed(WorkOrder workOrder) { return Seconds.secondsBetween(workOrder.getDateTime(), referenceDateTime).getSeconds(); } /** * The rank for a VIP WorkOrder is calculated using the formula max(4, 2n log n) where n is the number of seconds that have elapsed from the reference DateTime. * * @param workOrder The VIP WorkOrder to compute the rank for. * @return The rank of the VIP WorkOrder */ private double computeVIPRank(WorkOrder workOrder) { final double secondsElapsed = computeSecondsElapsed(workOrder); return Math.max(4, (2 * secondsElapsed) * Math.log(secondsElapsed)); } /** * The rank for a Priority WorkOrder is calculated using the formula max(3, n log n) where n is the number of seconds that have elapsed from the reference DateTime. * * @param workOrder The Priority WorkOrder to compute the rank for. * @return The rank of the Priority WorkOrder */ private double computePriorityRank(WorkOrder workOrder) { final double secondsElapsed = computeSecondsElapsed(workOrder); return Math.max(3, secondsElapsed * Math.log(secondsElapsed)); } } <file_sep>package ie.jgriffin.priorityq.model.impl; /** * Created by jgriffin on 18/04/2017. */ public class RankConstants { /** * The factor used to determine whether a WorkOrder's requestor Id is of type priority. */ public static final long PRIORITY_FACTOR = 3L; /** * The factor used to determine whether a WorkOrder's requestor Id is of type VIP. */ public static final long VIP_FACTOR = 5L; /** * The factor used to determine whether a WorkOrder's requestor Id is of type management override. */ public static final long MANAGEMENT_OVERRIDE = PRIORITY_FACTOR * VIP_FACTOR; } <file_sep># F1zzBuzzPr10r1tyQ This is a Spring Boot project which allows clients to add and remove WorkOrders to a priority queue in a RESTful manner. # Building and running the app This is a gradle project which uses the gradle wrapper. On Windows the following commands can be used in the project's root folder To build the project: ```` gradlew.bat build ```` To run the generated jar navigate to {projectDir}/build/libs then run: ```` java -jar app-1.0.jar ```` To run unit tests and generate jacoco reports run (from the project root), jacoco reports will be at {projectDir}/build/reports/jacoco/test/html ```` gradlew.bat test jacocoTestReport ```` To generate javadocs run (from the project root), javadocs will be available at {projectDir}/build/docs/javadoc ```` gradlew.bat javadoc ```` SwaggerUI can be used to view documentation and test the REST API here when the app is running ```` http://localhost:8080/jgriffin-priorityq/api/v1/swagger-ui.html ```` # General Notes * All REST API parameters are mandatory * DateTime fields use the standard ISO-8601 DateTime format, example: "2017-04-18T23:28:12.000Z" <file_sep>package ie.jgriffin.priorityq.config; import ie.jgriffin.priorityq.persistence.WorkOrderQueue; import ie.jgriffin.priorityq.persistence.impl.WorkOrderQueueImpl; import ie.jgriffin.priorityq.rest.WorkOrderRestController; import ie.jgriffin.priorityq.validation.WorkOrderValidator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Created by jgriffin on 19/04/2017. * <p> * The JavaConfig class for this service, creates and configures all necessary beans. */ @Configuration public class ApplicationConfig { @Bean public WorkOrderRestController workOrderRestController() { return new WorkOrderRestController(workOrderQueue(), workOrderValidator()); } @Bean public WorkOrderQueue workOrderQueue() { return new WorkOrderQueueImpl(); } @Bean public WorkOrderValidator workOrderValidator() { return new WorkOrderValidator(); } } <file_sep>package ie.jgriffin.priorityq.model.impl; import org.joda.time.DateTime; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Created by jgriffin on 18/04/2017. */ public class WorkOrderImplTest { @Test public void constructor_ValidFields_GettersReturnPassedValues() { final Long id = 1L; final DateTime dateTime = DateTime.now(); WorkOrderImpl workOrder = new WorkOrderImpl(id, dateTime); assertEquals("incorrect id", id, workOrder.getId()); assertEquals("incorrect dateTime", dateTime, workOrder.getDateTime()); } } <file_sep>server.contextPath=/jgriffin-priorityq/api/v1 spring.jackson.serialization.write_dates_as_timestamps=false <file_sep>package ie.jgriffin.priorityq.model.impl; import ie.jgriffin.priorityq.model.WorkOrder; import java.io.Serializable; import java.util.Comparator; /** * Created by jgriffin on 18/04/2017. * <p> * The Comparator used to sort WorkOrders in the WorkOrderQueue by rank, higher ranked WorkOrders will be placed at the head of the queue. */ public class WorkOrderRankComparator implements Comparator<WorkOrder>, Serializable { private final RankComputer rankComputer; public WorkOrderRankComparator(RankComputer rankComputer) { this.rankComputer = rankComputer; } @Override public int compare(WorkOrder o1, WorkOrder o2) { boolean managementOverrideO1 = o1.getId() % RankConstants.MANAGEMENT_OVERRIDE == 0; boolean managementOverrideO2 = o2.getId() % RankConstants.MANAGEMENT_OVERRIDE == 0; //special case: if only one of the workOrders is a management override id then there is no need to compute rank if (managementOverrideO1 && !managementOverrideO2) { return -1; } else if (!managementOverrideO1 && managementOverrideO2) { return 1; } else { //the higher ranked objects should be at the head of the queue, so reverse the computed rank difference return -((Double) (rankComputer.compute(o1) - rankComputer.compute(o2))).intValue(); } } } <file_sep>package ie.jgriffin.priorityq.model.impl; import ie.jgriffin.priorityq.model.WorkOrder; import org.joda.time.DateTime; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; /** * Created by jgriffin on 18/04/2017. */ @RunWith(MockitoJUnitRunner.class) public class WorkOrderComparatorTest { @InjectMocks private WorkOrderRankComparator workOrderComparator; @Mock private RankComputer mockRankComputer; @Mock private WorkOrder mockWO1; @Mock private WorkOrder mockWO2; @Test public void compare_BothComparatorsNotManagementOverride_InvertedRankDifferenceUsedToCompare(){ when(mockWO1.getId()).thenReturn(RankConstants.PRIORITY_FACTOR); when(mockWO2.getId()).thenReturn(RankConstants.PRIORITY_FACTOR); when(mockRankComputer.compute(mockWO1)).thenReturn(10D); when(mockRankComputer.compute(mockWO2)).thenReturn(1D); int result = workOrderComparator.compare(mockWO1, mockWO2); assertTrue("incorrect compare result", result < 0); } @Test public void compare_ManagementOverrideFirst_NegativeResult(){ when(mockWO1.getId()).thenReturn(RankConstants.MANAGEMENT_OVERRIDE); when(mockWO2.getId()).thenReturn(RankConstants.PRIORITY_FACTOR); int result = workOrderComparator.compare(mockWO1, mockWO2); assertTrue("incorrect compare result", result < 0); } @Test public void compare_ManagementOverrideSecond_PositiveResult(){ when(mockWO1.getId()).thenReturn(RankConstants.PRIORITY_FACTOR); when(mockWO2.getId()).thenReturn(RankConstants.MANAGEMENT_OVERRIDE); int result = workOrderComparator.compare(mockWO1, mockWO2); assertTrue("incorrect compare result", result > 0); } }
960d839fae08e91f599cb9dd0a67094bc46841c1
[ "Markdown", "Java", "INI", "Gradle" ]
9
Gradle
griffinjm/F1zzBuzzPr10r1tyQ
8db00182388f27d0c7fa3aa7313c944e33859863
906b146291a229372fdcea2f3ea2aa2a35bfac3d
refs/heads/master
<repo_name>Borumer/Virtual-Calculator<file_sep>/index.md # Kalculator <a href = "calculator/application.windows64/calculator.exe">64-bit Windows</a> <a href = "calculator/application.windows32/calculator.exe">32-bit Windows</a> <a href = "calculator/calculator.pde" download = "Kalculator">Download calculator</a> <file_sep>/calculator/application.windows32/source/Operation.java import java.util.ArrayList; public class Operation { String operation; String operationSymbol; ArrayList<String> userInput = calculator.listName; public Operation(String op, String operSymbol) { operation = op; operationSymbol = operSymbol; } double doOperation(double double1, double double2) { switch (operationSymbol) { case "+": return double1 + double2; case "-": return double1 - double2; case "*": return double1 * double2; case "/": return double1 / double2; case "%": return double1 % double2; case "^": return Math.pow(double1, double2); case "\u221A": return Math.pow(double2, 1 / double1); default: return 0.0; } } String calculate() { int operationIndex = userInput.indexOf(operationSymbol); // The location at which the user pressed an operation sign ArrayList<String> ClickedNumbers = new ArrayList<String>(); // Create an array list of all the characters before the operation sign System.out.println(operation + " index: " + operationIndex); for (int i = 0; i < operationIndex; i++) { ClickedNumbers.add(userInput.get(i)); // Adds all the number strings before the sign to clicked numbers } double double1 = calculator.StringToDouble(String.join("", ClickedNumbers)); // Converts the joined ClickedNumbers array list before the sign into a double System.out.println("double1: " + double1); ClickedNumbers.clear(); int equalsIndex = userInput.indexOf("="); // Find the location at which the user pressed equals for (int i = operationIndex + 1; i < equalsIndex; i++) { ClickedNumbers.add(userInput.get(i)); } double double2 = calculator.StringToDouble(String.join("", ClickedNumbers)); // Converts the joined ClickedNumbers array list after the sign into a double System.out.println("double2: " + double2); Double operResult = this.doOperation(double1, double2); String operationResult = calculator.doubleToString(operResult); System.out.println("Operation Result: " + operationResult); return operationResult; } } <file_sep>/README.md # Virtual Calculator The calculator app is an app I made from Processing java, finished in 3 days and first programmed on Eclipse. 7/19/2018 Release v.1.2.0 Calculator The app consists of numbers, *, +, ^, %(modulus), -, =, and . (Working) I have yet to add +/-, โˆš, trigonometry, %(percent) I also plan on making it easier, more efficient, and reduce the large amount of repeated code that there is already with the current method. Finishing touches will include - making the colors and design more professional, higher quality, - mouse hover making the button display change in some way 8/30/2018 Release v1.3.0 The Key Update The Key Update introduces newly written code with regular expressions, key-based input for numbers and operations, and negatives! The calculator app is still in beta, so stay tuned for adding multiple operations at once and parenthesis! (()) 8/28/2018 Release v2.0.0 The Regular Expression Update The app calculations are now refactored to be called from a single method in the Operation class This app uses regular expressions There are now negatives Resolved issue with text repeating When there are supposed to be errors, the program simply doesn't try to do the operation because the expression isn't valid The less precision is still a problem even though the floats are not Overall, the app is much easier to code, use, and update 12/16/2018 Release v2.1.0 The Hover Update New Operations! root, reciprocal, and x^2 Refactored GridSquare new instances, so now it is easier to lay out the calculator button texts in the 2-D array textToDisplay String[][] The calculator looks more professional The buttons now light up on mouse hover <file_sep>/calculator/application.windows64/source/calculator.java import processing.core.*; import processing.data.*; import processing.event.*; import processing.opengl.*; import java.util.ArrayList; import java.util.Arrays; import java.util.regex.*; import java.util.HashMap; import java.util.ArrayList; import java.io.File; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class calculator extends PApplet { public String result = ""; public String processStatement = ""; float screenMargin = 40; float padding = 15; public static ArrayList < String > listName = new ArrayList < String > (); float w = 0; float h = 0; float totalMargin = 2 * screenMargin; String[][] textToDisplay = new String[][] { { "%", "\u221A", "xยฒ", "1/x" }, { "^", "C", "<-", "/" }, { "7", "8", "9", "*", }, { "4", "5", "6", "-", }, { "1", "2", "3", "+", }, { " ", "0", ".", "=", } }; int rows = textToDisplay.length; int cols = textToDisplay[2].length; GridSquare[][] buttons; Operation addition = new Operation("Plus", "+"); Operation subtraction = new Operation("Subtract", "-"); Operation multiplication = new Operation("Multiply", "*"); Operation division = new Operation("Divide", "/"); Operation modulus = new Operation("Modulo", "%"); Operation exponential = new Operation("Expound", "^"); Operation root = new Operation("Root", "\u221A"); public void settings() { size(400, 600); } public void setup() { background(255, 255, 255); System.out.println(Arrays.deepToString(textToDisplay)); } public void draw() { drawCalculator(); drawButtons(); } public void drawCalculator() { w = (width - totalMargin); h = (height - totalMargin); rectMode(CORNER); // Draw perimeter of calculator fill(125, 125, 125); rect(screenMargin, screenMargin, w, h); // Create screen drawScreen(); } public void drawScreen() { w = (width - totalMargin); h = (height - totalMargin); fill(255); rect(screenMargin + padding, screenMargin + padding, w - 2 * padding, h / 8); fill(0, 0, 0); textAlign(RIGHT, CENTER); text(String.join("", listName), 300, 80); } public void drawButtons() { w = (width - totalMargin); h = (height - totalMargin); buttons = new GridSquare[rows][cols]; float margin = 65; float calcMarginX = 0; float calcMarginY = 130; float dimensions = 45; float totalWidth = margin + dimensions * (cols - 1); for (int i = 0; i < rows; i++) { for (int j = 0; j < textToDisplay[i].length; j++) { calcMarginX = w - totalWidth; calcMarginX /= 2; calcMarginX += screenMargin; buttons[i][j] = new GridSquare(j * margin + calcMarginX, i * margin + calcMarginY, dimensions, dimensions); if (buttons[i][j].onHover(mouseX, mouseY)) { buttons[i][j].c = color(255, 210, 210, 100); } else { buttons[i][j].c = color(255, 255, 255); } buttons[i][j].displayText(textToDisplay, i, j); } } } public boolean validateExpression(String exp ) { // Reg Ex: - or + one or more numbers . one or more numbers operator same thing String regex = "^[-]?[0-9]*\\.?[0-9]+[\\/\\+\\-\\*\\%\\^\\\u221A][-+]?[0-9]*\\.?[0-9]+=$"; Pattern pattern = Pattern.compile( regex ); Matcher matcher = pattern.matcher( exp.trim() ); return matcher.find(); } public void getCalcFunctionality() { boolean isValidated = validateExpression(String.join("", listName)); if (isValidated) { if (listName.contains("+")) { processStatement = "Adding Numbers..."; result = addition.calculate(); } else if (listName.contains("-")) { processStatement = "Subtracting Numbers..."; result = subtraction.calculate(); } else if (listName.contains("*")) { processStatement = "Multiplying Numbers..."; result = multiplication.calculate(); } else if (listName.contains("/")) { processStatement = "Dividing Numbers..."; result = division.calculate(); } else if (listName.contains("%")) { processStatement = "Modulufying Numbers..."; result = modulus.calculate(); } else if (listName.contains("^")) { processStatement = "Expounding numbers..."; result = exponential.calculate(); } else if (listName.contains("\u221A")) { processStatement = "Rooting Numbers..."; result = root.calculate(); } System.out.println(processStatement); } if (listName.contains("C")) { listName.clear(); // Clears the "Screen" when C is clicked by clearing the array } else if (listName.contains("=")) { listName.clear(); // Clears the "Screen" when = is clicked by clearing the array listName.add(result); // Show the result drawScreen(); } } public static String doubleToString(double dble) { return String.valueOf(dble); } public static float StringToFloat(String string) { return Float.parseFloat(string); } public static double StringToDouble(String string) { return Double.parseDouble(string); } public void mouseReleased() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { buttons[i][j].onClick(mouseX, mouseY); } } getCalcFunctionality(); } public void keyTyped() { String key1 = Character.toString(key); for (int i = 0; i < textToDisplay.length; i++) { if (Arrays.asList(textToDisplay[i]).contains(key1)) { listName.add(key1); } } final boolean bool = key == ENTER || key == RETURN; if (bool) listName.add("="); getCalcFunctionality(); } public class GridSquare{ public float x; public float y; public float ws; public float hs; public String value; public int c = color(255, 255, 255); public GridSquare(float tempX, float tempY, float tempW, float tempH) { x = tempX; y = tempY; ws = tempW; hs = tempH; } public Boolean onHover(float clickedX, float clickedY) { return clickedX > x && clickedX < x + ws && clickedY > y && clickedY < y + hs; } public void onClick(float clickedX, float clickedY) { boolean isEmpty = result.length() == 0; // If the user is still putting in the expression // If a grid square is clicked if (this.onHover(clickedX, clickedY)) { if (isEmpty) { listName.add(value); // Push the result to the screen (listName) System.out.println("Mouse Button Input: " + listName.toString()); // Show the array of mouse button input } else if (!isEmpty && listName.size() <= 1) { // If the user starts a new expression without pressing C then reset all the variables and add the first character to the screen and listName arrayList listName.remove(0); listName.add(value); result = ""; } } } public void draw() { fill(c); rectMode(CORNER); rect(x, y, ws, hs); } public void displayText(String[][] text2Display, int i, int j) { float squarePadding = 20; // Space between each square this.draw(); textSize(20); fill(0); textAlign(CENTER, CENTER); value = text2Display[i][j]; text(value, x + squarePadding, y + squarePadding); } } static public void main(String[] passedArgs) { String[] appletArgs = new String[] { "calculator" }; if (passedArgs != null) { PApplet.main(concat(appletArgs, passedArgs)); } else { PApplet.main(appletArgs); } } }
f263597a30b6ed61483e4e32f83b25d20cebeddb
[ "Markdown", "Java" ]
4
Markdown
Borumer/Virtual-Calculator
8d31ccb7ea796557bca22dc8c2bbd8d68d8d9234
7c0939b1d2cc1d95d01333ef9118481dc9bb7fca
refs/heads/master
<repo_name>AntonioJesPG/JuegosProgramacion<file_sep>/3EnRaya/src/Final_Version/Podio.java package Final_Version; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import javax.swing.JPanel; import javax.swing.JFrame; import javax.swing.JOptionPane; import java.util.ArrayList; import java.util.List; //Esta clase es usada para mostrar el podio y ver que jugador ha ganado public class Podio extends Canvas{ JFrame ventana = new JFrame("Podio"); //Alto y ancho de la ventana private static final int JFRAME_WIDTH=700; private static final int JFRAME_HEIGHT=700; private int ganador; //Constructor public Podio(int i) { ganador = i; AlmacenImagenes.getInstance(); //Creamos el JPanel haciendo un recast del contenido de nuestra ventana JPanel panel = (JPanel) ventana.getContentPane(); //Le establecemos el layout al panel y lo aรฑadimos panel.setLayout(new BorderLayout()); panel.add(this, BorderLayout.CENTER); //Dimensiรณn de la ventana ventana.setBounds(0,0,JFRAME_WIDTH,JFRAME_HEIGHT); //Sonido en bucle del podio AlmacenSonidos.getInstance().loopSound("VictoryTheme.wav"); //Eliminamos el cierre normal de la ventana y personalizamos la posibilidad de cerrar la ventana ventana.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { cerrarAplicacion(); } }); //Mostrar la ventana ventana.setVisible(true); //Cambiamos el foco al canvas this.requestFocus(); } private void cerrarAplicacion() { String[] opciones = {"Aceptar","Cancelar"}; //Creamos las opciones de salir de la aplicaciรณn int eleccion = JOptionPane.showOptionDialog(ventana, "ยฟSalir de la aplicaciรณn?","Salir", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, opciones, "Aceptar"); //Si el usuario desea salir lo cerramos if(eleccion == JOptionPane.YES_OPTION) { System.exit(0); } } //Modificamos el mรฉtodo paint de canvas @Override public void paint(Graphics g) { super.paint(g); if(ganador == TresEnRaya.getInstance().JUGADOR_1) { g.drawImage(AlmacenImagenes.getInstance().getSprite("ganadorJ1.png"),0,0,JFRAME_WIDTH,JFRAME_HEIGHT,this); } if(ganador == TresEnRaya.getInstance().JUGADOR_2) { g.drawImage(AlmacenImagenes.getInstance().getSprite("ganadorJ2.png"),0,0,JFRAME_WIDTH,JFRAME_HEIGHT,this); } } } <file_sep>/Formula1/src/Version_1/Pista.java package Version_1; import javax.swing.JOptionPane; public class Pista { private Vehiculo conductor; private Obstaculo[] obstaculos = new Obstaculo[4]; private final int tamanioPista = 20; private String[] p = new String[tamanioPista]; public Pista(Vehiculo v, int idConductor) { for(int i = 0 ; i < 4 ; i++) { int valor = (int) Math.round(Math.random() * (100 - 0)) + 0; int posicionEnPista = (int) Math.round(Math.random() * (19 - 1)) + 1; while(hayObstaculo(posicionEnPista)) { posicionEnPista = (int) Math.round(Math.random() * (19 - 1)) + 1; } //Hay que crear posiciones al azar if(valor >= 50) { Mancha mancha = new Mancha(posicionEnPista,1); obstaculos[i] = mancha; } if(valor < 50) { Rampa rampa = new Rampa(posicionEnPista,1); obstaculos[i] = rampa; } } this.conductor = v; for(int i = 0; i < tamanioPista ; i++) p[i] = null; p[0] = "X"; for(int i=0; i < obstaculos.length; i++) { if(obstaculos[i] != null) { if(obstaculos[i] instanceof Mancha) p[obstaculos[i].getX()] = "M"; if(obstaculos[i] instanceof Rampa) p[obstaculos[i].getX()] = "R"; } } System.out.println("Conductor " + idConductor); mostrarPista(); } public void mostrarPista() { System.out.print("\n["); for(int i = 0; i<p.length ; i++) { if(p[i]==null) System.out.print(" ,"); else System.out.print(p[i] + ","); } System.out.println("]\n"); } public void conducir() { int cantidadMovimiento = conductor.avanza(); int movimientosRestantes = cantidadMovimiento; boolean puedoMoverme = true; for(int i = 0; i <= cantidadMovimiento; i++) { p[conductor.getX()] = null; if(puedoMoverme) { conductor.setX(conductor.getX()+1); movimientosRestantes--; if(movimientosRestantes <= 0) puedoMoverme = false; } if(hayObstaculo(conductor.getX())) { movimientosRestantes = movimientosRestantes - pasarObstaculo(conductor.getX()); } if(conductor.getX() < p.length) p[conductor.getX()] = "X"; else { p[tamanioPista-1] = "X"; i = cantidadMovimiento+1; } } mostrarPista(); } //conductor.setX(cantidadMovimiento); public int pasarObstaculo(int pos) { for(int i = 0 ; i < 4 ; i++) { if(obstaculos[i] != null) { if(obstaculos[i].getX() == pos) return obstaculos[i].getReduccionDeVelocidad(); } } return 0; } public boolean hayObstaculo(int pos) { boolean obstaculo = false; for(int i = 0 ; i < 4 ; i++) { if(obstaculos[i] != null) { if(obstaculos[i].getX() == pos) obstaculo = true; } } return obstaculo; } public int getTamanioPista() { return this.tamanioPista; } public Vehiculo getConductor() { return this.conductor; } public boolean metaPista() { return conductor.getX()>=tamanioPista; } } <file_sep>/3EnRaya/src/Version_03/TresEnRaya.java package Version_03; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Graphics; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JPanel; import javax.swing.JFrame; import javax.swing.JOptionPane; public class TresEnRaya extends Canvas{ //Creamos la ventana JFrame ventana = new JFrame("3 en raya"); //Alto y ancho de la ventana private static final int JFRAME_WIDTH=700; private static final int JFRAME_HEIGHT=700; //Constructor public TresEnRaya() { //Creamos el JPanel haciendo un recast del contenido de nuestra ventana JPanel panel = (JPanel) ventana.getContentPane(); //Le establecemos el layout al panel y lo aรฑadimos panel.setLayout(new BorderLayout()); panel.add(this, BorderLayout.CENTER); //Dimensiรณn de la ventana y mostrarla ventana.setBounds(0,0,JFRAME_WIDTH,JFRAME_HEIGHT); ventana.setVisible(true); //Eliminamos el cierre normal de la ventana y personalizamos la posibilidad de cerrar la ventana ventana.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { cerrarAplicacion(); } }); //Cambiamos el foco al canvas this.requestFocus(); } private void cerrarAplicacion() { String[] opciones = {"Aceptar","Cancelar"}; //Creamos las opciones de salir de la aplicaciรณn int eleccion = JOptionPane.showOptionDialog(ventana, "ยฟSalir de la aplicaciรณn?","Salir", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, opciones, "Aceptar"); //Si el usuario desea salir lo cerramos if(eleccion == JOptionPane.YES_OPTION) { System.exit(0); } } //Modificamos el mรฉtodo paint de canvas @Override public void paint(Graphics g) { super.paint(g); //Pintamos un rectรกngulo blanco g.setColor(Color.WHITE); g.fillRect(0, 0, this.getWidth(), this.getHeight()); } //Mรฉtodo main public static void main(String[] args) { TresEnRaya tres = new TresEnRaya(); } } <file_sep>/Formula1/src/Version_1/Moto.java package Version_1; import java.awt.Color; import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; public class Moto extends Vehiculo{ public Moto() { super(); } public Moto(int x, int y) { super(x,y); } public void paint(JPanel frame) { frame.add(new Cuadrado()); } } <file_sep>/Formula1/src/Version_1/Mancha.java package Version_1; public class Mancha extends Obstaculo{ public Mancha(int x, int tamanio) { super(x,tamanio,2); } public void paint() { } } <file_sep>/Formula1/src/Version_1/Obstaculo.java package Version_1; public abstract class Obstaculo{ private int x; private int tamanio; private int reduccionDeVelocidad; public Obstaculo(int x,int tamanio, int reduccionDeVelocidad){ this.x = x; this.tamanio = tamanio; this.reduccionDeVelocidad = reduccionDeVelocidad; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getTamanio() { return tamanio; } public void setTamanio(int tamanio) { this.tamanio = tamanio; } public int getReduccionDeVelocidad() { return reduccionDeVelocidad; } public void setReduccionDeVelocidad(int reduccionDeVelocidad) { this.reduccionDeVelocidad = reduccionDeVelocidad; } public abstract void paint(); }
6602a3bef447c0bcc0eeaa4007dfb70e0de49c7c
[ "Java" ]
6
Java
AntonioJesPG/JuegosProgramacion
0aaaba57389f7794441abe9fe0bb39cfe78cf742
faae6b2ec86ea4fa47bb7f07548df7ce0d8ce317
refs/heads/main
<file_sep>๏ปฟusing System; namespace SnakeAndLadderSimulator { class Program { static void Main(string[] args) { int player1Position = 0; int player2Position = 0; SnakeAndLadder Game = new SnakeAndLadder(); while (player1Position != 100 && player2Position != 100) //While Loop Until AnyOne Player Reaches 100 { for (int chance=1; chance <= 2; chance++) // This For Loop Gives the Chance To Each Player One By One { if (chance == 1) //Player1 Gets his Turn { player1Position = Game.Player1(); // Player1 Will Use his Turn } else if (chance == 2) //Player2 Gets his Turn { player2Position = Game.Player2(); // Player2 Will Use his Turn } } } Console.WriteLine("Player 1 Position: " + player1Position); Console.WriteLine("Player 2 Position: " + player2Position); // RePorts, Who Won the Game if (player1Position > player2Position) Console.WriteLine("**Player 1 Won this Game**"); if (player2Position > player1Position) Console.WriteLine("**Player 2 Won this Game**"); } } } <file_sep>๏ปฟusing System; using System.Collections.Generic; using System.Text; namespace SnakeAndLadderSimulator { class SnakeAndLadder { //Variables int position1 = 0; int position2 = 0; //Constants const int LADDER = 1; const int SNAKE = 2; const int NOPLAY = 0; const int MAXPOSITION = 100; const int MINPOSITION = 0; Random random = new Random(); /// <summary> /// Rolldie() Method is Defined To Use, Whenever Needs to Roll The Dice /// </summary> public int Rolldie() { int die = random.Next(1, 7); return die; } /// <summary> /// Player1 Method is Defined, to Give Chance to player 1 When gets his Turn.. /// </summary> public int Player1() { int option = random.Next(0, 3); int dice = Rolldie(); switch (option) { case LADDER: position1 += dice; int extraDice1 = Rolldie(); //When Player climbed Ladder, He will get Extra Chance position1 += extraDice1; break; case SNAKE: position1 -= dice; if (position1 < MINPOSITION) position1 = MINPOSITION; //When Player Bite by Snake and If he Lost his Position Below Zero, He will Restart the Game From 0 break; case NOPLAY: position1 += 0; //If Noplay, He Doesn't Move Forward or Backward break; } if (position1 > MAXPOSITION) position1 -= dice; //If Player Moves Above MaxPosition 100, He will Return Back to Previous Position return position1; } /// <summary> /// Player2 Method is Defined, to Give Chance to player 2 When gets his Turn.. /// </summary> public int Player2() { int option = random.Next(0, 3); int dice = Rolldie(); switch (option) { case LADDER: position2 += dice; int extraDice2 = Rolldie(); //When Player climbed Ladder, He will get Extra Chance position2 += extraDice2; break; case SNAKE: position2 -= dice; if (position2 < MINPOSITION) //When Player Bite by Snake and If he Lost his Position Below Zero, He will Restart the Game From 0 position2 = MINPOSITION; break; case NOPLAY: position2 += 0; //If Noplay, He Doesn't Move Forward or Backward break; } if (position2 > MAXPOSITION) position2 -= dice; //If Player Moves Above MaxPosition 100, He will Return Back to Previous Position return position2; } } }
4da8c558129e1513dc2e05289935586501d5f80b
[ "C#" ]
2
C#
bharathmighty248/SnakeAndLadderSimulator
26f917921132130991166b7eeb92335a378a9c95
c4001a81ebe80a39d2be23aa9f2230d3e772e77d
refs/heads/master
<repo_name>MuriLOCO/AngularAssignments<file_sep>/assignment-three/src/app/display-details/display-details.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-display-details', templateUrl: './display-details.component.html', styleUrls: ['./display-details.component.css'] }) export class DisplayDetailsComponent implements OnInit { showDetails: boolean = false; constructor() { } ngOnInit() { } onShowDetails(){ this.showDetails = true; } }
40126619135b49d093423514ae044045a78663f5
[ "TypeScript" ]
1
TypeScript
MuriLOCO/AngularAssignments
6a0a5bcb021ef2c45bae7b0d0d62050bd8fd2ceb
38dcb13855f2655d678e0cac70cc9daa9e9d9c7d
refs/heads/master
<file_sep>import React from "react" export default () => <div>Hello world!df</div>
dc58535acf660f43397da96872135b88fd956774
[ "JavaScript" ]
1
JavaScript
RoadToCode822/gatsby-intro
88cbc23ae84dac7f28861980cf2a4bfad4c4649f
8783a15673bd1d88dd08102bb2b631334b7c7f67
refs/heads/master
<file_sep>package main import ( "go/format" "io" "log" "os" "github.com/cheekybits/genny/parse" ) func gennyGen(filename, pkgName string, typesets []map[string]string, out io.Writer) error { var output []byte var err error var file *os.File file, err = os.Open(filename) if err != nil { panic(err) } defer file.Close() output, err = parse.Generics(filename, "outputFilename.go", pkgName, "", file, typesets) if err != nil { return err } fmtOutput, err := format.Source([]byte(output)) if err != nil { log.Fatal(err) } out.Write(fmtOutput) return nil } <file_sep>package clefs import ( "reflect" "sort" "github.com/ikasamt/goslicer/typeslicer" ) type Anything struct { //generic.Type } //generic.Type type Anythings []Anything // First is .. func (anythings Anythings) First() (Anything, bool) { if len(anythings) == 0 { return Anything{}, false } return anythings[0], true } // Where is .. func (anythings Anythings) Where(f func(anything Anything) bool) (result Anythings) { for _, a := range anythings { if f(a) { result = append(result, a) } } return } // Count is .. func (anythings Anythings) Count() (counter int) { return len(anythings) } // CountIf is .. func (anythings Anythings) CountIf(f func(anything Anything) bool) (counter int) { for _, a := range anythings { if f(a) { counter++ } } return } // Select is .. func (anythings Anythings) Select(fieldName string) (result typeslicer.InterfaceSlice) { for _, a := range anythings { i := reflect.ValueOf(a).FieldByName(fieldName).Interface() result = append(result, i) } return } // SortBy is .. func (anythings Anythings) SortBy(sortFunc func(Anything, Anything) bool) (result Anythings) { f := func(i, j int) bool { a := anythings[i] b := anythings[j] return sortFunc(a, b) } tmp := make(Anythings, len(anythings)) copy(tmp, anythings) sort.Slice(tmp, f) return tmp } // DistinctBy is .. func (anythings Anythings) DistinctBy(f func(anything Anything) interface{}) (result Anythings) { tmp := map[interface{}]Anything{} for _, a := range anythings { tmp[f(a)] = a } for _, t := range tmp { result = append(result, t) } return } func (anythings Anythings) Mapper(f func(anything Anything) Anything) (result Anythings) { for _, a := range anythings { result = append(result, f(a)) } return } <file_sep>package example type Something struct { //generic.Type ID int //generic.Type } //generic.Type func (any Anything) WhySomething(ID int, some Something) bool { return any.ID == some.ID } <file_sep>module github.com/ikasamt/zapp-jam go 1.14 require ( github.com/cheekybits/genny v1.0.0 github.com/ikasamt/goslicer v1.0.4 // indirect golang.org/x/mod v0.3.0 // indirect golang.org/x/tools v0.0.0-20200618155944-c7475b9d7fb2 // indirect ) <file_sep>package app // +jam /clefs/example/is.go // +jam /clefs/example/some.go User Item // +jam ValidatePresenceOf Name // +jam Setter Name type Company struct { ID int Name string } // +jam /clefs/example/is.go // +jam /clefs/example/diff.go // +jam ValidatePresenceOf Name,CompanyID type Item struct { ID int Name string CompanyID int } <file_sep>package main import ( "bytes" "go/build" "go/format" "strings" // "bytes" "flag" "fmt" "log" "os" "path/filepath" ) const ( exitCode = 0 prefixAutoGen = "zzz-" buildTag = `+jam` validationSep = `,` ) var GoPath string var ZappJamSrcRoot string const SemanticVersion = `v0.6.8` func init() { GoPath = os.Getenv("GOPATH") if GoPath == "" { GoPath = build.Default.GOPATH } ZappJamSrcRoot = filepath.Join(GoPath, `/pkg/mod/github.com/ikasamt/zapp-jam@`+SemanticVersion) log.Println(ZappJamSrcRoot) } var parseFlags = func() []string { flag.Parse() return flag.Args() } func jamMain() { packagePaths := parseFlags() if len(packagePaths) == 0 { return } packagePath := packagePaths[0] packageName, task, validations := ParseDir(packagePath) log.Println(task) log.Println(fmt.Sprintf("# %s", packageName)) for inFn, typesets := range task { _, fn := filepath.Split(inFn) outFn := filepath.Join(packagePath, fmt.Sprintf("%s%s", prefixAutoGen, fn)) log.Println(fmt.Sprintf("%s -> %s", inFn, outFn)) out, err := os.Create(outFn) defer out.Close() if err != nil { log.Println(err) return } gennyGen(inFn, packageName, typesets, out) } if len(validations) != 0 { for funcName, validation := range validations { switch funcName { case `Ngram`: var buf bytes.Buffer buf.WriteString("package " + packageName) buf.WriteString("\n\n// Auto-generated DO NOT EDIT!") buf.WriteString("\n") buf.WriteString("\n\nimport (") buf.WriteString("\"github.com/ikasamt/zapp/zapp\"") buf.WriteString("\n)") buf.WriteString("\n") buf.WriteString("\n") for _, value := range validation { for structName, fieldsStr := range value { fields := strings.Split(fieldsStr, validationSep) buf.WriteString("\n") fmt.Fprintf(&buf, "\nfunc (x %s) Ngrams() []string {", structName) fmt.Fprintf(&buf, "\nngrams := []string{}") for _, v := range fields { fmt.Fprintf(&buf, "\nngrams = append(ngrams, zapp.SplitNgramsRange(x.%s, 3)...)", v) } fmt.Fprintf(&buf, "\nreturn ngrams}") buf.WriteString("\n") } } buf.WriteString("\n") formatted, err := format.Source(buf.Bytes()) if err != nil { log.Printf("%v", err) log.Printf("%s", buf.Bytes()) } file := filepath.Join(packagePath, fmt.Sprintf("%s%s", prefixAutoGen, `ngram.go`)) fh, err := os.Create(file) if err != nil { log.Printf(`failed to open file %s for writing`, file) } defer fh.Close() fh.Write(formatted) case `ValidatePresenceOf`: var buf bytes.Buffer buf.WriteString("package " + packageName) buf.WriteString("\n\n// Auto-generated DO NOT EDIT!") buf.WriteString("\n") buf.WriteString("\n\nimport (") buf.WriteString(" validation \"github.com/go-ozzo/ozzo-validation\"") buf.WriteString("\n)") buf.WriteString("\n") buf.WriteString("\n") for _, value := range validation { for structName, fieldsStr := range value { fields := strings.Split(fieldsStr, validationSep) buf.WriteString("\n") fmt.Fprintf(&buf, "\nfunc (x %s) Validations() error {", structName) fmt.Fprintf(&buf, "\nreturn validation.ValidateStruct(&x,") for _, v := range fields { fmt.Fprintf(&buf, "\nvalidation.Field(&x.%s, validation.Required),", v) } fmt.Fprintf(&buf, "\n)") fmt.Fprintf(&buf, "\n}") buf.WriteString("\n") } } buf.WriteString("\n") formatted, err := format.Source(buf.Bytes()) if err != nil { log.Printf("%s", buf.Bytes()) } file := filepath.Join(packagePath, fmt.Sprintf("%s%s", prefixAutoGen, `validate-presence-of.go`)) fh, err := os.Create(file) if err != nil { log.Printf(`failed to open file %s for writing`, file) } defer fh.Close() fh.Write(formatted) } } } } func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) jamMain() os.Exit(exitCode) } <file_sep>package app // +jam /clefs/example/is.go // +jam ValidatePresenceOf Name,CompanyID // +jam Ngram Name,CompanyID type User struct { ID int Name string CompanyID int } <file_sep>package main import ( "testing" ) func TestParseDir(t *testing.T) { pn, task, _ := ParseDir("./example/app") if pn != `app` { t.Fatalf("failed test %v", pn) } if task == nil { t.Fatalf("failed test %v", task) } } <file_sep>package example func (any Anything) Diff(ID int) bool{ return any.ID != ID } <file_sep>package main import ( "go/doc" "go/parser" "go/token" "log" "path/filepath" "strings" ) type Task map[string][]map[string]string type Validation map[string][]map[string]string func ParseDir(packagePath string) (packageName string, task Task, validation Validation) { task = Task{} validation = Validation{} fset := token.NewFileSet() d, err := parser.ParseDir(fset, packagePath, nil, parser.ParseComments) if err != nil { log.Println(err) return } for pn, f := range d { packageName = pn p := doc.New(f, "./", 0) for _, t := range p.Types { doc := t.Doc structName := t.Name lines := strings.Split(doc, "\n") for _, line := range lines { if strings.Contains(line, buildTag) { tmp := strings.Fields(line) switch len(tmp) { case 1: continue // needs filename case 2: filename := tmp[1] if strings.HasPrefix(filename, `/clefs/`) { filename = filepath.Join(ZappJamSrcRoot, filename) } else { filename = filepath.Join(packagePath, filename) } task[filename] = append(task[filename], map[string]string{`Anything`: structName}) default: if strings.Contains(tmp[1], `.go`) { filename := tmp[1] if strings.HasPrefix(filename, `/clefs/`) { filename = filepath.Join(ZappJamSrcRoot, filename) } else { filename = filepath.Join(packagePath, filename) } args := tmp[2:] for _, arg := range args { task[filename] = append(task[filename], map[string]string{`Anything`: structName, `Something`: arg}) } } else { key := tmp[1] validation[key] = append(validation[key], map[string]string{structName: tmp[2]}) } } } } } } return } <file_sep>module github.com/ikasamt/zapp-jam/example/app go 1.14 require ( github.com/cheekybits/genny v1.0.0 // indirect github.com/ikasamt/zapp-jam v0.6.1 // indirect golang.org/x/mod v0.3.0 // indirect golang.org/x/tools v0.0.0-20200618031402-d15173dcc7e4 // indirect ) <file_sep> build: go build clean: rm -rf example/app/zzz-* example: build clean ./zapp-jam example/app<file_sep>package example // Anything is defined as base Struct for genny type Anything struct { //generic.Type ID int //generic.Type } //generic.Type func (any Anything) Is(ID int) bool{ return any.ID == ID }
e63f5ab481d477cffdf9377263e5835341c801b3
[ "Makefile", "Go Module", "Go" ]
13
Go
ikasamt/zapp-jam
ab281fc43810c86271decab4fc6da70bf1e83d09
5068e89a94e8c02921945f71efcf83443b4962c5
refs/heads/master
<repo_name>TrungSpy/tomoscan<file_sep>/server/src/api/SignMessageController.js import { Router } from 'express' import db from '../models' import Web3Util from '../helpers/web3' const SignMessageController = Router() SignMessageController.post('/verifySignedMess', async (req, res, next) => { try { let web3 = await Web3Util.getWeb3() const signedMessage = req.body.message || '' const signature = req.body.signature || '' const hash = req.body.hash || '' let acc = await db.Account.findOne({ hash: hash }) if (!acc) { return res.status(404).send() } let result = await web3.eth.accounts.recover(signedMessage, signature) if (acc.contractCreation === result.toLowerCase()) { res.send('OK') } else { res.send({ error: { message: 'Not match' } }) } } catch (e) { console.trace(e) console.log(e) return res.status(500).send() } }) export default SignMessageController
89d523987bb9298cbd20f6a6e7eb300f1d1bfabb
[ "JavaScript" ]
1
JavaScript
TrungSpy/tomoscan
e9a97e2adbf85945fb35abfececb8e676fe42df3
30c537b7b61787b94094792a5466bb6a03437aa6
refs/heads/master
<file_sep>from django.urls import path from . import views app_name = 'kakeibo' urlpatterns = [ path('kakeibo_list/', views.KakeiboListView.as_view(), name='kakeibo_list'), path('kakeibo_create/',views.KakeiboCreateView.as_view(),name='kakeibo_create'), path('create_done/',views.create_done,name='create_done'), path('update/<int:pk>',views.KakeiboUpdateView.as_view(),name='kakeibo_update'), path('update_done/',views.update_done,name='update_done'), path('delete/<int:pk>/',views.KakeiboDeleteViews.as_view(),name='kakeibo_delete'), path('dekete_done/',views.delete_done,name='delete_done'), path('circle/',views.show_circle_grahp,name='kakeibo_circle'), path('line/',views.show_line_grahp,name='kakeibo_line'), ]
651ad3fd23772f3054bb87a07a88b99e7f12f1be
[ "Python" ]
1
Python
mr110825/kakeibo
fb2658baa81005937b447f1b962d84467a8e1369
f66a4758eaeaa90d3159e9af98f141384a0cdbff
refs/heads/main
<file_sep>#! /usr/bin/python3.8 from PyDictionary import PyDictionary switch = True def Translate(query,targetLangCode): return dictionary1.translate(query, targetLangCode) while switch: query = input("[+]Enter the word you wish to learn about, peasant(Enter 'q' to quit,'-t' for translation services): ") #EXIT_CONDITION if(query=='q'or query=='Q'): break dictionary1 = PyDictionary() #TRANSLATION if(query=='-t'): query = input("[+]Enter the sentence to translate: ") langCode = input("[+]Enter the lang code: ") l = query.split() for w in l: print(Translate(w,langCode)) #MEANING NOUN meaning = dictionary1.meaning(query) if 'Noun' in meaning: meaning_noun = meaning['Noun'] print("|||NOUN|||: ") for s in meaning_noun: print(s) print("_"*128) print("*"*128) print('*'*128) #MEANING_VERB if 'Verb' in meaning: meaning_verb = meaning['Verb'] print("|||VERB|||: ") for s in meaning_verb: print(s) print("_"*128) print('*'*128) print('*'*128) #MEANING_ADJECTIVE if 'Adjective' in meaning: meaning_adjective = meaning['Adjective'] print("|||ADJECTIVE|||: ") for s in meaning_adjective: print(s) print("_"*128) print("*"*128) print("*"*128) #SYNONYM synonym = dictionary1.synonym(query) print("|||SYNONYMS|||: ") for s in synonym: print(s) print('_'*128) print("*"*128) print('*'*128) #ANTONYM antonyms = dictionary1.antonym(query) print("|||ANTONYMS|||: ") for s in antonyms: print(s) print('_'*128) print('*'*128) print('*'*128) <file_sep># Dictionary A virtual dictionary application made in Python <h3>Usage<h3> <ul> <li><h5>Open your terminal and navigate to the directory in which the file has been downloaded</h5></li> <li><h5>run the file with Python3</h5></li> <li><h5>Follow the instructions</h5></li> </ul> <hr>
e0fcc221a08212c47aa2ab1039617385615c4747
[ "Markdown", "Python" ]
2
Python
NoctemLeges/Dictionary
1533b4c5d1b97345f5c8a68cbbac72761d466a2a
f4d4a6794d76e440c0153aaf4a2478268ebae235
refs/heads/master
<repo_name>ZivanovicLuka/FourierTransformationVisualization<file_sep>/README.md <h1 align="center">Fourier Transformation Visualisation</h1> <p align="center"> <img src="public/images/splash.png?raw=true" alt="Workflow Screen Shot 1" width="500"> </p> <div align="center"> <sub>Built with ReactJS and PixiJS by <a href="https://github.com/ZivanovicLuka">Luka</a> </a> for Scientific Computing course @<a href="http://www.math.rs/eng/">MATF</a> </div> ## Table of Contents - [Installation](#installation) - [Running](#running) - [Workflow](#workflow) ## Installation Install NodeJS from https://nodejs.org/en/download/ ```sh $ git clone https://github.com/ZivanovicLuka/FourierTransformationVisualization $ cd FourierTransformationVisualization $ npm i ``` ## Running In the project directory, you can run: ### `npm start` Runs the app in the development mode.<br> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br> You will also see any lint errors in the console. ### `npm run build` Builds the app for production to the `build` folder.<br> It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.<br> Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you canโ€™t go back!** If you arenโ€™t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youโ€™re on your own. You donโ€™t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnโ€™t feel obligated to use this feature. However we understand that this tool wouldnโ€™t be useful if you couldnโ€™t customize it when you are ready for it. ## Workflow <p align="center"> Click on Choose File:<br> <img src="public/images/1.png?raw=true" alt="Workflow Screen Shot 1" width="500"> <br>Choose File:<br> <img src="public/images/2.png?raw=true" alt="Workflow Screen Shot 2" width="500"> <br>Convert loaded file:<br> <img src="public/images/3.png?raw=true" alt="Workflow Screen Shot 3" width="500"> <br>Adjust duration:<br> <img src="public/images/4.png?raw=true" alt="Workflow Screen Shot 4" width="500"> <br>Click play:<br> <img src="public/images/5.png?raw=true" alt="Workflow Screen Shot 5" width="500"> <br>Enjoy :)<br> <img src="public/images/6.png?raw=true" alt="Workflow Screen Shot 6" width="500"> </p><file_sep>/src/App.js import React, { Component } from "react"; import "./App.css"; import Loader from "./components/Loader"; import Controls from "./components/Controls"; import MainGraph from "./components/MainGraph"; class App extends Component { constructor(props) { super(props); this.state = { songData: [], songLength: 0, isPlaying: false, speed:0 }; } onUploaded = (songData, songLength) => { this.setState({songData, songLength}); } rangeChange = (start, end) => { this.setState({start:start, end:end}); } speedChange = (speed) => { this.setState({speed:speed}); } onPlay = () => { this.setState({isPlaying:!this.state.isPlaying}); } render() { return ( <div className="App"> <Loader onUploaded={this.onUploaded} rangeChange={this.rangeChange} ></Loader> <MainGraph songData={this.state.songData} songLength={this.state.songLength} isPlaying={this.state.isPlaying} start={this.state.start} end={this.state.end} speed={this.state.speed} > </MainGraph> <Controls onPlay={this.onPlay} speedChange={this.speedChange}> </Controls> </div> ); } } export default App; <file_sep>/src/components/MainGraph.js import React, { Component } from "react"; import * as PIXI from "pixi.js"; class MainGraph extends Component { constructor(props) { super(props); this.pixi_cnt = null; this.app = new PIXI.Application({ transparent: false, antialias: true, }); this.graphics = new PIXI.Graphics(); this.canvasMargin = 100; this.canvasPadding = 20; this.topSectionHeight = 50; this.botSectionHeight = 50; this.sectionGap = 20; this.coordinateSystemExtra = 30; this.f = 0; this.data = this.props.songData; this.length = this.props.songLength; this.oscilationNumber = 0; this.oscilationProgress = 0; this.transformedData = []; this.renderText = []; } // TODO 10000 - parameter reduceDataAverage(data, num=10000) { let n = data.length; if(n<num) return data; let step = Math.ceil(n/num); let ret = []; let curr = 0; for(let i=0; i<n; i++){ curr+=data[i]; if(i%step === 0){ ret.push(curr/step); curr=0; } } return ret; } initData() { if(this.props.start === undefined || this.props.end === undefined) return; if(this.props.isPlaying !== true) return; this.data = this.props.songData.slice(this.props.start,this.props.end); this.data = this.reduceDataAverage(this.data); this.length = this.props.songLength; let min = Math.min.apply(Math,this.data); this.data = this.data.map(point => point-min); let max = Math.max.apply(Math,this.data); this.data = this.data.map(point => point/max); this.app.ticker.add(delta => this.gameLoop(delta)); } componentDidUpdate() { this.initData(); } setup = () => { this.app.stage.position.x = this.canvasPadding; this.app.stage.scale.x = (this.app.renderer.width-2*this.canvasPadding)/this.app.renderer.width; this.app.stage.position.y = this.app.renderer.height / this.app.renderer.resolution; this.app.stage.scale.y = this.app.stage.scale.y = -(this.app.renderer.height-2*this.canvasPadding)/this.app.renderer.height; }; // e^ix = cosx + i*sinx eulerFormula = x => { return [Math.cos(x), Math.sin(x)]; } convertToCircle = ({data, f = .01, radius = 100, center={x:0, y:0}}) => { let t=0; let transformed = []; for (const point of data) { let newPoint = this.eulerFormula(-Math.PI*2*t); newPoint[0] = newPoint[0] * radius * point + center.x; newPoint[1] = newPoint[1] * radius * point + center.y; transformed.push(newPoint); t+=f; } if(t>this.oscilationNumber){ this.oscilationNumber++; } this.oscilationProgress = this.oscilationNumber-t; return transformed; } drawCoordinateSystem = ({center, top, left, width, height, steps=2, color=0x9999ff, x_min=0, x_max=0, showTicks=false, ticksTop=false, showText=false, scaledTicks=false, formula=(v=>v)}) => { let tickHeight=30; this.graphics.lineStyle(1, color); // Draw X axis this.graphics.moveTo(left - this.coordinateSystemExtra, center.y); this.graphics.lineTo(left + width + this.coordinateSystemExtra, center.y); this.graphics.endFill(); // Draw Y axis this.graphics.moveTo(center.x, top + this.coordinateSystemExtra); this.graphics.lineTo(center.x, top - height - this.coordinateSystemExtra); this.graphics.endFill(); // Draw Ticks if(showTicks){ let gap = {length:width/steps, value:(x_max-x_min)/steps}; if(scaledTicks) { gap.length = (gap.length*(steps) + gap.length*this.oscilationProgress)/(steps+1); } for(let i=0; i<=steps; i++){ this.graphics.moveTo(left + i*gap.length, center.y - tickHeight/2); this.graphics.lineTo(left + i*gap.length, center.y + tickHeight/2); this.graphics.endFill(); if(showText){ let val = (x_min + i*gap.value); var valText = new PIXI.Text((steps<=10 || i%Math.ceil(steps/10)===0)?formula(val).toFixed(2):``, { fill: color, fontFamily: `Courier New`, fontWeight: `lighter`, fontSize: tickHeight/2, }); // Position the text valText.x = left + i*gap.length - (i===steps ? tickHeight : 0); if(ticksTop) valText.y = top + this.coordinateSystemExtra; else valText.y = center.y - tickHeight/2; valText.scale.y = -1; this.renderText.push(valText); } } } } drawSignalSection = ({data, center}) => { this.drawCoordinateSystem({ center: {x:0, y:center.y}, top:this.app.renderer.height, left:0, width: this.app.renderer.width, height: this.topSectionHeight, showTicks: true, showText: true, x_max: this.length, steps: 10 }); let signalTop = this.app.render.height - center.y + this.topSectionHeight; this.drawSignal({data, center, signalTop}); } drawSignal = ({data, center, color=0xffff00, top=20}) => { this.graphics.lineStyle(2, color); this.graphics.moveTo(0+center.x, data[0]+center.y); let step = this.app.renderer.width / this.app.renderer.resolution / data.length; let max = Math.max(...data); data.forEach(function(point, i) { this.graphics.lineTo(i*step + center.x, point*top/max*2 + center.y ); }.bind(this)); } drawTransformedSignalSection = ({data, center, color=0xffffff}) => { this.drawCoordinateSystem({ center: {x:0, y:center.y}, top:this.topSectionHeight, left:0, width: this.app.renderer.width, height: this.topSectionHeight, }); this.drawTransformedSignal({data, center, color}); } drawTransformedSignal = ({data, center, color=0xffffff}) => { if(data.length < 2) return; this.graphics.lineStyle(2, color); this.graphics.moveTo(0+center.x, data[0]+center.y); let step = this.app.renderer.width / this.app.renderer.resolution / data.length; data.forEach(function(point, i) { this.graphics.lineTo(i*step + center.x, point + center.y ); }.bind(this)); } drawIntegral(x, y, color = 0xff5555, width = 3, radius = 5){ this.graphics.lineStyle(radius, color); this.graphics.drawCircle(x, y, width); } drawTransformation = ({data, center, radius}) => { data = this.convertToCircle({data, center, f:this.f, radius }); let integral = {x:0, y:0}; this.graphics.moveTo(data[0][0], data[0][1]); data.forEach(function(point, i) { this.graphics.lineStyle(2, 0xffffff, i/data.length); this.graphics.lineTo(point[0], point[1] ); integral.x += point[0]; integral.y += point[1]; }.bind(this)); integral.x /= data.length; integral.y /= data.length; this.drawIntegral(integral.x, integral.y); let scaleFix = this.botSectionHeight/radius; this.transformedData.push((integral.x - center.x)*scaleFix); this.graphics.endFill(); } drawTransformationSection = ({data}) => { let center = {x:this.app.renderer.width/2,y:this.app.renderer.height/2}; let radius = Math.min(this.canvasWidth/2, this.canvasHeight/2 - this.topSectionHeight - this.botSectionHeight) - this.sectionGap; let top = center.y + radius; let left = center.x - radius; this.drawCoordinateSystem({ center, top, left, width: 2*radius, height: 2*radius }); this.drawTransformation({data, center, radius}); } gameLoop(delta){ if(!this.props.isPlaying) return; this.renderText = []; this.app.stage.removeChildren(); let data = this.data; this.graphics.clear(); this.drawSignalSection({ data, center:{x:0, y:this.app.renderer.height- this.topSectionHeight }, }); this.drawTransformationSection({data}); this.drawTransformedSignalSection({ data: this.transformedData, center:{x:0,y:this.botSectionHeight/2}, color: 0xff5555 }); this.app.stage.addChild(this.graphics); this.renderText.forEach( t => this.app.stage.addChild(t) ); this.f+=this.props.speed*delta; } updatePixiCnt = element => { this.pixi_cnt = element; if (this.pixi_cnt && this.pixi_cnt.children.length <= 0) { this.canvasWidth = element.offsetWidth - this.canvasMargin; this.canvasHeight=element.offsetHeight - this.canvasMargin; this.app.renderer.resize(this.canvasWidth, this.canvasHeight); this.pixi_cnt.appendChild(this.app.view); this.setup(); } }; render() { return <div id="canvas" ref={this.updatePixiCnt} />; } } export default MainGraph;
f086cdd904c4a9b289716435acfb67e0bf72e165
[ "Markdown", "JavaScript" ]
3
Markdown
ZivanovicLuka/FourierTransformationVisualization
7af3aad0ffc179b82cf15af3e02962b10043b3bf
b3b7e3c2af738ba92817cbaf41b7eace1c1a67b0
refs/heads/master
<repo_name>hrasof/Course3GetCleanData_Ass_RunAnalysis<file_sep>/README.MD HOW I CREATED the README.MD? - Create a new "R Markdown" in RStudio - Fill in the File and Save it in the Working Directory - Using Git Bash, 1) go to Working Dir using cd XXX (Important Step) 2) git Add -A, git commit -m "myMessage", git Push - Check the GitHub (Remote Directory) --> It should show two files (Run_Analysis & README.MD) ======================================================== #This is an R Markdown document. Markdown is a simple formatting syntax for authoring web pages (click the **Help** toolbar button for more details on using R Markdown). #When you click the **Knit HTML** button a web page will be generated that includes both content as well as #the output of any embedded R code chunks within the document. You can embed an R code chunk like this: ```{r} Init <- function(workDirStr = "C:/Users/hsofoian/Desktop/DataScience/Course 3 - Getting and Cleaning data/Course3_PeerAss_RunAnalysis"){ setwd(workDirStr) } Init() ################################################################################################## # 1. Merges the training and the test sets to create one data set. xtrain <- read.table("train/X_train.txt") xtest <- read.table("test/X_test.txt") xtt <- rbind(xtrain, xtest) ## 561 Columns, 10299 rows ----> to be used with features.txt ytrain <- read.table("train/y_train.txt") ytest <- read.table("test/y_test.txt") ytt <- rbind(ytrain, ytest) ### 1 column, 10299 rows (1s,2s ... 6s) ----> to be used with activity_labels.txt strain <- read.table("train/subject_train.txt") stest <- read.table("test/subject_test.txt") stt <- rbind(strain, stest) ### 1 column, 10299 rows (incl 1s,2s ... 6s) ################################################################################################## # 2. Extracts only the measurements on the mean and standard deviation for each measurement. ## mean(): Mean value std(): Standard deviation features <- read.table("features.txt") ## 2 cols , 561 rows indices_of_good_features <- grep("-mean\\(\\)|-std\\(\\)", features[, 2]) # Returns indices of mean&SD from featurees[,V2] # Example [1] 1 2 3 4 5 6 41 42 43 44 ...[66] xtt <- xtt[, indices_of_good_features] ## select from X(Trani/Test) using indices related to mean/SD names(xtt) <- features[indices_of_good_features, 2] names(xtt) <- gsub("\\(|\\)", "", names(xtt)) ## replace "()" by empty using gsub names(xtt) <- tolower(names(xtt)) # Result of names(xtt): [1] "tbodyacc-mean-x" [2] "tbodyacc-mean-y" [3] "tbodyacc-mean-z" # [4] "tbodyacc-std-x" ..... [66] "fbodybodygyrojerkmag-std" # Result of xtt[1:2,1:2]: ## tbodyacc-mean-x tbodyacc-mean-y ## 1 0.2885845 -0.02029417 ## 2 0.2784188 -0.01641057 ################################################################################################## # 3. Uses descriptive activity names to name the activities in the data set activities <- read.table("activity_labels.txt") ## activities ## V1 V2 ## 1 1 WALKING ## 2 2 WALKING_UPSTAIRS ## 3 3 WALKING_DOWNSTAIRS ## 4 4 SITTING ## 5 5 STANDING ## 6 6 LAYING activities[, 2] = gsub("_", "", tolower(as.character(activities[, 2]))) ## V1 V2 ## 1 1 walking ## 2 2 walkingupstairs ## 3 3 walkingdownstairs ## 4 4 sitting ## 5 5 standing ## 6 6 laying ytt[,1] = activities[ytt[,1], 2] names(ytt) <- "activity" ## y[1:5,] ## [1] "standing" "standing" "standing" ## [4] "standing" "standing" ....... ################################################################################################## # 4. Appropriately labels the data set with descriptive activity names. names(stt) <- "subject" cleaned <- cbind(stt, ytt, xtt) write.table(cleaned, "Tidy1_mergedandcleandata.txt") ## ## 68 Columns, 10299 rows ## cleaned[1:3,1:5] ## subject activity tbodyacc-mean-x tbodyacc-mean-y tbodyacc-mean-z ## 1 1 standing 0.2885845 -0.02029417 -0.1329051 ## 2 1 standing 0.2784188 -0.01641057 -0.1235202 ## 3 1 standing 0.2796531 -0.01946716 -0.1134617 ################################################################################################## # 5. Creates a 2nd, independent tidy data set with the average of each variable for each activity and each subject. uniqueSubjects = unique(stt)[,1] ## [1] 1 3 5 ... [30] 24 numSubjects = length(unique(stt)[,1]) ## 30 numActivities = length(activities[,1]) ## 6 numCols = dim(cleaned)[2] ## 68 result = cleaned[1:(numSubjects*numActivities), ] ## 180 rows row = 1 for (stt in 1:numSubjects) { for (a in 1:numActivities) { result[row, 1] = uniqueSubjects[stt] result[row, 2] = activities[a, 2] tmp <- cleaned[cleaned$subject==stt & cleaned$activity==activities[a, 2], ] result[row, 3:numCols] <- colMeans(tmp[, 3:numCols]) row = row+1 } } write.table(result, "Tidy2_datasetwithaverages.txt") # row 180, col 68 ``` <file_sep>/run_analysis.R # Source of data for the project: # https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip Init <- function(workDirStr = "C:/Users/hsofoian/Desktop/DataScience/Course 3 - Getting and Cleaning data/Course3_PeerAss_RunAnalysis"){ setwd(workDirStr) } Init() ################################################################################################## # 1. Merges the training and the test sets to create one data set. xtrain <- read.table("train/X_train.txt") xtest <- read.table("test/X_test.txt") xtt <- rbind(xtrain, xtest) ## 561 Columns, 10299 rows ----> to be used with features.txt ytrain <- read.table("train/y_train.txt") ytest <- read.table("test/y_test.txt") ytt <- rbind(ytrain, ytest) ### 1 column, 10299 rows (1s,2s ... 6s) ----> to be used with activity_labels.txt strain <- read.table("train/subject_train.txt") stest <- read.table("test/subject_test.txt") stt <- rbind(strain, stest) ### 1 column, 10299 rows (incl 1s,2s ... 6s) ################################################################################################## # 2. Extracts only the measurements on the mean and standard deviation for each measurement. ## mean(): Mean value std(): Standard deviation features <- read.table("features.txt") ## 2 cols , 561 rows indices_of_good_features <- grep("-mean\\(\\)|-std\\(\\)", features[, 2]) # Returns indices of mean&SD from featurees[,V2] # Example [1] 1 2 3 4 5 6 41 42 43 44 ...[66] xtt <- xtt[, indices_of_good_features] ## select from X(Trani/Test) using indices related to mean/SD names(xtt) <- features[indices_of_good_features, 2] names(xtt) <- gsub("\\(|\\)", "", names(xtt)) ## replace "()" by empty using gsub names(xtt) <- tolower(names(xtt)) # Result of names(xtt): [1] "tbodyacc-mean-x" [2] "tbodyacc-mean-y" [3] "tbodyacc-mean-z" # [4] "tbodyacc-std-x" ..... [66] "fbodybodygyrojerkmag-std" # Result of xtt[1:2,1:2]: ## tbodyacc-mean-x tbodyacc-mean-y ## 1 0.2885845 -0.02029417 ## 2 0.2784188 -0.01641057 ################################################################################################## # 3. Uses descriptive activity names to name the activities in the data set activities <- read.table("activity_labels.txt") ## activities ## V1 V2 ## 1 1 WALKING ## 2 2 WALKING_UPSTAIRS ## 3 3 WALKING_DOWNSTAIRS ## 4 4 SITTING ## 5 5 STANDING ## 6 6 LAYING activities[, 2] = gsub("_", "", tolower(as.character(activities[, 2]))) ## V1 V2 ## 1 1 walking ## 2 2 walkingupstairs ## 3 3 walkingdownstairs ## 4 4 sitting ## 5 5 standing ## 6 6 laying ytt[,1] = activities[ytt[,1], 2] names(ytt) <- "activity" ## y[1:5,] ## [1] "standing" "standing" "standing" ## [4] "standing" "standing" ....... ################################################################################################## # 4. Appropriately labels the data set with descriptive activity names. names(stt) <- "subject" cleaned <- cbind(stt, ytt, xtt) write.table(cleaned, "Tidy1_mergedandcleandata.txt") ## ## 68 Columns, 10299 rows ## cleaned[1:3,1:5] ## subject activity tbodyacc-mean-x tbodyacc-mean-y tbodyacc-mean-z ## 1 1 standing 0.2885845 -0.02029417 -0.1329051 ## 2 1 standing 0.2784188 -0.01641057 -0.1235202 ## 3 1 standing 0.2796531 -0.01946716 -0.1134617 ################################################################################################## # 5. Creates a 2nd, independent tidy data set with the average of each variable for each activity and each subject. uniqueSubjects = unique(stt)[,1] ## [1] 1 3 5 ... [30] 24 numSubjects = length(unique(stt)[,1]) ## 30 numActivities = length(activities[,1]) ## 6 numCols = dim(cleaned)[2] ## 68 result = cleaned[1:(numSubjects*numActivities), ] ## 180 rows row = 1 for (stt in 1:numSubjects) { for (a in 1:numActivities) { result[row, 1] = uniqueSubjects[stt] result[row, 2] = activities[a, 2] tmp <- cleaned[cleaned$subject==stt & cleaned$activity==activities[a, 2], ] result[row, 3:numCols] <- colMeans(tmp[, 3:numCols]) row = row+1 } } write.table(result, "Tidy2_datasetwithaverages.txt") # row 180, col 68 ################################################################################################## # Helpful for README # write.table will create listofnames.md in the current working directory data(result) datanames <- names(result) outputlines <- paste("* ",datanames , sep="") write.table(outputlines,file="listofvariables.md", quote = FALSE, col.names=FALSE, row.names=FALSE)
81616f62d03503b883ce3deaf512e0ab241b9bb7
[ "Markdown", "R" ]
2
Markdown
hrasof/Course3GetCleanData_Ass_RunAnalysis
8d30ff5f5fd71c5909846599771212be9189a4a5
80b4276571b781d833b664f20eddf56791a7bc69
refs/heads/master
<file_sep>package providers import ( "fmt" "io" "io/ioutil" "log" "net/http" "net/url" "strings" "time" "golang.org/x/net/html" ) var header = map[string]string{ "Content-Type": "application/x-www-form-urlencoded", "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)", } var params = map[string]string{ "name": "", "search": "", "description": "", "file": "", "user": "", "cat": "404", //"subcat": "409", // mangas "subcat": "406", // BD "submit": "Recherche", "order": "added", "type": "desc", } var cookies = []http.Cookie{ {Name: "uid", Value: "7531997"}, {Name: "pass", Value: "<PASSWORD>"}, {Name: "authKey", Value: "<KEY>"}, } // Init the provider execution func Init(search string) *url.URL { params["name"] = search params["search"] = "@name " + search // Build URL var urlp *url.URL urlp, err := url.Parse("http://www.t411.in") if err != nil { panic("Unable to parse 'T411' provider URL") } urlp.Path += "/torrents/search/" // Add parameters parameters := url.Values{} for k, p := range params { parameters.Add(k, p) } urlp.RawQuery = parameters.Encode() fmt.Printf("Encoded URL is %q\n", urlp.String()) return urlp } // Search execute search to the provider func Search(urlp *url.URL) io.Reader { fmt.Printf("Execute %q\n", urlp.String()) // Create HTTP request client := http.Client{} request, err := http.NewRequest("GET", urlp.String(), nil) if err != nil { log.Fatal(err) } // Add headers for k, h := range header { request.Header.Add(k, h) } // Add Cookies for _, c := range cookies { request.AddCookie(&c) } // Execute request resp, err := client.Do(request) if err != nil { log.Fatal(err) } //defer resp.Body.Close() //fmt.Println("response Status:", resp.Status) //fmt.Println("response Headers:", resp.Header) return resp.Body } // ParseSearch body of the provider search request func ParseSearch(body io.Reader) *[]Result { var results = make([]Result, 0) doc, err := html.Parse(body) if err != nil { log.Fatal(err) } var f func(*html.Node) f = func(n *html.Node) { if n.Type == html.ElementNode && n.Data == "a" { var found = false var result = Result{} for _, a := range n.Attr { if a.Key == "href" && strings.Contains(a.Val, "www.t411.in/torrents") { result.DetailURL = a.Val found = true } if a.Key == "title" && found { result.Name = strings.TrimSpace(a.Val) results = append(results, result) } } } for c := n.FirstChild; c != nil; c = c.NextSibling { f(c) } } f(doc) return &results } // AnalyzeSearch make an string analysis to identify results func AnalyzeSearch(results []Result, typeSearch string, number int) []Result { var newResults = make([]Result, 0) for i := range results { result := &results[i] for _, analyzer := range Analyzers { analyzer.analyze(result) if (typeSearch == "volume" && result.IsVolume) || (typeSearch == "chapter" && result.IsChapter) { newResults = append(newResults, *result) } } } return newResults } // GetDetails execute search to get details func GetDetails(urlp *url.URL) io.Reader { fmt.Printf("Execute %q\n", urlp.String()) // Create HTTP request client := http.Client{} request, err := http.NewRequest("GET", urlp.String(), nil) if err != nil { log.Fatal(err) } // Add headers for k, h := range header { request.Header.Add(k, h) } // Add Cookies for _, c := range cookies { request.AddCookie(&c) } // Execute request resp, err := client.Do(request) if err != nil { log.Fatal(err) } //defer resp.Body.Close() //fmt.Println("response Status:", resp.Status) //fmt.Println("response Headers:", resp.Header) return resp.Body } // ParseDetails body of the provider search request func ParseDetails(body io.Reader) string { doc, err := html.Parse(body) if err != nil { log.Fatal(err) } var f func(*html.Node) string f = func(n *html.Node) string { if n.Type == html.ElementNode && n.Data == "a" { for _, a := range n.Attr { if a.Key == "href" && strings.Contains(a.Val, "/torrents/download/") { return a.Val } } } for c := n.FirstChild; c != nil; c = c.NextSibling { var val = f(c) if val != "" { return val } } return "" } return f(doc) } // DownloadTorrentFile execute search to get details func DownloadTorrentFile(urlp *url.URL, dest string) error { fmt.Printf("Download Torrent File %q\n", urlp.String()) // Create HTTP request timeout := time.Duration(5 * time.Second) client := http.Client{ Timeout: timeout, } request, err := http.NewRequest("GET", urlp.String(), nil) if err != nil { return err } // Add headers for k, h := range header { request.Header.Add(k, h) } // Add Cookies for _, c := range cookies { request.AddCookie(&c) } // Execute request resp, err := client.Do(request) if err != nil { return err } //fmt.Println("response Status:", resp.Status) //fmt.Println("response Headers:", resp.Header) var filename = resp.Header.Get("Content-Disposition") filename = strings.Replace(filename, "attachment; filename=", "", 1) filename = strings.Replace(filename, "\"", "", 2) defer resp.Body.Close() d, err := ioutil.ReadAll(resp.Body) if writeFile(dest+filename, d) == nil { fmt.Printf("saved %s as %s\n", urlp.String(), dest+filename) } return nil } func writeFile(dst string, d []byte) error { err := ioutil.WriteFile(dst, d, 0444) if err != nil { log.Fatal(err) } return err } <file_sep>package providers import "regexp" // Analyzers available analyzers var Analyzers = []Analyzer{ VolumeAnalyzer{}, } // Analyzer Analyzer interface type Analyzer interface { analyze(Analyzed *Result) *Result } // VolumeAnalyzer Analyze volumes type VolumeAnalyzer struct { } var volumesWords = "(Volume|Volumes|volume|volumes|Tome|Tomes|tome|tomes|TOME|TOMES|T[0-9]+|V[0-9]+|Vol[0-9]+|vol[0-9]+)" func (v VolumeAnalyzer) analyze(analyzed *Result) *Result { matchVolume, _ := regexp.MatchString(volumesWords, analyzed.Name) if matchVolume { analyzed.IsVolume = true re, _ := regexp.Compile(`([0-9]+)`) // want to know what is in front of 'at' res := re.FindAllStringSubmatch(analyzed.Name, -1) var elements = make([]string, 0) for _, r := range res { elements = append(elements, r[0]) } analyzed.RefNumbers = elements } else { analyzed.IsChapter = true re, _ := regexp.Compile(`([0-9]+)`) // want to know what is in front of 'at' res := re.FindAllStringSubmatch(analyzed.Name, -1) var elements = make([]string, 0) for _, r := range res { elements = append(elements, r[0]) } analyzed.RefNumbers = elements } return analyzed } <file_sep># gobookie GoBookie <file_sep>package main import ( "fmt" "regexp" ) func main() { re, _ := regexp.Compile(`(Volume|Tome|volume|tome|T[0-9]+|V[0-9]+|Vol[0-9]+|vol[0-9]+)`) r := re.FindStringSubmatch("[MFT] One Piece Scan T01-65 fr") fmt.Printf("%s\n", r) re, _ = regexp.Compile(`([0-9]+)`) // want to know what is in front of 'at' res := re.FindAllStringSubmatch("[MFT] One Piece Scan T01-T65 fr", -1) fmt.Printf("%v\n", res) matchVolume, _ := regexp.MatchString(`(Volume|Tome|volume|tome|T[0-9]+|V[0-9]+)`, "[MFT] One Piece Tome 01-65 fr") fmt.Println(matchVolume) // [MFT] One Piece Scan 740 fr } <file_sep>package providers import "fmt" // Providers available var Providers = map[string]Provider{ "T411": {"http://www.t411.io", "html"}, } // Provider contains informations and options about providers type Provider struct { URL string Type string } // Result of provider search type Result struct { Name string DetailURL string TorrentURL string IsVolume bool IsChapter bool RefNumbers []string IsMultifiles bool Format string } // Display display the result func (r *Result) Display() { fmt.Println(r.Name) if r.IsVolume { fmt.Printf(" - Volume : %v\n", r.RefNumbers) } else if r.IsChapter { fmt.Printf(" - Chapter : %v\n", r.RefNumbers) } fmt.Println(" - URL D : ", r.DetailURL) fmt.Println(" - URL T : ", r.TorrentURL) } // IsAvailableProvider provider func IsAvailableProvider(provider string) bool { _, exists := Providers[provider] return exists } // DisplayProvidersList liste all available providers in the output func DisplayProvidersList() { fmt.Println("Available providers are :") for k := range Providers { fmt.Printf("- %s \n", k) } } <file_sep>package main import ( "flag" "fmt" "net/url" p "github.com/bpetetot/bookie/providers" ) func main() { // Parsing command line arguments var provider = flag.String("provider", "t411", "Provider name") var search = flag.String("search", "", "Searched book or manga") var typeSearch = flag.String("type", "volume", "Set volume or chapter") var number = flag.Int("number", 1, "Volume or Chapter number") flag.Parse() if *provider == "" || *search == "" { flag.PrintDefaults() } // Search values into providers if p.IsAvailableProvider(*provider) { fmt.Printf("Search '%s' with '%s' provider. \n", *search, *provider) var urlp = p.Init(*search) var body = p.Search(urlp) var results = p.ParseSearch(body) var uResults = p.AnalyzeSearch(*results, *typeSearch, *number) for _, r := range uResults { // Get details urlp, err := url.Parse("http:" + r.DetailURL) if err != nil { panic("Unable to parse 'T411' provider URL") } body = p.GetDetails(urlp) r.TorrentURL = p.ParseDetails(body) r.Display() // Download torrent file urlp, err = url.Parse("http://www.t411.in" + r.TorrentURL) if err != nil { panic("Unable to parse 'T411' provider URL") } err = p.DownloadTorrentFile(urlp, "D:\\temp\\") if err != nil { fmt.Printf("Error downloading torrent %s\n", err) } } } else { fmt.Printf("Provider '%s' not found. \n", *provider) p.DisplayProvidersList() } }
24022da008cd7cb4da5f72a6a3961d3a783f0303
[ "Markdown", "Go" ]
6
Go
bpetetot/gobookie
83c0a5ecfbeada39cdd8d366b96d6ff532a20173
bf20665afe53aaef2e395802c0c4e9fd8ea7e627
refs/heads/master
<file_sep> #include <stdio.h> #include "hash_mapping_table.h" void test_mapping_table_1() { int result; result = has_common_character("ๅ›ฝ็Ž‹", "ๅ›ฝๅฎถ", 0); fprintf(stderr, "result = %d\n", result); result = has_common_character("ๅ›ฝ็Ž‹", "ๅ›ฝๅฎถ", 1); fprintf(stderr, "result = %d\n", result); } // void test_mapping_table_2() { // int result; // result = BinarySearchTable(sc2k, sc2k[sc2k_size - 1]->original, 0, sc2k_size - 1); // fprintf(stderr, "result = %d (%d)\n", result, sc2k_size - 1); // result = BinarySearchTable(k2sc, k2sc[k2sc_size - 1]->original, 0, k2sc_size - 1); // fprintf(stderr, "result = %d (%d)\n", result, k2sc_size - 1); // } // void test() { // test_mapping_table_1(0); // test_mapping_table_1(7); // test_mapping_table_1(77); // test_mapping_table_1(777); // test_mapping_table_1(5000); // test_mapping_table_2(); // } int main(int argc, char **argv) { load_mapping_tables(); fprintf(stderr, "Finish reading from file.\n"); // test(); test_mapping_table_1(); }<file_sep>// Tool to calculate word-word cooccurrence statistics for sentence aligned // corpus of 2 languages. // // Copyright (c) 2014 The Board of Trustees of // The Leland Stanford Junior University. All Rights Reserved. // // 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. // // // For more information, bug reports, fixes, contact: // <NAME> (<EMAIL>) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "bisearch_mapping_table.h" MAPTABREC **k2sc, **sc2k; /** * Compare 2 mapping table record, used in qsort function. * notice the type of a and b are (MAPTABREC **) */ int compare_original(const void *a, const void *b) { return strcmp((*(MAPTABREC **)a)->original, (*(MAPTABREC **)b)->original); } /** * Read one or several Kanji or Hanzi from text file */ int get_characters(char *word, FILE *fin) { int i = 0, ch; while (!feof(fin)) { ch = fgetc(fin); if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { break; } word[i++] = ch; } word[i] = 0; return i; } /** * Read mapping table from file, and sort it */ MAPTABREC ** load_one_mapping_table(char *filename, int table_size) { int i; FILE *f; char *original, *corresponding; MAPTABREC *table_record; MAPTABREC **table; table = (MAPTABREC **)malloc( sizeof(MAPTABREC *) * table_size ); f = fopen(filename, "rb"); for (i = 0; i < table_size; i++) { table[i] = (MAPTABREC *)malloc( sizeof(MAPTABREC) ); get_characters(table[i]->original, f); get_characters(table[i]->corresponding, f); } fclose(f); qsort(&table[0], table_size, sizeof(MAPTABREC*), compare_original); return table; } /** * Read 2 mapping tables */ void load_mapping_tables() { sc2k = load_one_mapping_table(SC2K_FILENAME, SC2K_SIZE); k2sc = load_one_mapping_table(K2SC_FILENAME, K2SC_SIZE); } /** * Binary Search a character from the mapping table */ int bisearch_table(MAPTABREC **table, char *ch, int left, int right) { int mid, cmp; if (right < left) { return -1; } mid = left + (right - left) / 2; cmp = strcmp(table[mid]->original, ch); if (cmp == 0) { return mid; } else if (cmp > 0) { return bisearch_table(table, ch, left, mid - 1); } else { return bisearch_table(table, ch, mid + 1, right); } } int compare_characters(char *corresponding, char *word2) { int len1, len2, i, j; len1 = strlen(corresponding); len2 = strlen(word2); for (i = 0; i < len1; i+= 3) { for (j = 0; j < len2; j += 3) { if (word2[j] == corresponding[i] && word2[j+1] == corresponding[i+1] && word2[j+2] == corresponding[i+2]) { //if (verbose > 2) fprintf(stderr, "source_ch %s, target_ch %s, j %d, word2 %s\n", source_ch, target_ch, j, word2); return 1; } } } return 0; } /** * return 1 if the 2 words has a common character. */ int has_common_character(char *word1, char *word2, int lang_id) { char source_ch[4], target_ch[4]; int len1, len2; int i, j, pos, table_size; int parallel = 1 - lang_id; MAPTABREC **table; if (lang_id == 1) { table = sc2k; table_size = SC2K_SIZE; } else { table = k2sc; table_size = K2SC_SIZE; } len1 = strlen(word1); len2 = strlen(word2); if (len1 % 3 != 0 || len2 % 3 != 0) { return 0; } // if (verbose > 2) fprintf(stderr, "CJWordMatch : %s - %s - %d\n", word1, word2, lang_id); source_ch[3] = 0; target_ch[3] = 0; for (i = 0; i < len1; i += 3) { // get a character from word1 for (j = 0; j < 3; j++) { source_ch[j] = word1[i + j]; } pos = bisearch_table(table, source_ch, 0, table_size - 1); if (pos >= 0) { if (compare_characters(table[pos]->corresponding, word2) > 0) { return 1; } } } return 0; } <file_sep>from collections import defaultdict import codecs def count(corpus, output_file): debug = False dic = defaultdict(int) other = set() fout = codecs.open(output_file, 'w', 'utf8') for line in open(corpus, 'r'): words = line.split() for word in words: if len(word) % 3 == 0: for i in xrange(len(word) / 3): dic[word[i:i+3]] += 1 else: other.add(word) fout.write('%i %i\n' % (len(dic), len(other))) record_list = [(y, x) for x, y in dic.items()] record_list.sort() record_list.reverse() i = 0 for x, y in record_list: #print y.decode('utf8'), x try: yy = y.decode('GBK') except: print y yy = 'N/A' fout.write('%s %i\n' % (yy, x)) i += 1 if i > 10 and debug: break other_list = list(other) other_list.sort() for item in other_list: #print item.decode('utf8') item2 = item.decode('utf8') fout.write(item2) fout.write('\n') i += 1 if i > 20 and debug: break fout.close() if __name__ =='__main__': count('data/train.zh_parsed', 'output/count.zh') count('data/train.ja_parsed', 'output/count.ja') <file_sep>""" Experiment 2 Use a file of word pairs, to calculate Cross-Lingual Synonym Comparison """ import argparse import numpy as np import sys class WordVecDict(object): def __init__(self, vocab_file, vectors_file): self.vocab_file = vocab_file self.vectors_file = vectors_file self.generate() def generate(self): with open(self.vocab_file, 'r') as f: words = [x.rstrip().split(' ')[0] for x in f.readlines()] with open(self.vectors_file, 'r') as f: vectors = {} for line in f: vals = line.rstrip().split(' ') vectors[vals[0]] = [float(x) for x in vals[1:]] vocab_size = len(words) vocab = {w: idx for idx, w in enumerate(words)} ivocab = {idx: w for idx, w in enumerate(words)} vector_dim = len(vectors[ivocab[0]]) W = np.zeros((vocab_size, vector_dim)) for word, v in vectors.items(): if word == '<unk>' or word == '2</s>': continue W[vocab[word], :] = v # normalize each word vector to unit variance W_norm = np.zeros(W.shape) d = (np.sum(W ** 2, 1) ** (0.5)) W_norm = (W.T / d).T self.W = W_norm self.vocab = vocab self.ivocab = ivocab def distance(self, word1, word2, verbose = False): if not word1 in self.vocab: print('Word: %s Out of dictionary!\n' % word1) return if not word2 in self.vocab: print('Word: %s Out of dictionary!\n' % word2) return vec_result = np.copy(self.W[self.vocab[word1], :]) vec_norm = np.zeros(vec_result.shape) d = (np.sum(vec_result ** 2,) ** (0.5)) vec_norm = (vec_result.T / d).T dist = np.dot(self.W, vec_norm.T) #for term in input_term.split(' '): index = self.vocab[word1] dist[index] = -np.Inf a = np.argsort(-dist)#[:N] idx = 0 for x in a: # in same language if self.ivocab[x][0] == word2[0]: idx += 1 if verbose: print idx, self.ivocab[x], dist[x] if self.ivocab[x] == word2: return idx, dist[x] print("Error: %s -> %s %f" % (word1, word2)) return -1, -1 def analogy(self, words, verbose = False): """ words = <w0, w1, w2, w3> Find distance of (w1 - w0 + w2) and w3 """ v0 = np.copy(self.W[self.vocab[words[0]], :]) v1 = np.copy(self.W[self.vocab[words[1]], :]) v2 = np.copy(self.W[self.vocab[words[2]], :]) v = np.add(v1, v2) vec_result = np.subtract(v, v0) vec_norm = np.zeros(vec_result.shape) d = (np.sum(vec_result ** 2,) ** (0.5)) vec_norm = (vec_result.T / d).T dist = np.dot(self.W, vec_norm.T) #for term in input_term.split(' '): for i in [0, 1, 2]: index = self.vocab[words[i]] dist[index] = -np.Inf a = np.argsort(-dist)#[:N] idx = 0 for x in a: # in same language if self.ivocab[x][0] == words[3][0]: idx += 1 if verbose: print idx, self.ivocab[x], dist[x] if self.ivocab[x] == words[3]: return idx, dist[x] print("Error") return -1, -1 def sentenceVec(self, sentence): """ input sentence = <w0, w1, ...> calculate the average data of corresponding <v0, v1, v2> """ sen = [] for w in sentence: if w in self.vocab: sen.append(w) if len(sen) == 0: return None tmp = self.W[0, :] vec = np.zeros(tmp.shape) for w in sen: v = np.copy(self.W[self.vocab[w], :]) vec = np.add(vec, v) vec = vec / (len(sen) * 1.0) return vec def readWordPairs(): path = "experiment/experiment2_data.txt" fin = open(path, 'r') wordPairList = [] for line in fin.readlines(): if len(line) > 2: words = line.split() w1 = "2" + words[0].strip() w2 = "1" + words[1].strip() wordPairList.append((w1, w2)) return wordPairList if __name__ == "__main__": print "reading word embeddings" wordVecDict = WordVecDict("output/vocab.cj_001", "output/batch_02/ctrl_s_0.03.vec.txt") print "reading word pairs" wordPairList = readWordPairs() print "calculating distances" ja_wc = 22748 zh_wc = 25219 result = [] # ja, zh word pair ja_rate = 0 zh_rate = 0 cnt = 0 for word1, word2 in wordPairList: cnt += 1 idx1, dist1 = wordVecDict.distance(word1, word2) ja_rate += 1 - idx1 * 1.0 / ja_wc idx2, dist2 = wordVecDict.distance(word2, word1) zh_rate += 1 - idx2 * 1.0 / zh_wc item = (word1, word2, idx1, dist1, idx2, dist2) result.append(item) print word1, word2, idx1, dist1, idx2, dist2 ja_rate /= cnt zh_rate /= cnt print "Total", cnt, "pairs, ja_rate", ja_rate, "zh_rate", zh_rate <file_sep> vocab_file = "output/vocab.cj_001" def getVocab(): vocab = set() for line in open(vocab_file): if len(line) >= 3: vocab.add(line.split()[0]) return vocab def count(vocab, filename, lang): dic = {} for line in open(filename): cnt = 0 for w in line.split(): v = lang + w if v in vocab: cnt += 1 dic[cnt] = dic.get(cnt, 0) + 1 return dic if __name__ == "__main__": vocab = getVocab() zh = count(vocab, 'data/train.zh_parsed', '1') ja = count(vocab, 'data/train.ja_parsed', '2') zhLine = "" jaLine = "" for i in xrange(331): zhLine += "%i," % zh.get(i, 0) jaLine += "%i," % ja.get(i, 0) print zhLine[:-1] print jaLine[:-1] <file_sep> class AnalogyData(): def __init__(self): self.read_analogy() self.translationPairs = None self.crossZh = None self.crossJa = None self.cross2Zh2Ja = None self.cross1Zh3Ja = None self.cross3Zh1Ja = None def read_analogy(self): self.records = [] fin = open("data/analogy_02/analogy_source.txt", 'r') for i in xrange(7): line = fin.readline() words = line.split() # in cjboc data file, 0 - ja, 1 - zh # in cjglo data file, 1 - zh, 2 - ja zh_county = '1' + words[0] zh_city = '1' + words[1] ja_county = '2' + words[2] ja_city = '2' + words[3] record = [[zh_county, zh_city], [ja_county, ja_city]] self.records.append(record) # in the translation pairs def generateTranslationPairs(self): self.translationPairs = [] for record in self.records: # self.translationPairs.append((token.zh_county, token.zh_city, token.ja_county, token.ja_city)) # self.translationPairs.append((token.zh_city, token.zh_county, token.ja_city, token.ja_county)) # self.translationPairs.append((token.ja_county, token.ja_city, token.zh_county, token.zh_city)) # self.translationPairs.append((token.ja_city, token.ja_county, token.zh_city, token.zh_county)) for lang in [0, 1]: for c in [0, 1]: self.translationPairs.append(record[lang][c], record[lang][1-c], record[1-lang][c], record[1-lang][1-c]) def getTranslationPairs(self): if not self.translationPairs: self.generateTranslationPairs() def generateCrossSingleLang(self, lang): result = [] for record1 in self.records: for record2 in self.records: if record1 == record2: continue for c in [0, 1]: result.append((record1[lang][c], record1[lang][1-c], record2[lang][c], record2[lang][1-c])) return result def generateCrossZh(self): self.crossZh = self.generateCrossSingleLang(0) def getCrossZh(self): if not self.crossZh: self.generateCrossZh() return self.crossZh def generateCrossJa(self): self.crossJa = self.generateCrossSingleLang(1) def getCrossJa(self): if not self.crossJa: self.generateCrossJa() return self.crossJa def generateCross2Zh2Ja(self): self.cross2Zh2Ja = [] for record1 in self.records: for record2 in self.records: if record1 == record2: continue for c in [0, 1]: self.cross2Zh2Ja.append((record1[0][c], record1[0][1-c], record2[1][c], record2[1][1-c])) self.cross2Zh2Ja.append((record1[0][c], record1[1][1-c], record2[0][c], record2[1][1-c])) self.cross2Zh2Ja.append((record1[0][c], record1[1][1-c], record2[1][c], record2[0][1-c])) self.cross2Zh2Ja.append((record1[1][c], record1[0][1-c], record2[0][c], record2[1][1-c])) self.cross2Zh2Ja.append((record1[1][c], record1[0][1-c], record2[1][c], record2[0][1-c])) self.cross2Zh2Ja.append((record1[1][c], record1[1][1-c], record2[0][c], record2[0][1-c])) def getCross2Zh2Ja(self): if not self.cross2Zh2Ja: self.generateCross2Zh2Ja() return self.cross2Zh2Ja def generateCross1vs3(self, lang): # lang has 1 token result = [] for record1 in self.records: for record2 in self.records: if record1 == record2: continue for c in [0, 1]: result.append((record1[lang][c], record1[1-lang][1-c], record2[1-lang][c], record2[1-lang][1-c])) result.append((record1[1-lang][c], record1[lang][1-c], record2[1-lang][c], record2[1-lang][1-c])) result.append((record1[1-lang][c], record1[1-lang][1-c], record2[lang][c], record2[1-lang][1-c])) result.append((record1[1-lang][c], record1[1-lang][1-c], record2[1-lang][c], record2[lang][1-c])) return result def generateCross1Zh3Ja(self): self.cross1Zh3Ja = self.generateCross1vs3(0) def getCross1Zh3Ja(self): if not self.cross1Zh3Ja: self.generateCross1Zh3Ja() return self.cross1Zh3Ja def generateCross3Zh1Ja(self): self.cross3Zh1Ja = self.generateCross1vs3(1) def getCross3Zh1Ja(self): if not self.cross3Zh1Ja: self.generateCross3Zh1Ja() return self.cross3Zh1Ja def getByZhCount(self, zhCount): if zhCount == 0: return self.getCrossJa() elif zhCount == 1: return self.getCross1Zh3Ja() elif zhCount == 2: return self.getCross2Zh2Ja() elif zhCount == 3: return self.getCross3Zh1Ja() else: return self.getCrossZh() if __name__ == '__main__': data = AnalogyData() #for t in data.getCross3Zh1Ja(): #for t in data.getCross1Zh3Ja(): #for t in data.getCross2Zh2Ja(): for t in data.getCrossZh(): print t[0], t[1], t[2], t[3] <file_sep> from WordVecDict import WordVecDict import numpy as np def readTestDataFile(filename, prefix): data = [] for line in open(filename, 'r').readlines(): if len(line) == 0: continue sentence = [] for w in line.split(): sentence.append(prefix + w) data.append(sentence) return data def readTestData(): zhData = readTestDataFile("data/test.zh_parsed", "1") jaData = readTestDataFile("data/test.ja_parsed", "2") return zhData, jaData def calculateAcc(vecFile): wordVecDict = WordVecDict("output/vocab.cj_001", vecFile) zhData, jaData = readTestData() n = len(zhData) zhVec = [] jaVec = [] for i in xrange(n): zhVec.append(wordVecDict.sentenceVec(zhData[i])) jaVec.append(wordVecDict.sentenceVec(jaData[i])) matrix = [] for i in xrange(n): line = [] for j in xrange(n): line.append(np.dot(zhVec[i], jaVec[j])) matrix.append(line) dic = {} acc = 0 for i in xrange(n): order = [(matrix[i][j], j) for j in xrange(n)] order.sort() for j in xrange(n): if order[j][1] == i: #print "Zh", i, "matches Ja", i, "at position", n - j k = n - j # oerder is from small to big, so k == 1 is the best match dic[k] = dic.get(k, 0) + 1 acc += 1.0 - (k - 1.0) / n break acc = acc * 1.0 / n return acc def batch(): for s in xrange(1, 6): for c in xrange(1, 6): inputFile = "output/batch_02/exp_s_0.0%i_c_0.0%i.vec.txt" % (s, c) print calculateAcc(inputFile), print "" if __name__ == "__main__": #print calculateAcc("output/batch_02/ctrl_s_0.03.vec.txt") batch() <file_sep> #include <stdio.h> #include "bisearch_mapping_table.h" extern MAPTABREC **k2sc, **sc2k; void test_mapping_table_1(index) { int result; result = bisearch_table(sc2k, sc2k[index]->original, 0, SC2K_SIZE - 1); fprintf(stderr, "result = %d\n", result); result = bisearch_table(k2sc, k2sc[index]->original, 0, K2SC_SIZE - 1); fprintf(stderr, "result = %d\n", result); } void test_mapping_table_2() { int result; result = bisearch_table(sc2k, sc2k[SC2K_SIZE - 1]->original, 0, SC2K_SIZE - 1); fprintf(stderr, "result = %d (%d)\n", result, SC2K_SIZE - 1); result = bisearch_table(k2sc, k2sc[K2SC_SIZE - 1]->original, 0, K2SC_SIZE - 1); fprintf(stderr, "result = %d (%d)\n", result, K2SC_SIZE - 1); } void test_search() { test_mapping_table_1(0); test_mapping_table_1(7); test_mapping_table_1(77); test_mapping_table_1(777); test_mapping_table_1(5000); test_mapping_table_2(); } void test_mapping() { int result; result = has_common_character("ๆจฑ่Šฑ", "ๆกœใŒใ•ใ", 1); fprintf(stderr, "ๆจฑ่Šฑ - ๆกœใŒใ•ใ, result = %d\n", result); result = has_common_character("ๆกœใŒใ•ใ", "ๆจฑ่Šฑ", 2); fprintf(stderr, "ๆกœใŒใ•ใ - ๆจฑ่Šฑ, result = %d\n", result); result = has_common_character("ๅ›ฝๅฎถ", "ๆกœใŒใ•ใ", 1); fprintf(stderr, "ๅ›ฝๅฎถ - ๆกœใŒใ•ใ, result = %d\n", result); result = has_common_character("ๅ›ฝๅฎถ", "็Ž‹ๅ›ฝ", 2); fprintf(stderr, "ๅ›ฝๅฎถ - ็Ž‹ๅ›ฝ, result = %d\n", result); } int main(int argc, char **argv) { load_mapping_tables(); test_mapping(); }<file_sep>/* Author <NAME>, April 2001. Permission to use this code is freely granted, provided that this statement is retained. */ /* Bitwise hash function. Note that tsize does not have to be prime. */ unsigned int bitwisehash(char *word, int tsize, unsigned int seed) { char c; unsigned int h; h = seed; for( ; ( c=*word )!='\0' ; word++ ) { h ^= ( (h << 5) + c + (h >> 2) ); } return((unsigned int)((h&0x7fffffff) % tsize)); } /* Efficient string comparison */ int scmp( char *s1, char *s2 ) { while (*s1 != '\0' && *s1 == *s2) {s1++; s2++;} return(*s1 - *s2); }<file_sep>from collections import defaultdict """ The input file is download from: http://lotus.kuee.kyoto-u.ac.jp/~chu/pubdb/LREC2012/kanji_mapping_table.txt Removed the introduction text in the head, only character triples remained in input file. """ def check_kanji_length(): """ Checked by this function, the first item of each triple is excatly one Kanji charachter. """ fin = open('data/kanji_mapping_table_clean.txt', 'r') for line in fin: triple = line.split() kanji = triple[0] if len(kanji) != 3: print kanji, len(kanji) break def check_duplicated_kanji(): """ Checked by this function, No duplicated Kanjis in this mapping table's first column """ fin = open('data/kanji_mapping_table_clean.txt', 'r') kanji_set = set() for line in fin: triple = line.split() kanji = triple[0] if kanji in kanji_set: print kanji break kanji_set.add(kanji) print "There are", len(kanji_set), "Kanjis in the mapping table." def write_tuple_to_file(tuple, filename): fout = open(filename, 'w') for kanji, simple_chinese in tuple: fout.write("%s %s\n" % (kanji, simple_chinese)) fout.close() def kanji_2_simple_chinese(): """ Result: There are 569 N/A, 5205 single corresponding Simple Chinese charachters, 582 mutiple corresponding Simple Chinese charachters, in total 6356 lines. A Kanji Character is mapping to X Simple Chinese Character: {0: 569, 1: 5205, 2: 538, 3: 41, 4: 1, 6: 2} """ fin = open('data/kanji_mapping_table_clean.txt', 'r') single_result = [] mutiple_result = [] single = 0 mutiple = 0 na = 0 dic = {} for line in fin: triple = line.split() kanji = triple[0] simple_chinese = triple[2] if simple_chinese == 'N/A': na += 1 elif len(simple_chinese) <= 3: single += 1 single_result.append((kanji, simple_chinese)) else: mutiple += 1 simple_chinese = ''.join(simple_chinese.split(',')) mutiple_result.append((kanji, simple_chinese)) key = len(simple_chinese) / 3 dic[key] = dic.get(key, 0) + 1 # write_tuple_to_file(single_result, "output/mapping_table/single_01.txt") # write_tuple_to_file(mutiple_result, "output/mapping_table/mutiple_01.txt") result = single_result + mutiple_result result.sort() write_tuple_to_file(result, "output/mapping_table/kanji2simplec.txt") print "There are", na, "N/A,", print single, "single corresponding Simple Chinese charachters,", print mutiple, "mutiple corresponding Simple Chinese charachters,", print "in total", (na + single + mutiple), "lines." dic[0] = na dic[1] = single print "A Kanji Character is mapping to X Simple Chinese Character:" print dic def simple_chinese_2_kanji(): """ A Simple Chinese Character is mapping to X Kanji Character: {1: 3873, 2: 903, 3: 189, 4: 34, 5: 5, 6: 1, 7: 1} """ fin = open('data/kanji_mapping_table_clean.txt', 'r') dic = defaultdict(list) for line in fin: triple = line.split() kanji = triple[0] simple_chinese = triple[2] if simple_chinese == 'N/A': continue elif len(simple_chinese) <= 3: dic[simple_chinese].append(kanji) else: for character in simple_chinese.split(','): dic[character].append(kanji) result = [(x, ''.join(y)) for x, y in dic.items()] result.sort() write_tuple_to_file(result, "output/mapping_table/simplec2kanji.txt") dic2 = defaultdict(int) for key in dic: dic2[len(dic[key])] += 1 print "A Simple Chinese Character is mapping to X Kanji Character:" print dic2 def find_same_shape_character(): """ The shape of a common character in 3 categories are sometimes the same, sometimes not. Only consider lines without "N/A", there are 5 patterns: Type Kanji Tranditional Simple 0 A A A 1 A A B 2 A B A 3 A B B 4 A B C This function counts these types, and save to corresponding files. """ fin = open('data/kanji_mapping_table_clean.txt', 'r') dic = defaultdict(list) type_set = [[] for _ in xrange(6)] # Type 5 is 'N/A' for line in fin: triple = line.split() if 'N/A' in triple: type_set[5].append(line) continue kanji = triple[0] tranditional = triple[1] simple = triple[2] for c_kanji in kanji.split(','): for c_tranditional in tranditional.split(','): for c_simple in simple.split(','): if c_kanji == c_tranditional and c_kanji == c_simple: type_set[0].append(line) elif c_kanji == c_tranditional: type_set[1].append(line) elif c_kanji == c_simple: type_set[2].append(line) elif c_tranditional == c_simple: type_set[3].append(line) else: type_set[4].append(line) for i in xrange(6): fout = open("output/mapping_table/character_shape_type_%i.txt" % i, "w") for line in type_set[i]: fout.write(line) fout.close() def find_same_shape_character_single(): """ Same with find_same_shape_character(), but only deal with line that in each type there is only 1 character. """ fin = open('data/kanji_mapping_table_clean.txt', 'r') dic = defaultdict(list) type_set = [[] for _ in xrange(6)] # Type 5 is line with ',' for line in fin: if ',' in line: type_set[5].append(line) continue triple = line.split() if 'N/A' in triple: continue c_kanji = triple[0] c_tranditional = triple[1] c_simple = triple[2] if c_kanji == c_tranditional and c_kanji == c_simple: type_set[0].append(line) elif c_kanji == c_tranditional: type_set[1].append(line) elif c_kanji == c_simple: type_set[2].append(line) elif c_tranditional == c_simple: type_set[3].append(line) else: type_set[4].append(line) for i in xrange(6): fout = open("output/mapping_table/character_shape_type_single_%i.txt" % i, "w") for line in type_set[i]: fout.write(line) fout.close() if __name__ == '__main__': # check_kanji_length() # check_duplicated_kanji() # kanji_2_simple_chinese() # simple_chinese_2_kanji() # find_same_shape_character() find_same_shape_character_single() <file_sep>// Tool to calculate word-word cooccurrence statistics for sentence aligned // corpus of 2 languages. // // Copyright (c) 2014 The Board of Trustees of // The Leland Stanford Junior University. All Rights Reserved. // // 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. // // // For more information, bug reports, fixes, contact: // <NAME> (<EMAIL>) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> typedef struct mapping_table { //char *original; char original[4]; // at most 7 corresponding characters //char *corresponding;// char corresponding[22]; } mapping_table; mapping_table **k2sc, **sc2k; char *sc2k_filename = "../data/simplec2kanji.txt"; char *k2sc_filename = "../data/kanji2simplec.txt"; int sc2k_size = 5;//5006; int k2sc_size = 5787; int debug_counter = 0; int compare_original(const void *a, const void *b) { //int t = strcmp(((mapping_table *)a)->original, ((mapping_table *)b)->original); //fprintf(stderr, "%s %s %d\n", ((mapping_table *)a)->original, ((mapping_table *)b)->original, t); //scanf("%d", &t); mapping_table *aa, *bb, **aaa, **bbb; aaa = ((mapping_table **)a); //aa = aaa[0]; aa = *aaa; bbb = ((mapping_table **)b); bb = *bbb; //bb = bbb[0]; fprintf(stderr, "Compareing: %s %s\n", (*(mapping_table **)a)->original, (*(mapping_table **)b)->original); fprintf(stderr, " &a=%p, &b=%p, \n &aa=%p, &bb=%p, \n &aa->original=%p, bb->original=%p\n", a, b, aa, bb, aa->original, bb->original); //return strcmp(((mapping_table *)a)->original, ((mapping_table *)b)->original); return strcmp((*(mapping_table **)a)->original, (*(mapping_table **)b)->original); } int compare_original_2(mapping_table *a, mapping_table *b) { int t; if (debug_counter < 70000) { t = strcmp(a->original, b->original); // fprintf(stderr, "%s %s %x %x %d\n", a->original, b->original, a, b, t); scanf("%d", &t); debug_counter++; } return strcmp(a->original, b->original); } int get_characters(char *word, FILE *fin) { int i = 0, ch; while (!feof(fin)) { ch = fgetc(fin); //if (ch == 13) continue; if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { break; } word[i++] = ch; //if (i >= MAX_STRING_LENGTH - 1) i--; // truncate words that exceed max length } word[i] = 0; return i; } mapping_table ** ReadMappingTableFromFile(char *filename, int table_size) { int i; FILE *f; char *original, *corresponding; mapping_table *table_record; mapping_table **table; table = (mapping_table **)malloc( sizeof(mapping_table *) * table_size ); f = fopen(filename, "rb"); for (i = 0; i < table_size; i++) { // for char * original. // table_record = (mapping_table *)malloc( sizeof(mapping_table)); // table_record->original = (char *)malloc( sizeof(char) * 30); // if (i % 700 == 0) fprintf(stderr, "table_record->original %p\n", table_record->original); // table_record->corresponding = (char *)malloc( sizeof(char) * 50); // get_characters(table_record->original, f); // get_characters(table_record->corresponding, f); // //table_record->original = original; // //table_record->corresponding = corresponding; // table[i] = table_record; // if (i % 700 == 0) fprintf(stderr, "%d %s %s %p %p %p\n", i, table[i]->original, table[i]->corresponding, table[i]->original, table[i]->corresponding, table[i]); // for char original[4] table_record = (mapping_table *)malloc( sizeof(mapping_table) ); get_characters(table_record->original, f); get_characters(table_record->corresponding, f); //table_record->original = original; //table_record->corresponding = corresponding; table[i] = table_record; //if (i % 700 == 0) fprintf(stderr, "%d %s %s %p %p %p\n", i, table[i]->original, table[i]->corresponding, table[i]->original, table[i]->corresponding, table[i]); } fclose(f); //fprintf(stderr, "ReadMappingTableFromFile - table %p, table[7] %p, table[7]->original %p\n", table, table[7], table[7]->original); fprintf(stderr, "=============== After Reading File ============\n"); fprintf(stderr, "&table=%p\n", table); for (i = 0; i < sc2k_size; i++) { fprintf(stderr, "%d ", i); fprintf(stderr, "table[i]=%s, &table[i]=%p, &table[i]->original=%p\n", table[i]->original, table[i], table[i]->original); } // TODO the bug is because the usage of qsort!!!!!!!=============== qsort(&table[0], table_size, sizeof(mapping_table*), compare_original); fprintf(stderr, "=============== After QSORT ============\n"); fprintf(stderr, "&table=%p\n", table); for (i = 0; i < sc2k_size; i++) { fprintf(stderr, "%d ", i); fprintf(stderr, "table[i]=%s, &table[i]=%p, &table[i]->original=%p\n", table[i]->original, table[i], table[i]->original); } // fprintf(stderr, "ReadMappingTableFromFile - table %p, table[7] %p, table[7]->original %p\n", table, table[7], table[7]->original); // for (i = 0; i < sc2k_size; i += 700) { // fprintf(stderr, "%d ", i); // fprintf(stderr, "%p %p\n", table[i]->original, table[i]->corresponding);//, table[i]->original, table[i]->corresponding); // } return table; } void ReadMappingTable() { sc2k = ReadMappingTableFromFile(sc2k_filename, sc2k_size); k2sc = ReadMappingTableFromFile(k2sc_filename, k2sc_size); } int BinarySearchTable(mapping_table **table, char *ch, int left, int right) { int mid, cmp; if (right < left) { return -1; } mid = left + (right - left) / 2; fprintf(stderr, "mid = %d, %s\n", mid, table[mid]->original); //cmp = strcmp(ch, table[mid]->original); cmp = strcmp(table[mid]->original, ch); //int compare_original(const void *a, const void *b) { // return strcmp(((struct mapping_table *)a)->original, ((struct mapping_table *)b)->original); //} if (cmp == 0) { return mid; } else if (cmp < 0) { return BinarySearchTable(table, ch, left, mid - 1); } else { return BinarySearchTable(table, ch, mid + 1, right); } } int test_mapping_table_1() { int i, result; fprintf(stderr, "test_mapping_table_1\n"); sc2k = ReadMappingTableFromFile(sc2k_filename, sc2k_size); fprintf(stderr, "After ReadMappingTableFromFile\n"); //fprintf(stderr, "%p\n", sc2k); fprintf(stderr, "table %p, table[7] %p, table[7]->original %p\n", sc2k, sc2k[7], sc2k[7]->original); for (i = 0; i < sc2k_size; i++) { //if (i % 700 == 0) fprintf(stderr, "%d ", i); //if (i % 700 == 0) fprintf(stderr, "%p %p\n", sc2k[i]->original, sc2k[i]->corresponding); printf("%s %s %p %p %p\n", sc2k[i]->original, sc2k[i]->corresponding, sc2k[i]->original, sc2k[i]->corresponding, sc2k[i]); } result = BinarySearchTable(sc2k, sc2k[1]->original, 0, sc2k_size - 1); fprintf(stderr, "result = %d\n", result); } int main(int argc, char **argv) { test_mapping_table_1(); } <file_sep>// Tool to calculate word-word cooccurrence statistics for sentence aligned // corpus of 2 languages. // // Copyright (c) 2014 The Board of Trustees of // The Leland Stanford Junior University. All Rights Reserved. // // 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. // // // For more information, bug reports, fixes, contact: // <NAME> (<EMAIL>) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "hash_mapping_table.h" MAPTABREC **k2sc, **sc2k; /* Create hash table, initialise ptrs to NULL */ MAPTABREC ** init_hash_mapping_table() { int i; MAPTABREC **ht; ht = (MAPTABREC **) malloc( sizeof(MAPTABREC *) * M_SIZE ); for(i = 0; i < M_SIZE; i++) { ht[i] = (MAPTABREC *) NULL; } return(ht); } /* Search hash table for given string, return record if found, else NULL */ MAPTABREC * hash_search_mapping_table(MAPTABREC **ht, char *w) { MAPTABREC *htmp, *hprv; unsigned int hval = M_HASHFN(w, M_SIZE, M_SEED); for( hprv = NULL, htmp=ht[hval] ; htmp != NULL && scmp(htmp->original, w) != 0 ; hprv = htmp, htmp = htmp->next ) { ; } if( hprv!=NULL ) { /* move to front on access */ hprv->next = htmp->next; htmp->next = ht[hval]; ht[hval] = htmp; } return(htmp); } /* Search hash table for given string, insert if not found */ void hash_insert_mapping_table(MAPTABREC **ht, char *original, char *corresponding) { MAPTABREC *htmp, *hprv; unsigned int hval = M_HASHFN(original, M_SIZE, M_SEED); for( hprv = NULL, htmp=ht[hval] ; htmp != NULL && scmp(htmp->original, original) != 0 ; hprv = htmp, htmp = htmp->next ) { ; } if(htmp == NULL) { htmp = (MAPTABREC *) malloc( sizeof(MAPTABREC) ); //htmp->word = (char *) malloc( strlen(w) + 1 ); strcpy(htmp->original, original); strcpy(htmp->corresponding, corresponding); htmp->next = NULL; if(hprv == NULL) { ht[hval] = htmp; } else { hprv->next = htmp; } /* new records are not moved to front */ } else { if(hprv != NULL) { /* move to front on access */ hprv->next = htmp->next; htmp->next = ht[hval]; ht[hval] = htmp; } } return; } /** * Read one or several Kanji or Hanzi from text file */ int get_characters(char *word, FILE *fin) { int i = 0, ch; while (!feof(fin)) { ch = fgetc(fin); if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { break; } word[i++] = ch; } word[i] = 0; return i; } /** * Read mapping table from file, and sort it */ MAPTABREC ** load_one_mapping_table(char *filename, int table_size) { int i; FILE *f; char original[4], corresponding[22]; // MAPTABREC *record; MAPTABREC **table; table = init_hash_mapping_table(); fprintf(stderr, "start reading %s\n", filename); f = fopen(filename, "rb"); for (i = 0; i < table_size; i++) { // record = (MAPTABREC *)malloc( sizeof(MAPTABREC) ); get_characters(original, f); get_characters(corresponding, f); hash_insert_mapping_table(table, original, corresponding); } fclose(f); return table; } /** * Read 2 mapping tables */ void load_mapping_tables() { sc2k = load_one_mapping_table(SC2K_FILENAME, SC2K_SIZE); k2sc = load_one_mapping_table(K2SC_FILENAME, K2SC_SIZE); } int compare_characters(char *corresponding, char *word2) { int len1, len2, i, j; fprintf(stderr, "compare_characters: %s %s\n", corresponding, word2); len1 = strlen(corresponding); len2 = strlen(word2); fprintf(stderr, "compare_characters: %d %d\n", len1, len2); for (i = 0; i < len1; i+= 3) { for (j = 0; j < len2; j += 3) { if (word2[j] == corresponding[i] && word2[j+1] == corresponding[i+1] && word2[j+2] == corresponding[i+2]) { //if (verbose > 2) fprintf(stderr, "source_ch %s, target_ch %s, j %d, word2 %s\n", source_ch, target_ch, j, word2); return 1; } } } return 0; } /** * return 1 if the 2 words has a common character. */ int has_common_character(char *word1, char *word2, int lang_id) { char source_ch[4], target_ch[4]; int len1, len2; int i, j, table_size; int parallel = 1 - lang_id; MAPTABREC **table; MAPTABREC *ret; if (lang_id == 1) { table = sc2k; table_size = SC2K_SIZE; } else { table = k2sc; table_size = K2SC_SIZE; } len1 = strlen(word1); len2 = strlen(word2); if (len1 % 3 != 0 || len2 % 3 != 0) { return 0; } fprintf(stderr, "has_common_character : %s - %s - %d\n", word1, word2, lang_id); source_ch[3] = 0; target_ch[3] = 0; for (i = 0; i < len1; i += 3) { // get a character from word1 for (j = 0; j < 3; j++) { source_ch[j] = word1[i + j]; } // pos = bisearch_table(table, source_ch, 0, table_size - 1); // if (pos >= 0) { // if (compare_characters(table[pos]->corresponding, word2) > 0) { // return 1; // } // } fprintf(stderr, "for : %s\n", source_ch); ret = hash_search_mapping_table(table, source_ch); fprintf(stderr, "for : %p %s %s\n", ret, ret->original, ret->corresponding); if (ret) { if (compare_characters(ret->corresponding, word2) > 0) { return 1; } } } return 0; } <file_sep>CC = gcc #For older gcc, use -O3 or -O2 instead of -Ofast CFLAGS = -lm -pthread -Ofast -march=native -funroll-loops -Wno-unused-result BUILDDIR := build SRCDIR := src all: dir glove shuffle cooccur vocab_count bi_vocab_count bi_cooccur dir : mkdir -p $(BUILDDIR) glove : $(SRCDIR)/glove.c $(CC) $(SRCDIR)/glove.c -o $(BUILDDIR)/glove $(CFLAGS) shuffle : $(SRCDIR)/shuffle.c $(CC) $(SRCDIR)/shuffle.c -o $(BUILDDIR)/shuffle $(CFLAGS) cooccur : $(SRCDIR)/cooccur.c $(CC) $(SRCDIR)/cooccur.c -o $(BUILDDIR)/cooccur $(CFLAGS) vocab_count : $(SRCDIR)/vocab_count.c $(CC) $(SRCDIR)/vocab_count.c -o $(BUILDDIR)/vocab_count $(CFLAGS) bi_vocab_count : $(SRCDIR)/bi_vocab_count.c $(CC) $(SRCDIR)/bi_vocab_count.c -o $(BUILDDIR)/bi_vocab_count $(CFLAGS) bi_cooccur : $(SRCDIR)/bi_cooccur.c #$(CC) $(SRCDIR)/bi_cooccur.c $(SRCDIR)/hash_mapping_table.c -o $(BUILDDIR)/bi_cooccur $(CFLAGS) $(CC) $(SRCDIR)/bi_cooccur.c $(SRCDIR)/bisearch_mapping_table.c -o $(BUILDDIR)/bi_cooccur $(CFLAGS) clean: rm -rf glove shuffle cooccur vocab_count bi_vocab_count bi_cooccur build <file_sep># CJ-Glo Chinese Japanese Word Embedding based on GloVe <file_sep> from WordVecDict import WordVecDict from AnalogyData import AnalogyData data = AnalogyData() ja_wc = 22748 zh_wc = 25219 def calculateRate(idx, word): if word[0] == '1': return 1 - idx * 1.0 / zh_wc else: return 1 - idx * 1.0 / ja_wc def batchCtrl(): for b in xrange(1, 6): inputFile = "output/batch_02/ctrl_s_0.0%i.vec.txt" % b wordVecDict = WordVecDict("output/vocab.cj_001", inputFile) for zhCount in xrange(5): outputFile = "output/batch_02/analogy_01/ctrl_s_0.0%i_zh_%i.csv" % (b, zhCount) print "Writing to", outputFile, '... ... ... ...' fout = open(outputFile, 'w') records = data.getByZhCount(zhCount) for record in records: idx, _ = wordVecDict.analogy(record) rate = calculateRate(idx, record[3]) line = ','.join(record) line += ',%i,%f\n' % (idx, rate) fout.write(line) fout.close() def batchExp(): for s in xrange(1, 6): for c in xrange(1, 6): inputFile = "output/batch_02/exp_s_0.0%i_c_0.0%i.vec.txt" % (s, c) wordVecDict = WordVecDict("output/vocab.cj_001", inputFile) for zhCount in xrange(5): outputFile = "output/batch_02/analogy_01/exp_s_0.0%i_c_0.0%i_zh_%i.csv" % (s, c, zhCount) print "Writing to", outputFile, '... ... ... ...' fout = open(outputFile, 'w') records = data.getByZhCount(zhCount) for record in records: idx, _ = wordVecDict.analogy(record) rate = calculateRate(idx, record[3]) line = ','.join(record) line += ',%i,%f\n' % (idx, rate) fout.write(line) fout.close() if __name__ == '__main__': #batchCtrl() batchExp()<file_sep> import WordVecDict if __name__ == '__main__': #wordVecDict = WordVecDict.WordVecDict("output/vocab.cj_001", "output/batch_02/ctrl_s_0.03.vec.txt") wordVecDict = WordVecDict.WordVecDict("output/vocab.cj_001", "output/batch_02/exp_s_0.05_c_0.05.vec.txt") while True: print "Input w0 w1 w2 w3:" line = raw_input().split() print wordVecDict.distance(line[0], line[1], True)<file_sep>// Tool to calculate word-word cooccurrence statistics for sentence aligned // corpus of 2 languages. // // Copyright (c) 2014 The Board of Trustees of // The Leland Stanford Junior University. All Rights Reserved. // // 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. // // // For more information, bug reports, fixes, contact: // <NAME> (<EMAIL>) #define SC2K_FILENAME "../data/simplec2kanji.txt" #define K2SC_FILENAME "../data/kanji2simplec.txt" #define SC2K_SIZE 5006 #define K2SC_SIZE 5787 typedef struct mapping_table_record { char original[4]; // at most 7 corresponding characters char corresponding[22]; } MAPTABREC; /** * Read 2 mapping tables */ void load_mapping_tables(); /** * Binary Search a character from the mapping table */ int bisearch_table(MAPTABREC **table, char *ch, int left, int right); /** * return 1 if the 2 words has a common character. */ int has_common_character(char *word1, char *word2, int lang_id); <file_sep> class Token(): def __init__(self, zh_county, zh_city, ja_county, ja_city): self.zh_county = zh_county self.zh_city = zh_city self.ja_county = ja_county self.ja_city = ja_city def read_analogy(): fin = open("data/analogy_02/analogy_source.txt", 'r') for i in xrange(7): fin.readline() line = fin.readline() tokens = line.split() # in data file, 0 - ja, 1 - zh for k in xrange(4): if tokens[k] == 0: if __name__ == "__main__": <file_sep>""" Experiment 2 Use a file of word pairs, to calculate Cross-Lingual Synonym Comparison """ import argparse import numpy as np import sys def generate(): parser = argparse.ArgumentParser() parser.add_argument('--vocab_file', default='vocab.txt', type=str) parser.add_argument('--vectors_file', default='vectors.txt', type=str) args = parser.parse_args() with open(args.vocab_file, 'r') as f: words = [x.rstrip().split(' ')[0] for x in f.readlines()] with open(args.vectors_file, 'r') as f: vectors = {} for line in f: vals = line.rstrip().split(' ') vectors[vals[0]] = [float(x) for x in vals[1:]] vocab_size = len(words) vocab = {w: idx for idx, w in enumerate(words)} ivocab = {idx: w for idx, w in enumerate(words)} vector_dim = len(vectors[ivocab[0]]) W = np.zeros((vocab_size, vector_dim)) for word, v in vectors.items(): if word == '<unk>': continue W[vocab[word], :] = v # normalize each word vector to unit variance W_norm = np.zeros(W.shape) d = (np.sum(W ** 2, 1) ** (0.5)) W_norm = (W.T / d).T return (W_norm, vocab, ivocab) def distance(W, vocab, ivocab, word1, word2): if not word1 in vocab: print('Word: %s Out of dictionary!\n' % word1) return if not word2 in vocab: print('Word: %s Out of dictionary!\n' % word2) return vec_result = np.copy(W[vocab[word1], :]) vec_norm = np.zeros(vec_result.shape) d = (np.sum(vec_result ** 2,) ** (0.5)) vec_norm = (vec_result.T / d).T dist = np.dot(W, vec_norm.T) #for term in input_term.split(' '): index = vocab[word1] dist[index] = -np.Inf a = np.argsort(-dist)#[:N] #print("\n Word Cosine distance\n") #print("---------------------------------------------------------\n") #for x in a: # print("%35s\t\t%f" % (ivocab[x], dist[x])) idx = 0 for x in a: if ivocab[x][0] == word2[0]: idx += 1 if ivocab[x] == word2: #print("%s -> %s %f" % (word1, ivocab[x], dist[x])) #break return idx, dist[x] print("Error: %s -> %s %f" % (word1, word2)) return -1, -1 def readWordPairs(): path = "experiment/experiment2_data.txt" fin = open(path, 'r') wordPairList = [] for line in fin.readlines(): if len(line) > 2: words = line.split() w1 = "2" + words[0].strip() w2 = "1" + words[1].strip() wordPairList.append((w1, w2)) return wordPairList if __name__ == "__main__": N = 20; # number of closest words that will be shown print "reading word embeddings" W, vocab, ivocab = generate() print "reading word pairs" wordPairList = readWordPairs() print "calculating distances" ja_wc = 22748 zh_wc = 25219 result = [] # ja, zh word pair ja_rate = 0 zh_rate = 0 cnt = 0 for word1, word2 in wordPairList: cnt += 1 idx1, dist1 = distance(W, vocab, ivocab, word1, word2) ja_rate += 1 - idx1 * 1.0 / ja_wc idx2, dist2 = distance(W, vocab, ivocab, word2, word1) zh_rate += 1 - idx2 * 1.0 / zh_wc item = (word1, word2, idx1, dist1, idx2, dist2) result.append(item) print word1, word2, idx1, dist1, idx2, dist2 ja_rate /= cnt zh_rate /= cnt print "Total", cnt, "pairs, ja_rate", ja_rate, "zh_rate", zh_rate <file_sep>""" Train CJ-GLO model by different parameters, then test the result. """ import os vocab_file = "output/vocab.cj_001" glove_args_2 = { "threads": "8", "x-max": "10", "iter": "15", "vector-size": "50", "binary": "2", "vocab-file": vocab_file, "verbose": "0" } # used to find a good ctrl parameters glove_args = { "threads": "16", "x-max": "100", "iter": "15", "vector-size": "100", "binary": "2", "vocab-file": vocab_file, "eta": "0.05", "verbose": "2", "alpha": "0.75" } def fill_glove_command(input_filename, output_filename): cmd = "build/glove -save-file output/" + output_filename cmd += " -input-file output/" + input_filename for args in glove_args: cmd += " -" + args + " " + glove_args[args] return cmd shuffle_args_old = { "memory": "4.0", "verbose": "0" } shuffle_args = { "memory": "8.0", "verbose": "2" } def fill_shuffle_command(input_filename, output_filename): cmd = "build/shuffle" for args in shuffle_args: cmd += " -" + args + " " + shuffle_args[args] cmd += " < output/" + input_filename cmd += " > output/" + output_filename return cmd def fill_bi_cooccur_command(window_size, sentence_rate, cjglo, cjglo_rate, output_filename): cmd = "build/bi_cooccur -verbose 0" cmd += " -corpus-file-1 data/train.zh_parsed" cmd += " -corpus-file-2 data/train.ja_parsed" cmd += " -window-size " + window_size cmd += " -vocab-file " + vocab_file cmd += " -sentence-rate " + sentence_rate cmd += " -cjglo " + cjglo cmd += " -cjglo-rate " + cjglo_rate cmd += " > output/" + output_filename return cmd def fill_experiment2_command(word_vec_filename, output_filename): cmd = "python tools/experiment2.py --vocab_file " + vocab_file cmd += " --vectors_file output/" + word_vec_filename cmd += " > output/" + output_filename return cmd def run_once(sentence_rate, cjglo, window_size, cjglo_rate, prefix): co_output_filename = prefix + ".co" co_cmd = fill_bi_cooccur_command(window_size, sentence_rate, cjglo, cjglo_rate, co_output_filename) print co_cmd os.popen(co_cmd) shuf_output_filename = prefix + ".shuf" shuf_cmd = fill_shuffle_command(co_output_filename, shuf_output_filename) print shuf_cmd os.popen(shuf_cmd) glove_output_filename = prefix + ".vec" glove_cmd = fill_glove_command(shuf_output_filename, glove_output_filename) print glove_cmd os.popen(glove_cmd) word_vec_filename = prefix + ".vec.txt" experiment2_output_filename = prefix + ".exp2.txt" experiment2_cmd = fill_experiment2_command(word_vec_filename, experiment2_output_filename) print experiment2_cmd os.popen(experiment2_cmd) # clean tmp files print "rm -rf output/" + co_output_filename os.popen("rm -rf output/" + co_output_filename) print "rm -rf output/" + shuf_output_filename os.popen("rm -rf output/" + shuf_output_filename) def run_control_by_list(prefix, sentence_rate_list): for sentence_rate in sentence_rate_list: control_prefix = prefix + "ctrl_s_" + sentence_rate run_once(sentence_rate, "0", "0", control_prefix) def run_experiment_by_list(prefix, window_size_list, sentence_rate_list, cjglo_rate_list): for sentence_rate in sentence_rate_list: for cjglo_rate in cjglo_rate_list: for window_size in window_size_list: exp_prefix = prefix + "exp_w_" + window_size + "_s_" + sentence_rate + "_c_" + cjglo_rate run_once(sentence_rate, "1", window_size, cjglo_rate, exp_prefix) def main(): prefix = "batch_04/" sentence_rate_list = ["0.00", "0.01", "0.02", "0.03", "0.04", "0.05"] # [str(0.1 * x) for x in xrange(1, 11)] #sentence_rate_list = ["0.000", "0.001", "0.002", "0.003", "0.004", "0.005", "0.006", "0.007", "0.008", "0.009"] cjglo_rate_list = ["0.00", "0.01", "0.02", "0.03", "0.04", "0.05"] # [str(0.1 * x) for x in xrange(1, 11)] #cjglo_rate_list = ["0.000", "0.001", "0.002", "0.003", "0.004", "0.005", "0.006", "0.007", "0.008", "0.009"] #run_control_by_list(prefix, sentence_rate_list) window_size_list = ["5", "10"] run_experiment_by_list(prefix, window_size_list, sentence_rate_list, cjglo_rate_list) if __name__ == '__main__': main()<file_sep> import WordVecDict if __name__ == '__main__': #vecFile = "output/batch_02/exp_s_0.05_c_0.05.vec.txt" vecFile = "cjboc_output/batch_01/exp_s_0.05_c_0.05.cjboc.txt" #wordVecDict = WordVecDict.WordVecDict("output/vocab.cj_001", "output/batch_02/ctrl_s_0.03.vec.txt") wordVecDict = WordVecDict.WordVecDict("output/vocab.cj_001", ) while True: print "Input w0 w1:" line = raw_input() print wordVecDict.analogy(line.split(), True)<file_sep>""" Count the sentence lenth of a parsed (after word segmentation) corpus. """ import argparse def count_length(): parser = argparse.ArgumentParser() parser.add_argument('--corpus_file', default='train.js_parsed', type=str) args = parser.parse_args() fin = open(args.corpus_file) dic = {} for line in fin: length = len(line.split()) dic[length] = dic.get(length, 0) + 1 return dic if __name__ == '__main__': dic = count_length() print dic
f9bf5d0c7076d5152ce483f9c16bbe2217d879a0
[ "Markdown", "C", "Python", "Makefile" ]
22
C
jileiwang/CJ-Glo
e2c9ecf040bcc31276ba1d122327e0f0c5b46744
9e0459dc82156980fefa45457126db094ed81aa5
refs/heads/master
<file_sep>require_relative 'item_basic' class NormalItem include ItemBasic def update_quality in_date? ? lost_quality = 1 : lost_quality = 2 lost_quality = @quality if @quality - lost_quality < 0 @quality -= lost_quality end def update_sell_in @sell_in -= 1 end private def in_date? @sell_in >= 0 end end <file_sep>require_relative 'item_basic' class GrowItem include ItemBasic def update_quality @quality - lost_quality > 50 ? quality = @quality -50 : quality = lost_quality @quality -= quality end def update_sell_in @sell_in -= 1 end private def lost_quality sell_in < 0 ? -2 : -1 end end <file_sep>require 'normal_item' require 'item_basic' describe NormalItem do let(:subject) {NormalItem.new("A normal item",10,20)} it_behaves_like ItemBasic it 'decreases quality by 1 when in date' do expect{subject.update_quality}.to change{subject.quality}.by(-1) end it 'decreases quality by 2 when not in date' do subject.sell_in = -1 expect{subject.update_quality}.to change{subject.quality}.by(-2) end it 'can not have a negative quality' do subject.quality = 0 expect{subject.update_quality}.to change{subject.quality}.by(0) end it 'changes sell_in by -1' do expect{subject.update_sell_in}.to change{subject.sell_in}.by(-1) end end <file_sep>require 'legendary' require 'item_basic' describe Legendary do let(:subject) {Legendary.new("A legendary item",0,80)} it_behaves_like ItemBasic it 'never changes quality' do expect{subject.update_quality}.to change{subject.quality}.by(0) end it 'changes sell_in by 0' do expect{subject.update_sell_in}.to change{subject.sell_in}.by(0) end end <file_sep>require 'unnormal_item' require 'item_basic' describe GrowItem do let(:subject) {GrowItem.new("An appriciating item",40,20)} it_behaves_like ItemBasic it 'increases in quality by 1 when in date' do subject.sell_in = 0 expect{subject.update_quality}.to change{subject.quality}.by(1) end it 'increases in quality by 2 when not in date' do subject.sell_in = -1 expect{subject.update_quality}.to change{subject.quality}.by(2) end it 'never raises quality to above 50' do subject.quality = 50 expect{subject.update_quality}.to change{subject.quality}.by(0) end it 'raises quality from 49 to 50' do subject.quality = 49 subject.sell_in = -1 expect{subject.update_quality}.to change{subject.quality}.by(1) end it 'changes sell_in by -1' do expect{subject.update_sell_in}.to change{subject.sell_in}.by(-1) end end <file_sep>require 'item_basic' shared_examples_for ItemBasic do it { is_expected.to respond_to :name } it { is_expected.to respond_to :quality } it { is_expected.to respond_to :sell_in } end <file_sep>require_relative 'item_basic' class Ticket include ItemBasic def update_quality @quality - lost_quality > 50 ? quality = @quality - 50 : quality = lost_quality @quality -= quality end def update_sell_in @sell_in -= 1 end private def in_10_days @sell_in <= 10 end def in_5_days @sell_in <= 5 end def lost_quality in_10_days ? lost_quality = -2 : lost_quality = -1 in_5_days ? lost_quality = -3 : 0 sell_in < 0 ? lost_quality = @quality : lost_quality end end <file_sep>require_relative 'item_basic' class Legendary include ItemBasic def update_quality @quality end def update_sell_in @sell_in end end <file_sep>require 'gilded_rose' require 'item' describe GildedRose do let(:item) { (double :item, update_quality: true, update_sell_in: -1) } let(:subject) {GildedRose.new([item])} it 'calls update_quality on the items' do expect(item).to receive(:update_quality) subject.update_quality end it 'calls update_sell_in on the items' do expect(item).to receive(:update_sell_in) subject.update_quality end end <file_sep>require 'ticket' require 'item_basic' describe Ticket do let(:subject) {Ticket.new("A ticket",10,20)} it_behaves_like ItemBasic it 'increases quality by 1 when more than 10 days till event' do subject.sell_in = 11 expect{subject.update_quality}.to change{subject.quality}.by(1) end it 'increases quality by 2 when less than 10 days till event' do subject.sell_in = 10 expect{subject.update_quality}.to change{subject.quality}.by(2) end it 'increases quality by 3 when less than 5 days till event' do subject.sell_in = 5 expect{subject.update_quality}.to change{subject.quality}.by(3) end it 'sets quality to 0 after event' do subject.quality = 20 subject.sell_in = -1 expect(subject.update_quality).to eq 0 end it 'does not let quality exceed 50' do subject.quality = 50 expect{subject.update_quality}.to change{subject.quality}.by(0) end it 'changes sell_in by -1' do expect{subject.update_sell_in}.to change{subject.sell_in}.by(-1) end end <file_sep>require 'normal_item' class GildedRose attr_reader :items def initialize(items) @items = items end def update_quality @items.each do |item| item.update_quality item.update_sell_in end end end
5d0d0e5797dc097ff7d770c90c47db4d001e90da
[ "Ruby" ]
11
Ruby
kirillzabrodin/gilded-rose-project
3cfcb52456ad96e6a2fbc86d9d70013be85c8404
95d77b7567c5b0b5c32faf8471a1922d5bb1edab