branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>chendss/imageBed<file_sep>/src/script/upload.js
import BaseUpload from './baseUpload'
import { log, objToFormData } from '@/utils'
import { PostXhr } from '@/utils/baseRequest'
class UploadFile extends BaseUpload {
constructor() {
super()
this.dict = {
jd: 'https://api.uomg.com/api/image.jd',
qihu: 'https://api.uomg.com/api/image.360',
oss: 'https://api.169740.com/api/image.ali',
sousou: 'https://api.uomg.com/api/image.sogou',
weibo: 'https://api.uomg.com/api/image.sina',
baidu: 'https://api.uomg.com/api/image.baidu',
juejin: 'https://api.uomg.com/api/image.juejin',
}
this.type = 'oss'
}
get url () {
return this.dict[this.type]
}
changeType (type) {
this.type = type
}
formParams () {
let params = {
file: 'multipart',
}
return params
}
/**
* 上传文件到oss
*
* @param {*} file
* @memberof UploadFile
*/
async send (file, onprogress) {
const formParams = this.formParams(file)
const formData = objToFormData(formParams)
formData.append('Filedata', file)
const p = onprogress instanceof Function ? onprogress : function () { }
const res = await PostXhr.new(this.url).xhrSend(formData, p)
return res
}
}
export default UploadFile<file_sep>/src/script/baseUpload.js
class BaseUpload {
constructor() {
}
}
export default BaseUpload<file_sep>/src/utils/index.js
import Nedb from 'nedb'
import { isArray, pick, map, mergeWith, get as lodashGet, isEqual, isObject, set, sum } from 'lodash'
const href = window.location.href
export const log = function () {
console.log(...arguments)
}
/**
* 对象转表单数据
*
* @param {*} obj
* @returns
*/
export const objToFormData = function (obj) {
const source = obj || {}
const formData = new FormData()
for (let [name, val] of Object.entries(source)) {
formData.append(name, val)
}
return formData
}
/**
* 不会报错的json parse
*
* @param {*} obj
* @returns
*/
export const jsonpParse = function (obj) {
try {
return JSON.parse(obj)
} catch (error) {
return obj
}
}
export const toArray = function (source) {
let result = []
if (source instanceof Array) {
result = source
} else {
result = [source]
}
return result.filter(f => !['', null, undefined].includes(f))
}
/**
* 创建数据库对象
*
* @param {*} dbPath
* @returns
*/
export const dataset = function (dbPath) {
return new Nedb({
filename: dbPath,
autoload: true
})
}
/**
* 找到一个值
*
* @param {*} dict_
* @returns
*/
export const datasetFind = function (db, dict_) {
return new Promise((resolve) => {
db.findOne(dict_, (err, docs) => {
resolve(docs)
})
})
}
/**
* 生成随机数
*
* @param {number} [n=32]
* @returns
*/
export const random = function (n = 32) {
let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
let letter = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz'
let maxPos = chars.length
let result = ''
for (let i = 0; i < n; i++) {
result += chars.charAt(Math.floor(Math.random() * maxPos))
}
result = letter.charAt(Math.floor(Math.random() * letter.length)) + result
return result.substring(0, result.length - 1)
}
export const queryToObj = function (url_) {
const url = url_ || window.location.href
let result = {}
const urlSplit = url.split('?')
const len = urlSplit.length - 1
let queryParam = urlSplit[len] || ''
queryParam
.split('&')
.filter(str => str !== '')
.forEach(str => {
const [key, value] = str.split('=')
result[key] = value
})
return result
}
export const objToQuery = function (obj) {
let strList = []
Object.entries(obj).forEach(entries => {
const [key, value] = entries
strList.push(`${key}=${value}`)
})
return encodeURIComponent(strList.join('&'))
}
/**
* lodash的 get函数超集,当取得值为null、 null、undefined,''将返回默认值
* path支持数组,会依次选取优先级高的放前面
* @static
* @param {object} obj 源数据
* @param {string|array} path 参数路径
* @param {*} defaultValue 默认值
* @returns
*
*/
export const get = function (obj, path, defaultValue) {
let value = null
const rules = [null, 'null', '', undefined]
const pathList = toArray(path)
for (let p of pathList) {
value = lodashGet(obj, p + '', null)
if (!rules.includes(value)) {
return value
}
}
return defaultValue
}
export const dpi = function (dom) {
let dx = window.innerWidth / 1920
dx = Math.max(dx * 0.9, 1)
const fontSize = Number(getComputedStyle(dom).fontSize.replace('px', ''))
const size = Math.ceil(fontSize * dx)
const style = dom.getAttribute('style') || ''
dom.setAttribute('style', style + `font-size:${size}px;`)
}
export const isInViewPort = function (el) {
// viewPortHeight 兼容所有浏览器写法
const viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
const offsetTop = el.offsetTop
const scrollTop = document.documentElement.scrollTop
const top = offsetTop - scrollTop
return top <= viewPortHeight + 100
}
/**
* 动态加载js
*
* @param {Object} srcDict src的字典
*/
export const createScriptFormRemote = function (srcDict) {
for (let key of Object.keys(srcDict)) {
if (document.querySelector(`#${key}`) == null) {
const src = srcDict[key]
const script = document.createElement('script')
script.type = 'text/javascript'
script.src = src
script.id = key
document.head.appendChild(script)
}
}
}
/**
* 字符串模板转换 ,将数据源对应{键}的值填入str
*
* @param {*} str 字符串
* @param {*} source 数据源
* @param {*} handle 处理函数
* @returns
*/
export const strFormat = function (str, source, handle = () => { }) {
if (str instanceof Function) {
return str(source)
} else if (!isObject(source)) {
return str
}
const data = { ...source }
const r = /{[^}]+}/
while (r.test(str)) {
const key = str
.match(r)
.toString()
.replace('{', '')
.replace('}', '')
const value = get(data, key, [])
const ids = toArray(value).filter(id => id != null)
str = str.replace(r, ids.join(','))
handle(key, value)
}
return str
}
/**
* 等待一段时间
*
* @param {*} time
* @returns
*/
export const sleep = async function (time) {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, time)
})
}
export const openLoading = function () {
const loading = document.querySelector('#loading')
loading.classList.remove('none')
}
export const closeLoading = function () {
const loading = document.querySelector('#loading')
loading.classList.add('none')
}
/**
* 将html插入body
*
* @param {*} html
*/
export const insertBody = function (html) {
document.querySelector('body').insertAdjacentHTML('beforeend', html)
}
/**
* 空间两点之间的距离
*
* @param {*} [point1=[]]
* @param {*} [point2=[]]
* @returns
*/
export const pointDistance = function (point1 = [], point2 = []) {
let result = 0
for (let i = 0; i < point1.length; i++) {
const x1 = point1[i]
const x2 = point2[i]
const x = x2 - x1
const value = Math.pow(x, 2)
result += value
}
return Math.sqrt(result)
}
/**
* lodash 的 mergeRight 改造,将会选择为null,undefined的值
*
* @returns
*/
export const merge = function () {
return mergeWith(...arguments, (obj, source) => {
if ([obj, source].some(item => [null, undefined].includes(item))) {
return obj || source
} else if ([obj, source].every(item => item instanceof Array)) {
const objLen = get(obj, 'length', 0)
const sourceLen = get(source, 'length', 0)
if (objLen !== sourceLen) {
return source
}
}
})
}
export const jsonParse = function (obj) {
try {
return JSON.parse(obj)
} catch (error) {
return obj
}
}
/**
* 文本转dom树
*
* @param {*} data
* @returns {Document}
*/
export const textToDom = function (data) {
const p = new DOMParser()
const Html = p.parseFromString(data, 'text/html')
return Html
}
/**
* iframe式请求
*
* @param {*} url
* @param {*} callback
* @returns
*/
export const iframeRequest = function (url, wait) {
const body = document.body
const iframe = document.createElement('iframe')
iframe.src = url
body.appendChild(iframe)
return new Promise((resolve) => {
iframe.onload = async () => {
try {
const win = iframe.contentWindow
const doc = win.document
if (wait instanceof Function) {
await wait(doc, win)
}
resolve({ doc, win })
} catch (error) {
console.log('报错了', error, url)
resolve(null)
} finally {
setTimeout(() => {
iframe.remove()
}, 500)
}
}
})
}
/**
* 选中元素
*
* @param {string} s
* @returns {HTMLElement}
*/
export const q = function (s) {
return document.querySelector(s)
}
export const qs = s => [...document.querySelectorAll(s)]
export const e = (dom, selector) => dom.querySelector(selector)
/**
* 相当于dom.querySelectorAll
*
* @param {*} dom
* @returns {Array<HTMLElementTagNameMap>}
* @param {*} selector
*/
export const es = (dom, selector) => [...dom.querySelectorAll(selector)]
/**
* 清空cookies
*
*/
export const clearCookie = function () {
var keys = document.cookie.match(/[^ =;]+(?=\=)/g)
let domainArray = ['.dtyunxi.cn', '.dtyunxi.com']
if (keys) {
for (var i = keys.length; i--;) {
document.cookie = keys[i] + '=0;path=/;expires=' + new Date(0).toUTCString()
document.cookie = keys[i] + '=0;path=/;domain=' + document.domain + ';expires=' + new Date(0).toUTCString()
domainArray.forEach(domain => {
document.cookie = keys[i] + `=0;path=/;domain=${domain};expires=` + new Date(0).toUTCString()
})
}
}
}
export const average = function (list) {
if (list instanceof Array) {
const total = sum(list.map(i => typeof i === 'number' ? i : Number(i)))
const len = list.length
return Math.floor(total / len)
} else {
return 0
}
}
/**
* 判断是否移动端
*
* @returns
*/
export const isMobile = function () {
let info = navigator.userAgent
let agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPod', 'iPad']
for (let i = 0; i < agents.length; i++) {
if (info.indexOf(agents[i]) >= 0) return true
}
return false
}<file_sep>/webpack/config.js
const path = require('path')
module.exports = {
port: 6629,
publicPath: './',
devtool (env) {
return env === 'loc' ? 'cheap-module-source-map' : false
},
watch (env) {
return env === 'loc'
},
watchOptions () {
return {
// 只有开启监听模式watchOptions才有意义
ignored: /node_modules/, // 不监听的文件或者文件夹,默认为空,支持正则匹配。
// 监听到变化发生后,会等300ms再去执行更新,默认是300ms
aggregateTimeout: 300,
poll: 1000, // 判断文件是否发生变化,是通过不停的询问系统指定文件有没有发生变化实现的,默认每秒问1000次。
}
},
mode (env) {
return env === 'loc' ? 'development' : 'production'
},
optimization (env) {
if (env === 'prod') {
return {
concatenateModules: true,
splitChunks: {
chunks: 'all',
},
usedExports: true
}
}
return undefined
}
}<file_sep>/README.md
# 图床项目
[TOC]
有兴趣的同学可以去给我的图床项目点个**start** [⭐⭐⭐⭐⭐](https://github.com/chendss/imageBed)
本项目旨在整个互联网的免费的图床,整合上传, 也借此项目使用 webpack4 从零搭建一个项目,看此文的朋友我希望你拥有基础的 webpack 相关知识,包括但不限于 如何初始化一个项目、npm 是什么、yarn 是什么、webpack 基本配置、前端模块化,现在正文开始。
项目截图


## 一、webpack 理论
### 1、webpack 是个啥
- webpack 是一个模块打包器(bundler)。
- 在 webpack 看来, 前端的所有资源文件(js/json/css/img/less/...)都会作为模块处理
- 它将根据模块的依赖关系进行静态分析,生成对应的静态资源
### 2. 五个核心概念
- Entry:入口起点(entry point)指示 webpack 从哪个文件开始。
- Output:output 属性告诉 webpack 把输出文件放在哪里,输出的叫什么名字。
- Loader:loader 的概念其实非常简单,就是一个字符串处理函数,把**less、sass**之类的文件转成**css**。
- Plugins:插件则可以用于执行范围更广的任务。插件的范围包括,从打包优化和压缩,一直到重新定义环境中的变量等。
- Mode:模式,有生产模式 production 和开发模式 development
#### 理解 Loader
简单来说,就是处理代码、资源文件的
- webpack 本身只能加载**js**、**json**模块,如果要加载其他类型的文件(模块),就需要使用对应的 loader 进行转换/加载
- Loader 本身也是运行在 node.js 环境中的 JavaScript 模块
- 它本身是一个函数,接受源文件作为参数,返回转换的结果
- loader 一般以 xxx-loader 的方式命名,xxx 代表了这个 loader 要做的转换功能,比如 json-loader。
#### 理解 Plugins
用来扩展 webpack 功能的
- 插件可以完成一些 loader 不能完成的功能。
- 插件的使用一般是在 webpack 的配置信息 plugins 选项中指定。
### 关于**webpack.config.js**
很多文章都在说这个文件是 webpack 的配置文件,其实不能这样说,因为这个文件其实可以随便命名,即使我把它命名**xxxx.js**也是可以的,现在假设项目里有个文件,路径在**src/test.js**里面的内容是 webpack 的配置,那么我们依然可以通过 `webpack --config src/test.js` 命令启动 webpack
### 3、webpack 工作流程
其实它简化之后就是那么简单而已,一个文本处理器

## 二、如何从零写一个 webpack
其他配置其实是大同小异的,本文拿**scss**、**原生 js**来举例
### 1、环境与 webpack 编译
项目一定是分环境的,所以我们应该根据环境将文件分开
- 在**webpack**文件夹创建文件**webpack.config.dev.js**表示开发环境的配置
- 在**webpack**文件夹创建文件**webpack.config.prod.js**表示生产环境的配置
然而我们知道这两个环境的配置大多数是相同的,所以为了避免重复,我们创建一个文件**webpack.config.base.js**,表示公共配置
现在我们把注意点收缩,只关注开发环境先,等开发环境配置完成,我们再抽象一个生产环境的配置,然后再抽象公共配置 **webpack.config.dev.js**
```javaScript
// in webpack.config.dev.js
const path = require('path')
const {
resolve
} = path
module.exports = {
entry: resolve(__dirname, '../src/index.js'),
output: {
filename: 'bundle.js',
path: resolve(__dirname, '../dist')
},
mode: 'development',
}
```
关于 上述代码解释 如下
- **entry** 入口代码,这里只需要一个文件
- **output** 输入目录的文件
- `__dirname` 执行文件的路径,它是 node 执行的时候注入的变量,例如 webpack --config xx/xx/xx.js 那么 dirname 就是 xx/xx
### 2、配置 webpack 过程
#### 最简单的 webpack 配置
到这里,最简单的**webpack**配置已经完成,我们在**package.json**添加**script**命令**dev**,具体如下

```shell
webpack --config webpack/webpack.config.dev.js
```
然后执行 `npm run dev` ,但是光这样不行,因为当 dist 的文件越来越多,很容易残留,所以我们需要将其缓存清空
清空一个文件夹的**shell**命令是 `rm -rf dist` ,但是注意这个命令在 linux 是无法正确执行的,因为在 linux 上要 sudo 提权,所以我们需要一个包来磨平这种差异,这里推荐用**rimraf**, 所以我们在 scirpt 新增一条命令 clean,代码如下
```shell
rimraf dist/*
```

这样当我们每次执行 `npm run dev` 时,代码就会生成,
#### 自动监听文件变化
接下来遇到一个问题,每次修改文件都需要重新执行一次命令,这样很麻烦,我希望文件更新便自动刷新 所以我们需要在 webpack 配置中配置 watch 和 watchOptions
```javaScript
// in webpack.config.dev.js
module.exports = {
...其他,
watch: true,
watchOptions: {
// 只有开启监听模式watchOptions才有意义
ignored: /node_modules/, // 不监听的文件或者文件夹,默认为空,支持正则匹配。
aggregateTimeout: 300, // 监听到变化发生后,会等300ms再去执行更新,默认是300ms
poll: 1000, // 判断文件是否发生变化,是通过不停的询问系统指定文件有没有发生变化实现的,默认每秒问1000次。
},
}
```

##### 如何自动打开浏览器并且热更新
如此我们就可以代码一修改编译就自动运行了。但是还是需要手动刷新页面,有没有办法自动刷新页面呢,那当然是有的
我们分解一下需求
- 自动打开浏览器
- 代码修改页面热更新
一个一个来,**自动打开浏览器**
```javaScript
// in webpack.config.dev.js
module.exports = {
devServer: {
hot: true,
hotOnly: true,
port: config.port,
contentBase: path.resolve(__dirname, '../dist/'),
},
}
```
其中需要注意的是,这样打开浏览器是看不到任何东西的,因为平时我们开发项目的时候打开浏览器能看得见东西是因为有一个 webpack 服务器,所以还需要做两件事
- 配置 html 模版
- 配置 webpack 服务器
###### 配置 html 模版
是什么意思呢,就是配置一个 html 文件,做为母版,在母版里面配置加载的 js 文件、样式文件等等,也是作为浏览器访问的 html 文件,我们得借助一个插件完成这件事(不是说不用插件就做不了,当然也是可以做的,后面会讲手动实现的思路) **html-webpack-plugin**
```javaScript
// in webpack.config.dev.js
const htmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
...其他,
plugins: [
...其他,
new htmlWebpackPlugin({
filename: 'index.html',
title: '图床',
showErrors: true,
publicPath: config.publicPath, // 这个可以作为变量塞到母版里
template: path.join(__dirname, '../src/index.html')
})
]
}
```
这样编译后使得 dist 里多一个文件 **index.html**,到此我们的模版就做好了
###### 搭建 webpack 本地服务器
这个东东其实是浏览器打开 localhost:xx 的时候访问资源所需要的承载,这个不需要太在意,就记住要一个服务器就好了。
我们一开始都是使用 webpack --config xx 来执行 webpack 构建过程的,到这里我们需要换一个库,就是让 webpack 带服务器运行的插件,**webpack-dev-serve**,至此我们的**package.json**的 script 代码修改为
```json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "npm run clean && webpack-dev-server --config webpack/webpack.config.dev.js --open",
"clean": "rimraf dist/*"
}
```
这样浏览器打开之后就可以看到**index.html**的内容了
我们到现在完成了以下的功能
- 可以自动打开浏览器,运行在 webpack 服务器 (**webpack-dev-serve**+**html-webpack-plugin**)
- 自动监听文件变化,自动编译 (配置 watch)
整个项目的配置到现在如下
```javaScript
// in webpack.config.dev.js
const path = require('path')
const webpack = require('webpack')
const htmlWebpackPlugin = require('html-webpack-plugin')
const templateHtmlPlugin = function() {
return new htmlWebpackPlugin({
filename: 'index.html',
title: '图床',
showErrors: true,
publicPath: './',
template: path.join(__dirname, '../src/index.html')
})
}
module.exports = {
entry: path.resolve(__dirname, '../src/index.js'),
watch: true,
watchOptions: {
// 只有开启监听模式watchOptions才有意义
ignored: /node_modules/, // 不监听的文件或者文件夹,默认为空,支持正则匹配。
// 监听到变化发生后,会等300ms再去执行更新,默认是300ms
aggregateTimeout: 300,
poll: 1000, // 判断文件是否发生变化,是通过不停的询问系统指定文件有没有发生变化实现的,默认每秒问1000次。
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
templateHtmlPlugin(),
],
devServer: {
hot: true,
port: 3108,
contentBase: path.resolve(__dirname, '../dist/'),
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, '../dist'),
},
mode: 'development,
}
```
```json
// in package.json
{
"name": "imagebed",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "npm run clean && cross-env-shell ENV=loc webpack-dev-server --config webpack/webpack.config.dev.js --open",
"clean": "rimraf dist/*"
},
"repository": {
"type": "git",
"url": "none"
},
"author": "",
"license": "ISC",
"devDependencies": {
"cross-env": "^7.0.2",
"html-webpack-plugin": "^4.2.1",
"open-browser-webpack-plugin": "^0.0.5",
"rimraf": "^3.0.2",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
},
"dependencies": {
"axios": "^0.19.2",
"jquery": "^3.5.0",
"lodash": "^4.17.15"
}
}
```
### 3、处理非 js 文件的 loader
一个前端项目里不可能只有 js 文件,我们还会有**css**文件,**字体**文件,**图片**文件等资源文件,接下来我们就一步步处理这些资源。
#### 处理 css 与预编译样式问题
如果项目不需要预处理器,这个部分可以跳过
预处理有好几个,像**less**、**sass**等等,配置方法大同小异,这里只讲**sass**的配置
在把 sass 纳入项目我们需要两个东西
- sass 引擎 - 因为 sass 以及自成一套体系,几乎可以作为一个新的语言
- sass-loader - webpack 如何解析 sass、scss 文件就靠这个 loader
#### sass 引擎
这个简单,直接安装就是,但是在安装时会遇到安装问题, 如下安装方法即可
```shell
npm install --save-dev node-sass --registry=https://registry.npm.taobao.org
```
#### 关于 sass 的 loader
市面上普遍是使用 **sass-loader** 但是它很慢,所以我们为了更好的性能可以使用 **fast-sass-loader**, sass 处理完就得处理 css,同样的为了性能使用 **fast-css-loader**,**style-loader**
```shell
npm install fast-sass-loader fast-css-loader style-loader --save-dev
```
然后就可以配置 webpack 了, 因为以后项目还会有很多的 loader,所以不希望太多代码聚集在同一个文件里,创建文件 **webpack\module.js**
```javaScript
// in module.js
module.exports = function() {
return {
rules: [{
test: /\.scss$/,
exclude: /node_modules/,
loader: [
'style-loader',
'fast-css-loader',
'fast-sass-loader',
]
}, ]
}
}
```
```javaScript
// in webpack.config.dev.js
const moduleConfig = require('./module')
module.exports = {
module: moduleConfig(),
}
```
这样我们的 sass 文件就可以被 webpack 识别,并且在页面生效了,那么能不即用**sass**又用**less**呢,当然是可以的,只要两个 loader 就可以了,(项目里最好不要用两个,为了技术栈统一,现在是为了展示 loader 是如何使用的)
##### 如何让项目即支持 sass 也支持 less
less 没有自成一个体系,所以不需要引擎,只需要 loader 就可以了
```shell
npm install less less-loader --save-dev
```
然后配置 module.js
```javaScript
rules: [{
test: /\.(less|css)$/,
loader: [
'style-loader',
'fast-css-loader',
'less-loader'
]
}],
```
然后我们的项目就两种都支持了
### 3、如何做热更新
现在项目的代码修改是会引起浏览器刷新的,如果希望不刷新也能更新代码,则需要继续配置
```javaScript
// in webpack.config.dev.js
module.exports = {
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // +
new OpenBrowserPlugin({
url: `http://localhost:${config.port}`
}),
templateHtmlPlugin(),
],
devServer: {
hot: true,
hotOnly: true, // +
port: config.port,
contentBase: path.resolve(__dirname, '../dist/'),
},
}
```
### 4、查看各个包在项目所占的大小
```shell
npm install webpack-bundle-analyzer --save-dev
```
```javaScript
// in webpack.config.dev.js
const {
BundleAnalyzerPlugin
} = require('webpack-bundle-analyzer'); //打包内容分析
module.exports = {
plugins: [
// 其他
new BundleAnalyzerPlugin({
analyzerPort: 8919
}),
],
}
```
### 5、希望编译的时候带进度
```shell
npm install progress-bar-webpack-plugin --save-dev
```
```javaScript
// in webpack.config.dev.js
const ProgressBarPlugin = require('progress-bar-webpack-plugin')
module.exports = {
plugins: [
// 其他
new ProgressBarPlugin(),
],
}
```
### 6、分离 css 文件
现在我们的样式文件都是挤在 js 里面,我们希望样式文件可以分离出去,我们使用 **mini-css-extract-plugin**插件
```shell
npm install mini-css-extract-plugin --save-dev
```
```javaScript
// in webpack.config.dev.js
const miniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
plugins: [
// 其他
new miniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[id].[hash].css',
}),
],
module: {
rules: [{
test: /\.scss|scss|css$/,
exclude: /node_modules/,
use: [
MiniCssExtractPlugin.loader,
'fast-css-loader',
'fast-sass-loader'
]
},
{
test: /\.(less|css)$/,
use: [
MiniCssExtractPlugin.loader,
'fast-css-loader',
'less-loader'
]
},
]
}
}
```
#### 友好的错误提示
插件**friendly-errors-webpack-plugin**
#### 静态资源拷贝
**copy-webpack-plugin**
```javaScript
new CopyWebpackPlugin([
{
from: resolve('static'),
to: '地址'
},
]),
```
#### 抽离文件大的包
例如 jquery 体积很大,可以单独取出来,在 webpack4 里很容易配置就可以满足
```javaScript
// in webpack.config.dev.js
module.exports = {
optimization:{
concatenateModules: true,
splitChunks: {
chunks: 'all',
},
usedExports: true
}
}
```
希望上述几个例子可以理解 **plugins**和**loader**的作用
### 6、执行环境
我们知道每个项目都区分环境,我们希望不同环境下 webpack 的配置有些不同,比如开发环境就没必要压缩了,这个时候我们需要一个变量可以区分环境,这里就要引入**cross-env**,安装之后在 _package.json_ 的 script 中 dev 命令中改成
```shell
npm install cross-env --save-dev
```
```json
"scripts": {
"dev": "cross-env-shell ENV=loc webpack --config webpack/webpack.config.dev.js", // 相对于给 process.env 注入一个变量ENV为loc
"clean": "rimraf dist/*"
}
```
现在仅仅是拥有了可以区分环境的能力,生产环境跟开发环境有几个点的区别
#### 压缩 css
压缩 css 也是要用到额外的插件**optimize-css-assets-webpack-plugin**、**cssnano**
```shell
npm install OptimizeCssAssetsPlugin --save-dev
```
```javaScript
// in webpack.config.dev.js
const cssnano = require('cssnano')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
module.exports = {
plugins: [
// 其他
new OptimizeCSSAssetsPlugin({
assetNameRegExp: /\.css\.*(?!.*map)/g, //注意不要写成 /\.css$/g
cssProcessor: cssnano,
cssProcessorOptions: {
discardComments: { removeAll: true },
safe: true,
autoprefixer: false
},
canPrint: true
}),
],
}
```
#### 将用不到的 css 删除
很多时候我们的样式是有大量用不上的,这样我们就可以使用两个插件将这些样式去掉
```javaScript
const purifycssWebpack = require('purifycss-webpack');
const glob = require('glob')
// ...其他代码
new purifycssWebpack({
paths: glob.sync(模板html的地址)
})
```
#### 压缩 js
简单配置即可
```javaScript
// in webpack.config.dev.js
const cssnano = require('cssnano')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
module.exports = {
optimization: {
concatenateModules: true,
splitChunks: {
chunks: 'all',
},
usedExports: true
}
},
}
```
### 8、babel 是个什么东西
首先要说明的是,现在前端流行用的 WebPack 或其他同类工程化工具会将源文件组合起来,这部分并不是 Babel 完成的,是这些打包工具自己实现的,Babel 的功能非常纯粹,以字符串的形式将源代码传给它,它就会返回一段新的代码字符串(以及 sourcemap)。他既不会运行你的代码,也不会将多个代码打包到一起,它就是个编译器,输入语言是 ES6+,编译目标语言是 ES5。
#### babel 简介
babel 实际上类似一般的的语言编译器,作用就是输入输入代码,实际上跟很多人理解的不太一样,babel 并不是只能用于 ES6 编译成 ES5,只要你愿意,你完全可以把 ES5 编译成 ES6,或者使用自己创造的某种语法(例如 JSX,以及本文结合的 babel 插件就属于这类),你需要做的只是编写对应的插件。
#### bable 原理解析
Babel 的编译过程跟绝大多数其他语言的编译器大致同理,分为三个阶段:
1. **解析**:将代码字符串解析成抽象语法树
2. **变换**:对抽象语法树进行变换操作
3. **再建**:根据变换后的抽象语法树再生成代码字符串
一句话来说就是,字符串转成另一种字符串而实现的技术是用抽象语法树 **AST**(下面会稍微讲一下)
#### 迷惑的 AST
我们都知道 javascript 代码是由一系列字符组成的,我们看一眼字符就知道它是干什么的,例如变量声明、赋值、括号、函数调用等等。但是计算机并没有眼睛可以看到,它需要某种机制去理解代码字符串,基于此考虑为了让人和计算机都能够理解代码,就有了 AST 这么个东西,它是源代码的一种映射,在某种规则中二者可以相互转化,语言引擎根据 AST 就能知道代码的作用是什么。
简单来说就是有一个东西将代码映射成内存里一个对象,如图

这里简单举个例子 ,有兴趣深究的同学可以看[The ESTree Spec](https://github.com/estree/estree)。
## 三、最后
### 代码拆分
在项目中,webpack 的配置很多,为了后期的维护,作者提出一个拆分方案
- 在跟目录创建文件夹 **webpack** 将 webpack 的配置相关的代码移到此文件夹中
- 将 **loader** 与 **plugins** 单独抽离出来
- 将具有环境相关的并且通用的配置放在**config.js**里
所以现在代码就可以拆分成以下结构
```javaScript
// in config.js
const path = require('path')
module.exports = {
port: 6629,
publicPath: './',
devtool (env) {
return env === 'loc' ? 'cheap-module-source-map' : false
},
watch (env) {
return env === 'loc'
},
watchOptions () {
return {
// 只有开启监听模式watchOptions才有意义
ignored: /node_modules/, // 不监听的文件或者文件夹,默认为空,支持正则匹配。
// 监听到变化发生后,会等300ms再去执行更新,默认是300ms
aggregateTimeout: 300,
poll: 1000, // 判断文件是否发生变化,是通过不停的询问系统指定文件有没有发生变化实现的,默认每秒问1000次。
}
},
mode (env) {
return env === 'loc' ? 'development' : 'production'
},
optimization (env) {
if (env === 'prod') {
return {
concatenateModules: true,
splitChunks: {
chunks: 'all',
},
usedExports: true
}
}
return undefined
}
}
```
```javaScript
// in module.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const cssLoader = function (env) {
if (env === 'prod') {
return [MiniCssExtractPlugin.loader]
}
return ['style-loader']
}
const styleLoader = function (env) {
return [
{
test: /\.scss|scss|css$/,
exclude: /node_modules/,
use: [
...cssLoader(env),
'fast-css-loader',
'fast-sass-loader',
]
},
{
test: /\.(less|css)$/,
exclude: /node_modules/,
use: [
...cssLoader(env),
'fast-css-loader',
'less-loader'
]
},
]
}
module.exports = function (env) {
return {
rules: [
...styleLoader(env),
],
noParse: /jquery/
}
}
```
```javaScript
// in webpack.config.dev
const path = require('path')
const config = require('./config')
const plugins = require('./plugins')
const moduleConfig = require('./module')
const ENV = process.env.ENV
const distPath = path.resolve(__dirname, '../dist')
module.exports = {
plugins: plugins(ENV, config, distPath),
watchOptions: config.watchOptions(),
watch: config.watch(ENV),
module: moduleConfig(ENV),
devtool: config.devtool(ENV),
entry: path.resolve(__dirname, '../src/index.js'),
devServer: {
hot: true,
hotOnly: true,
port: config.port,
contentBase: distPath,
},
output: {
filename: '[name].[hash].bundle.js',
path: distPath,
},
optimization: config.optimization(ENV),
mode: config.mode(ENV),
}
```
```javaScript
// in plugins.js
const path = require('path')
const glob = require('glob')
const webpack = require('webpack')
const cssnano = require('cssnano')
const purifycssWebpack = require('purifycss-webpack')
const htmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const miniCssExtractPlugin = require('mini-css-extract-plugin')
const ProgressBarPlugin = require('progress-bar-webpack-plugin')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')//打包内容分析
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const friendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const templateHtmlPlugin = function (config) {
return new htmlWebpackPlugin({
filename: 'index.html',
title: '图床',
showErrors: true,
publicPath: config.publicPath,
template: path.join(__dirname, '../src/index.html')
})
}
const cssOptPlugin = function (env, config) {
const result = []
if (env === 'prod') {
result.push(new OptimizeCSSAssetsPlugin({
assetNameRegExp: /\.css\.*(?!.*map)/g, //注意不要写成 /\.css$/g
cssProcessor: cssnano,
cssProcessorOptions: {
discardComments: { removeAll: true },
safe: true,
autoprefixer: false
},
canPrint: true
}))
result.push(new miniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[id].[hash].css',
}))
}
return result
}
/**
* 处理没有用到的css
*
* @param {*} env
*/
const purifycss = function (env, distPath) {
if (env === 'prod') {
return [new purifycssWebpack({
paths: glob.sync(distPath)
})]
}
return []
}
const copyAction = function (env,distPath) {
let result = []
if (env === 'prod') {
result = [new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../src/static'),
to: distPath + '/static'
},
])]
}
return result
}
module.exports = function (env, config, distPath) {
const result = [
...cssOptPlugin(env),
new ProgressBarPlugin(),
templateHtmlPlugin(config),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new BundleAnalyzerPlugin({
analyzerMode: 'disabled', // 不启动展示打包报告的http服务器
generateStatsFile: true, // 是否生成stats.json文件 }),
}),
new friendlyErrorsWebpackPlugin(),
...purifycss(env, distPath),
...copyAction(env, distPath)
]
return result
}
```
至今为止,代码结构如下

### package.json 配置
```json
{
"name": "imagebed",
"version": "1.0.0",
"description": "本项目旨在整个互联网的免费的图床,整合上传,也借此项目使用webpack4从零搭建一个项目,看此文的朋友我希望你拥有基础的webpack相关知识,包括但不限于 如何初始化一个项目、npm是什么、yarn是什么、webpack基本配置、前端模块化,现在正文开始。",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"analyz": "webpack-bundle-analyzer --port 6919 ./dist/stats.json",
"dev": "npm run clean && cross-env-shell ENV=loc webpack-dev-server --config webpack/webpack.config.dev.js --open",
"build": "npm run clean && cross-env-shell ENV=prod webpack --config webpack/webpack.config.dev.js && npm run analyz",
"prod": "npm run clean && cross-env-shell ENV=prod webpack --config webpack/webpack.config.dev.js",
"clean": "rimraf dist/*"
},
"repository": {
"type": "git",
"url": "none"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.9.6",
"@babel/polyfill": "^7.8.7",
"@babel/preset-env": "^7.9.6",
"@babel/runtime": "^7.9.6",
"babel-loader": "^8.1.0",
"copy-webpack-plugin": "^5.1.1",
"cross-env": "^7.0.2",
"cssnano": "^4.1.10",
"fast-css-loader": "^1.0.2",
"fast-sass-loader": "^1.5.0",
"friendly-errors-webpack-plugin": "^1.7.0",
"glob": "^7.1.6",
"html-webpack-plugin": "^4.2.1",
"less": "^3.11.1",
"less-loader": "^6.0.0",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^4.14.0",
"open-browser-webpack-plugin": "^0.0.5",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"progress-bar-webpack-plugin": "^2.1.0",
"purify-css": "^1.2.5",
"purifycss-webpack": "^0.7.0",
"rimraf": "^3.0.2",
"style-loader": "^1.2.1",
"webpack": "^4.43.0",
"webpack-bundle-analyzer": "^3.7.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3",
"webpack-parallel-uglify-plugin": "^1.1.2"
},
"dependencies": {
"axios": "^0.19.2",
"jquery": "^3.5.0",
"lodash": "^4.17.15"
}
}
```
### 写在最后
写了那么多,大家应该对 webpack 有一定的认识,其实这些东西都很简单只是需要大家动手尝试,最好是将每个部分的东西分离出来,这样才不会混在一起,无法阅读。本文档是项目初期写的,后期项目有更新将不会同步文档,只要掌握原理就大同小异了。有兴趣的同学可以去给我的图床项目点个**start** [⭐⭐⭐⭐⭐](https://github.com/chendss/imageBed)
<file_sep>/webpack/plugins.js
const path = require('path')
const glob = require('glob')
const webpack = require('webpack')
const cssnano = require('cssnano')
const purifycssWebpack = require('purifycss-webpack')
const htmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const miniCssExtractPlugin = require('mini-css-extract-plugin')
const ProgressBarPlugin = require('progress-bar-webpack-plugin')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')//打包内容分析
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const friendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const templateHtmlPlugin = function (config) {
return new htmlWebpackPlugin({
filename: 'index.html',
title: '图床',
showErrors: true,
publicPath: config.publicPath,
template: path.join(__dirname, '../src/index.html')
})
}
const cssOptPlugin = function (env, config) {
const result = []
if (env === 'prod') {
result.push(new OptimizeCSSAssetsPlugin({
assetNameRegExp: /\.css\.*(?!.*map)/g, //注意不要写成 /\.css$/g
cssProcessor: cssnano,
cssProcessorOptions: {
discardComments: { removeAll: true },
safe: true,
autoprefixer: false
},
canPrint: true
}))
result.push(new miniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[id].[hash].css',
}))
}
return result
}
/**
* 处理没有用到的css
*
* @param {*} env
*/
const purifycss = function (env, distPath) {
if (env === 'prod') {
return [new purifycssWebpack({
paths: glob.sync(distPath)
})]
}
return []
}
const copyAction = function (env, distPath) {
let result = [
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../src/static'),
to: distPath + '/static'
},
{
from: path.resolve(__dirname, '../src/css'),
to: distPath + '/css'
},
])
]
return result
}
module.exports = function (env, config, distPath) {
const result = [
...cssOptPlugin(env),
new ProgressBarPlugin(),
templateHtmlPlugin(config),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new BundleAnalyzerPlugin({
analyzerMode: 'disabled', // 不启动展示打包报告的http服务器
generateStatsFile: true, // 是否生成stats.json文件 }),
}),
new friendlyErrorsWebpackPlugin(),
// ...purifycss(env, distPath),
...copyAction(env, distPath)
]
return result
}<file_sep>/serve/db.py
from tools import wirte_file, read_file, get
import pydash
class DB:
def __init__(self, path):
self.data = read_file(path)
self.path = path
def get(self, key):
result = get(self.data, key, None)
return result
def insert(self, key, value):
pydash.set_(self.data, key, value)
wirte_file(self.path, self.data)
def insert_list(self, key, values):
target = get(self.data, key, [])
target.extend(values)
self.insert(key, target)
<file_sep>/webpack/webpack.config.dev.js
const path = require('path')
const config = require('./config')
const plugins = require('./plugins')
const moduleConfig = require('./module')
const ENV = process.env.ENV
const distPath = path.resolve(__dirname, '../dist')
module.exports = {
plugins: plugins(ENV, config, distPath),
watchOptions: config.watchOptions(),
watch: config.watch(ENV),
module: moduleConfig(ENV),
devtool: config.devtool(ENV),
entry: path.resolve(__dirname, '../src/index.js'),
devServer: {
hot: true,
inline: true,
hotOnly: true,
compress: true,
port: config.port,
contentBase: distPath,
},
output: {
filename: '[name].[hash].bundle.js',
path: distPath,
},
resolve: {
alias: {
'@': path.resolve(__dirname, '../src'),
},
extensions: ['*', '.js', '.vue', '.json'],
},
optimization: config.optimization(ENV),
mode: config.mode(ENV),
}<file_sep>/serve/main.py
import json
import requests
from flask_cors import CORS
from db import DB
import random
import urllib3
from tools import is_phone, get, img_remote_size
from flask import Flask, redirect, abort, make_response, jsonify, send_file, request
app = Flask(__name__)
CORS(app, supports_credentials=True)
CORS(app, resources=r'/*')
dataset = DB('./data.json')
def api_param_parse(params):
api_param = params if params != None else {}
return api_param
def image_remote(ua):
"""
获得图片接口地址
"""
if is_phone(ua):
image = 'https://api.uomg.com/api/rand.img2?format=json'
else:
image = 'https://api.uomg.com/api/rand.img1?format=json'
return image
def img_list(is_phone_, image, count=1):
"""
根据数量获得随机图组
"""
result = []
while len(result) < int(count):
ir = requests.get(image, allow_redirects=False)
text = json.loads(ir.text)
img_url = get(text, 'imgurl', '')
min_size = 100 if is_phone_ else 200
if img_remote_size(img_url) > min_size:
result.append(img_url)
return result
@app.route('/img', methods=['GET'])
def get_img():
"""
获得图片
"""
ua = request.headers.get('User-Agent')
image = image_remote(ua)
api_param = api_param_parse(request.args)
count = get(api_param, 'count', '1')
is_phone_ = is_phone(ua)
key = 'image.phone' if is_phone_ == True else 'image.pc'
local_image = get(dataset.data, key, [])
result = []
if len(local_image) <= int(count):
result = img_list(is_phone_, image, count)
dataset.insert_list(key, result)
else:
result = random.sample(dataset.get(key), int(count))
return json.dumps(result)
if __name__ == '__main__':
app.run(
host='0.0.0.0',
port=6388,
debug=True
)
<file_sep>/src/utils/DB.js
class DB {
/**
* 从缓存提取值
*
* @static
* @param {string} key
* @returns
* @memberof DB
*/
static get (key) {
let localValue = localStorage.getItem(key)
return localValue ? JSON.parse(localValue) : null
}
/**
*
* 写入缓存
* @static
* @param {string} key 键
* @param {string} value 值
* @memberof DB
*/
static set (key, value) {
localStorage.setItem(key, JSON.stringify(value))
}
}
export default DB<file_sep>/src/utils/baseRequest.js
import { jsonpParse, log, get } from './index'
class XHR {
constructor(url, headers, method) {
this.url = url
this.method = method
this.headers = headers || {}
this.xhr = new XMLHttpRequest()
this.init()
}
/**
* 这样就可以链式调用节约一行代码
*
* @static
* @param {*} url
* @param {*} headers
* @returns
* @memberof XHR
*/
static new (url, headers) {
return new this(url, headers)
}
/**
* 父类初始化
*
* @memberof XHR
*/
init () {
this.xhr.timeout = 8000
this.xhr.open(this.method, this.url, true)
Object.keys(this.headers).forEach(key => {
const val = this.headers[key]
this.xhr.setRequestHeader(key, val)
})
}
_send (xhr, data) {
if (data == null) {
xhr.send()
} else {
xhr.send(data)
}
}
/**
* 请求发送
*
* @param {Object} data
* @returns
*/
xhrSend (data, onprogress) {
const xhr = this.xhr
xhr.withCredentials = false
return new Promise((resolve, reject) => {
xhr.onreadystatechange = event => {
const that = event.currentTarget
const status = that.status
if (that.readyState === 4) {
if ([200, 204].includes(status)) {
const response = jsonpParse(that.response)
resolve(get(response, 'data', response))
} else if (status === 403) {
resolve({ status, message: '没有权限' })
} else if (that.readyState === 4) {
reject({ status, body: that })
}
}
}
xhr.onprogress = onprogress
xhr.ontimeout = () => reject('请求超时')
xhr.onerror = reject
this._send(xhr, data)
})
}
}
class PostXhr extends XHR {
constructor(url, headers) {
super(url, headers, 'post')
this.xhr.timeout = 100 * 1000
}
send (data) {
this.xhrSend(data)
}
}
class GetXhr extends XHR {
constructor(url, headers) {
super(url, headers, 'get')
this.xhr.timeout = 100 * 1000
this.xhr.responseType = 'json'
}
send (data) {
return this.xhrSend(data)
}
}
export { PostXhr, GetXhr }
<file_sep>/src/index.js
import axios from 'axios'
import './styles/index.scss'
import config from '@/config'
import { Notyf } from 'notyf'
import UploadFile from './script/upload'
import ImageControl from './script/imageControl'
import { qs, log, q, es, get } from '@/utils/index'
import MicroModal from 'micromodal'
const notyf = new Notyf({ duration: 2000 })
const imgClick = function (id) {
MicroModal.show(id)
log('按摩', id)
}
const insertImg = function (url, file) {
const resultBox = q('#id-upload-result')
const id = get(file, 'lastModified', '')
resultBox.insertAdjacentHTML('beforeend', `
<div class="img-result-item" >
<img src="${url}" onclick="imgClick(${id})" id="${id}">
<p>${url} <strong>${get(file, 'name', '')}</strong></p>
</div>
`)
}
const inputEvent = function (upload) {
const input = q('#id-upload-btn input')
input.addEventListener('change', async () => {
log('change', input.files)
const uploadBtn = q('#id-upload-btn')
uploadBtn.setAttribute('d', 'true')
const file = input.files[0]
const res = await upload.send(file)
const url = get(res, ['url', 'imgurl'], null)
if (url == null) {
notyf.error('上传失败,请更换图床或者重新上传')
} else {
insertImg(url, file)
notyf.success('成功')
}
uploadBtn.setAttribute('d', '')
})
}
const main = async function () {
window.imgClick = imgClick
await ImageControl.new()
const upload = new UploadFile()
inputEvent(upload)
const typeBtn = q('#id-type-btn')
typeBtn.addEventListener('click', () => {
q('#id-drop').classList.toggle('none')
})
es(typeBtn, '.cy_btn').forEach(btn => {
btn.addEventListener('click', () => {
const input = q('#id-upload-btn input')
const type = btn.getAttribute('urltype')
upload.changeType(type)
input.outerHTML = '<input type="file" id="id-input-upload"></input>'
inputEvent(upload)
})
})
}
main() | 174a2d036e45644094188dbefa95da32d2fc304a | [
"JavaScript",
"Python",
"Markdown"
] | 12 | JavaScript | chendss/imageBed | edf9baa39d6cdca35ae21b480104e222dc62427e | 436fb429457d7ee8259916559d299e0c89f980a1 |
refs/heads/master | <repo_name>etoki/0726_biginning<file_sep>/README.md
# 0726_biginning
初めて書いたコード集
<file_sep>/bootstrap/app/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader, Context
def show_temp(request):
context = Context()
context.update(dict(metadata=request.META))
template = loader.get_template('bootstrap.html')
return HttpResponse(template.render(context))
<file_sep>/loginform/loginform/urls.py
from django.conf.urls import *
from app.views import *
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^registration/', registration),
url(r'^login/', login),
url(r'^forgot/', forgot),
]
<file_sep>/loginform/app/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader, Context
def registration(request):
context = Context()
context.update(dict(metadata=request.META))
template = loader.get_template('registration.html')
return HttpResponse(template.render(context))
def login(request):
context = Context()
context.update(dict(metadata=request.META))
template = loader.get_template('login.html')
return HttpResponse(template.render(context))
def forgot(request):
context = Context()
context.update(dict(metadata=request.META))
template = loader.get_template('forgot.html')
return HttpResponse(template.render(context))
| 77515e0b8201c3b39190e10e3d4cfb3954c26839 | [
"Markdown",
"Python"
] | 4 | Markdown | etoki/0726_biginning | 7c7f82312cfffbbddcfb32c2e507da01834b3a31 | 36564a00912317c8afe06b03a2f42fbb4bbe44dc |
refs/heads/master | <repo_name>Felipe-Borba/hello-world<file_sep>/README.md
# hello-world
In the editor, write a bit about yourself.
test of something
sadasdasdasd
asdasdas
<file_sep>/Codigo em c/teste.c
#include <stdio.h>
int main(void){
unsigned int in = 0x0f;
unsigned int out;
out = (in>>1);
printf("in: %x\n", in);
printf("out: %x\n", out);
return 0;
}
<file_sep>/Bank Management System.c
#include<stdio.h>
#include<stdlib.h>
#define NCAR 500
typedef struct _costumer {
char name[NCAR];
char date_of_birth[NCAR];
char citizenship_number[NCAR];
char address[NCAR];
char phone_number[NCAR];
char account_number[NCAR];
float saving;
float current;
struct _costumer *next;
} costumer;
costumer *first = NULL; /* = 0 ponteiro do primeiro elemento*/
void read_str(char *s, int n) { /* ler uma string */
fgets(s, n, stdin);
s[strlen(s)-1] = '\0';
}//le uma string iteira
void read_costumer(costumer *a) { /* ler um registo do cliente */
printf("Name: ");
read_str(a->name, NCAR);
printf("Date_of_birth: ");
read_str(a->date_of_birth, NCAR);
printf("Citizenship_number: ");
read_str(a->citizenship_number, NCAR);
printf("Address: ");
read_str(a->address, NCAR);
printf("Phone_number: ");
read_str(a->phone_number, NCAR);
printf("Account number: ");
read_str(a->account_number, NCAR);
if(a->saving==0 && a->current==0){
printf("Saving (insert 0 for not use this type of account): ");
scanf("%f", &a->saving);
printf("Current (insert 0 for not use this type of account): ");
scanf("%f", &a->current);
}
}//le os dados inseridos do cliente
void write_costumer(costumer *a) { /* escrever um registo de aluno */
printf("Nome: %s\n", a->name);
printf("date_of_birth: %s\n", a->date_of_birth);
printf("citizenship_number: %s\n", a->citizenship_number);
printf("address: %s\n", a->address);
printf("phone_number: %s\n", a->phone_number);
printf("account_number: %s\n", a->account_number);
printf("\n");
}
costumer* new_costumer(void) {
costumer *p;
p = (costumer*)malloc(sizeof(costumer));
p->next = NULL;
return p;
}//cria ponteiro para a estruct
void insert() { /* insere um novo registo no inicio da lista */
costumer *p;
char s[NCAR];
p = new_costumer();
read_str(s, NCAR);
read_costumer(p);
if(first == NULL)
first = p;
else {
p->next = first;
first = p;
}
}
costumer* search() {/* efectua a busca de um nome na lista */
costumer *p;
char s[NCAR];
printf("Nome a procurar? ");
read_str(s, NCAR);
read_str(s, NCAR);
p = first;
while(p != NULL && strcmp(p->name, s) != 0)
p = p->next;
if(p == NULL)
printf("customer not found/registered\n");
else {
write_costumer(p);
if(p->saving!=0)
printf("amount deposited: %f\n", p->saving);
else
printf("amount deposited: %f\n", p->current);
}
return p;
}
void erase() { /* elimina um registo da lista ligada */
costumer *p, *pa;
char resp;
p = search();
if(p == NULL)
return;
printf("wish remove (y,n)? ");
scanf(" %c", &resp);
if(resp =='y')
if(p == first) {
first = p->next;
free(p);
} else {
pa = first;
while(pa->next != p)
pa=pa->next;
pa->next = p->next;
free(p);
}
}
void list() {
costumer *p;
p = first;
while(p != NULL) {
write_costumer(p);
p=p->next;
}
}
void upadate(){
costumer *p;
p=search();
read_costumer(p);
//fazer função para saber se a string tiver vazia não muda
}//atualiza informações do cliente
void Transaction(){
costumer *p;
p=search();
int x=0;
if(p->saving!=0){
//printf("amount deposited: %d\n", p->saving);
printf("Deposit(+) or withdraw(-): ");
scanf("%d", &x);
p->saving +=x;
} else {
//printf("amount deposited: %d\n", p->current);
printf("Deposit or withdraw: ");
scanf("%d", &x);
p->current +=x;
}
}
void wait(){
char a;
printf("Press enter to continue...");
//scanf("%c",&a); //não faço ideia do pq tenho que colocar dois scanf
scanf(" %c",&a);
//printf("%c\n",a);
}
void menu (){
printf(" =====Bank Management System===== \n\n");
printf(" (1) Crate new account \n");
printf(" (2) Upadate information of existing account \n");
printf(" (3) Transactions \n");
printf(" (4) Check details of existing account \n");
printf(" (5) Remove account \n");
printf(" (6) View customers's list \n");
printf(" (7) Exit \n\n");
printf(" Enter your choice: ");
}
main(){
int choice;
int i=0;
while(1){
menu();
scanf("%d", &choice);
printf("\n");
switch(choice){
case 1:
insert();//função
wait();
break;
case 2:
upadate();//função
wait();
break;
case 3:
Transaction();//função
wait();
break;
case 4:
search();//função busca por um cliente
wait();
break;
case 5:
erase();//função remove
wait();
break;
case 6:
list();//função lista todos os clientes
wait();
break;
case 7:
printf("Exiting...\n");
return(0);
break;
default:
printf("Invalid option \n");
i++;
if(i>=100){
printf("Bad lock \n");
return(0);
}
}
}
} | 0e2f0d37a0ed5529d281b73fd8a04427bdfb3b02 | [
"Markdown",
"C"
] | 3 | Markdown | Felipe-Borba/hello-world | b7ca51d729521cc7addb2924cde9e6e9d095915f | 20e5cb411ab6bc2b02868d50cd44df0a5290acf8 |
refs/heads/master | <repo_name>bomek1/nowa_pem<file_sep>/nehisa/Form1.cs
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace nehisa
{
public partial class Form1 : Form
{
public proces proces1;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
textBox1.Text = of.FileName;
}
private void button2_Click(object sender, EventArgs e)
{
this.proces1 = new proces();
StreamReader sr = new StreamReader(textBox1.Text);
textBox2.Text = sr.ReadToEnd();
sr.Close();
string test;
int i, j;
int s;
char[] c = null;
c = new char[5];
StreamReader sr2 = new StreamReader(textBox1.Text);
test = sr2.ReadLine();
this.proces1.n = Convert.ToInt32(test);
this.proces1.NT = new Int32[this.proces1.n+1];
this.proces1.NM = new Int32[this.proces1.n+1];
this.proces1.P = new Int32[this.proces1.n+1];
test = sr2.ReadLine();
string[] exploded2 = test.Split(' ');
for (i = 1; i <= this.proces1.n; i++)
{
this.proces1.NT[i] = Convert.ToInt32(exploded2[i-1]);
}
test = sr2.ReadLine();
string[] exploded3 = test.Split(' ');
for (i = 1; i <= this.proces1.n; i++)
{
this.proces1.NM[i] = Convert.ToInt32(exploded3[i-1]);
}
test = sr2.ReadLine();
string[] exploded4 = test.Split(' ');
for (i = 1; i <= this.proces1.n; i++)
{
this.proces1.P[i] = Convert.ToInt32(exploded4[i-1]);
}
test = sr2.ReadLine();
this.proces1.m = Convert.ToInt32(test);
this.proces1.permutacja = new Int32[this.proces1.n + this.proces1.m];
test = sr2.ReadLine();
string[] exploded5 = test.Split(' ');
for (i = 0; i < this.proces1.n+this.proces1.m; i++)
{
this.proces1.permutacja[i] = Convert.ToInt32(exploded5[i]);
}
sr2.Close();
}
private void button3_Click(object sender, EventArgs e)
{
int i;
StreamWriter writer = new StreamWriter("wyniki1.txt");
for (i = 0; i < this.proces1.n; i++)
{
writer.Write(this.proces1.S[i]);
writer.Write(' ');
writer.WriteLine(this.proces1.C[i]);
}
writer.WriteLine(this.proces1.cmax);
writer.Close();
}
private void button4_Click(object sender, EventArgs e)
{
int i;
int a, b, c;
this.proces1.PT = new Int32[this.proces1.n+1];
this.proces1.PM = new Int32[this.proces1.n+1];
this.proces1.LP = new Int32[this.proces1.n+1];
for (i = 1; i <= this.proces1.n; i++)
{
this.proces1.PT[i] = 0;
this.proces1.PM[i] = 0;
this.proces1.LP[i]=0;
}
for(i=1; i<=this.proces1.n; i++)
{
a = this.proces1.NT[i];
if (a > 0)
{
this.proces1.PT[a] = i;
}
b = this.proces1.NM[i];
if (b > 0)
{
this.proces1.PM[b] = i;
}
}
for (i = 1; i <= this.proces1.n; i++)
{
if(this.proces1.PT[i]>0)
{
this.proces1.LP[i]++;
}
if (this.proces1.PM[i] > 0)
{
this.proces1.LP[i]++;
}
}
this.proces1.kolejnosc = new List<int>();
for (i = 1; i <= this.proces1.n; i++) //pierwsze przegladniecie
{
if (this.proces1.LP[i] == 0)
{
this.proces1.kolejnosc.Add(i);
}
}
i = 0;
while (this.proces1.kolejnosc.Count < this.proces1.n) //nie wiem czy może być taki warunek - w momencie jak nie będzie dało się ustalić koeljności się wysypie
{
a = this.proces1.kolejnosc[i];
b=this.proces1.NT[a];
c=this.proces1.NM[a];
this.proces1.LP[b]--;
if (this.proces1.LP[b] == 0)
{
this.proces1.kolejnosc.Add(b);
}
this.proces1.LP[c]--;
if (this.proces1.LP[c] == 0)
{
this.proces1.kolejnosc.Add(c);
}
i++;
}
b = 123;
this.proces1.C = new Int32[this.proces1.n];
this.proces1.S = new Int32[this.proces1.n];
for (i = 1; i < this.proces1.n; i++ )
{
if(this.proces1.LP[i]==0)
{
}
}
for (i = 0; i < this.proces1.n; i++)
{
this.proces1.C[i] = i;
this.proces1.S[i] = i;
}
this.proces1.cmax = 472057;
}
}
public class proces
{
public int n = 0;
public int m = 0;
public int[] NT;
public int[] NM;
public int[] PT;
public int[] PM;
public int[] LP;
public int[] P;
public int[] permutacja;
public List<Int32> kolejnosc;
public int[] C;
public int[] S;
public int cmax;
}
}
| efeb6b62402db4fdca052458f9c2d5777f79be16 | [
"C#"
] | 1 | C# | bomek1/nowa_pem | 9d240cc75e231b48fbfae04752ad03dfce32c3f1 | 33ec403b236454ab85dbd01f031f63392055c6be |
refs/heads/master | <repo_name>st55425/NNPIA_React_Todo<file_sep>/src/components/TodoItem.js
export default function TodoItem({item, onClickHandler}) {
return (
<div className="border d-flex flex-row itemContainer mx-auto">
<p className="item">{item.name}</p>
{!item.completed && <button className="btn btn-danger" onClick={() => onClickHandler(item)}>Complete</button>}
{item.completed && <button className="btn btn-secondary" onClick={() => onClickHandler(item)}>Revert</button>}
</div>
)
}<file_sep>/README.md
## Jednoduchá TODO aplikace
- Napsáno v Reactu, ke stylování použit Bootstrap
- dostupné na adrese: [http://st55425.borec.cz/](http://st55425.borec.cz/)
<file_sep>/src/footer.js
export default function Footer() {
return (
<div className="footer">
<p>Created by: <NAME></p>
<a href={"https://github.com/st55425/NNPIA_React_Todo"}>Github repozitář</a>
</div>
)
}<file_sep>/src/components/TodoList.js
import TodoItem from "./TodoItem";
export default function TodoList({data, completed, setData}) {
const clickHandler = function (item){
item.completed = item.completed === false;
const newData = [...data]
setData(newData)
}
const noToComplete = data.filter( item => item.completed === completed).length <= 0 && completed === false
const noCompleted = data.filter( item => item.completed === completed).length <= 0 && completed === true
return(
<div className="col justify-content-center">
{noToComplete && <p>Výborně, nemáte žádné úkoly ke splnění</p>}
{noCompleted && <p>Nemáte žádné splněné úkoly</p>}
{data.filter(item => item.completed === completed).map(item => <TodoItem key={item.id} item={item} onClickHandler={clickHandler}/>)}
</div>
)
}<file_sep>/src/App.js
import './App.css';
import TodoForm from "./components/TodoForm";
import TodoList from "./components/TodoList";
import { useState} from "react";
import 'bootstrap/dist/css/bootstrap.min.css';
import Footer from "./footer";
function App() {
const initialData = [
{
id:1,
name: "<NAME>",
completed: false
},
{
id:2,
name: "<NAME>",
completed: false
},
{
id:3,
name: "<NAME>",
completed: false
}
]
const [data, setData] = useState(initialData)
const [lastId, setLastId] = useState(4);
return (
<div className="App">
<TodoForm data={data} setData={setData} lastId={lastId} setLastId={setLastId}/>
<h1>Nesplněné úkoly</h1>
<TodoList data={data} completed={false} setData={setData}/>
<h1>Splněné úkoly</h1>
<TodoList data={data} completed={true} setData={setData}/>
<Footer/>
</div>
);
}
export default App;
| 2150804e301e15108392a677a30e1d1b138b33d2 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | st55425/NNPIA_React_Todo | be44b43017bccf9306820a70e945692a32e8431b | ff199e698172a834a1030efef2b6feb11d89bfa5 |
refs/heads/master | <repo_name>angeldelacruzdev/contador-con-react-native<file_sep>/src/pages/CounterPage.js
import React from "react";
import { StatusBar } from "expo-status-bar";
import { View, Text, StyleSheet, SafeAreaView, Pressable } from "react-native";
import { useSelector, useDispatch } from "react-redux";
import { increment, decrement, reset } from "../features/counter/counterSlice";
export default CounterPage = () => {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
return (
<SafeAreaView style={styles.container}>
<View>
<Text style={styles.title}>{count}</Text>
<StatusBar style="auto" />
</View>
<View style={styles.btnContainer}>
<Pressable
style={styles.pressable}
onPress={() => dispatch(increment())}
>
<Text>Increment</Text>
</Pressable>
<Pressable
style={styles.pressable}
onPress={() => dispatch(decrement())}
>
<Text>Decrement</Text>
</Pressable>
</View>
<Pressable style={styles.pressable} onPress={() => dispatch(reset())}>
<Text>Reset</Text>
</Pressable>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
title: {
fontSize: 57,
},
btnContainer: {
flexDirection: "row",
},
pressable: {
height: 40,
width: 150,
backgroundColor: "#AAA",
justifyContent: "center",
alignItems: "center",
margin: 10,
borderRadius: 5,
},
});
| 03a5b53fc9f294024b752f253a09dfdaccb25426 | [
"JavaScript"
] | 1 | JavaScript | angeldelacruzdev/contador-con-react-native | 34945ef71885a4fd42c9c623dad2e6832ee3af2d | e8ad4a36990e4e2a5be45a4edffd55948497b41d |
refs/heads/master | <repo_name>julia-francais/hackernews-<file_sep>/src/App.js
import React, { Component } from "react";
import "./App.css";
import { sortBy } from "lodash";
import Search from "./components/Search";
import Table from "./components/Table";
import Button from "./components/Button";
const DEFAULT_QUERY = "redux";
const DEFAULT_HPP = "50";
const PATH_BASE = "https://hn.algolia.com/api/v1";
const PATH_SEARCH = "/search";
const PARAM_SEARCH = "query=";
const PARAM_PAGE = "page=";
const PARAM_HPP = "hitsPerPage=";
export const SORTS = {
NONE: list => list,
TITLE: list => sortBy(list, "title"),
AUTHOR: list => sortBy(list, "author"),
COMMENTS: list => sortBy(list, "num_comments").reverse(),
POINTS: list => sortBy(list, "points").reverse()
};
const Loading = () => (
<div className="spinner-border text-info" role="status">
<span className="sr-only">Loading...</span>
</div>
);
const withLoading = Component => ({ isLoading, ...rest }) =>
isLoading ? <Loading /> : <Component {...rest} />;
const ButtonWithLoading = withLoading(Button);
const updateSearchTopStoriesState = (hits, page) => prevState => {
const { searchKey, results } = prevState;
const oldHits = results && results[searchKey] ? results[searchKey].hits : [];
const updatedHits = [...oldHits, ...hits];
return {
results: {
...results,
[searchKey]: { hits: updatedHits, page }
},
isLoading: false
};
};
class App extends Component {
constructor(props) {
super(props);
this.state = {
results: null,
searchKey: "",
searchTerm: DEFAULT_QUERY,
error: null,
isLoading: false
};
this.needsToSearchTopStories = this.needsToSearchTopStories.bind(this);
this.setSearchTopStories = this.setSearchTopStories.bind(this);
this.fetchSearchTopStories = this.fetchSearchTopStories.bind(this);
this.onDismiss = this.onDismiss.bind(this);
this.onSearchChange = this.onSearchChange.bind(this);
this.onSearchSubmit = this.onSearchSubmit.bind(this);
}
needsToSearchTopStories(searchTerm) {
return !this.state.results[searchTerm];
}
setSearchTopStories(result) {
const { hits, page } = result;
this.setState(updateSearchTopStoriesState(hits, page));
}
fetchSearchTopStories(searchTerm, page = 0) {
this.setState({ isLoading: true });
fetch(
`${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${searchTerm}&${PARAM_PAGE}${page}&${PARAM_HPP}${DEFAULT_HPP}`
)
.then(response => response.json())
.then(result => this.setSearchTopStories(result))
.catch(error => this.setState({ error }));
}
componentDidMount = () => {
const { searchTerm } = this.state;
this.setState({ searchKey: searchTerm });
this.fetchSearchTopStories(searchTerm);
};
onSearchChange = event => {
this.setState({ searchTerm: event.target.value });
};
onSearchSubmit(event) {
const { searchTerm } = this.state;
this.setState({ searchKey: searchTerm });
if (this.needsToSearchTopStories(searchTerm)) {
this.fetchSearchTopStories(searchTerm);
}
event.preventDefault();
}
onDismiss = id => {
const { searchKey, results } = this.state;
const { hits, page } = results[searchKey];
const updatedHits = hits.filter(item => item.objectID !== id);
this.setState({
results: { ...results, [searchKey]: { hits: updatedHits, page } }
});
};
render() {
const { searchTerm, results, searchKey, error, isLoading } = this.state;
const page =
(results && results[searchKey] && results[searchKey].page) || 0;
const list =
(results && results[searchKey] && results[searchKey].hits) || [];
return (
<div className="page">
<div className="interactions">
<Search
value={searchTerm}
onChange={this.onSearchChange}
onSubmit={this.onSearchSubmit}
>
Search
</Search>
</div>
{error ? (
<div className="interactions">
<p>Something went wrong.</p>
</div>
) : (
<Table list={list} onDismiss={this.onDismiss} />
)}
<div className="interactions">
<ButtonWithLoading
isLoading={isLoading}
onClick={() => this.fetchSearchTopStories(searchKey, page + 1)}
>
More
</ButtonWithLoading>
</div>
</div>
);
}
}
export default App;
export { Button, Search, Table };
| 4b0c3f4a7b00dbb3d77f4a0c2383b5bba526759e | [
"JavaScript"
] | 1 | JavaScript | julia-francais/hackernews- | c70f98fd93901b8b5079e44780999860b82b1719 | 8d7669e5e02ebe519af4182b6b414196411d056f |
refs/heads/master | <repo_name>timproctor/Just-summing-arrays<file_sep>/total.rb
Just-summing-arrays
===================
Two ways to sum array
# Using #inject is a efficient way to sum any array
def total(array)
array.inject(:+).to_f
end
# Or.....
def total(array)
total = 0
array.each do |number|
total += number.to_f
end
total
end
p total([1,2,3,4,5,6,-2.3,-12]) => 6.7
# Which one is more elegant Ruby?
<file_sep>/README.md
Just-summing-arrays
===================
Two ways to sum array: an inject method and a non-inject method.
Input is an array of numbers and the output is the sum of that array.
I'm curious which one is more "elegant" Ruby. What do you think?
| 2b05469cea88c428272dfc3460565da90a69c417 | [
"Markdown",
"Ruby"
] | 2 | Ruby | timproctor/Just-summing-arrays | 226ea6aa11ceb5bf513cf5a2cb0270d65f5aa52f | bc2bad9801e5d25852d26fe30210a81cfe116496 |
refs/heads/master | <repo_name>jarpar/Dziedziczenie<file_sep>/src/dziedziczenie/potwory/Zombie.java
package dziedziczenie.potwory;
public class Zombie extends Potwor {
@Override
protected void opis() {
}
public Zombie() {
System.out.println("Domyślny konstruktor z klasy Zombie");
}
@Override
public String toString() {
return "Zombie{" +
"predkoscChodzenia=" + predkoscChodzenia +
", zywotnosc=" + zywotnosc +
'}';
}
}
<file_sep>/src/dziedziczenie/potwory/Szkielet.java
package dziedziczenie.potwory;
public class Szkielet extends Potwor {
public void atakuj() {
//super.atakuj();//super czyli metoda ataku z potwor
/*
tutaj dodać specyficzną dla Szkielet,
dodatkową implementację ataku
*/
System.out.println("To jest metoda atakuj z klasy Szkielet");
}
@Override
protected void opis() {
}
String typBroni;
public Szkielet() {
System.out.println("Domyślny konstruktor z klasy Szkielet");
}
public Szkielet(double predkoscChodzenia, double zywotnosc) {
super(predkoscChodzenia, zywotnosc);
System.out.println("Niedomyślny konstruktor z klasy szkielet z dwoma argumentami.");
}
public Szkielet(double predkoscChodzenia, double zywotnosc, String typBroni) {
// this.predkoscChodzenia = predkoscChodzenia;
// this.zywotnosc = zywotnosc;
super(predkoscChodzenia, zywotnosc);
this.typBroni = typBroni;
System.out.println("Niedomyślny konstruktor z klasy Szkielet");
}
@Override
public String toString() {
return "Szkielet{" +
"typBroni='" + typBroni + '\'' +
", predkoscChodzenia=" + predkoscChodzenia +
", zywotnosc=" + zywotnosc +
'}';
}
}
<file_sep>/src/dziedziczenie/Dziedziczenie.java
package dziedziczenie;
import dziedziczenie.potwory.Potwor;
import dziedziczenie.potwory.Szkielet;
import dziedziczenie.potwory.Zombie;
public class Dziedziczenie {
public static void main(String[] args) {
Potwor p = new Szkielet(25, 36, "miecz");
System.out.println(p);
// Potwor ps = new Szkielet(10, 100);
// ps.atakuj();
// System.out.println("####");
//
// Potwor pz = new Zombie();
// pz.atakuj();
// System.out.println("####");
//
// specialAttack(ps, pz);
// Potwor p = new Potwor(10, 100);
// System.out.println(p);
//
// Szkielet s = new Szkielet(20, 50, "Łuk");
// System.out.println(s);
// s.atakuj();
//
// Zombie z = new Zombie();
// System.out.println(z);
}
// static void specialAttack(Potwor potwor1, Potwor potwor2) {
// potwor1.atakuj();
// potwor2.atakuj();
// }
}
<file_sep>/src/dziedziczenie/Pajak.java
package dziedziczenie;
import dziedziczenie.potwory.Potwor;
public class Pajak extends Potwor {
void funkcja() {
this.atakuj();
}
@Override
protected void opis() {
}
}
| 7f77690ae29106fa444e87c1fe9622efcf38f4f7 | [
"Java"
] | 4 | Java | jarpar/Dziedziczenie | e42ef5356ec8364299670cc82d53c8dd3e81b57b | bf4cb588069a6f2862055be75cde26e33043d025 |
refs/heads/master | <file_sep>#!/usr/bin/env python
# options @ http://tidy.sourceforge.net/docs/quickref.html
import tinytidy
options = {
'indent': 1,
'markup': 1,
'add-xml-decl': 1,
'output-xhtml': 1
}
print tinytidy.parseString('<title>Foo</title><p>Foo!', options)
<file_sep>/*
* Python TinyTidy: a minimal TidyLib wrapper version 0.1
* Copyright (c) 2005-2006 <NAME> <<EMAIL>>
*
* Inspired by http://utidylib.berlios.de/
* but only parseString method implemented.
* This code is python2.1 compatible
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this software; if not, write to the
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <Python.h>
#include <tidy/tidy.h>
#include <tidy/buffio.h>
#ifndef PyMODINIT_FUNC
#define PyMODINIT_FUNC void
#endif
/* Yes I like to abuse of gcc preprocessor */
#define TIDY_SET_PYERR() { PyErr_SetString(PyExc_ValueError, (const char *) errbuf.bp); }
#define TDOC_RETURN() \
{ \
Py_DECREF(item); \
Py_DECREF(value); \
tidyBufFree(&errbuf); \
tidyRelease(tdoc); \
return res; \
}
#define PY_TO_TIDY(py_check, tidy_type, py_converter, mustbe) \
{ \
if (!Py##py_check(value)) \
{ \
PyErr_Format(PyExc_ValueError, "Option '%s' must be " mustbe, PyString_AsString(item)); \
TDOC_RETURN(); \
} \
if (!tidyOptSet##tidy_type(tdoc, tidyOptGetId(option), Py##py_converter(value))) \
{ \
TIDY_SET_PYERR(); \
TDOC_RETURN(); \
} \
}
static PyObject *TinyTidyError;
static PyObject *parseString(PyObject *self, PyObject *args)
{
char *cp;
int i, len, list_size;
TidyDoc tdoc;
TidyOption option = TidyUnknownOption;
PyObject *res = NULL, *arglist = NULL;
PyObject *key_list = NULL, *item = NULL, *value = NULL;
TidyBuffer output = {0};
TidyBuffer errbuf = {0};
if (!PyArg_ParseTuple(args, "s#|O", &cp, &len, &arglist))
return NULL;
if (arglist && !PyDict_Check(arglist))
{
PyErr_SetString(PyExc_TypeError, "Second argument must be a dictionary!");
return NULL;
}
tdoc = tidyCreate();
tidySetErrorBuffer(tdoc, &errbuf);
if (!arglist) goto im_so_lazy; /* no args provided */
key_list = PyDict_Keys(arglist);
list_size = PyList_Size(key_list);
for (i = 0; i < list_size; i++)
{
item = PyList_GetItem(key_list, i);
value = PyDict_GetItem(arglist, item);
Py_INCREF(item);
Py_INCREF(value);
option = tidyGetOptionByName(tdoc, PyString_AsString(item));
if (option == TidyUnknownOption)
{
PyErr_Format(PyExc_KeyError, "Unknown tidy option '%s'", PyString_AsString(item));
TDOC_RETURN();
}
switch (tidyOptGetType(option))
{
case TidyString:
PY_TO_TIDY(String_Check, Value, String_AsString, "a String");
break;
case TidyInteger:
PY_TO_TIDY(Int_Check, Int, Int_AsLong, "an Integer");
break;
case TidyBoolean:
PY_TO_TIDY(Int_Check, Bool, Int_AsLong, "a Boolean or an Integer");
break;
default:
{
PyErr_Format(PyExc_RuntimeError,
"Something strange happened, there is no option type %d",
tidyOptGetType(option));
TDOC_RETURN();
}
}
Py_DECREF(item);
Py_DECREF(value);
}
im_so_lazy:
tidyParseString(tdoc, cp);
tidyCleanAndRepair(tdoc);
tidySaveBuffer(tdoc, &output);
res = Py_BuildValue("s#", output.bp, output.size);
tidyBufFree(&output);
tidyBufFree(&errbuf);
tidyRelease(tdoc);
return res;
}
static PyMethodDef tinytidy_methods[] =
{
{ "parseString", (PyCFunction) parseString, METH_VARARGS, "TinyTidy 4 Python" },
{ NULL, NULL}
};
PyMODINIT_FUNC inittinytidy(void)
{
PyObject *m;
m = Py_InitModule("tinytidy", tinytidy_methods);
TinyTidyError = PyErr_NewException("tinytidy.error", NULL, NULL);
Py_INCREF(TinyTidyError);
PyModule_AddObject(m, "error", TinyTidyError);
}
<file_sep>#!/usr/bin/env python
# -*- Mode: Python; tab-width: 4 -*-
#
# DistUtils Setup for TinyTidy Python Module
# Copyright (C) 2005-2006 Sherpya <<EMAIL>>
#
# 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 2, 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 MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
# ======================================================================
from distutils.core import setup, Extension
tinytidy = Extension('tinytidy',
sources = [ 'tinytidy.c' ],
libraries = [ 'tidy' ])
setup(name = 'TinyTidy', version = '0.1',
description = 'tinytidy',
ext_modules = [ tinytidy ])
| 71d72868315429bca18854c00311d18e07292325 | [
"C",
"Python"
] | 3 | Python | xNidmeSx/tinytidy | fe0db88e9f06871acdab4177f016678de3425692 | de4c0cbaf6ddcad9a22f81e048c1b27fb660b5c2 |
refs/heads/master | <repo_name>Emomotko/Beatbox<file_sep>/module2.py
#!/home/emilia/anaconda3/bin/ipython
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 28 18:22:16 2015
@author: emilia
"""
import re
import sys
from module1 import *
from module2 import *
import numpy as np
import scipy.io.wavfile
import scipy.fftpack
import os
def save_music(utwor, y, fs, fname):
scipy.io.wavfile.write(fname,
fs,
np.int16(y/max(np.abs(y))*32767))
def beatbox(utwor, fs = 44100):
#number_song = re.search('[0-9]', utwor).group(0)
path_name = ''.join([utwor,'song.txt'])
paths = open(path_name).readlines()
paths = list(map(str.strip,paths))
bpm = open(''.join([utwor,'defs.txt']) ).readlines()
bpm = list(map(str.strip,bpm))
bpm = float(re.search('[0-9]+', bpm[1]).group(0))
wave = create_music(utwor, bpm, paths)
fname = ''.join([utwor, utwor[0:len(utwor)-1],'.wav'])
#if not os.path.exists(utwor[0:len(utwor)-1]):
#os.makedirs(utwor[0:len(utwor)-1])
save_music(utwor, wave, fs, fname)
<file_sep>/README.txt
# Beatbox
Konstrukcja katalogu:
beatbox.py # glówna "aplikacja"
readme.txt # dodatkowe informacje o programie (m.in. opis plików, rozszerzen itp.)
innymodul1.py # dodatkowy modul, nazwa dowolna
...
innymodulN.py # dodatkowy modul, nazwa dowolna (musza byc co najmniej 2 dodatkowo)
utworX/ # katalog, nazwa dowolna, definicja utworu
sample01.wav # plik .wav, nazwa sampleUV.wav, gdzie UV to 2 cyfry
...
sampleXY.wav # jw.
track01.txt # definicja sciezki 01, nazwa trackUV, gdzie UV to 2 cyfry
...
trackAB.txt # jw.
defs.txt # konfiguracja (m.in. bpm, zobacz nizej)
song.txt # okresla kolejnosc odgrywanych sciezek (zob. nizej)
W folderze utworX znajduja sie sciezki, sample, definicja i kolejnosc sciezek w utworze.
Sample sa w formacie Wav.
Wygenerowanie utworu z katalogu utworX odbywa sie nsatepujaco:
1. Wpisujemy w konsoli: ./beatbox.py 'utworX/'
2. klikamy ENTER
3. W folderze utworX pojawil sie nowy plik muzyczny w formacie wav o nazwie utworX.wav
Wygenerowane pliki:
utwor1 - "Szla dzieweczka do laseczka" - zmiksowany utwór
utwor2 - "Gdybym mial gitare..." - zmiksowany utwór
utwor3 - zmiksowany utwór<file_sep>/module1.py
#!/home/emilia/anaconda3/bin/ipython
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 27 23:01:08 2015
@author: <NAME>
In this file the notes will be generated and the music based in them will be
created. Additional samples will also be added in order to emphasize the beat.
Hope you will enjoy this beatbox!!
"""
import numpy as np
import scipy.io.wavfile
import scipy.fftpack
import os
def generate_note(name, fs, l):
decay = int(0.01*l)
import numpy as np
freq = np.array([131, 147, 156, 175, 196, 220, 247, 262, 294, 330, 349, 389, 440, 494, 523, 587, 659, 698, 784, 880, 988])
names = np.array(['C-3', 'D-3', 'E-3', 'F-3','G-3', 'A-3', 'H-3', 'C-4', 'D-4', 'E-4', 'F-4','G-4', 'A-4', 'H-4','C-5', 'D-5', 'E-5', 'F-5','G-5', 'A-5', 'H-5'])
f = freq[np.where(names==name)]
t = np.linspace(0, 1, l)
y = np.sin(2*np.pi*f*t)
return y
def lengths(utwor, bpm, tracks):
tracks = open(tracks).readlines()
tracks = list(map(str.strip,tracks))
g = int(44100.0/(bpm/60.0))
n = len(tracks)
l = len(tracks[0].rsplit(" "))
result = np.zeros(shape = (n, l))
for j in range(len(tracks)):
actual = tracks[j].rsplit(" ")
for k in range(len(actual)):
if len(actual[k]) == 3:
result[j, k] = g
else:
if actual[k] == '--':
result[j, k] = 0
else:
sample = ''.join([utwor,'sample', actual[k],'.wav'])
fs, y = scipy.io.wavfile.read(sample)
result[j, k] = len(y)
return result
def overall_bias(bpm, lista):
g = int(44100.0/(bpm/60.0))
w = g
for i in range(0, len(lista)):
w = w - g
if w < 0:
w = 0
x = lista[i] - g
if x > w:
w = x
return w
def create_music(utwor, bpm, paths):
N = len(paths)
g = int(44100.0/(bpm/60.0))
l = [lengths(utwor, bpm, x) for x in [''.join([utwor,'track',p]) for p in paths]]
main_lengths = []
for i in range(len(paths)):
main_lengths.append([np.max(x) for x in l[i]])
bias = [overall_bias(bpm, x) for x in main_lengths]
a = [len(x)*g for x in main_lengths]
l = list(map(sum,zip(a, bias)))
result = np.zeros(int(np.sum(l)))
pom = np.r_[[0], np.cumsum(l)]
h = 0
for i in range(len(paths)):
track_name = ''.join([utwor,'track',paths[i]])
tracks = open(track_name).readlines()
tracks = list(map(str.strip,tracks))
for j in range(len(tracks)):
actual = tracks[j].rsplit(" ")
for k in actual:
if len(k) == 3:
result[pom[i] + j*g:pom[i] +j*g + g] = result[pom[i] +j*g:pom[i] +j*g + g] + generate_note(k, 44100, g)
else:
if k != '--':
sample = ''.join([utwor,'sample', k,'.wav'])
fs, y = scipy.io.wavfile.read(sample)
y = np.mean(y, axis = 1)
y = y/32767
result[pom[i] + j*g:pom[i] +j*g + len(y)] = result[pom[i] +j*g:pom[i] +j*g + len(y)] + y
else:
result[pom[i] + j*g:pom[i] +j*g + g] = result[pom[i] +j*g:pom[i] +j*g + g] + np.zeros(g)
return result
<file_sep>/beatbox.py
#!/home/emilia/anaconda3/bin/ipython
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 28 21:58:54 2015
@author: emilia
"""
import re
import sys
from module1 import *
from module2 import *
import numpy as np
import scipy.io.wavfile
import scipy.fftpack
import os
utwor = sys.argv[1]
print(utwor)
beatbox(utwor, fs = 44100)
| 70ffe9eb8d6a651d243bb9cc5fe32f17793d6deb | [
"Python",
"Text"
] | 4 | Python | Emomotko/Beatbox | 9fa0f858b54f7ee497ec5d78f1c5a46925a9c849 | 3208785d031766abd087ff81d534bde752e50d66 |
refs/heads/master | <repo_name>cs1102-lab1-09-2019-2/proyecto-final-streetlab<file_sep>/ProyectoFinalStreetLabV2.cpp
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class Mapa {
public:
string texto;
ifstream inFile;
vector<vector<int>> matriz;
int j = 0;
int sum = 0;
int x;
int p = 0, a, b, c, d;
void imprimirMapa() {
std::cout << "Mapa:" << endl;
while (!inFile.eof()) {
//vector<int> linea;
getline(inFile, texto);
//cout << texto << endl;
//cout << texto.length() << endl;
matriz.push_back(vector<int>());
for (int i = 0; i < texto.length(); i++) {
cout << setw(4) << setfill(' ') << texto[i];
if (texto[i] - 48 == 0)
matriz[j].push_back(-1);
else if (texto[i] - 48 == 1)
matriz[j].push_back(-2);
else if (texto[i] == 'F') {
matriz[j].push_back(-1);
c = i;
d = j;
}
else if (texto[i] == 'X') {
matriz[j].push_back(0);
a = i;
b = j;
}
}
cout << endl;
j++;
}
}
void calcularRuta() {
do {
for (int y = 0; y < matriz.size(); y++) {
for (int x = 0; x < matriz[y].size(); x++) {
if (matriz[y][x] == p) {
if ((x + 1 < matriz[0].size()) && matriz[y][x + 1] == -1)
matriz[y][x + 1] = p + 1;
if ((x - 1 >= 0) && matriz[y][x - 1] == -1)
matriz[y][x - 1] = p + 1;
if ((y + 1 < matriz.size()) && matriz[y + 1][x] == -1)
matriz[y + 1][x] = p + 1;
if ((y - 1 >= 0) && matriz[y - 1][x] == -1)
matriz[y - 1][x] = p + 1;
}
}
}
p++;
///////
for (int y = 0; y < matriz.size(); y++) {
for (int x = 0; x < matriz[y].size(); x++) {
cout << setw(4) << setfill(' ') << matriz[y][x];
}
cout << endl;
}
cout << endl;
} while (matriz[d][c] == -1);
cout << endl << "Mapa con ruta:" << endl;
matriz[d][c] = -4;
for (int k = p - 1; k > 0; k--) {
if ((c + 1 < matriz[0].size()) && matriz[d][c + 1] == k) {
matriz[d][c + 1] = -5;
c++;
}
else if ((c - 1 >= 0) && matriz[d][c - 1] == k) {
matriz[d][c - 1] = -5;
c--;
}
else if ((d + 1 < matriz.size()) && matriz[d + 1][c] == k) {
matriz[d + 1][c] = -5;
d++;
}
else if ((d - 1 >= 0) && matriz[d - 1][c] == k) {
matriz[d - 1][c] = -5;
d--;
}
}
for (int y = 0; y < matriz.size(); y++) {
for (int x = 0; x < matriz[y].size(); x++) {
if (matriz[y][x] == -5)
cout << setw(4) << setfill(' ') << '.';
else if (matriz[y][x] == -2)
cout << setw(4) << setfill(' ') << 1;
else if (matriz[y][x] == 0)
cout << setw(4) << setfill(' ') << 'X';
else if (matriz[y][x] == -4)
cout << setw(4) << setfill(' ') << 'F';
else
cout << setw(4) << setfill(' ') << 0;
}
cout << endl;
}
}
void mostrarResultado() {
cout << "La ruta mide: " << p << endl;
cout << "StreetLab Team 2019 \251";
}
~Mapa() {}
};
class Archivo : public Mapa {
private:
string ruta;
public:
Archivo() {}
void setRuta() {
string _ruta;
cout << "Ingrese la ruta donde se encuentra el archivo. La sintaxis es: [Ejemplo]" << endl;
cout << "C:\\Users\\nombre_del_usuario\\Downloads\\mapa.txt" << endl;
cin >> _ruta;
ruta = _ruta;
}
void abrirMapa() {
inFile.open(ruta, ios::in);
if (!inFile) {
cout << "El archivo no pudo ser encontrado :(";
exit(1);
}
}
void cerrarMapa() {
inFile.close();
}
~Archivo() {}
};
int main() {
Archivo archivo;
Mapa mapa;
archivo.setRuta();
archivo.abrirMapa();
mapa.imprimirMapa();
mapa.calcularRuta();
mapa.mostrarResultado();
archivo.cerrarMapa();
}
<file_sep>/tipos.h
#ifndef PROYECTO-FINAL-STREETLAB_TIPOS_H
#define PROYECTO-FINAL-STREETLAB_TIPOS_H
#include <iostream>
#include <iomanip>
using namespace std;
typedef int Entero;
typedef string Palabra;
#endif PROYECTO-FINAL-STREETLAB_TIPOS_H
<file_sep>/README.md
# Proyecto de Programación Orientado a Objetos
<div style="text-align:center; font-size: 20px;">
Nombre del Grupo: <b>StreetLab</b>
</div>
Integrantes - (Usuarios Github):
--
1.- <b><NAME></b><br>
<i> theowex</i>
2.- <b><NAME></b><br>
<i> Antonio-Zegarra-Becerra</i>
3.- <b><NAME></b><br>
<i> JayIsBae</i>
Instrucciones:
--
Nombre del Proyecto:
--
El proyecto lleva como nombre: <b>Sistema Planeador de Rutas</b>
Objetivo
--
El objetivo del <b><i>Sistema Planeador de Rutas</i></b> es generar un Mapa
Bidimensional de forma aleatoria y que cumpla con la condicion de no caer
en un callejon sin salida. Además, este debe encontrar la ruta optima entre
dos puntos ingresados por el usuario en el mapa generado.
Ejemplo
--
Dado el siguiente Mapa:

Donde:
* <b>X</b> es la posición inicial <b>{3,2}</b>
* <b>F</b> es la posición final <b>{9, 0}</b>
* <b>1</b>, indican los obstaculos y que no se puede pasar por esos puntos.
* <b>0</b>, indican las posiciones libres y que el vehiculo puede utilizar.
El mapa generado seriá el siguiente:

Donde:
* El semáforo indica el punto de partida
* La bandera indica el punto de llegada.
* El valor <b>1</b> representan las montañas
Mapa de la ruta generada por el vehiculo desde el punto
inicial al punto final.

Utilizar en la Implementación
--
Leer archivos, estructurar la data, Procesar, y luego
formatear la salida en el terminal.
Separar las definiciones de las implementaciones, utilizar
diferentes clases que manejen diferents tipos de datos y
diferentes tareas.
Crear clases que esten relacionadas por composición
y/o herencia.
Otras clases pueden ser mergeadas a travez de programacion generica.
En este proyecto demostraran sus habilidades en programación
orientado a objetos en C++.
Fecha de Asignacion:
--
Semana 7 - Jueves 03/10/2019
Número de Alumnos por equipo
--
* 3 alumnos por equipo
* Uno de los integrantes del grupo ingresa al link de classroom y crea un proyecto
asignadole un nombre.
* El resto de los integrantes del grupo busca ese nombre creado para
ser parte del grupo.
Recursos
--
* [Comandos GitHub](recursos/git-cheat-sheet-education.pdf)
Hito 1
--
Semana 11
Hito 2
--
Semana 15
<file_sep>/Pro/mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QString te = ui->textEdit->toPlainText();
ui->textSalida->setText(te);
ofstream arch;
arch.open("C:\\Users\\owena\\Downloads\\labmavis.txt", ios::out);//Aqui reemplacen la ruta del archivo de su proyecto
if(arch.fail()){
cout<<"Hubo un problema al guardar el archivo :("<<endl;
}
//for(int i = 0; i < texto.size(); i++) {
//arch<<texto[i]<<endl;
string data = te.toUtf8().constData();
arch<<data;
//}
arch.close();
string texto;
vector<vector<int>> matriz;
int j = 0;
int sum = 0;
int x;
int p = 0, a, b, c, d;
ifstream inFile;
inFile.open("C:\\Users\\owena\\Downloads\\labmavis.txt", ios::in);
if (!inFile) {
cout << "El archivo no pudo ser encontrado :(";
exit(1);
}
cout<<"Mapa:"<<endl;
while (!inFile.eof()) {
//vector<int> linea;
getline(inFile, texto);
//cout << texto << endl;
//cout << texto.length() << endl;
matriz.push_back(vector<int>());
for (int i = 0; i < texto.length(); i++) {
//cout <<setw(4) <<setfill(' ')<<texto[i];
if (texto[i] - 48 == 0) {
matriz[j].push_back(-1);
cout <<setw(4) <<setfill(' ')<<texto[i];
}
else if(texto[i] - 48 == 1) {
matriz[j].push_back(-2);
cout <<setw(4) <<setfill(' ')<<texto[i];
}
else if(texto[i] == 'F') {
matriz[j].push_back(-1);
c = i;
d = j;
cout <<setw(4) <<setfill(' ')<<texto[i];
}
else if(texto[i] == 'X') {
matriz[j].push_back(0);
a = i;
b = j;
cout <<setw(4) <<setfill(' ')<<texto[i];
}
}
cout<<endl;
j++;
}
inFile.close();
do{
for (int y = 0; y < matriz.size(); y++) {
for (int x = 0; x < matriz[y].size(); x++) {
if (matriz[y][x] == p) {
if ((x+1 < matriz[0].size()) && matriz[y][x + 1] == -1)
matriz[y][x + 1] = p+1;
if ((x - 1 >= 0) && matriz[y][x - 1] == -1)
matriz[y][x - 1] = p+1;
if ((y + 1 < matriz.size()) && matriz[y + 1][x] == -1)
matriz[y + 1][x] = p+1;
if ((y - 1 >= 0) && matriz[y - 1][x] == -1)
matriz[y - 1][x] = p+1;
}
}
}
p++;
///////
/*for (int y = 0; y < matriz.size(); y++) {
for (int x = 0; x < matriz[y].size(); x++){
cout <<setw(4) <<setfill(' ')<<matriz[y][x];
}
cout << endl;
}
cout << endl;*/
}while(matriz[d][c] == -1);
cout<<endl<<"Mapa con ruta:"<<endl;
matriz[d][c] = -4;
for (int k = p - 1; k > 0; k--) {
if ((c+1 < matriz[0].size()) && matriz[d][c + 1] == k) {
matriz[d][c + 1] = -5;
c++;
}
else if ((c - 1 >= 0) && matriz[d][c - 1] == k) {
matriz[d][c - 1] = -5;
c--;
}
else if ((d + 1 < matriz.size()) && matriz[d + 1][c] == k) {
matriz[d + 1][c] = -5;
d++;
}
else if ((d - 1 >= 0) && matriz[d - 1][c] == k) {
matriz[d - 1][c] = -5;
d--;
}
}
string datafinal = "";
for (int y = 0; y < matriz.size(); y++) {
for (int x = 0; x < matriz[y].size(); x++){
if(matriz[y][x] == -5){
cout <<setw(4) <<setfill(' ')<<'.';
datafinal += '_';
}
else if(matriz[y][x] == -2){
cout <<setw(4) <<setfill(' ')<<1;
datafinal += '1';
}
else if(matriz[y][x] == 0){
cout <<setw(4) <<setfill(' ')<<'X';
datafinal += 'X';
}
else if(matriz[y][x] == -4){
cout <<setw(4) <<setfill(' ')<<'F';
datafinal += 'F';
}
else{
cout <<setw(4) <<setfill(' ')<<0;
datafinal += '0';
}
datafinal += ' ';
}
cout << endl;
datafinal += '\n';
}
/*for (int y = 0; y < matriz.size(); y++) {
for (int x = 0; x < matriz[y].size(); x++){
cout <<setw(4) <<setfill(' ')<<matriz[y][x];
datafinal += strmatriz[y][x];
}
cout << endl;
datafinal += '\n';
}*/
QString str = QString::fromUtf8(datafinal.c_str());
ui->textSalida->setText(str);
cout<<"La ruta mide: "<<p<<endl;
cout<<"StreetLab Team 2019 \251";
}
| e123350a954aea1ab3ca90d2718fd514f4a5db3b | [
"Markdown",
"C++"
] | 4 | C++ | cs1102-lab1-09-2019-2/proyecto-final-streetlab | 1b733825f9a1917a1bb05a9d9921f75c977ef27e | 8eab1d09c36e924ecab1b5cc9a0b9bf201c69e6c |
refs/heads/master | <repo_name>guranshdua/laworder<file_sep>/officer/pages/citizens/approve.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php
include('../../partials/_head.php');
?>
</head>
<?php
if(isset($_GET))
{
extract($_GET);
$query="SELECT * from `citizen` where Citizen_id=$id";
$result=mysqli_query($con,$query);
$record = mysqli_fetch_assoc($result);
}
?>
<body>
<div class="container-scroller">
<!-- partial:../../partials/_navbar.html -->
<?php
include("../../partials/_navbar.php")
?>
<!-- partial -->
<div class="container-fluid page-body-wrapper">
<!-- partial:../../partials/_sidebar.html -->
<?php
include("../../partials/sidenav.php");
?>
<!-- partial -->
<div class="main-panel">
<div class="content-wrapper">
<div class="container">
<br>
<div class="row">
<div class="col-lg-12">
<h1>Account Approval</h1><br>
<?php
if(isset($err))
{
if($err==0)
{
echo '
<div class="alert alert-primary" role="alert">
<small>Account Approved</small>
</div>';
unset($err);
}
}
?>
<div class="col-12 grid-margin">
<div class="card">
<div class="card-body">
<form class="form-sample" method="post" action="">
<p class="card-description">
Personal info
</p>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Name</label>
<div class="col-sm-9">
<input type="text" name="fname" class="form-control" value="<?php echo $record['Name'] ?>" placeholder="<NAME>" readonly/>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">S/o</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="lname" value="<?php echo $record['Parents_name'] ?>" placeholder="Last Name" readonly/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">DOB</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="rno" value="<?php echo $record['DOB'] ?>" placeholder="Register No." readonly/>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">E - Mail ID</label>
<div class="col-sm-9">
<input type="email" class="form-control" name="mail" placeholder="E-Mail ID" value="<?php echo $record['email'] ?>" readonly/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Mobile Number</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="mobile" placeholder="Mobile Number" value="<?php echo $record['contact'] ?>" readonly/>
</div>
</div>
</div>
</div>
<br>
<p class="card-description">
Address
</p>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Police Station ID</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="block" value="<?php echo $record['ps'] ?>" readonly/>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Address</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="room" value="<?php echo $record['Address'] ?>" readonly/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<?php
echo "
<img width='100%' src='data:image/jpeg;base64,".base64_encode( $record['id_image'] )."'/>
";
?>
</div>
</div>
<br />
<form method="post" action="">
<div class="row ">
<div class="col-sm-3 offset-sm-3">
<a class="btn btn-success btn-block" href="accept.php?id=<?php echo $record['Citizen_id'];?>">Approve</a>
</div>
<div class="col-sm-3">
<a class="btn btn-danger btn-block" href="reject.php?id=<?php echo $record['Citizen_id'];?>">Reject</a>
</div>
</div>
</form>
</form>
</div>
<?php
/*if(isset($flag))
{
if($flag==1)
{
echo "DONE";
}
else if($flag==2)
{
echo "Nahi Hua<br>";
echo("Error description: " . mysqli_error($con));
}
}
if(isset($query))
{
echo $query;
}*/
?>
</div>
</div>
<!-- content-wrapper ends -->
<!-- partial:../../partials/_footer.html -->
</div>
</div>
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<?php
include('../../partials/_footer.html');
?>
<!-- page-body-wrapper ends -->
</div>
<!-- container-scroller -->
<!-- plugins:js -->
<script src="../../vendors/js/vendor.bundle.base.js"></script>
<script src="../../vendors/js/vendor.bundle.addons.js"></script>
<!-- endinject -->
<!-- Plugin js for this page-->
<!-- End plugin js for this page-->
<!-- inject:js -->
<script src="../../js/off-canvas.js"></script>
<script src="../../js/misc.js"></script>
<!-- endinject -->
<!-- Custom js for this page-->
<!-- End custom js for this page-->
</body>
</html>
<file_sep>/officer/pages/cases/case.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php
include('../../partials/_head.php');
?>
</head>
<?php
if(isset($_POST['fir']))
{
//echo "HELLO";
extract($_POST);
$query="SELECT FIR_ID from `fir` where FIR_ID=$fir";
//echo $query;
$res=mysqli_query($con,$query);
if($res)
{
$row=mysqli_num_rows($res);
}
else {
$row=0;
}
if($row>0)
{
$query="INSERT INTO `case_details` values(NULL,'$fir','$location', '$prop', '$status', '$dept','$cenvertedTime')";
//echo $query;
if(mysqli_query($con,$query))
{
//echo "HERE";
$err=0;
}
else {
echo("Error description: " . mysqli_error($con));
$err=2;
}
}
else {
$err=3;
}
}
?>
<body>
<div class="container-scroller">
<!-- partial:../../partials/_navbar.html -->
<?php
include("../../partials/_navbar.php")
?>
<!-- partial -->
<div class="container-fluid page-body-wrapper">
<!-- partial:../../partials/_sidebar.html -->
<?php
include("../../partials/sidenav.php");
?>
<!-- partial -->
<div class="main-panel">
<div class="content-wrapper">
<div class="container">
<br>
<div class="row">
<div class="col-lg-12">
<h1>New Case</h1><br>
<?php
if(isset($err))
{
if($err==0)
{
echo '
<div class="alert alert-success" role="alert">
<small>Case Lodged!</small>
</div>';
unset($err);
}
else {
echo '
<div class="alert alert-danger" role="alert">
<small>Case not Lodged!</small>
</div>';
unset($err);
}
}
?>
<div class="col-12 grid-margin">
<div class="card">
<div class="card-body">
<form method="post" enctype="multipart/form-data">
<p class="card-description">
</p>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">FIR ID</label>
<div class="col-sm-9">
<input type="text" name="fir" class="form-control" placeholder="ID" required/>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Location</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="location" placeholder="" required/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Property Seized</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="prop" placeholder="" required/>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Status</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="status" placeholder="" required/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="dept">Department</label>
<div class="col-sm-9">
<select name="dept" class="form-control " id="dept" >
<option value="Crime">
Civil Crime
</option>
<option value="Traffic">
Traffic
</option>
</select>
</div>
</div>
</div>
</div>
<br />
<div class="row ">
<div class="col-sm-3 offset-sm-4">
<button type="submit" name="submit" class="btn btn-success btn-block" >Create Case</button>
</div>
</div>
</form>
</div>
<?php
/*if(isset($flag))
{
if($flag==1)
{
echo "DONE";
}
else if($flag==2)
{
echo "Nahi Hua<br>";
echo("Error description: " . mysqli_error($con));
}
}
if(isset($query))
{
echo $query;
}*/
?>
</div>
</div>
<!-- content-wrapper ends -->
<!-- partial:../../partials/_footer.html -->
</div>
</div>
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<?php
include('../../partials/_footer.html');
?>
<!-- page-body-wrapper ends -->
</div>
<script type="application/javascript">
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
$('.custom-file-label').html(fileName);
});
</script>
<!-- container-scroller -->
<!-- plugins:js -->
<script src="../../vendors/js/vendor.bundle.base.js"></script>
<script src="../../vendors/js/vendor.bundle.addons.js"></script>
<!-- endinject -->
<!-- Plugin js for this page-->
<!-- End plugin js for this page-->
<!-- inject:js -->
<script src="../../js/off-canvas.js"></script>
<script src="../../js/misc.js"></script>
<!-- endinject -->
<!-- Custom js for this page-->
<!-- End custom js for this page-->
</body>
</html>
<file_sep>/officer/pages/citizens/criminals.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php
include('../../partials/_head.php');
?>
</head>
<body>
<div class="container-scroller">
<!-- partial:../../partials/_navbar.html -->
<?php
include("../../partials/_navbar.php")
?>
<!-- partial -->
<div class="container-fluid page-body-wrapper">
<!-- partial:../../partials/_sidebar.html -->
<?php
include("../../partials/sidenav.php");
?>
<!-- partial -->
<div class="main-panel">
<div class="content-wrapper">
<div class="col-lg-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h3>Criminals</h3>
<br />
<div class="row">
<div class="col-sm-3">
<button class="btn btn-alert btn-info" onclick="location.href='./criminal.php'">New Criminal</button>
</div>
<form method="post" enctype="multipart/form-data">
<div class="col-sm-9">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Search by Criminal ID</label>
<div class="col-sm-6">
<input type="text" name="cid" class="form-control" placeholder="ID" required/>
</div>
<div class="col-sm-3">
<button class="btn btn-alert btn-primary" type="submit">Search</button>
</div>
</div>
</div>
</form>
</div>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>
Criminal No.
</th>
<th>
Name
</th>
<th>
Age
</th>
<th>
Address
</th>
<th>
Job
</th>
</tr>
</thead>
<tbody>
<?php
if(isset($_POST['cid']))
{
$query="SELECT * from `criminal` where Criminal_ID=$_POST[cid]";
}
else {
$query="SELECT * from `criminal`";
}
$result=mysqli_query($con,$query);
while($row=(mysqli_fetch_array($result)))
{
echo "
<tr>
<td>
$row[0]
</td>
<td>
$row[1]
</td>
<td>
$row[2]
</td>
<td>
$row[3]
</td>
<td>
$row[4]
</td>
</tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- content-wrapper ends -->
<!-- partial:../../partials/_footer.html -->
<?php
include('../../partials/_footer.html');
?>
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<!-- page-body-wrapper ends -->
</div>
<!-- container-scroller -->
<!-- plugins:js -->
<script src="../../vendors/js/vendor.bundle.base.js"></script>
<script src="../../vendors/js/vendor.bundle.addons.js"></script>
<!-- endinject -->
<!-- Plugin js for this page-->
<!-- End plugin js for this page-->
<!-- inject:js -->
<script src="../../js/off-canvas.js"></script>
<script src="../../js/misc.js"></script>
<!-- endinject -->
<!-- Custom js for this page-->
<!-- End custom js for this page-->
</body>
</html>
<file_sep>/register.php
<!DOCTYPE html>
<html lang="en">
<?php
include("./db.php");
include('./authlogin.php');
?>
<?php
if (isset($_POST['fname'])) {
//echo "HAI";
//echo $_POST['myfile'];
$fileExtensions = ['jpeg','jpg']; // Get all the file extensions
extract($_POST);
$check=1;
$imgData =addslashes (file_get_contents($_FILES['myfile']['tmp_name']));
$fileName = $_FILES['myfile']['name'];
$fileExtension = (explode('.',$fileName));
$fileExtension = strtolower(end($fileExtension));
while($check==1)
{
$Postf=rand(1000,9999);
$ID='2019'.$Postf;
$Que="Select Citizen_id from `citizen` where Citizen_id='$ID'";
$result=mysqli_query($con,$Que);
if(mysqli_num_rows($result)==0)
{
$check=0;
}
else {
$check=1;
}
}
//echo "YAHAN";
if (! in_array($fileExtension,$fileExtensions)) {
$err =1;
}
else {
$err=0;
$query="INSERT INTO `citizen` values('$ID','$p1','$fname','$dob','$pname', $mob, '$email','$add','$area','$idtype','{$imgData}',0)";
if(!mysqli_query($con,$query))
{
$err=4;
}
else {
$err=0;
}
}
//echo "DONE";
}
else {
//echo "NOT THERE";
}
if(isset($_GET))
{
extract($_GET);
}
?>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Register</title>
<!-- plugins:css -->
<link rel="stylesheet" href="./citizen/vendors/iconfonts/mdi/css/materialdesignicons.min.css">
<link rel="stylesheet" href="./citizen/vendors/css/vendor.bundle.base.css">
<link rel="stylesheet" href="./citizen/vendors/css/vendor.bundle.addons.css">
<!-- endinject -->
<!-- plugin css for this page -->
<!-- End plugin css for this page -->
<!-- inject:css -->
<link rel="stylesheet" href="./citizen/css/style.css">
<!-- endinject -->
<link rel="shortcut icon" href="./citizen/images/favicon.png" />
</head>
<body>
<div class="container-scroller">
<div class="container-fluid page-body-wrapper full-page-wrapper auth-page">
<div class="content-wrapper d-flex align-items-center auth register-bg-1 theme-one">
<div class="row w-100">
<div class="col-lg-4 mx-auto">
<h2 class="text-center mb-4">Register</h2>
<div class="auto-form-wrapper">
<?php
if(isset($err))
{
if($err==1)
{
echo'
<div class="alert alert-danger" role="alert">
Not an Image!
</div>';
}
if($err==0)
{
echo'
<div class="alert alert-success" role="alert">
Your ID is '.$ID.'. Your approval is pending and will be done within 24 hrs.
</div>';
}
unset($err);
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="Name" name="fname" required/>
<div class="input-group-append">
<span class="input-group-text">
<i class="mdi mdi-check-circle-outline"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="Parent's Name" name="pname" required/>
<div class="input-group-append">
<span class="input-group-text">
<i class="mdi mdi-check-circle-outline"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="date" class="form-control" placeholder="Date Of Birth" name="dob" required/>
<div class="input-group-append">
<span class="input-group-text">
<i class="mdi mdi-check-circle-outline"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="tel" class="form-control" placeholder="Mobile Number" name="mob" required/>
<div class="input-group-append">
<span class="input-group-text">
<i class="mdi mdi-check-circle-outline"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<select class="form-control" name="area">
<option value=NULL>
Select Area
</option>
<?php
$query="SELECT * from `ps` ORDER BY Location";
$rows=mysqli_query($con,$query);
while($res=mysqli_fetch_assoc($rows))
{
?>
<option value="<?php echo $res['Station_Code'];?>"><?php echo $res['Location'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="Address" name="add" required/>
<div class="input-group-append">
<span class="input-group-text">
<i class="mdi mdi-check-circle-outline"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="email" class="form-control" placeholder="Email ID" name="email" required/>
<div class="input-group-append">
<span class="input-group-text">
<i class="mdi mdi-check-circle-outline"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<select class="form-control" name="idtype">
<option value=NULL>
Select ID Proof Type
</option>
<option value="1">
Aadhaar Card
</option>
<option value="2">
Voter ID
</option>
<option value="3">
Passport
</option>
<option value="4">
Driving License
</option>
<option value="5">
Employee ID
</option>
<option value="6">
School ID
</option>
</select>
</div>
</div>
<div class="form-group">
<div class="custom-file input-group">
<input type="file" class="custom-file-input file-upload-default form-control" name="myfile" id="customFile" required/>
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="p1" required/>
<div class="input-group-append">
<span class="input-group-text">
<i class="mdi mdi-check-circle-outline"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="<PASSWORD>" class="form-control" placeholder="Confirm Password" name="p2" required/>
<div class="input-group-append">
<span class="input-group-text">
<i class="mdi mdi-check-circle-outline"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary submit-btn btn-block">Register</button>
</div>
<div class="text-block text-center my-3">
<span class="text-small font-weight-semibold">Already have and account ?</span>
<a href="index.php" class="text-black text-small">Login</a>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- content-wrapper ends -->
</div>
<!-- page-body-wrapper ends -->
</div>
<!-- container-scroller -->
<!-- plugins:js -->
<script src="./citizen/vendors/js/vendor.bundle.base.js"></script>
<script src="./citizen/vendors/js/vendor.bundle.addons.js"></script>
<!-- endinject -->
<!-- inject:js -->
<script src="./citizen/js/off-canvas.js"></script>
<script src="./citizen/js/misc.js"></script>
<script type="application/javascript">
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
$('.custom-file-label').html(fileName);
});
</script>
<!-- endinject -->
</body>
</html>
<file_sep>/authlogin.php
<?php
if(isset($_SESSION["police"])){
header("Location: ./officer/index.php");
exit(); }
else if(isset($_SESSION["citizen"])){
header("Location: ./citizen/index.php");
exit(); }
else if(isset($_SESSION["administrator"])){
header("Location: ./administrator/index.php");
exit(); }
?>
<file_sep>/officer/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php
include("partials/_headroot.php");
?>
</head>
<body>
<div class="container-scroller">
<!-- partial:../../partials/_navbar.html -->
<?php
include("./partials/_navbarroot.php")
?>
<!-- partial -->
<div class="container-fluid page-body-wrapper">
<!-- partial:../../partials/_sidebar.html -->
<?php
include("./partials/sidenavroot.php");
?>
<!-- partial -->
<div class="main-panel">
<div class="content-wrapper">
<div class="col-lg-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-sm-12 text-center">
<h2>Indian Police Services</h2>
<br /><br />
</div>
</div>
<?php
$query="SELECT * from `police` where Officer_id='$_SESSION[police]'";
$result = mysqli_query($con,$query) or die(mysql_error());
$record = mysqli_fetch_array($result);
?>
<div class="row">
<div class="col-lg-12 grid-margin stretch-card ">
<!-- Display the countdown timer in an element -->
<div class="card bg-light mb-3 col-sm-12 offset-sm-0" >
<div class="card-body text-center">
<h3>My Profile</h3>
<br />
<div class="row">
<div class="col-sm-3 offset-sm-0 text-left">
<h4><strong>ID</strong> : <?php echo $record[0];?></h4>
</div>
<div class="col-sm-4 text-left">
<h4><strong>Name</strong> : <?php echo $record[2];?></h4>
</div>
<div class="col-sm text-left">
<h4><strong>Designation</strong> : <?php echo $record[3];?></h4>
</div>
</div>
<br />
<div class="row">
<div class="col-sm-3 text-left">
<h4><strong>DOB</strong> : <?php echo $record[4];?></h4>
</div>
<div class="col-sm-4 text-left">
<h4><strong>Contact</strong> : <?php echo $record[5];?></h4>
</div>
<div class="col-sm text-left">
<h4><strong>Email</strong> : <?php echo $record[6];?></h4>
</div>
</div><br />
<div class="row">
<div class="col-sm text-left">
<h4><strong>Qualification</strong> : <?php echo $record[8];?></h4>
</div>
<div class="col-sm text-left">
<h4><strong>Department</strong> : <?php echo $record[10];?></h4>
</div>
</div>
<br />
<div class="row">
<div class="col-sm-6 text-left">
<h4><strong>Address</strong> : <?php echo $record[7];?></h4>
</div>
<div class="col-sm-6 text-left">
<h4><strong>Police Station</strong> : <?php
$que="SELECT * from ps where Station_Code=$record[9]";
$result = mysqli_query($con,$que) or die(mysql_error());
$record = mysqli_fetch_array($result);
echo $record[3].', '.$record[2];
?></h4>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- content-wrapper ends -->
<!-- partial:../../partials/_footer.html -->
<?php
include('./partials/_footer.html');
?>
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<!-- page-body-wrapper ends -->
</div>
<!-- container-scroller -->
<!-- plugins:js -->
<script src="./vendors/js/vendor.bundle.base.js"></script>
<script src="./vendors/js/vendor.bundle.addons.js"></script>
<!-- endinject -->
<!-- Plugin js for this page-->
<!-- End plugin js for this page-->
<!-- inject:js -->
<script src="./js/off-canvas.js"></script>
<script src="./js/misc.js"></script>
<script>
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src='https://weatherwidget.io/js/widget.min.js';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','weatherwidget-io-js');
</script>
<!-- endinject -->
<!-- Custom js for this page-->
<!-- End custom js for this page-->
</body>
</html>
<file_sep>/admin/pages/permit/view.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php
include('../../partials/_head.php');
?>
</head>
<?php
?>
<body>
<div class="container-scroller">
<!-- partial:../../partials/_navbar.html -->
<?php
include("../../partials/_navbar.php")
?>
<!-- partial -->
<div class="container-fluid page-body-wrapper">
<!-- partial:../../partials/_sidebar.html -->
<?php
include("../../partials/sidenav.php");
?>
<!-- partial -->
<div class="main-panel">
<div class="content-wrapper">
<div class="col-lg-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h3>Pending Approvals</h3>
<?php
if(isset($err))
{
//echo $query;
if($err==3)
{
echo'
<div class="alert alert-danger" role="alert">
Request was not completed!
</div>';
}
if($err==0)
{
echo'
<div class="alert alert-success" role="alert">
Request Approved Successfully!
</div>';
}
if($err==1)
{
echo'
<div class="alert alert-success" role="alert">
Request Rejected Successfully!
</div>';
}
if($err==2)
{
echo'
<div class="alert alert-danger" role="alert">
Request was not completed!
</div>';
}
unset($err);
}
?>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>
Name
</th>
<th>
DOB
</th>
<th>
S/O
</th>
<th>
Mobile Number
</th>
<th>
Email
</th>
<th>
Address
</th>
<th>
Applied On
</th>
</tr>
</thead>
<tbody>
<?php
$query="SELECT * from `licence` where ps=$_SESSION[ps] and Status=0";
$result=mysqli_query($con,$query);
while($row=(mysqli_fetch_array($result)))
{
$que="SELECT * from `citizen` where Citizen_id=$row[1]";
$result1=mysqli_query($con,$que);
$row1=(mysqli_fetch_array($result1));
$rown=$row[0]*(-1);
echo "
<tr>
<td>
$row1[2]
</td>
<td>
$row1[3]
</td>
<td>
$row1[4]
</td>
<td>
$row1[5]
</td>
<td>
$row1[6]
</td>
<td>
$row1[7]
</td>
<td>
$row[4]
</td>
</tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- content-wrapper ends -->
<!-- partial:../../partials/_footer.html -->
<?php
include('../../partials/_footer.html');
?>
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<!-- page-body-wrapper ends -->
</div>
<!-- container-scroller -->
<!-- plugins:js -->
<script src="../../vendors/js/vendor.bundle.base.js"></script>
<script src="../../vendors/js/vendor.bundle.addons.js"></script>
<!-- endinject -->
<!-- Plugin js for this page-->
<!-- End plugin js for this page-->
<!-- inject:js -->
<script src="../../js/off-canvas.js"></script>
<script src="../../js/misc.js"></script>
<!-- endinject -->
<!-- Custom js for this page-->
<!-- End custom js for this page-->
</body>
</html>
<file_sep>/citizen/pages/permit/view.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php
include('../../partials/_head.php');
?>
</head>
<?php
$query="SELECT * from `licence` where Citizen_id=$_SESSION[citizen]";
$res=mysqli_query($con,$query);
$rows=mysqli_num_rows($res);
if($rows==0)
{
$err=3;
}
else {
$record=mysqli_fetch_assoc($res);
if($record['Status']==0)
{
$err=0;
}
else if($record['Status']==1){
$err=1;
}
else {
$err=2;
}
}
?>
<body>
<div class="container-scroller">
<!-- partial:../../partials/_navbar.html -->
<?php
include("../../partials/_navbar.php")
?>
<!-- partial -->
<div class="container-fluid page-body-wrapper">
<!-- partial:../../partials/_sidebar.html -->
<?php
include("../../partials/sidenav.php");
?>
<!-- partial -->
<div class="main-panel">
<div class="content-wrapper">
<div class="container">
<br>
<div class="row">
<div class="col-lg-12">
<h1>Arms Appication</h1><br>
<?php
if(isset($err))
{
if($err==3)
{
echo'
<div class="alert alert-danger" role="alert">
You Haven\'t applied for arms yet.
</div>';
}
if($err==0)
{
echo'
<div class="alert alert-info" role="alert">
Your approval is pending.
</div>';
}
if($err==1)
{
echo'
<div class="alert alert-success" role="alert">
Your request was approved by <strong>'.$record['approved_by'].'</strong> on <strong>'.$record['approved_on'].'</strong>.
</div>';
}
if($err==2)
{
echo'
<div class="alert alert-danger" role="alert">
Application Rejected.
</div>';
}
unset($err);
}
?>
<!-- content-wrapper ends -->
<!-- partial:../../partials/_footer.html -->
</div>
</div>
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<?php
include('../../partials/_footer.html');
?>
<!-- page-body-wrapper ends -->
</div>
<!-- container-scroller -->
<!-- plugins:js -->
<script src="../../vendors/js/vendor.bundle.base.js"></script>
<script src="../../vendors/js/vendor.bundle.addons.js"></script>
<!-- endinject -->
<!-- Plugin js for this page-->
<!-- End plugin js for this page-->
<!-- inject:js -->
<script src="../../js/off-canvas.js"></script>
<script src="../../js/misc.js"></script>
<!-- endinject -->
<!-- Custom js for this page-->
<!-- End custom js for this page-->
</body>
</html>
<file_sep>/admin/pages/police/viewps.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php
include('../../partials/_head.php');
?>
</head>
<body>
<div class="container-scroller">
<!-- partial:../../partials/_navbar.html -->
<?php
include("../../partials/_navbar.php")
?>
<!-- partial -->
<div class="container-fluid page-body-wrapper">
<!-- partial:../../partials/_sidebar.html -->
<?php
include("../../partials/sidenav.php");
?>
<!-- partial -->
<div class="main-panel">
<div class="content-wrapper">
<div class="col-lg-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h3>Police Stations</h3>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>
PS ID
</th>
<th>
Area
</th>
<th>
City
</th>
<th>
State
</th>
</tr>
</thead>
<tbody>
<?php
$query="SELECT * from `ps` ";
$result=mysqli_query($con,$query);
while($row=(mysqli_fetch_array($result)))
{
echo "
<tr>
<td>
$row[0]
</td>
<td>
$row[3]
</td>
<td>
$row[2]
</td>
<td>
$row[1]
</td>
</tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- content-wrapper ends -->
<!-- partial:../../partials/_footer.html -->
<?php
include('../../partials/_footer.html');
?>
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<!-- page-body-wrapper ends -->
</div>
<!-- container-scroller -->
<!-- plugins:js -->
<script src="../../vendors/js/vendor.bundle.base.js"></script>
<script src="../../vendors/js/vendor.bundle.addons.js"></script>
<!-- endinject -->
<!-- Plugin js for this page-->
<!-- End plugin js for this page-->
<!-- inject:js -->
<script src="../../js/off-canvas.js"></script>
<script src="../../js/misc.js"></script>
<!-- endinject -->
<!-- Custom js for this page-->
<!-- End custom js for this page-->
</body>
</html>
<file_sep>/officer/pages/cases/fir.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php
include('../../partials/_head.php');
?>
</head>
<?php
if(isset($_POST['sub']))
{
//echo "HELLO";
extract($_POST);
$imgData =addslashes (file_get_contents($_FILES['myfile']['tmp_name']));
$fileName = $_FILES['myfile']['name'];
$fileExtension = (explode('.',$fileName));
$fileExtension = strtolower(end($fileExtension));
$fileExtensions = ['jpeg','jpg']; // Get all the file extensions
if (! in_array($fileExtension,$fileExtensions)) {
$err=1;
}
else {
$query="INSERT INTO `fir` values(NULL,'$sub','$dept', '$appname', '$accname', '$details','$date','{$imgData}',$_SESSION[ps],$_SESSION[police])";
if(mysqli_query($con,$query))
{
//echo "HERE";
$err=0;
}
else {
echo("Error description: " . mysqli_error($con));
$err=2;
}
}
}
?>
<body>
<div class="container-scroller">
<!-- partial:../../partials/_navbar.html -->
<?php
include("../../partials/_navbar.php")
?>
<!-- partial -->
<div class="container-fluid page-body-wrapper">
<!-- partial:../../partials/_sidebar.html -->
<?php
include("../../partials/sidenav.php");
?>
<!-- partial -->
<div class="main-panel">
<div class="content-wrapper">
<div class="container">
<br>
<div class="row">
<div class="col-lg-12">
<h1>FIR</h1><br>
<?php
if(isset($err))
{
if($err==0)
{
echo '
<div class="alert alert-success" role="alert">
<small>FIR Lodged!</small>
</div>';
unset($err);
}
else {
echo '
<div class="alert alert-danger" role="alert">
<small>FIR not Lodged!</small>
</div>';
unset($err);
}
}
?>
<div class="col-12 grid-margin">
<div class="card">
<div class="card-body">
<form method="post" enctype="multipart/form-data">
<p class="card-description">
Personal info
</p>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Applicant</label>
<div class="col-sm-9">
<input type="text" name="appname" class="form-control" placeholder="Name" required/>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Accused</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="accname" placeholder="Name" required/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Subject</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sub" placeholder="Name" required/>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Details</label>
<div class="col-sm-9">
<textarea class="form-control" name="details"></textarea>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<input type="file" class="custom-file-input file-upload-default form-control" name="myfile" id="customFile" required/>
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="dept">Department</label>
<div class="col-sm-9">
<select name="dept" class="form-control " id="dept" >
<option value="Crime">
Civil Crime
</option>
<option value="Traffic">
Traffic
</option>
</select>
</div>
</div>
</div>
</div>
<br />
<div class="row ">
<div class="col-sm-3 offset-sm-4">
<button type="submit" name="submit" class="btn btn-success btn-block" >Lodge FIR</button>
</div>
</div>
</form>
</div>
<?php
/*if(isset($flag))
{
if($flag==1)
{
echo "DONE";
}
else if($flag==2)
{
echo "Nahi Hua<br>";
echo("Error description: " . mysqli_error($con));
}
}
if(isset($query))
{
echo $query;
}*/
?>
</div>
</div>
<!-- content-wrapper ends -->
<!-- partial:../../partials/_footer.html -->
</div>
</div>
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<?php
include('../../partials/_footer.html');
?>
<!-- page-body-wrapper ends -->
</div>
<script type="application/javascript">
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
$('.custom-file-label').html(fileName);
});
</script>
<!-- container-scroller -->
<!-- plugins:js -->
<script src="../../vendors/js/vendor.bundle.base.js"></script>
<script src="../../vendors/js/vendor.bundle.addons.js"></script>
<!-- endinject -->
<!-- Plugin js for this page-->
<!-- End plugin js for this page-->
<!-- inject:js -->
<script src="../../js/off-canvas.js"></script>
<script src="../../js/misc.js"></script>
<!-- endinject -->
<!-- Custom js for this page-->
<!-- End custom js for this page-->
</body>
</html>
<file_sep>/citizen/partials/_head.php
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>ISTE-VIT</title>
<link rel="icon" type="image" href="../../images/ISTE.ico" />
<!-- plugins:css -->
<link rel="stylesheet" href="../../vendors/iconfonts/mdi/css/materialdesignicons.min.css">
<link rel="stylesheet" href="../../vendors/css/vendor.bundle.base.css">
<link rel="stylesheet" href="../../vendors/css/vendor.bundle.addons.css">
<link rel="stylesheet" href="../../vendors/iconfonts/font-awesome/css/font-awesome.css">
<!-- endinject -->
<!-- plugin css for this page -->
<!-- End plugin css for this page -->
<!-- inject:css -->
<link rel="stylesheet" href="../../css/style.css">
<!-- endinject -->
<?php
require("../auth/auth.php");
require("../auth/db.php");
$startTime = date("Y-m-d H:i:s");
$cenvertedTime = date('Y-m-d H:i:s',strtotime('+5 hour +30 minutes',strtotime($startTime)));
$unixTimestamp = strtotime($cenvertedTime);
$dayOfWeek = date("l", $unixTimestamp);
$datetime = explode(" ",$cenvertedTime);
$date=$datetime[0];
$time=$datetime[1];
$month=date('m',strtotime($date));
$day=date('d',strtotime($date));
?>
<file_sep>/citizen/pages/samples/updatepassword.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php
include('../../partials/_head.php');
?>
</head>
<?php
if(isset($_POST['pass']))
{
extract($_POST);
if(strlen($pass)>=8)
{
if(strcmp($pass,$cpass)==0)
{
$query="UPDATE `citizen` SET Password='$<PASSWORD>' where Citizen_id=$_SESSION[citizen]";
if(mysqli_query($con,$query))
{
$passerror=0;
}
else {
$passerror=2;
echo $query;
}
}
else {
$passerror=1;
}
}
else {
$passerror=3;
}
}
?>
<body>
<div class="container-scroller">
<!-- partial:../../partials/_navbar.html -->
<?php
include("../../partials/_navbar.php")
?>
<!-- partial -->
<div class="container-fluid page-body-wrapper">
<!-- partial:../../partials/_sidebar.html -->
<?php
include("../../partials/sidenav.php");
?>
<!-- partial -->
<div class="main-panel">
<div class="content-wrapper">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1>Update Password</h1><br>
<div class="col-12 grid-margin">
<div class="card">
<div class="card-body">
<form class="form-sample" method="post" action="">
<p class="card-description">
Password
</p>
<?php
if(isset($passerror))
{
if($passerror==0)
{
echo '
<div class="alert alert-success" role="alert">
<small>Password updated successfully.</small>
</div>';
unset($passerror);
}
else if($passerror==1)
{
echo '
<div class="alert alert-danger" role="alert">
<small>Passwords do not match, please retype. Error ISTEPW01</small>
</div>';
unset($passerror);
}
else if($passerror==2)
{
echo '
<div class="alert alert-danger" role="alert">
<small>Could not update password. Error ISTEPW02</small>
</div>';
unset($passerror);
}
else if($passerror==3)
{
echo '
<div class="alert alert-danger" role="alert">
<small>Password must be greater than 8 characters. Error ISTEPW03</small>
</div>';
unset($passerror);
}
}
?>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Enter Password</label>
<div class="col-sm-9">
<input type="<PASSWORD>" name="pass" class="form-control" placeholder="***************" required/>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Verify Password</label>
<div class="col-sm-9">
<input type="<PASSWORD>" class="form-control" name="cpass" placeholder="***************" required/>
</div>
</div>
</div>
</div>
<br>
<button type="submit" class="btn btn-success mr-2">Submit</button>
</form>
</div>
</div>
</div>
<!-- content-wrapper ends -->
<!-- partial:../../partials/_footer.html -->
</div>
</div>
<!-- partial -->
</div>
</div>
<?php
include('../../partials/_footer.html');
?>
</div>
<!-- main-panel ends -->
</div>
</div>
<!-- page-body-wrapper ends -->
<!-- container-scroller -->
<!-- plugins:js -->
<script src="../../vendors/js/vendor.bundle.base.js"></script>
<script src="../../vendors/js/vendor.bundle.addons.js"></script>
<!-- endinject -->
<!-- Plugin js for this page-->
<!-- End plugin js for this page-->
<!-- inject:js -->
<script src="../../js/off-canvas.js"></script>
<script src="../../js/misc.js"></script>
<!-- endinject -->
<!-- Custom js for this page-->
<!-- End custom js for this page-->
</body>
</html>
<file_sep>/admin/pages/auth/logout.php
<?php
session_start();
UNSET($_SESSION['admin']);
if(!isset($_SESSION['admin']))
{
// Redirecting To Home Page
header("Location: ../../../index.php");
}
?>
<file_sep>/officer/pages/cases/cases.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php
include('../../partials/_head.php');
?>
</head>
<body>
<div class="container-scroller">
<!-- partial:../../partials/_navbar.html -->
<?php
include("../../partials/_navbar.php")
?>
<!-- partial -->
<div class="container-fluid page-body-wrapper">
<!-- partial:../../partials/_sidebar.html -->
<?php
include("../../partials/sidenav.php");
?>
<!-- partial -->
<div class="main-panel">
<div class="content-wrapper">
<div class="col-lg-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h3>Cases</h3>
<br />
<?php
if(isset($_GET['err']))
{
extract($_GET);
if($err==0)
{
echo '
<div class="alert alert-success" role="alert">
<small>Case Disposed!</small>
</div>';
unset($err);
}
else {
echo '
<div class="alert alert-danger" role="alert">
<small>Case not Disposed!</small>
</div>';
unset($err);
}
}
?>
<div class="row">
<div class="col-sm-3">
<button class="btn btn-alert btn-info" onclick="location.href='./case.php'">Create New Case</button>
</div>
<form method="post" enctype="multipart/form-data">
<div class="col-sm-9">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Search by Case ID</label>
<div class="col-sm-6">
<input type="text" name="appname" class="form-control" placeholder="Case ID" required/>
</div>
<div class="col-sm-3">
<button class="btn btn-alert btn-primary" type="submit">Search</button>
</div>
</div>
</div>
</form>
</div>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>
Case ID
</th>
<th>
FIR ID
</th>
<th>
Location
</th>
<th>
Property
</th>
<th>
Status
</th>
<th>
Department
</th>
<th>
Date
</th>
<th>
Action
</th>
</tr>
</thead>
<tbody>
<?php
if(isset($_POST['appname']))
{
$query="SELECT * from `case_details` where Case_ID=$_POST[appname] AND Status NOT LIKE '-1'";
}
else {
$query="SELECT * from `case_details` where Status NOT LIKE '-1' ";
}
//echo $query;
$result=mysqli_query($con,$query);
while($row=(mysqli_fetch_array($result)))
{
echo "
<tr>
<td>
$row[0]
</td>
<td>
$row[1]
</td>
<td>
$row[2]
</td>
<td>
$row[3]
</td>
<td>
$row[4]
</td>
<td>
$row[5]
</td>
<td>
$row[6]
</td>
<td>
<a href='dispose.php?id=$row[0]'>Dispose to Court</a>
</td>
</tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- content-wrapper ends -->
<!-- partial:../../partials/_footer.html -->
<?php
include('../../partials/_footer.html');
?>
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<!-- page-body-wrapper ends -->
</div>
<!-- container-scroller -->
<!-- plugins:js -->
<script src="../../vendors/js/vendor.bundle.base.js"></script>
<script src="../../vendors/js/vendor.bundle.addons.js"></script>
<!-- endinject -->
<!-- Plugin js for this page-->
<!-- End plugin js for this page-->
<!-- inject:js -->
<script src="../../js/off-canvas.js"></script>
<script src="../../js/misc.js"></script>
<!-- endinject -->
<!-- Custom js for this page-->
<!-- End custom js for this page-->
</body>
</html>
<file_sep>/citizen/pages/permit/apply.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php
include('../../partials/_head.php');
?>
</head>
<?php
if(isset($_POST['submit']))
{
$query="INSERT INTO `licence` values(NULL,$_SESSION[citizen],$_SESSION[ps],0,'$cenvertedTime',NULL,NULL)";
//echo "<br /><br /><br />".$query;
if(!mysqli_query($con,$query))
{
$err=1;
}
else {
$err=0;
}
}
?>
<body>
<div class="container-scroller">
<!-- partial:../../partials/_navbar.html -->
<?php
include("../../partials/_navbar.php")
?>
<!-- partial -->
<div class="container-fluid page-body-wrapper">
<!-- partial:../../partials/_sidebar.html -->
<?php
include("../../partials/sidenav.php");
?>
<!-- partial -->
<div class="main-panel">
<div class="content-wrapper">
<div class="container">
<br>
<div class="row">
<div class="col-lg-12">
<h1>Arms Appication</h1><br>
<?php
if(isset($err))
{
if($err==1)
{
echo'
<div class="alert alert-danger" role="alert">
You can apply only once!! Check Status of previous application in Permits Menu.
</div>';
}
if($err==0)
{
echo'
<div class="alert alert-success" role="alert">
Your approval is pending.
</div>';
}
unset($err);
}
?>
<div class="col-12 grid-margin">
<div class="card">
<div class="card-body">
<form class="form-sample" method="post" action="">
<p class="card-description">
</p>
<button name="submit" type="submit" class="btn btn-primary submit-btn btn-block">Apply by agreeing to T&Cs of posessing arms.</button>
</form>
</div>
<?php
/*if(isset($flag))
{
if($flag==1)
{
echo "DONE";
}
else if($flag==2)
{
echo "Nahi Hua<br>";
echo("Error description: " . mysqli_error($con));
}
}
if(isset($query))
{
echo $query;
}*/
?>
</div>
</div>
<!-- content-wrapper ends -->
<!-- partial:../../partials/_footer.html -->
</div>
</div>
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<?php
include('../../partials/_footer.html');
?>
<!-- page-body-wrapper ends -->
</div>
<!-- container-scroller -->
<!-- plugins:js -->
<script src="../../vendors/js/vendor.bundle.base.js"></script>
<script src="../../vendors/js/vendor.bundle.addons.js"></script>
<!-- endinject -->
<!-- Plugin js for this page-->
<!-- End plugin js for this page-->
<!-- inject:js -->
<script src="../../js/off-canvas.js"></script>
<script src="../../js/misc.js"></script>
<!-- endinject -->
<!-- Custom js for this page-->
<!-- End custom js for this page-->
</body>
</html>
<file_sep>/admin/pages/police/transfer.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php
include('../../partials/_head.php');
?>
</head>
<?php
if(isset($_POST['oid']))
{
//echo "HELLO";
extract($_POST);
$query="UPDATE `police`SET Station_Code='$ostation' WHERE Officer_id='$oid'";
if(mysqli_query($con,$query))
{
//echo "HERE";
$err=0;
}
else {
//echo("Error description: " . mysqli_error($con));
$err=2;
}
}
?>
<body>
<div class="container-scroller">
<!-- partial:../../partials/_navbar.html -->
<?php
include("../../partials/_navbar.php")
?>
<!-- partial -->
<div class="container-fluid page-body-wrapper">
<!-- partial:../../partials/_sidebar.html -->
<?php
include("../../partials/sidenav.php");
?>
<!-- partial -->
<div class="main-panel">
<div class="content-wrapper">
<div class="container">
<br>
<div class="row">
<div class="col-lg-12">
<h1>Transfer Officer</h1><br>
<?php
if(isset($err))
{
if($err==0)
{
echo '
<div class="alert alert-success" role="alert">
<small>Officer Transferred!</small>
</div>';
unset($err);
}
else {
echo '
<div class="alert alert-danger" role="alert">
<small>Officer not Transferred!</small>
</div>';
unset($err);
}
}
?>
<div class="col-12 grid-margin">
<div class="card">
<div class="card-body">
<form method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Officer ID</label>
<div class="col-sm-9">
<input type="text" name="oid" class="form-control" placeholder="" required/>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Station</label>
<div class="col-sm-9">
<select name="ostation" class="form-control">
<?php
$query="SELECT * from `ps`";
$res=mysqli_query($con,$query);
while($row=mysqli_fetch_array($res))
{
echo "<option value='$row[0]'>
$row[3]
</option>";
}
?>
</select>
</div>
</div>
</div>
</div>
<br />
<div class="row ">
<div class="col-sm-3 offset-sm-4">
<button type="submit" name="submit" class="btn btn-success btn-block" >Transfer!</button>
</div>
</div>
</form>
</div>
<?php
/*if(isset($flag))
{
if($flag==1)
{
echo "DONE";
}
else if($flag==2)
{
echo "Nahi Hua<br>";
echo("Error description: " . mysqli_error($con));
}
}
if(isset($query))
{
echo $query;
}*/
?>
</div>
</div>
<!-- content-wrapper ends -->
<!-- partial:../../partials/_footer.html -->
</div>
</div>
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<?php
include('../../partials/_footer.html');
?>
<!-- page-body-wrapper ends -->
</div>
<script type="application/javascript">
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
$('.custom-file-label').html(fileName);
});
</script>
<!-- container-scroller -->
<!-- plugins:js -->
<script src="../../vendors/js/vendor.bundle.base.js"></script>
<script src="../../vendors/js/vendor.bundle.addons.js"></script>
<!-- endinject -->
<!-- Plugin js for this page-->
<!-- End plugin js for this page-->
<!-- inject:js -->
<script src="../../js/off-canvas.js"></script>
<script src="../../js/misc.js"></script>
<!-- endinject -->
<!-- Custom js for this page-->
<!-- End custom js for this page-->
</body>
</html>
<file_sep>/index.php
<!DOCTYPE html>
<?php
include("./db.php");
include('./authlogin.php');
?>
<?php
$startTime = date("Y-m-d H:i:s");
$cenvertedTime = date('Y-m-d H:i:s',strtotime('+5 hour +30 minutes',strtotime($startTime)));
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
$type=$_POST['type'];
//echo $type;
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
if($type==1)
{
$query = "SELECT * FROM `citizen` WHERE Citizen_id='$username'
and Password='$<PASSWORD>' and CrossCheckStatus=1";
}
else if($type==2)
{
$query = "SELECT * FROM `police` WHERE Officer_id='$username'
and Password='$<PASSWORD>' ";
}
else if($type==3)
{
$query = "SELECT * FROM `administrator` WHERE ID='$username'
and Password='$<PASSWORD>' ";
}
//echo $query;
//Checking is user existing in the database or not
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
$record = mysqli_fetch_assoc($result);
if($rows==1){
if($type==1)
{
echo "Here";
$_SESSION["citizen"] = $record['Citizen_id'];
$_SESSION["ps"]=$record['ps'];
}
else if($type==2)
{
$_SESSION["police"] = $record['Officer_id'];
$_SESSION["ps"]=$record['Station_Code'];
}
else if($type==3)
{
$_SESSION["admin"] = $record['ID'];
}
$_SESSION["name"]=$record['Name'];
if($type==1)
{
header("Location: ./citizen");
}
else if($type==2)
{
header("Location: ./officer");
}
else if($type==3)
{
header("Location: ./admin");
}
}
else{
$_SESSION['loginerror']=1;
}
}
?>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Indian Law</title>
<!-- plugins:css -->
<link rel="stylesheet" href="./citizen/vendors/iconfonts/mdi/css/materialdesignicons.min.css">
<link rel="stylesheet" href="./citizen/vendors/css/vendor.bundle.base.css">
<link rel="stylesheet" href="./citizen/vendors/css/vendor.bundle.addons.css">
<!-- endinject -->
<!-- plugin css for this page -->
<!-- End plugin css for this page -->
<!-- inject:css -->
<link rel="stylesheet" href="./citizen/css/style.css">
<!-- endinject -->
</head>
<body>
<div class="container-scroller">
<div class="container-fluid page-body-wrapper full-page-wrapper auth-page">
<div class="content-wrapper d-flex align-items-center auth auth-bg-1 theme-one">
<div class="row w-100">
<div class="col-lg-4 mx-auto">
<div class="auto-form-wrapper">
<h1>Law and Order</h1>
<?php
if(isset($_SESSION['loginerror']))
{
if($_SESSION['loginerror']==1)
{
echo '
<div class="alert alert-danger" role="alert">
<small>Invalid Credentials</small>
</div>';
unset($_SESSION['loginerror']);
}
}
?>
<form action="" method="post" name="login">
<div class="form-group">
<label class="label">User Type</label>
<div class="input-group">
<select name="type" class="form-control">
<option value='1'>
Citizen
</option>
<option value='2'>
Police
</option>
<option value='3'>
Administrator
</option>
</select>
</div>
</div>
<div class="form-group">
<label class="label">Username</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="Username" name="username">
<div class="input-group-append">
<span class="input-group-text">
<i class="mdi mdi-check-circle-outline"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="label">Password</label>
<div class="input-group">
<input type="<PASSWORD>" class="form-control" placeholder="*********" name="password">
<div class="input-group-append">
<span class="input-group-text">
<i class="mdi mdi-check-circle-outline"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary submit-btn btn-block" type="submit" name="submit">Login</button>
</div>
</form>
<button class="btn btn-info btn-block" onclick="location.href='./register.php'">Sign Up</button>
</div>
<p class="footer-text text-center">Copyright © 2019 Dua Technologies. All rights reserved.</p>
</div>
</div>
</div>
<!-- content-wrapper ends -->
</div>
<!-- page-body-wrapper ends -->
</div>
<!-- container-scroller -->
<!-- plugins:js -->
<!-- endinject -->
<!-- inject:js -->
<!-- endinject -->
</body>
</html>
<file_sep>/admin/pages/citizens/reject.php
<head>
<?php
include('../../partials/_head.php');
?>
</head>
<?php
if(isset($_GET))
{
extract($_GET);
$query="DELETE FROM `citizen` where Citizen_id=$id";
if(mysqli_query($con,$query))
{
echo "Rejected!";
}
}
?>
<a href="./approval.php">Go Back</a>
<file_sep>/officer/pages/auth/logout.php
<?php
session_start();
UNSET($_SESSION['police']);
if(!isset($_SESSION['police']))
{
// Redirecting To Home Page
header("Location: ../../../index.php");
}
?>
<file_sep>/officer/pages/cases/dispose.php
<?php
include('../../partials/_head.php');
if(isset($_GET['id']))
{
$query="UPDATE `case_details` SET Status='-1' WHERE Case_ID=$_GET[id]";
if(mysqli_query($con,$query))
{
header("Location: ./cases.php?err=0");
}
else {
header("Location: ./cases.php?err=1");
}
}
?>
| b52d107ae6f0947951c6c83b7fe7615c1f2e1628 | [
"PHP"
] | 20 | PHP | guranshdua/laworder | fdb92aec7b5b58f634e7d91b8a025ae0f0ccf1e0 | e2fc220df4cf3ebcd8ccd3bc1e467688d3a23b02 |
refs/heads/master | <file_sep>window.onload=function (ev) {
lun_bo();
let w = parseInt($('.win').width());
$('.cir').css({
left:(w/2-35)+'px'
})
};
let t = 0;
function lun_bo() {
t++;
if (t >= 100) {
let w = parseInt($('.win').width());
let l = parseInt($('.imgs').css('marginLeft'));
let m = 20;
let c = -l / w + 1;
let y = w / m;
let s = 0;
function lun_one() {
s++;
$('.win .imgs').css({
marginLeft: l-y*s + 'px'
});
let nei = window.requestAnimationFrame(lun_one);
if (s>=m){
console.log(s);
c++;
window.cancelAnimationFrame(nei);
console.log(c);
if(c>=5){
console.log('123456789');
c=1;
$('.win .imgs').css({
marginLeft: 0
});}
}
}
lun_one();
t = 0;
}
window.requestAnimationFrame(lun_bo);
} | 4ce7fa16cea9a52685b9a5a1a3b8bdc92b19042e | [
"JavaScript"
] | 1 | JavaScript | gebidawang/gebidawang | 1079d0f5b34f23e887bd051f483a289d60204ff4 | 96e8af2312f0a86a792906f21b127fa00e0d06a5 |
refs/heads/master | <repo_name>Shas77/Sprint2<file_sep>/Asian_Paints_Sprint2/src/test/java/pageFactory/HomePageFactory.java
package pageFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class HomePageFactory {
@FindBy(id="headerSearch")
WebElement selectSearchTab;
@FindBy(name="q")
WebElement enterProduct;
@FindBy(xpath = "//button[@class='js-header-search-handle']")
WebElement selectSearchBtn;
@FindBy(xpath = "//h4[@class='report-title']")
WebElement selectProduct;
@FindBy(xpath = "//input[@class='commonTextComp track_search_click']")
WebElement invalidProduct;
@FindBy(xpath = "//div[@class='headerDropdown']")
WebElement selectDropDown;
@FindBy(xpath = "//div[@class='no-results-content__text-block text']")
WebElement errorMessage;
WebDriver driver;
public HomePageFactory(WebDriver driver)
{
this.driver=driver;
PageFactory.initElements(driver, this);
}
public void clickSearchTab()
{
selectSearchTab.click();
}
public void enterProduct(String prod)
{
enterProduct.sendKeys(prod);
}
public void clickSearchBtn()
{
selectSearchBtn.click();
}
public void clickProduct()
{
selectProduct.click();
}
public void enterInvalidProd(String prod)
{
invalidProduct.sendKeys(prod);
}
public String dispTitle()
{
return driver.getTitle();
}
public void clickDropDown()
{
selectDropDown.click();
}
public String dispError()
{
return errorMessage.getText();
}
public void endScenario()
{
driver.quit();
}
public void selectUserType(String user)
{
driver.findElement(By.linkText(user)).click();
}
}
<file_sep>/Asian_Paints_Sprint2/src/test/resources/Properties/Config.properties
driverPath = D:\\Software\\chromedriver.exe
driverType = webdriver.chrome.driver
baseUrl = https://www.asianpaints.com
filePath1 = src\\test\\resources\\ExcelFiles\\asianPaintTest1.xlsx
filePath2 = src\\test\\resources\\ExcelFiles\\asianPaintTest2.xlsx
excelFileName = asianPaintTest.xlsx
sheetName1 = Sheet1
sheetName2 = Sheet2
<file_sep>/Asian_Paints_Sprint2/test-output/old/Default suite/methods.html
<h2>Methods run, sorted chronologically</h2><h3>>> means before, << means after</h3><p/><br/><em>Default suite</em><p/><small><i>(Hover the method name to see the test class name)</i></small><p/>
<table border="1">
<tr><th>Time</th><th>Delta (ms)</th><th>Suite<br>configuration</th><th>Test<br>configuration</th><th>Class<br>configuration</th><th>Groups<br>configuration</th><th>Method<br>configuration</th><th>Test<br>method</th><th>Thread</th><th>Instances</th></tr>
<tr bgcolor="63a271"> <td>21/07/13 15:59:49</td> <td>0</td> <td> </td><td> </td><td> </td><td> </td><td title=">>TestngSteps.launchApplication()[pri:0, instance:testngSteps.TestngSteps@2d778add]">>>launchApplication</td>
<td> </td> <td>main@2019826979</td> <td></td> </tr>
<tr bgcolor="63a271"> <td>21/07/13 15:59:59</td> <td>10239</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="TestngSteps.SearchProduct(java.lang.String)[pri:1, instance:testngSteps.TestngSteps@2d778add]">SearchProduct</td>
<td>main@2019826979</td> <td></td> </tr>
<tr bgcolor="63a271"> <td>21/07/13 16:00:07</td> <td>17947</td> <td> </td><td> </td><td> </td><td> </td><td title="<<TestngSteps.endTest()[pri:0, instance:testngSteps.TestngSteps@2d778add]"><<endTest</td>
<td> </td> <td>main@2019826979</td> <td></td> </tr>
<tr bgcolor="63a271"> <td>21/07/13 16:00:08</td> <td>19150</td> <td> </td><td> </td><td> </td><td> </td><td title=">>TestngSteps.launchApplication()[pri:0, instance:testngSteps.TestngSteps@2d778add]">>>launchApplication</td>
<td> </td> <td>main@2019826979</td> <td></td> </tr>
<tr bgcolor="63a271"> <td>21/07/13 16:00:16</td> <td>27608</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="TestngSteps.SearchProduct(java.lang.String)[pri:1, instance:testngSteps.TestngSteps@2d778add]">SearchProduct</td>
<td>main@2019826979</td> <td></td> </tr>
<tr bgcolor="63a271"> <td>21/07/13 16:00:23</td> <td>34127</td> <td> </td><td> </td><td> </td><td> </td><td title="<<TestngSteps.endTest()[pri:0, instance:testngSteps.TestngSteps@2d778add]"><<endTest</td>
<td> </td> <td>main@2019826979</td> <td></td> </tr>
<tr bgcolor="63a271"> <td>21/07/13 16:00:24</td> <td>34882</td> <td> </td><td> </td><td> </td><td> </td><td title=">>TestngSteps.launchApplication()[pri:0, instance:testngSteps.TestngSteps@2d778add]">>>launchApplication</td>
<td> </td> <td>main@2019826979</td> <td></td> </tr>
<tr bgcolor="63a271"> <td>21/07/13 16:00:32</td> <td>43246</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="TestngSteps.SearchInvalidProduct(java.lang.String)[pri:2, instance:testngSteps.TestngSteps@2d778add]">SearchInvalidProduct</td>
<td>main@2019826979</td> <td></td> </tr>
<tr bgcolor="63a271"> <td>21/07/13 16:00:36</td> <td>46838</td> <td> </td><td> </td><td> </td><td> </td><td title="<<TestngSteps.endTest()[pri:0, instance:testngSteps.TestngSteps@2d778add]"><<endTest</td>
<td> </td> <td>main@2019826979</td> <td></td> </tr>
</table>
<file_sep>/Asian_Paints_Sprint2/src/test/java/com/libraries/ExcelUtility.java
package com.libraries;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtility
{
public String[] getData(String fileName, String sheetName)
{
String data[]=null;
try
{
FileInputStream input = new FileInputStream(fileName);
XSSFWorkbook workBook = new XSSFWorkbook(input);
XSSFSheet sheet = workBook.getSheet(sheetName);
XSSFRow row = sheet.getRow(0);
int numRows = sheet.getPhysicalNumberOfRows();
int numCols = row.getLastCellNum();
Cell cell;
data = new String[numRows-1];
for(int i=1;i<numRows;i++)
{
for(int j=0;j<numCols;j++)
{
row = sheet.getRow(i);
cell = row.getCell(j);
data[i-1] = cell.getStringCellValue();
}
}
workBook.close();
}
catch(Exception e)
{
System.out.println("The Exception is: "+e.getMessage());
}
return data;
}
}
| f4f557d3bcc4fcbcadd7ff54eef8fbb4d74d7410 | [
"Java",
"HTML",
"INI"
] | 4 | Java | Shas77/Sprint2 | abdddbd03824a146ccfaf57209d7e6122e34947c | 252299a110199b3b67b0cafefc3af2aa10086b1f |
refs/heads/main | <repo_name>poojakolani/hacktoberfest-1<file_sep>/codevita1.py
def isPrime(n):
b = True
for x in range(2,n-1):
if(n%x==0):
b = False
break
return b
totalHr , division = map(int,input().split())
peroid = int(totalHr /division)
counter = 0
for i in range(2,peroid):
if isPrime(i):
for j in range(1,division):
if isPrime(peroid*j+i):
if totalHr - (peroid*j+i) < peroid :
counter+=1
break
continue
else:
break
print(counter,end="")
| 188eec5404320313afa3cc81e089136877dd9029 | [
"Python"
] | 1 | Python | poojakolani/hacktoberfest-1 | 5a6ea948b7979c8b000ea40e568c8d21df577a61 | 9fd966a3eab104267cb4fdb4f074d982f849afd0 |
refs/heads/master | <file_sep># valter.2019.2.poo<file_sep>package aula1;
public class camisa {
String manga;
String cor;
String tipo;
String tamanho;
boolean desenho;
void desenhar(){
if(desenho)
System.out.println("Desenho encontrado");
else
System.out.println("Desenho não encontrado");
}
void vestir(){
}
void lavar(){
}
void status(){
System.out.println("Classe camisa");
System.out.println("manga:" + manga);
System.out.println("cor:" + cor);
System.out.println("tipo:" + tipo);
System.out.println("tamanho:" + tamanho);
}
}
| a0b4a36818d411f370eccd49756f9ea24585d307 | [
"Markdown",
"Java"
] | 2 | Markdown | lorenzanf/valter.2019.2.poo | f00ccd156fa819212cd3ddf3d5c3914c494e0e6e | fa3451464282918babaa3e5ce492d23a34c1c33e |
refs/heads/master | <repo_name>rodrigobarro/meutimefcapp<file_sep>/README.md
# MeuTimeFC App
[](https://appcenter.ms)
<file_sep>/ios/Podfile
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'MeuTimeFcApp' do
pod 'AppCenter/Crashes', '~> 2.0.1'
pod 'AppCenter/Analytics', '~> 2.0.1'
pod 'AppCenterReactNativeShared', '~> 2.0.0'
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for MeuTimeFcApp
platform :ios, '9.0'
pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons'
target 'MeuTimeFcAppTests' do
inherit! :search_paths
# Pods for testing
end
end
target 'MeuTimeFcApp-tvOS' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for MeuTimeFcApp-tvOS
target 'MeuTimeFcApp-tvOSTests' do
inherit! :search_paths
# Pods for testing
end
end
<file_sep>/src/pages/Signup/FinalStep/index.js
import React, { Component } from 'react';
import {
StyleSheet, View, TouchableOpacity, Image,
} from 'react-native';
import { Text, Icon, Button, Input } from 'react-native-elements';
const styles = StyleSheet.create({
container: {
backgroundColor: '#141414',
flex: 1,
alignItems: 'center',
},
card: {
marginTop: 56,
backgroundColor: '#3A3A3C',
borderWidth: 0,
marginLeft: 16,
marginRight: 16,
borderRadius: 12,
width: '92%',
alignItems: 'center',
},
assetTitle: {
fontSize: 12,
color: 'white',
fontWeight: 'bold',
marginTop: 12,
},
bottomImage: {
resizeMode: 'cover',
},
containerStyleButton: {
width: '90%',
marginTop: 16,
},
buttonStyle: {
backgroundColor: '#9A9B9F',
borderRadius: 10,
height: 48,
},
buttonTitleStyle: {
marginRight: 40,
marginLeft: 40,
fontWeight: 'bold',
},
labelInput: {
color: '#ffffff',
fontSize: 14,
paddingBottom: 4,
},
input: {
backgroundColor: 'white',
borderRadius: 8,
paddingHorizontal: 16,
height: 8,
},
containerInput: {
marginBottom: 6,
paddingHorizontal: 16,
},
inputRestrictions: {
fontSize: 12,
color: '#626262',
textAlign: 'left',
width: '100%',
marginLeft: 36,
marginBottom: 16,
},
});
export default class FinalStep extends Component {
constructor() {
super();
this.state = {};
}
render() {
return (
<View style={styles.container}>
<View style={styles.card}>
<View style={{width: '80%',flexDirection: 'row', justifyContent: 'space-around'}}>
<View style={{width: '50%', alignItems: 'center'}}>
<Text style={styles.assetTitle}><NAME></Text>
<Image
style={styles.shieldBack}
source={require('~/assets/signup/coach/vestimenta-01.png')}
/>
</View>
<View style={{width: '50%', alignItems: 'center'}}>
<Text style={styles.assetTitle}><NAME></Text>
<Image
style={styles.shieldBack}
source={require('~/assets/signup/shield-backs/escudo-1-fundo.png')}
/>
</View>
</View>
<Input
containerStyle={styles.containerInput}
inputStyle={styles.input}
placeholderTextColor="#999999"
placeholder="Ex.: <NAME>"
label="ENTRE COM SEU E-MAIL"
labelStyle={styles.labelInput}
underlineColorAndroid="transparent"
/>
<Input
containerStyle={styles.containerInput}
inputStyle={styles.input}
placeholderTextColor="#999999"
placeholder="Ex.: <NAME>"
label="CRIE SUA SENHA"
labelStyle={styles.labelInput}
/>
<Text style={styles.inputRestrictions}>Pelo menos 6 caracteres</Text>
<View style={{flexDirection: 'row', marginBottom: 16}}>
<Text style={{fontSize: 12, color: 'white', fontWeight: 'bold'}}>Você aceita os</Text>
<Text style={{fontSize: 12, color: 'white', fontWeight: 'bold', textDecorationLine: 'underline'}}> Termos de Uso</Text>
<Text style={{fontSize: 12, color: 'white', fontWeight: 'bold'}}> e a </Text>
<Text style={{fontSize: 12, color: 'white', fontWeight: 'bold', textDecorationLine: 'underline'}}>Política de Privacidade?</Text>
</View>
</View>
<Button
containerStyle={styles.containerStyleButton}
buttonStyle={styles.buttonStyle}
icon={<Icon name="chevron-right" size={48} color="white" />}
iconContainerStyle={{ marginLeft: 56 }}
iconRight
titleStyle={styles.buttonTitleStyle}
title="ACEITO. BORA PRO JOGO!"
onPress={() => alert('ola')}
/>
<Image style={styles.bottomImage} source={require('~/assets/background.png')} />
</View>
);
}
}
<file_sep>/src/pages/Main/index.js
/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {
Text,
View,
StyleSheet,
TouchableHighlight,
Image,
ImageBackground,
Modal,
TouchableOpacity,
FlatList,
ScrollView,
} from 'react-native';
import { Button } from 'react-native-elements';
import Icon from 'react-native-vector-icons/FontAwesome';
import PrivacyModal from '~/pages/Main/Modal/PrivacyModal';
import TermsModal from '~/pages/Main/Modal/TermsModal';
export default class Main extends React.Component {
state = {
modalVisible: false,
subModalVisible: false,
currentModal: '',
};
setModalVisible(visible) {
this.setState({ modalVisible: visible });
}
setSubModalVisible(visible) {
this.setState({ subModalVisible: visible });
}
_keyExtractor = (item, key) => item.key;
handleModalItemSelect(visible, item) {
switch (item.type) {
case 'regulamento':
this.setState({ subModalVisible: visible });
this.setState({ currentModal: item.type});
break;
case 'termo':
this.setState({ subModalVisible: visible });
this.setState({ currentModal: item.type});
break;
case 'privacidade':
this.setState({ subModalVisible: visible });
this.setState({ currentModal: item.type});
break;
default:
}
}
render() {
return (
<ImageBackground
source={require('../../assets/soccer-background.jpg')}
style={styles.backgroundImage}
resizeMode="cover"
>
<TouchableOpacity
onPress={() => this.setModalVisible(true)}
style={{
width: '100%',
justifyContent: 'flex-start',
paddingLeft: 16,
paddingTop: 16,
}}
>
<Icon type="font-aewsome" name="bars" size={28} />
</TouchableOpacity>
<Image source={require('../../assets/logo.png')} style={styles.logo} />
<Image source={require('../../assets/escale.png')} style={styles.escale} />
<Text style={styles.noAccountQuestion}>Ainda não tem uma conta?</Text>
<Button
title="CRIE SEU TIME AGORA!"
containerStyle={{width: '80%'}}
titleStyle={styles.titleCreateNewTeam}
buttonStyle={styles.buttonCreateNewTeam}
onPress={() => this.props.navigation.navigate('Signup')}
/>
<View style={styles.container}>
<Text style={styles.isCustomer}>Já tem conta?</Text>
<TouchableHighlight onPress={() => this.props.navigation.navigate('Login')}>
<Text style={styles.clickHere}>Acesse aqui</Text>
</TouchableHighlight>
</View>
<View style={styles.leagueContainer}>
<Image style={styles.league} source={require('../../assets/copa_america.png')} />
<Image style={styles.league} source={require('../../assets/copa_libertadores.png')} />
<Image style={styles.league} source={require('../../assets/premier_league.png')} />
<Image style={styles.league} source={require('../../assets/champions_league.png')} />
</View>
<View style={styles.footerContainer}>
<Text style={styles.footerText}>Powered by Fabrica 18</Text>
<Text style={styles.footerText}>{'\u00A9'}2019 - Todos os direitos reservados</Text>
</View>
<View>
<Modal animationType="slide" transparent={false} visible={this.state.modalVisible}>
<View style={{ backgroundColor: '#000000', width: '100%', height: '100%' }}>
<TouchableOpacity
style={{
width: '100%',
alignSelf: 'center',
marginTop: 16,
marginRight: 16,
}}
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}
>
<Icon
type="font-aewsome"
name="times"
size={36}
color="white"
style={{
alignSelf: 'flex-end',
paddingRight: 16,
paddingTop: 8,
marginBottom: 4,
}}
/>
</TouchableOpacity>
<FlatList
data={[
{ key: 'REGULAMENTO', type: 'regulamento' },
{ key: 'GANHADORES', type: 'ganhadores' },
{ key: '<NAME>', type: 'termo' },
{ key: '<NAME>', type: 'privacidade' },
{ key: '', modal: '' },
]}
style={{ paddingTop: -16 }}
ItemSeparatorComponent={() => (
<View style={{ height: 0.5, width: '100%', backgroundColor: '#2F2E2E' }} />
)}
renderItem={({ item }) => (
<TouchableOpacity
style={{
height: 60,
marginLeft: 16,
}}
onPress={() => {
this.handleModalItemSelect(!this.state.subModalVisible, item);
}}
>
<View
style={{
height: '100%',
backgroundColor: 'black',
flex: 1,
justifyContent: 'center',
}}
>
<Text style={{ color: 'white', fontSize: 16 }}>{item.key}</Text>
</View>
</TouchableOpacity>
)}
/>
<ScrollView>
</ScrollView>
</View>
</Modal>
</View>
<View>
<Modal animationType="fade" transparent visible={this.state.subModalVisible}>
<View style={styles.card}>
<TouchableOpacity
style={{
width: '100%',
alignSelf: 'center',
marginTop: 16,
marginRight: 16,
}}
onPress={() => {
this.setSubModalVisible(!this.state.subModalVisible);
}}
>
<Icon
type="font-aewsome"
name="times"
size={36}
color="white"
style={{
alignSelf: 'flex-end',
paddingRight: 16,
paddingTop: 8,
marginBottom: 4,
}}
/>
</TouchableOpacity>
<ScrollView>
{(() => {
switch(this.state.currentModal) {
case 'regulamento':
return <TermsModal />;
case 'privacidade':
return <PrivacyModal />;
case 'termo':
return <TermsModal />;
default:
return null;
}
})()}
</ScrollView>
</View>
</Modal>
</View>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
backgroundImage: {
width: '100%',
height: '100%',
flex: 1,
alignItems: 'center',
},
logo: {
marginTop: -32,
resizeMode: 'center',
},
escale: {
resizeMode: 'center',
width: '80%',
marginTop: -72,
},
noAccountQuestion: {
color: '#fff',
fontWeight: 'bold',
fontSize: 16,
paddingHorizontal: 20,
paddingBottom: 4,
marginTop: -24,
fontFamily: 'oswaldRegular',
},
buttonCreateNewTeam: {
backgroundColor: '#FFCC28',
borderRadius: 12,
paddingBottom: 12,
paddingTop: 12,
},
titleCreateNewTeam: {
color: '#2A2627',
fontSize: 18,
fontFamily: 'oswaldRegular',
},
clickHere: {
color: '#fff',
fontWeight: 'bold',
fontSize: 16,
paddingHorizontal: 2,
paddingBottom: 4,
textDecorationLine: 'underline',
},
isCustomer: {
color: '#fff',
fontWeight: 'bold',
fontSize: 16,
paddingHorizontal: 2,
paddingBottom: 4,
},
container: {
paddingTop: 16,
flexDirection: 'row',
alignItems: 'center',
},
leagueContainer: {
flex: 1,
flexDirection: 'row',
marginTop: 8,
paddingBottom: 8,
},
league: {
width: 72,
height: 72,
paddingTop: 4,
margin: 4,
},
footerContainer: {
flex: 1,
alignItems: 'center',
marginTop: 48,
},
footerText: {
color: '#fff',
fontWeight: 'bold',
fontSize: 12,
},
card: {
marginTop: 32,
backgroundColor: '#000000',
borderWidth: 0.5,
borderColor: '#8B8D8F',
marginLeft: 16,
marginRight: 16,
borderRadius: 12,
height: '90%',
alignItems: 'center',
},
});
<file_sep>/src/pages/Login/index.js
import React from 'react';
import {
View, Text, StyleSheet, Image, ImageBackground, TouchableOpacity,
} from 'react-native';
import { Button, Input } from 'react-native-elements';
// import {TextInputMask} from 'react-native-masked-text';
// eslint-disable-next-line react/prefer-stateless-function
export default class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
show: true,
};
}
ShowHideComponent = () => {
if (this.state.show == true) {
this.setState({ show: false });
} else {
this.setState({ show: true });
}
};
render() {
return (
<ImageBackground
source={require('../../assets/soccer-background.jpg')}
style={styles.backgroundImage}
resizeMode="cover"
>
<Image source={require('../../assets/logo.png')} style={styles.logo} />
<Image source={require('../../assets/escale.png')} style={styles.escale} />
<Text style={styles.accessTitle}>ACESSE SUA CONTA</Text>
{this.state.show ? (
<View style={{ width: '100%' }}>
<Text style={styles.labelInput}>E-mail</Text>
<Input
containerStyle={styles.containerInput}
inputStyle={styles.input}
placeholderTextColor="#999999"
placeholder="Digite seu E-mail"
/>
<Text style={styles.labelInput}>Senha</Text>
<Input
containerStyle={styles.containerInput}
inputStyle={styles.input}
placeholderTextColor="#999999"
placeholder="Digite sua senha"
/>
</View>
) : (
<View style={{width: '100%'}}>
<Text style={styles.labelInput}>DIGITE O NÚMERO DO SEU CELULAR</Text>
<Input
containerStyle={styles.containerInput}
inputStyle={styles.input}
placeholderTextColor="#999999"
placeholder="+55 (00) 00000-0000"
/>
</View>
)}
<TouchableOpacity onPress={this.ShowHideComponent}>
<Text style={styles.usePhoneNumber}>
{this.state.show ? 'Usar número do seu celular' : 'Usar E-mail'}
</Text>
</TouchableOpacity>
<Button
title="ENTRAR"
titleStyle={styles.buttonTitle}
buttonStyle={styles.button}
containerStyle={styles.buttonContainer}
//onPress={() => this.props.navigation.navigate('Signup')}
/>
{this.state.show ? (
<TouchableOpacity onPress={() => this.props.navigation.navigate('RecoverPass')}>
<Text style={styles.passwordRecovery}>Recuperar senha</Text>
</TouchableOpacity>
) : null}
<View style={styles.divider} />
<View style={styles.container}>
<Text style={styles.isCustomer}>Ainda não tem uma conta?</Text>
<TouchableOpacity onPress={() => this.props.navigation.navigate('Signup')}>
<Text style={styles.clickHere}>Cadastre-se</Text>
</TouchableOpacity>
</View>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
backgroundImage: {
width: '100%',
height: '100%',
flex: 1,
alignItems: 'center',
},
logo: {
resizeMode: 'center',
marginTop: -24,
width: '36%',
},
escale: {
resizeMode: 'center',
// todo:corrigir
marginTop: -96,
width: '70%',
},
input: {
backgroundColor: '#ffffff',
borderRadius: 8,
paddingHorizontal: 16,
height: 24,
},
accessTitle: {
fontSize: 18,
color: '#ffffff',
paddingBottom: 8,
marginTop: -32,
fontFamily: 'oswaldBold',
},
containerInput: {
marginBottom: 6,
paddingHorizontal: 16,
marginTop: -6,
},
labelInput: {
color: '#ffffff',
fontSize: 16,
paddingBottom: 4,
fontFamily: 'oswaldRegular',
alignSelf: 'flex-start',
marginLeft: 16,
},
buttonContainer: {
marginTop: 8,
width: '90%',
},
button: {
backgroundColor: '#2D8E43',
borderRadius: 12,
height: 40,
},
buttonTitle: {
color: '#FFFFFF',
fontFamily: 'oswaldRegular',
fontSize: 18,
marginVertical: 6,
paddingHorizontal: 32,
},
clickHere: {
color: '#fff',
fontWeight: 'bold',
fontSize: 16,
paddingHorizontal: 2,
paddingBottom: 4,
textDecorationLine: 'underline',
},
passwordRecovery: {
color: '#fff',
fontSize: 16,
fontFamily: 'oswaldRegular',
paddingHorizontal: 2,
paddingBottom: 4,
marginTop: 12,
textDecorationLine: 'underline',
},
container: {
paddingTop: 16,
flexDirection: 'row',
alignItems: 'center',
paddingBottom: 12,
},
isCustomer: {
color: '#fff',
fontWeight: 'bold',
fontSize: 16,
paddingHorizontal: 2,
paddingBottom: 4,
},
usePhoneNumber: {
color: '#fff',
fontFamily: 'oswaldRegular',
fontSize: 16,
paddingHorizontal: 2,
paddingBottom: 8,
textDecorationLine: 'underline',
},
divider: {
marginTop: 32,
borderBottomColor: '#FFFFFF',
borderBottomWidth: 1,
width: '90%',
},
});
<file_sep>/src/pages/Main/Modal/TermsModal/index.js
/* eslint-disable react/prefer-stateless-function */
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import styled from 'styled-components';
const Body = styled.View`
width: 90%;
margin: 0 auto;
`;
const Title = styled.Text`
text-align: center;
padding-top: 20px;
font-size: 25px;
font-weight: bold;
color: #fffed8;
margin-bottom: 40px;
`;
const Topic = styled.Text`
font-size: 25px;
font-weight: bold;
font-style: italic;
color: #fffed8;
margin-top: 20px;
margin-bottom: 20px;
`;
const Paragraph = styled.Text`
color: #fffed8;
`;
export default class TermsModal extends Component {
constructor(props) {
super(props);
}
render() {
const APP_NAME = '';
const DOMAIN = '';
const BRAND_SITE = '';
return (
<Body>
<Title>TERMOS DE USO</Title>
<Topic>1. {APP_NAME}</Topic>
<Paragraph>
1.1. O presente termo contempla as condições de uso da plataforma eletrônica do {APP_NAME}{' '}
no Brasil.
</Paragraph>
<Paragraph>
1.1.1 Este termo de uso (“Termo de Uso”) regulamenta a utilização da plataforma eletrônica
para o uso da versão web (“Website”) e do aplicativo {APP_NAME} (“Aplicativo”) no site{' '}
{DOMAIN.toUpperCase()}, seu download e demais sistemas de acesso e instalação,
disponibilizados pela empresa {BRAND_SITE}, aos seus usuários, através do endereço
eletrônico {DOMAIN}. No ato de adesão à Plataforma, o usuário (doravante “Usuário”) se
obriga a aceitar, plenamente e sem reservas, todos os termos e condições deste Termo de
Uso, que tem por objetivo a definição de regras de uso com a finalidade de promover a
informação, entretenimento, diversão e lazer dos seus usuários.
</Paragraph>
<Paragraph>
1.2.1 A {BRAND_SITE} disponibilizará, através do site {DOMAIN} o acesso a versão web ao
Usuário, através do qual será possível interagir em uma plataforma denominada {APP_NAME},
onde fatos do mundo real influenciam os resultados obtidos no mundo virtual.
</Paragraph>
<Paragraph>
1.2.2 O jogo tem versão web sendo responsivo a acesso mobile podendo ser utilizado através
de computadores e notebooks pelos navegadores web ou através do seu celular pelo endereço{' '}
{DOMAIN}.
</Paragraph>
<Paragraph>
1.2.3 A Plataforma destina-se apenas para fins de informação e entretenimento, tratando-se
de um entretenimento de estratégia e habilidade, podendo ser utilizada de forma gratuita
sem restrições de jogabilidade e usabilidade.
</Paragraph>
<Topic>2. CADASTRO E CONDIÇÕES DE USO</Topic>
<Paragraph>
2.1 A partir de 12 de junho de 2018, poderá ser utilizada a versão disponibilizada pelos
usuários que cumpram os requisitos mínimos identificados neste Termo.
</Paragraph>
<Paragraph>
2.1.1 Os Usuários dos Serviços de Entretenimento {APP_NAME} serão conjuntamente
denominados neste termo simplesmente como “Usuários”.
</Paragraph>
<Paragraph>
2.1.2 O Usuário declara estar plenamente apto às práticas dos atos da vida civil, sendo
que não há restrição de idade. Caso o Usuário se trate de pessoa que necessite de
representação na forma da lei, deverá estar devidamente representado ou assistido
(conforme o caso), por seus representantes legais, os quais deverão contratar o {APP_NAME}{' '}
em caráter de representação ou assistência, responsabilizando-se integralmente pelo
Usuário e seus atos. O Usuário (e seu representante legal, quando for o caso), declara
estar ciente de todos os direitos e obrigações aqui estabelecidos, com os quais
expressamente concorda.
</Paragraph>
<Paragraph>
2.1.3 No {APP_NAME}, poderá ser exigido um cadastro no site, com a indicação de nome,
e-mail, sexo, data de nascimento, endereço completo, CPF, celular e outros elementos de
identificação que se demonstrem necessários com o tempo para cumprimento das formalidades
legais e objetivos da plataforma. O Usuário e/ou o seu representante legal é/são o(s)
único(s) responsável(is) pelas informações cadastrais prestadas, respondendo pela
veracidade e correção dos dados. O Usuário se compromete a informar à {BRAND_SITE}{' '}
qualquer alteração em seus dados cadastrais no prazo de até 10 (dez) dias, mantendo-os
sempre atualizados. Periodicamente a plataforma poderá solicitar ao Usuário que valide os
dados cadastrais informados, para confirmação de sua veracidade e validade. Caso o Usuário
deixe de atualizar ou validar as suas informações, a utilização da plataforma eletrônica
nas suas diversas formas poderá ser suspensa até que o Usuário tenha atualizado ou
validado a veracidade de suas informações cadastrais. O Usuário desde já autoriza a{' '}
{BRAND_SITE}, sempre que julgar necessário, por si ou por terceiros por ela credenciados,
solicitar documentos adicionais para comprovação dos dados informados, que deverão ser
disponibilizados pelo Usuário no prazo máximo de 10 (dez) dias. A {BRAND_SITE} poderá,
ainda, consultar quaisquer bancos de dados, inclusive bases de restrições creditícias,
para validação das informações prestadas pelo Usuário. A verificação de documentos e/ou
consulta de bases de dados pela {BRAND_SITE} não confere ao Usuário atestado de
regularidade para qualquer finalidade, nem o exime do cumprimento das obrigações previstas
neste Termo de Uso.
</Paragraph>
<Topic>3. FORMAS E RESPONSABILIDADE DE CADASTRAMENTO</Topic>
<Paragraph>
3.1 Os Serviços de Entretenimento descritos neste Termo serão disponibilizados através dos
meios disponíveis no momento do cadastramento, mediante o correto preenchimento das
informações solicitadas e cumprimento integral das condições legalmente previstas e
constantes neste Termo atualizados em conformidade pela {BRAND_SITE}. Uma vez finalizado o
cadastro do Usuário, a {BRAND_SITE} liberará a utilização das funcionalidades da
plataforma, passando este Termo de Uso a vigorar automaticamente em relação ao Usuário. O
Usuário é o único responsável pela guarda e utilização do login e senha cadastrados para
acesso a plataforma e jogo, sendo vedada sua divulgação a terceiros. O Usuário desde já
concorda que toda e qualquer operação realizada com o login e senha cadastrados pelo
Usuário, ainda que sem sua autorização, será de sua inteira e exclusiva responsabilidade.
</Paragraph>
<Topic>4. PRAZO E PERÍODO DE DISPONIBILIZAÇÃO DO {APP_NAME}</Topic>
<Paragraph>
4.1 A utilização da plataforma eletrônica e aplicativos será disponibilizada com prazo até
28/02/2019 e enquanto se demonstrarem cumpridas as condições estipuladas no presente Termo
e demais Regulamentos pertinentes.
</Paragraph>
<Topic>5. MECÂNICA E REGRAS DO {APP_NAME}</Topic>
<Paragraph>5.1. O {APP_NAME} tem diversos módulos com atrativos diferentes:</Paragraph>
<Paragraph>
5.1.1 Ao subscrever o {APP_NAME}, os Usuários receberão o total de $ 100.000 (cem mil) em
moedas virtuais sem nenhum valor real usadas no jogo. O objetivo do Usuário no módulo
Fantasy é acumular pontos escalando um time de jogadores de acordo de diversos torneios
reais de futebol conforme descritas nas Regras do Jogo. Cada jogador pontua de acordo com
a sua performance durante o Campeonato. O Usuário que acumular mais pontos é o vencedor do
Fantasy.{' '}
</Paragraph>
<Paragraph>
5.1.2 O Usuário também pode dar palpites no resultado de jogos para participar de um Bolão
onde acumula pontos de acordo com os seus palpites em comparação com os resultados reais
dos jogos. Novamente, o Usuário que acumular mais pontos é o vencedor do Bolão.
</Paragraph>
<Paragraph>
5.1.3 A terceira forma do usuário participar do jogo é através da criação e participação
em Ligas onde ele pode ser convidado ou criar Ligas com amigos para disputar até três (3)
Ligas Fantasy e até três (3) Ligas Bolão para concorrer somente com os usuários que
estiverem na Liga. O Usuário que tiver mais pontos na Liga, ganha.
</Paragraph>
<Paragraph>
5.1.4 A quarta forma de participar do jogo é aquela em que cada Usuário pode participar
com mais quatro (4) Usuários de uma Seleção que joga com equipes formadas por mais cinco
(5) usuários onde os seus resultados são somados a cada rodada para ver qual a Seleção que
acumula mais pontos e é o campeão das Seleções.
</Paragraph>
<Paragraph>
5.2 O usuário não é obrigado a participar em todas os módulos. Ele é livre para escolher
as fórmulas que mais gosta ou se identifica.
</Paragraph>
<Topic>6. RANKINGS E SUAS MECÂNICAS</Topic>
<Paragraph>
6.1 O {APP_NAME} é uma competição mensal em formato de rankings. Cada jogador participará
da Liga única de cada torneio disponibilizado no jogo e pode participar de Ligas criadas
por ele ou outros usuários nas modalidades Fantasy e Bolão. O Ranking é a classificação do
Usuário em cada uma das Ligas em que participa.
</Paragraph>
<Topic>7. PROPRIEDADE INTELECTUAL</Topic>
<Paragraph>
7.1 A {BRAND_SITE} concede aos Usuários uma licença não exclusiva, intransferível e
limitada de acesso para utilizar os Serviços de Informação e Entretenimento,
exclusivamente para uso pessoal, sem fins comerciais e desde que integralmente atendidas
as condições previstas neste termo.
</Paragraph>
<Paragraph>
7.2 Tendo em vista o caráter da licença concedida para acesso aos Serviços de Informacao e
Entretenimento, os Usuários não poderão, diretamente ou através de dispositivo, mecanismo,
software ou qualquer outro meio, exemplificativamente (i) remover, alterar, interferir,
evitar ou de qualquer forma modificar marca d’água, copyright, símbolo, marca ou qualquer
outro sinal indicativo de propriedade relativos aos Serviços de Informação Entretenimento,
ou quaisquer direitos e/ou mecanismos de proteção associados aos Serviços; (ii) copiar,
fazer download, capturar, reproduzir, arquivar, distribuir, fazer upload, publicar,
modificar, traduzir, exibir, transmitir, apropriar, incorporar ou comercializar os
Serviços de Entretenimento; (iii) incorporar os Serviços de Entretenimento a qualquer
aplicativo de software ou hardware, exibir ou retransmitir os Serviços de Entretenimento
através dos mesmos, ou torná-lo disponível através de frames ou links; (iv) distribuir,
anunciar ou desenvolver um negócio a partir dos Serviços de Entretenimento; (v) utilizar
os Serviços de Entretenimento ou parte deles, de qualquer forma, para a criação de obras
derivadas ou nele baseadas, tais como montagens, vídeos similares e materiais de marketing
ou merchandising, entre outros.
</Paragraph>
<Paragraph>
7.3 A {BRAND_SITE} esta licenciada para uso de todos os direitos relacionados ao Uso da
Plataforma durante o período de vigência deste termo. O uso da Plataforma, das informações
e as demais funcionalidades do Fantasy.{BRAND_SITE}, nomeadamente logo , marca e outros
são protegidos pela legislação de direitos autorais e outros direitos de propriedade
intelectual. Neste sentido, e conforme descrito acima, os Usuários não poderão reproduzir,
copiar, utilizar, executar, criar trabalhos derivados, republicar, fazer upload, editar,
enviar, transmitir ou distribuir, por qualquer meio que seja, quaisquer partes dos
Serviços de Entretenimento, marcas, materiais, entre outros, de titularidade da{' '}
{BRAND_SITE} ou por ela utilizados sob licença , sem a autorização prévia por escrito
desta.
</Paragraph>
<Paragraph>
7.4 Fica expressamente vedada qualquer prática que possa prejudicar a imagem da{' '}
{BRAND_SITE} ou violar direitos desta sobre os Serviços de Informação e Entretenimento,
danificar seus patrimônios, danificar ou de qualquer forma interferir no fluxo normal de
comunicações com seus servidores, na segurança, inviolabilidade e privacidade dos dados lá
armazenados e transmitidos.
</Paragraph>
<Topic>8. DISPOSIÇÕES GERAIS</Topic>
<Paragraph>
8.1 Este Termo de Uso estará disponível em todas as plataformas que disponibilizam o{' '}
{APP_NAME}.com, sendo que os mesmos poderão ser imediatamente cancelados para os Usuários
que praticarem atos que desrespeitem a legislação vigente e as regras deste Termo e/ou que
utilizarem quaisquer meios ilícitos ou não expressamente permitidos para obter benefício
próprio ou para terceiro.
</Paragraph>
<Paragraph>
8.1.1 Sem prejuízo do disposto neste termo, poderão ter igualmente a utilização do{' '}
{APP_NAME} suspensa, desativada e/ou cancelada, a exclusivo critério da {BRAND_SITE}, os
Usuários que desrespeitarem as políticas de segurança e privacidade do site {DOMAIN}.
</Paragraph>
<Paragraph>
8.2 As questões não expressamente previstas neste termo serão analisadas e julgadas pelo
departamento de atendimento ao cliente da {BRAND_SITE}, cujas decisões serão a critério da{' '}
{BRAND_SITE} publicadas no site {DOMAIN} e/ou enviadas ao Usuário por e-mail ou outro meio
escrito.
</Paragraph>
<Paragraph>
.3 O Usuário concorda com todas as condições deste termo sem reservas a partir da
disponibilização dos Serviços de Entretenimento do {APP_NAME} e reconhece que este termo
poderá ser alterado pela {BRAND_SITE} sempre que necessário e a seu exclusivo critério. A{' '}
{BRAND_SITE} publicará as atualizações no website {DOMAIN}.
</Paragraph>
<Paragraph>
8.4 O {APP_NAME} dispõe de uma estrutura tecnológica assente em sistemas de hardware e
software dedicados à sua operação, sendo que a {BRAND_SITE} se reserva o direito de
efetuar toda e qualquer ação de manutenção, correção e atualização que se demonstrarem
necessárias nas suas plataformas, podendo ou não a seu critério informar os Usuários das
referidas modificações e/ou atualizações.
</Paragraph>
<Paragraph>
8.5 O Usuário reconhece e declara estar ciente de que poderá haver interrupções na
disponibilização e acessibilidade da plataforma eletrônica e aplicativos do {APP_NAME}{' '}
pela {BRAND_SITE} por motivos técnicos, em razão de manutenção preventiva ou corretiva ou
por motivos de caso fortuito ou força maior. A {BRAND_SITE} não garante que a
disponibilidade e acessibilidade da plataforma eletrônica e aplicativos ficarão sem
interrupção, nem se responsabiliza por eventuais operações que deixem de ser realizadas
durante os períodos de indisponibilidade.
</Paragraph>
<Paragraph>
8.6. Reconhecem os Usuários que terceiros de má-fé poderão se utilizar de subterfúgios
tecnológicos a fim de ter acesso a seus dados pessoais e/ou a fraudar as funcionalidades
da plataforma eletrônica e dos aplicativos e, portanto, isentam a {BRAND_SITE} de qualquer
responsabilidade correlata.
</Paragraph>
<Paragraph>
8.7 Os Usuários, no ato da aquisição, declaram aderir sem reservas as disposições
constantes deste regulamento e autorizam desde logo de forma gratuita a divulgação pela{' '}
{BRAND_SITE}, a seu critério, das informações respeitantes em especial aos seus nomes e
respectivas pontuações, no ambiente da plataforma e seus aplicativos, bem como em qualquer
outro meio audiovisual.
</Paragraph>
<Paragraph>
8.8 A {BRAND_SITE} poderá suspender ou interromper definitivamente os Serviços de
Informação e Entretenimento, a qualquer tempo, a seu exclusivo critério.
</Paragraph>
<Paragraph>
8.9 Os Usuários obrigam-se a cumprir todas as regras sobre prevenção e combate aos crimes
de lavagem de dinheiro, de terrorismo e seu financiamento, entre outros, a ocultação de
bens especificados pela Lei nº 9.613/98, conforme alterada, e pelo Conselho de Controle de
Atividades Financeiras, além de outras legislações e regulamentações aplicáveis às
hipóteses, bem como a colaborar de forma efetiva com as autoridades, órgãos de regulação
e/ou de fiscalização, incluindo órgãos de defesa do consumidor, no fornecimento de dados
e/ou informações, quando legalmente admitidos, inclusive, mas sem limitação, no que tange
à prevenção e combate aos crimes de lavagem de dinheiro e ocultação de bens aos crimes
contra crianças e adolescentes, adotando todas as medidas necessárias de sua
responsabilidade para coibir tais ilícitos. O Usuário declara e garante que não pratica ou
praticará quaisquer atos que sejam tidos como lavagem de dinheiro ou ocultação de bens,
direitos ou valores. O Usuário deverá informar a {BRAND_SITE} imediatamente sobre qualquer
situação que possa estar relacionada à lavagem de dinheiro e/ou ao financiamento do
terrorismo e que possam afetar a {BRAND_SITE} direta ou indiretamente.
</Paragraph>
<Paragraph>
8.10 Aplica-se a este regulamento a legislação brasileira e fica desde já eleito o Foro
Central da Comarca da Capital do Estado de São Paulo para dirimir quaisquer controvérsias
dele oriundas, caso as mesmas não possam ser resolvidas pelo serviço de atendimento ao
Cliente da {BRAND_SITE}.
</Paragraph>
<Paragraph>Termo de Uso – V.02 – datada de 30 de julho de 2018</Paragraph>
</Body>
);
}
}
<file_sep>/src/pages/Signup/CreateShield/index.js
import React, { Component } from 'react';
import {
StyleSheet, View, TouchableOpacity, Image, FlatList,
} from 'react-native';
import { Text, ButtonGroup, Icon, Button } from 'react-native-elements';
const styles = StyleSheet.create({
container: {
backgroundColor: '#141414',
flex: 1,
},
card: {
marginTop: 56,
backgroundColor: '#3A3A3C',
borderWidth: 0,
marginLeft: 16,
marginRight: 16,
borderRadius: 12,
alignItems: 'center',
},
cardTitle: {
fontSize: 18,
color: 'white',
fontWeight: 'bold',
marginTop: 16,
},
containerModelSelect: {
flexDirection: 'row',
height: '50%',
marginTop: 16,
alignItems: 'center',
marginBottom: 16,
},
containerButtonGroup: {
height: 40,
backgroundColor: '#1E1E1E',
borderWidth: 0,
marginTop: -64,
},
selectedButtonGroup: {
backgroundColor: '#707375',
},
selectedButtonGroupText: {
fontWeight: 'bold',
},
innerBorderButtonGroup: {
color: '#3A3A3C',
},
arrowContainer: {
height: 60,
alignItems: 'center',
},
shieldBack: {
marginLeft: 16,
marginRight: 16,
},
patternsList: {
marginTop: 16,
},
patternsList2: {
marginTop: -16,
},
itemList: {
paddingHorizontal: 4,
},
backShieldSelectContainer: {
marginTop: -56,
width: '100%',
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingHorizontal: 42,
},
containerStyleButton: {
width: '90%',
marginTop: 16,
backgroundColor: '#5C9C23',
alignSelf: 'center',
},
buttonStyle: {
backgroundColor: '#5C9C23',
borderRadius: 10,
height: 48,
},
buttonTitleStyle: {
marginRight: 60,
marginLeft: 60,
fontWeight: 'bold',
},
containerRandomButton: {
width: '90%',
marginTop: 16,
alignSelf: 'center',
},
randomButton: {
backgroundColor: '#3A3A3C',
borderRadius: 10,
height: 48,
},
randomButtonTitle: {
marginRight: 60,
marginLeft: 60,
fontWeight: 'bold',
fontSize: 14,
},
});
export default class CreateShield extends Component {
constructor() {
super();
this.state = {
selectedIndex: 0,
data: [
{ uri: require('~/assets/signup/buttons/patterns/img-padrao-1-selecionar.png') },
{ uri: require('~/assets/signup/buttons/patterns/img-padrao-2-selecionar.png') },
{ uri: require('~/assets/signup/buttons/patterns/img-padrao-3-selecionar.png') },
{ uri: require('~/assets/signup/buttons/patterns/img-padrao-4-selecionar.png') },
{ uri: require('~/assets/signup/buttons/patterns/img-padrao-5-selecionar.png') },
{ uri: require('~/assets/signup/buttons/patterns/img-padrao-6-selecionar.png') },
{ uri: require('~/assets/signup/buttons/patterns/img-padrao-7-selecionar.png') },
],
data2: [
{ uri: require('~/assets/signup/buttons/patterns/img-padrao-8-selecionar.png') },
{ uri: require('~/assets/signup/buttons/patterns/img-padrao-9-selecionar.png') },
{ uri: require('~/assets/signup/buttons/patterns/img-padrao-10-selecionar.png') },
],
};
this.updateIndex = this.updateIndex.bind(this);
}
updateIndex(selectedIndex) {
this.setState({ selectedIndex });
}
render() {
const buttons = ['PADRÕES', 'CORES', 'ORNAMENTOS'];
const { selectedIndex } = this.state;
const currentShieldBack = require('~/assets/signup/shield-backs/escudo-1-fundo.png');
return (
<View style={styles.container}>
<View style={styles.card}>
<Text style={styles.cardTitle}><NAME></Text>
<View style={styles.containerModelSelect}>
<View style={styles.backShieldSelectContainer}>
<TouchableOpacity style={styles.arrowContainer}>
<Icon
name="chevron-left"
type="font-awesome"
color="#fff"
size={56}
/>
</TouchableOpacity>
<View>
<Image style={styles.shieldBack} source={currentShieldBack} />
</View>
<TouchableOpacity style={styles.arrowContainer}>
<Icon
name="chevron-right"
type="font-awesome"
color="#fff"
size={56}
/>
</TouchableOpacity>
</View>
</View>
<ButtonGroup
onPress={this.updateIndex}
selectedIndex={selectedIndex}
buttons={buttons}
containerStyle={styles.containerButtonGroup}
selectedButtonStyle={styles.selectedButtonGroup}
selectedTextStyle={styles.selectedButtonGroupText}
innerBorderStyle={styles.innerBorderButtonGroup}
/>
<FlatList
style={styles.patternsList}
numColumns={7}
data={this.state.data}
keyExtractor={item => item.uri}
renderItem={({ item }) => (
<View style={styles.itemList} >
<Image style={styles.imageItemList} source={item.uri}></Image>
</View>
)}
/>
<FlatList
style={styles.patternsList2}
numColumns={6}
data={this.state.data2}
keyExtractor={item => item.uri}
renderItem={({ item }) => (
<View style={styles.itemList} >
<Image style={styles.imageItemList} source={item.uri}></Image>
</View>
)}
/>
</View>
<Button
containerStyle={styles.containerRandomButton}
buttonStyle={styles.randomButton}
titleStyle={styles.randomButtonTitle}
title="MONTE PRA MIM"
onPress={() => alert('seleciona valores randomicamente')}
/>
<Button
containerStyle={styles.containerStyleButton}
buttonStyle={styles.buttonStyle}
icon={<Icon name="chevron-right" size={48} color="white" />}
iconContainerStyle={{ marginLeft: 80 }}
iconRight
titleStyle={styles.buttonTitleStyle}
title="TÁ LINDO. VAIIIII!!!"
onPress={() => this.props.navigation.navigate('SelectClothes')}
/>
<Image style={styles.bottomImage} source={require('~/assets/background.png')} />
</View>
);
}
}
<file_sep>/src/pages/Signup/SelectClothes/index.js
import React, { Component } from 'react';
import {
StyleSheet, View, TouchableOpacity, Image,
} from 'react-native';
import { Text, Icon, Button } from 'react-native-elements';
const styles = StyleSheet.create({
container: {
backgroundColor: '#141414',
flex: 1,
alignItems: 'center',
},
card: {
marginTop: 56,
backgroundColor: '#3A3A3C',
borderWidth: 0,
marginLeft: 16,
marginRight: 16,
borderRadius: 12,
alignItems: 'center',
},
cardTitle: {
fontSize: 18,
color: 'white',
fontWeight: 'bold',
marginTop: 12,
},
containerClothesSelect: {
flexDirection: 'row',
height: '30%',
marginTop: 36,
alignItems: 'center',
marginBottom: 8,
},
arrowContainer: {
height: 60,
alignItems: 'center',
paddingHorizontal: 12,
},
backShieldSelectContainer: {
marginTop: 16,
width: '100%',
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
bottomImage: {
resizeMode: 'cover',
},
containerStyleButton: {
width: '90%',
marginTop: 16,
backgroundColor: '#5C9C23',
},
buttonStyle: {
backgroundColor: '#5C9C23',
borderRadius: 10,
height: 48,
},
buttonTitleStyle: {
marginRight: 60,
marginLeft: 60,
fontWeight: 'bold',
},
});
export default class SelectClothes extends Component {
constructor() {
super();
this.state = {};
}
render() {
return (
<View style={styles.container}>
<View style={styles.card}>
<Text style={styles.cardTitle}><NAME></Text>
<View style={styles.containerClothesSelect}>
<View style={styles.backShieldSelectContainer}>
<TouchableOpacity style={styles.arrowContainer}>
<Icon name="chevron-left" type="font-awesome" color="#fff" size={50} />
</TouchableOpacity>
<View>
<Image
style={styles.shieldBack}
source={require('~/assets/signup/coach/vestimenta-01.png')}
/>
</View>
<TouchableOpacity style={styles.arrowContainer}>
<Icon name="chevron-right" type="font-awesome" color="#fff" size={50} />
</TouchableOpacity>
</View>
</View>
</View>
<Button
containerStyle={styles.containerStyleButton}
buttonStyle={styles.buttonStyle}
icon={<Icon name="chevron-right" size={48} color="white" />}
iconContainerStyle={{ marginLeft: 80 }}
iconRight
titleStyle={styles.buttonTitleStyle}
title="TÁ NA GRIFE. BORA!!!"
onPress={() => this.props.navigation.navigate('FinalStep')}
/>
<Image style={styles.bottomImage} source={require('~/assets/background.png')} />
</View>
);
}
}
<file_sep>/src/routes.js
import { createAppContainer, createStackNavigator } from 'react-navigation';
import Main from '~/pages/Main';
import Login from '~/pages/Login';
import MenuExample from '~/pages/Main/Menu';
import Signup from '~/pages/Signup';
import CreateShield from '~/pages/Signup/CreateShield';
import SelectClothes from '~/pages/Signup/SelectClothes';
import FinalStep from '~/pages/Signup/FinalStep';
import RecoverPass from '~/pages/RecoverPass';
const Routes = createAppContainer(
createStackNavigator({
Main: {
screen: Main,
navigationOptions: {
title: '',
headerTransparent: 'true',
},
},
Login: {
screen: Login,
navigationOptions: {
title: '',
headerTransparent: 'true',
},
},
RecoverPass: {
screen: RecoverPass,
navigationOptions: {
title: '',
headerTransparent: 'true',
},
},
FinalStep: {
screen: FinalStep,
navigationOptions: {
title: 'SÓ FALTA SABER QUEM É VOCÊ',
headerTransparent: 'true',
headerTintColor: '#fff',
headerTitleStyle: { alignSelf: 'center' },
},
},
SelectClothes: {
screen: SelectClothes,
navigationOptions: {
title: 'E AGORA PRA FICAR NA ESTICA',
headerTransparent: 'true',
headerTintColor: '#fff',
headerTitleStyle: { alignSelf: 'center' },
},
},
CreateShield: {
screen: CreateShield,
navigationOptions: {
title: 'VAMOS FAZER SEU ESCUDO!',
headerTransparent: 'true',
headerTintColor: '#fff',
headerTitleStyle: { alignSelf: 'center' },
},
},
Signup: {
screen: Signup,
navigationOptions: {
title: 'VAMOS CRIAR SEU TIME!',
headerTransparent: 'true',
headerTintColor: '#fff',
headerTitleStyle: {
alignSelf: 'center',
justifyContent: 'center',
fontFamily: 'oswaldRegular',
fontWeight: '400',
},
},
},
MenuExample: {
screen: MenuExample,
navigationOptions: {
title: '',
headerTransparent: 'true',
},
},
}),
);
export default Routes;
<file_sep>/src/pages/RecoverPass/index.js
import React from 'react';
import {
View, Text, StyleSheet, Image, ImageBackground,
} from 'react-native';
import { Button, Input } from 'react-native-elements';
// eslint-disable-next-line react/prefer-stateless-function
export default class RecoverPass extends React.Component {
render() {
return (
<ImageBackground
source={require('../../assets/soccer-background.jpg')}
style={styles.backgroundImage}
resizeMode="cover"
>
<Image source={require('../../assets/logo.png')} style={styles.logo} />
<Image
source={require('../../assets/escale.png')}
style={styles.escale}
/>
<Text style={styles.accessTitle}>RECUPERE SUA SENHA</Text>
<Input
containerStyle={styles.containerInput}
inputStyle={styles.input}
placeholderTextColor="#999999"
placeholder="Email"
label="DIGITE SEU EMAIL"
labelStyle={styles.labelInput}
/>
<Button
title="RECUPERAR SENHA"
titleStyle={styles.buttonTitle}
buttonStyle={styles.button}
containerStyle={styles.buttonContainer}
/>
<View style={styles.footerContainer}>
<View
style={{
marginTop: 16,
borderBottomColor: '#FFFFFF',
borderBottomWidth: 1,
width: '90%',
}}
/>
<View style={styles.container}>
<Text style={styles.isCustomer}>Ainda não tem uma conta?</Text>
<Text style={styles.clickHere}>Cadastre-se</Text>
</View>
</View>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
backgroundImage: {
width: '100%',
height: '100%',
flex: 1,
alignItems: 'center',
},
logo: {
resizeMode: 'center',
marginTop: -24,
width: '36%',
},
escale: {
resizeMode: 'center',
// todo:corrigir
marginTop: -96,
width: '70%',
},
input: {
backgroundColor: '#ffffff',
borderRadius: 8,
paddingHorizontal: 16,
height: 8,
},
accessTitle: {
fontSize: 16,
color: '#ffffff',
fontWeight: 'bold',
paddingBottom: 8,
marginTop: -24,
},
containerInput: {
marginBottom: 6,
paddingHorizontal: 16,
marginTop: 16,
},
labelInput: {
color: '#ffffff',
fontSize: 16,
paddingBottom: 4,
},
buttonContainer: {
marginTop: 16,
width: '90%',
},
button: {
backgroundColor: '#2D8E43',
borderRadius: 12,
height: 48,
},
buttonTitle: {
color: '#FFFFFF',
fontWeight: 'bold',
fontSize: 16,
paddingHorizontal: 32,
},
clickHere: {
color: '#fff',
fontWeight: 'bold',
fontSize: 16,
paddingHorizontal: 2,
paddingBottom: 4,
textDecorationLine: 'underline',
},
container: {
paddingTop: 16,
flexDirection: 'row',
alignItems: 'center',
paddingBottom: 12,
},
isCustomer: {
color: '#fff',
fontWeight: 'bold',
fontSize: 16,
paddingHorizontal: 2,
paddingBottom: 4,
},
footerContainer: {
flex: 1,
width: '100%',
alignItems: 'center',
marginTop: 28,
},
});
| 72e2ed5f2fea3ea2f853e40bc214b57366cd385b | [
"Markdown",
"JavaScript",
"Ruby"
] | 10 | Markdown | rodrigobarro/meutimefcapp | 4e19fbf2f4fa2d23378a490fdadd6a6af425c3f8 | 5ee7419e7c66a6f2958fed342d50763e70c7d1fc |
refs/heads/main | <repo_name>MitsuiWei/Temperature-conversion<file_sep>/temperature.py
tem = input('請問你要將華氏轉攝氏(F),還是攝氏轉華氏(C): ')
if tem == 'F':
f = input('請輸入華氏溫度:')
f = int(f)
c = (f - 32) * 0.555
print('相當於攝氏溫度:', c)
elif tem == 'C':
c = input('請輸入攝氏溫度:')
c = int(c)
f = (c * 1.8) + 32
print('相當於華氏溫度:', f)
#pw:0 | 128227df8358c7cffce122a1976cce0d13375885 | [
"Python"
] | 1 | Python | MitsuiWei/Temperature-conversion | ae6d007b17d8edce8613e3bc815bb4222702963f | 7339ea575feacfa791edc4f3cccbf3421ea73bfe |
refs/heads/master | <repo_name>zesbr/minigolf<file_sep>/minigolf/src/test/java/minigolf/domain/HoleTest.java
package minigolf.domain;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class HoleTest {
Hole hole;
public HoleTest() { }
@BeforeClass
public static void setUpClass() { }
@AfterClass
public static void tearDownClass() { }
@Before
public void setUp() {
hole = new Hole(100, 100);
}
@After
public void tearDown() { }
@Test
public void getMethodForHoleCoordinatesWork() {
int x = hole.getX();
int y = hole.getY();
assertEquals(100, x);
assertEquals(100, y);
}
@Test
public void setMethodForHoleCoordinatesWork() {
hole.setX(0);
hole.setY(0);
int x = hole.getX();
int y = hole.getY();
assertEquals(0, x);
assertEquals(0, y);
}
@Test
public void holeCannotBeConstructedWithNegativeCoordinates() {
hole = new Hole(-100, -100);
int x = hole.getX();
int y = hole.getY();
assertEquals(0, x);
assertEquals(0, y);
}
@Test
public void setMethodsDoesNotAcceptNegativeCoordinates() {
hole.setX(-100);
hole.setY(-100);
int x = hole.getX();
int y = hole.getY();
assertEquals(0, x);
assertEquals(0, y);
}
@Test
public void holeRadiusIsFifteen() {
int radius = hole.getRadius();
assertEquals(15, radius);
}
@Test
public void holeDiameterIsThirty() {
int diameter = hole.getDiameter();
assertEquals(30, diameter);
}
@Test
public void holeCenterIsCorrect() {
int centerX = hole.getCenterX();
int centerY = hole.getCenterY();
assertEquals(115, centerX);
assertEquals(115, centerY);
}
@Test
public void checkingIfCoordinateIsInsideHoleWorks() {
assertEquals(true, hole.inHole(120, 120));
assertEquals(false, hole.inHole(200, 200));
}
@Test
public void checkingIfCoordinateIsWithInRadius() {
assertEquals(true, hole.withinDistance(120, 120, 20));
assertEquals(false, hole.withinDistance(200, 200, 79));
}
}
<file_sep>/minigolf/src/main/java/minigolf/gui/GUI.java
package minigolf.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* Pelialustalle kuuluva graafinen käyttöliittymäpaneeli, jonka tehtävänä
* on huolehtia käyttöliittymän komponenttien luomisesta ja alustamisesta.
* @author zesbr
*/
public class GUI extends JPanel {
private GameCanvas canvas;
private PowerBar powerBar;
private JLabel hintText;
public GUI(GameCanvas canvas) {
super();
this.canvas = canvas;
this.powerBar = new PowerBar(canvas);
this.hintText = new JLabel();
init();
addComponents();
}
/**
* Palauttaa lyönnin voimapalkkikomponentin
* @return voimapalkki
*/
public PowerBar getPowerBar() {
return powerBar;
}
// Alustaa paneelin ja komponentit
private void init() {
setLayout(null);
setOpaque(false);
powerBar.setForeground(Color.blue);
powerBar.setBorderPainted(false);
powerBar.setBounds(740, 360, 20, 200);
hintText.setText("Hold and release left mouse button to shoot");
hintText.setFont(new Font("Lato Light", Font.BOLD, 18));
hintText.setForeground(Color.WHITE);
hintText.setBounds(200, 460, 600, 50);
}
/**
*
*/
public void disableHint() {
hintText.setVisible(false);
}
// Lisää komponentit paneeliin
private void addComponents() {
add(powerBar);
add(hintText);
}
}
<file_sep>/minigolf/src/main/java/minigolf/gui/MouseInputManager.java
package minigolf.gui;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* Pelialustaan liittyvä hiiren tapahtumiakäsittelijä. Luokan tehtävä on mm.
* asettaa
* @author zesbr
*/
public class MouseInputManager extends MouseAdapter {
private PowerBar powerBar;
public MouseInputManager(PowerBar powerBar) {
this.powerBar = powerBar;
}
/**
* Hiiren painikkeen painallustapahtumaa käsittelevä metodi, joka kutsuu
* käyttöliittymän voimapalkin ajastinta käynnistymään
* @param me : hiiren tapahtuma
*/
@Override
public void mousePressed(MouseEvent me) {
powerBar.startTimer();
}
/**
* Hiireen painikkeen vapauttamistapahtumaa käsittelevä metodi, joka
* asettaa voimapalkille hiiren osoittimen sijainnin koordinaatteina
* ja pysäyttää voimapalkin ajastimen
* @param me ; hiiren tapahtuma
*/
@Override
public void mouseReleased(MouseEvent me) {
Point mousePosition = me.getComponent().getMousePosition();
powerBar.setAimX(mousePosition.x);
powerBar.setAimY(mousePosition.y);
powerBar.stopTimer();
}
}
<file_sep>/minigolf/src/main/java/minigolf/Main.java
package minigolf;
import javax.swing.SwingUtilities;
/**
* Sovelluksen käynnistävä luokka, joka sisältää main metodin, jossa luodaan
* uusi sovellus-instanssi ja käynnistetään sovellus.
* @author zesbr
*/
public class Main {
public static void main(String[] args) {
App app = new App();
SwingUtilities.invokeLater(app);
}
}
<file_sep>/minigolf/src/main/java/minigolf/gui/GameCanvas.java
package minigolf.gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import javax.swing.JPanel;
import javax.swing.Timer;
import minigolf.domain.*;
import minigolf.game.*;
/**
* Sovelluksen piirtoalusta, jonka tehtävänä on huolehtia
* piirtoalustan alustamisesta sekä piirtoalustaan kohdistuvista
* piirtotapahtumista.
* @author zesbr
*/
public class GameCanvas extends JPanel {
private Game game;
private GUI gui;
private HUD hud;
private Timer timer;
private MouseInputManager mouse;
private ViewManager viewManager;
private final boolean SHOW_HUD = true;
private final boolean SHOW_GUI = true;
private final int FPS = 1000 / 60;
public GameCanvas(Game game, ViewManager viewManager) {
super();
this.game = game;
this.gui = new GUI(this);
this.hud = new HUD(this);
this.timer = new Timer(FPS, new GameCanvasUpdater(this));
this.mouse = new MouseInputManager(gui.getPowerBar());
this.viewManager = viewManager;
init();
}
// Valmistelee piirtoalustaan ja lisää siihen alikomponentit
private void init() {
setBackground(new Color(138, 224, 0));
setLayout(new GridLayout(1, 1));
add(gui);
addMouseListener(mouse);
}
/**
* Käynnistää ajastimen. Tätä kutsutaan aina puttaustapahtuman
* aluksi, kun piirtoalustaa halutaan päivittää automaattisesti
*/
public void startTimer() {
timer.start();
}
/**
* Pysäyttää ajastimen. Tätä kutsutaan aina puttaustapahtuman
* päätteksi, kun piirtoalustan automaattinen päivittäminen halutaan
* lopettaa
*/
public void stopTimer() {
timer.stop();
}
/**
* Tarkistaa onko ajastin päällä ja palauttaa totuusarvon
* @return totuusarvo, onko ajastin päällä (true) vai ei (false)
*/
public boolean timerIsRunning() {
return timer.isRunning();
}
/**
* Asettaa ajastimelle viiveen
* @param delay : viive
*/
public void setTimerDelay(int delay) {
timer.setDelay(delay);
}
/**
* Palauttaa piirtoalustan peli-instanssin. Tätä kutsutaan aina, kun
* piirtoalustan kautta halutaan päästä peli-instanssiin käsiksi
* @return peli-instanssi
*/
public Game getGame() {
return game;
}
/**
* Palauttaa piirtoalustan graafisen käyttöliittmäpaneelin
* @return
*/
public GUI getGui() {
return gui;
}
// Palauttaa reunepehmennetyn grafiikka-olion
private Graphics2D getSmootherGraphics(Graphics g) {
RenderingHints rendering = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON
);
rendering.put(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY
);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHints(rendering);
return g2d;
}
/**
* Piirtää pelikentän reiän
* @param g : grafiikka-olio
* @param hole : reikä
*/
public void paint(Graphics2D g, Hole hole) {
int x = hole.getX();
int y = hole.getY();
int diameter = hole.getDiameter();
g.setColor(Color.BLACK);
g.fillOval(x, y, diameter, diameter);
}
/**
* Piirtää pelikentän esteen
* @param g : grafiikka-olio
* @param obstacle : este
*/
public void paint(Graphics2D g, Obstacle obstacle) {
int x = obstacle.getX();
int y = obstacle.getY();
int width = obstacle.getWidth();
int height = obstacle.getHeight();
g.setColor(new Color(166, 134, 76));
g.fillRect(x, y, width, height);
}
/**
* Piirtää pallon
* @param g : grafiikka-olio
* @param ball : pallo
*/
public void paint(Graphics2D g, Ball ball) {
int x = (int) ball.getX();
int y = (int) ball.getY();
int diameter = ball.getDiameter();
g.setColor(Color.WHITE);
g.fillOval(x, y, diameter, diameter);
}
/**
* Piirtää pelialustan komponentit
* @param g : grafiikka-olio
*/
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Luo uuden reunapehmennetyn (antialias) grafiikka-olion
Graphics2D graphics = getSmootherGraphics(g);
// Haetaan nykyinen kenttä
Level level = game.getCurrentLevel();
// Piirtää kaikki kentän esteet piirtoalustaan
for (Obstacle obstacle : level.getObstacles()) {
paint(graphics, obstacle);
}
// Piirtää reiän piirtoalustaan
paint(graphics, level.getHole());
// Piirtää pallon piirtoalustaan
paint(graphics, game.getActiveBall());
}
public void showScoreCard() {
viewManager.showScorecard(game);
}
}
<file_sep>/minigolf/src/main/java/minigolf/domain/LevelObject.java
package minigolf.domain;
/**
* Pelikentällä sijaitsevien liikumattomien objektien sijaintia mallintava
* abstrakti luokka, jonka reikä, aloituspaikka ja este perivät.
* @author zesbr
*/
public abstract class LevelObject {
private int x;
private int y;
public LevelObject(int x, int y) {
setX(x);
setY(y);
}
/**
* Palauttaa kenttä-objektin x-koordinaatin
* @return x-koordinaatti
*/
public int getX() {
return x;
}
/**
* Palauttaa kenttä-objektin y-koordinaatin
* @return y-koordinaatti
*/
public int getY() {
return y;
}
/**
* Asettaa kenttä-objektin x-koordinaatin, jonka on oltava suurempi kuin 0
* @param x : x-koordinaatti
*/
public void setX(int x) {
if (x < 0) {
this.x = 0;
} else {
this.x = x;
}
}
/**
* Asettaa kenttä-objektin y-koordinaatin, jonka on oltava suurempi kuin 0
* @param y : y-koordinaatti
*/
public void setY(int y) {
if (y < 0) {
this.y = 0;
} else {
this.y = y;
}
}
}
<file_sep>/minigolf/src/test/java/minigolf/domain/LevelArchitectTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minigolf.domain;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class LevelArchitectTest {
public LevelArchitectTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void levelArchitectReturnsLevelWhenAskedForLevelThatExists() {
for (int i = 1; i <= 9; i++) {
Level lvl = LevelArchitect.buildLevel(i);
boolean actual = lvl instanceof Level;
assertEquals(true, actual);
}
}
@Test
public void levelArchitectReturnsNullWhenAskedForLevelThatDoesNotExists() {
Level actual = LevelArchitect.buildLevel(-1);
assertEquals(null, actual);
}
}
<file_sep>/README.md
# Minigolf
Ohjelmoinnin harjoitustyönä toteutettava minigolf -peli.
<file_sep>/minigolf/src/main/java/minigolf/domain/Level.java
package minigolf.domain;
import java.util.ArrayList;
import java.util.Objects;
/**
* Pelialuetta mallintava luokka, joka vastaa pelialueen ja siihen kuuluvien
* objektien määrittämisestä
* @author zesbr
*/
public class Level {
private int x;
private int y;
private int width;
private int height;
private Tee tee;
private Hole hole;
private String name;
private ArrayList<Obstacle> obstacles;
private final int WALL_THICKNESS = 20;
public Level(int x, int y, int width, int height, Tee tee, Hole hole, String name) {
if (x < 0) {
this.x = 0;
} else {
this.x = x;
}
if (y < 0) {
this.y = 0;
} else {
this.y = x;
}
this.width = width;
this.height = height;
setTee(tee);
setHole(hole);
this.name = name;
this.obstacles = new ArrayList<>();
buildWalls();
}
/**
* Palauttaa kentän x-koordinaatin
* @return x-koordinaatti
*/
public int getX() {
return x;
}
/**
* Palauttaa kentän y-koordinaatin
* @return y-koordinaatti
*/
public int getY() {
return y;
}
/**
* Palauttaa kentän leveyden
* @return leveys
*/
public int getWidth() {
return width;
}
/**
* Palauttaa kentän korkeuden
* @return korkeus
*/
public int getHeight() {
return height;
}
/**
* Palauttaa kentän aloituspaikan
* @return aloituspaikka
*/
public Tee getTee() {
return tee;
}
/**
* Asettaa kentälle uuden aloituspaikan
* @param tee : aloituspaikka
*/
public void setTee(Tee tee) {
if (!isOutOfBounds(tee.getX(), tee.getY())) {
if (hole != null) {
if (!hole.withinDistance(tee.getX(), tee.getY(), 200)) {
this.tee = tee;
}
} else {
this.tee = tee;
}
}
}
/**
* Palautttaa kentän reiän
* @return reikä
*/
public Hole getHole() {
return hole;
}
/**
* Asettaa kentälle uuden reiän
* @param hole : eikä
*/
public void setHole(Hole hole) {
if (!isOutOfBounds(hole.getX(), hole.getY())) {
if (tee != null) {
if (!hole.withinDistance(tee.getX(), tee.getY(), 200)) {
this.hole = hole;
}
} else {
this.hole = hole;
}
}
}
/**
* Palautta kentän nimen
* @return nimi
*/
public String getName() {
return this.name;
}
/**
* Palauttaa listan kentän esteistä
* @return estelista
*/
public ArrayList<Obstacle> getObstacles() {
return obstacles;
}
/**
* Lisää uuden esteen kentän estelistaan
* @param obstacle : este
*/
public void addObstacle(Obstacle obstacle) {
this.obstacles.add(obstacle);
}
/**
* Tarkistaa onko koordinaatti pelialueen ulkopuolella ja palauttaa totuusarvon
* @param x : x-koordinaatti
* @param y : y-koordinaatti
* @return totuusarvo oliko piste pelialueen ulkopuolella (true) vai sisäpuolella (false)
*/
public boolean isOutOfBounds(int x, int y) {
if (x < this.x || x > (this.x + this.width) || y < this.y || y > (this.y + this.height)) {
return true;
}
return false;
}
/**
* Tarkistaa onko pallo reiässä ja palauttaa totuusarvon
* @param ball : pelissä oleva pallo
* @return totuusarvo, onko pallo reiässä (true) vai ei (false)
*/
public boolean ballIsInHole(Ball ball) {
// Tarkistaa onko pallon keskipiste reiän kehän sisällä
if (hole.inHole(ball.getCenterX(), ball.getCenterY())) {
// Tarkistaa onko pallon nopeus liian suuri upotakseen reikään
if (ball.getSpeed() < 300) {
System.out.println("Pallo on reiässä!");
return true;
}
}
return false;
}
/**
* Tarkistaa osuuko pallo johonkin kentän esteeseen ja palauttaa totuusarvon
* @param ball : pallo
* @return totuusarvo, osuuko pallo esteeseen (true) vai ei (false)
*/
public boolean ballHitsObstacle(Ball ball) {
for (Obstacle obstacle : obstacles) {
if (obstacle.hits(ball)) {
System.out.println("TÖRMÄYS!");
return true;
}
}
return false;
}
// Rakentaa pelialuetta ympäröivät seinät uusina esteinä ja lisää ne estelistaan
private void buildWalls() {
// Määritetään seinien koordinaatit apumuuttujiin
int topLeftX = x;
int topLeftY = y;
int topRightX = x + width - WALL_THICKNESS;
int topRightY = y;
int bottomLeftX = x;
int bottomLeftY = x + height - WALL_THICKNESS;
int bottomRightX = x + width + WALL_THICKNESS;
int bottomRightY = y + height;
// Rakentaa yläseinän
addObstacle(new Obstacle(topLeftX, topLeftY, width, WALL_THICKNESS));
// Rakentaa alaseinän
addObstacle(new Obstacle(bottomLeftX, bottomLeftY, width, WALL_THICKNESS));
// Rakentaa vasemman seinän
addObstacle(new Obstacle(topLeftX, (topLeftY + WALL_THICKNESS), WALL_THICKNESS, (height - (2 * WALL_THICKNESS))));
// Asettaa oikean seinän
addObstacle(new Obstacle(topRightX, (topRightY + WALL_THICKNESS), WALL_THICKNESS, (height - (2 * WALL_THICKNESS))));
}
}<file_sep>/minigolf/src/test/java/minigolf/domain/ObstacleTest.java
package minigolf.domain;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class ObstacleTest {
private Obstacle obstacle;
public ObstacleTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
obstacle = new Obstacle(100, 100, 100, 20);
}
@After
public void tearDown() {
}
@Test
public void getWidthWorks() {
int width = obstacle.getWidth();
assertEquals(100, width);
}
@Test
public void getHeightWorks() {
int height = obstacle.getHeight();
assertEquals(20, height);
}
@Test
public void getTopSideYWorks() {
assertEquals(100, obstacle.getTopSideY());
}
@Test
public void getRightSideXWorks() {
assertEquals(200, obstacle.getRightSideX());
}
@Test
public void getBottomSideYWorks() {
assertEquals(120, obstacle.getBottomSideY());
}
@Test
public void getLeftSideXWorks() {
assertEquals(100, obstacle.getLeftSideX());
}
@Test
public void checkingIfCoordinateIsInsideObstacleBordersWork() {
assertEquals(true, obstacle.inside(150, 110));
assertEquals(false, obstacle.inside(500, 500));
}
@Test
public void collisionDetectionForTopSideCollisionWorks() {
Ball trueBall = new Ball(140, 80);
Ball falseBall = new Ball(140, 79);
assertEquals(true, obstacle.hits(trueBall));
assertEquals(false, obstacle.hits(falseBall));
}
@Test
public void collisionDetectionForRightSideCollisionWorks() {
Ball trueBall = new Ball(200, 100);
Ball falseBall = new Ball(200, 80);
assertEquals(true, obstacle.hits(trueBall));
assertEquals(false, obstacle.hits(falseBall));
}
@Test
public void collisionDetectionForBottomSideCollisionWorks() {
Ball trueBall = new Ball(140, 120);
Ball falseBall = new Ball(140, 121);
assertEquals(true, obstacle.hits(trueBall));
assertEquals(false, obstacle.hits(falseBall));
}
@Test
public void collisionDetectionForLeftSideCollisionWorks() {
Ball trueBall = new Ball(80, 100);
Ball falseBall = new Ball(79, 100);
assertEquals(true, obstacle.hits(trueBall));
assertEquals(false, obstacle.hits(falseBall));
}
@Test
public void collisionDetectionForTopLeftCornerWorkWhenBallHitsCornersButNotSides() {
Ball ball = new Ball(90, 90);
assertEquals(false, obstacle.hitsSides(ball));
assertEquals(true, obstacle.hitsCorners(ball));
}
@Test
public void collisionDetectionForTopRightCornerWorkWhenBallHitsCornersButNotSides() {
Ball ball = new Ball(190, 90);
assertEquals(false, obstacle.hitsSides(ball));
assertEquals(true, obstacle.hitsCorners(ball));
}
@Test
public void collisionDetectionForBottomRightCornerWorkWhenBallHitsCornersButNotSides() {
Ball ball = new Ball(190, 110);
assertEquals(false, obstacle.hitsSides(ball));
assertEquals(true, obstacle.hitsCorners(ball));
}
@Test
public void collisionDetectionForBottomLeftCornerWorkWhenBallHitsCornersButNotSides() {
Ball ball = new Ball(90, 110);
assertEquals(false, obstacle.hitsSides(ball));
assertEquals(true, obstacle.hitsCorners(ball));
}
}
<file_sep>/minigolf/src/main/java/minigolf/domain/LevelArchitect.java
package minigolf.domain;
/**
* Kenttäarkkitehti eli luokka, joka vastaa kenttien rakentamisesta
* @author zesbr
*/
public class LevelArchitect {
/**
* Rakentaa ja palauttaa kentän parametrina saadun kentän numeron perusteella
* @param id : kentän numero
* @return uusi kenttä
*/
public static Level buildLevel(int id) {
switch (id) {
case 1:
return level01();
case 2:
return level02();
case 3:
return level03();
case 4:
return level04();
case 5:
return level05();
case 6:
return level06();
case 7:
return level07();
case 8:
return level08();
case 9:
return level09();
default:
return null;
}
}
// Kenttä #1
private static Level level01() {
Level level = new Level(0, 0, 800, 600, new Tee(390, 540), new Hole(385, 60), "1");
return level;
}
// Kenttä #2
private static Level level02() {
Level level = new Level(0, 0, 800, 600, new Tee(390, 540), new Hole(385, 60), "2");
level.addObstacle(new Obstacle(200, 200, 400, 20));
return level;
}
// Kenttä #3
private static Level level03() {
Level level = new Level(0, 0, 800, 600, new Tee(390, 550), new Hole(120, 500), "3");
level.addObstacle(new Obstacle(120, 100, 580, 20));
level.addObstacle(new Obstacle(340, 200, 20, 380));
level.addObstacle(new Obstacle(580, 200, 20, 200));
return level;
}
// Kenttä #4
private static Level level04() {
Level level = new Level(0, 0, 800, 600, new Tee(100, 550), new Hole(650, 100), "4");
level.addObstacle(new Obstacle(200, 200, 580, 20));
level.addObstacle(new Obstacle(20, 400, 580, 20));
return level;
}
// Kenttä #5
private static Level level05() {
Level level = new Level(0, 0, 800, 600, new Tee(700, 350), new Hole(95, 500), "5");
level.addObstacle(new Obstacle(200, 150, 20, 530));
level.addObstacle(new Obstacle(350, 20, 20, 120));
level.addObstacle(new Obstacle(350, 200, 20, 120));
level.addObstacle(new Obstacle(220, 400, 560, 20));
return level;
}
// Kenttä #6
// HUOM! TÄSSÄ ON BUGI ELI JÄÄ KULMAAN KIINNI TOISELLA LYÖNNILLÄ DEFAULT LYÖNTIARVOILLA.
// JOHTUU HUONOSTA TÖRMÄYKSEN AIHEUTTAMASTA KULMAN LASKENNASTA JOS PALLO OSUU ESTEEN KULMAAN
private static Level level06() {
Level level = new Level(0, 0, 800, 600, new Tee(105, 500), new Hole(680, 350), "6");
level.addObstacle(new Obstacle(200, 150, 20, 530));
level.addObstacle(new Obstacle(220, 150, 360, 20));
level.addObstacle(new Obstacle(580, 150, 20, 530));
return level;
}
// Kenttä #7
private static Level level07() {
Level level = new Level(0, 0, 800, 600, new Tee(390, 290), new Hole(400, 50), "7");
level.addObstacle(new Obstacle(200, 100, 40, 40));
level.addObstacle(new Obstacle(560, 100, 40, 40));
level.addObstacle(new Obstacle(200, 460, 40, 40));
level.addObstacle(new Obstacle(560, 460, 40, 40));
return level;
}
// TODO: Kenttä #8
private static Level level08() {
Level level = new Level(0, 0, 800, 600, new Tee(600, 120), new Hole(110, 125), "8");
level.addObstacle(new Obstacle(220, 0, 20, 120));
level.addObstacle(new Obstacle(220, 180, 20, 120));
level.addObstacle(new Obstacle(20, 280, 200, 20));
level.addObstacle(new Obstacle(360, 110, 20, 100));
level.addObstacle(new Obstacle(320, 280, 400, 20));
return level;
}
// Kenttä #9
private static Level level09() {
Level level = new Level(0, 0, 800, 600, new Tee(400, 550), new Hole(385, 75), "9");
level.addObstacle(new Obstacle(20, 80, 300, 20));
level.addObstacle(new Obstacle(480, 80, 300, 20));
int startX = 60;
for (int y = 160; y < 440; y+=80) {
for (int x = startX; x < 740; x+=80) {
level.addObstacle(new Obstacle(x, y, 40, 40));
}
if (startX == 60) {
startX = 100;
} else {
startX = 60;
}
}
level.addObstacle(new Obstacle(20, 480, 300, 20));
level.addObstacle(new Obstacle(480, 480, 300, 20));
return level;
}
}
<file_sep>/dokumentointi/tuntikirjanpito.md
# Tuntikirjanpito
### Tiistai 12.5.2015
* Työympäristön ja projektin alustus
* Githubin, Mavenin ja PIT:n conffaus
* Aiheen suunnittelu
* Aihekuvausen dokumetointi
* Alustavien vaatimusten dokumentointi
* Käyttötapausten kirjaaminen
* Labtoolin conffaus ja tehtävien kirjaus
Työmäärä: 4h
### Tiisti 19.5.2015
* Sovellusrkkitehtuurin suunnitelu
* Luokkakaavion piirtely
* Alustavan sovelluslogiikan toteuttaminen
Työmäärä: 6h
### Keskiviikko 20.5.2015
* Sovellusarkkitehtuurin suunnitelu
* Luokkakaavioiden piirtely
* Testikäyttöliittymän toteutus
* Sovelluslogiikan tekeminen
* Koodin refaktorointi
Työmäärä: 10h
### Torstai 21.5
* Sovellusrkkitehtuurin suunnitelu
* Luokkakaavion piirttely
* Muut dokumentointi tehtävät
* Sovelluslogiikan tekeminen
* Koodin refaktorointi
* Yksikkötestien tekeminen
Työmäärä: 10h
### Keskiviikko 27.5
* Sovelluslogiikan tekeminen
* Koodin refaktorointi
Työmäärä: 8h
### Torstai 28.5
* Sovelluslogiikan tekeminen
* Törmäyksentunnistamisen toiminnalisuus
* Koodin refaktorointi
* Yksikkötestien tekeminen
Työmäärä: 9h
### Keskiviikko 3.6
* Uusien kenttien tekeminen
* Kentän ja pelaajan vaihdon toiminnallisuus
Työmäärä: 6h
### Torstai 4.6
* Pallon animaatio
* Koodin refaktorointi
* Sekvenssikaavion piirtäminen
* Yksikkötestien tekeminen
Työmäärä: 12h
### Perjantai 5.6
* Käyttöliittymän parantelu
* Refaktorointia
Työmäärä: 9h
### Lauantai 6.6
* Aihekuvauksen ja vaatimusten päivittäminen
* Käyttöliittmän hiominen
* Luokkakaavion päivittäminen
Työmäärä: 3h
### Tiistai 9.6
* Sovelluslogiikan tekeminen
* Koodin refaktorointi
* Javadocin päivitys
Työmäärä: 4h
### Keskiviikko 10.6
* Graafisen käyttöliitymän tekeminen
* Koodin refaktorointi
* Javadocin päivitys
Työmäärä: 6h
### Torstai 11.6
* Koodin refaktorointi
* JUnit testien kirjoittaminen
* Sekvenssikaavioiden piirtäminen
* Dokumentoinnin päivitys
Työmäärä: 6h
### Tiistai 16.6
* Demo valmistelut
Työmäärä: 2h
### Keskiviikko 17.6
* Dokumentaation ajantasaistaminen
Työmäärä: 2h
### Torstai 18.6
* Refaktorointia
* Dokumentaation ajantasaistaminen
* Loppupalautuksen valmistelu
Työmäärä: 5h
<file_sep>/minigolf/src/main/java/minigolf/gui/ViewManager.java
package minigolf.gui;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import minigolf.App;
import minigolf.game.Game;
/**
* Sovelluksen näkymienhallinnasta huolehtiva luokka, jonka tehtävä on käsitellä
* tapahtumat, joilla halutaan vaikuttaa esitettävään näkymään App luokan JFrame
* ikkunakehyksessä.
* @author zesbr
*/
public class ViewManager extends JPanel implements ActionListener {
private final String STARTMENU = "Start Menu";
private final String GAME = "Game";
private final String SCORECARD = "Scorecard";
private App app;
private CardLayout layout;
public ViewManager(App app) {
this.app = app;
this.layout = new CardLayout();
init();
}
// Alustaa näkymänhallitsijan
private void init() {
setLayout(layout);
showStartMenu();
}
// Näyttää päävalikon
private void showStartMenu() {
add(STARTMENU, new StartMenu(this));
layout.show(this, STARTMENU);
}
// Käynnistää uuden pelin ja näyttää pelialustan
private void startGame(Game game) {
add(GAME, new GameCanvas(game, this));
layout.show(this, GAME);
}
/**
* Näyttää tuloskortin pelikierroksen päätteeksi
* @param game : peli-instanssi
*/
public void showScorecard(Game game) {
add(SCORECARD, new Scorecard(game, this));
layout.show(this, SCORECARD);
}
/**
* Tapahtumakuuntelija, joka käsittelee näkymien vaihtamiseen ja luontiin
* liittyvät pyynnöt
* @param ae : tapahtuma
*/
@Override
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("NEW GAME")) {
startGame(new Game());
} else if (ae.getActionCommand().equals("CONTINUE")) {
showStartMenu();
} else if (ae.getActionCommand().equals("QUIT")) {
System.exit(0);
}
}
}
<file_sep>/minigolf/src/main/java/minigolf/gui/PowerBar.java
package minigolf.gui;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JProgressBar;
import javax.swing.Timer;
import minigolf.domain.Ball;
import minigolf.domain.Player;
public class PowerBar extends JProgressBar implements ActionListener {
private float aimX;
private float aimY;
private int power;
private boolean increase;
private GameCanvas canvas;
private Timer timer;
public PowerBar(GameCanvas canvas) {
super(JProgressBar.VERTICAL, 0, 1000);
this.aimX = 0;
this.aimY = 0;
this.power = 0;
this.increase = true;
this.canvas = canvas;
this.timer = new Timer(3, this);
setOpaque(true);
}
/**
* Käynnistää voimapalkin ajastimen.Tätä metodia kutsutaan pelialustan
* hiirentapahtumakäsittelijästä, kun hiiren vasenta painiketta pidetään
* pohjassa.
*/
public void startTimer() {
timer.start();
}
/**
* Pysäyttää voimapalkin ajastimen sekä kutsuu uuden lyönnin käynnistävää
* toimenpidettä. Tätä metodia kutsutaan pelialustan
* hiirentapahtumakäsittelijästä, kun hiiren vasen painike vapauteaan.
*/
public void stopTimer() {
timer.stop();
put();
init();
}
/**
* Asettaa lyönnille x-koordinaatin
* @param x : x-koordinaatti
*/
public void setAimX(float x) {
this.aimX = x;
}
/**
* Asettaa lyönnin y-koordinaatin
* @param y : y-koordinaatti
*/
public void setAimY(float y) {
this.aimY = y;
}
// Suorittaa lyönnin aktiivisella pelaajalla
private void put() {
canvas.getGui().disableHint(); // Piilottaa hint-tekstin
Player player = canvas.getGame().getActivePlayer();
Ball ball = player.getBall(); // Hakee aktiivisen pelaajan pallon
double angle = ball.getAngleToPoint(aimX, aimY); // Laskee lyönnin kulman
// Tarkistaa ettei pelialustan ajastin ole käynnissä
if (!canvas.timerIsRunning()) {
System.out.println(player.getName() + " lyö palloa voimalla " + power + " ja kulmassa " + angle);
player.put(power, angle); // Suorittaa putin aktiivisella pelaajalla
canvas.startTimer(); // Käynnistää pelialustan ajastimen
}
}
/**
* Ajastimen tapahtumakuuntelija, joka päivittää voimapalkin arvoa ajastimen
* viiveen määrittämällä nopeudella
* @param ae : ajastimen päivitystapahtuma
*/
@Override
public void actionPerformed(ActionEvent ae) {
// Tarkistaa tuleeko voimapalkin arvoa kasvattaa vai vähentää
if (power <= 0) {
power = 0;
increase = true;
} else if (power >= 1000) {
power = 1000;
increase = false;
}
// Kasvattaa tai vähentää voimapalkin arvoa
if (increase) {
power += 3;
} else{
power -= 3;
}
transformColor();
// Asettaa voimapalkin päivityneen arvon
setValue(power);
System.out.println("Power = " + power);
}
// Alustaa voimapalkin
private void init() {
power = 0;
increase = true;
setValue(power);
}
// Vaihtaa voimapalkin väriä
private void transformColor() {
int r = 255 * power / 1000;
int g = (255 * (1000 - power) / 1000);
int b = 0;
setForeground(new Color(r, g, b));
}
}
<file_sep>/dokumentointi/tehtavalista.md
# Tehtävälista
## Viikko 1
- [x] Suunnitele ja kirjoita aihekuvaus
- [x] Dokumentoi soveluuksen alustavat vaatimukset
- [x] Dokumentoi sovelluksen käyttötapaukset
- [x] Pystytä työympäristö ja versiohallinta
## Viikko 2 (18.-24.5)
- [x] Piirrää määrittelyvaiheen luokkakaavio
- [x] Toteuta peli-ikkuna
- [x] Toteuta käyttöliittymä lyönnin määärittämiselle
- [x] Toteuta aihealueen pääluokat
- [x] Toteuta laskentalogiikka pallon liikkumiselle
- [x] Toteuta JUnit yksikkötestit (n. 10 testiä)
- [x] Generoi pit-raportti
## Viikko 3 (25.-31.5)
- [x] Täydennä luokkakaaviota lisäämällä kytkentärajoiteet
- [x] Toteuta animaatio pallon liikkeelle
- [x] Lisää pelialueelle seinät
- [x] Toteuta fysiikkamallinnus pallon kimpoamiselle
- [x] Aloita Javadocin kirjoittaminen
- [x] Toteuta JUnit yksikkötestit (Rivikattavuus n. 70%)
- [x] Genroi pit-raportti
## Viikko 4 (1.-7.6)
- [ ] Piirrä 2-3 sekvenssikaaviota keskeisimmistä käyttötapauksista
- [ ] Päivitä luokkakaaviota
- [ ] Toteuta sovelluslogiikka pelikierrokselle
- [ ] Toteuta sovelluslogiikka lyöntilaskurille
- [ ] Paranna pallon animaatiota
- [ ] Toteuta fysiikkamallinnus pallon kiihtyvyydelle ja hidastumiselle
- [ ] Suunnittele ja toteuta pelin kentät (väh. 3)
- [ ] Jatka Javadocin kirjoittamista
- [ ] Toteuta JUnit yksikkötestit (Rivikattavuus n. 80%)
- [ ] Generoi pit-raportti
## Viikko 5 (8.-14.6)
- [ ] Suunnittele ja toteuta pelin päävalikko
- [ ] Toteuta parannettu käyttöliittymä
- [ ] Päivitä edellisiä sekvenssikaavioita
- [ ] Piirrä 1-2 sekvenssikaaviota muista käyttötapauksista
- [ ] Lisää tekstuurit pelimaailman objekteille
- [ ] Lisää äänitehosteet pelimaailman tapahtumille
- [ ] Refaktoroi koko lähdekoodi
- [ ] Viimeistele Javadoc
- [ ] Toteuta JUnit yksikkötestit (Rivikattavuus n. 90%)
- [ ] Generoi pit-raportti
- [ ] Tee .jar tiedosto
<file_sep>/minigolf/src/main/java/minigolf/domain/Hole.java
package minigolf.domain;
/**
* Pelikentän reikää mallintava luokka jonka tehtävä on huolehtia reiän sijaintiin
* liittyvistä palveluista
* @author zesbr
*/
public class Hole extends LevelObject {
private final int RADIUS = 15;
private final int DIAMETER = RADIUS * 2;
public Hole(int x, int y) {
super(x, y);
}
/**
* Palauttaa reiän säteen
* @return säde
*/
public int getRadius() {
return RADIUS;
}
/**
* Palauttaa reiän halkaisijan
* @return halkaisija
*/
public int getDiameter() {
return DIAMETER;
}
/**
* Palautaa reiän keskipisteen x-koordinaatin
* @return x-koordinaatti
*/
public int getCenterX() {
return getX() + RADIUS;
}
/**
* Palautaa reiän keskipisteen y-koordinaatin
* @return y-koordinaatti
*/
public int getCenterY() {
return getY() + RADIUS;
}
/**
* Tarkistaa onko piste reiän sisällä
* @param x : pisteen x-koordinaatti
* @param y : pisteen y-koordinaatti
* @return totuusarvo onko piste reiän kehän sisäpuolellea (true) vai ulkopuolella (false)
*/
public boolean inHole(int x, int y) {
return withinDistance(x, y, RADIUS);
}
/**
* Tarkistaa onko piste tietyn etäisyyden päässä reiästä
* @param x : pisteen x-koordinaatti
* @param y : pisteen y-koordinaatti
* @param distance : tarkistusalueen säde eli etäisyys reiän keskipisteestä
* @return totuusarvo onko piste etäisyyden päässä reiän keskipisteessä (true) vai ei (false)
*/
public boolean withinDistance(int x, int y, int distance) {
if (Math.pow(x - getCenterX(), 2) + Math.pow(y - getCenterY(), 2) < Math.pow(distance, 2)) {
return true;
}
return false;
}
}<file_sep>/minigolf/src/main/java/minigolf/game/Game.java
package minigolf.game;
import minigolf.domain.Tee;
import minigolf.domain.Level;
import minigolf.domain.Player;
import minigolf.domain.Ball;
import java.util.ArrayDeque;
import java.util.ArrayList;
import minigolf.domain.LevelArchitect;
/**
* Pelikierrosta hallinnoiva luokka, jonka tehtävä on huolehtia pelikierroksen
* alustamisesta, sekä pelikierroksen aikana tapahtuvista muutoksista kuten kentän
* ja pelivuoron vaihdoista
* @author zesbr
*/
public class Game {
private ArrayList<Level> levels;
private ArrayDeque<Level> unfinishedLevels;
private ArrayDeque<Player> players;
public Game() {
this.levels = new ArrayList<>();
this.players = new ArrayDeque<>();
this.unfinishedLevels = new ArrayDeque<>();
init();
}
public Game(ArrayDeque<Player> players) {
this.levels = new ArrayList<>();
this.unfinishedLevels = new ArrayDeque<>();
this.players = players;
init();
}
public Game(ArrayList<Level> levels) {
this.levels = levels;
this.unfinishedLevels = new ArrayDeque<>();
this.players = new ArrayDeque<>();
init();
}
public Game(ArrayList<Level> levels, ArrayDeque<Player> players) {
this.levels = levels;
this.players = players;
this.unfinishedLevels = new ArrayDeque<>();
init();
}
// Lisää pelaajat ja kentät, sekä asettaa pelaajien pallot aloituspaikalle.
private void init() {
addPlayers();
addLevels();
placeBallsToTee(getCurrentLevel().getTee());
}
// Lisää pelaajat
private void addPlayers() {
if (players.isEmpty()) {
players.add(new Player("Player 1"));
} else if (players.size() > 8) {
ArrayDeque<Player> newPlayers = new ArrayDeque<>();
int id = 1;
for (Player player : players) {
if (id == 9) {
break;
}
newPlayers.add(player);
id++;
}
players = newPlayers;
}
}
// Lisää kentät
private void addLevels() {
// Jos kenttiä ei ole tai niitä on enemmän kuin yhdeksän, niin alustetaan peli yhdeksällä kentällä
if (levels.isEmpty() || levels.size() > 9) {
if (levels.size() > 9) {
levels = new ArrayList<>();
}
for (int i = 1; i <= 9; i++) {
Level level = LevelArchitect.buildLevel(i);
levels.add(level);
unfinishedLevels.add(level);
}
} else {
for (Level level : levels) {
unfinishedLevels.add(level);
}
}
}
/**
* Vaihtaa kentän ja palauttaa seuraavaksi pelattavan kentän
* @return seuraavaa vuorossa oleva kenttä
*/
public Level switchLevel() {
unfinishedLevels.pollFirst();
return getCurrentLevel();
}
/**
* Kierrättää tai vaihtaa aktiivisen pelaajan ja palauttaa seuraavan
* vuorossa olevan pelaajan
* @return seuraava pelaaja
*/
public Player switchPlayer() {
Player previous = players.pollFirst();
players.add(previous);
return getActivePlayer();
}
/**
* Palauttaa nykyisen kentän eli sen jota parhaillaan pelataan
* @return nykyinen kenttä
*/
public Level getCurrentLevel() {
return unfinishedLevels.peekFirst();
}
/**
* Kirjaa pelaajan lyönnit tuloskortiin
*/
public void markScore() {
Player player = getActivePlayer();
player.addScore(getCurrentLevel(), player.getStrikes());
System.out.println(player.getName() + " pelasi pallon reikään " + player.getStrikes() + " lyönnillä.");
player.initStrikes();
}
/**
* Tarkistaa onko peli päättynyt ja palautta totuusarvon.
* @return totuusarvo siitä onko peli päättynyt (true) vai ei (false)
*/
public boolean hasEnded() {
Level level = getCurrentLevel();
if (level == null) {
return true;
}
return false;
}
/**
* Tarkistaa ovatko kaikki pelaajat pelanneet nykyisen kentän ja palauttaa
* totuusarvon.
* @return totuusarvo ovatko kaikki pelanneet kentän (true) vai eivät (false)
*/
public boolean allPlayersHaveCompletedLevel() {
Player player = getActivePlayer();
if (player.getScore(getCurrentLevel()) != -1) {
return true;
}
return false;
}
/**
* Palauttaa aktiivisen pelaajan eli sen kenen vuoro parhaillaan on
* @return aktiivinen pelaaja
*/
public Player getActivePlayer() {
return players.peekFirst();
}
/**
* Hakee ja palauttaa aktiivisen pelaajan pallon
* @return Ball : Aktiivisen pelaajan pallo
*/
public Ball getActiveBall() {
Player player = getActivePlayer();
return player.getBall();
}
/**
* Alustaa jokaisen pelaajan pallot kentän aloituspaikalle.
* @param tee : kentän aloituspaikka
*/
public void placeBallsToTee(Tee tee) {
for (Player player : players) {
player.setBall(new Ball(tee.getX(), tee.getY()));
}
}
/**
* Palautta kaikki kentät
* @return kaikki kentät
*/
public ArrayList getAllLevels() {
return this.levels;
}
/**
* Palauttaa kaikki pelaajat
* @return kaikki pelaajat
*/
public ArrayDeque getAllPlayers() {
return this.players;
}
/**
* Palauttaa kaikki kentät, jotka ovat vielä pelaamatta mukaan lukien
* nykyinen kenttä
* @return kaikki pelaamattomat kentät
*/
public ArrayDeque getUnfinishedLevels() {
return this.unfinishedLevels;
}
}<file_sep>/minigolf/src/main/java/minigolf/domain/Player.java
package minigolf.domain;
import java.util.HashMap;
import java.util.Objects;
/**
* Pelikierrokselle osallistuvaa pelaajaa mallintava luokka, jonka tehtävänä on
* pitää kirjaa pelaajan tiedoista ja lyönneistä, sekä määrittää pallolle lähtö-
* nopeus ja -voima lyönnin alussa.
* @author zesbr
*/
public class Player {
private String name;
private Ball ball;
private int strikes;
private HashMap<Level, Integer> scorecard;
public Player(String name) {
this.name = name;
this.strikes = 0;
this.scorecard = new HashMap<>();
}
/**
* Palauttaa pelaajalle kuuluvan pallon
* @return pelaajan omistama pallo
*/
public Ball getBall() {
return ball;
}
/**
* Asettaa pelaajalle uuden pallon
* @param ball : pelaajan uusi pallo
*/
public void setBall(Ball ball) {
this.ball = ball;
}
/**
* Palauttaa pelaajan suorittamien lyöntien määrän
* @return lyöntien lukumäärä
*/
public int getStrikes() {
return strikes;
}
/**
* Palauttaa pelaajan nimen
* @return pelaajan nimi
*/
public String getName() {
return name;
}
/**
* Nollaa lyöntilaskurin
*/
public void initStrikes() {
strikes = 0;
}
/**
* Suorittaa lyönnin eli puttauksen, joka asettaa pallolle löhtänopeuden ja
* -kulman, sekä kasvattaa lyöntilaskuria yhdellä
* @param power : lyönnin voima, joka on sama kuin pallon lähtönopeus
* @param angle : lyönnin nopeus, joka on sama kuin pallon lähtökulma
*/
public void put(double power, double angle) {
ball.setSpeed(power);
ball.setAngle(angle);
strikes++;
}
/**
* Lisää uuden tuloksen kenttää kohti
* @param level : kenttä (avain)
* @param score : tulos eli lyöntien lukumäärä (arvo)
*/
public void addScore(Level level, int score) {
if (level != null) {
this.scorecard.put(level, score);
}
}
/**
* Palauttaa tuloksen, jonka pelaaja suoritti kentällä
* @param level : kenttä
* @return tulos eli lyöntien lukumäärä. palauttaa -1, jos kenttää ei ole
* kirjattu pelatuksi
*/
public int getScore(Level level) {
if (scorecard.containsKey(level)) {
return scorecard.get(level);
} else {
return -1;
}
}
}
<file_sep>/minigolf/src/main/java/minigolf/gui/HUD.java
package minigolf.gui;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.*;
import minigolf.domain.Level;
import minigolf.domain.Player;
import minigolf.game.Game;
/**
* TODO: Lisää tekstipaneelit lyöntilaskurille, kentän numerolle ja
* pelaajan nimelle
*
* Pelialustalle kuuluva infopaneeli, jonka tehtävänä on huolehtia peliin
* liittyvistä ilmoituksista esim. vuorollisen pelaajan ja lyöntimäärän
* esittämisestä käyttäjälle.
* @author zesbr
*/
public class HUD extends JPanel {
private GameCanvas canvas;
private JLabel levelID;
private JLabel playerName;
private JLabel playerStrikes;
public HUD(GameCanvas canvas) {
super();
this.canvas = canvas;
this.levelID = new JLabel();
this.playerName = new JLabel();
this.playerStrikes = new JLabel();
init();
addComponents();
}
private void init() {
setOpaque(false);
Game game = canvas.getGame();
Level level = game.getCurrentLevel();
Player player = game.getActivePlayer();
levelID.setText(level.getName());
playerName.setText(player.getName());
playerStrikes.setText("" + player.getStrikes());
}
private void addComponents() {
add(levelID);
add(playerName);
add(playerStrikes);
}
}
<file_sep>/minigolf/src/test/java/minigolf/domain/LevelTest.java
package minigolf.domain;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class LevelTest {
private Level level;
public LevelTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
level = new Level(0, 0, 800, 600, new Tee(800,600), new Hole(0,0), "");
}
@After
public void tearDown() {
}
@Test
public void getMethodsForCoordinatesWork() {
assertEquals(0, level.getX());
assertEquals(0, level.getY());
}
@Test
public void cannotBeBuiltWithNegativeCoordinates() {
Level level = new Level(-100, -100, 800, 600, new Tee(0,0), new Hole(0,0), "");
assertEquals(0, level.getX());
assertEquals(0, level.getY());
}
@Test
public void getWidthForLevelWorks() {
assertEquals(800, level.getWidth());
}
@Test
public void getHeightForLevelWorks() {
assertEquals(600, level.getHeight());
}
@Test
public void getMethodsForLevelCoordinatesWork() {
int x = level.getX();
int y = level.getY();
assertEquals(0, x);
assertEquals(0, y);
}
@Test
public void levelCannotBeConstructedWithNegativeCoordinates() {
level = new Level(-10, -10, 800, 600, new Tee(0,0), new Hole(0,0), "");
int x = level.getX();
int y = level.getY();
assertEquals(0, x);
assertEquals(0, y);
}
@Test
public void teeCannotBeSetOutsideLevelBorders() {
level.setTee(new Tee(1000, 1000));
assertEquals(800, level.getTee().getX());
assertEquals(600, level.getTee().getY());
}
@Test
public void holeCannotBeSetOutsideLevelBorders() {
level.setHole(new Hole(1000, 1000));
assertEquals(0, level.getHole().getX());
assertEquals(0, level.getHole().getY());
}
@Test
public void teeAndHoleMustBeMoreThanTwoHundredPixelsAwayFromEachOther() {
// TODO
}
@Test
public void obstacleAndTeeMustBeMoreThanTwentyPixelsAwayFromEachOther() {
// TODO
}
@Test
public void obstacleAndHoleMustBeMoreThanTwentyPixelsAwayFromEachOther() {
// TODO
}
}
<file_sep>/dokumentointi/aiheenKuvausJaRakenne.md
#Mingolf-peli :golf:
*Ohjelmoinnin harjoitustyö, alkukesä 2015*
## 1. Aiheen kuvaus
Toteutuksen aiheena on kaksiulotteinen minigolf-peli. Pelin idana on sama kuin oikeassa minigolfissa, eli pelaaja yrittää löydä pallon mahdollisimman vähillä lyönneillä reikään. Peliä pelaatan oikean minigolfin tavoin radoilla, jotka ovat vaihtelevia. Ratoja ympäröi seinät ja radoilla voi olla erilaisia esteitä pelin hankaloittamiseksi. Peli aloitetaan radan aloituspaikalta ja uusi lyönti aloitetaan siitä mihin edellinen lyönti päättyi. Pelikierros päättyy kun pallo pelataan reikään.
Peliä voi pelata yksin tai kaveria vastaan ja sitä ohjataan hiirellä. Hiiren osoittimella valitaan lyönnin suunta ja hiiren vasenta painiketta pohjassa pitämällä asetetaan voima jolla lyönti suoritetaan. Lyönti siis vaikuttaa pallon liikkeeseen eli siihen mihin suuntaan ja millä voimalla pallo alussa lähtee. Pallon edetessä sen liike hidastuu kunnes se lopulta pysähtyy. Tämän jälkeen, peliä jatketaan uudella lyönnillä tai jos pallo päätyi reikään, niin aloitetaan peli uudelta kentältä. Edetessään pallo voi törmätä esteisiin, jolloin pallon liikkeen suunta ja nopeus muuttuvat. Pallon liikeen ja törmäilyn tulee vaikuttaa uskottavalta ja sen tulee jossain määrin noudattaa fysiikan lakeja.
Peli tulee olemaan kaksiulotteinen, joka on kuvattu rataan nähden ylhäältä päin. Peliä voi toistaiseksi pelata vain yksinpelinä.
## 2. Alustavat vaatimukset
HUOM! Yliviivatut vaatimukset siirtyvät jatkokehityskohteeksi
#### Yleiset:
* Pelissä on oltavat vähintään yksi pelaaja
* ~~Pelissä voi olla monta pelaaja~~ *(Siirretty jatkokehityskohteeksi)*
* ~~Peliä voi pelata yksin tai toisia pelaajia vastaan~~ *(Siirretty jatkokehityskohteeksi)*
* ~~Pelissä voi olla tekoäly pelaajia~~ *(Siirretty jatkokehityskohteeksi)*
* ~~Tekoäly pelaajilla on vaikeustaso~~ *(Siirretty jatkokehityskohteeksi)*
* Pelissä on useita ratoja
* ~~Pelaaja voi valita haluamansa radan~~ *(Siirretty jatkokehityskohteeksi)*
* Pelikierroksen aikana pidetään kirjaa lyöntien lukumäärästä
* ~~Pelissä pidetään kirjaa ennätyspisteitä eli ns. high scoreista~~ *(Siirretty jatkokehityskohteeksi)*
#### Ohjaus:
* Lyönnin suunta ja voima määritetään hiirellä
#### Fysiikkamallinnus:
* Lyönneillä on suunta ja voima
* ~~Lyönneillä voi olla ylä- tai alakierre~~ *(Siirretty jatkokehityskohteeksi)*
* Pallolla on liike, mikä kertoo pallon sen hetkisen suunnan ja nopeuden
* ~~Pallola on pyörimisliike, mikä kertoo pallon pyörimissuunnan ja pyörimisnopeuden~~ *(Siirretty jatkokehityskohteeksi)*
* Lyöntien suunta ja voima vaikuttaa pallon liikkeeseen
* ~~Lyöntien kierre vaikuttaa pallon pyörimisliikkeeseen~~ *(Siirretty jatkokehityskohteeksi)*
* ~~Pallon pyörimisliike vaikuttaa pallon liikkeeseen~~ *(Siirretty jatkokehityskohteeksi)*
* Pallon osuminen objektiin vaikuttaa liikkeeseen
* ~~Radan pinnanmuodot vaikuttaa pallon liikkeeseen~~ *(Siirretty jatkokehityskohteeksi)*
* ~~Radan päällyste vaikuttaa pallon nopeuteen~~ *(Siirretty jatkokehityskohteeksi)*
#### Radat:
* Radalla on pohjapiirros, joka määrittää radan mitat
* Rata voi olla tasainen eli siinä ei ole korkeuseroja
* ~~Rata voi sisältää korkeuseroja ja/tai kaltevuuksia~~ *(Siirretty jatkokehityskohteeksi)*
* ~~Radalla on päällyste, joka on jotain materiaalia~~ *(Siirretty jatkokehityskohteeksi)*
* Radalla on yksi aloituslyöntipaikka
* Radalla on yksi reikä
* Radalla voi olla objekteja esim. seiniä tai esteitä
* Objektit voivat olla kulmikkaita
* ~~Objektit voivat olla kaarevia~~ *(Siirretty jatkokehityskohteeksi)*
* Objektit voivat olla staattisia esim. seinät
* ~~Objektit voivat olla dynaamisia (liikkuvia) esim. tuulimyllyt~~ *(Siirretty jatkokehityskohteeksi)*
#### Erikoistehosteet:
* ~~Lyönnin tulee aiheuttaa ääniefekti~~ *(Siirretty jatkokehityskohteeksi)*
* ~~Pallon osuessa objektiin tulee aiheuttaa ääniefekti~~ *(Siirretty jatkokehityskohteeksi)*
* ~~Pallon pudotessa reikään tulee aiheuttaa ääniefekti~~ *(Siirretty jatkokehityskohteeksi)*
* ~~Onnistuneen väylän (par tai alle) jälkeen tulee seurata ääniefekti (aplodit)~~ *(Siirretty jatkokehityskohteeksi)*
* ~~Epäonnistuneen väylän (yli par) jälkeen tulee seurata ääniefekti (buuaus)~~ *(Siirretty jatkokehityskohteeksi)*
* ~~Lyönnin ja törmäyksen voiman tulee vaikuttaa ääniefektiin~~ *(Siirretty jatkokehityskohteeksi)*
## 3. Käyttötapaukset
**Käyttäjät:** Pelaaja
**Pelaajan toiminnot:**
* Pelaaja aloittaa uuden pelin
* Pelaaja määrittää osallistujat
* Pelaaja valitsee haluamansa radan
* Pelaaja suorittaa lyönnin
* Pelaaja keskeyttä pelin
* Pelaaja lopettaa pelin
## 4. Jatkokehitys
Jatkokehityksen kohteeksi siirtyvät toiminnallisuudet, joita ei ehditä toteuttaa tämän kurssi-iteraation aikana. Nämä kohteet sisältävät
mm. pallon fysiikkamallinuksen parantelua (mm. pyörimisliike), ratojen monipuolistamisen (mm. korkeuserot, dynaamiset esteet ja pyöreät kulmat) sekä erikoistehosteiden (mm. ääniefektit) ja tekstuureiden lisäämisen.
## 5. Rakenne
Sovelluksen arkkitehtuuri ei tietoisesti noudata mitään yleisesti tunnettua suunnittelumallia. Käytetyn arkkitehtuuriratkaisun ideana on ollut jakaa sovelluksen eri osa-alueet omiin kokonaisuuksiin, riippuen niiden toteuttamista toiminnallisuuksista. Näin ollen sovelluksen eri osa-alueet muodostavat yhteistyönä sovelluksen kokonaisuuden. Luokkasuunnittelussa on pyritty noudattamaan single-responsibility periaatetta, jossa jokaisen luokan tehtävä on huolehtia yhden rajatun ja loogisen kokonaisuuden toteuttamisesta.
Sovellus on jaettu neljään eri pakettiin: **minigolf**, **minigolf.domain**, **minigolf.game** ja **minigolf.gui**. **Minigolf** paketissa olevien luokkien (App ja Main) tehtävä on huolehtia sovelluksen käynnistämisestä ja ikkunan alustamisesta. **Minigolf.domain** paketissa olevien luokien (Ball, Hole, Level, LevelArchitect, LevelObject, Obstacle, Player, Tee) tehtävä on huolehtia pelikentälle ja peliin liittyvien objektien toiminnallisuuksista. **Minigolf.game** paketissa olevan luokan (Game) tehtävä on huolehtia pelikierroksen hallinnasta ja siihen liittyvästä toimintalogiikasta. **Minigolf.gui** paketissa olevien luokkien (GUI, GameCanvas, HUD, MouseInputManager, PowerBar, ScoreCard, StartMenu, ViewManager) tehtävä on huolehtia pelin käyttöliittymistä ja sovelluksen näkymistä.
### 5.1 Näkymien hallinta
Sovellus koostuu kolmesta päänäkymästä: Päävalikko (StartMenu), Pelitila tai Pelin piirtoalusta (GameCanvas) sekä Tuloskortti -näkymä (ScoreCard). Sovellusikkunassa esitettävää näkymää hallitsee luokka ViewManager. ViewManager:lla on ulkoasuna CardLayout, joka voi esittää vain yhden aktiivisen näkymän kerrallaan sovelluksen ikkunassa (App). ViewManager toteuttaa tapahtumakuuntelija rajapinnan (ActionListener), joka on liitetty päävalikon ja tuloskortti -näkymän painikkeisiin. Näin ollen, siis painikkeen painaminen käynnistää tapahtuman, joka vaihtaa sovelluksen aktiivista näkymää. Lisäksi, pelikierroksen päätyttyä sovellus avaa automaattisesti Scorecard näkymän, joten sitä ei aktivoida minkään panikkeen kautta.
### 5.2 Lyöntitapahtuma
Pallon lyöntitapahtuma yhdessä pallon liikkumisen kanssa on kenties sovelluksen monimutkaisin tapahtumaketju, joka käynnistyy käyttäjän antamien hiirikomentojen seurauksena. Sovelluksen pelialusta:lla (GameCanvas) on hiiren tapahtumien kuuntelija (MouseInputManager), joka käsittelee hiiren vasemman painikkeen pohjaan painamisen ja vapauttamisen tapahtumat. Hiiren kuuntelijalla on pelialustan käyttöliittymän (GUI) komponetti voimapalkki (PowerBar), joka perii Java Swing -komponentin JProgressBar. Voimapalkilla on ajastin (Timer), joka määrittää milloin voimapalkin mittaripalkki on aktiivisena. **Aina kun käyttäjä painaa hiireen vasemman painikkeen pohjaan, hiiren tapahtuma käsittelijä käynnistää voimapalkin ajastimen.** Tällöin löynnin voimaa kuvaava mittaripalkki alkaa liikkua. **Kun käyttäjä vapauttaa hiiren vasemman painikkeen, hiiren tapahtuma käsittelijä pysäyttää voimapalkin ajastimen sekä asettaa tälle hiiren osoittimen sen hetkisen koordinaatin.** Tämän jälkeen voimapalkki pyytää pelin (Game) aktiivsen pelaajan (Player) palloa (Ball) laskemaan pallon lähtökulman hiirenkoordinaattien perusteella. Lopuksi, voimapalkki pyytää pelaajaa asettamaan pallolleen kulmaksi lasketun kulman ja nopeudeksi voimapalkin määrittämän voima arvon sekä käynnistää pelialustan ajastimen.
Pelialustan (GameCanvas) ajastimen päivitystiheys eli ns. FPS on 60 kertaa sekunnissa. Tämä tarkoittaa sitä, että **aina kun pelialustan ajastin on käynnissä, niin pelialusta päivittyy 60 kertaa sekunnissa.** Tällöin siis ajastin kutsuu tapahtumakuuntelija (GameCanvasUpdater), jonka tehtävä on päivittää pelialusta. Ajastimen ollessa käynnissä, tapahtumankuuntelija hakee aktiivisen pelaajan pallon ja tarkistaa paljonko sen nopeus on. **Jos pallon nopeus on suurempi kuin 0, tarkoittaa se että pallossa jäljellä liike-energiaa. Tässä tapauksessa, tapahtumakuuntelijasta pyydetään palloa liikkumaan pallon kulman suuntaan pallon nopeus/60 askelta eli pikseliä**. Tämä on siis se matka, jonka pallo liikkuu jokaisen piirtoalustan päivityksen aikana, luoden pallon liikeen animaation. **Pallo liikkuu askeleittain ja jokaisen askeleen aikana tarkistetaan, onko pallo reiässä tai osuuko se yhteenkään kentän esteeseen.** Jos pallo on reiässä, niin liike pysäytetään. Jos pallo osuu esteeseen lasketaan pallolle uusi kulma riippuen siitä missä kulmassa ja mihin kohtaan estettä pallo osuu. Törmäyksen tarkistus tapahtuu kutsumalla kutsumalla jokaista aktiivisen pelikentän (Level) estettä (Obstacle) ja tarkistamalla osuvatko pallon kehän koordinaatit siihen.
Lopuksi, kun pallossa ei ole enää liikettä, niin pelialustan ajastin pysäytetään ja näin ollen sen päivittäminen keskeytään. Riippuen siitä onko pallo reiässä vai ei vaikuttaa siihen, että jatkuuko peli uudella lyöntitapahtumalla vai tehdään pelaajan vaihdos tai jos kaikki pelaajat ovat pelanneet kentän, niin tehdäänkö kentän vaihdos tai jos kaikki pelaajat ovat pelanneet kaikki kentät, niin lopetetaan pelikierros ja näytetään pelikierroksen tuloskortti (ScoreCard).
## 6. Bugit ja puuttet
Pelissä on tällä hetkellä olemassa bugi, jonka seurauksena pallo voi joutua esteen sisälle. Tämä aiheutuu tilanteesta, jolloin pallo osuu esteen kulmaan tietyssä kulmassa. Syynä on logiikka virhe kulman osuman tunnistuksessa ja törmäyksen aihettavan uuden kulman laskemisesta, joka tälle hetkellä laskee kulma törmäyksen vain 180 asteen sektorilla tapahtuville törmäyksille.
Voimapalkin arvo kiihtyy ja hidastuu tällä hetkellä lineaarisesti. Jotta voiman ajoittamisesta tulisi haastavampaa, voisi kiihtymisen toteuttaa toisella tavalla.
Peliä voi tällä hetkellä pelata vain yksinpelinä. Suunnitelmana olisi, että ennen pelin alkamista esitettäisiin näkymä jossa käyttäjä voisi määrittää peliin osallistuvat muut pelaajat. Lisäksi peliin voisi tehdä tekoälypelaajia joita pelaaja voisi myös haastaa.
<file_sep>/dokumentointi/pit-reports/201506120022/minigolf.domain/Obstacle.java.html
<html>
<head>
<style type='text/css'>
html, body, div, span, p, blockquote, pre {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-weight: inherit;
font-style: inherit;
font-size: 100%;
font-family: inherit;
vertical-align: baseline;
}
body{
line-height: 1;
color: black;
background: white;
margin-left: 20px;
}
.src {
border: 1px solid #dddddd;
padding-top: 10px;
padding-right: 5px;
padding-left: 5px;
}
.covered {background-color: #ddffdd}
.uncovered {background-color: #ffdddd}
.killed {background-color: #aaffaa}
.survived {background-color: #ffaaaa}
.uncertain {background-color: #dde7ef}
.run_error {background-color: #dde7ef}
.na {background-color: #eeeeee}
.timed_out {background-color: #dde7ef}
.non_viable {background-color: #aaffaa}
.memory_error {background-color: #dde7ef}
.not_started {background-color: #dde7ef; color : red}
.no_coverage {background-color: #ffaaaa}
.pop {outline:none; }
.pop strong {line-height:30px;}
.pop {text-decoration:none;}
.pop span { z-index:10;display:none; padding:14px 20px; margin-top:-30px; margin-left:28px; width:800px; line-height:16px; word-wrap:break-word; }
.pop:hover span{ display:inline; position:absolute; color:#111; border:1px solid #DCA; background:#fffAF0;}
.pop span { border-radius:4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; -moz-box-shadow: 5px 5px 8px #CCC; -webkit-box-shadow: 5px 5px 8px #CCC; box-shadow: 5px 5px 8px #CCC; }
</style>
</head>
<body>
<h1>Obstacle.java</h1>
<table class="src">
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_1'/>
1
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_1'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''>package minigolf.domain;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_2'/>
2
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_2'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''></span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_3'/>
3
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_3'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''>/**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_4'/>
4
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_4'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * Pelikentän estettä mallintava luokka, jonka tehtävä on huolehtia esteen</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_5'/>
5
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_5'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * ulottuvuuksista sekä esteeseen törmäyksen tunnistamisesta</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_6'/>
6
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_6'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @author zesbr</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_7'/>
7
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_7'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> */</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_8'/>
8
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_8'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''>public class Obstacle extends LevelObject {</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_9'/>
9
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_9'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_10'/>
10
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_10'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> private int width;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_11'/>
11
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_11'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> private int height;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_12'/>
12
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_12'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_13'/>
13
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_13'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> public Obstacle(int x, int y, int width, int height) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_14'/>
14
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_14'></a>
<span>
</span>
</td>
<td class='covered'><pre><span class=''> super(x, y);</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_15'/>
15
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_15'></a>
<span>
</span>
</td>
<td class='covered'><pre><span class=''> this.width = width;</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_16'/>
16
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_16'></a>
<span>
</span>
</td>
<td class='covered'><pre><span class=''> this.height = height;</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_17'/>
17
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_17'></a>
<span>
</span>
</td>
<td class='covered'><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_18'/>
18
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_18'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_19'/>
19
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_19'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> /**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_20'/>
20
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_20'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * Palauttaa esteen leveyden</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_21'/>
21
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_21'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @return leveys</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_22'/>
22
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_22'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> */</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_23'/>
23
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_23'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> public int getWidth() {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_24'/>
24
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_24'>1</a>
<span>
1. getWidth : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return width;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_25'/>
25
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_25'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_26'/>
26
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_26'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_27'/>
27
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_27'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> /**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_28'/>
28
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_28'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * Palauttaa esteen korkeuden</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_29'/>
29
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_29'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @return korkeus</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_30'/>
30
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_30'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> */</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_31'/>
31
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_31'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> public int getHeight() {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_32'/>
32
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_32'>1</a>
<span>
1. getHeight : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return height;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_33'/>
33
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_33'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_34'/>
34
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_34'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_35'/>
35
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_35'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> /**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_36'/>
36
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_36'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * Palauttaa esteen ylälaidan y-koordinaatin</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_37'/>
37
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_37'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @return ylälaidan y-koordinaatti</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_38'/>
38
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_38'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> */</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_39'/>
39
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_39'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> public int getTopSideY() {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_40'/>
40
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_40'>1</a>
<span>
1. getTopSideY : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return getY();</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_41'/>
41
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_41'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_42'/>
42
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_42'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_43'/>
43
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_43'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> /**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_44'/>
44
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_44'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * Palauttaa esteen oikean laidan x-koordinaatin</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_45'/>
45
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_45'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @return oikean laidan x-koordinaatti</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_46'/>
46
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_46'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> */</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_47'/>
47
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_47'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> public int getRightSideX() {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_48'/>
48
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_48'>2</a>
<span>
1. getRightSideX : Replaced integer addition with subtraction → KILLED<br/>
2. getRightSideX : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return getX() + getWidth();</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_49'/>
49
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_49'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_50'/>
50
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_50'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_51'/>
51
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_51'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> /**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_52'/>
52
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_52'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * Palauttaa esteen alalaidan y-koordinaatin</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_53'/>
53
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_53'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @return alalaidan y-koordinaatti</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_54'/>
54
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_54'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> */</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_55'/>
55
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_55'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> public int getBottomSideY() {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_56'/>
56
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_56'>2</a>
<span>
1. getBottomSideY : Replaced integer addition with subtraction → KILLED<br/>
2. getBottomSideY : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return getY() + getHeight();</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_57'/>
57
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_57'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_58'/>
58
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_58'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_59'/>
59
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_59'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> /**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_60'/>
60
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_60'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * Palauttaa esteen vasemman laidan x-koordinaatin</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_61'/>
61
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_61'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @return <NAME>an x-koordinaatti</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_62'/>
62
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_62'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> */</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_63'/>
63
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_63'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> public int getLeftSideX() {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_64'/>
64
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_64'>1</a>
<span>
1. getLeftSideX : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return getX();</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_65'/>
65
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_65'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_66'/>
66
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_66'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_67'/>
67
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_67'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> /**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_68'/>
68
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_68'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * Tarkistaa onko piste esteen rajojen sisällä ja palauttaa totuusarvon</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_69'/>
69
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_69'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @param x : pisteen x-koordinaatti</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_70'/>
70
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_70'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @param y : pisteen y-koordinaatti</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_71'/>
71
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_71'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @return totuusarvo onko piste esteen rajojen sisällä (true) vai ulkopuolella (false)</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_72'/>
72
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_72'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> */</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_73'/>
73
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_73'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> public boolean inside(int x, int y) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_74'/>
74
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_74'>8</a>
<span>
1. inside : changed conditional boundary → SURVIVED<br/>
2. inside : changed conditional boundary → SURVIVED<br/>
3. inside : changed conditional boundary → SURVIVED<br/>
4. inside : changed conditional boundary → SURVIVED<br/>
5. inside : negated conditional → KILLED<br/>
6. inside : negated conditional → KILLED<br/>
7. inside : negated conditional → KILLED<br/>
8. inside : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='survived'> if (x < getLeftSideX() || x > getRightSideX() || y < getTopSideY() || y > getBottomSideY()) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_75'/>
75
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_75'>1</a>
<span>
1. inside : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return false;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_76'/>
76
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_76'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_77'/>
77
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_77'>1</a>
<span>
1. inside : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_78'/>
78
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_78'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_79'/>
79
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_79'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_80'/>
80
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_80'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> /**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_81'/>
81
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_81'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * Tarkistaa osuuko pallo esteeseen ja kutsuu palloa päivittämään törmäyksen </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_82'/>
82
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_82'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * aiheuttaman muutoksen pallon liikerataan, sekä palauttaa totuusarvon</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_83'/>
83
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_83'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @param ball : pallo</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_84'/>
84
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_84'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @return totuusarvo, osuuko pallo esteeseen (true) vai ei (false)</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_85'/>
85
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_85'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> */ </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_86'/>
86
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_86'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> public boolean hits(Ball ball) {</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_87'/>
87
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_87'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> // Tarkistaa osuuko pallo esteen laitoihin tai jos ei osu, niin osuuko sen kulmiin</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_88'/>
88
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_88'>1</a>
<span>
1. hits : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> if (hitsSides(ball)) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_89'/>
89
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_89'>1</a>
<span>
1. hits : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_90'/>
90
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_90'>1</a>
<span>
1. hits : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> } else if (hitsCorners(ball)) {</span></pre></td></tr>
<tr>
<td class='uncovered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_91'/>
91
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_91'>1</a>
<span>
1. hits : replaced return of integer sized value with (x == 0 ? 1 : 0) → NO_COVERAGE<br/>
</span>
</td>
<td class='uncovered'><pre><span class='survived'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_92'/>
92
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_92'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_93'/>
93
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_93'>1</a>
<span>
1. hits : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return false;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_94'/>
94
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_94'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_95'/>
95
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_95'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_96'/>
96
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_96'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> /**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_97'/>
97
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_97'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * Tarkistaa osuuko pallo esteen laitoihin ja palauttaa totuusarvon</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_98'/>
98
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_98'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @param ball : pallo</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_99'/>
99
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_99'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @return totuusarvo, osuuko pallo esteen laitoihin (true) vai ei (false)</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_100'/>
100
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_100'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> */</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_101'/>
101
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_101'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> public boolean hitsSides(Ball ball) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_102'/>
102
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_102'></a>
<span>
</span>
</td>
<td class='covered'><pre><span class=''> boolean hits = false;</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_103'/>
103
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_103'>1</a>
<span>
1. hitsSides : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> if (hitsTopsSide(ball.getBottomX(), ball.getBottomY())) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_104'/>
104
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_104'>1</a>
<span>
1. hitsSides : removed call to minigolf/domain/Ball::calculateAngleFromVerticalCollision → SURVIVED<br/>
</span>
</td>
<td class='covered'><pre><span class='survived'> ball.calculateAngleFromVerticalCollision();</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_105'/>
105
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_105'></a>
<span>
</span>
</td>
<td class='covered'><pre><span class=''> hits = true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_106'/>
106
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_106'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_107'/>
107
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_107'>1</a>
<span>
1. hitsSides : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> if (hitsRightSide(ball.getLeftX(), ball.getLeftY())) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_108'/>
108
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_108'>1</a>
<span>
1. hitsSides : removed call to minigolf/domain/Ball::calculateAngleFromHorizontalCollision → SURVIVED<br/>
</span>
</td>
<td class='covered'><pre><span class='survived'> ball.calculateAngleFromHorizontalCollision();</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_109'/>
109
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_109'></a>
<span>
</span>
</td>
<td class='covered'><pre><span class=''> hits = true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_110'/>
110
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_110'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_111'/>
111
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_111'>1</a>
<span>
1. hitsSides : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> if (hitsBottomSide(ball.getTopX(), ball.getTopY())) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_112'/>
112
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_112'>1</a>
<span>
1. hitsSides : removed call to minigolf/domain/Ball::calculateAngleFromVerticalCollision → SURVIVED<br/>
</span>
</td>
<td class='covered'><pre><span class='survived'> ball.calculateAngleFromVerticalCollision();</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_113'/>
113
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_113'></a>
<span>
</span>
</td>
<td class='covered'><pre><span class=''> hits = true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_114'/>
114
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_114'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_115'/>
115
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_115'>1</a>
<span>
1. hitsSides : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> if (hitsLeftSide(ball.getRightX(), ball.getRightY())) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_116'/>
116
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_116'>1</a>
<span>
1. hitsSides : removed call to minigolf/domain/Ball::calculateAngleFromHorizontalCollision → SURVIVED<br/>
</span>
</td>
<td class='covered'><pre><span class='survived'> ball.calculateAngleFromHorizontalCollision();</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_117'/>
117
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_117'></a>
<span>
</span>
</td>
<td class='covered'><pre><span class=''> hits = true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_118'/>
118
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_118'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_119'/>
119
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_119'>1</a>
<span>
1. hitsSides : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return hits;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_120'/>
120
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_120'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_121'/>
121
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_121'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_122'/>
122
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_122'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> /**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_123'/>
123
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_123'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * Tarkistaa osuuko pallo esteen kulmiin ja palauttaa totuusarvon</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_124'/>
124
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_124'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @param ball : pallo</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_125'/>
125
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_125'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> * @return totuusarvo, osuuko pallo kulmaan (true) vai ei (false)</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_126'/>
126
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_126'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> */</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_127'/>
127
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_127'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> public boolean hitsCorners(Ball ball) { </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_128'/>
128
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_128'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> // Tarkistaa osuuko pallo esteen vasempaan yläkulmaan</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_129'/>
129
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_129'>1</a>
<span>
1. hitsCorners : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> if (hitsTopLeftCorner(ball)) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_130'/>
130
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_130'>1</a>
<span>
1. hitsCorners : removed call to minigolf/domain/Ball::calculateAngleFromCornerCollision → SURVIVED<br/>
</span>
</td>
<td class='covered'><pre><span class='survived'> ball.calculateAngleFromCornerCollision(getLeftSideX(), getTopSideY());</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_131'/>
131
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_131'>1</a>
<span>
1. hitsCorners : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_132'/>
132
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_132'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_133'/>
133
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_133'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> // Tarkistaa osuuko pallo esteen oikeaan yläkulmaan</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_134'/>
134
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_134'>1</a>
<span>
1. hitsCorners : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> if (hitsTopRightCorner(ball)) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_135'/>
135
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_135'>1</a>
<span>
1. hitsCorners : removed call to minigolf/domain/Ball::calculateAngleFromCornerCollision → SURVIVED<br/>
</span>
</td>
<td class='covered'><pre><span class='survived'> ball.calculateAngleFromCornerCollision(getRightSideX(), getTopSideY());</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_136'/>
136
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_136'>1</a>
<span>
1. hitsCorners : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_137'/>
137
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_137'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_138'/>
138
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_138'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> // Tarkistaa osuuko pallo esteen oikeaan alakulmaan</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_139'/>
139
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_139'>1</a>
<span>
1. hitsCorners : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> if (hitsBottomRightCorner(ball)) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_140'/>
140
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_140'>1</a>
<span>
1. hitsCorners : removed call to minigolf/domain/Ball::calculateAngleFromCornerCollision → SURVIVED<br/>
</span>
</td>
<td class='covered'><pre><span class='survived'> ball.calculateAngleFromCornerCollision(getRightSideX(), getBottomSideY());</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_141'/>
141
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_141'>1</a>
<span>
1. hitsCorners : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_142'/>
142
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_142'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_143'/>
143
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_143'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> // Tarkistaa osuuko pallo esteen vasempaan alakulmaan</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_144'/>
144
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_144'>1</a>
<span>
1. hitsCorners : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> if (hitsBottomLeftCorner(ball)) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_145'/>
145
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_145'>1</a>
<span>
1. hitsCorners : removed call to minigolf/domain/Ball::calculateAngleFromCornerCollision → SURVIVED<br/>
</span>
</td>
<td class='covered'><pre><span class='survived'> ball.calculateAngleFromCornerCollision(getLeftSideX(), getBottomSideY());</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_146'/>
146
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_146'>1</a>
<span>
1. hitsCorners : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_147'/>
147
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_147'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_148'/>
148
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_148'>1</a>
<span>
1. hitsCorners : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return false;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_149'/>
149
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_149'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_150'/>
150
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_150'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_151'/>
151
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_151'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> // Tarkistaa osuuko pallo esteen yläreunaan</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_152'/>
152
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_152'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> private boolean hitsTopsSide(int x, int y) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_153'/>
153
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_153'>6</a>
<span>
1. hitsTopsSide : changed conditional boundary → SURVIVED<br/>
2. hitsTopsSide : changed conditional boundary → SURVIVED<br/>
3. hitsTopsSide : Replaced integer addition with subtraction → KILLED<br/>
4. hitsTopsSide : negated conditional → KILLED<br/>
5. hitsTopsSide : negated conditional → KILLED<br/>
6. hitsTopsSide : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='survived'> if (x >= getX() && x <= getX() + getWidth() && y == getY()) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_154'/>
154
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_154'>1</a>
<span>
1. hitsTopsSide : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_155'/>
155
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_155'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_156'/>
156
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_156'>1</a>
<span>
1. hitsTopsSide : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return false;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_157'/>
157
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_157'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_158'/>
158
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_158'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_159'/>
159
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_159'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> // Tarkistaa osuuko pallo esteen oikeaan laitaan</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_160'/>
160
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_160'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> private boolean hitsRightSide(int x, int y) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_161'/>
161
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_161'>7</a>
<span>
1. hitsRightSide : changed conditional boundary → SURVIVED<br/>
2. hitsRightSide : changed conditional boundary → SURVIVED<br/>
3. hitsRightSide : Replaced integer addition with subtraction → KILLED<br/>
4. hitsRightSide : Replaced integer addition with subtraction → KILLED<br/>
5. hitsRightSide : negated conditional → KILLED<br/>
6. hitsRightSide : negated conditional → KILLED<br/>
7. hitsRightSide : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='survived'> if (y >= getY() && y <= getY() + getHeight() && x == getX() + getWidth()) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_162'/>
162
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_162'>1</a>
<span>
1. hitsRightSide : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_163'/>
163
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_163'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_164'/>
164
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_164'>1</a>
<span>
1. hitsRightSide : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return false;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_165'/>
165
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_165'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_166'/>
166
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_166'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_167'/>
167
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_167'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> // Tarkistaa osuuko piste esteen alalaitaan</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_168'/>
168
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_168'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> private boolean hitsBottomSide(int x, int y) { </span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_169'/>
169
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_169'>7</a>
<span>
1. hitsBottomSide : changed conditional boundary → SURVIVED<br/>
2. hitsBottomSide : changed conditional boundary → SURVIVED<br/>
3. hitsBottomSide : Replaced integer addition with subtraction → KILLED<br/>
4. hitsBottomSide : Replaced integer addition with subtraction → KILLED<br/>
5. hitsBottomSide : negated conditional → KILLED<br/>
6. hitsBottomSide : negated conditional → KILLED<br/>
7. hitsBottomSide : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='survived'> if (x >= getX() && x <= getX() + getWidth() && y == getY() + getHeight()) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_170'/>
170
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_170'>1</a>
<span>
1. hitsBottomSide : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_171'/>
171
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_171'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_172'/>
172
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_172'>1</a>
<span>
1. hitsBottomSide : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return false;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_173'/>
173
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_173'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_174'/>
174
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_174'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_175'/>
175
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_175'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> // Tarkistaa osuuko pallo esteen vasempaan</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_176'/>
176
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_176'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> private boolean hitsLeftSide(int x, int y) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_177'/>
177
</td>
<td class='survived'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_177'>6</a>
<span>
1. hitsLeftSide : changed conditional boundary → SURVIVED<br/>
2. hitsLeftSide : changed conditional boundary → SURVIVED<br/>
3. hitsLeftSide : Replaced integer addition with subtraction → KILLED<br/>
4. hitsLeftSide : negated conditional → KILLED<br/>
5. hitsLeftSide : negated conditional → KILLED<br/>
6. hitsLeftSide : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='survived'> if (y >= getY() && y <= getY() + getHeight() && x == getX()) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_178'/>
178
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_178'>1</a>
<span>
1. hitsLeftSide : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_179'/>
179
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_179'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_180'/>
180
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_180'>1</a>
<span>
1. hitsLeftSide : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return false; </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_181'/>
181
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_181'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_182'/>
182
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_182'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_183'/>
183
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_183'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> // Tarkistaa osuuko pallo esteen vasempaan yläkulmaan</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_184'/>
184
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_184'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> private boolean hitsTopLeftCorner(Ball ball) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_185'/>
185
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_185'>1</a>
<span>
1. hitsTopLeftCorner : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> if (ball.hits(getLeftSideX(), getTopSideY())) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_186'/>
186
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_186'>1</a>
<span>
1. hitsTopLeftCorner : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_187'/>
187
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_187'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_188'/>
188
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_188'>1</a>
<span>
1. hitsTopLeftCorner : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return false;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_189'/>
189
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_189'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_190'/>
190
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_190'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_191'/>
191
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_191'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> // Tarkistaa osuuko pallo esteen oikeaan yläkulmaan</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_192'/>
192
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_192'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> private boolean hitsTopRightCorner(Ball ball) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_193'/>
193
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_193'>1</a>
<span>
1. hitsTopRightCorner : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> if (ball.hits(getRightSideX(), getTopSideY())) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_194'/>
194
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_194'>1</a>
<span>
1. hitsTopRightCorner : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_195'/>
195
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_195'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_196'/>
196
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_196'>1</a>
<span>
1. hitsTopRightCorner : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return false;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_197'/>
197
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_197'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_198'/>
198
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_198'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_199'/>
199
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_199'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> // Tarkistaa osuuko pallo esteen oikeaan alakulmaan</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_200'/>
200
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_200'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> private boolean hitsBottomRightCorner(Ball ball) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_201'/>
201
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_201'>1</a>
<span>
1. hitsBottomRightCorner : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> if (ball.hits(getRightSideX(), getBottomSideY())) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_202'/>
202
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_202'>1</a>
<span>
1. hitsBottomRightCorner : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_203'/>
203
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_203'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_204'/>
204
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_204'>1</a>
<span>
1. hitsBottomRightCorner : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return false;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_205'/>
205
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_205'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_206'/>
206
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_206'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_207'/>
207
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_207'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> // Tarkistaa osuuko pallo esteen vasempaan alakulmaan</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_208'/>
208
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_208'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> private boolean hitsBottomLeftCorner(Ball ball) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_209'/>
209
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_209'>1</a>
<span>
1. hitsBottomLeftCorner : negated conditional → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> if (ball.hits(getLeftSideX(), getBottomSideY())) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_210'/>
210
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_210'>1</a>
<span>
1. hitsBottomLeftCorner : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return true;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_211'/>
211
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_211'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_212'/>
212
</td>
<td class='killed'>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_212'>1</a>
<span>
1. hitsBottomLeftCorner : replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED<br/>
</span>
</td>
<td class='covered'><pre><span class='killed'> return false;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_213'/>
213
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_213'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_214'/>
214
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_214'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''></span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@198d9a14_215'/>
215
</td>
<td class=''>
<span class='pop'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_215'></a>
<span>
</span>
</td>
<td class=''><pre><span class=''>}</span></pre></td></tr>
<tr><td></td><td></td><td><h2>Mutations</h2></td></tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_24'>24</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_24'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>getWidth<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_32'>32</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_32'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>getHeight<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_40'>40</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_40'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>getTopSideY<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_48'>48</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_48'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>getRightSideX<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> Replaced integer addition with subtraction → KILLED</p> <p class='KILLED'><span class='pop'>2.<span><b>2</b><br/><b>Location : </b>getRightSideX<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_56'>56</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_56'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>getBottomSideY<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> Replaced integer addition with subtraction → KILLED</p> <p class='KILLED'><span class='pop'>2.<span><b>2</b><br/><b>Location : </b>getBottomSideY<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_64'>64</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_64'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>getLeftSideX<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_74'>74</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_74'/>
<p class='SURVIVED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>inside<br/><b>Killed by : </b>none</span></span> changed conditional boundary → SURVIVED</p> <p class='SURVIVED'><span class='pop'>2.<span><b>2</b><br/><b>Location : </b>inside<br/><b>Killed by : </b>none</span></span> changed conditional boundary → SURVIVED</p> <p class='SURVIVED'><span class='pop'>3.<span><b>3</b><br/><b>Location : </b>inside<br/><b>Killed by : </b>none</span></span> changed conditional boundary → SURVIVED</p> <p class='SURVIVED'><span class='pop'>4.<span><b>4</b><br/><b>Location : </b>inside<br/><b>Killed by : </b>none</span></span> changed conditional boundary → SURVIVED</p> <p class='KILLED'><span class='pop'>5.<span><b>5</b><br/><b>Location : </b>inside<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p> <p class='KILLED'><span class='pop'>6.<span><b>6</b><br/><b>Location : </b>inside<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p> <p class='KILLED'><span class='pop'>7.<span><b>7</b><br/><b>Location : </b>inside<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p> <p class='KILLED'><span class='pop'>8.<span><b>8</b><br/><b>Location : </b>inside<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_75'>75</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_75'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>inside<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_77'>77</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_77'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>inside<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_88'>88</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_88'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hits<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_89'>89</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_89'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hits<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_90'>90</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_90'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hits<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_91'>91</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_91'/>
<p class='NO_COVERAGE'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hits<br/><b>Killed by : </b>none</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → NO_COVERAGE</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_93'>93</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_93'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hits<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_103'>103</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_103'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsSides<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_104'>104</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_104'/>
<p class='SURVIVED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsSides<br/><b>Killed by : </b>none</span></span> removed call to minigolf/domain/Ball::calculateAngleFromVerticalCollision → SURVIVED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_107'>107</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_107'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsSides<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_108'>108</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_108'/>
<p class='SURVIVED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsSides<br/><b>Killed by : </b>none</span></span> removed call to minigolf/domain/Ball::calculateAngleFromHorizontalCollision → SURVIVED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_111'>111</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_111'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsSides<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_112'>112</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_112'/>
<p class='SURVIVED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsSides<br/><b>Killed by : </b>none</span></span> removed call to minigolf/domain/Ball::calculateAngleFromVerticalCollision → SURVIVED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_115'>115</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_115'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsSides<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_116'>116</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_116'/>
<p class='SURVIVED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsSides<br/><b>Killed by : </b>none</span></span> removed call to minigolf/domain/Ball::calculateAngleFromHorizontalCollision → SURVIVED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_119'>119</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_119'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsSides<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_129'>129</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_129'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsCorners<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_130'>130</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_130'/>
<p class='SURVIVED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsCorners<br/><b>Killed by : </b>none</span></span> removed call to minigolf/domain/Ball::calculateAngleFromCornerCollision → SURVIVED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_131'>131</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_131'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsCorners<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_134'>134</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_134'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsCorners<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_135'>135</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_135'/>
<p class='SURVIVED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsCorners<br/><b>Killed by : </b>none</span></span> removed call to minigolf/domain/Ball::calculateAngleFromCornerCollision → SURVIVED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_136'>136</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_136'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsCorners<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_139'>139</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_139'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsCorners<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_140'>140</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_140'/>
<p class='SURVIVED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsCorners<br/><b>Killed by : </b>none</span></span> removed call to minigolf/domain/Ball::calculateAngleFromCornerCollision → SURVIVED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_141'>141</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_141'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsCorners<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_144'>144</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_144'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsCorners<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_145'>145</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_145'/>
<p class='SURVIVED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsCorners<br/><b>Killed by : </b>none</span></span> removed call to minigolf/domain/Ball::calculateAngleFromCornerCollision → SURVIVED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_146'>146</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_146'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsCorners<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_148'>148</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_148'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsCorners<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_153'>153</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_153'/>
<p class='SURVIVED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsTopsSide<br/><b>Killed by : </b>none</span></span> changed conditional boundary → SURVIVED</p> <p class='SURVIVED'><span class='pop'>2.<span><b>2</b><br/><b>Location : </b>hitsTopsSide<br/><b>Killed by : </b>none</span></span> changed conditional boundary → SURVIVED</p> <p class='KILLED'><span class='pop'>3.<span><b>3</b><br/><b>Location : </b>hitsTopsSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> Replaced integer addition with subtraction → KILLED</p> <p class='KILLED'><span class='pop'>4.<span><b>4</b><br/><b>Location : </b>hitsTopsSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p> <p class='KILLED'><span class='pop'>5.<span><b>5</b><br/><b>Location : </b>hitsTopsSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p> <p class='KILLED'><span class='pop'>6.<span><b>6</b><br/><b>Location : </b>hitsTopsSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_154'>154</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_154'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsTopsSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_156'>156</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_156'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsTopsSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_161'>161</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_161'/>
<p class='SURVIVED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsRightSide<br/><b>Killed by : </b>none</span></span> changed conditional boundary → SURVIVED</p> <p class='SURVIVED'><span class='pop'>2.<span><b>2</b><br/><b>Location : </b>hitsRightSide<br/><b>Killed by : </b>none</span></span> changed conditional boundary → SURVIVED</p> <p class='KILLED'><span class='pop'>3.<span><b>3</b><br/><b>Location : </b>hitsRightSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> Replaced integer addition with subtraction → KILLED</p> <p class='KILLED'><span class='pop'>4.<span><b>4</b><br/><b>Location : </b>hitsRightSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> Replaced integer addition with subtraction → KILLED</p> <p class='KILLED'><span class='pop'>5.<span><b>5</b><br/><b>Location : </b>hitsRightSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p> <p class='KILLED'><span class='pop'>6.<span><b>6</b><br/><b>Location : </b>hitsRightSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p> <p class='KILLED'><span class='pop'>7.<span><b>7</b><br/><b>Location : </b>hitsRightSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_162'>162</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_162'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsRightSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_164'>164</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_164'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsRightSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_169'>169</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_169'/>
<p class='SURVIVED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsBottomSide<br/><b>Killed by : </b>none</span></span> changed conditional boundary → SURVIVED</p> <p class='SURVIVED'><span class='pop'>2.<span><b>2</b><br/><b>Location : </b>hitsBottomSide<br/><b>Killed by : </b>none</span></span> changed conditional boundary → SURVIVED</p> <p class='KILLED'><span class='pop'>3.<span><b>3</b><br/><b>Location : </b>hitsBottomSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> Replaced integer addition with subtraction → KILLED</p> <p class='KILLED'><span class='pop'>4.<span><b>4</b><br/><b>Location : </b>hitsBottomSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> Replaced integer addition with subtraction → KILLED</p> <p class='KILLED'><span class='pop'>5.<span><b>5</b><br/><b>Location : </b>hitsBottomSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p> <p class='KILLED'><span class='pop'>6.<span><b>6</b><br/><b>Location : </b>hitsBottomSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p> <p class='KILLED'><span class='pop'>7.<span><b>7</b><br/><b>Location : </b>hitsBottomSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_170'>170</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_170'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsBottomSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_172'>172</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_172'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsBottomSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_177'>177</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_177'/>
<p class='SURVIVED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsLeftSide<br/><b>Killed by : </b>none</span></span> changed conditional boundary → SURVIVED</p> <p class='SURVIVED'><span class='pop'>2.<span><b>2</b><br/><b>Location : </b>hitsLeftSide<br/><b>Killed by : </b>none</span></span> changed conditional boundary → SURVIVED</p> <p class='KILLED'><span class='pop'>3.<span><b>3</b><br/><b>Location : </b>hitsLeftSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> Replaced integer addition with subtraction → KILLED</p> <p class='KILLED'><span class='pop'>4.<span><b>4</b><br/><b>Location : </b>hitsLeftSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p> <p class='KILLED'><span class='pop'>5.<span><b>5</b><br/><b>Location : </b>hitsLeftSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p> <p class='KILLED'><span class='pop'>6.<span><b>6</b><br/><b>Location : </b>hitsLeftSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_178'>178</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_178'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsLeftSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_180'>180</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_180'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsLeftSide<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_185'>185</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_185'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsTopLeftCorner<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_186'>186</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_186'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsTopLeftCorner<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_188'>188</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_188'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsTopLeftCorner<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_193'>193</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_193'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsTopRightCorner<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_194'>194</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_194'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsTopRightCorner<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_196'>196</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_196'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsTopRightCorner<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_201'>201</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_201'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsBottomRightCorner<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_202'>202</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_202'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsBottomRightCorner<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_204'>204</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_204'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsBottomRightCorner<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_209'>209</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_209'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsBottomLeftCorner<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> negated conditional → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_210'>210</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_210'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsBottomLeftCorner<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@198d9a14_212'>212</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@198d9a14_212'/>
<p class='KILLED'><span class='pop'>1.<span><b>1</b><br/><b>Location : </b>hitsBottomLeftCorner<br/><b>Killed by : </b>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest</span></span> replaced return of integer sized value with (x == 0 ? 1 : 0) → KILLED</p>
</td>
</tr>
</table>
<h2>Active mutators</h2>
<ul>
<li class='mutator'>INCREMENTS_MUTATOR</li>
<li class='mutator'>CONDITIONALS_BOUNDARY_MUTATOR</li>
<li class='mutator'>RETURN_VALS_MUTATOR</li>
<li class='mutator'>VOID_METHOD_CALL_MUTATOR</li>
<li class='mutator'>INVERT_NEGS_MUTATOR</li>
<li class='mutator'>MATH_MUTATOR</li>
<li class='mutator'>NEGATE_CONDITIONALS_MUTATOR</li>
</ul>
<h2>Tests examined</h2>
<ul>
<li>minigolf.domain.ObstacleTest.minigolf.domain.ObstacleTest (7 ms)</li>
</ul>
<br/>
Report generated by <a href='http://pitest.org'>PIT</a> 1.1.4
</body>
</html><file_sep>/minigolf/src/main/java/minigolf/gui/Scorecard.java
package minigolf.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import static java.awt.Component.CENTER_ALIGNMENT;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.util.ArrayDeque;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import minigolf.domain.Level;
import minigolf.domain.Player;
import minigolf.game.Game;
public class Scorecard extends JPanel {
private Game game;
private ActionListener handler;
private JPanel menuPanel;
private JLabel title;
private JButton quitButton;
private JTable scores;
private JButton continueButton;
public Scorecard(Game game, ActionListener handler) {
super();
this.game = game;
this.handler = handler;
this.menuPanel = new JPanel();
ArrayList<Level> levels = game.getAllLevels();
ArrayDeque<Player> players = game.getAllPlayers();
String[] columns = getColumns(levels);
Object[][] rows = getRows(levels, players);
this.scores = new JTable(rows, columns);
this.continueButton = new JButton("CONTINUE");
this.handler = handler;
init();
addComponents();
}
private void init() {
// Pohja
setLayout(new BorderLayout());
//setLayout(new GridBagLayout());
setBackground(new Color(138, 224, 0));
menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS));
//menuPanel.setAlignmentX(CENTER_ALIGNMENT);
//menuPanel.setAlignmentY(TOP_ALIGNMENT);
// menuPanel.setBounds(0, 0, 400, 400);
menuPanel.setOpaque(false);
// Alustaa taulukon ylärivin
initTableHeader();
scores.setFont(new Font("Liberations Sans", Font.BOLD, 14));
scores.setRowHeight(32);
scores.setOpaque(false);
// scores.setGridColor(new Color(138, 224, 0));
scores.setAlignmentX(CENTER_ALIGNMENT);
scores.setAlignmentY(CENTER_ALIGNMENT);
scores.setShowGrid(false);
// Keskittää solun tekstit
centralAlignCells();
// Continue painike
continueButton.setFont((new Font("Liberation Sans", Font.BOLD, 20)));
continueButton.setAlignmentX(CENTER_ALIGNMENT);
continueButton.setBackground(Color.WHITE);
continueButton.setForeground(Color.WHITE);
continueButton.setOpaque(false);
continueButton.setBorderPainted(false);
continueButton.setMargin(new Insets(10, 20, 10, 20));
continueButton.setFocusPainted(false);
// Tapahtumakuuntelija (ViewManager)
continueButton.addActionListener(handler);
}
// Palauttaa taulukon sarakkeet
private String[] getColumns(ArrayList<Level> levels) {
String[] columns = new String[levels.size()+2];
int col = 0;
columns[col] = "HOLE";
col++;
for (Level level : levels) {
columns[col] = level.getName();
col++;
}
columns[col] = "TOTAL";
return columns;
}
// Palauttaa taulukon rivit
private Object[][] getRows(ArrayList<Level> levels, ArrayDeque<Player> players) {
Object[][] rows = new Object[players.size()][levels.size()+2];
int row = 0;
for (Player player : players) {
int col = 0;
int total = 0;
rows[row][col] = player.getName();
col++;
for (Level level : levels) {
int score = player.getScore(level);
if (score == -1) {
rows[row][col] = "-";
} else {
rows[row][col] = score;
total += score;
}
col++;
}
rows[row][col] = total;
row++;
}
return rows;
}
// Alustaa taulukon ylärivin
private void initTableHeader() {
JTableHeader header = scores.getTableHeader();
header.setBackground(Color.WHITE);
header.setOpaque(false);
header.setFont(new Font("Liberation Sans", Font.BOLD, 16));
scores.setTableHeader(header);
}
// Keskittää taulukonsolujen tekstikentät
private void centralAlignCells() {
for (int i = 0; i < scores.getColumnCount(); i++) {
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
scores.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
}
}
private void addComponents() {
menuPanel.add(scores.getTableHeader());
menuPanel.add(scores);
menuPanel.add(continueButton);
add(menuPanel);
}
}<file_sep>/minigolf/src/main/java/minigolf/domain/Obstacle.java
package minigolf.domain;
/**
* Pelikentän estettä mallintava luokka, jonka tehtävä on huolehtia esteen
* ulottuvuuksista sekä esteeseen törmäyksen tunnistamisesta
* @author zesbr
*/
public class Obstacle extends LevelObject {
private int width;
private int height;
public Obstacle(int x, int y, int width, int height) {
super(x, y);
this.width = width;
this.height = height;
}
/**
* Palauttaa esteen leveyden
* @return leveys
*/
public int getWidth() {
return width;
}
/**
* Palauttaa esteen korkeuden
* @return korkeus
*/
public int getHeight() {
return height;
}
/**
* Palauttaa esteen ylälaidan y-koordinaatin
* @return ylälaidan y-koordinaatti
*/
public int getTopSideY() {
return getY();
}
/**
* Palauttaa esteen oikean laidan x-koordinaatin
* @return oikean laidan x-koordinaatti
*/
public int getRightSideX() {
return getX() + getWidth();
}
/**
* Palauttaa esteen alalaidan y-koordinaatin
* @return alalaidan y-koordinaatti
*/
public int getBottomSideY() {
return getY() + getHeight();
}
/**
* Palauttaa esteen vasemman laidan x-koordinaatin
* @return vasemman laidan x-koordinaatti
*/
public int getLeftSideX() {
return getX();
}
/**
* Tarkistaa onko piste esteen rajojen sisällä ja palauttaa totuusarvon
* @param x : pisteen x-koordinaatti
* @param y : pisteen y-koordinaatti
* @return totuusarvo onko piste esteen rajojen sisällä (true) vai ulkopuolella (false)
*/
public boolean inside(int x, int y) {
if (x < getLeftSideX() || x > getRightSideX() || y < getTopSideY() || y > getBottomSideY()) {
return false;
}
return true;
}
/**
* Tarkistaa osuuko pallo esteeseen ja kutsuu palloa päivittämään törmäyksen
* aiheuttaman muutoksen pallon liikerataan, sekä palauttaa totuusarvon
* @param ball : pallo
* @return totuusarvo, osuuko pallo esteeseen (true) vai ei (false)
*/
public boolean hits(Ball ball) {
// Tarkistaa osuuko pallo esteen laitoihin tai jos ei osu, niin osuuko sen kulmiin
if (hitsSides(ball)) {
return true;
} else if (hitsCorners(ball)) {
return true;
}
return false;
}
/**
* Tarkistaa osuuko pallo esteen laitoihin ja palauttaa totuusarvon
* @param ball : pallo
* @return totuusarvo, osuuko pallo esteen laitoihin (true) vai ei (false)
*/
public boolean hitsSides(Ball ball) {
boolean hits = false;
if (hitsTopsSide(ball.getBottomX(), ball.getBottomY())) {
ball.calculateAngleFromVerticalCollision();
hits = true;
}
if (hitsRightSide(ball.getLeftX(), ball.getLeftY())) {
ball.calculateAngleFromHorizontalCollision();
hits = true;
}
if (hitsBottomSide(ball.getTopX(), ball.getTopY())) {
ball.calculateAngleFromVerticalCollision();
hits = true;
}
if (hitsLeftSide(ball.getRightX(), ball.getRightY())) {
ball.calculateAngleFromHorizontalCollision();
hits = true;
}
return hits;
}
/**
* Tarkistaa osuuko pallo esteen kulmiin ja palauttaa totuusarvon
* @param ball : pallo
* @return totuusarvo, osuuko pallo kulmaan (true) vai ei (false)
*/
public boolean hitsCorners(Ball ball) {
// Tarkistaa osuuko pallo esteen vasempaan yläkulmaan
if (hitsTopLeftCorner(ball)) {
//ball.calculateAngleFromCornerCollision(getLeftSideX(), getTopSideY());
ball.calcualateAngleFromTopLeftCollision();
return true;
}
// Tarkistaa osuuko pallo esteen oikeaan yläkulmaan
if (hitsTopRightCorner(ball)) {
// ball.calculateAngleFromCornerCollision(getRightSideX(), getTopSideY());
ball.calcualateAngleFromTopRightCollision();
return true;
}
// Tarkistaa osuuko pallo esteen oikeaan alakulmaan
if (hitsBottomRightCorner(ball)) {
// ball.calculateAngleFromCornerCollision(getRightSideX(), getBottomSideY());
ball.calcualateAngleFromBottomRightCollision();
return true;
}
// Tarkistaa osuuko pallo esteen vasempaan alakulmaan
if (hitsBottomLeftCorner(ball)) {
// ball.calculateAngleFromCornerCollision(getLeftSideX(), getBottomSideY());
ball.calcualateAngleFromBottomLeftCollision();
return true;
}
return false;
}
// Tarkistaa osuuko pallo esteen yläreunaan
private boolean hitsTopsSide(int x, int y) {
if (x >= getX() && x <= getX() + getWidth() && y == getY()) {
return true;
}
return false;
}
// Tarkistaa osuuko pallo esteen oikeaan laitaan
private boolean hitsRightSide(int x, int y) {
if (y >= getY() && y <= getY() + getHeight() && x == getX() + getWidth()) {
return true;
}
return false;
}
// Tarkistaa osuuko piste esteen alalaitaan
private boolean hitsBottomSide(int x, int y) {
if (x >= getX() && x <= getX() + getWidth() && y == getY() + getHeight()) {
return true;
}
return false;
}
// Tarkistaa osuuko pallo esteen vasempaan
private boolean hitsLeftSide(int x, int y) {
if (y >= getY() && y <= getY() + getHeight() && x == getX()) {
return true;
}
return false;
}
// Tarkistaa osuuko pallo esteen vasempaan yläkulmaan
private boolean hitsTopLeftCorner(Ball ball) {
if (ball.hits(getLeftSideX(), getTopSideY())) {
return true;
}
return false;
}
// Tarkistaa osuuko pallo esteen oikeaan yläkulmaan
private boolean hitsTopRightCorner(Ball ball) {
if (ball.hits(getRightSideX(), getTopSideY())) {
return true;
}
return false;
}
// Tarkistaa osuuko pallo esteen oikeaan alakulmaan
private boolean hitsBottomRightCorner(Ball ball) {
if (ball.hits(getRightSideX(), getBottomSideY())) {
return true;
}
return false;
}
// Tarkistaa osuuko pallo esteen vasempaan alakulmaan
private boolean hitsBottomLeftCorner(Ball ball) {
if (ball.hits(getLeftSideX(), getBottomSideY())) {
return true;
}
return false;
}
} | 077e804f0cef0f63cd8ab833508a571eb260890f | [
"Markdown",
"Java",
"HTML"
] | 24 | Java | zesbr/minigolf | cdf33c00e55054d4993663e87576c1fb37c295fa | 0a09d82f9f855fe042fd46d3789e8a03f10c3ff8 |
refs/heads/master | <repo_name>rubemvieira/projetointegrador-modulov<file_sep>/LojaServico/src/main/java/persistencia/ServicoDAO.java
package persistencia;
import java.io.Serializable;
import java.util.List;
import org.hibernate.query.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import bean.Servico;
public class ServicoDAO implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public static void gravar(Servico servico) {
Session sessao = HibernateUtil.getSessionFactory().openSession();
Transaction t = sessao.beginTransaction();
if(servico.getId() == 0) {
sessao.save(servico);
} else {
sessao.update(servico);
}
t.commit();
sessao.close();
}
public static void excluir(Servico servico) {
Session sessao = HibernateUtil.getSessionFactory().openSession();
Transaction t = sessao.beginTransaction();
sessao.delete(servico);
t.commit();
sessao.close();
}
public static List<Servico> listagem() {
Session sessao = HibernateUtil.getSessionFactory().openSession();
Query<Servico> consulta = sessao.createQuery("from Servico order by descricao", Servico.class);
List<Servico> lista = consulta.getResultList();
sessao.close();
return lista;
}
}
<file_sep>/LojaServico/src/main/java/negocio/CarrinhoController.java
package negocio;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import bean.ItemPedido;
import bean.Pedido;
import bean.Pessoa;
import wrapper.Produto;
import persistencia.PedidoDAO;
import persistencia.PessoaDAO;
import persistencia.ProdutoDAO;
@ManagedBean
@SessionScoped
public class CarrinhoController implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((pedido == null) ? 0 : pedido.hashCode());
result = prime * result + ((produtoSelecionado == null) ? 0 : produtoSelecionado.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CarrinhoController other = (CarrinhoController) obj;
if (pedido == null) {
if (other.pedido != null)
return false;
} else if (!pedido.equals(other.pedido))
return false;
if (produtoSelecionado == null) {
if (other.produtoSelecionado != null)
return false;
} else if (!produtoSelecionado.equals(other.produtoSelecionado))
return false;
return true;
}
private Pedido pedido = new Pedido();
private Produto produtoSelecionado;
private Double quantidade;
private Pessoa cliente;
public CarrinhoController() {
// TODO Auto-generated constructor stub
}
public Pedido getPedido() {
return pedido;
}
public void setPedido(Pedido pedido) {
this.pedido = pedido;
}
public void actionInserirProduto() {
if (pedido == null)
pedido = new Pedido();
Double quantidade = produtoSelecionado.getQuantidade();
ItemPedido item = new ItemPedido();
item.setPedido(pedido);
item.setProduto(produtoSelecionado.getProduto());
item.setValorunitario(produtoSelecionado.getProduto().getPreco());
item.setQuantidade(quantidade);
item.setSubtotal(quantidade * produtoSelecionado.getProduto().getPreco());
pedido.setTotalproduto(pedido.getTotalproduto() == null ? 0.00 : pedido.getTotalproduto());
pedido.setTotalproduto(pedido.getTotalproduto() + item.getSubtotal());
pedido.setTotalgeral(pedido.getTotalproduto());
pedido.getItens().add(item);
quantidade = 0.0;
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Sucesso", "Produto incluído no carrinho!"));
}
public String actionFinalizarPedido() {
if (pedido == null) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Erro", "Carrinho vazio!"));
return "/index.html";
}
pedido.setId(0);
pedido.setPessoa(this.getUsuarioLogado());
PedidoDAO.gravar(pedido);
limparCarrinho();
return "/cliente/cliente";
}
public String getQuantidadeItens() {
if (pedido != null)
return Integer.toString(pedido.getItens() != null ? pedido.getItens().size() : 0);
else
return "0";
}
public List<Produto> getListagem() {
List<bean.Produto> lista = ProdutoDAO.listagem();
List<Produto> ret = new ArrayList<>();
if (!lista.isEmpty()) {
for(int i = 0; i < lista.size(); i++) {
Produto w = new Produto();
w.setProduto(lista.get(i));
w.setQuantidade(0.0);
ret.add(w);
}
}
return ret;
}
public Produto getProdutoSelecionado() {
return produtoSelecionado;
}
public void setProdutoSelecionado(Produto produtoSelecionado) {
this.produtoSelecionado = produtoSelecionado;
}
public Double getQuantidade() {
return quantidade;
}
public void setQuantidade(Double quantidade) {
if(quantidade != null)
this.quantidade = quantidade;
}
public Pessoa getCliente() {
return cliente;
}
public void setCliente(Pessoa cliente) {
this.cliente = cliente;
}
public Pessoa getUsuarioLogado() {
UserDetails user = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
PessoaDAO p = new PessoaDAO();
return p.retrieveByEmail(user.getUsername());
}
public void limparCarrinho() {
this.setCliente(null);
this.setProdutoSelecionado(null);
this.setQuantidade(null);
this.setPedido(null);
}
}
<file_sep>/LojaServico/src/main/java/converter/FormaPagamentoConverter.java
package converter;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import persistencia.FormaPagamentoDAO;
import bean.FormaPagamento;
@ManagedBean
@RequestScoped
public class FormaPagamentoConverter implements Converter {
public FormaPagamentoConverter() {
// TODO Auto-generated constructor stub
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || value.isEmpty()) {
return null;
}
return new FormaPagamentoDAO().retrieveById(Integer.parseInt(value));
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return "";
}
if (value instanceof FormaPagamento) {
return String.valueOf(((FormaPagamento) value).getId());
} else {
throw new ConverterException(new FacesMessage(String.format("%s is not a valid FormaPagamento", value)), null);
}
}
}
<file_sep>/LojaServico/src/main/java/negocio/ProdutoController.java
package negocio;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import bean.Produto;
import persistencia.ProdutoDAO;
@ManagedBean
@SessionScoped
public class ProdutoController implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Produto produto;
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public List<Produto> getListagem() {
return ProdutoDAO.listagem();
}
public String actionGravar() {
ProdutoDAO.gravar(produto);
return ("lista_produtos" );
}
public String actionInserir() {
produto = new Produto();
produto.setId(0);
return "formulario_produto";
}
public String actionExcluir(Produto m) {
ProdutoDAO.excluir(m);
return "lista_produtos";
}
public String actionAlterar(Produto m) {
produto = m;
return "formulario_produto";
}
public String actionListar() {
return "lista_produtos";
}
}
<file_sep>/LojaServico/src/main/java/converter/PessoaConverter.java
package converter;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import persistencia.PessoaDAO;
import bean.Pessoa;
@ManagedBean
@RequestScoped
public class PessoaConverter implements Converter {
public PessoaConverter() {
// TODO Auto-generated constructor stub
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || value.isEmpty()) {
return null;
}
return new PessoaDAO().retrieveById(Long.parseLong(value));
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return "";
}
if (value instanceof Pessoa) {
return String.valueOf(((Pessoa) value).getId());
} else {
throw new ConverterException(new FacesMessage(String.format("%s is not a valid Pessoa", value)), null);
}
}
}
<file_sep>/LojaServico/src/main/java/bean/Pessoa.java
package bean;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "pessoa")
public class Pessoa implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2131272464788833307L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "pessoa_id")
private Integer id;
@Column(name = "nome")
private String nome;
@Column(name = "cpf")
private String cpf;
@Column(name = "rg")
private String rg;
@Column(name = "datanasc")
private Date dataNascimento;
@Column(name = "rua")
private String rua;
@Column(name = "bairro")
private String bairro;
@Column(name = "cidade")
private String cidade;
@Column(name = "uf")
private String uf;
@Column(name = "cep")
private Integer cep;
@Column(name = "email")
private String email;
@Column(name = "senha")
private String senha;
@Column(name = "tipo")
private String tipo;
@OneToMany(mappedBy="pessoa", cascade = CascadeType.PERSIST)
private Set<Fone> fones;
public Set<Fone> getFones() {
return fones;
}
public void setFones(Set<Fone> fones) {
this.fones = fones;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
public String getRua() {
return rua;
}
public void setRua(String rua) {
this.rua = rua;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
public Integer getCep() {
return cep;
}
public void setCep(Integer cep) {
this.cep = cep;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public Pessoa() {
// TODO Auto-generated constructor stub
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bairro == null) ? 0 : bairro.hashCode());
result = prime * result + ((cep == null) ? 0 : cep.hashCode());
result = prime * result + ((cidade == null) ? 0 : cidade.hashCode());
result = prime * result + ((cpf == null) ? 0 : cpf.hashCode());
result = prime * result + ((dataNascimento == null) ? 0 : dataNascimento.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result + ((rg == null) ? 0 : rg.hashCode());
result = prime * result + ((rua == null) ? 0 : rua.hashCode());
result = prime * result + ((senha == null) ? 0 : senha.hashCode());
result = prime * result + ((tipo == null) ? 0 : tipo.hashCode());
result = prime * result + ((uf == null) ? 0 : uf.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pessoa other = (Pessoa) obj;
if (bairro == null) {
if (other.bairro != null)
return false;
} else if (!bairro.equals(other.bairro))
return false;
if (cep == null) {
if (other.cep != null)
return false;
} else if (!cep.equals(other.cep))
return false;
if (cidade == null) {
if (other.cidade != null)
return false;
} else if (!cidade.equals(other.cidade))
return false;
if (cpf == null) {
if (other.cpf != null)
return false;
} else if (!cpf.equals(other.cpf))
return false;
if (dataNascimento == null) {
if (other.dataNascimento != null)
return false;
} else if (!dataNascimento.equals(other.dataNascimento))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
if (rg == null) {
if (other.rg != null)
return false;
} else if (!rg.equals(other.rg))
return false;
if (rua == null) {
if (other.rua != null)
return false;
} else if (!rua.equals(other.rua))
return false;
if (senha == null) {
if (other.senha != null)
return false;
} else if (!senha.equals(other.senha))
return false;
if (tipo == null) {
if (other.tipo != null)
return false;
} else if (!tipo.equals(other.tipo))
return false;
if (uf == null) {
if (other.uf != null)
return false;
} else if (!uf.equals(other.uf))
return false;
return true;
}
}
<file_sep>/LojaServico/src/main/java/bean/ItemPedido.java
package bean;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "itenspedido")
public class ItemPedido implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "itenspedido_id")
private Integer id;
@ManyToOne
@JoinColumn(name = "pedido_id")
private Pedido pedido;
@ManyToOne
@JoinColumn(name = "produto_id")
private Produto produto;
@ManyToOne
@JoinColumn(name = "servico_id")
private Servico servico;
@Column(name = "dataautorizacao")
private Date dataAutorizacao;
@Column(name = "qtde")
private Double quantidade;
@Column(name = "valorunit")
private Double valorunitario;
@Column(name = "subtotal")
private Double subtotal;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Pedido getPedido() {
return pedido;
}
public void setPedido(Pedido pedido) {
this.pedido = pedido;
}
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public Servico getServico() {
return servico;
}
public void setServico(Servico servico) {
this.servico = servico;
}
public Date getDataAutorizacao() {
return dataAutorizacao;
}
public void setDataAutorizacao(Date dataAutorizacao) {
this.dataAutorizacao = dataAutorizacao;
}
public Double getQuantidade() {
return quantidade;
}
public void setQuantidade(Double quantidade) {
this.quantidade = quantidade;
}
public Double getValorunitario() {
return valorunitario;
}
public void setValorunitario(Double valorunitario) {
this.valorunitario = valorunitario;
}
public Double getSubtotal() {
return subtotal;
}
public void setSubtotal(Double subtotal) {
this.subtotal = subtotal;
}
public ItemPedido() {
// TODO Auto-generated constructor stub
}
}
<file_sep>/LojaServico/target/m2e-wtp/web-resources/META-INF/maven/br.com.rubem/LojaServico/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>br.com.rubem</groupId>
<artifactId>LojaServico</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Loja Serviço</name>
<properties>
<springsecurity.version>4.0.4.RELEASE</springsecurity.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>https://repository.primefaces.org</url>
<layout>default</layout>
</repository>
<repository>
<id>jvnet-nexus-releases</id>
<name>jvnet-nexus-releases</name>
<url>https://maven.java.net/content/repositories/releases/</url>
</repository>
<repository>
<id>org.springframework.security.taglibs.facelets</id>
<url>http://spring-security-facelets-taglib.googlecode.com/svn/repo/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.10</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.10</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>6.1</version>
</dependency>
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>redmond</artifactId>
<version>1.0.10</version>
</dependency>
<dependency>
<groupId>org.primefaces.extensions</groupId>
<artifactId>primefaces-extensions</artifactId>
<version>6.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.11.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-el/commons-el -->
<dependency>
<groupId>commons-el</groupId>
<artifactId>commons-el</artifactId>
<version>1.0</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<!-- Servlet+JSP+JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>10</source>
<target>10</target>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>/LojaServico/src/main/java/persistencia/PessoaDAO.java
package persistencia;
import java.io.Serializable;
import java.util.List;
import org.hibernate.query.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import bean.Pessoa;
public class PessoaDAO implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public static void gravar(Pessoa pessoa) {
Session sessao = HibernateUtil.getSessionFactory().openSession();
Transaction t = sessao.beginTransaction();
if(pessoa.getId() == 0) {
sessao.save(pessoa);
} else {
sessao.update(pessoa);
}
t.commit();
sessao.close();
}
public static void excluir(Pessoa pessoa) {
Session sessao = HibernateUtil.getSessionFactory().openSession();
Transaction t = sessao.beginTransaction();
sessao.delete(pessoa);
t.commit();
sessao.close();
}
public static List<Pessoa> listagem() {
Session sessao = HibernateUtil.getSessionFactory().openSession();
Query<Pessoa> consulta = sessao.createQuery("from Pessoa order by nome", Pessoa.class);
List<Pessoa> lista = consulta.getResultList();
sessao.close();
return lista;
}
public Pessoa retrieveById(Long id) {
Session sessao = HibernateUtil.getSessionFactory().openSession();
Pessoa pessoa = sessao.get(Pessoa.class, id);
sessao.close();
return pessoa;
}
public Pessoa retrieveByEmail(String email) {
Session sessao = HibernateUtil.getSessionFactory().openSession();
Pessoa consulta = sessao.createQuery("from Pessoa where email = :Email", Pessoa.class).setParameter("Email", email).uniqueResult();
sessao.close();
return consulta;
}
}
| 361eb1d3bbefd3b1582eca2b7c7b64e170cad89a | [
"Java",
"Maven POM"
] | 9 | Java | rubemvieira/projetointegrador-modulov | a783bf64fbf689189503a94ee660067c20d8e4ce | ff561ba20d7e98643947d7b3d7d2add804c83a9f |
refs/heads/master | <file_sep>#include <iostream>
#include "matgen.hpp"
#include "fdops.hpp"
#include "IterativeSolvers/jacobi.hpp"
namespace bz = blaze;
namespace bu = blazeutils;
/**/
int main() {
std::mt19937 g(0);
bz::DynamicMatrix<double> A = bu::randn_matrix_real<double>(3UL, 3UL, g);
//bu::print_mat(A);
bz::CompressedMatrix<double> D1 = bu::deriv1_forward_1d<double>(5);
bz::DynamicMatrix<double> D1_1(D1);
//bu::print_mat(D1_1);
bz::DynamicMatrix<double> system{{3, 2}, {3, 5}};
bz::DynamicVector<double> b{4, 7};
bz::DynamicVector<double> sol;
sol = bu::jacobi<double>(system, b);
system = bu::randu_matrix_real<double>(10, 10, g);
b = bu::randu_vector_real<double>(10, g);
sol = bu::jacobi<double>(system, b);
for(int i = 0; i < 2; ++i){
std::cout << sol[i] << '\n';
}
return 0;
}<file_sep>//
// Created by chronum-work on 28/5/17.
//
#ifndef BLAZEUTILS_SOLVER_EXCEPTIONS_HPP
#define BLAZEUTILS_SOLVER_EXCEPTIONS_HPP
#endif //BLAZEUTILS_SOLVER_EXCEPTIONS_HPP
<file_sep>//
// Created by chronum-work on 25/5/17.
//
#ifndef BLAZEUTILS_FDOPS_HPP
#define BLAZEUTILS_FDOPS_HPP
#include "blaze/Blaze.h"
namespace bz = blaze;
namespace blazeutils{
template<typename T>
bz::CompressedMatrix<T> deriv2_1d(const unsigned long mat_dim) {
bz::CompressedMatrix<T> result(mat_dim, mat_dim);
// This method uses the low-level reserve/append/finalize methods.
// https://bitbucket.org/blaze-lib/blaze/wiki/Matrix%20Operations#!element-insertion
result.reserve(3*mat_dim-2); // A 2nd-order Laplacian has 3n-2 nonzeros.
// Inserting into first row.
result.append(0, 0, -2); // diag.
result.append(0, 1, 1); //upper diag.
result.finalize(0);
for(unsigned long i = 1; i < mat_dim-1; ++i) {
std::cout << i << std::endl;
result.append(i, i - 1, 1); // lower diag.
result.append(i, i, -2); // diag.
result.append(i, i + 1, 1); // upper diag.
result.finalize(i);
}
// Last row updated here. Putting this before the loop
// causes a bug where you update and finalize row 0
// even though you explicitly tell it to update row n-1.
result.append(mat_dim-1, mat_dim-1, -2); // diag.
result.append(mat_dim-1, mat_dim-2, 1); // lower diag.
result.finalize(mat_dim-1);
return result;
}
template<typename T>
bz::CompressedMatrix<T> deriv1_centered_1d(const unsigned long mat_dim) {
bz::CompressedMatrix<T> result(mat_dim, mat_dim);
// This method uses the low-level reserve/append/finalize methods.
// https://bitbucket.org/blaze-lib/blaze/wiki/Matrix%20Operations#!element-insertion
result.reserve(2*mat_dim-2); // A centered first derivative has 2n-2 nonzeros.
// Inserting into first row.
result.append(0, 1, -1); //upper diag.
result.finalize(0);
for(unsigned long i = 1; i < mat_dim-1; ++i){
result.append(i, i-1, 1); // lower diag.
result.append(i, i+1, -1); // upper diag.
result.finalize(i);
}
// Updating last row after loop.
result.append(mat_dim-1, mat_dim-2, 1); //lower diag.
result.finalize(mat_dim-1);
return result;
}
template<typename T>
bz::CompressedMatrix<T> deriv1_forward_1d(const unsigned long mat_dim) {
bz::CompressedMatrix<T> result(mat_dim, mat_dim);
// This method uses the low-level reserve/append/finalize methods.
// https://bitbucket.org/blaze-lib/blaze/wiki/Matrix%20Operations#!element-insertion
result.reserve(2*mat_dim-1); // A fw/bw first derivative has 2n-1 nonzeros.
for(unsigned long i = 0; i < mat_dim-1; ++i){
result.append(i, i, 1); //diag.
result.append(i, i+1, -1); // upper diag.
result.finalize(i);
}
// Updating last row after loop.
result.append(mat_dim-1, mat_dim-1, 1); //diag.
result.finalize(mat_dim-1);
return result;
}
template<typename T>
bz::CompressedMatrix<T> deriv1_backward_1d(const unsigned long mat_dim) {
bz::CompressedMatrix<T> result(mat_dim, mat_dim);
// This method uses the low-level reserve/append/finalize methods.
// https://bitbucket.org/blaze-lib/blaze/wiki/Matrix%20Operations#!element-insertion
result.reserve(2*mat_dim-1); /// A fw/bw first derivative has 2n-1 nonzeros.
// Updating last row after loop.
result.append(0, 0, 1); //ldiag.
result.finalize(0);
for(unsigned long i = 1; i < mat_dim; ++i){
result.append(i, i, -1); // diag.
result.append(i, i-1, 1); // lower diag.
result.finalize(i);
}
// Updating last row after loop.
result.append(mat_dim-1, mat_dim-1, 1); // diag.
result.finalize(mat_dim-1);
return result;
}
};
#endif //BLAZEUTILS_FDOPS_HPP
<file_sep>cmake_minimum_required(VERSION 3.7)
project(BlazeUtils)
set(CMAKE_CXX_STANDARD 14)
link_libraries(openblas)
set(SOURCE_FILES main.cpp
matgen.hpp
fdops.hpp
IterativeSolvers/linutils.hpp
IterativeSolvers/jacobi.hpp
IterativeSolvers/jacobi.cpp
IterativeSolvers/solver_exceptions.hpp)
add_executable(BlazeUtils ${SOURCE_FILES})<file_sep>//
// Created by chronum-work on 26/5/17.
//
#include "jacobi.hpp"
namespace blazeutils {
template<typename T>
bz::DynamicVector<T> jacobi(bz::DynamicMatrix<T> &A, bz::DynamicVector<T>&b , float tol, int max_iter) {
// Dimensions of system.
auto dims = b.size();
bz::DynamicVector <T> result(dims);
// Initializing the initial and update x-vectors.
bz::DynamicVector <T> x0(dims), xk(dims);
x0 = 1;
bz::DynamicVector <T> residual(dims);
// Norm of b, the RHS vector, and the residual.
// The norm of the residual is calculated in the loop.
double norm_residual = 1;
double norm_b = norm2(b);
int niter = 0; // Iteration counter.
bool solution_found = false;
// Extracting diagonal of the given matrix, and inverting.
// This is the iteration matrix for the Jacobi method.
bz::DynamicMatrix <T> jacobi_matrix = diag_from<double>(A);
bz::invert(jacobi_matrix);
// Main solver loop.
for (niter = 0; niter < max_iter; ++niter) {
residual = b - A * x0;
norm_residual = norm2(residual);
// Early termination check.
if (norm_residual < tol * norm_b) {
std::cout << "Solution in " << niter << " iterations!" << std::endl;
solution_found = true;
break;
}
xk = x0 + jacobi_matrix * residual;
x0 = xk;
}
if (!solution_found) {
// TODO: Create a separate header for custom exceptions to throw around.
throw solution_found;
}
return x0;
}
template
bz::DynamicVector<double> jacobi(bz::DynamicMatrix<double>& A, bz::DynamicVector<double>& b, float tol, int max_iter);
template
bz::DynamicVector<float> jacobi(bz::DynamicMatrix<float>& A, bz::DynamicVector<float>& b, float tol, int max_iter);
}<file_sep>//
// Created by chronum-work on 28/5/17.
//
#ifndef BLAZEUTILS_JACOBI_HPP
#define BLAZEUTILS_JACOBI_HPP
#include "blaze/Blaze.h"
#include "linutils.hpp"
namespace bz = blaze;
namespace blazeutils{
template<typename T>
bz::DynamicVector<T> jacobi(bz::DynamicMatrix<T> &A, bz::DynamicVector<T> &b,
float tol = 1e-8, int max_iter = 500);
}
#endif //BLAZEUTILS_JACOBI_HPP
<file_sep>//
// Created by chronum-work on 26/5/17.
//
#ifndef BLAZEUTILS_LINUTILS_HPP
#define BLAZEUTILS_LINUTILS_HPP
#include <type_traits>
#include "blaze/Blaze.h"
namespace bz = blaze;
namespace blazeutils {
template<typename T>
bz::DynamicMatrix<T> diag_from(const bz::DynamicMatrix<T>& A) {
if(A.rows() != A.columns()){
std::cout << "Can only have diagonals of square matrices" << std::endl;
return A;
} else {
unsigned long dim = A.rows();
bz::DynamicMatrix<T> result(dim, dim);
for (unsigned long i = 0; i < dim; ++i){
result(i, i) = A(i ,i);
}
return result;
}
}
template<typename T>
double norm2(bz::DynamicVector<T>& vector){
double norm = 0;
double length = vector.size();
for(unsigned long i = 0; i < length; ++i){
norm += vector[i]*vector[i];
}
return std::sqrt(norm);
}
}
#endif //BLAZEUTILS_LINUTILS_HPP
<file_sep>//
// Created by chronum on 5/23/17.
//
#ifndef BLAZEUTILS_MATGEN_HPP
#define BLAZEUTILS_MATGEN_HPP
#include <blaze/Blaze.h>
#include <iomanip>
#include <iostream>
#include <random>
namespace bz=blaze;
namespace blazeutils {
// Generates a uniform random matrix of type T using a (P)RNG
// of class Generator.
template<typename T, class Generator = std::mt19937>
bz::DynamicMatrix<T> randu_matrix_real(const unsigned long rows,
const unsigned long cols, Generator& g) {
bz::DynamicMatrix <T> rand_matrix(rows, cols);
std::uniform_real_distribution<T> distribution(0, 1);
for (auto row = 0; row < rows; ++row) {
for (auto col = 0; col < cols; ++col) {
rand_matrix(row, col) = distribution(g);
}
}
return rand_matrix;
}
// Generates a normal random matrix of type T using a (P)RNG
// of class Generator.
template<typename T, class Generator = std::mt19937>
bz::DynamicMatrix<T> randn_matrix_real(const unsigned long rows,
const unsigned long cols,
Generator& g,
double mu = 0.0, double sigma = 1.0) {
bz::DynamicMatrix <T> rand_matrix(rows, cols);
std::normal_distribution<T> distribution(mu, sigma);
for (auto row = 0; row < rows; ++row) {
for (auto col = 0; col < cols; ++col) {
rand_matrix(row, col) = distribution(g);
}
}
return rand_matrix;
}
// Generates a uniform random matrix of type T using a (P)RNG
// of class Generator.
template<typename T, class Generator = std::mt19937>
bz::DynamicVector<T> randu_vector_real(const unsigned long length, Generator& g) {
bz::DynamicVector <T> rand_vector(length);
std::uniform_real_distribution<T> distribution(0, 1);
for (auto element = 0; element < length; ++element) {
rand_vector[element] = distribution(g);
}
return rand_vector;
}
// Generates a normal random matrix of type T using a (P)RNG
// of class Generator.
template<typename T, class Generator = std::mt19937>
bz::DynamicVector<T> randn_vector_real(const unsigned long length,
Generator& g,
double mu = 0.0, double sigma = 1.0) {
bz::DynamicVector <T> rand_vector(length);
std::normal_distribution<T> distribution(mu, sigma);
for (auto element = 0; element < length; ++element) {
rand_vector[element] = distribution(g);
}
return rand_vector;
}
// TODO: This does not belong here. Should be placed elsewhere.
// Potentially with other similar functions.
template <typename T>
void print_mat(T const& matrix){
unsigned long rows = matrix.rows(), cols = matrix.columns();
std::cout.width(10);
std::cout.precision(4);
std::cout.right;
std::cout.fixed;
std::cout << ' ' << std::endl;
//std::cout << std::setw(10) << std::endl;
//std::cout << std::setprecision(6) << std::endl;
for(auto i = 0UL; i < rows; ++i) {
for (auto j = 0UL; j < cols; ++j){
std::cout << matrix(i, j) << '\t';
}
std::cout << std::endl;
}
}
}
#endif //BLAZE_IDE_TEST_BLAZEGEN_HPP | 7302ed9767cef24123f3881b23cc78385dc69b53 | [
"CMake",
"C++"
] | 8 | C++ | Chronum94/BlazeUtils | 86a47b756cbda562d3db28221b5ddf2a31613345 | 610cb3c390580f667faf4997e601117b73e5683a |
refs/heads/master | <repo_name>citradp/DOM-practice<file_sep>/dice.js
// alert("Hello")
var randomDice1 = Math.floor(Math.random() * 6) + 1;
var numberDice1 = "/images/dice" + randomDice1 + '.png';
var randomDice2 = Math.floor(Math.random() * 6) + 1;
var numberDice2 = "/images/dice" + randomDice2 + '.png';
var dice1 = document.querySelectorAll('img')[0];
dice1.setAttribute("src", numberDice1)
// console.log(numberDice1);
var dice2 = document.querySelectorAll('img')[1];
dice2.setAttribute('src', numberDice2);
var result = document.querySelector('h1');
if (randomDice1 > randomDice2){
result.textContent = "Player 1 Win";
} else if (randomDice1 < randomDice2){
result.textContent = "Player 2 Win";
} else {
result.textContent = "Draw";
}
| 3515d070c2fba0a172e44bba88299d61b224feb0 | [
"JavaScript"
] | 1 | JavaScript | citradp/DOM-practice | 58dafc6ff31ddca4107ef45184f73ec2986d38a4 | a0bfca77cfeb995f4bceacdcbc38bcdfab0363dd |
refs/heads/master | <repo_name>LeoCR/react-redux-users-restaurant<file_sep>/src/actions/userActions.js
import {SET_USER,EDIT_USER} from '../constants/userTypes';
import api from "../apis/api";
export const setUser=(user)=>{
return{
type:SET_USER,
payload:user
};
}
export const editUser=user=>async dispatch=>{
const response = await api.put(`/api/user/update/${user.email}`,user)
.then((user)=>{
console.log('User updated');
console.log(user);
})
.catch((err)=>{
console.log('An error occurs');
console.log(err);
})
dispatch({
type:EDIT_USER,
payload:response.data
})
}<file_sep>/src/components/Modal.js
import React from "react";
import $ from 'jquery';
import api from '../apis/api';
import {connect} from 'react-redux';
import UserDetails from './user/UserDetails';
import {updateItemUnits,deleteFromCart} from '../actions/cartActions';
import CartProducts from './shopping-cart/CartProducts';
import {setUser} from "../actions/userActions";
class Modal extends React.Component{
componentDidMount(){
this.setUserData();
}
setUserData=()=>{
var _this=this;
try {
api.get('/api/user/info').then(function (res) {
if(res.data){
_this.props.setUser(res.data);
}
});
} catch (error) {
console.log('An error occurs in Modal.setUserData() '+error);
}
}
closeModal=(e)=>{
$('.modal').css({'display':'none'});
$('body').toggleClass('modal-opened');
}
checkout=()=>{
window.location.replace("/checkout");
}
render(){
var ModalContent,titleModal;
if(this.props.showModal==='showUserDetails'){
ModalContent=<UserDetails/>;
titleModal='User Details';
}
else{
titleModal='Shopping Cart';
ModalContent=<CartProducts calculateOrders={this.props.calculateOrders} checkout={this.checkout}/>;
}
return(
<div className="modal" tabIndex="-1" role="dialog">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">{titleModal}</h5>
<button type="button" className="close"
data-dismiss="modal" aria-label="Close"
onClick={(e)=>this.closeModal(e)}>
<span aria-hidden="true">×</span>
</button>
</div>
{ModalContent}
</div>
</div>
</div>
)
}
}
const mapStateToProps=(state)=>{
return{
orders:state.orders,
user:state.user.user
}
}
export default connect(mapStateToProps,{updateItemUnits,deleteFromCart,setUser})(Modal)<file_sep>/src/containers/UserContainer.js
import React from "react";
import { Router, Route, Link } from "react-router-dom";
import history from '../history';
import UserProfile from '../components/user/UserProfile';
import UserHistory from '../components/user/UserHistory';
import UserInvoice from "../components/user/UserInvoice";
const UserContainer=()=>{
return(
<React.Fragment>
<Router history={history}>
<ul className="nav nav-tabs">
<li className="tab-link">
<Link to="/user/profile" className="nav_tab">Profile</Link>
</li>
<li className="tab-link">
<Link to="/user/history" className="nav_tab">History</Link>
</li>
</ul>
<div className="tabs-content">
<Route
exact
path='/user/'
render={() => <React.Fragment>
<UserProfile/>
</React.Fragment>}
/>
<Route
exact
path='/user/profile'
render={() => <React.Fragment>
<UserProfile/>
</React.Fragment>}
/>
<Route
exact
path='/user/history'
render={() =><React.Fragment>
<UserHistory/>
</React.Fragment>}
/>
<Route
exact
path='/user/history/invoice/:order_code'
component={UserInvoice}
/>
</div>
</Router>
</React.Fragment>
)
}
export default UserContainer;<file_sep>/src/components/shopping-cart/Basket.js
import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
export const Basket=props=>{
const getOrders=()=>{
if(!props.hasOrders){
return(
<React.Fragment>
<div id="empty-basket-car">
</div>
</React.Fragment>
)
}
return (
<React.Fragment>
<g id="quantity-container">
<g transform="matrix(0.67766,0,0,0.759,-139.309,-25.3393)">
<ellipse cx="855.275" cy="124.857" rx="115.93" ry="101.844"
style={{fill:'rgb(166,26,2)',
stroke:'rgb(166,26,2)',
strokeWidth:'0.86px',strokeLinecap:'round',
strokeMiterlimit:1.5}}/>
</g>
<g transform="matrix(6.72557,0,0,7.39687,-4530.4,-1023.58)">
<text x="732.501px" y="151.716px"
style={{fontFamily:"'ArialMT', 'Arial', sans-serif",fontSize:'12px',
fill:'rgb(235,235,235)'}}
id="text-quantity">{props.totalOrders}</text>
</g>
</g>
</React.Fragment>
)
}
const showProdutcs=()=>{
$('body').toggleClass('modal-opened');
props.setShowOrders();
props.calculateOrders();
}
return ReactDOM.createPortal(
<svg onClick={()=>{showProdutcs()}} width="100%" height="100%"
viewBox="0 0 959 840" version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
xmlSpace="preserve"
style={{fillRule:'evenodd',clipRule:'evenodd',
strokeLinejoin:'round',strokeMiterlimit:1.41421,cursor:'pointer',
width:'85px'}}>
<g id="shopping-cart-table-board" transform="matrix(1.70469,0,0,1.54998,30.9675,29.137)">
<rect x="-18.166" y="-18.798" width="562.296" height="541.398" style={{fill:'none'}}/>
<g transform="matrix(0.586617,0,0,0.64517,-18.1661,-18.7983)">
<path d="M854.408,87.419L35.72,86.107L119.876,750.029L768.611,750.029L854.408,87.419Z"/>
</g>
<g id="shopping-cart" transform="matrix(0.586617,0,0,0.64517,75.7024,88.461)">
<path d="M153,408C124.95,408 102,430.95 102,459C102,487.05 124.95,510 153,510C181.05,510 204,487.05 204,459C204,430.95 181.05,408 153,408ZM0,0L0,51L51,51L142.8,244.8L107.1,306C104.55,313.65 102,323.85 102,331.5C102,359.55 124.95,382.5 153,382.5L459,382.5L459,331.5L163.2,331.5C160.65,331.5 158.1,328.95 158.1,326.4L158.1,323.849L181.05,280.499L369.75,280.499C390.15,280.499 405.45,270.299 413.1,254.999L507.394,92.17C511.466,82.993 519.869,72.57 511.43,61.475C503.69,51.298 499.8,51 484.5,51L107.1,51L84.15,0L0,0ZM408,408C379.95,408 357,430.95 357,459C357,487.05 379.95,510 408,510C436.05,510 459,487.05 459,459C459,430.95 436.05,408 408,408Z"
style={{fill:'rgb(235,235,235)',fillRule:'nonzero',stroke:'rgb(235,235,235)',
strokeWidth:'1px'}}/>
</g>
{getOrders()}
</g>
</svg>,
document.querySelector("#basket-shopping-cart"),
);
}
export default React.memo(Basket)<file_sep>/src/components/user/UserDetails.js
import React from "react";
import {connect} from "react-redux";
const UserDetails=props=>{
const logOut=(e)=>{
e.preventDefault();
window.location.replace("/logout");
}
const getProfile=(e)=>{
e.preventDefault();
window.location.replace('/user/profile/');
}
return(
<React.Fragment>
<div className="container-user-details" style={{margin:'20px 50px'}}>
{props.user.username ? <p>Username: {props.user.username}</p>:''}
{props.user.firstname ? <p>First Name: {props.user.firstname}</p>:''}
{props.user.lastname ? <p>Last Name: {props.user.lastname}</p>:''}
{props.user.email ? <p>Email: {props.user.email}</p>:'' }
<button id="btn-logout" onClick={(e)=>logOut(e)} className="btn btn-danger">
Logout
</button>
<button onClick={(e)=>getProfile(e)} className="btn btn-success">Profile</button>
</div>
</React.Fragment>
)
}
const mapStateToProps=(state)=>{
return{
user:state.user.user
}
}
export default connect(mapStateToProps)(UserDetails);<file_sep>/src/constants/userTypes.js
export const SET_USER='SET_USER';
export const EDIT_USER='EDIT_USER';<file_sep>/src/containers/App.js
import React from 'react';
import $ from 'jquery';
import CartContainer from "./CartContainer";
import UserContainer from "./UserContainer";
import {connect} from 'react-redux';
import {addToCart} from '../actions/cartActions';
class App extends React.Component {
state={
showModal:'showBasket',
product:null,
hasOrders:false,
totalOrders:0
}
setShowUserDetails=()=>{
$('body').removeClass('signup');
this.setState({
showModal:'showUserDetails'
})
}
setShowOrders=()=>{
this.setState({
showModal:'showBasket'
});
this.calculateOrders();
$('.modal').css({'display':'block'});
}
calculateOrders=()=>{
var totalQuantity=0;
try {
this.props.orders.orders.forEach(function(element) {
totalQuantity+=element.quantity;
});
}
catch (error) {
console.log(error);
}
finally{
if(totalQuantity<10){
this.setState({
totalOrders:'0'+totalQuantity
})
}
else{
this.setState({
totalOrders:totalQuantity
})
}
}
if(totalQuantity>=1){
this.setState({
hasOrders:true
});
}
}
componentDidMount(){
this.calculateOrders();
}
addProductToCart=(product)=>{
setTimeout(() => {
$("#productName").val(product.name);
$("#quantity-cart").val(1);
$("#pricePerUnit").val(product.price);
$("#totalPrice").val(product.price);
$('.modal').css({'display':'block'});
}, 300);
this.setState({
product:product
});
this.calculateOrders();
}
addToCart=(quantity)=>{
const orderObject = Object.assign({quantity: quantity}, this.state.product);
this.props.addToCart(orderObject);
this.calculateOrders();
}
setShowLogin=()=>{
$('body').removeClass('signup');
console.log('setShowLogin');
this.setState({
showModal:'showLogin'
})
}
render() {
return (
<React.Fragment>
<UserContainer/>
<CartContainer
setShowLogin={this.setShowLogin}
setShowUserDetails={this.setShowUserDetails}
setShowOrders={this.setShowOrders}
showModal={this.state.showModal}
hasOrders={this.state.hasOrders}
totalOrders={this.state.totalOrders}
addToCart={this.addToCart}
calculateOrders={this.calculateOrders}
/>
</React.Fragment>
);
}
}
const mapStateToProps=(state)=>{
return{
orders:state.orders
}
}
export default connect(mapStateToProps,{addToCart})(App)<file_sep>/README.md
# React Redux Shopping Cart
React + Redux Thunk + Node-JS + MySQL
This project require another project as BackEnd [Server Nodejs](https://github.com/LeoCR/server-restaurant-client)
## User Interfaces
### View Profile
<img src="screenshots/user_profile.png" alt="Profile"/>
### View Invoices
<img src="screenshots/view_invoices.png" alt="View Invoices"/>
### View Invoice
<img src="screenshots/view_invoice.png" alt="View Invoice"/>
This project was splitted in 2 more differents projects:
<ul>
<li><a href="https://github.com/LeoCR/react-redux-shopping-cart-restaurant" target="_new">Shopping Cart Restaurant</a></li>
<li><a href="https://github.com/LeoCR/react-redux-checkout-restaurant" target="_new">Checkout Restaurant</a></li>
</ul>
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
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.
### `npm test`
Launches the test runner in the interactive watch mode.
### `npm run build`
Builds the app for production to the `build` folder.<file_sep>/src/components/user/UserInvoice.js
import React,{useEffect,useState} from "react";
import {connect} from "react-redux";
import api from "../../apis/api";
import { withRouter } from "react-router";
const UserInvoice=props=>{
const [orderProducts,setOrderProducts]=useState([]);
const fetchOrders=async()=>{
const {order_code}=props.match.params;
await api.get('/api/invoice/show/products/'+order_code+'/'+props.user.username+'/'+props.user.id)
.then((res)=>{
setOrderProducts(res.data)
})
}
useEffect(()=>{
fetchOrders();
},[orderProducts])
const renderProductsOrder=()=>{
var totalPrice=0;
if(orderProducts.length>0){
orderProducts.forEach(product => {
totalPrice+=parseFloat(product.total)
});
return(
<div className="table-responsive">
<table className="table">
<thead className="thead-dark">
<tr>
<th>Product Name</th>
<th>Quantity per Product</th>
<th>Pricer per Quantity</th>
</tr>
</thead>
<tbody>
{
orderProducts.map((order)=>
<tr>
<td>{order.product_name}</td>
<td>{order.product_quantity}</td>
<td>{order.total}</td>
</tr>
)
}
<tr className='total-row'>
<td colSpan="2">
<p style={{color:'#fff'}}>Total :</p>
</td>
<td>
<p style={{color:'#fff'}}>{totalPrice.toFixed(2)}</p>
</td>
</tr>
</tbody>
</table>
</div>
)
}
}
return(
<React.Fragment>
<h1>Invoice</h1>
{(orderProducts.length>0)?renderProductsOrder():<p>You don't have invoices</p>}
</React.Fragment>
)
}
const mapStateToProps=(state)=>{
return{
user:state.user.user
}
}
export default withRouter(connect(mapStateToProps)(UserInvoice));<file_sep>/src/actions/cartActions.js
import { ADD_TO_CART,DELETE_FROM_CART,UPDATE_ITEM_UNITS,SHOW_ORDERS,DELETE_ORDERS} from "../constants/cartTypes";
export const addToCart = (order) => {
return {
type: ADD_TO_CART,
payload: order
};
};
export const deleteFromCart=(id)=> {
return {
type: DELETE_FROM_CART,
payload: id
}
}
export const getOrders = () => {
return {
type: SHOW_ORDERS
};
};
export const deleteOrders = () => {
return {
type: DELETE_ORDERS
};
};
export function updateItemUnits(order) {
return {
type: UPDATE_ITEM_UNITS,
payload:order
}
}<file_sep>/src/store.js
import {createStore,applyMiddleware,compose} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const middleware = [thunk];
const storageState = localStorage.getItem('orders') ? JSON.parse(localStorage.getItem('orders')) : [];
const store = createStore(rootReducer, storageState, composeEnhancers(
applyMiddleware(...middleware)
));
store.subscribe( () => {
localStorage.setItem('orders', JSON.stringify(store.getState()))
});
export default store;<file_sep>/src/components/shopping-cart/CartProducts.js
import React,{useEffect} from "react";
import $ from 'jquery';
import {connect} from 'react-redux';
import {updateItemUnits,deleteFromCart} from '../../actions/cartActions';
export const CartProducts=props=>{
useEffect(()=>{
props.calculateOrders();
},[props])
const deleteOrder=(order,e)=>{
e.preventDefault();
props.deleteFromCart(order.id);
props.calculateOrders();
}
const checkout=(e)=>{
e.preventDefault();
props.checkout();
}
const decrementOrder=(order)=>{
if(order.quantity>1){
order.quantity=order.quantity-1;
$('#quantity-added').val(order.quantity);
}
props.updateItemUnits(order);
props.calculateOrders();
}
const incrementOrder=(order)=>{
order.quantity=order.quantity+1;
$('#quantity-added').val(order.quantity);
props.updateItemUnits(order);
props.calculateOrders();
}
const calculateTotal=()=>{
var orders=props.orders.orders,
totalPrice=0;
orders.forEach(function(element) {
totalPrice+=element.price*element.quantity;
});
return(
<React.Fragment>
<hr></hr>
<h3>Total Price:</h3>
<h5>{totalPrice}$</h5>
</React.Fragment>
)
}
const goToMenu=(e)=>{
if(e){
e.preventDefault();
}
window.location.replace("/#menu");
$('.modal').css({'display':'none'});
$('body').toggleClass('modal-opened');
$('body').removeClass('signup');
}
var orders=props.orders.orders;
if(orders.length===0){
return(
<div className="modal-body">
Your cart is Empty
<button className="btn btn-success" onClick={(e)=>goToMenu(e)}>Go to Menu</button>
</div>
)
}
return(
<div id="show-orders" className="modal-body">
<ul style={{padding:'5px 15px',listStyle:'none'}}>
{orders.map(order =>
<li key={order.id}
style={{listStyle:'none',width:'100%',
position:'relative',float:'left'}}>
<h5 style={{maxWidth:'350px',float:'left',
width:'100%'}}>{order.name}</h5>
<button style={{width:'50px' ,float:'left'}}
type="button" className="btn btn-danger"
data-dismiss="modal" aria-label="Close"
onClick={(e)=>deleteOrder(order,e)}>
<span aria-hidden="true">×</span>
</button>
<div style={{width:'225px'}}>
<p style={{width:' 75px',float:'left'}}>Quantity:</p>
<p style={{width:'80px',height:'30px',float:'left', border:'1px solid black',padding:'0'}} id="quantity-added">{order.quantity} </p>
<button type="button" className="btn btn-primary" onClick={()=>decrementOrder(order)} style={{float: 'right'}}>-</button>
<button type="button" className="btn btn-success" onClick={()=>incrementOrder(order)} style={{float: 'right'}}>+</button>
</div>
</li>
)}
</ul>
{calculateTotal()}
<button className="btn btn-primary" onClick={(e)=>checkout(e)}>Checkout</button>
</div>
)
}
const mapStateToProps=(state)=>{
return{
products:state.products,
orders:state.orders
}
}
export default connect(mapStateToProps,{updateItemUnits,deleteFromCart})(React.memo(CartProducts))<file_sep>/src/containers/CartContainer.js
import React from "react";
import Basket from "../components/shopping-cart/Basket";
import Login from "../components/user/Login";
import Modal from "../components/Modal";
const CartContainer=(props)=>{
return(
<React.Fragment>
<Basket
hasOrders={props.hasOrders}
totalOrders={props.totalOrders}
calculateOrders={props.calculateOrders}
setShowOrders={props.setShowOrders}/>
<Login
setShowLogin={props.setShowLogin}
setShowUserDetails={props.setShowUserDetails}
showModal={props.showModal}
/>
<Modal
setShowUserCreated={props.setShowUserCreated}
setShowSignUp={props.setShowSignUp}
setShowLogin={props.setShowLogin}
setShowUserDetails={props.setShowUserDetails}
addToCart={props.addToCart}
calculateOrders={props.calculateOrders}
showModal={props.showModal}
setShowUserDetails={props.setShowUserDetails}
/>
</React.Fragment>
)
}
export default CartContainer; | ff23bc83f866abd6333d65ec1d368bd573803d0d | [
"JavaScript",
"Markdown"
] | 13 | JavaScript | LeoCR/react-redux-users-restaurant | e437875b65530d45899512174b22c25e25332f62 | d1a69b7dd9a9bcbc58154f20feea3b8fec0f3096 |
refs/heads/master | <file_sep>package fr.comvqh.lvinbottle;
import org.bukkit.command.CommandExecutor;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import fr.comvqh.lvinbottle.commands.Commands;
import fr.comvqh.lvinbottle.listeners.BottleXPListener;
public class Main extends JavaPlugin {
public void onEnable()
{
getLogger().info("Level-In-Bottle V1.0 - Enabled");
CommandExecutor commandsExecutor = new Commands();
getCommand("bottlexp").setExecutor(commandsExecutor);
Listener l = new BottleXPListener();
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(l, this);
}
public void onDisable() {
getLogger().info("Level-In-Bottle V1.0 - Disabled");
}
}
| e2d85dc5b2941512d10a0342836b16318d1247f8 | [
"Java"
] | 1 | Java | comvqh/Level-In-Bottle | 7f9c0597835e5544c0ac0c35e6bacf3e8d1fe824 | 4298c616414b6e0488b5919f837bf621c1401d69 |
refs/heads/master | <file_sep>function createEmployeeRecord(empArray){
let employee = {}
employee.firstName = empArray[0]
employee.familyName = empArray[1]
employee.title = empArray[2]
employee.payPerHour = empArray[3]
employee.timeInEvents = []
employee.timeOutEvents = []
return employee
}
function createEmployeeRecords(employeeArrArr){
const newEmployeeRecord = employeeArrArr.map(employeeArr => createEmployeeRecord(employeeArr))
return newEmployeeRecord
}
function createTimeOutEvent(employee, dateStamp){
let [date, hour] = dateStamp.split(" ")
employee.timeOutEvents.push({
type: "TimeOut",
hour: parseInt(hour, 10),
date: date
})
return employee
}
function createTimeInEvent(employee, dateStamp){
let [date, hour] = dateStamp.split(" ")
employee.timeInEvents.push({
type: "TimeIn",
hour: parseInt(hour, 10),
date: date
})
return employee
}
function hoursWorkedOnDate(employee, date){
let clockIn = employee.timeInEvents.find(function(e){
return e.date === date
})
let clockOut = employee.timeOutEvents.find(function(e){
return e.date === date
})
return (clockOut.hour - clockIn.hour) / 100
}
function wagesEarnedOnDate(employee, date){
let wagesEarned = hoursWorkedOnDate(employee, date) * employee.payPerHour
return parseFloat(wagesEarned.toString())
}
function allWagesFor(employee){
let datesWorked = employee.timeInEvents.map(function(e){
return e.date
})
let payment = datesWorked.reduce(function(total, d){
return total + wagesEarnedOnDate(employee, d)
}, 0)
return payment
}
function findEmployeeByFirstName(employeeArray, firstName){
return employeeArray.find(function(employee){
return employee.firstName === firstName
})
}
function calculatePayroll(empRecordArray){
return empRecordArray.reduce(function(total, emp){
return total + allWagesFor(emp)
}, 0)
} | 43b8e5d6cfe0d0343f2b8bdb69dce667096a8278 | [
"JavaScript"
] | 1 | JavaScript | christopherleja/js-advanced-functions-introduction-to-context-lab-nyc04-seng-ft-021720 | f44841dd29cad38f5748cbfec8d377e0064a8aed | 3942181158eef5909eb0de5383d17da5c4f45824 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbaloneGameForm
{
class Board
{
public static int CENTER_ROW_INDEX = 4;
public static int COLUMNS = 17;
public static int ROWS = 9;
Player player1, player2;
public Board()
{
player1 = new Player(1);
player2 = new Player(2);
}
internal void Paint(Graphics graphics)
{
player1.Paint(graphics);
player2.Paint(graphics);
}
internal void Click(Point location)
{
int row = (location.Y - 40) / (Piece.PIECESIZE + 4);
int col = (location.X - 47) / (Piece.PIECESIZE * 2 / 3);
Piece piece1 = player1.GetPiece(row, col);
Piece piece2 = player2.GetPiece(row, col);
}
}
}
| c884af06add93ca085f98d4df1762e8c22f24f1c | [
"C#"
] | 1 | C# | honyelbaz/AbaloneGUI | 2236bf88f46b645a0f260d4015b2018d695eea6a | d58658cf119133f018e26ed983d6f0440a027da9 |
refs/heads/master | <file_sep># FriendFinder- A small Web App to match you with compatible friends
## Project Overview
The FriendFinder is a project that involves a few components: client-side interface, an express.js server, and server-side routing. The app is designed to take in user's answers to a survey of 10 questions including their name and an image link. The user's information and answers will be added to a friend's list. The app will return the name and submitted picture of the friend that answered the most similar to the user!
## Building the App
1. We will first need to initialize our Github Repository and create the following files:
1. server.js - this file will contain the main server code
2. home.html and survey.html - these will be in the public folder and will contain the client-side interfacing
3. apiRoutes.js and htmlRoutes.js- these will be the route handling files for handling get and post requests from the client.
4. friends.js - this will act as pseudo database that we can store and retrieve data from
2. Posting data from the client will be handled within the survey.html page within a script tag as opposed to an external js file
## Running the App
You can visit the Heroku deployed version of the app [here](https://whispering-falls-43811.herokuapp.com/)!
## Packages used
1. Express
2. Path
## Skills Used
1. Javascript
2. Node.js
3. HTML
4. Jquery
## Technologies Used
1. Github
2. Heroku
## Licensing
1. MIT
<file_sep>var data = require('../data/friends.js')
module.exports = function apiRoute(app) {
app.get('/api/friends', function (req, res) {
return res.json(data)
})
app.post('/api/friends', function (req, res) {
newData = req.body;
console.log(newData)
data.push(newData);
//This section is to compare the scores of the user's scores to the other scores in the database and determine the index of the friend they are closest to
var isFirst = true;
if(data.length > 1){
isFirst = false;
var diff = newData.scores
var closest = 40;
var index = 0;
for (var i = 0; i < data.length -1; i++) {
var friend = data[i].scores
var close = 0;
for(var j = 0; j < 10; j++){
close += Math.abs(diff[j] - friend[j]);
}
if(close < closest){
closest = close;
index = i;
}
}
console.log(closest, close, index)
console.log(data[index]);
//We will return the information of the friend who turned out to have the closest scores
return res.json(data[index]);
}
})
} | caf8d08cfbd3f5677045743a368bad5417732c65 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | blmlol/FriendFinder | 1af96820781a1cac03abd5fd6d327bddf79a9d5a | efcc331148a9020774433ae3562378051d9b5aa9 |
refs/heads/master | <file_sep>$(document).ready(function() {
// REMOVE LINK FROM TOP MENU ITEM
$('.sidebarNavItem .menu-item > a').first().removeAttr('href');
// SIDEBAR NAV MENU
var nav_item = $('.sidebarNavItem li');
$(nav_item).mouseover(function() {
$('ul:first()', this).addClass('visible');
}).mouseout(function() {
$('ul:first()', this).removeClass('visible');
});
// SIDEBAR NAV MENU END
});
| 34fe0f1dcc9c83429b6d931514473e43f7d1b8c3 | [
"JavaScript"
] | 1 | JavaScript | mru24/Navbars | 6aaa3dd859201d8f86fde75f81944b656784abc4 | 073955da713dffbf7f738caaea56481bae4aa89e |
refs/heads/master | <file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using stringCalcKata;
using System;
namespace stringCalcKata.Tests
{
[TestClass]
public class AddStringCalcTest
{
[TestMethod]
public void add_getsEmptyString_returnsZero()
{
//arrange
string input = "";
StringCalc stringCalcTest = new StringCalc();
//act
var result = stringCalcTest.Add(input);
//assert
Assert.AreEqual(0, result);
}
[TestMethod]
public void add_getsEmptyString_returnsOneInt()
{
//arrange
string input = "69";
StringCalc stringCalcTest = new StringCalc();
//act
var result = stringCalcTest.Add(input);
//assert
Assert.AreEqual(69, result);
}
[TestMethod]
public void add_getsEmptyString_returnsSum()
{
//arrange
string input = "69,44";
StringCalc stringCalcTest = new StringCalc();
//act
var result = stringCalcTest.Add(input);
//assert
Assert.AreEqual(113, result);
}
[TestMethod]
public void add_getsIntegers_returnsSum()
{
//arrange
string input = "69,44,77";
StringCalc stringCalcTest = new StringCalc();
//act
var result = stringCalcTest.Add(input);
//assert
Assert.AreEqual(190, result);
}
[TestMethod]
public void add_getsIntegersWithEscapeChar_returnsSum()
{
//arrange
string input = "69\n44,77";
StringCalc stringCalcTest = new StringCalc();
//act
var result = stringCalcTest.Add(input);
//assert
Assert.AreEqual(190, result);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException),"negatives not allowed!")]
public void add_getsNegatives_throwsExeption()
{
//arrange
string input = "-55,-11";
StringCalc stringCalcTest = new StringCalc();
//act
var result = stringCalcTest.Add(input);
//assert
}
[TestMethod]
public void add_getsIntLargerThan1000_returnsSum()
{
//arrange
string input = "1000,25";
StringCalc stringCalcTest = new StringCalc();
//act
var result = stringCalcTest.Add(input);
//assert
Assert.AreEqual(25, result);
}
[TestMethod]
public void add_getsLongSeparator_shouldReturnSum()
{
//arrange
string input = "//[xxx]\n1xxx2xxx3";
StringCalc stringCalcTest = new StringCalc();
//act
var result = stringCalcTest.Add(input);
//assert
Assert.AreEqual(6, result);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace stringCalcKata
{
public class StringCalc
{
public int Add (string input)
{
if (input == "")
{
return 0;
}
else if (input.Contains(",") == false)
{
return int.Parse(input);
}
else
{
string[] splitCharsArray = new string[3] { ",", "\n" , "///()" };
string[] numbersArray = input.Split(splitCharsArray, StringSplitOptions.None);
int sum = 0;
for(int i = 0; i < numbersArray.Length; i++)
{
if(Int16.Parse(numbersArray[i]) < 0)
{
//throw exeption
throw new System.ArgumentException("negatives not allowed!");
}
else
{
if (Int16.Parse(numbersArray[i]) < 1000)
sum += Int16.Parse(numbersArray[i]);
}
}
return sum;
}
}
}
}
| 6fbb1ee7fae009221d3950d459ddc173340bfa24 | [
"C#"
] | 2 | C# | bigMackD/stringCalcKata | 017791faf2505b8e60a1dfff70c9a79d0ac15c50 | bc825d3e1f826af758913d659effb175f360bcf2 |
refs/heads/master | <file_sep>/* Tabla de Simbolos */
struct simbolo { /* Nombre de la variable */
char *name;
char *type;
char *scope;
};
char *compareTypes(char*a,char*b);
char *resultOperations(char *a, char *b, char *op);
char *getTypeOfFunc(char text[]);
char *getTypeOfArray(char text[]);
int getRangeOfArray(char text[]);
//tamano y tabla de simbolos
#define TableHash 9990
struct simbolo tablaSimbolos[TableHash];
/*convierte el id a numero*/
static unsigned idToHash(char *sym);
/* interface al lex */
extern int yylineno; /* numero de lineas definidas en el lex */
void yyerror(char *s, ...);
/* Funciones de Tabla de Simbolos */
void insertTable(char *name, char *type, char *scope);
struct simbolo * search(char* sym);
void actualizaScopes(char *scope);
void printSimbTable();
//Variables para los errores
char Errors[100][100];
int counter;
int ErrorLineNumb[999];
extern int debug;
<file_sep>Jaguar: jaguarSyntaxis.y jaguarLex.l jaguar.c jaguar.h
bison -d jaguarSyntaxis.y
flex -o jaguarLex.lex.c jaguarLex.l
gcc -o $@ jaguarSyntaxis.tab.c jaguarLex.lex.c jaguar.c -ly -ll -lm<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include "jaguar.h"
#include "jaguarSyntaxis.tab.h"
static unsigned idToHash(char *sym) {
unsigned int hash = 0;
unsigned c;
while((c = *sym++)) hash = hash*9 ^ c;
return hash;
}
int yywrap(){
return -1;
}
void yyerror(char *s, ...){
fprintf(stderr, "%d: error ", yylineno);
fprintf(stderr,"%s \n", s);
}
void insertTable(char *name, char *type, char *scope){
struct simbolo *sp = &tablaSimbolos[idToHash(name)%TableHash]; //obtener entrada
int scount = TableHash; /* cuantos lugares hemos "visto" */
while(--scount >= 0) {
if(sp->name && !strcmp(sp->name, name)) {
strcpy(Errors[counter], "Simbolo previamente declarado");
ErrorLineNumb[counter++] = yylineno;
}
if(!sp->name) { /* Crear Entrada */
sp->name = strdup(name);
sp->type = strdup(type);
//sp->scope = strdup(scope);
if(strlen(scope)>0)
sp->scope = strdup(scope);
tablaSimbolos[idToHash(name)%TableHash] = *sp;
return;
}
if(++sp >= tablaSimbolos+TableHash) sp = tablaSimbolos; /* Seguir intentando */
}
strcpy(Errors[counter], "Se paso la capacidad de la tabla");
ErrorLineNumb[counter++] = yylineno;
}
void actualizaScopes(char *scope){
int scount = TableHash;
while(scount >= 0) {
//printf("Entro %s\n", scope);
struct simbolo *sp = &tablaSimbolos[scount-1];
if(sp->name){
if(!sp->scope)
tablaSimbolos[scount-1].scope = scope;
}
scount--;
}
}
struct simbolo * search(char* id){
struct simbolo *sp = &tablaSimbolos[idToHash(id)%TableHash]; //obtener entrada
int scount = TableHash;
while(--scount >= 0) {
if(sp->name && !strcmp(sp->name, id)) {
return sp;
}
if(!sp->name) { /* Entrada Vacia */
struct simbolo * tmp = malloc(sizeof (struct simbolo));
tmp->name = "-1";
return tmp;
}
if(++sp >= tablaSimbolos+TableHash) {sp = tablaSimbolos; /* Seguir intentando */}
}
yyerror("symbol table overflow\n");
abort(); /* tried them all, table is full */
}
char *resultOperations(char *a, char *b, char *op){
/*suma*/
int operador = 0;
if(strcmp(op,"+")==0){ operador =1; }
if(strcmp(op,"-")==0){ operador =2; }
if(strcmp(op,"*")==0){ operador =3; }
if(strcmp(op,"/")==0){ operador =4; }
//printf("A comparar: %s %s %s ",a,op,b);
//printf("\n operador es %d \n", operador);
switch(operador){
case 1:
if( (strcmp(a,"string")==0 && (strcmp(b,"string")==0 || strcmp(b,"int")==0 || strcmp(b,"float")==0) )
|| (strcmp(a,"real")==0 && strcmp(b,"string")==0) || (strcmp(a,"int")==0 && strcmp(b,"string")==0)) {
return "string";
}else{
if( (strcmp(a,"int") == 0)&& (strcmp(b,"int")==0) ) {
return "int";
}else{
if ( (strcmp(a,"float")==0 &&(strcmp(b,"int")==0 || strcmp(b,"float")==0)) || (strcmp(a,"int")==0 && strcmp(b,"float")==0) ){
return "float";
}
else{
if(strcmp(a,"bool")==0 && strcmp(b,"bool")==0){
return "bool";
}
else {
return "error";
}
}
}
}
break;
case 2:
if((strcmp(a,"float")==0 && (strcmp(b,"float")==0 || strcmp(b,"int")==0))
|| (strcmp(a,"int")==0 && strcmp(b,"float")==0)){
return "float";
}
else{
if(strcmp(a,"int")==0 && strcmp(b,"int")==0){
return "int";
}
else{
if(strcmp(a,"bool")==0 && strcmp(b,"bool")==0){
return "bool";
}
else{
return "error";
}
}
}
break;
case 3:
if((strcmp(a,"float")==0 && (strcmp(b,"float")==0 || strcmp(b,"int")==0))
|| (strcmp(a,"int")==0 && strcmp(b,"float")==0)){
return "float";
}
else{
if(strcmp(a,"int")==0&&strcmp(b,"int")==0){
return "int";
}
else{
if((strcmp(a,"string")==0 && strcmp(b,"int")==0 ) || (strcmp(a,"int")==0 &&strcmp(b,"string")==0)){
return "string";
}else{
if(strcmp(a,"bool")==0 && strcmp(b,"bool")==0){
return "bool";
}else{
return "error";
}
}
}
}
break;
case 4:
if((strcmp(a,"float")==0 && (strcmp(b,"float")==0 || strcmp(b,"int")==0))
|| (strcmp(a,"int")==0 && (strcmp(b,"float")==0 || strcmp(b,"int")==0))){
return "float";
}else{
return "error";
}
break;
default:
//printf("Operador no aceptado\n" );
strcpy(Errors[counter], "Operador no reconocido");
ErrorLineNumb[counter++] = yylineno;
break;
}
return "";
}
char *getTypeOfFunc(char text[])
{
char *typeFunc;
char tmp[50];
sprintf(tmp, "%s", text);
typeFunc = strtok(tmp, ">");
typeFunc = strtok(NULL, ">");
return typeFunc;
}
char *getTypeOfArray(char text[])
{
char *typeArray;
char tmp[50];
sprintf(tmp, "%s", text);
typeArray = strtok(tmp, ",");
typeArray = strtok(NULL, ",");
typeArray = strtok(typeArray, ")");
return typeArray;
}
int getRangeOfArray(char text[])
{
char *typeArray;
char tmp[50];
sprintf(tmp, "%s", text);
typeArray = strtok(tmp, ".");
typeArray = strtok(NULL, ".");
typeArray = strtok(typeArray, ",");
int range = atoi(typeArray);
return range;
}
void printSimbTable(){
int indx;
printf("---------- Tabla de Simbolos ------------\n");
for (indx = 0;indx<TableHash; indx++) {
if (tablaSimbolos[indx].name) {
printf("ID: %s | Type: %s | Scope: %s\n",tablaSimbolos[indx].name,tablaSimbolos[indx].type, tablaSimbolos[indx].scope);
}
}
printf("---------- --------------- ------------\n");
}
int yyparse();
int main(void){
return yyparse();
}<file_sep>/* A Bison parser, made by GNU Bison 2.3. */
/* Skeleton interface for Bison's Yacc-like parsers in C
Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
Free Software Foundation, Inc.
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 2, 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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
/* Put the tokens into the symbol table, so that GDB and other debuggers
know about them. */
enum yytokentype {
PROGRAM = 258,
PROGRAMEND = 259,
STRUCT = 260,
IF = 261,
ELSE = 262,
RETURN = 263,
FOR = 264,
AND = 265,
OR = 266,
READ = 267,
WRITE = 268,
ID = 269,
OPERADORRELACIONAL = 270,
CADENA = 271,
TYPE = 272,
MAIN = 273,
INTEGER = 274,
REAL = 275,
BOOLEAN = 276
};
#endif
/* Tokens. */
#define PROGRAM 258
#define PROGRAMEND 259
#define STRUCT 260
#define IF 261
#define ELSE 262
#define RETURN 263
#define FOR 264
#define AND 265
#define OR 266
#define READ 267
#define WRITE 268
#define ID 269
#define OPERADORRELACIONAL 270
#define CADENA 271
#define TYPE 272
#define MAIN 273
#define INTEGER 274
#define REAL 275
#define BOOLEAN 276
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE
#line 12 "jaguarSyntaxis.y"
{
int i;
float f;
char *c;
char car;
int b;
struct simbolo *sim;
}
/* Line 1529 of yacc.c. */
#line 100 "jaguarSyntaxis.tab.h"
YYSTYPE;
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
# define YYSTYPE_IS_TRIVIAL 1
#endif
extern YYSTYPE yylval;
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
char *getTypeOfFunc(char text[])
{
char *typeFunc;
typeFunc = strtok(text, ">");
typeFunc = strtok(NULL, ">");
return typeFunc;
}
char *getTypeOfArray(char text[])
{
char *typeArray;
typeArray = strtok(text, ",");
typeArray = strtok(NULL, ",");
typeArray = strtok(typeArray, ")");
return typeArray;
}
int main(void){
char str1[] = "array(0..2,int)";
char *x = getTypeOfArray(str1);
printf("%s\n", x);
} | 4361ef1b3c9a94218c77655011f5c900a907e87d | [
"C",
"Makefile"
] | 5 | C | MemoBego/JaguarC | ecf8b24ef316893ee91d3b6450832868ee27eca9 | 92fe75adfed50031417a53ba801dfef1bb60f6d1 |
refs/heads/master | <file_sep>import Share from 'tencent-share';
Share.setShareInfo(shareData);
document.querySelector('.btn').addEventListener('click', function(){
Share.show();
})<file_sep># 设置分享信息
该模块集成了微信、QQ、腾讯新闻客户端、腾讯视频客户端的分享API,可以设置分享的标题、描述、图片和链接。
请注意: 当前功能只能在`*.qq.com`域名的网页中使用,其他域名调用当前模块是没有效果的。
使用方式:
```javascript
import Share from 'tencent-share';
// 分享信息
var shareData = {
title: '读腾讯新闻,助力公益事业,让你的时间更有意义',
desc: '上腾讯新闻,捐阅读时长做公益,一起为爱聚力',
img: 'http://mat1.gtimg.com/news/qqnews/qqspring/img/logo.png',
link: window.location.href
};
Share.setShareInfo(shareData);
Share.setShareInWx(shareData, 'friends');
```
`setShareInfo`为总方法,调用该方法后,开发者无需关心当前处于什么环境,模块会自动根据UA设置微信、QQ、腾讯新闻客户端、腾讯视频客户端的分享信息。
如果想在不同的环境里设置的信息,下面的这几个方法可以调用:
* `setShareInWx(shareData, type)` : 设置页面在`微信`中的分享信息,type字段稍后讲解;
* `setShareInQQ(shareData)` : 设置页面在`QQ`中的分享信息;
* `setShareInNews(shareData)` : 设置页面在`新闻客户端`中的分享信息;
* `setShareInVideo(shareData)` : 设置页面在`腾讯视频`中的分享信息;
在设置页面在`微信`中的分享信息的方法里,有个`type`字段,这个type字段能设置在微信中分别分享给好友、朋友圈、QQ和QQ空间的信息。
`setShareInWx(shareData, 'friends')`表示分享给好友时的分享信息,type字段有:
* friends : 分享给好友
* timeline : 分享到朋友圈
* qq : 分享给QQ好友
* qzone : 分享到QQ空间
如果没有分别设置分享信息的需求,直接调用`Share.setShareInfo(shareData);`即可。
在*新闻客户端*内设置分享信息后,还可以调用`show()`方法来主动呼起分享面板:
```javascript
Share.show(); // 该方法只在新闻客户度内有效
```
同时,还可以在 *Android版的新闻客户端* 内,禁止该页面的分享功能:
```javascript
Share.forbidShareInNews();
``` | 3977bf25538ca232ef38e28f8698bfe9f2e9f030 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | lyken/tencent-share | 195960cd0795e69ab27f36995ffbd54193097459 | fd71a1f9d151c93b42c9dd13ae610397055a8a1a |
refs/heads/master | <file_sep>import { Controller, Get, Param, Query } from '@nestjs/common';
import { Project } from '../project.interface';
import { ProjectsService } from './projects.service';
import { DateBoundQuery } from '../date-bound-query.interface';
@Controller('projects')
export class ProjectsController {
constructor(private readonly projectsService: ProjectsService) {}
@Get(':projectId/stats')
async findOneWtihStats(@Param('projectId') projectId: string,
@Query() query: DateBoundQuery): Promise<Project> {
return this.projectsService.stats(projectId, query.startDate, query.endDate);
}
}
<file_sep>import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigService } from './config/config.service';
import { JiraService } from './jira/jira.service';
import { ProjectsController } from './projects/projects.controller';
import { ProjectsService } from './projects/projects.service';
import { ConfigModule } from './config/config.module';
@Module({
imports: [ConfigModule],
controllers: [AppController, ProjectsController],
providers: [AppService, ProjectsService, JiraService, ConfigService],
})
export class AppModule {}
<file_sep>import { Issue } from './issue.interface';
export interface Release {
version: string;
description: string;
leadTimeAsString: string;
issues: Issue[];
}
<file_sep># 4 KPIs Take Two
## Description
The book [Accelerate](https://www.amazon.com/Accelerate-Software-Performing-Technology-Organizations/dp/1942788339) by <NAME> PhD, <NAME> and <NAME> talks about 4 KPIs of high performing teams. These KPIs are:
* Lead time: The time from code commit to production
* Deployment frequency: The number of times deployed to production per day
* Deployment failure rate: The percentage of time a deployment to production results in requiring remediation, whether it's a rollback, fix forward, patch release, etc.
* Mean time to restore: The amount of time it takes a failed deployment or failure in production to be resolved
This project aims to automate the calculation of lead time and deployment frequency using the JIRA Server API. It is highly dependent on the team's ability to manage code deployments using JIRA releases, and to consistently move cards to a 'Done' or a 'Closed' state upon completion. If cards are marked as 'Done' or 'Closed' *after* a release is marked complete, it will not be counted, as that would result in a negative lead time, which is impossible.
Yes, there are many assumptions of the JIRA workflow, but in the absence of instrumenting these in the actual deployment pipeline of each team, this is the next best thing. Ideally we actually track these metrics by tracking code commits into version control and tagging/relating them to production deployments, as that truly measures when value is realized to the end customer.
## Technologies / Main Libraries
* [nestjs](https://nestjs.com/): Used as a lightweight Node.js framework to serve up an API for pulling stats
* [JavaScript JIRA API for node.js](https://github.com/jira-node/node-jira-client): I need a JIRA client to access the API. Unfortunately this library uses basic auth as a V1 implementation and will need to migrate away from that once it's deprecated
* [jest](https://jestjs.io/): JavaScript testing framework
* [TypeScript starter repository](https://github.com/nestjs/typescript-starter): Used as a way to bootstrap my nestjs project
## Installation
```bash
$ npm install
```
## Setup
This project uses [dotenv](https://github.com/motdotla/dotenv#readme) to manage environment configuration. Create these files on your local system and fill in fields as appropriate.
```
# development.env
JIRA_HOST = <wheremyjirais.com>
JIRA_USERNAME = <myuser>
JIRA_USER_PASSWORD = <<PASSWORD>>
# test.env
JIRA_HOST = <wheremyjirais.com>
JIRA_USERNAME = <myuser>
JIRA_USER_PASSWORD = <<PASSWORD>>
# production.env
JIRA_HOST = <wheremyjirais.com>
JIRA_USERNAME = <myuser>
JIRA_USER_PASSWORD = <<PASSWORD>>
```
## Running the app (local)
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
# test it out
$ curl "http://localhost:3000/projects/MYKEY/stats?endDate=2019-12-31&startDate=2019-07-01"
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Running with Docker
```bash
$ docker-compose build
$ docker-compose up
$ curl "http://localhost:3000/projects/MYKEY/stats?endDate=2019-12-31&startDate=2019-07-01"
```
## Development
I find it easiest to have 2 terminal windows open to see the results of your web application, along with tests running continuously to make sure you didn't break anything.
```bash
$ npm run start:dev
$ npm run test:watch
```
## License
This project is MIT licensed.
<file_sep>import { Injectable, Param } from '@nestjs/common';
import { Project } from '../project.interface';
import { JiraService } from '../jira/jira.service';
@Injectable()
export class ProjectsService {
constructor(private readonly jiraService: JiraService) {}
async stats(projectId: string, startDate: string, endDate: string): Promise<Project> {
return {
key: projectId,
releases: await this.jiraService.releases(projectId, startDate, endDate)
}
// return {
// key: 'DLK',
// leadTime: 32,
// deploymentFrequency: 2,
// deploymentFailureRate: 7,
// meanTimeToRestore: 53,
// }
}
}
<file_sep>import { Release } from './release.interface';
export interface Project {
key: string;
releases: Release[];
}
<file_sep>import { Injectable, Logger } from '@nestjs/common';
import JiraApi from 'jira-client';
import { ConfigService } from '../config/config.service';
import { min, average } from 'simple-statistics';
import prettyMilliseconds from 'pretty-ms';
import { Release } from '../release.interface';
@Injectable()
export class JiraService {
constructor(private readonly configService: ConfigService) {}
/**
* Returns the releases for a specific JIRA project between startDate (inclusive) and endDate (exclusive)
* along with metadata about the release, including issues in the release as well as lead time.
*
* @param projectId The JIRA project id
* @param startDate The startDate in yyyy-mm-dd format
* @param endDate The endDate in yyyy-mm-dd format
*/
async releases(projectId: string, startDate: string, endDate: string): Promise<Release[]> {
const jiraClient = new JiraApi({
protocol: 'https',
host: this.configService.get('JIRA_HOST'),
username: this.configService.get('JIRA_USERNAME'),
password: this.configService.get('JIRA_USER_PASSWORD'),
apiVersion: '2',
strictSSL: true
});
// const endDate = '2019-12-31';
// const startDate = '2019-07-01';
// const projectId = 'DLK';
const releases = [];
const versions: JiraApi.JsonResponse = await jiraClient.getVersions(projectId);
const versionsInRange = versions.filter((version: any) => version.released && version.releaseDate < endDate && version.releaseDate >= startDate);
const averageDoneToReleaseLeadTimes: number[] = [];
for (const version of versionsInRange) {
const issuesInVersion = [];
// Release dates in JIRA only have start of day, so assume we release next day
const releaseDate: Date = new Date(new Date(version.releaseDate).getTime() + (1000 * 60 * 60 * 24));
console.log(`\n=== RELEASE ${version.name} on ${releaseDate} ===`);
// console.log(release.name);
const issues = await jiraClient.searchJira(`project = ${projectId} AND fixVersion = '${version.name}'`, { fields: [ 'created', 'summary' ]});
const doneDates: Date[] = [];
for (const issue of issues.issues) {
// console.log(issue);
const endStateDates: Date[] = [];
const histories = (await jiraClient.findIssue(issue.key, "changelog")).changelog.histories;
// In order to see when a JIRA ticket transitioned to 'Done' or 'Closed' state we need to look at the history items in a ticket
histories.forEach((h: any) => {
for (const historyItem of h.items) {
if (historyItem.field === 'status' && (historyItem.toString === 'Done' || historyItem.toString === 'Closed')) {
const temp = new Date(h.created);
// We want to filter out anything that closes after the release date.
// This can happen if we have a fixVersion in a ticket that is done but we forget to move it to a completed state.
// If we don't filter this out it can potentially skew the results as we'll have negative lead times
if (+releaseDate >= +temp) {
endStateDates.push(temp);
}
}
}
});
if (endStateDates.length > 0) {
doneDates.push(new Date(min(endStateDates.map(d => +d))));
}
issuesInVersion.push({
key: issue.key,
url: issue.self,
title: issue.fields.summary
});
}
const doneDifferences = doneDates.map((d: Date) => (+releaseDate - +d)); // The + coerces to a number
if (doneDifferences.length > 0) {
const avgDoneToRelease = average(doneDifferences);
console.log(`Lead time of ${prettyMilliseconds(avgDoneToRelease)}`);
averageDoneToReleaseLeadTimes.push(avgDoneToRelease);
releases.push({
version: version.name,
description: version.description || '',
leadTimeAsString: prettyMilliseconds(average(averageDoneToReleaseLeadTimes)),
issues: issuesInVersion
});
}
}
console.log(`\nAverage done to release lead time is: ${prettyMilliseconds(average(averageDoneToReleaseLeadTimes))}`);
return releases;
}
}
/**
* jiraApi.getVersions("DLK") example
* [{
self: 'https://jira.miohq.com/rest/api/2/version/13024',
id: '13024',
description: 'Roll out feature X',
name: '1.16',
archived: true,
released: true,
releaseDate: '2017-11-23',
userReleaseDate: '23/Nov/17',
projectId: 11410
}]
*/
<file_sep>import { Test, TestingModule } from '@nestjs/testing';
import { JiraService } from './jira.service';
import { ConfigService } from '../config/config.service';
describe('JiraService', () => {
let service: JiraService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ConfigService, JiraService],
}).compile();
service = module.get<JiraService>(JiraService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
| f019532a87dd1e8a47ec4103e23b7443b55b332b | [
"Markdown",
"TypeScript"
] | 8 | TypeScript | adrianchung/4-kpis-take-2 | 42e0b0547eee32715208bae2e55e32a915fd0966 | b06005a9f542b7d865425d6766d10bd8b95f8a90 |
refs/heads/master | <repo_name>szymcio32/flask-aws-esc-terraform<file_sep>/flask_app/config.ini
[app]
secret_key = secret_key
[awssqs]
name = flask_app
[awscognito]
user_pool_name = flask_app
user_pool_client_name = flask_app
username = test
user_password = <PASSWORD>!<file_sep>/README.md
# Deployment of Flask application on Amazon Fargate using Terraform
The project describe how to deploy a Flask application to Amazon Fargate using Terraform.
The application is using AWS Cognito for user authentication.
It is also able to send a message to AWS SQS when visiting specific URL.
The message triggers an AWS lambda function.
The purpose of the project was to:
- learn how to deploy a Flask application to AWS
- familiarize myself with some AWS services and Python boto3 library
- learn about Terraform tool
## Terraform
Terraform files in the project are able to deploy and configure following AWS services:
- VPC - create VPC network
- IAM - create roles and policies
- ECS - deploy Fargate service
- Congito - user authentication
- SQS - create a queue
- CloudWatch - logs monitoring
- S3 - store Lambda function
- Lambda - function will be triggered by new message in SQS
## Setup
- Clone repository
- Create AWS configuration and credential file:
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html
- Change `aws_region` variable in `terraform/0-variables.tf` according to your settings
- Initialize a Terraform working directory
```buildoutcfg
cd terraform
terraform init
```
- Deploy application
```buildoutcfg
terraform apply
```
- Destroy application
```buildoutcfg
terraform destroy
```
**NOTE**
`terraform/0-variables.tf` and `flask_app/config.ini` contains some common settings.
Modification of one file requires the same change to be made to the other file.
## Usage
Open AWS ECS service and grab public IP address of deployed container.
Application is running on port `5008`
### Routes
Main page
```buildoutcfg
/
```
Login page. Credentials for Cognito user are defined in `flask_app/config.ini`
```buildoutcfg
/login
```
Protected page. It can be accessed only by logged in users
```buildoutcfg
/protected
```
Visiting this route will send a message to SQS. Then the message will trigger Lambda function
```buildoutcfg
/queue
```
### Logs
Logs are stored in AWS CloudWatch:
- application logs `/ecs/flask_app`
- Lamba function logs `/aws/lambda/triggered_by_queue`
## Technologies
- Python 3.8.0
- Terraform 0.12.21
- Flask 1.1.1
- boto3 1.12.17
- AWS
- Docker<file_sep>/Dockerfile
FROM python:3.7-alpine
WORKDIR /flask_app
COPY requirements.txt requirements.txt
ADD flask_app /flask_app
RUN pip install -r requirements.txt
ENV FLASK_APP __init__.py
EXPOSE 5008
CMD flask run --host=0.0.0.0 --port=5008<file_sep>/flask_app/settings.py
import configparser
from pathlib import Path
config_path = Path(__file__).parent / 'config.ini'
settings = configparser.ConfigParser()
with open(config_path) as ini_file:
settings.read_file(ini_file)
class AwsSqsConfig:
NAME = settings['awssqs']['name']
URL = ''
class AwsCognitoConfig:
USER_POOL_ID = ''
CLIENT_ID = ''
USER_POOL_NAME = settings['awscognito']['user_pool_name']
USER_POOL_CLIENT_NAME = settings['awscognito']['user_pool_client_name']
USER = {
'name': settings['awscognito']['username'],
'password': settings['awscognito']['user_password']
}
<file_sep>/flask_app/auth.py
from flask import session
from flask_login import UserMixin
from flask_app import login_manager, cognito_client
@login_manager.request_loader
def get_user_from_cognito(request):
try:
response = cognito_client.get_user(
AccessToken=session['AccessToken']
)
username = response['Username']
return User(username)
except Exception:
return None
class User(UserMixin):
def __init__(self, username):
self.username = username
<file_sep>/flask_app/views.py
from botocore.exceptions import ClientError
from flask import request, session
from flask_login import current_user, login_required
from flask_app import app
from flask_app import cognito_client, sqs_client
from flask_app.settings import AwsCognitoConfig, AwsSqsConfig
@app.route('/')
def index():
return 'flask app'
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return f'You are already logged in as a {current_user.username}'
if request.method == 'POST':
try:
response = cognito_client.admin_initiate_auth(
UserPoolId=AwsCognitoConfig.USER_POOL_ID,
ClientId=AwsCognitoConfig.CLIENT_ID,
AuthFlow='ADMIN_USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': request.form['username'],
'PASSWORD': <PASSWORD>['<PASSWORD>']
}
)
except ClientError as exc:
app.logger.error(exc)
return "Invalid credentials"
# add AccessToken from Cognito to flask session
session['AccessToken'] = response['AuthenticationResult']['AccessToken']
return "You have been logged in"
return """
<div>
<h2>Login to your account</h2>
<form method="POST">
<input type="text" name="username" placeholder="username" />
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" />
<button type="submit">Login</button>
</form>
</div>
"""
@app.route("/protected")
@login_required
def page_with_login():
return f"Logged in! Hi, {current_user.username}"
@app.route("/queue")
def send_message_to_queue():
try:
response = sqs_client.send_message(
QueueUrl=AwsSqsConfig.URL,
MessageBody='New message is ready'
)
except ClientError as exc:
app.logger.error(exc)
return 'Could not send a message to SQS'
return f'Message with id {response["MessageId"]} has been successfully sent to SQS'
<file_sep>/terraform/lambdas/triggered_by_queue.py
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
data = json.dumps({
'message_id': event['Records'][0]['messageId'],
'message_body': event['Records'][0]['body']
})
logger.info(data)
return {
'statusCode': 200,
'body': data
}
<file_sep>/flask_app/aws_handlers.py
from flask_app import cognito_client
from flask_app import sqs_client
from flask_app.settings import AwsCognitoConfig
from flask_app.settings import AwsSqsConfig
def set_user_pool_id():
response = cognito_client.list_user_pools(
MaxResults=5
)
AwsCognitoConfig.USER_POOL_ID = [
user_pool['Id']
for user_pool in response['UserPools']
if user_pool['Name'] == AwsCognitoConfig.USER_POOL_NAME
][0]
def set_user_pool_client_id():
response = cognito_client.list_user_pool_clients(
UserPoolId=AwsCognitoConfig.USER_POOL_ID
)
AwsCognitoConfig.CLIENT_ID = [
user_pool_client['ClientId']
for user_pool_client in response['UserPoolClients']
if user_pool_client['ClientName'] == AwsCognitoConfig.USER_POOL_CLIENT_NAME
][0]
def create_user_pool_test_user():
try:
cognito_client.admin_create_user(
UserPoolId=AwsCognitoConfig.USER_POOL_ID,
Username=AwsCognitoConfig.USER['name']
)
cognito_client.admin_set_user_password(
UserPoolId=AwsCognitoConfig.USER_POOL_ID,
Username=AwsCognitoConfig.USER['name'],
Password=<PASSWORD>.USER['password'],
Permanent=True
)
except cognito_client.exceptions.UsernameExistsException:
pass
def set_sqs_url():
response = sqs_client.get_queue_url(
QueueName=AwsSqsConfig.NAME
)
AwsSqsConfig.URL = response['QueueUrl']
<file_sep>/flask_app/__init__.py
import boto3
import logging
from flask import Flask
from flask_login import LoginManager
from flask_app.settings import settings
cognito_client = boto3.client('cognito-idp')
sqs_client = boto3.client('sqs')
login_manager = LoginManager()
app = Flask(__name__)
app.secret_key = settings['app']['secret_key']
app.logger.setLevel(logging.INFO)
login_manager.init_app(app)
import flask_app.views
import flask_app.auth
from flask_app.aws_handlers import set_user_pool_id, set_user_pool_client_id, create_user_pool_test_user, set_sqs_url
@app.before_first_request
def set_initial_variables():
try:
set_user_pool_id()
set_user_pool_client_id()
create_user_pool_test_user()
set_sqs_url()
except Exception as exc:
app.logger.error(exc)
app.logger.error('Unable to set initial AWS configuration')
| 7e05cbd20699967a441d71a88f8d87a5ae890456 | [
"Markdown",
"Python",
"Dockerfile",
"INI"
] | 9 | INI | szymcio32/flask-aws-esc-terraform | 29035ecf19486e671429cd62c59bd71c8a080a72 | 34ad76e29a86eecfbbcfe8daa243cce88a501c01 |
refs/heads/master | <file_sep>package test.model;
import org.fanfan.resp.param.annotation.Document;
import org.fanfan.resp.param.annotation.ResponseField;
/**
* @description: 内部类
* @author: fanfanlordship
* @create: 2021-03-03 23:06
*/
@Document
public class InC {
@ResponseField(name = "开始")
private Integer start;
}
<file_sep>package org.fanfan.resp.param.config;
import org.fanfan.resp.param.model.PublicArg;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @description: 全局默认配置
* @author: fanfanlordship
* @create: 2021-03-03 23:33
*/
public class DefaultConfig {
/**
* 实体字段映射参数字段字典
*/
private final static Map<Class, String> FILEDTYPE_PARAMTYPE = new HashMap<>();
/**
* 公共部分
*/
private final static List<PublicArg> PUBLIC_ARGS = new ArrayList<>();
public static String getTypeFormatStr(Class clazz) {
return FILEDTYPE_PARAMTYPE.getOrDefault(clazz, "Object");
}
public static Map<Class, String> getFiledtypeParamtype() {
return FILEDTYPE_PARAMTYPE;
}
public static List<PublicArg> getPublicArgs() {
return PUBLIC_ARGS;
}
}
<file_sep>package test.model;
import org.fanfan.resp.param.annotation.Document;
import org.fanfan.resp.param.annotation.ResponseField;
/**
* @description:
* @author: fanfanlordship
* @create: 2021-03-03 22:38
*/
@Document
public class Online {
@ResponseField(name = "名称", memo = "接口名称")
private String name;
@ResponseField(name = "详情")
private InC inC;
}
<file_sep>package org.fanfan.resp.param;
import org.fanfan.resp.param.config.DefaultConfig;
import org.fanfan.resp.param.config.DefaultResponseParamConfig;
import org.fanfan.resp.param.model.PublicArg;
import java.util.List;
/**
* @description: 项目启动
* @author: fanfanlordship
* @create: 2021-03-03 23:46
*/
public class RunStart {
public static void load() {
load(new DefaultResponseParamConfig());
}
public static void load(DefaultResponseParamConfig defaultResponseParamConfig) {
defaultResponseParamConfig.filedTypeMappingParamType(DefaultConfig.getFiledtypeParamtype());
defaultResponseParamConfig.appendFiledTypeMappingParamType(DefaultConfig.getFiledtypeParamtype());
List<PublicArg> publicArgs = DefaultConfig.getPublicArgs();
defaultResponseParamConfig.publicArgs(publicArgs);
}
}
| 4a1b34d0a3f34a2a2e421d9d3bf5d81dc78de2b7 | [
"Java"
] | 4 | Java | fanfanlordship/ResponseArgs | 6646b7fb1355baf2caaa50690e4b58881eb25e04 | 58af664b6f2b647752f2bd5cfc78b46f5747fb28 |
refs/heads/master | <file_sep>const defaultResult = 0;
let currentResult = defaultResult;
let logEntries = [];
function getUserInput() {
return parseInt(userInput.value);
}
function writeToLog(operator, pervResult, operationNum, newResult) {
const loogEntry = {
operation: operator,
prevResult: pervResult,
number: operationNum,
result: newResult,
};
logEntries.push(loogEntry);
console.log(logEntries);
}
function createAndWriteLog(operator, resultBeforeCalc, calcNumber) {
const calcDescription = `${resultBeforeCalc} ${operator} ${calcNumber}`;
outputResult(currentResult, calcDescription);
}
function calculateResult(calculationType) {
const enteredNumber = getUserInput();
const initialResult = currentResult;
let mathOperator;
if (calculationType === "ADD") {
currentResult += enteredNumber;
mathOperator = "+";
} else if (calculationType === "ADD") {
currentResult -= enteredNumber;
}
currentResult += enteredNumber;
createAndWriteLog("+", initialResult, enteredNumber);
writeToLog("ADD", initialResult, enteredNumber, currentResult);
}
function add() {
const enteredNumber = getUserInput();
const initialResult = currentResult;
console.log("INPUT: ", enteredNumber);
currentResult += enteredNumber;
createAndWriteLog("+", initialResult, enteredNumber);
writeToLog("ADD", initialResult, enteredNumber, currentResult);
}
function subtract() {
const enteredNumber = getUserInput();
const initialResult = currentResult;
currentResult -= enteredNumber;
createAndWriteLog("-", initialResult, enteredNumber);
writeToLog("SUBTRACT", initialResult, enteredNumber, currentResult);
}
function multiply() {
const enteredNumber = getUserInput();
const initialResult = currentResult;
currentResult *= enteredNumber;
createAndWriteLog("*", initialResult, enteredNumber);
writeToLog("MULTIPLY", initialResult, enteredNumber, currentResult);
}
function divide() {
const enteredNumber = getUserInput();
const initialResult = currentResult;
currentResult /= enteredNumber;
createAndWriteLog("/", initialResult, enteredNumber);
writeToLog("DIVIDE", initialResult, enteredNumber, currentResult);
}
addBtn.addEventListener("click", add);
subtractBtn.addEventListener("click", subtract);
multiplyBtn.addEventListener("click", multiply);
divideBtn.addEventListener("click", divide);
<file_sep>const addMovieBtn = document.getElementById("add-movie-btn");
const searchBtn = document.getElementById("search-btn");
const movies = [];
const clearAllInputs = () => {
const userInputSection = document.getElementById("user-input");
const inputs = userInputSection.querySelectorAll("input");
for (let i = 0; i < inputs.length; i++) {
inputs[i].value = "";
}
};
const renderMovies = (filter = "") => {
const movieListSection = document.getElementById("movie-list");
movieListSection.innerHTML = "";
if (movies.length === 0) {
movieListSection.classList.remove("visible");
return;
} else {
movieListSection.classList.add("visible");
}
movieListSection.innerHTML = "";
const filteredMovies =
filter === ""
? movies
: movies.filter((moviesIndex) => moviesIndex.info.title.includes(filter));
filteredMovies.forEach((moviesX) => {
const movieElement = document.createElement("li");
const moviesKey = Object.keys(moviesX.info);
let text = `${moviesX.info.title} - ${moviesKey[1]}: ${
moviesX.info[moviesKey[1]]
}`;
movieElement.textContent = text;
movieListSection.append(movieElement);
});
};
const addMovieHandler = () => {
const title = document.getElementById("title").value;
const extraName = document.getElementById("extra-name").value;
const extraValue = document.getElementById("extra-value").value;
if (
title.trim() === "" ||
extraValue.trim() === "" ||
extraName.trim() === ""
) {
return;
}
const newMovie = {
info: {
title,
[extraName]: extraValue,
},
id: Math.floor(Math.random()),
};
movies.push(newMovie);
renderMovies();
clearAllInputs();
};
const searchHandler = () => {
const filterTerm = document.getElementById("filter-title").value;
renderMovies(filterTerm);
};
addMovieBtn.addEventListener("click", addMovieHandler);
searchBtn.addEventListener("click", searchHandler);
| 97a803b66bed397f1cbe541d27ca45b0e824b054 | [
"JavaScript"
] | 2 | JavaScript | amahmadnia/javascript | d9eb6cbe21e94ac8c3609178575bb88a0c7761c7 | 6f2c314029b45c590bc077308203bb7ac8f95f43 |
refs/heads/master | <file_sep>package net.icenet.massrenamer.core;
import java.io.File;
/**
* A file that reads names of all similar files in the folder + their extentions separately
* It can add a random length text into every files' name - and add a complex iterable number as well
*/
/*
* Class READER - reads all file names and their extentions into separate ArrayList
* Class EDITOR - gives interface for selecting a type of modification user can make to all file's names
* Class WORKBENCH - adds the modification to filenames
* Class KAMINO - copies the contents of every respected file into a newly-created one with an altered name + add the extention
* and puts new files into a SUBFOLDER with a name generated from user's modification choices
*/
public class EntryPoint {
public static void main (String args []){
FileNameReader Original = new FileNameReader ();
FileNameSplitter OriginalSplit = new FileNameSplitter (Original);
NameOptions newNameProto = new NameOptions ();
FileNameConstructor newFileNames = new FileNameConstructor (Original, OriginalSplit, newNameProto);
// TESTING Block
System.out.println("TESTING original filenames:");
for (String filename: Original.OriginalFilesArray)
System.out.println(filename);
System.out.println("\nTESTINGNEW filenames:");
for (String filename: newFileNames.newFileNamesArray)
System.out.println(filename);
System.out.println("\nTESTING ORIGINAL FILE PATH AND NAME REBUILT: "+Original.dirPath+File.separator+Original.OriginalFilesArray[0]);
////
GrandFileCopier NewFilez = new GrandFileCopier (Original, newFileNames);
System.out.println("New files are cussefully made!\n"
+ " ** **"
+ "***have a good day!***"
+ " ** **");
}
}
<file_sep>package net.icenet.massrenamer.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileContentCopier {
static void Copy (File original, File clone){
InputStream inS = null;
OutputStream ouS = null;
try{
inS = new FileInputStream(original);
ouS = new FileOutputStream(clone);
byte [] fileBuffer = new byte [1048576];
int fileLength;
while ((fileLength = inS.read(fileBuffer))>0){
ouS.write(fileBuffer, 0, fileLength);
}
}
catch (IOException e) {
System.out.println("Ooops! There was a problem reading the files :-(");
}
}
}
<file_sep>package net.icenet.massrenamer.core;
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class FileNameReader {
//body of future OBJECT
String dirPath;
public int quantOfFiles=0;
public int quantOfFilesAndFolders;
String [] OriginalFilesArray;
//object constructor
FileNameReader(){
while(true){// SHOULD ASK FOR FOLDER NAME UNTILL A REAL ONE IS INPUT!
dirPath=takePath();
File dir = new File(dirPath);
if(dir.isDirectory())
System.out.print("*** Directory found OK; ");
try{
quantOfFilesAndFolders=new File(dirPath).listFiles().length;
System.out.println("there are "+quantOfFiles+" files in the specified dir");
break;
}
catch (NullPointerException e0){
System.out.println("0 files in the directory - try a different dir. path!");
}
}
String [] OriginalFilesArrayUnsorted = new String [quantOfFilesAndFolders];
File [] OriginalFiles = new File(dirPath).listFiles();
for (int i=0,j=0;i<quantOfFilesAndFolders;i++)
if (OriginalFiles[i].isFile()){
OriginalFilesArrayUnsorted[j]=OriginalFiles[i].getName();
j++;
quantOfFiles=j;
}
OriginalFilesArray =Arrays.copyOf(OriginalFilesArrayUnsorted, quantOfFiles);
Arrays.sort(OriginalFilesArray);
}
String takePath (){
int ctrl0=0;
String path;
Scanner keyboard = new Scanner(System.in);
do{
System.out.println("Input the desired directory:");
path=keyboard.next();
System.out.println("Verify if input was correct: (1) - YES; (any other num) - NO");
ctrl0=keyboard.nextInt();
}while(ctrl0!=1);
return path;
}
}
<file_sep># File-renamer
A simple program that renames files; usefull for audiobooks with stupid "100500.mp3" files
| 4129f6fdf63e526b54316da984d54e3c933ad4d7 | [
"Markdown",
"Java"
] | 4 | Java | vtolok/File-renamer | 737618e7e97b84509663987913505b7a3fd79f21 | ec993ca5c61e2eeff55844b761b100510c30c140 |
refs/heads/master | <repo_name>mandypand/WeCreative-mongoDB<file_sep>/mongo.js
const mongoDB = require('mongodb')
const mongoClient = mongoDB.MongoClient
const Url = `mongodb+srv://${process.env.DB_USERNAME}:${process.env.DB_URL}:${process.env.DB_PASSWORD}`
async function run() {
try {
const client = new mongoClient(Url)
await client.connect()
const db = client.db('wecreative')
const collection = db.collection('users')
const cursor = collection.find({})
const data = await cursor.toArray()
await collection.update(
{
}
)
client.close
} catch(error) {
console.log(error)
}
}
run()<file_sep>/README.md
# WeCreative-mongoDB
| 26bc4a904c2321976f6df29668db8660360dfccf | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | mandypand/WeCreative-mongoDB | 11cc77e6de9d52b8a883c3da46591fed9dfa5bda | c4330b90a3cf67300835489a759cfcd87fc96b23 |
refs/heads/master | <file_sep>
class HtmlOutputer(object):
def __init__(self):
self.datas = []
def collect_data(self, data):
if data is None:
return
self.datas.append(data)
def output_html(self):
fout = open("output.html", "w", encoding = 'utf-8')
fout.write("<html>")
fout.write("<head>")
fout.write('<link rel="stylesheet" type="text/css" href="my_style.css">')
fout.write("</head>")
fout.write("<body>")
fout.write("<table>")
# fout.write("<th>")
fout.write("<th>{}</th>".format('标题'))
fout.write("<th>{}</th>".format('简介'))
# fout.write("<td>{}</td>".format('简介'))
# fout.write("</th>")
for data in self.datas:
fout.write("<tr>")
# fout.write("<td>{}</td>".format(data['url']))
fout.write("<td>%s</td>" % data['title'])
fout.write("<td>%s</td>" % data['brief'])
fout.write("</tr>")
print("title: {}".format(data['title']))
print("brief: {}".format(data['brief']))
fout.write("</table>")
fout.write("</body>")
fout.write("</html>")
fout.close()
| 494b92d05b8105500fd04facca57a3d73a1a588a | [
"Python"
] | 1 | Python | xfwaaang/baike_spider | 5f0c083e2cda52a1682e5d383ccad14651fbb501 | 68c07492bcea288725764c1fd2fdda26c2b8aa06 |
refs/heads/master | <repo_name>manoelrmj/CPA-III<file_sep>/strings/leString.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main(){
char texto[100];
char padrao[100];
int i;
int j = 0;
int found = 0;
printf("Insira o texto T: ");
scanf("%[^\n]s", texto);
scanf("%*c");
printf("Insira o padrão P: ");
scanf("%[^\n]s", padrao);
for(i=0; i<strlen(texto); i++){
if(texto[i] == padrao[j]){
j++;
}else{
j = 0;
}
if(j == strlen(padrao)){
found = 1;
}
}
if(found)
printf("Padrão encontrado!\n");
else
printf("Padrão não encontrado!\n");
}
<file_sep>/grafos/grafo.c
#include <stdio.h>
void main(){
int i, j, n, origem, destino, peso;
int grafo[10][10];
// Preencher a matriz com -1, valor que representa a ausência de relação entre as arestas
for(i=0; i<10; i++){
for(j=0; j<10; j++){
grafo[i][j] = 0;
}
}
printf("Insira o número de arestas desejadas: ");
scanf("%d", &n);
for(i=0; i<n; i++){
// e.g. 1 5 6 -> Establece uma aresta de peso 6 com origem no vértice 1 e destino no vértice 5
scanf("%d %d %d", &origem, &destino, &peso);
grafo[origem][destino] = peso;
}
// Imprime a matriz
for(i=0; i<10; i++){
printf("|");
for(j=0; j<10; j++){
printf("%3d|", grafo[i][j]);
}
printf("\n");
}
}
<file_sep>/revisão/revisao.c
#include <stdio.h>
#include <stdlib.h>
int produtoEscalar(int *matA, int *matB, int n){
int i;
int result = 0;
for(i = 0; i<n; i++){
result += matA[i]*matB[i];
}
return result;
}
void main(){
int n, i;
printf("Size: ");
scanf("%d", &n);
int *matA = malloc(sizeof(int)*n);
int *matB = malloc(sizeof(int)*n);
printf("Array A: \n");
for(i = 0; i<n; i++){
scanf("%d", &matA[i]);
}
printf("Array B: \n");
for(i = 0; i<n; i++){
scanf("%d", &matB[i]);
}
printf("\nResult: %d\n", produtoEscalar(matA, matB, n));
}
<file_sep>/grafos/stack.h
// Stack elements data type
typedef int SType;
// Define a stack data type
typedef struct stack{
SType* array; // Array containing the stack elements
int capacity; // Stack capacity
int size; // Current stack size
}stack;
// Create an empty stack - O(1)
void make_stack(stack* s);
// Test is stack is empty - O(1)
int empty(stack* s);
// Return the number of elements in the stack - O(1)
int size(stack* s);
// Return the element on the top of the stack - O(1)
SType top(stack* s);
// Insert k on top of the stack s - O(1)
void push(SType k, stack* s);
// Remove the element k on the top of the stack s
// The stack can't be empty
void pop(stack* s);
//Make the stack s be equal to p in O(n+m)
//where n = size(s) and m = size(p)
void copy(stack* s, stack* p);
// Free the memory allocated to the stack in O(n), where n = size
void free_stack(stack* s);<file_sep>/grafos/stack.c
#include <stdlib.h>
#include "stack.h"
void reserve(int m, stack *s){ // Aumenta para 'm' a capacidade da pilha 's'
int i;
if(m > s->capacity){
s->capacity = m;
SType *aux = (SType*) malloc(sizeof(SType) * s->capacity);
for(i=0; i < s->size; i++){ // Copia os elementos presentes na pilha anterior para a pilha auxiliar
aux[i] = s->array[i];
}
free(s->array);
s->array = aux;
}
}
void make_stack(stack* s){
s->size = 0;
s->capacity = 10;
s->array = malloc(sizeof(SType) * s->capacity);
}
int empty(stack* s){
return s->size == 0;
}
int size(stack* s){
return s->size;
}
SType top(stack* s){
return s->array[s->size-1];
}
void push(SType k, stack* s){
if(s->size == s->capacity) // Pilha cheia
reserve(2 * s->capacity, s); // Dobra o tamanho da pilha
s->array[s->size] = k;
s->size++;
}
void pop(stack* s){
s->size--;
}
void copy(stack* s, stack* p){
int i;
reserve(p->capacity, s);
s->size = p->size;
for(i=0; i< p->size; i++){
s->array[i] = p->array[i];
}
}
void free_stack(stack* s){
free(s->array);
s->size = 0;
}<file_sep>/revisão/script.sh
for i in {50..1000..50}
do
time ./a.out $i
done
<file_sep>/grafos/testDataStructure.c
#include <stdio.h>
#include "stack.h"
void print_stack(stack *s){
printf("-> Capacidade: %d\n", s->capacity);
printf("-> Vazia: %d\n", empty(s));
printf("-> Tamanho: %d\n", s->size);
printf("-> Topo: %d\n", top(s));
int i;
//printf("\n");
for(i=s->size-1; i>=0; i--){
printf("%d\n", s->array[i]);
}
printf("--------\n");
}
void main(){
stack s;
make_stack(&s);
push(1, &s);
push(2, &s);
push(3, &s);
push(4, &s);
push(5, &s);
push(6, &s);
push(7, &s);
push(8, &s);
push(9, &s);
push(10, &s);
//print_stack(&s);
push(11, &s);
//print_stack(&s);
pop(&s);
print_stack(&s);
free_stack(&s);
print_stack(&s);
}<file_sep>/revisão/produtoMatriz.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int **produtoMatriz(int **mA, int **mB, int n){
int i, j, k;
int **mR = (int**) calloc(n, sizeof(int*));
for(i=0; i<n; i++)
mR[i] = calloc(n, sizeof(int));
for(i=0; i<n; i++){
for(j=0; j<n; j++){
for(k = 0; k<n; k++){
mR[i][j] += mA[i][k]*mB[k][j];
}
}
}
return mR;
}
int main(int argc, char *argv[]){
int i, j;
int n = atoi(argv[1]);
//printf("Matrix size: ");
//scanf("%d", &n);
int **matA = (int**) malloc(sizeof(int*)*n);
for(i=0; i<n; i++)
matA[i] = malloc(sizeof(int)*n);
int **matB = (int**) malloc(sizeof(int*)*n);
for(i=0; i<n; i++)
matB[i] = malloc(sizeof(int)*n);
int **matR = (int**) malloc(sizeof(int*)*n);
for(i=0; i<n; i++)
matR[i] = malloc(sizeof(int)*n);
srand(time(NULL));
// Gera matriz
for(i=0; i<n; i++){
for(j=0; j<n; j++){
matA[i][j] = 1+rand()%3;
matB[i][j] = 1+rand()%3;
}
}
// Imprime matriz A
/*printf("\nMatriz A: \n");
for(i=0; i<n; i++){
for(j=0; j<n; j++){
printf("%d ", matA[i][j]);
}
printf("\n");
}*/
// Imprime matriz B
/*printf("\nMatriz B: \n");
for(i=0; i<n; i++){
for(j=0; j<n; j++){
printf("%d ", matB[i][j]);
}
printf("\n");
}*/
// Imprime produto das matrizes
matR = produtoMatriz(matA, matB, n);
/*printf("\nMatriz resultante: \n");
for(i=0; i<n; i++){
for(j=0; j<n; j++){
printf("%d ", matR[i][j]);
}
printf("\n");
}*/
}
<file_sep>/README.md
# CPA-III
Programas e exemplos estudados no curso preparatório para AEDS III
| 4100043d9e8da7704d6907bd215ba0669929b30d | [
"Markdown",
"C",
"Shell"
] | 9 | C | manoelrmj/CPA-III | 7e84f0f1581615a3b66d07f5f4719475c9682fe4 | 0570a3916d45373e13d60837bb9965cd699bb637 |
refs/heads/master | <file_sep>## mote-models
Intended to be a simple data modeling library with immutability built-in.
It is inspired by Ruby's ActiveModel, though much fewer features.
### Installation
```
npm i -S mote-models
```
Note: lodash 4.17.x is a peer dependency. So make sure to include it in your application's dependencies.
### API
See the included `User` model for a sample implementation of a model and its attributes.
<file_sep>export default (condition, message = 'invariant failed') => {
const truthy = Boolean(condition);
if (truthy) {
return true;
}
throw new Error(message);
};
<file_sep>import { isFunction, isNumber, isInteger, isString, isBoolean, isDate } from 'lodash/lang';
import { findKey } from 'lodash/object';
import invariant from './util/invariant';
export const TYPE_BOOLEAN = 'boolean';
export const TYPE_INTEGER = 'integer';
export const TYPE_FLOAT = 'float';
export const TYPE_STRING = 'string';
export const TYPE_DATE = 'date';
export const TYPE_ENUM = 'enum';
export const TYPES = {
boolean: TYPE_BOOLEAN,
integer: TYPE_INTEGER,
float: TYPE_FLOAT,
string: TYPE_STRING,
date: TYPE_DATE,
enum: TYPE_ENUM
};
export default class Attribute {
constructor({ name, type, isRequired = false, defaultValue = null, members = null }) {
invariant(isString(name), 'A name is required for all attributes');
invariant(isString(type), 'A type is required for all attributes');
this.name = name;
this.type = TYPES[type.toLowerCase()];
invariant(
isString(this.type),
'A valid type is required for all attributes, see Attribute.TYPES'
);
this.isRequired = isRequired;
this.defaultValue = defaultValue;
if (this.isEnum()) {
if (!members || members.length === 0) {
throw new Error(`Enum attribute ${name} declared without any members`);
}
this.members = members;
}
}
getDefaultValue() {
return isFunction(this.defaultValue) ? this.defaultValue() : this.defaultValue;
}
// converts a value to its internal representation
// (eg. converts a string enum key to its integer value)
prepareValue(rawValue) {
if (rawValue === null || typeof rawValue === 'undefined') {
return rawValue;
}
if (this.type === TYPE_ENUM && !isInteger(rawValue)) {
const intValue = this.members[rawValue.toUpperCase()];
invariant(
typeof intValue !== 'undefined',
`Value ${rawValue} is not a member of the ${this.name} enum`
);
return intValue;
}
// TODO: possibly some other formatting/normalizing for mysql?
// TODO: possibly a custom prepare() function?
return rawValue;
}
// converts an internal value to its external representation
// (eg. converts an integer enum value to its string key)
unprepareValue(value) {
if (value !== null && typeof value !== 'undefined' && this.isEnum()) {
return findKey(this.members, v => v === value);
}
return value;
}
isValid(value) {
if ((this.isRequired && value === null) || typeof value === 'undefined') {
return false;
}
if (value !== null && typeof value !== 'undefined') {
switch (this.type) {
case TYPE_BOOLEAN:
return isBoolean(value);
case TYPE_INTEGER:
return isInteger(value);
case TYPE_FLOAT:
return isNumber(value);
case TYPE_STRING:
return isString(value);
case TYPE_DATE:
return isDate(value);
case TYPE_ENUM:
if (isString(value)) {
return Object.prototype.hasOwnProperty.call(this.members, value);
}
return !!findKey(this.members, v => v === value);
default:
return false;
}
}
return true;
}
static boolean(opts = {}) {
return new this({ ...opts, type: TYPE_BOOLEAN });
}
static integer(opts = {}) {
return new this({ ...opts, type: TYPE_INTEGER });
}
static float(opts = {}) {
return new this({ ...opts, type: TYPE_FLOAT });
}
static string(opts = {}) {
return new this({ ...opts, type: TYPE_STRING });
}
static date(opts = {}) {
return new this({ ...opts, type: TYPE_DATE });
}
static enum(opts = {}) {
return new this({ ...opts, type: TYPE_ENUM });
}
isBoolean() {
return this.type === TYPE_BOOLEAN;
}
isInteger() {
return this.type === TYPE_INTEGER;
}
isFloat() {
return this.type === TYPE_FLOAT;
}
isString() {
return this.type === TYPE_STRING;
}
isDate() {
return this.type === TYPE_DATE;
}
isEnum() {
return this.type === TYPE_ENUM;
}
}
<file_sep>import Attribute, { TYPES } from '../Attribute';
describe('Attribute', () => {
describe('constructor', () => {
it('requires a name and type option', () => {
expect(() => new Attribute({ type: 'string' })).toThrow(/name/i);
expect(() => new Attribute({ name: 'something' })).toThrow(/type/i);
});
it('requires a members option when type is enum', () => {
expect(() => new Attribute({ name: 'status', type: 'enum' })).toThrow(/enum/i);
});
it('converts type to a symbol', () => {
const attribute = new Attribute({ name: 'id', type: 'integer' });
expect(attribute.type).toBe(TYPES.integer);
});
});
describe('type helpers', () => {
const attributeName = 'someAttribute';
describe('#boolean', () => {
it('creates an attribute of type boolean', () => {
const attribute = Attribute.boolean({ name: attributeName, isRequired: true });
expect(attribute.type).toBe(TYPES.boolean);
expect(attribute.name).toBe(attributeName);
expect(attribute.isRequired).toBe(true);
});
});
describe('#integer', () => {
it('creates an attribute of type integer', () => {
const attribute = Attribute.integer({ name: attributeName, isRequired: true });
expect(attribute.type).toBe(TYPES.integer);
expect(attribute.name).toBe(attributeName);
expect(attribute.isRequired).toBe(true);
});
});
describe('#float', () => {
it('creates an attribute of type float', () => {
const attribute = Attribute.float({ name: attributeName, isRequired: true });
expect(attribute.type).toBe(TYPES.float);
expect(attribute.name).toBe(attributeName);
expect(attribute.isRequired).toBe(true);
});
});
describe('#string', () => {
it('creates an attribute of type string', () => {
const attribute = Attribute.string({ name: attributeName, isRequired: true });
expect(attribute.type).toBe(TYPES.string);
expect(attribute.name).toBe(attributeName);
expect(attribute.isRequired).toBe(true);
});
});
describe('#date', () => {
it('creates an attribute of type date', () => {
const attribute = Attribute.date({ name: attributeName, isRequired: true });
expect(attribute.type).toBe(TYPES.date);
expect(attribute.name).toBe(attributeName);
expect(attribute.isRequired).toBe(true);
});
});
describe('#enum', () => {
it('creates an attribute of type enum', () => {
const attribute = Attribute.enum({
name: attributeName,
isRequired: true,
members: { ZERO: 0, ONE: 1 }
});
expect(attribute.type).toBe(TYPES.enum);
expect(attribute.name).toBe(attributeName);
expect(attribute.isRequired).toBe(true);
});
});
});
describe('prepareValue', () => {
let attribute;
describe('with enum attribute', () => {
const members = { ZERO: 0, ONE: 1 };
beforeEach(() => {
attribute = Attribute.enum({ name: 'someAttribute', members });
});
it('converts a string to underlying enum value', () => {
expect(attribute.prepareValue('ONE')).toBe(members.ONE);
expect(attribute.prepareValue('ZERO')).toBe(members.ZERO);
});
it('throws an error if string does not map to enum value', () => {
expect(() => attribute.prepareValue('thirty')).toThrow(/enum/);
});
});
describe('with string attribute', () => {
beforeEach(() => {
attribute = Attribute.string({ name: 'someAttribute' });
});
it('returns the value given unchanged', () => {
const newValue = 'something';
expect(attribute.prepareValue(newValue)).toBe(newValue);
});
});
});
describe('isValid', () => {
let attribute;
describe('when isRequired', () => {
beforeEach(() => {
attribute = Attribute.string({ name: 'something', isRequired: true });
});
it('returns false when the value is null or undefined', () => {
expect(attribute.isValid(null)).toBeFalsy();
expect(attribute.isValid(undefined)).toBeFalsy();
});
it('returns true when the value is specified and correct', () => {
expect(attribute.isValid('yes')).toBeTruthy();
});
});
describe('enum', () => {
let members = { ZERO: 0, ONE: 1 };
beforeEach(() => {
attribute = Attribute.enum({ name: 'something', members });
});
it('returns false when value is not a member of the enum', () => {
expect(attribute.isValid('thirty')).toBeFalsy();
});
it('returns true when value is a member of the enum values', () => {
expect(attribute.isValid(members.ONE)).toBeTruthy();
});
it('returns true when value is a member of the enum keys', () => {
expect(attribute.isValid('ONE')).toBeTruthy();
});
});
describe('boolean', () => {
beforeEach(() => {
attribute = Attribute.boolean({ name: 'something' });
});
it('returns true when value is a boolean', () => {
expect(attribute.isValid(true)).toBeTruthy();
});
it('returns false when value is not a boolean', () => {
expect(attribute.isValid('blah')).toBeFalsy();
});
});
describe('integer', () => {
beforeEach(() => {
attribute = Attribute.integer({ name: 'something' });
});
it('returns true when value is a integer', () => {
expect(attribute.isValid(10)).toBeTruthy();
});
it('returns false when value is not a integer', () => {
expect(attribute.isValid('blah')).toBeFalsy();
});
});
describe('float', () => {
beforeEach(() => {
attribute = Attribute.float({ name: 'something' });
});
it('returns true when value is a float', () => {
expect(attribute.isValid(7.2)).toBeTruthy();
});
it('returns false when value is not a float', () => {
expect(attribute.isValid('blah')).toBeFalsy();
});
});
describe('string', () => {
beforeEach(() => {
attribute = Attribute.string({ name: 'something' });
});
it('returns true when value is a string', () => {
expect(attribute.isValid('some string')).toBeTruthy();
});
it('returns false when value is not a string', () => {
expect(attribute.isValid(123)).toBeFalsy();
});
});
describe('date', () => {
beforeEach(() => {
attribute = Attribute.date({ name: 'something' });
});
it('returns true when value is a date', () => {
expect(attribute.isValid(new Date())).toBeTruthy();
});
it('returns false when value is not a date', () => {
expect(attribute.isValid('blah')).toBeFalsy();
});
});
});
});
<file_sep>import { Record } from 'immutable';
import camelcase from 'camelcase';
import { isFunction } from 'lodash/lang';
import Attribute from './Attribute';
import invariant from './util/invariant';
export const defaultAttributes = [
Attribute.integer({ name: 'id' }), // TODO isRequired only for persisted records
Attribute.date({ name: 'createdAt' }),
Attribute.date({ name: 'updatedAt' })
];
const Model = (attributes, modelName = 'Model') => {
const attributesMap = {};
const recordProps = {};
[...defaultAttributes, ...attributes].forEach(attribute => {
if (isFunction(attribute.defaultValue)) {
recordProps[attribute.name] = attribute.prepareValue(null);
} else {
recordProps[attribute.name] = attribute.prepareValue(attribute.defaultValue);
}
attributesMap[attribute.name] = attribute;
});
const normalizeName = name => camelcase(name);
const getAttribute = name => attributesMap[normalizeName(name)];
const prepareAttributeValue = (attribName, value, defaultIfNull = false) => {
const attribute = getAttribute(attribName);
invariant(!!attribute, `There is no ${attribName} attribute on the ${modelName} model`);
if (
defaultIfNull &&
(value === null || typeof value === 'undefined') &&
isFunction(attribute.defaultValue)
) {
return attribute.prepareValue(attribute.defaultValue());
}
return attribute.prepareValue(value);
};
return class extends Record(recordProps, modelName) {
constructor(props) {
const preparedProps = Object.keys(props).reduce((result, propName) => {
// ignore props that don't match any defined attribute
if (getAttribute(propName)) {
return {
...result,
[normalizeName(propName)]: prepareAttributeValue(propName, props[propName], true)
};
}
return result;
}, {});
// ensure we respect defaultValues for any attribute not specified in constructor
Object.keys(recordProps).forEach(propName => {
if (preparedProps[propName] === null || typeof preparedProps[propName] === 'undefined') {
preparedProps[propName] = prepareAttributeValue(propName, recordProps[propName], true);
}
});
super(preparedProps, modelName);
this.errors = {};
this.valid = true;
}
static attributes = attributesMap;
static isModel(maybeModel) {
return Record.isRecord(maybeModel);
}
static isInstance(maybeModel) {
return Record.isRecord(maybeModel) && Record.getDescriptiveName(maybeModel) === modelName;
}
static fromMysql(row) {
const props = Object.keys(row).reduce(
(attribs, col) => ({
...attribs,
[normalizeName(col)]: row[col]
}),
{}
);
return new this(props);
}
set(attribName, rawValue) {
const normalizedName = normalizeName(attribName);
const preparedValue = prepareAttributeValue(normalizedName, rawValue);
return super.set(normalizedName, preparedValue);
}
setRaw(attribName, rawValue) {
return super.set(normalizeName(attribName), rawValue);
}
get(attribName) {
const attribute = getAttribute(normalizeName(attribName));
invariant(!!attribute, `There is no ${attribName} attribute on the ${modelName} model`);
const rawValue = super.get(attribute.name);
return attribute.unprepareValue(rawValue);
}
// makes no attempt to transform the output that is stored
// (eg. by dereferencing from an enum)
getRaw(attribName) {
return super.get(normalizeName(attribName));
}
/**
* Returns all attributes of the model as a POJO
*
* @param {Boolean} rawValues flag indicates whether to skip preparing values
* @param {Boolean} setOnly flag indicates whether to omit null/undefined
* keys + values from the result.
*/
toObject({ rawValues = false, setOnly = false } = {}) {
return Object.keys(attributesMap).reduce((obj, key) => {
const value = rawValues ? this.getRaw(key) : this.get(key);
if (setOnly) {
if (value !== null && typeof value !== 'undefined') {
return {
...obj,
[key]: value
};
} else {
return obj;
}
}
return {
...obj,
[key]: value
};
}, {});
}
isValid() {
this.valid = true;
this.errors = {};
Object.values(attributesMap).forEach(attribute => {
if (!attribute.isValid(this.get(attribute.name))) {
this.errors[attribute.name] = 'is invalid';
this.valid = false;
}
});
return this.valid;
}
errorMessage() {
return Object.keys(this.errors).reduce(
(message, key) => `${message}. ${this.errors[key]}`,
''
);
}
};
};
export default Model;
| 86ed474582cb812392f921ca515296eec6827745 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | disbelief/mote-models | 574951bc49673951d0bcef3d5570da0649d1f359 | 5a7375d4f9792bd2bdee591dc6b2fb1b8e45cfff |
refs/heads/master | <file_sep>import React, {PropTypes} from 'react'
export default React.createClass({
propTypes: {
appID: PropTypes.string
},
render() {
const appIDSwitcher = this.props.appID ? (
<select>
<option>appID1</option>
<option>appID2</option>
</select>
) : ''
return (
<div id="header">
<h1>React sample project</h1>
{appIDSwitcher}
</div>
)
}
})
| 372563309583631144d6ef5ada30306d13ad3175 | [
"JavaScript"
] | 1 | JavaScript | WeBest/react-sample-project | 3534099214afeb6c13f86eb2c7a32d071db0fb86 | e7268b14cad74030917aab9f964977e52655c098 |
refs/heads/master | <repo_name>alifahfathonah/website-presensi-karyawan<file_sep>/pengajuan.php
<?php
include('koneksi.php');
$kepentingan = $_POST['kepentingan'];
$nip = $_POST['nip'];
$tgl = $_POST['tgl'];
$waktu = $_POST['waktu'];
$absen = $_POST['absen'];
$result["message"] = "";
if ($kepentingan == "") {
$result["message"] = '
<div class="alert alert-success alert-dismissable" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="alert-heading font-size-h4 font-w400">Warning</h3>
<p class="mb-0">Kepentingan harus diisi!</p>
</div>
';
}else{
$qy = $connect->query("INSERT into pengajuan_lembur VALUES (null, '$nip','$kepentingan','$waktu','$tgl','$absen','Tidak')");
$result["message"] = '
<div class="alert alert-success alert-dismissable" role="alert">
<button type="button" class="close" onclick="myFunction()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="alert-heading font-size-h4 font-w400">Success</h3>
<p class="mb-0">Pengajuan lembur terkirim</p>
</div>
';
}
echo json_encode($result);
?>
<file_sep>/data-kehadiran.php
<?php
include("koneksi.php");
include("session.php");
include("format-tgl.php");
$qy_pegawai = mysqli_query($connect, "SELECT * FROM pegawai, jabatan, pengguna WHERE pegawai.nip = '$_SESSION[nip]' AND pegawai.jabatan = jabatan.id_jabatan AND pegawai.nip = pengguna.nip");
$pegawai = mysqli_fetch_array($qy_pegawai);
?>
<div id="page-container" class="sidebar-inverse side-scroll page-header -fixed page-header-inverse main-content-boxed">
<!-- Header -->
<header id="page-header">
<!-- Header Content -->
<div class="content-header">
<!-- Left Section -->
<div class="content-header-section">
</div>
<!-- END Left Section -->
<!-- Middle Section -->
<div class="content-header-section d-none d-lg-block">
<!-- Header Navigation -->
<!--
Desktop Navigation, mobile navigation can be found in #sidebar
If you would like to use the same navigation in both mobiles and desktops, you can use exactly the same markup inside sidebar and header navigation ul lists
If your sidebar menu includes headings, they won't be visible in your header navigation by default
If your sidebar menu includes icons and you would like to hide them, you can add the class 'nav-main-header-no-icons'
-->
<!-- Logo -->
<div class="content-header-item">
<a class="link-effect font-w700 mr-5" href="dashboard-pegawai">
<span class="font-size-xl text-dual-primary-dark">Bank</span><span class="font-size-xl text-danger"> Wakaf</span>
</a>
</div>
<!-- END Logo -->
<!-- END Header Navigation -->
</div>
<!-- END Middle Section -->
<!-- Right Section -->
<div class="content-header-section">
<!-- User Dropdown -->
<div class="btn-group" role="group">
<button type="button" class="btn btn-rounded btn-dual-secondary" id="page-header-user-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?= $pegawai['nama_pegawai'] ?><i class="fa fa-angle-down ml-5"></i>
</button>
<div class="dropdown-menu dropdown-menu-right min-width-150" aria-labelledby="page-header-user-dropdown">
<?php if($pegawai['hak_akses'] == 'Admin'){ ?>
<a class="dropdown-item" href="dashboard-admin">
<i class="si si-note mr-5"></i> Page Admin
</a>
<?php } ?>
<a class="dropdown-item" href="data-kehadiran">
<i class="si si-note mr-5"></i> Data Kehadiran
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="keluar">
<i class="si si-logout mr-5"></i> Sign Out
</a>
</div>
</div>
<!-- END User Dropdown -->
</div>
<!-- END Right Section -->
</div>
<!-- END Header Content -->
<!-- Header Search -->
<div id="page-header-search" class="overlay-header">
<div class="content-header content-header-fullrow">
<form action="bd_search.html" method="post">
<div class="input-group">
<span class="input-group-btn">
<!-- Close Search Section -->
<!-- Layout API, functionality initialized in Codebase() -> uiApiLayout() -->
<button type="button" class="btn btn-secondary px-15" data-toggle="layout" data-action="header_search_off">
<i class="fa fa-times"></i>
</button>
<!-- END Close Search Section -->
</span>
<input type="text" class="form-control" placeholder="Search or hit ESC.." id="page-header-search-input" name="page-header-search-input">
<span class="input-group-btn">
<button type="submit" class="btn btn-secondary px-15">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
</div>
</div>
<!-- END Header Search -->
<!-- Header Loader -->
<!-- Please check out the Activity page under Elements category to see examples of showing/hiding it -->
<div id="page-header-loader" class="overlay-header bg-primary">
<div class="content-header content-header-fullrow text-center">
<div class="content-header-item">
<i class="fa fa-sun-o fa-spin text-black"></i>
</div>
</div>
</div>
<!-- END Header Loader -->
</header>
<!-- END Header -->
<!-- Main Container -->
<main id="main-container">
<!-- Dynamic Table Simple -->
<div class="block">
<div class="bg-image bg-image-fixed" style="background-image: url('assets/img/photos/photo13@2x.jpg');">
<div class="bg-primary-dark-op">
<div class="content content-full text-center">
<!-- Avatar -->
<div class="mb-15">
<a class="img-link" href="be_pages_generic_profile.html">
<img class="img-avatar img-avatar96 img-avatar-thumb" src="assets/img/avatars/<?= $pegawai['foto']; ?>" alt="">
</a>
</div>
<!-- END Avatar -->
<!-- Personal -->
<h1 class="h3 text-white font-w700 mb-10"><?= $pegawai['nama_pegawai']; ?></h1>
<h2 class="h5 text-white-op">
<?= $pegawai['nama_jabatan']; ?>
</h2>
<center>
<table class="table table-sm" style="width:80%">
<tr class="text-white-op">
<td style="width:40%">Tempat, Tanggal Lahir</td>
<td><?= $pegawai['tmp_lahir']; ?>, <?= indonesian_date($pegawai['tgl_lahir']); ?></td>
</tr>
<tr class="text-white-op">
<td>Jenis Kelamin</td>
<td><?= $pegawai['jk']; ?></td>
</tr>
<tr class="text-white-op">
<td>Alamat</td>
<td><?= $pegawai['alamat']; ?></td>
</tr>
</table>
</center>
</div>
</div>
</div>
<div class="block-header block-header-default">
<h2 class="block-title" style="text-align:center;">Data Kehadiran</h2>
</div>
<div class="block-content block-content-full" style="width:90%">
<!-- DataTables init on table by adding .js-dataTable-simple class, functionality initialized in js/pages/be_tables_datatables.js -->
<table class="table table-bordered table-striped table-vcenter js-dataTable-simple">
<thead>
<tr>
<th class="text-center"></th>
<th>Tanggal</th>
<th>Absen Pagi</th>
<th>Status Absen Pagi</th>
<th>Absen Sore</th>
<th>Status Absen Sore</th>
<th>Absen Lembur</th>
<th>Jumlah Lembur</th>
</tr>
</thead>
<tbody>
<?php
$qy = mysqli_query($connect, "SELECT * FROM absensi, pegawai WHERE pegawai.nip = absensi.nip AND pegawai.nip = '$_SESSION[nip]' ORDER BY absensi.tgl_absen");
$no = 1;
while ($a = mysqli_fetch_array($qy)) {
?>
<tr>
<td class="text-center"><?= $no; ?></td>
<td class="font-w600"><?= tanggal($a['tgl_absen']); ?></td>
<td class="d-none d-sm-table-cell"><?= $a['absen_pagi']; ?></td>
<td class="d-none d-sm-table-cell"><?= $a['status_pagi']; ?></td>
<td class="d-none d-sm-table-cell"><?= $a['absen_sore']; ?></td>
<td class="d-none d-sm-table-cell"><?= $a['status_sore']; ?></td>
<?php if($a['absen_lembur'] == ''){ ?>
<td class="d-none d-sm-table-cell">Tidak ada jam lembur</td>
<?php }else{ ?>
<td class="d-none d-sm-table-cell"><?= $a['absen_lembur']; ?></td>
<?php } ?>
<?php if($a['absen_lembur'] == ''){ ?>
<td class="d-none d-sm-table-cell">-</td>
<?php }else{ ?>
<td class="d-none d-sm-table-cell"><?= $a['jml_lembur']; ?> Jam</td>
<?php } ?>
</tr>
<?php $no++; } ?>
</tbody>
</table>
</div>
</div>
<!-- END Dynamic Table Simple -->
</main>
<!-- END Main Container -->
<!-- Footer -->
<footer id="page-footer" class="opacity-0">
<div class="content py-20 font-size-xs clearfix">
<div class="float-right">
Crafted with <i class="fa fa-heart text-pulse"></i> by <a class="font-w600" href="http://goo.gl/vNS3I" target="_blank">pixelcave</a>
</div>
<div class="float-left">
<a class="font-w600" href="https://goo.gl/po9Usv" target="_blank">Codebase 1.3</a> © <span class="js-year-copy">2017</span>
</div>
</div>
</footer>
<!-- END Footer -->
</div>
<file_sep>/login-baru.php
<?php date_default_timezone_set("Asia/Jakarta"); ?>
<!doctype html>
<!--[if lte IE 9]> <html lang="en" class="no-focus lt-ie10 lt-ie10-msg"> <![endif]-->
<!--[if gt IE 9]><!--> <html lang="en" class="no-focus"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
<meta name="description" content="Codebase - Bootstrap 4 Admin Template & UI Framework created by pixelcave and published on Themeforest">
<meta name="author" content="pixelcave">
<meta name="robots" content="noindex, nofollow">
<!-- Open Graph Meta -->
<meta property="og:title" content="Codebase - Bootstrap 4 Admin Template & UI Framework">
<meta property="og:site_name" content="Codebase">
<meta property="og:description" content="Codebase - Bootstrap 4 Admin Template & UI Framework created by pixelcave and published on Themeforest">
<meta property="og:type" content="website">
<meta property="og:url" content="">
<meta property="og:image" content="">
<link rel="shortcut icon" href="assets/img/favicons/favicon.png">
<link rel="icon" type="image/png" sizes="192x192" href="assets/img/favicons/favicon-192x192.png">
<link rel="apple-touch-icon" sizes="180x180" href="assets/img/favicons/apple-touch-icon-180x180.png">
<link rel="stylesheet" id="css-main" href="assets/css/codebase.min.css">
<style type="text/css">
#v{
width:100%;
height:100%;
}
#qr-canvas{
display:none;
}
#result{
border: solid #0101;
border-width: 1px 1px 1px 1px;
padding:20px;
width:100%;
}
</style>
<script type="text/javascript" src="llqrcode.js"></script>
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<script type="text/javascript" src="webqr.js"></script>
</head>
<body>
<div id="page-container">
<!-- Main Container -->
<main id="main-container">
<!-- Page Content -->
<div class="bg-body-dark bg-pattern" style="background-image: url('assets/img/various/bg-pattern-inverse.png');">
<div class="row mx-0 justify-content-center">
<div class="hero-static col-lg-6 col-xl-4">
<div class="content content-full overflow-hidden">
<!-- Header -->
<div class="py-30 text-center">
<a class="link-effect font-w700" href="index.html">
<i class="si si-fire"></i>
<span class="font-size-xl text-primary-dark">Bank</span><span class="font-size-xl">Wakaf</span>
</a>
<h1 class="h4 font-w700 mt-30 mb-10">Selamat datang di Presensi Bank Wakaf</h1>
<h2 class="h5 font-w400 text-muted mb-0">Silahkan dekatkan QR Code Anda pada Webcam untuk melakukan Absensi</h2>
</div>
<form class="js-validation-signin" action="be_pages_auth_all.html" method="post">
<div class="block block-themed block-rounded block-shadow">
<div class="block-header bg-gd-dusk">
<h3 class="block-title">Silahkan Presensi</h3>
</div>
<div class="block-content">
<div id="mainbody">
<table class="tsel" border="0">
<tr>
<td><img class="selector" id="webcamimg"/></td>
<td><img class="selector" id="qrimg" onclick="setimg()"></td></tr>
<tr>
<td colspan="2" align="center">
<div id="outdiv"></div>
</td>
</tr>
</table>
<br>
<form class="" action="simpan.php" method="post">
<div class="form-group row">
<div class="col-12">
<label for="login-username">NIP</label>
<div id="result"></div>
</div>
</div>
</div>
</form>
</div>
<center><p id="response"></p></center>
<div class="block-content bg-body-light">
<div class="form-group text-center">
<a class="link-effect text-muted mr-10 mb-5 d-inline-block" href="login">
<i class="fa fa-plus mr-5"></i> Masuk Akun
</a>
</div>
</div>
</div>
</form>
<!-- END Sign In Form -->
</div>
</div>
</div>
</div>
<!-- END Page Content -->
</main>
<!-- END Main Container -->
</div>
<!-- Codebase Core JS -->
<script src="assets/js/core/jquery.min.js"></script>
<script src="assets/js/core/popper.min.js"></script>
<script src="assets/js/core/bootstrap.min.js"></script>
<script src="assets/js/core/jquery.slimscroll.min.js"></script>
<script src="assets/js/core/jquery.scrollLock.min.js"></script>
<script src="assets/js/core/jquery.appear.min.js"></script>
<script src="assets/js/core/jquery.countTo.min.js"></script>
<script src="assets/js/core/js.cookie.min.js"></script>
<script src="assets/js/codebase.js"></script>
<script src="assets/js/pages/op_auth_signin.js"></script>
<canvas id="qr-canvas"></canvas>
<script type="text/javascript">load();</script>
</body>
</html>
<file_sep>/simpan-absen.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="assets/js/plugins/sweetalert2/es6-promise.auto.min.js"></script>
<script src="assets/js/plugins/sweetalert2/sweetalert2.min.js"></script>
<link rel="stylesheet" href="assets/js/plugins/sweetalert2/sweetalert2.min.css">
</head>
<body>
</body>
</html>
<?php
include('koneksi.php');
// include('session.php');
function antiinjection($data){
$filter_sql = stripslashes(strip_tags(htmlspecialchars($data,ENT_QUOTES)));
return $filter_sql;
}
$id = antiinjection($_POST['id']);
$nip = antiinjection($_POST['nip']);
$wkt = antiinjection($_POST['waktu']);
$hour = $wkt;
$tgl = antiinjection($_POST['tgl']);
$j = mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM jam WHERE id_jam = '1'"));
date_default_timezone_set("Asia/Jakarta");
$jam = date("H:i");
$awalpagi = $j['awalabsen_pagi'];
$akhirpagi = $j['akhirabsen_pagi'];
$awalsore = $j['awalabsen_sore'];
$akhirsore = $j['akhirabsen_sore'];
$awallembur = $j['awalabsen_lembur'];
$akhirlembur = $j['akhirabsen_lembur'];
$sel = $hour - $lembur;
$cek = mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM absensi WHERE tgl_absen = '$tgl' AND nip = '$_SESSION[nip]'"));
$id = $cek['id_absensi'];
if (empty($id)) {
echo '<script language="javascript">swal("Absen gagal!", "Mohon jalankan cron terlebih dahulu", "error").then(() => { window.location="masuk"; });</script>';
}else{
if($wkt >= $awalpagi && $wkt <= $akhirpagi){
mysqli_query($connect, "UPDATE absensi SET absen_pagi = '$wkt', status_pagi = 'H' WHERE id_absensi = '$id'");
echo '<script language="javascript">swal("Absen berhasil!", "Data absen pagi tersimpan", "success").then(() => { window.location="masuk"; });</script>';
}else if($wkt >= $awalsore && $wkt <= $akhirsore){
mysqli_query($connect, "UPDATE absensi SET absen_sore = '$wkt', status_sore = 'H' WHERE id_absensi = '$id'");
echo '<script language="javascript">swal("Absen berhasil!", "Data absen sore ", "success").then(() => { window.location="masuk"; });</script>';
}else if($wkt >= $awallembur && $wkt <= $akhirlembur){
mysqli_query($connect, "UPDATE absensi SET absen_lembur = '$wkt', status_lembur = 'H' WHERE id_absensi = '$id'");
echo '<script language="javascript">swal("Absen berhasil!", "Data absen lembur ", "success").then(() => { window.location="masuk"; });</script>';
}else{
echo "<script>alert('Gagal Simpan.');</script>";
echo "<meta http-equiv='refresh' content='0; url=media.php?pages=login'>";
}
}
}
?>
<file_sep>/db/absensi.sql
-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Dec 31, 2018 at 05:28 PM
-- Server version: 10.1.9-MariaDB
-- PHP Version: 5.6.15
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `absensi`
--
-- --------------------------------------------------------
--
-- Table structure for table `absensi`
--
CREATE TABLE `absensi` (
`id_absensi` int(50) NOT NULL,
`nip` varchar(100) NOT NULL,
`tgl_absen` date NOT NULL,
`absen_pagi` varchar(11) DEFAULT NULL,
`absen_sore` varchar(11) DEFAULT NULL,
`absen_lembur` varchar(11) DEFAULT NULL,
`pulang_lembur` varchar(11) DEFAULT NULL,
`jml_lembur` int(11) DEFAULT NULL,
`status_pagi` enum('H','A','I','S') NOT NULL DEFAULT 'A',
`status_sore` enum('H','A','I','S') NOT NULL DEFAULT 'A',
`status_lembur` enum('H','A','I','S') NOT NULL DEFAULT 'A',
`verifikasi_lembur` enum('Ya','Tidak') NOT NULL DEFAULT 'Tidak',
`uang_lembur` decimal(10,0) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `absensi`
--
INSERT INTO `absensi` (`id_absensi`, `nip`, `tgl_absen`, `absen_pagi`, `absen_sore`, `absen_lembur`, `pulang_lembur`, `jml_lembur`, `status_pagi`, `status_sore`, `status_lembur`, `verifikasi_lembur`, `uang_lembur`) VALUES
(91, '15110134', '2018-12-28', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(92, '15110135', '2018-12-28', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(93, '15110136', '2018-12-28', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(94, '15110137', '2018-12-28', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(95, '15110139', '2018-12-28', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(96, '17021991063', '2018-12-28', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(97, '15110134', '2018-12-29', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(98, '15110135', '2018-12-29', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(99, '15110136', '2018-12-29', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(100, '15110137', '2018-12-29', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(101, '15110139', '2018-12-29', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(102, '17021991063', '2018-12-29', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(103, '15110134', '2018-12-30', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(104, '15110135', '2018-12-30', '11:20', '16:17', NULL, '18:01', 1, 'H', 'H', 'A', 'Tidak', '50000'),
(105, '15110136', '2018-12-30', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(106, '15110137', '2018-12-30', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(107, '15110139', '2018-12-30', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(108, '17021991063', '2018-12-30', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(109, '15110134', '2018-12-30', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(110, '15110135', '2018-12-30', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(111, '15110136', '2018-12-30', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(112, '15110137', '2018-12-30', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(113, '15110139', '2018-12-30', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(114, '17021991063', '2018-12-30', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(115, '15110134', '2018-12-31', '07:33', '14:40', '17:06', '21:07', 4, 'H', 'H', 'H', 'Tidak', '200000'),
(116, '15110135', '2018-12-31', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(117, '15110136', '2018-12-31', '07:53', NULL, NULL, NULL, NULL, 'H', 'A', 'A', 'Tidak', '0'),
(118, '15110137', '2018-12-31', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(119, '15110139', '2018-12-31', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(120, '17021991063', '2018-12-31', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(121, '15110134', '2018-12-31', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(122, '15110135', '2018-12-31', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(123, '15110136', '2018-12-31', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(124, '15110137', '2018-12-31', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(125, '15110139', '2018-12-31', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0'),
(126, '17021991063', '2018-12-31', NULL, NULL, NULL, NULL, NULL, 'A', 'A', 'A', 'Tidak', '0');
-- --------------------------------------------------------
--
-- Table structure for table `jabatan`
--
CREATE TABLE `jabatan` (
`id_jabatan` varchar(11) NOT NULL,
`nama_jabatan` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `jabatan`
--
INSERT INTO `jabatan` (`id_jabatan`, `nama_jabatan`) VALUES
('', ''),
('BW0001', 'Manager'),
('BW0002', 'Supervisor'),
('BW0003', 'Admin'),
('BW0004', 'Teller'),
('BW0005', 'Acount Officer'),
('BW0006', 'Karyawan');
-- --------------------------------------------------------
--
-- Table structure for table `jam`
--
CREATE TABLE `jam` (
`id_jam` int(11) NOT NULL,
`awalabsen_pagi` varchar(11) NOT NULL,
`awalabsen_sore` varchar(11) NOT NULL,
`akhirabsen_pagi` varchar(11) NOT NULL,
`akhirabsen_sore` varchar(11) NOT NULL,
`awalabsen_lembur` varchar(11) NOT NULL,
`akhirabsen_lembur` varchar(11) NOT NULL,
`batasjam_lembur` varchar(11) NOT NULL,
`uang_lembur` decimal(10,0) NOT NULL,
`uang_makan` decimal(10,0) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `jam`
--
INSERT INTO `jam` (`id_jam`, `awalabsen_pagi`, `awalabsen_sore`, `akhirabsen_pagi`, `akhirabsen_sore`, `awalabsen_lembur`, `akhirabsen_lembur`, `batasjam_lembur`, `uang_lembur`, `uang_makan`) VALUES
(1, '07:30', '14:00', '08:00', '16:30', '17:00', '18:00', '23:00', '50000', '0');
-- --------------------------------------------------------
--
-- Table structure for table `pegawai`
--
CREATE TABLE `pegawai` (
`nip` varchar(100) NOT NULL,
`nama_pegawai` varchar(100) NOT NULL,
`alamat` varchar(200) NOT NULL,
`jk` enum('Laki-laki','Perempuan') NOT NULL,
`tmp_lahir` varchar(50) NOT NULL,
`tgl_lahir` date NOT NULL,
`foto` varchar(100) NOT NULL,
`jabatan` varchar(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `pegawai`
--
INSERT INTO `pegawai` (`nip`, `nama_pegawai`, `alamat`, `jk`, `tmp_lahir`, `tgl_lahir`, `foto`, `jabatan`) VALUES
('15110134', 'Sefi Khasanah', 'JL. LETJEND POL SOEMARTO, Watumas, Purwanegara,Purwokerto Utara, Banyumas, Jawa Tengah 53126', 'Perempuan', 'Purwokerto', '1995-01-10', 'face2.jpg', 'BW0003'),
('15110135', '<NAME>', 'JL. LETJEND POL SOEMARTO, Watumas, Purwanegara,Purwokerto Utara, Banyumas, Jawa Tengah 53126', 'Laki-laki', 'Purwokerto', '1995-01-10', 'face21.jpg', 'BW0001'),
('15110136', '<NAME>', 'JL. LETJEND POL SOEMARTO, Watumas, Purwanegara,Purwokerto Utara, Banyumas, Jawa Tengah 53126', 'Laki-laki', 'Purwokerto', '1995-01-10', 'face12.jpg', 'BW0004'),
('15110137', 'Fauzan', 'JL. LETJEND POL SOEMARTO, Watumas, Purwanegara,Purwokerto Utara, Banyumas, Jawa Tengah 53126', 'Laki-laki', 'Purwokerto', '1995-01-10', 'foto.jpg', 'BW0003'),
('15110139', 'Nawasena', '<NAME>', 'Laki-laki', 'Amarta', '2018-01-02', 'phone.png', 'BW0004'),
('17021991063', '<NAME>', 'Cilacap, Maos', 'Perempuan', 'Cilacap', '1991-04-03', '', 'BW0006');
-- --------------------------------------------------------
--
-- Table structure for table `pengajuan_lembur`
--
CREATE TABLE `pengajuan_lembur` (
`id_lembur` int(11) NOT NULL,
`nip` varchar(100) NOT NULL,
`kepentingan` varchar(100) NOT NULL,
`waktu` varchar(11) NOT NULL,
`tgl` date NOT NULL,
`id_absensi` int(11) NOT NULL,
`arsip` enum('Ya','Tidak') NOT NULL DEFAULT 'Tidak'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `pengajuan_lembur`
--
INSERT INTO `pengajuan_lembur` (`id_lembur`, `nip`, `kepentingan`, `waktu`, `tgl`, `id_absensi`, `arsip`) VALUES
(2, '15110135', 'mengerjakan laporanmengerjakan laporanmengerjakan laporanmengerjakan laporanmengerjakan laporan', '20:21', '2018-12-24', 7, 'Ya'),
(4, '15110136', 'mengerjakan laporan bareng yovie mengerjakan laporan bareng yoviemengerjakan laporan bareng yovie', '23:31', '2018-12-24', 13, 'Ya'),
(5, '15110137', 'mengerjakan laporan bareng yoviemengerjakan laporan bareng yoviemengerjakan laporan bareng yovie', '23:31', '2018-12-24', 14, 'Ya'),
(6, '15110135', 'klklklkl', '23:45', '2018-12-25', 17, 'Ya'),
(7, '15110135', 'klklklklk', '14:20', '2018-12-26', 22, 'Ya'),
(8, '15110134', 'menyelesaikan deadline minggu depan', '12:56', '2018-12-26', 21, 'Ya'),
(9, '15110135', 'deadline', '08:38', '2018-12-27', 0, 'Tidak');
-- --------------------------------------------------------
--
-- Table structure for table `pengguna`
--
CREATE TABLE `pengguna` (
`id_user` int(100) NOT NULL,
`nip` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`hak_akses` enum('Admin','Pegawai') NOT NULL DEFAULT 'Pegawai',
`status` enum('Baru','Lama') NOT NULL,
`token` varchar(100) NOT NULL,
`tokenExpire` datetime NOT NULL,
`kode_qrcode` varchar(100) NOT NULL,
`device` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `pengguna`
--
INSERT INTO `pengguna` (`id_user`, `nip`, `email`, `password`, `hak_akses`, `status`, `token`, `tokenExpire`, `kode_qrcode`, `device`) VALUES
(2, '<PASSWORD>', '<EMAIL>', '<PASSWORD>', 'Admin', 'Lama', '', '2018-12-23 21:14:47', '<PASSWORD>', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:60.0) Gecko/20100101 Firefox/60.0'),
(3, '15110134', '<EMAIL>', '<PASSWORD>', 'Pegawai', 'Lama', 'xow784nu3q', '2018-12-27 07:56:04', '5<PASSWORD>', 'Mozilla/5.0 (Linux; Android 5.1.1; Lenovo A6020a40) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.99 Mobile Safari/537.36'),
(4, '15110136', '', '9a079c8004162f3e6c38c904b284394a', 'Pegawai', 'Lama', '', '0000-00-00 00:00:00', 'h1f1ne6g7idu9o1r3v2ctas01zljmqwxk4pb5y8', 'Mozilla/5.0 (Linux; Android 5.1.1; Lenovo A6020a40) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71'),
(5, '15110137', '', '9a079c8004162f3e6c38c904b284394a', 'Pegawai', 'Lama', '', '0000-00-00 00:00:00', '71xsqm1i8ha15c60tb1gkj3yupz4don29rwflve', 'Mozilla/5.0 (Linux; Android 5.1.1; Lenovo A6020a40) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71'),
(7, '15110139', '', '9a079c8004162f3e6c38c904b284394a', 'Pegawai', 'Lama', '', '0000-00-00 00:00:00', '', ''),
(8, '17021991063', '', '9a079c8004162f3e6c38c904b284394a', 'Pegawai', 'Lama', '', '0000-00-00 00:00:00', '', '');
-- --------------------------------------------------------
--
-- Table structure for table `recovery_keys`
--
CREATE TABLE `recovery_keys` (
`rid` int(11) NOT NULL,
`userID` int(11) NOT NULL,
`token` varchar(50) NOT NULL,
`valid` tinyint(4) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `absensi`
--
ALTER TABLE `absensi`
ADD PRIMARY KEY (`id_absensi`);
--
-- Indexes for table `jabatan`
--
ALTER TABLE `jabatan`
ADD PRIMARY KEY (`id_jabatan`);
--
-- Indexes for table `jam`
--
ALTER TABLE `jam`
ADD PRIMARY KEY (`id_jam`);
--
-- Indexes for table `pegawai`
--
ALTER TABLE `pegawai`
ADD PRIMARY KEY (`nip`),
ADD KEY `jabatan` (`jabatan`);
--
-- Indexes for table `pengajuan_lembur`
--
ALTER TABLE `pengajuan_lembur`
ADD PRIMARY KEY (`id_lembur`);
--
-- Indexes for table `pengguna`
--
ALTER TABLE `pengguna`
ADD PRIMARY KEY (`id_user`);
--
-- Indexes for table `recovery_keys`
--
ALTER TABLE `recovery_keys`
ADD PRIMARY KEY (`rid`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `absensi`
--
ALTER TABLE `absensi`
MODIFY `id_absensi` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=127;
--
-- AUTO_INCREMENT for table `jam`
--
ALTER TABLE `jam`
MODIFY `id_jam` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `pengajuan_lembur`
--
ALTER TABLE `pengajuan_lembur`
MODIFY `id_lembur` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT for table `pengguna`
--
ALTER TABLE `pengguna`
MODIFY `id_user` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `recovery_keys`
--
ALTER TABLE `recovery_keys`
MODIFY `rid` int(11) NOT NULL AUTO_INCREMENT;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `pegawai`
--
ALTER TABLE `pegawai`
ADD CONSTRAINT `pegawai_ibfk_1` FOREIGN KEY (`jabatan`) REFERENCES `jabatan` (`id_jabatan`) ON DELETE CASCADE ON UPDATE CASCADE;
DELIMITER $$
--
-- Events
--
CREATE DEFINER=`root`@`localhost` EVENT `test_event` ON SCHEDULE EVERY '0 8' DAY_HOUR STARTS '2018-09-30 07:14:33' ON COMPLETION NOT PRESERVE ENABLE DO INSERT INTO `absensi` (`id_absensi`) VALUES ('fsfsfsfsf')$$
DELIMITER ;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/simpan.php
<?php
include('koneksi.php');
date_default_timezone_set("Asia/Jakarta");
$wkt = date("H:i");
$tgl = date("Y-m-d");
$j = mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM jam WHERE id_jam = '1'"));
$awalpagi = $j['awalabsen_pagi'];
$akhirpagi = $j['akhirabsen_pagi'];
$awalsore = $j['awalabsen_sore'];
$akhirsore = $j['akhirabsen_sore'];
$awallembur = $j['awalabsen_lembur'];
$akhirlembur = $j['akhirabsen_lembur'];
$pulanglembur = $j['batasjam_lembur'];
$sel = $pulanglembur - $akhirlembur;
if(isset($_POST['send'])){
$arr= array();
$cek1 = mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM pengguna WHERE kode_qrcode = '$_POST[credential]'"));
$cek = mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM absensi WHERE tgl_absen = '$tgl' AND nip = '$cek1[nip]'"));
$id = $cek['id_absensi'];
if (empty($id)) {
$arr['success'] = false;
}else{
if($wkt >= $awalpagi && $wkt <= $akhirpagi){
mysqli_query($connect, "UPDATE absensi SET absen_pagi = '$wkt', status_pagi = 'H' WHERE id_absensi = '$id'");
$arr['success'] = true;
}elseif($wkt >= $awalsore && $wkt <= $akhirsore){
mysqli_query($connect, "UPDATE absensi SET absen_sore = '$wkt', status_sore = 'H' WHERE id_absensi = '$id'");
$arr['success'] = true;
}elseif($wkt >= $awallembur && $wkt <= $akhirlembur){
mysqli_query($connect, "UPDATE absensi SET absen_lembur = '$wkt', status_lembur = 'H' WHERE id_absensi = '$id'");
$arr['success'] = true;
}elseif($wkt > $akhirlembur && $wkt <= $pulanglembur){
$jam = $wkt-$awallembur;
$uang = $jam*$j['uang_lembur'];
mysqli_query($connect, "UPDATE absensi SET pulang_lembur = '$wkt',jml_lembur = '$jam', uang_lembur = $uang WHERE id_absensi = '$id'");
$arr['success'] = true;
}else{
$arr['success'] = false;
}
}
echo json_encode($arr);
}
?>
<file_sep>/media.php
<!doctype html>
<!--[if lte IE 9]> <html lang="en" class="no-focus lt-ie10 lt-ie10-msg"> <![endif]-->
<!--[if gt IE 9]><!--> <html lang="en" class="no-focus"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
<meta name="description" content="Codebase - Bootstrap 4 Admin Template & UI Framework created by pixelcave and published on Themeforest">
<meta name="author" content="pixelcave">
<meta name="robots" content="noindex, nofollow">
<!-- Open Graph Meta -->
<meta property="og:title" content="Codebase - Bootstrap 4 Admin Template & UI Framework">
<meta property="og:site_name" content="Codebase">
<meta property="og:description" content="Codebase - Bootstrap 4 Admin Template & UI Framework created by pixelcave and published on Themeforest">
<meta property="og:type" content="website">
<meta property="og:url" content="">
<meta property="og:image" content="">
<!-- Icons -->
<!-- The following icons can be replaced with your own, they are used by desktop and mobile browsers -->
<link rel="shortcut icon" href="assets/img/favicons/favicon.png">
<link rel="icon" type="image/png" sizes="192x192" href="assets/img/favicons/favicon-192x192.png">
<link rel="apple-touch-icon" sizes="180x180" href="assets/img/favicons/apple-touch-icon-180x180.png">
<!-- END Icons -->
<!-- Stylesheets -->
<!-- Page JS Plugins CSS -->
<link rel="stylesheet" href="assets/js/plugins/sweetalert2/sweetalert2.min.css">
<link rel="stylesheet" href="assets/js/plugins/datatables/dataTables.bootstrap4.min.css">
<!-- Codebase framework -->
<link rel="stylesheet" id="css-main" href="assets/css/codebase.min.css">
<link rel="stylesheet" href="assets/js/plugins/bootstrap-datepicker/css/bootstrap-datepicker3.min.css">
<link rel="stylesheet" href="assets/js/plugins/bootstrap-datepicker/js/jquery-clockpicker.min.css">
<!-- You can include a specific file from css/themes/ folder to alter the default color theme of the template. eg: -->
<!-- <link rel="stylesheet" id="css-theme" href="assets/css/themes/flat.min.css"> -->
<!-- END Stylesheets -->
</head>
<body>
<?php
session_start();
include("akses-file.php");
?>
<!-- END Page Container -->
<!-- Codebase Core JS -->
<script src="assets/js/core/jquery.min.js"></script>
<script src="assets/js/core/popper.min.js"></script>
<script src="assets/js/core/bootstrap.min.js"></script>
<script src="assets/js/core/jquery.slimscroll.min.js"></script>
<script src="assets/js/core/jquery.scrollLock.min.js"></script>
<script src="assets/js/core/jquery.appear.min.js"></script>
<script src="assets/js/core/jquery.countTo.min.js"></script>
<script src="assets/js/core/js.cookie.min.js"></script>
<script src="assets/js/codebase.js"></script>
<script src="assets/js/plugins/jquery-validation/jquery.validate.min.js"></script>
<script src="assets/js/pages/op_auth_signin.js"></script>
<!-- Page JS Plugins -->
<script src="assets/js/plugins/bootstrap-notify/bootstrap-notify.min.js"></script>
<script src="assets/js/plugins/sweetalert2/es6-promise.auto.min.js"></script>
<script src="assets/js/plugins/sweetalert2/sweetalert2.min.js"></script>
<script src="assets/js/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="assets/js/plugins/datatables/dataTables.bootstrap4.min.js"></script>
<script src="assets/js/pages/be_tables_datatables.js"></script>
<script src="assets/js/plugins/chartjs/Chart.bundle.min.js"></script>
<!-- Page JS Code -->
<script src="assets/js/pages/be_ui_activity.js"></script>
<script>
jQuery(function () {
// Init page helpers (BS Notify Plugin)
Codebase.helpers('notify');
});
</script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#target-content").load("media.php?pages=kelola-pegawai&page=1");
jQuery("#pagination li").live('click', function(e){
e.preventDefault();
jQuery('#target-content').html('loading...');
jQuery("#pagination li").removeClass('active');
jQuery(this).addClass('active');
var pageNum = this.id;
jQuery("#target-content").load("media.php?pages=kelola-pegawai&page=" + pageNum);
});
});
</script>
<script type="text/javascript">
$('#toggle1').click(function () {
//check if checkbox is checked
if ($(this).is(':checked')) {
$('#foto').removeAttr('disabled'); //enable input
} else {
$('#foto').attr('disabled', true); //disable input
}
});
</script>
<!-- Page JS Code -->
<script src="assets/js/pages/be_pages_dashboard.js"></script>
<!-- Page JS Plugins -->
<script src="assets/js/plugins/sparkline/jquery.sparkline.min.js"></script>
<script src="assets/js/plugins/easy-pie-chart/jquery.easypiechart.min.js"></script>
<script src="assets/js/plugins/chartjs/Chart.bundle.min.js"></script>
<!-- Page JS Code -->
<script src="assets/js/pages/be_blocks_widgets_stats.js"></script>
<script>
jQuery(function(){
// Init page helpers (Easy Pie Chart plugin)
Codebase.helpers('easy-pie-chart');
});
</script>
<script src="assets/js/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script>
<script src="assets/js/plugins/bootstrap-datepicker/js/jquery-clockpicker.min.js"></script>
<script src="assets/js/jquery.date-dropdowns.min.js"></script>
<script type="text/javascript">
$('#single-input').clockpicker({
placement: 'bottom',
align: 'right',
autoclose: true,
'default': '20:48'
});
$('#single-input2').clockpicker({
placement: 'bottom',
align: 'right',
autoclose: true,
'default': '20:48'
});
$('#single-input3').clockpicker({
placement: 'top',
align: 'right',
autoclose: true,
'default': '20:48'
});
$('#single-input4').clockpicker({
placement: 'top',
align: 'right',
autoclose: true,
'default': '20:48'
});
$('#single-input5').clockpicker({
placement: 'top',
align: 'right',
autoclose: true,
'default': '20:48'
});
</script>
<script src="assets/js/pages/be_forms_plugins.js"></script>
<script>
jQuery(function(){
// Init page helpers (BS Datepicker + BS Colorpicker + BS Maxlength + Select2 + Masked Input + Range Sliders + Tags Inputs plugins)
Codebase.helpers(['datepicker', 'colorpicker', 'maxlength', 'select2', 'masked-inputs', 'rangeslider', 'tags-inputs']);
});
</script>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('.input-daterange').datepicker({
todayBtn:'linked',
format: "yyyy-mm-dd",
autoclose: true
});
fetch_data('no');
function fetch_data1(is_date_search1, bulan='')
{
var dataTable = $('#order_data1').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"fetch-lembur.php",
type:"POST",
data:{
is_date_search1:is_date_search1, bulan:bulan
}
}
});
}
function fetch_data(is_date_search, start_date='', end_date='')
{
var dataTable = $('#order_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"fetch.php",
type:"POST",
data:{
is_date_search:is_date_search, start_date:start_date, end_date:end_date
}
}
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date !='')
{
$('#order_data').DataTable().destroy();
fetch_data('yes', start_date, end_date);
}
else
{
alert("Both Date is Required");
}
});
});
</script>
</body>
</html>
<file_sep>/pengajuan-lembur.php
<?php
include("koneksi.php");
include("session.php");
include("format-tgl.php");
$qy_pegawai = mysqli_query($connect, "SELECT * FROM pegawai, jabatan, pengguna WHERE pegawai.nip = '$_SESSION[nip]' AND pegawai.jabatan = jabatan.id_jabatan AND pegawai.nip = pengguna.nip");
$pegawai = mysqli_fetch_array($qy_pegawai);
date_default_timezone_set("Asia/Jakarta");
$tgl = date("Y-m-d");
$jam = date("H:i");
$qy = mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM absensi WHERE tgl_absen = '$tgl' AND nip = '$pegawai[nip]'"));
?>
<div id="page-container" class="sidebar-inverse side-scroll page-header -fixed page-header-inverse main-content-boxed">
<!-- Header -->
<header id="page-header">
<!-- Header Content -->
<div class="content-header">
<!-- Left Section -->
<div class="content-header-section">
</div>
<!-- END Left Section -->
<!-- Middle Section -->
<div class="content-header-section d-none d-lg-block">
<!-- Header Navigation -->
<!--
Desktop Navigation, mobile navigation can be found in #sidebar
If you would like to use the same navigation in both mobiles and desktops, you can use exactly the same markup inside sidebar and header navigation ul lists
If your sidebar menu includes headings, they won't be visible in your header navigation by default
If your sidebar menu includes icons and you would like to hide them, you can add the class 'nav-main-header-no-icons'
-->
<!-- Logo -->
<div class="content-header-item">
<a class="link-effect font-w700 mr-5" href="dashboard-pegawai">
<span class="font-size-xl text-dual-primary-dark">Bank</span><span class="font-size-xl text-danger"> Wakaf</span>
</a>
</div>
<!-- END Logo -->
<!-- END Header Navigation -->
</div>
<!-- END Middle Section -->
<!-- Right Section -->
<div class="content-header-section">
<!-- User Dropdown -->
<div class="btn-group" role="group">
<button type="button" class="btn btn-rounded btn-dual-secondary" id="page-header-user-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?= $pegawai['nama_pegawai'] ?><i class="fa fa-angle-down ml-5"></i>
</button>
<div class="dropdown-menu dropdown-menu-right min-width-150" aria-labelledby="page-header-user-dropdown">
<?php if($pegawai['hak_akses'] == 'Admin'){ ?>
<a class="dropdown-item" href="dashboard-admin">
<i class="si si-note mr-5"></i> Page Admin
</a>
<?php } ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="pengajuan-lembur">
<i class="si si-note mr-5"></i> Pengajuan Lembur
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="data-kehadiran">
<i class="si si-note mr-5"></i> Data Kehadiran
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="keluar">
<i class="si si-logout mr-5"></i> Sign Out
</a>
</div>
</div>
<!-- END User Dropdown -->
</div>
<!-- END Right Section -->
</div>
<!-- END Header Content -->
<!-- Header Search -->
<div id="page-header-search" class="overlay-header">
<div class="content-header content-header-fullrow">
<form action="bd_search.html" method="post">
<div class="input-group">
<span class="input-group-btn">
<!-- Close Search Section -->
<!-- Layout API, functionality initialized in Codebase() -> uiApiLayout() -->
<button type="button" class="btn btn-secondary px-15" data-toggle="layout" data-action="header_search_off">
<i class="fa fa-times"></i>
</button>
<!-- END Close Search Section -->
</span>
<input type="text" class="form-control" placeholder="Search or hit ESC.." id="page-header-search-input" name="page-header-search-input">
<span class="input-group-btn">
<button type="submit" class="btn btn-secondary px-15">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
</div>
</div>
<!-- END Header Search -->
<!-- Header Loader -->
<!-- Please check out the Activity page under Elements category to see examples of showing/hiding it -->
<div id="page-header-loader" class="overlay-header bg-primary">
<div class="content-header content-header-fullrow text-center">
<div class="content-header-item">
<i class="fa fa-sun-o fa-spin text-black"></i>
</div>
</div>
</div>
<!-- END Header Loader -->
</header>
<!-- END Header -->
<!-- Main Container -->
<main id="main-container">
<!-- Dynamic Table Simple -->
<div class="block">
<div class="bg-image bg-image-fixed" style="background-image: url('assets/img/photos/photo13@2x.jpg');">
<div class="bg-primary-dark-op">
<div class="content content-full text-center">
<!-- Avatar -->
<div class="mb-15">
<a class="img-link" href="be_pages_generic_profile.html">
<img class="img-avatar img-avatar96 img-avatar-thumb" src="assets/img/avatars/<?= $pegawai['foto']; ?>" alt="">
</a>
</div>
<!-- END Avatar -->
<!-- Personal -->
<h1 class="h3 text-white font-w700 mb-10"><?= $pegawai['nama_pegawai']; ?></h1>
<h2 class="h5 text-white-op">
<?= $pegawai['nama_jabatan']; ?>
</h2>
</div>
</div>
</div>
<div class="block-header block-header-default">
<h2 class="block-title bg-info" style="text-align:center;">Pengajuan Lembur Tanggal : <b><?= indonesian_date(date('d-m-Y')); ?></b></h2>
</div>
<div class="block-content block-content-full" style="width:90%">
<!-- Normal Form -->
<div class="block">
<div class="block-content">
<div class="row justify-content-center">
<div class="col-7">
<div class="form-group">
<label for="example-nf-email">Kepentingan</label>
<div id="pesan"></div>
<input type="hidden" class="form-control" id="example-nf-email" name="nip" value="<?= $pegawai['nip'] ?>">
<input type="hidden" name="tgl" value="<?= $tgl ?>">
<input type="hidden" name="waktu" value="<?= $jam ?>">
<input type="hidden" name="absen" value="<?= $qy['id_absensi'] ?>">
<input type="text" class="form-control" id="kepentingan" name="kepentingan" placeholder="Kepentingan Mel<NAME>">
</div>
<div class="form-group">
<button type="button" onclick="ajukan()" class="btn btn-alt-primary">Ajukan</button>
</div>
</div>
</div>
</div>
</div>
<!-- END Normal Form -->
</div>
</div>
<!-- END Dynamic Table Simple -->
</main>
<!-- END Main Container -->
<!-- Footer -->
<footer id="page-footer" class="opacity-0">
<div class="content py-20 font-size-xs clearfix">
<div class="float-right">
Crafted with <i class="fa fa-heart text-pulse"></i> by <a class="font-w600" href="http://goo.gl/vNS3I" target="_blank">pixelcave</a>
</div>
<div class="float-left">
<a class="font-w600" href="https://goo.gl/po9Usv" target="_blank">Codebase 1.3</a> © <span class="js-year-copy">2017</span>
</div>
</div>
</footer>
<!-- END Footer -->
</div>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script type="text/javascript">
function myFunction() {
location.reload();
}
function ajukan() {
var nip = $("[name='nip']").val();
var tgl = $("[name='tgl']").val();
var waktu = $("[name='waktu']").val();
var kepentingan = $("[name='kepentingan']").val();
var absen = $("[name='absen']").val();
var kep = $("#kepentingan");
if (kep.val() == "") {
kep.css('border', '1px solid red');
}else{
kep.css('border', '1px solid green');
$.ajax({
type : "POST",
data : "nip="+nip+"&tgl="+tgl+"&waktu="+waktu+"&kepentingan="+kepentingan+"&absen="+absen,
url : "pengajuan.php",
success : function(result) {
var resultObj = JSON.parse(result);
$("#pesan").html(resultObj.message);
}
});
}
}
</script>
<file_sep>/kelola-pegawai.php
<?php
define("ROW_PER_PAGE",4);
include("koneksi.php");
include("session.php");
include("format-tgl.php");
$qy_pegawai = mysqli_query($connect, "SELECT * FROM pegawai, jabatan WHERE pegawai.nip = '$_SESSION[nip]' AND pegawai.jabatan = jabatan.id_jabatan");
$pegawai = mysqli_fetch_array($qy_pegawai);
?>
<div id="page-container" class="sidebar-inverse side-scroll page-header-fixed page-header-inverse main-content-boxed">
<!-- Header -->
<header id="page-header">
<!-- Header Content -->
<div class="content-header">
<!-- Left Section -->
<div class="content-header-section">
<!-- Logo -->
<div class="content-header-item">
<a class="link-effect font-w700 mr-5" href="dashboard-admin">
<i class="si si-fire text-primary"></i>
<span class="font-size-xl text-dual-primary-dark">Bank</span><span class="font-size-xl text-danger"> Wakaf</span>
</a>
</div>
<!-- END Logo -->
</div>
<!-- END Left Section -->
<!-- Middle Section -->
<div class="content-header-section d-none d-lg-block">
<!-- Header Navigation -->
<!--
Desktop Navigation, mobile navigation can be found in #sidebar
If you would like to use the same navigation in both mobiles and desktops, you can use exactly the same markup inside sidebar and header navigation ul lists
If your sidebar menu includes headings, they won't be visible in your header navigation by default
If your sidebar menu includes icons and you would like to hide them, you can add the class 'nav-main-header-no-icons'
-->
<ul class="nav-main-header">
<li>
<a href="dashboard-admin"><i class="si si-compass"></i>Dashboard</a>
</li>
<li>
<a href="kelola-jabatan"><i class="si si-wrench"></i>Kelola Jabatan</a>
</li>
<li>
<a class="active" href="kelola-pegawai"><i class="si si-users"></i>Kelola Pegawai</a>
</li>
<li>
<a href="kelola-absensi"><i class="si si-book-open"></i>Kelola Absensi</a>
</li>
<li>
<a href="setting-waktu"><i class="si si-settings"></i>Setting</a>
</li>
</ul>
<!-- END Header Navigation -->
</div>
<!-- END Middle Section -->
<!-- Right Section -->
<div class="content-header-section">
<!-- User Dropdown -->
<div class="btn-group" role="group">
<button type="button" class="btn btn-rounded btn-dual-secondary" id="page-header-user-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?= $pegawai['nama_pegawai'] ?><i class="fa fa-angle-down ml-5"></i>
</button>
<div class="dropdown-menu dropdown-menu-right min-width-150" aria-labelledby="page-header-user-dropdown">
<a class="dropdown-item" href="dashboard-pegawai">
<i class="si si-note mr-5"></i> Absensi
</a>
<a class="dropdown-item" href="profile-admin">
<i class="si si-note mr-5"></i> Profile Admin
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="keluar">
<i class="si si-logout mr-5"></i> Sign Out
</a>
</div>
</div>
<!-- END User Dropdown -->
</div>
<!-- END Right Section -->
</div>
<!-- END Header Content -->
</header>
<!-- END Header -->
<!-- Main Container -->
<main id="main-container">
<!-- Hero -->
<div class="bg-image" style="background-image: url('assets/img/photos/photo26@2x.jpg');">
<div class="bg-black-op-75">
<div class="content content-top content-full text-center">
<div class="py-20">
<h1 class="h2 font-w700 text-white mb-10">Kelola Pegawai</h1>
<h2 class="h4 font-w400 text-white-op mb-0">Halaman Untuk Mengelola Data Pegawai</h2>
</div>
</div>
</div>
</div>
<!-- END Hero -->
<!-- Page Content -->
<div class="content">
<!-- Orders -->
<div class="content-heading">
<div class="dropdown float-right">
<button type="button" class="btn btn-alt-info" data-toggle="modal" data-target="#modal-fadein">
Tambah Pegawai
</button>
</div>
Data Pegawai
</div>
<div class="block block-rounded">
<div class="block-content bg-body-light">
<?php
$search_keyword = '';
if(!empty($_POST['search']['keyword'])) {
$search_keyword = $_POST['search']['keyword'];
}
$sql = 'SELECT * FROM pegawai WHERE nama_pegawai LIKE :keyword OR nip LIKE :keyword ORDER BY nip DESC ';
/* Pagination Code starts */
$per_page_html = '';
$page = 1;
$start=0;
if(!empty($_POST["page"])) {
$page = $_POST["page"];
$start=($page-1) * ROW_PER_PAGE;
}
$limit=" limit " . $start . "," . ROW_PER_PAGE;
$pagination_statement = $pdo_conn->prepare($sql);
$pagination_statement->bindValue(':keyword', '%' . $search_keyword . '%', PDO::PARAM_STR);
$pagination_statement->execute();
$row_count = $pagination_statement->rowCount();
if(!empty($row_count)){
$per_page_html .= "<nav aria-label='Orders navigation'>
<ul class='pagination justify-content-end'>";
$page_count=ceil($row_count/ROW_PER_PAGE);
if($page_count>1) {
for($i=1;$i<=$page_count;$i++){
if($i==$page){
$per_page_html .= '<li class="page-item active">
<input type="submit" name="page" value="' . $i . '" class="btn btn-primary active" />';
$per_page_html .= '</li>';
} else {
$per_page_html .= '<input type="submit" name="page" value="' . $i . '" class="btn btn-default" />';
}
}
}
$per_page_html .= "</ul></nav>";
}
$query = $sql.$limit;
$pdo_statement = $pdo_conn->prepare($query);
$pdo_statement->bindValue(':keyword', '%' . $search_keyword . '%', PDO::PARAM_STR);
$pdo_statement->execute();
$result = $pdo_statement->fetchAll();
?>
<!-- Search -->
<form name='frmSearch' action='' method='post'>
<div class="form-group">
<div class="input-group">
<input type='text' name='search[keyword]' placeholder="Masukan NIP / Nama Pegawai" value="<?php echo $search_keyword; ?>" id='keyword' class="form-control" maxlength='25'>
</div>
</div>
<!-- END Search -->
</div>
<div class="block-content">
<div class="row items-push">
<?php
if(!empty($result)) {
foreach($result as $row) {
?>
<div class="col-md-6 col-xl-3">
<div class="block block-rounded bg-danger text-center">
<div class="block-content block-content-full">
<?php if($row['foto'] == ''){ ?>
<img class="img-avatar" style="width:100px;height:100px;" src="assets/img/avatars/avatar0.jpg" alt="">
<?php }else { ?>
<img class="img-avatar" style="width:100px;height:100px;" src="assets/img/avatars/<?php echo $row['foto']; ?>" alt="">
<?php } ?>
</div>
<div class="block-content block-content-full bg-black-op-5" style="height:310px;">
<div class="font-w600" style="color:#f4f4f4"><?php echo $row['nip']; ?></div><hr>
<div class="font-size-sm" style="color:#f4f4f4"><?php echo $row['nama_pegawai']; ?></div><hr>
<div class="font-size-sm" style="color:#f4f4f4"><?= $row['tmp_lahir']; ?>, <?= indonesian_date($row['tgl_lahir']); ?></div><hr>
<div class="font-size-sm" style="color:#f4f4f4"><?php echo $row['jk']; ?></div><hr>
<div class="font-size-sm" style="color:#f4f4f4"><?php echo $row['alamat']; ?></div><hr>
</div>
<div class="block-content block-content-full">
<a class="btn btn-rounded btn-alt-secondary" href="media.php?pages=edit-pegawai&nip=<?php echo $row['nip']; ?>">
<i class="si si-pencil mr-5"></i>Edit
</a>
<a class="btn btn-rounded btn-alt-primary" href="hapus-pegawai.php?nip=<?php echo $row['nip']; ?>">
<i class="si si-trash mr-5"></i>Hapus
</a>
</div>
</div>
</div>
<?php
}
}
?>
</div>
<?php echo $per_page_html; ?>
</form>
</div>
</div>
<!-- END Orders -->
</div>
<!-- END Page Content -->
</main>
<!-- END Main Container -->
<!-- Footer -->
<footer id="page-footer" class="opacity-0">
<div class="content py-20 font-size-xs clearfix">
<div class="float-right">
Crafted with <i class="fa fa-heart text-pulse"></i> by <a class="font-w600" href="http://goo.gl/vNS3I" target="_blank">pixelcave</a>
</div>
<div class="float-left">
<a class="font-w600" href="https://goo.gl/po9Usv" target="_blank">Codebase 1.3</a> © <span class="js-year-copy">2017</span>
</div>
</div>
</footer>
<!-- END Footer -->
</div>
<!-- END Page Container -->
<!-- Fade In Modal -->
<div class="modal fade" id="modal-fadein" tabindex="-1" role="dialog" aria-labelledby="modal-fadein" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="block block-themed block-transparent mb-0">
<div class="block-header bg-primary-dark">
<h3 class="block-title">Tambah Pegawai</h3>
<div class="block-options">
<button type="button" class="btn-block-option" data-dismiss="modal" aria-label="Close">
<i class="si si-close"></i>
</button>
</div>
</div>
<div class="block-content">
<form action="simpan-pegawai.php" enctype="multipart/form-data" method="post">
<div class="form-group row">
<div class="col-md-9">
<div class="form-material floating">
<input type="text" class="form-control" id="material-text2" name="nip">
<label for="material-text2">NIP</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-9">
<div class="form-material floating">
<input type="text" class="form-control" id="material-text2" name="nama">
<label for="material-text2">Nama Lengkap</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-6">
<div class="form-material floating">
<input type="text" class="form-control" id="material-gridf2" name="tmp_lahir">
<label for="material-gridf2">Tempat Lahir</label>
</div>
</div>
<div class="col-6 row">
<div class="form-material">
<input type="date" class="js-datepicker form-control" name="tgl_lahir" data-week-start="1" data-autoclose="true" data-today-highlight="true" data-date-format="yyyy-mm-dd" placeholder="Masukan Tanggal Lahir">
<label for="example-datepicker6">Tanggal Lahir</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-12">
<label for="example-datepicker6">Jenis Kelamin</label>
</div>
<div class="col-12">
<label class="css-control css-control-primary css-radio mr-10">
<input type="radio" class="css-control-input" name="jk" value="Laki-laki" checked>
<span class="css-control-indicator"></span> Laki - Laki
</label>
<label class="css-control css-control-primary css-radio">
<input type="radio" class="css-control-input" name="jk" value="Perempuan">
<span class="css-control-indicator"></span> Perempuan
</label>
</div>
</div>
<div class="form-group row">
<div class="col-12">
<div class="form-material floating">
<textarea class="form-control" id="material-textarea-small2" name="alamat" rows="3"></textarea>
<label for="material-textarea-small2">Alamat</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-lg-8">
<div class="form-material">
<select class="js-select2 form-control" id="example2-select2" name="jabatan" style="width: 100%;" data-placeholder="Choose one..">
<option>Pilih Jabatan</option><!-- Required for data-placeholder attribute to work with Select2 plugin -->
<?php $qy_jb = mysqli_query($connect, "SELECT * FROM jabatan");
while ($jb = mysqli_fetch_array($qy_jb)) {
?>
<option value="<?= $jb['id_jabatan']; ?>"><?= $jb['nama_jabatan']; ?></option>
<?php } ?>
</select>
<label for="example2-select2">Jabatan</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-lg-8">
<div class="form-material">
<input type="file" accept="image/*" name="foto" class="form-control" />
<label for="example2-select2">Foto</label>
</div>
</div>
</div>
<br>
<div class="form-group row">
<div class="col-12">
<button type="submit" class="btn btn-alt-info">
<i class="si si-check mr-5"></i> Simpan
</button>
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<!-- END Fade In Modal -->
<file_sep>/dashboard-admin.php
<?php
include("koneksi.php");
include("session.php");
include("format-tgl.php");
$sql1 = mysqli_query($connect, "select *, count(jabatan.id_jabatan) as jml_jabatan from jabatan");
$a = mysqli_fetch_array($sql1);
$jml_jabatan = $a['jml_jabatan'];
$sql2 = mysqli_query($connect, "select *, count(pegawai.nip) as jml_pegawai from pegawai");
$b = mysqli_fetch_array($sql2);
$jml_pegawai = $b['jml_pegawai'];
$sql3 = mysqli_query($connect, "select *, count(pegawai.nip) as jml_pegawai_cowo from pegawai where jk = 'Laki-laki'");
$c = mysqli_fetch_array($sql3);
$jml_pegawai_cowo = $c['jml_pegawai_cowo'];
$sql4 = mysqli_query($connect, "select *, count(pegawai.nip) as jml_pegawai_cewe from pegawai where jk = 'Perempuan'");
$d = mysqli_fetch_array($sql4);
$jml_pegawai_cewe = $d['jml_pegawai_cewe'];
$qy_pegawai = mysqli_query($connect, "SELECT * FROM pegawai, jabatan, pengguna WHERE pegawai.nip = '$_SESSION[nip]' AND pegawai.jabatan = jabatan.id_jabatan AND pegawai.nip = pengguna.nip");
$pegawai = mysqli_fetch_array($qy_pegawai);
?>
<div id="page-container" class="sidebar-inverse side-scroll page-header-fixed page-header-inverse main-content-boxed">
<!-- Header -->
<header id="page-header">
<!-- Header Content -->
<div class="content-header">
<!-- Left Section -->
<div class="content-header-section">
</div>
<!-- END Left Section -->
<!-- Middle Section -->
<div class="content-header-section d-none d-lg-block">
<!-- Header Navigation -->
<!--
Desktop Navigation, mobile navigation can be found in #sidebar
If you would like to use the same navigation in both mobiles and desktops, you can use exactly the same markup inside sidebar and header navigation ul lists
If your sidebar menu includes headings, they won't be visible in your header navigation by default
If your sidebar menu includes icons and you would like to hide them, you can add the class 'nav-main-header-no-icons'
-->
<!-- Logo -->
<div class="content-header-item">
<a class="link-effect font-w700 mr-5" href="dashboard-admin">
<span class="font-size-xl text-dual-primary-dark">Bank</span><span class="font-size-xl text-danger"> Wakaf</span>
</a>
</div>
<!-- END Logo -->
<!-- END Header Navigation -->
</div>
<!-- END Middle Section -->
<!-- Right Section -->
<div class="content-header-section">
<!-- User Dropdown -->
<div class="btn-group" role="group">
<button type="button" class="btn btn-rounded btn-dual-secondary" id="page-header-user-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?= $pegawai['nama_pegawai'] ?><i class="fa fa-angle-down ml-5"></i>
</button>
<div class="dropdown-menu dropdown-menu-right min-width-150" aria-labelledby="page-header-user-dropdown">
<a class="dropdown-item" href="dashboard-pegawai">
<i class="si si-note mr-5"></i> Absensi
</a>
<a class="dropdown-item" href="profile-admin">
<i class="si si-note mr-5"></i> Profile Admin
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="keluar">
<i class="si si-logout mr-5"></i> Sign Out
</a>
</div>
</div>
<!-- END User Dropdown -->
</div>
<!-- END Right Section -->
</div>
<!-- END Header Content -->
<!-- Header Loader -->
<!-- Please check out the Activity page under Elements category to see examples of showing/hiding it -->
<div id="page-header-loader" class="overlay-header bg-primary">
<div class="content-header content-header-fullrow text-center">
<div class="content-header-item">
<i class="fa fa-sun-o fa-spin text-white"></i>
</div>
</div>
</div>
<!-- END Header Loader -->
</header>
<!-- END Header -->
<!-- Main Container -->
<main id="main-container">
<!-- Page Content -->
<div class="content">
<div class="row gutters-tiny invisible my-50" data-toggle="appear">
<!-- Row #1 -->
<div class="col-6 col-xl-3">
<a class="block block-link-shadow text-right" href="javascript:void(0)">
<div class="block-content block-content-full clearfix">
<div class="float-left mt-10 d-none d-sm-block">
<i class="si si-wrench fa-3x text-body-bg-dark"></i>
</div>
<div class="font-size-h3 font-w600" data-toggle="countTo" data-speed="1000" data-to="<?= $jml_jabatan ?>">0</div>
<div class="font-size-sm font-w600 text-uppercase text-muted">Jabatan</div>
</div>
</a>
</div>
<div class="col-6 col-xl-3">
<a class="block block-link-shadow text-right" href="javascript:void(0)">
<div class="block-content block-content-full clearfix">
<div class="float-left mt-10 d-none d-sm-block">
<i class="si si-users fa-3x text-body-bg-dark"></i>
</div>
<div class="font-size-h3 font-w600"><span data-toggle="countTo" data-speed="1000" data-to="<?= $jml_pegawai ?>">0</span></div>
<div class="font-size-sm font-w600 text-uppercase text-muted">Total Pegawai</div>
</div>
</a>
</div>
<div class="col-6 col-xl-3">
<a class="block block-link-shadow text-right" href="javascript:void(0)">
<div class="block-content block-content-full clearfix">
<div class="float-left mt-10 d-none d-sm-block">
<i class="si si-symbol-male fa-3x text-body-bg-dark"></i>
</div>
<div class="font-size-h3 font-w600" data-toggle="countTo" data-speed="1000" data-to="<?= $jml_pegawai_cowo ?>">0</div>
<div class="font-size-sm font-w600 text-uppercase text-muted">Total Pegawai Laki-laki</div>
</div>
</a>
</div>
<div class="col-6 col-xl-3">
<a class="block block-link-shadow text-right" href="javascript:void(0)">
<div class="block-content block-content-full clearfix">
<div class="float-left mt-10 d-none d-sm-block">
<i class="si si-symbol-female fa-3x text-body-bg-dark"></i>
</div>
<div class="font-size-h3 font-w600" data-toggle="countTo" data-speed="1000" data-to="<?= $jml_pegawai_cewe ?>">0</div>
<div class="font-size-sm font-w600 text-uppercase text-muted">Total Pegawai Perempuan</div>
</div>
</a>
</div>
<!-- END Row #1 -->
</div>
<div class="row gutters-tiny invisible" data-toggle="appear">
<!-- Row #5 -->
<!-- jabatan -->
<div class="col-6 col-md-3 col-xl-3">
<a class="block block-link-shadow text-center" href="kelola-jabatan">
<div class="block-content ribbon ribbon-bookmark ribbon-success ribbon-left">
<p class="mt-5">
<i class="si si-wrench fa-5x"></i>
</p>
<p class="font-w600">Kelola Jabatan</p>
</div>
</a>
</div>
<!-- pegawai -->
<div class="col-6 col-md-3 col-xl-3">
<a class="block block-link-shadow text-center" href="kelola-pegawai">
<div class="block-content">
<p class="mt-5">
<i class="si si-users fa-5x"></i>
</p>
<p class="font-w600">Kelola Pegawai</p>
</div>
</a>
</div>
<!-- absensi -->
<div class="col-6 col-md-3 col-xl-3">
<a class="block block-link-shadow text-center" href="kelola-absensi">
<div class="block-content ribbon ribbon-bookmark ribbon-primary ribbon-left">
<p class="mt-5">
<i class="si si-book-open fa-5x"></i>
</p>
<p class="font-w600">Kelola Absensi</p>
</div>
</a>
</div>
<!-- setting -->
<div class="col-6 col-md-3 col-xl-3">
<a class="block block-link-shadow text-center" href="setting-waktu">
<div class="block-content ribbon ribbon-bookmark ribbon-primary ribbon-left">
<p class="mt-5">
<i class="si si-settings fa-5x"></i>
</p>
<p class="font-w600">Setting Waktu</p>
</div>
</a>
</div>
<!-- END Row #5 -->
</div>
</div>
<!-- END Page Content -->
</main>
<!-- END Main Container -->
<!-- Footer -->
<footer id="page-footer" class="opacity-0">
<div class="content py-20 font-size-xs clearfix">
<div class="float-right">
Crafted with <i class="fa fa-heart text-pulse"></i> by <a class="font-w600" href="http://goo.gl/vNS3I" target="_blank">pixelcave</a>
</div>
<div class="float-left">
<a class="font-w600" href="https://goo.gl/po9Usv" target="_blank">Codebase 1.3</a> © <span class="js-year-copy">2017</span>
</div>
</div>
</footer>
<!-- END Footer -->
</div>
<file_sep>/update-absensi.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="assets/js/plugins/sweetalert2/es6-promise.auto.min.js"></script>
<script src="assets/js/plugins/sweetalert2/sweetalert2.min.js"></script>
<link rel="stylesheet" href="assets/js/plugins/sweetalert2/sweetalert2.min.css">
</head>
<body>
</body>
</html>
<?php
include "koneksi.php";
/*--------------------------------------------------------------------------*/
/*---------------------------- ANTI XSS & SQL INJECTION -------------------------------*/
function antiinjection($data){
$filter_sql = stripslashes(strip_tags(htmlspecialchars($data,ENT_QUOTES)));
return $filter_sql;
}
$id = antiinjection($_POST['id']);
$statuspagi = antiinjection($_POST['status_pagi']);
$statussore = antiinjection($_POST['status_sore']);
$sore = antiinjection($_POST['sore']);
$pagi = antiinjection($_POST['pagi']);
$lembur = antiinjection($_POST['lembur']);
$uang = antiinjection($_POST['uang']);
date_default_timezone_set("Asia/Jakarta");
$jam = date("H:i");
$sel = $sore - $lembur;
$total=$sel*$uang;
$cek_user=mysqli_num_rows(mysqli_query($connect, "SELECT * FROM absensi WHERE id_absensi = '$id'"));
if ($cek_user > 0) {
mysqli_query($connect, "UPDATE `absensi` SET absen_pagi = '$pagi', absen_sore = '$sore', status_pagi = '$statuspagi', status_sore = '$statussore', absen_lembur = '$lembur', jml_lembur = '$sel', uang_lembur = '$total' WHERE `id_absensi` = '$id'");
echo '<script language="javascript">swal("", "Absensi berhasil dirubah!", "success").then(() => { window.location="kelola-absensi"; });</script>';
} else {
echo '<script language="javascript">swal("", "Absensi tidak ditemukan!", "error").then(() => { window.history.back(); });</script>';
}
?>
<file_sep>/fetch.php
<?php
//fetch.php
include('koneksi.php');
include('format-tgl.php');
$columns = array('nip', 'nama_pegawai', 'tgl_absen', 'absen_pagi', 'status_pagi', 'absen_sore', 'status_sore', 'absen_lembur', 'jml_lembur');
$query = "SELECT * FROM absensi, pegawai WHERE absensi.nip = pegawai.nip AND ";
$j = mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM jam WHERE id_jam = 1"));
if($_POST["is_date_search"] == "yes")
{
$query .= 'absensi.tgl_absen BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
if(isset($_POST["search"]["value"]))
{
$query .= '
(absensi.nip LIKE "%'.$_POST["search"]["value"].'%"
OR pegawai.nama_pegawai LIKE "%'.$_POST["search"]["value"].'%"
OR absensi.absen_pagi LIKE "%'.$_POST["search"]["value"].'%"
OR absensi.absen_sore LIKE "%'.$_POST["search"]["value"].'%")
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'
';
}
else
{
$query .= 'ORDER BY id_absensi DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query . $query1);
$data = array();
$no = 1;
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = $no;
$sub_array[] = $row["nip"];
$sub_array[] = $row["tgl_absen"];
$sub_array[] = $row["nama_pegawai"];
if($row['absen_pagi'] == ''){
$sub_array[] = '-';
}else{
$sub_array[] = $row["absen_pagi"].' WIB';
}
$sub_array[] = $row["status_pagi"];
if($row['absen_sore'] == ''){
$sub_array[] = '-';
}else{
$sub_array[] = $row["absen_sore"].' WIB';
}
$sub_array[] = $row["status_sore"];
$sub_array[] = $row["absen_lembur"];
if($row['jml_lembur'] == ''){
$sub_array[] = '-';
}else{
$sub_array[] = $row["jml_lembur"].' Jam';
}
if($row['jml_lembur'] == ''){
$sub_array[] = '-';
}else{
$sub_array[] = "Rp".number_format($row["jml_lembur"] * $j['uang_lembur']).",-";
}
$sub_array[] = '<form class="" action="edit-absensi" method="post">
<input type="hidden" name="id" value="'. $row["id_absensi"] .'">
<button type="submit" class="btn btn-rounded btn-warning" style="width:100px" data-toggle="tooltip" title="Edit">
<i class="si si-note"> Edit</i>
</button><br/>
</form>'.'<a class="btn btn-rounded btn-alt-primary" style="width:100px" href="hapus-absensi.php?id='. $row["id_absensi"] .'"><i class="si si-trash mr-5"></i>Hapus</a>';
$data[] = $sub_array;
$no ++;
}
function get_all_data($connect)
{
$query = "SELECT * FROM absensi, pegawai WHERE absensi.nip = pegawai.nip";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
?>
<file_sep>/simpan-absensi.php
<?php
include ('koneksi.php');
function antiinjection($data){
$filter_sql = stripslashes(strip_tags(htmlspecialchars($data,ENT_QUOTES)));
return $filter_sql;
}
$nip = antiinjection($_POST['nip']);
$waktu = antiinjection($_POST['waktu']);
$tgl = antiinjection($_POST['tgl']);
$tgl = antiinjection($_POST['tgl']);
$id = antiinjection($_POST['id']);
date_default_timezone_set("Asia/Jakarta");
$awalpagi ='06:00:00am';
$akhirpagi ='08:00:00am';
$awalsore ='03:00:00pm';
$akhirsore ='12:00:00pm';
$lembur ='10:00:00pm';
if ($waktu >= $awalpagi && $waktu <= $akhirpagi) {
echo "siang";
}elseif ($waktu >= $awalsore && $waktu <= $akhirsore) {
if ($waktu >= $lembur) {
echo "lembur";
}else {
echo "biasa sore";
}
}else {
echo "salah";
}
?>
<file_sep>/edit-password.php
<?php
include("koneksi.php");
include("session.php");
include("format-tgl.php");
$qy_pegawai = mysqli_query($connect, "SELECT * FROM pegawai, jabatan, pengguna WHERE pegawai.nip = '$_SESSION[nip]' AND pegawai.jabatan = jabatan.id_jabatan AND pegawai.nip = pengguna.nip");
$pegawai = mysqli_fetch_array($qy_pegawai);
?>
<div id="page-container" class="sidebar-inverse side-scroll page-header-fixed page-header-inverse main-content-boxed">
<!-- Header -->
<header id="page-header">
<!-- Header Content -->
<div class="content-header">
<!-- Left Section -->
<div class="content-header-section">
</div>
<!-- END Left Section -->
<!-- Middle Section -->
<div class="content-header-section d-none d-lg-block">
<!-- Header Navigation -->
<!--
Desktop Navigation, mobile navigation can be found in #sidebar
If you would like to use the same navigation in both mobiles and desktops, you can use exactly the same markup inside sidebar and header navigation ul lists
If your sidebar menu includes headings, they won't be visible in your header navigation by default
If your sidebar menu includes icons and you would like to hide them, you can add the class 'nav-main-header-no-icons'
-->
<!-- Logo -->
<div class="content-header-item">
<a class="link-effect font-w700 mr-5" href="dashboard-pegawai">
<span class="font-size-xl text-dual-primary-dark">Bank</span><span class="font-size-xl text-danger"> Wakaf</span>
</a>
</div>
<!-- END Logo -->
<!-- END Header Navigation -->
</div>
<!-- END Middle Section -->
<!-- Right Section -->
<div class="content-header-section">
<!-- User Dropdown -->
<div class="btn-group" role="group">
<button type="button" class="btn btn-rounded btn-dual-secondary" id="page-header-user-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?= $pegawai['nama_pegawai'] ?><i class="fa fa-angle-down ml-5"></i>
</button>
<div class="dropdown-menu dropdown-menu-right min-width-150" aria-labelledby="page-header-user-dropdown">
<?php if($pegawai['hak_akses'] == 'Admin'){ ?>
<a class="dropdown-item" href="dashboard-admin">
<i class="si si-note mr-5"></i> Page Admin
</a>
<?php } ?>
<a class="dropdown-item" href="data-kehadiran">
<i class="si si-note mr-5"></i> Data Kehadiran
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="edit-password">
<i class="si si-note mr-5"></i> Edit Password
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="keluar">
<i class="si si-logout mr-5"></i> Sign Out
</a>
</div>
</div>
<!-- END User Dropdown -->
</div>
<!-- END Right Section -->
</div>
<!-- END Header Content -->
<!-- Header Search -->
<div id="page-header-search" class="overlay-header">
<div class="content-header content-header-fullrow">
<form action="bd_search.html" method="post">
<div class="input-group">
<span class="input-group-btn">
<!-- Close Search Section -->
<!-- Layout API, functionality initialized in Codebase() -> uiApiLayout() -->
<button type="button" class="btn btn-secondary px-15" data-toggle="layout" data-action="header_search_off">
<i class="fa fa-times"></i>
</button>
<!-- END Close Search Section -->
</span>
<input type="text" class="form-control" placeholder="Search or hit ESC.." id="page-header-search-input" name="page-header-search-input">
<span class="input-group-btn">
<button type="submit" class="btn btn-secondary px-15">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
</div>
</div>
<!-- END Header Search -->
<!-- Header Loader -->
<!-- Please check out the Activity page under Elements category to see examples of showing/hiding it -->
<div id="page-header-loader" class="overlay-header bg-primary">
<div class="content-header content-header-fullrow text-center">
<div class="content-header-item">
<i class="fa fa-sun-o fa-spin text-white"></i>
</div>
</div>
</div>
<!-- END Header Loader -->
</header>
<!-- END Header -->
<!-- Main Container -->
<main id="main-container">
<!-- Page Content -->
<div class="content">
<form action="update_password.php" method="post">
<div class="block block-themed" data-toggle="appear">
<div class="block-header bg-gd-sun">
<h3 class="block-title">Edit Password</h3>
<div class="block-options">
<button type="submit" class="btn btn-square btn-danger">
<i class="fa fa-save mr-5"></i>Save
</button>
</div>
</div>
<div class="block-content">
<div class="row justify-content-center">
<div class="col-6">
<div class="form-group mb-15">
<label for="side-overlay-profile-name">Nama</label>
<div class="input-group">
<input type="hidden" class="form-control" id="side-overlay-profile-name" name="id" placeholder="Your name.." value="<?= $pegawai['id_user']; ?>">
<input type="text" class="form-control" id="side-overlay-profile-name" name="nama" placeholder="Your name.." value="<?= $pegawai['nama_pegawai']; ?>">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
</div>
</div>
<div class="form-group mb-15">
<label for="side-overlay-profile-email">NIP</label>
<div class="input-group">
<input type="text" readonly class="form-control" id="side-overlay-profile-email" name="nip" placeholder="Your email.." value="<?= $pegawai['nip']; ?>">
<span class="input-group-addon"><i class="fa fa-key"></i></span>
</div>
</div>
<div class="form-group mb-15">
<label for="side-overlay-profile-password">Password Lama</label>
<div class="input-group">
<input type="password" class="form-control" id="side-overlay-profile-password" name="pass_lama" required placeholder="Masukan Password Lama..">
<span class="input-group-addon"><i class="fa fa-asterisk"></i></span>
</div>
</div>
<div class="form-group mb-15">
<label for="side-overlay-profile-password">Password Baru</label>
<div class="input-group">
<input type="password" class="form-control" id="pass1" name="pass_baru" placeholder="Masukan Password Baru.." required>
<span class="input-group-addon"><i class="fa fa-asterisk"></i></span>
</div>
</div>
<div class="form-group mb-15">
<label for="side-overlay-profile-password-confirm">Konfirmasi Password Baru</label>
<div class="input-group">
<input type="password" class="form-control" id="pass2" name="konfirmasi_pass" onkeyup="checkPass(); return false;" required placeholder="Konfirm Password Baru..">
<span class="input-group-addon"><i class="fa fa-asterisk"></i></span>
</div>
<span id="confirmMessage" class="confirmMessage"></span>
</div>
<div class="form-group row">
<div class="col-12">
<center>
<button type="submit" class="btn btn-block btn-alt-primary">
<i class="fa fa-refresh mr-5"></i> Update
</button>
</center>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<!-- END Page Content -->
</main>
<!-- END Main Container -->
<!-- Footer -->
<footer id="page-footer" class="opacity-0">
<div class="content py-20 font-size-xs clearfix">
<div class="float-right">
Crafted with <i class="fa fa-heart text-pulse"></i> by <a class="font-w600" href="http://goo.gl/vNS3I" target="_blank">pixelcave</a>
</div>
<div class="float-left">
<a class="font-w600" href="https://goo.gl/po9Usv" target="_blank">Codebase 1.3</a> © <span class="js-year-copy">2017</span>
</div>
</div>
</footer>
<!-- END Footer -->
</div>
<script type="text/javascript">
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#42a5f5";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass2.value == ""){
message.innerHTML = ""
}else if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Password Cocok!"
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Password Tidak Cocok!"
}
}
</script>
<file_sep>/readme.txt
=========================================********==========================================
Nama : <NAME>
email : <EMAIL>
=========================================********==========================================
Aplikasi Presensi dan Pengolahan Data Presensi Berbasis Website Responsive Menggunakan Random QR-Code
1. Aplikasi ini dibuat secara tim yaitu saya dan rekan saya bernama Yovie Fesya Pratama
2. Aplikasi yang dibuat telah mendukung fitur random QR Code dengan tujuan meminimalisir pemalsuan presensi
3. Studi Kasus di BWM (Bank Wakaf Mikro) Berkah Amanah Nusantara Purwokerto
<file_sep>/resetPassword.php
<!doctype html>
<!--[if lte IE 9]> <html lang="en" class="no-focus lt-ie10 lt-ie10-msg"> <![endif]-->
<!--[if gt IE 9]><!--> <html lang="en" class="no-focus"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
<title>Reset Password</title>
<meta name="description" content="Codebase - Bootstrap 4 Admin Template & UI Framework created by pixelcave and published on Themeforest">
<meta name="author" content="pixelcave">
<meta name="robots" content="noindex, nofollow">
<!-- Open Graph Meta -->
<meta property="og:title" content="Codebase - Bootstrap 4 Admin Template & UI Framework">
<meta property="og:site_name" content="Codebase">
<meta property="og:description" content="Codebase - Bootstrap 4 Admin Template & UI Framework created by pixelcave and published on Themeforest">
<meta property="og:type" content="website">
<meta property="og:url" content="">
<meta property="og:image" content="">
<!-- Icons -->
<!-- The following icons can be replaced with your own, they are used by desktop and mobile browsers -->
<link rel="shortcut icon" href="assets/img/favicons/favicon.png">
<link rel="icon" type="image/png" sizes="192x192" href="assets/img/favicons/favicon-192x192.png">
<link rel="apple-touch-icon" sizes="180x180" href="assets/img/favicons/apple-touch-icon-180x180.png">
<!-- END Icons -->
<!-- Stylesheets -->
<!-- Codebase framework -->
<link rel="stylesheet" id="css-main" href="assets/css/codebase.min.css">
<!-- You can include a specific file from css/themes/ folder to alter the default color theme of the template. eg: -->
<!-- <link rel="stylesheet" id="css-theme" href="assets/css/themes/flat.min.css"> -->
<!-- END Stylesheets -->
</head>
<body>
<!-- Page Container -->
<!--
Available classes for #page-container:
GENERIC
'enable-cookies' Remembers active color theme between pages (when set through color theme helper Codebase() -> uiHandleTheme())
SIDEBAR & SIDE OVERLAY
'sidebar-r' Right Sidebar and left Side Overlay (default is left Sidebar and right Side Overlay)
'sidebar-mini' Mini hoverable Sidebar (screen width > 991px)
'sidebar-o' Visible Sidebar by default (screen width > 991px)
'sidebar-o-xs' Visible Sidebar by default (screen width < 992px)
'sidebar-inverse' Dark themed sidebar
'side-overlay-hover' Hoverable Side Overlay (screen width > 991px)
'side-overlay-o' Visible Side Overlay by default
'side-scroll' Enables custom scrolling on Sidebar and Side Overlay instead of native scrolling (screen width > 991px)
HEADER
'' Static Header if no class is added
'page-header-fixed' Fixed Header
HEADER STYLE
'' Classic Header style if no class is added
'page-header-modern' Modern Header style
'page-header-inverse' Dark themed Header (works only with classic Header style)
'page-header-glass' Light themed Header with transparency by default
(absolute position, perfect for light images underneath - solid light background on scroll if the Header is also set as fixed)
'page-header-glass page-header-inverse' Dark themed Header with transparency by default
(absolute position, perfect for dark images underneath - solid dark background on scroll if the Header is also set as fixed)
MAIN CONTENT LAYOUT
'' Full width Main Content if no class is added
'main-content-boxed' Full width Main Content with a specific maximum width (screen width > 1200px)
'main-content-narrow' Full width Main Content with a percentage width (screen width > 1200px)
-->
<div id="page-container" class="main-content-boxed">
<!-- Main Container -->
<main id="main-container">
<!-- Page Content -->
<div class="bg-body-dark bg-pattern" style="background-image: url('assets/img/various/bg-pattern-inverse.png');">
<div class="row mx-0 justify-content-center">
<div class="hero-static col-lg-6 col-xl-4">
<div class="content content-full overflow-hidden">
<div class="py-30 text-center" style="margin-top:40px;">
<h1 class="h4 font-w700 mt-30 mb-10">Password Baru Anda adalah : </h1>
</div>
<!-- Reminder Form -->
<!-- jQuery Validation (.js-validation-reminder class is initialized in js/pages/op_auth_reminder.js) -->
<!-- For more examples you can check out https://github.com/jzaefferer/jquery-validation -->
<div class="block block-themed block-rounded block-shadow">
<div class="block-header bg-gd-primary">
</div>
<?php
require_once "functions.php";
require_once "koneksi.php";
if (isset($_GET['email']) && isset($_GET['token'])) {
$email = $connect->real_escape_string($_GET['email']);
$token = $connect->real_escape_string($_GET['token']);
$sql = $connect->query("SELECT id_user FROM pengguna WHERE
email='$email' AND token='$token' AND token<>'' AND tokenExpire > NOW()
");
if ($sql->num_rows > 0) {
$newPassword = <PASSWORD>NewString();
$newPasswordEncrypted = md5('<PASSWORD>'.$newPassword);
$connect->query("UPDATE pengguna SET token='', password = <PASSWORD>', status='Baru'
WHERE email='$email'
");
?>
<div class="block-content">
<div class="form-group row">
<div class="col-12">
<input type="text" readonly class="form-control" value="<?= $newPassword ?>" id="myInput">
</div>
</div>
<div class="form-group text-center">
<button type="button" class="btn btn-primary" onclick="myFunction()">
<i class="fa fa-copy mr-10"></i> Copy text
</button>
</div>
</div>
<div class="block-content bg-body-light">
<div class="form-group text-center">
<a class="link-effect text-muted mr-10 mb-5 d-inline-block" href="masuk">
<i class="fa fa-user text-muted mr-5"></i> Sign In
</a>
</div>
</div>
<?php
} else
redirectToLoginPage();
} else {
redirectToLoginPage();
}
?>
</div>
<!-- END Reminder Form -->
</div>
</div>
</div>
</div>
<!-- END Page Content -->
</main>
<!-- END Main Container -->
</div>
<!-- END Page Container -->
<script>
function myFunction() {
var copyText = document.getElementById("myInput");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
</script>
<!-- Codebase Core JS -->
<script src="assets/js/core/jquery.min.js"></script>
<script src="assets/js/core/popper.min.js"></script>
<script src="assets/js/core/bootstrap.min.js"></script>
<script src="assets/js/core/jquery.slimscroll.min.js"></script>
<script src="assets/js/core/jquery.scrollLock.min.js"></script>
<script src="assets/js/core/jquery.appear.min.js"></script>
<script src="assets/js/core/jquery.countTo.min.js"></script>
<script src="assets/js/core/js.cookie.min.js"></script>
<script src="assets/js/codebase.js"></script>
<!-- Page JS Plugins -->
<script src="assets/js/plugins/jquery-validation/jquery.validate.min.js"></script>
<!-- Page JS Code -->
<script src="assets/js/pages/op_auth_signin.js"></script>
</body>
</html>
<file_sep>/akses-file.php
<?php
$pg = isset($_GET['pages']) ? $_GET['pages'] : '' ;
switch ($pg) {
case 'list-pengajuan-lembur':
if(!file_exists('list-pengajuan-lembur.php'))die(header('location:error-brow.html'));
include("list-pengajuan-lembur.php");
break;
case 'login':
if(!file_exists('login.php'))die(header('location:error-brow.html'));
include("login.php");
break;
case 'masuk':
if(!file_exists('login-baru.php'))die(header('location:error-brow.html'));
include("login-baru.php");
break;
case 'pengajuan-lembur':
if(!file_exists('pengajuan-lembur.php'))die(header('location:error-brow.html'));
include("pengajuan-lembur.php");
break;
case 'forgot':
if(!file_exists('forgot.php'))die(header('location:error-brow.html'));
include("forgot.php");
break;
case 'logout':
if(!file_exists('logout.php'))die(header('location:error-brow.html'));
include("logout.php");
break;
case 'dashboard-admin':
if(!file_exists('dashboard-admin.php'))die(header('location:error-brow.html'));
include("dashboard-admin.php");
break;
case 'dashboard-pegawai':
if(!file_exists('dashboard-pegawai.php'))die(header('location:error-brow.html'));
include("dashboard-pegawai.php");
break;
case 'data-kehadiran':
if(!file_exists('data-kehadiran.php'))die(header('location:error-brow.html'));
include("data-kehadiran.php");
break;
case 'profile-admin':
if(!file_exists('profile-admin.php'))die(header('location:error-brow.html'));
include("profile-admin.php");
break;
case 'setting-waktu':
if(!file_exists('setting-waktu.php'))die(header('location:error-brow.html'));
include("setting-waktu.php");
break;
case 'edit-waktu':
if(!file_exists('edit-waktu.php'))die(header('location:error-brow.html'));
include("edit-waktu.php");
break;
case 'edit-password':
if(!file_exists('edit-password.php'))die(header('location:error-brow.html'));
include("edit-password.php");
break;
case 'kelola-jabatan':
if(!file_exists('kelola-jabatan.php'))die(header('location:error-brow.html'));
include("kelola-jabatan.php");
break;
case 'edit-jabatan':
if(!file_exists('edit-jabatan.php'))die(header('location:error-brow.html'));
include("edit-jabatan.php");
break;
case 'edit-absensi':
if(!file_exists('edit-absensi.php'))die(header('location:error-brow.html'));
include("edit-absensi.php");
break;
case 'kelola-pegawai':
if(!file_exists('kelola-pegawai.php'))die(header('location:error-brow.html'));
include("kelola-pegawai.php");
break;
case 'edit-pegawai':
if(!file_exists('edit-pegawai.php'))die(header('location:error-brow.html'));
include("edit-pegawai.php");
break;
case 'kelola-absensi':
if(!file_exists('kelola-absensi.php'))die(header('location:error-brow.html'));
include("kelola-absensi.php");
break;
case 'kelola-absensi-total':
if(!file_exists('kelola-absensi-total.php'))die(header('location:error-brow.html'));
include("kelola-absensi-total.php");
break;
case 'kelola-absensi-cetak':
if(!file_exists('kelola-absensi-cetak.php'))die(header('location:error-brow.html'));
include("kelola-absensi-cetak.php");
break;
case 'kelola-absensi-lembur':
if(!file_exists('kelola-absensi-lembur.php'))die(header('location:error-brow.html'));
include("kelola-absensi-lembur.php");
break;
}
?>
<file_sep>/qrcodegenerate/login-proses.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="assets/js/plugins/sweetalert2/es6-promise.auto.min.js"></script>
<script src="assets/js/plugins/sweetalert2/sweetalert2.min.js"></script>
<link rel="stylesheet" href="assets/js/plugins/sweetalert2/sweetalert2.min.css">
</head>
<body>
</body>
</html>
<?php
include('koneksi.php');
function antiinjection($data){
$filter_sql = stripslashes(strip_tags(htmlspecialchars($data,ENT_QUOTES)));
return $filter_sql;
}
if(empty($_POST['login-username']) && empty($_POST['login-password'])){
echo '<script language="javascript">swal("Akses ditolak!","","error").then(() => { window.location="masuk"; });</script>';
}else{
$uname = antiinjection($_POST['login-username']);
$pass = antiinjection($_POST['login-password']);
$salt ='<PASSWORD>';
$hash = md5($salt . $pass);
//------ANTI XSS & SQL INJECTION-------//
$sql=mysqli_query($connect, "SELECT * FROM pengguna WHERE nip='$uname' AND password='$hash'");
$r=mysqli_fetch_array($sql);
$device = $r['device'];
if ($r['nip']==$uname and $r['password']==$hash)
{
if (empty($device)) {
$ismobile = 0;
$container = $_SERVER['HTTP_USER_AGENT'];
$useragents = array();
foreach($useragents as $useragents){
if(strstr($container,$useragents)){
$ismobile = 1; }
} if($ismobile) {
}
$_SERVER['HTTP_USER_AGENT'];
mysqli_query($connect, "UPDATE pengguna SET device = '$_SERVER[HTTP_USER_AGENT]' WHERE nip = '$r[nip]'");
session_start();
$_SESSION['nip']=$r['nip'];
$_SESSION['password']=$r['<PASSWORD>'];
echo '<script language="javascript">swal("Login berhasil!", "Silahkan Masuk!", "success").then(() => { window.location="qr.php"; });</script>';
}else{
if ($r['device'] != $_SERVER['HTTP_USER_AGENT']) {
echo '<script language="javascript">swal("Device ditolak!","","error").then(() => { window.location="index.php"; });</script>';
exit;
}
session_start();
$_SESSION['nip']=$r['nip'];
$_SESSION['password']=$r['<PASSWORD>'];
echo '<script language="javascript">swal("Login berhasil!", "Silahkan Masuk!", "success").then(() => { window.location="qr.php"; });</script>';
}
}else{
echo '<script language="javascript">swal("Login Gagal!", " Silahkan cek lagi username dan password anda!", "error").then(() => { window.location="index.php"; });</script>';
}
}
?>
<file_sep>/forgot.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
require_once "functions.php";
require_once "koneksi.php";
if (isset($_POST['email'])) {
$email = $connect->real_escape_string($_POST['email']);
$sql = $connect->query("SELECT id_user FROM pengguna WHERE email='$email'");
if ($sql->num_rows > 0) {
$token = generateNewString();
$connect->query("UPDATE pengguna SET token='$token',
tokenExpire=DATE_ADD(NOW(), INTERVAL 5 MINUTE)
WHERE email='$email'
");
//Load Composer's autoloader
require 'vendor/autoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '<EMAIL>'; // SMTP username
$mail->Password = '<PASSWORD>'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('<EMAIL>', 'Administrator');
$mail->addAddress($email);
$mail->Subject = "Reset Password";
$mail->isHTML(true);
$mail->Body = "
Hi,<br><br>
In order to reset your password, please click on the link below:<br>
<a href='http://localhost/absensi/resetPassword.php?email=$email&token=$token'>Klik disini !!</a><br><br>
Manager,<br>
";
if ($mail->send())
exit(json_encode(array("status" => 1, "msg" => 'Please Check Your Email Inbox!')));
else
exit(json_encode(array("status" => 0, "msg" => $mail->ErrorInfo)));
} else
exit(json_encode(array("status" => 0, "msg" => 'Please Check Your Inputs!')));
}
?>
<div id="page-container" class="main-content-boxed">
<!-- Main Container -->
<main id="main-container">
<!-- Page Content -->
<div class="bg-body-dark bg-pattern" style="background-image: url('assets/img/various/bg-pattern-inverse.png');">
<div class="row mx-0 justify-content-center">
<div class="hero-static col-lg-6 col-xl-4">
<div class="content content-full overflow-hidden">
<div class="py-30 text-center" style="margin-top:40px;">
<a class="link-effect font-w700" href="#">
<i class="si si-fire"></i>
<span class="font-size-xl text-primary-dark">Bank</span><span class="font-size-xl">Wakaf</span>
</a>
<h1 class="h4 font-w700 mt-30 mb-10">Selamat datang di Absensi Bank Wakaf</h1>
<h2 class="h5 font-w400 text-muted mb-0">Silahkan Masukan NIP dan Password anda untuk melakukan Absensi</h2>
</div>
<!-- Reminder Form -->
<!-- jQuery Validation (.js-validation-reminder class is initialized in js/pages/op_auth_reminder.js) -->
<!-- For more examples you can check out https://github.com/jzaefferer/jquery-validation -->
<div class="block block-themed block-rounded block-shadow">
<div class="block-header bg-gd-primary">
<h3 class="block-title">Password Reminder</h3>
<div class="block-options">
<button type="button" class="btn-block-option">
<i class="si si-wrench"></i>
</button>
</div>
</div>
<div class="block-content">
<div class="form-group row">
<div class="col-12">
<label for="reminder-credential">Username or Email</label>
<input class="form-control" id="email" placeholder="Your Email Address">
</div>
</div>
<div class="form-group text-center">
<button type="button" class="btn btn-primary">
<i class="fa fa-asterisk mr-10"></i> Password Reminder
</button>
</div>
<center><p id="response"></p></center>
</div>
<div class="block-content bg-body-light">
<div class="form-group text-center">
<a class="link-effect text-muted mr-10 mb-5 d-inline-block" href="masuk">
<i class="fa fa-user text-muted mr-5"></i> Sign In
</a>
</div>
</div>
</div>
<!-- END Reminder Form -->
</div>
</div>
</div>
</div>
<!-- END Page Content -->
</main>
<!-- END Main Container -->
</div>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<!-- END Page Container -->
<script type="text/javascript">
var email = $("#email");
$(document).ready(function () {
$('.btn-primary').on('click', function () {
if (email.val() != "") {
email.css('border', '1px solid green');
$.ajax({
url: 'forgot.php',
method: 'POST',
dataType: 'json',
data: {
email: email.val()
}, success: function (response) {
if (!response.success)
$("#response").html(response.msg).css('color', "red");
else
$("#response").html(response.msg).css('color', "green");
}
});
} else
email.css('border', '1px solid red');
});
});
</script>
<file_sep>/cetak.php
<?php
/* include autoloader */
include('koneksi.php');
include('format-tgl.php');
require_once 'dompdf/autoload.inc.php';
/* reference the Dompdf namespace */
use Dompdf\Dompdf;
/* instantiate and use the dompdf class */
$dompdf = new Dompdf();
$atas = $_POST['atas'];
$bawah = $_POST['bawah'];
$j = mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM jam WHERE id_jam = '1'"));
$qy = mysqli_query($connect, "SELECT * FROM absensi, pegawai WHERE absensi.nip = pegawai.nip AND absensi.tgl_absen BETWEEN '$atas' AND '$bawah' ORDER BY absensi.id_absensi");
$qy1 = mysqli_query($connect, "SELECT * FROM absensi, pegawai WHERE absensi.nip = pegawai.nip AND absensi.absen_lembur != '' AND absensi.tgl_absen BETWEEN '$atas' AND '$bawah' ORDER BY absensi.id_absensi DESC");
$html = '
<!DOCTYPE html>
<html>
<head>
<style>
body{
height:80%;
}
table {
border-collapse: collapse;
}
table, th, td {
padding : 7px;
border: 1px solid black;
text-align:center;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h3 class="mt-30" align="center">LAPORAN ABSENSI BANK WAKAF<br>KARANGSUCI - PURWOKERTO<br><span>Jl. Letjend Pol Soemarto, Purwanegara, Purwokerto Utara</span></h3>
<p align="center">__________________________________________________________________________________________________________________________________</p>
<center>
<h4>Laporan Absensi tanggal '.indonesian_date($atas).' sampai tanggal '.indonesian_date($bawah).'</h4>
<table>
<thead>
<tr>
<th class="text-center">No</th>
<th class="text-center">NIP</th>
<th class="text-center">Tanggal</th>
<th class="text-center">Nama</th>
<th class="text-center">Absen Pagi</th>
<th class="text-center">Status Absen Pagi</th>
<th class="text-center">Absen Sore</th>
<th class="text-center">Status Absen Sore</th>
<th class="text-center">Absen Lembur</th>
<th class="text-center">Jumlah Lembur</th>
</tr>
</thead>
<tbody>
';
$no = 1;
while ($a = mysqli_fetch_array($qy)) {
$html .= '<tr>
<td>'. $no .'</td>
<td>'. $a['nip'] .'</td>
<td>'. $a['nama_pegawai'] .'</td>
<td>'. indonesian_date($a['tgl_absen']) .'</td>';
if($a['absen_pagi'] == ''){
$html .= '<td> - </td>'; }else{
$html .= '<td>'. $a['absen_pagi'] .'</td>'; }
$html .= '<td>'. $a['status_pagi'] .'</td>';
if($a['absen_sore'] == ''){
$html .= '<td> - </td>'; }else{
$html .= '<td>'. $a['absen_sore'] .'</td>'; }
$html .= '<td>'. $a['status_sore'] .'</td>';
if($a['absen_lembur'] == ''){
$html .= '<td> - </td>'; }else{
$html .= '<td>'. $a['absen_lembur'] .'</td>'; }
if($a['jml_lembur'] == ''){
$html .= '<td> - </td>'; }else{
$html .= '<td>'. $a['jml_lembur'] .'</td>'; }
$html .= '</tr>';
$no++; }
$html .= '</tbody>
</table>
<br>
<br>
<h2>Laporan Data Lembur</h2>
<table>
<thead>
<tr>
<th class="text-center">No</th>
<th class="text-center">NIP</th>
<th class="text-center">Tanggal</th>
<th class="text-center">Nama</th>
<th class="text-center">Absen Lembur</th>
<th class="text-center">Jumlah Lembur</th>
<th class="text-center">Uang Lembur</th>
</tr>
</thead>
<tbody>
';
$no = 1;
while ($a1 = mysqli_fetch_array($qy1)) {
$html .= '<tr>
<td>'. $no .'</td>
<td>'. $a1['nip'] .'</td>
<td>'. $a1['nama_pegawai'] .'</td>
<td>'. indonesian_date($a1['tgl_absen']) .'</td>';
if($a1['absen_lembur'] == ''){
$html .= '<td> - </td>'; }else{
$html .= '<td>'. $a1['absen_lembur'] .'</td>'; }
if($a1['jml_lembur'] == ''){
$html .= '<td> - </td>'; }else{
$html .= '<td>'. $a1['jml_lembur'] .'</td>'; }
$html .= '<td>Rp'. number_format($j['uang_lembur'] * $a1['jml_lembur']) .',-</td>';
$html .= '</tr>';
$no++; }
$html .= '</tbody>
</table>
</center>
</div>
</div>
</div>
</body>
</html>';
// echo $html;
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
/* Render the HTML as PDF */
$dompdf->render();
/* Output the generated PDF to Browser */
$dompdf->stream("Laporan-absensi-tgl-".indonesian_date($atas)."-".indonesian_date($bawah).".pdf");
?>
<file_sep>/acc.php
<?php
include('koneksi.php');
include('format-tanggal.php');
$id_pengajuan = $_POST['id_pengajuan'];
$absensi = $_POST['absensi'];
$acc = $_POST['acc'];
$k = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM pengajuan_lembur WHERE id_lembur = '$id_pengajuan'"));
$e = mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM pengguna where nip = '$k[nip]'"));
$email = $e['email'];
//Load Composer's autoloader
require 'vendor/autoload.php';
$result["message"] = "";
if($acc == ""){
$result["message"] = 'Tidak ada perubahan';
}elseif ($acc == "Tidak") {
$qy = $connect->query("UPDATE pengajuan_lembur SET arsip = 'Ya' WHERE id_lembur = '$id_pengajuan'");
$result["message"] = '
<div class="alert alert-warning alert-dismissable" role="alert">
<button type="button" class="close" onclick="myFunction()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="alert-heading font-size-h4 font-w400">Success</h3>
<p class="mb-0">Pengajuan lembur ditolak</p>
</div>
';
// //Create a new PHPMailer instance
// $mail = new PHPMailer;
// $mail->isSMTP(); // Set mailer to use SMTP
// $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
// $mail->SMTPAuth = true; // Enable SMTP authentication
// $mail->Username = '<EMAIL>'; // SMTP username
// $mail->Password = '<PASSWORD>'; // SMTP password
// $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
// $mail->Port = 587; // TCP port to connect to
//
//
// //Recipients
// $mail->setFrom('<EMAIL>', 'Administrator');
// $mail->addAddress($email);
// $mail->Subject = "Pengajuan Lembur";
//
// $mail->isHTML(true);
//
// $mail->Body = "
// Hi,<br><br>
//
// Berdasarkan pengajuan lembur yang diajukan pada ".indonesian_date($k['tgl'])." dengan keperluan <b>".$k['keperluan']."</b> ditolak.<br><br>
//
// Manager,<br>";
}else{
$qy1 = mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM absensi WHERE id_absensi = '$absensi'"));
$jml = $_POST['wkt'] - $qy1['absen_sore'];
$uang = $jml * $_POST['uang'];
//
// //Create a new PHPMailer instance
// $mail = new PHPMailer;
// $mail->isSMTP(); // Set mailer to use SMTP
// $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
// $mail->SMTPAuth = true; // Enable SMTP authentication
// $mail->Username = '<EMAIL>'; // SMTP username
// $mail->Password = '<PASSWORD>'; // SMTP password
// $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
// $mail->Port = 587; // TCP port to connect to
//
//
// //Recipients
// $mail->setFrom('<EMAIL>', 'Administrator');
// $mail->addAddress($email);
// $mail->Subject = "Pengajuan Lembur";
//
// $mail->isHTML(true);
//
// $mail->Body = "
// Hi,<br><br>
//
// Berdasarkan pengajuan lembur yang diajukan pada ".indonesian_date($k['tgl'])." dengan keperluan <b>".$k['keperluan']."</b> diterima.<br><br>
//
// Manager,<br>";
$qy = $connect->query("UPDATE pengajuan_lembur SET arsip = 'Ya' WHERE id_lembur = '$id_pengajuan'");
$qy2 = $connect->query("UPDATE absensi SET absen_lembur = '$_POST[wkt]', jml_lembur = '$jml', verifikasi_lembur = 'Ya', uang_lembur = '$uang' WHERE id_absensi = '$absensi'");
$result["message"] = '
<div class="alert alert-success alert-dismissable" role="alert">
<button type="button" class="close" onclick="myFunction()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="alert-heading font-size-h4 font-w400">Success</h3>
<p class="mb-0">Pengajuan lembur disetujui</p>
</div>
';
}
echo json_encode($result);
?>
<file_sep>/update-jam.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="assets/js/plugins/sweetalert2/es6-promise.auto.min.js"></script>
<script src="assets/js/plugins/sweetalert2/sweetalert2.min.js"></script>
<link rel="stylesheet" href="assets/js/plugins/sweetalert2/sweetalert2.min.css">
</head>
<body>
</body>
</html>
<?php
include "koneksi.php";
/*--------------------------------------------------------------------------*/
/*---------------------------- ANTI XSS & SQL INJECTION -------------------------------*/
function antiinjection($data){
$filter_sql = stripslashes(strip_tags(htmlspecialchars($data,ENT_QUOTES)));
return $filter_sql;
}
$id = antiinjection($_POST['id']);
$awalpagi = antiinjection($_POST['awal-pagi']);
$akhirpagi = antiinjection($_POST['akhir-pagi']);
$awalsore = antiinjection($_POST['awal-sore']);
$akhirsore = antiinjection($_POST['akhir-sore']);
$lembur = antiinjection($_POST['lembur']);
$uanglembur = antiinjection($_POST['uang-lembur']);
// $uangmakan = antiinjection($_POST['uang-makan']);
$sql = mysqli_query($connect, "UPDATE jam SET
awalabsen_pagi = '$awalpagi',
akhirabsen_pagi = '$akhirpagi',
awalabsen_sore = '$awalsore',
akhirabsen_sore = '$akhirsore',
absen_lembur = '$lembur',
uang_lembur = '$uanglembur'
WHERE id_jam = '$id'");
if($sql){
echo '<script language="javascript">swal("", "Jumlah uang lembur berhasil dirubah!", "success").then(() => { window.location="setting-waktu"; });</script>';
}else{
echo '<script language="javascript">swal("", "Jumlah uang lembur gagal dirubah!", "error").then(() => { window.location="setting-waktu"; });</script>';
}
?>
<file_sep>/edit-jabatan.php
<?php
include("koneksi.php");
include("session.php");
include("format-tgl.php");
$qy_pegawai = mysqli_query($connect, "SELECT * FROM pegawai, jabatan WHERE pegawai.nip = '$_SESSION[nip]' AND pegawai.jabatan = jabatan.id_jabatan");
$pegawai = mysqli_fetch_array($qy_pegawai);
?>
<div id="page-container" class="sidebar-inverse side-scroll page-header-fixed page-header-inverse main-content-boxed">
<!-- Header -->
<header id="page-header">
<!-- Header Content -->
<div class="content-header">
<!-- Left Section -->
<div class="content-header-section">
<!-- Logo -->
<div class="content-header-item">
<a class="link-effect font-w700 mr-5" href="dashboard-admin">
<i class="si si-fire text-primary"></i>
<span class="font-size-xl text-dual-primary-dark">Bank</span><span class="font-size-xl text-danger"> Wakaf</span>
</a>
</div>
<!-- END Logo -->
</div>
<!-- END Left Section -->
<!-- Middle Section -->
<div class="content-header-section d-none d-lg-block">
<ul class="nav-main-header">
<li>
<a href="dashboard-admin"><i class="si si-compass"></i>Dashboard</a>
</li>
<li>
<a class="active" href="kelola-jabatan"><i class="si si-wrench"></i>Kelola Jabatan</a>
</li>
<li>
<a href="kelola-pegawai"><i class="si si-users"></i>Kelola Pegawai</a>
</li>
<li>
<a href="kelola-absensi"><i class="si si-book-open"></i>Kelola Absensi</a>
</li>
<li>
<a href="setting-waktu"><i class="si si-settings"></i>Setting</a>
</li>
</ul>
<!-- END Header Navigation -->
</div>
<!-- END Middle Section -->
<!-- Right Section -->
<div class="content-header-section">
<!-- User Dropdown -->
<div class="btn-group" role="group">
<button type="button" class="btn btn-rounded btn-dual-secondary" id="page-header-user-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?= $pegawai['nama_pegawai'] ?><i class="fa fa-angle-down ml-5"></i>
</button>
<div class="dropdown-menu dropdown-menu-right min-width-150" aria-labelledby="page-header-user-dropdown">
<a class="dropdown-item" href="profile-admin">
<i class="si si-note mr-5"></i> Profile Admin
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="keluar">
<i class="si si-logout mr-5"></i> Sign Out
</a>
</div>
</div>
<!-- END User Dropdown -->
</div>
<!-- END Right Section -->
</div>
<!-- END Header Content -->
</header>
<!-- END Header -->
<!-- Main Container -->
<main id="main-container">
<!-- Page Content -->
<div class="content">
<div class="row gutters-tiny invisible" data-toggle="appear">
<div class="col-md-12">
<!-- Floating Labels -->
<div class="block">
<div class="block-header block-header-default">
<h3 class="block-title">Edit Jabatan</h3>
<div class="block-options">
<button type="button" class="btn-block-option">
<i class="si si-wrench"></i>
</button>
</div>
</div>
<div class="block-content">
<div class="col-md-12">
<form action="update-jabatan.php" method="post">
<div class="block block-rounded block-themed">
<div class="block-header bg-gd-primary">
<h3 class="block-title">Edit Data Jabatan</h3>
<div class="block-options">
<button type="submit" class="btn btn-sm btn-alt-primary">
<i class="fa fa-save mr-5"></i>Save
</button>
</div>
</div>
<div class="block-content block-content-full">
<div class="form-group row">
<label class="col-12" for="ecom-product-name">Id Jabatan</label>
<div class="col-12">
<input type="hidden" class="form-control" id="ecom-product-name" name="id_lama" placeholder="Product Name" value="<?= $_POST['id'] ?>">
<input type="text" class="form-control" id="ecom-product-name" name="id" placeholder="Product Name" value="<?= $_POST['id'] ?>">
</div>
</div>
<div class="form-group row">
<label class="col-12" for="ecom-product-name">Nama Jabatan</label>
<div class="col-12">
<input type="text" class="form-control" id="ecom-product-name" name="nama" placeholder="Product Name" value="<?= $_POST['nama'] ?>">
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- END Floating Labels -->
</div>
</div>
</div>
<!-- END Page Content -->
</main>
<!-- END Main Container -->
<!-- Footer -->
<footer id="page-footer" class="opacity-0">
<div class="content py-20 font-size-xs clearfix">
<div class="float-right">
Crafted with <i class="fa fa-heart text-pulse"></i> by <a class="font-w600" href="http://goo.gl/vNS3I" target="_blank">pixelcave</a>
</div>
<div class="float-left">
<a class="font-w600" href="https://goo.gl/po9Usv" target="_blank">Codebase 1.3</a> © <span class="js-year-copy">2017</span>
</div>
</div>
</footer>
<!-- END Footer -->
</div>
<file_sep>/cron.php
<?php
include "koneksi.php";
$sql = mysqli_query($connect, "SELECT * FROM pegawai");
$userinfo = array();
while($row_user = mysqli_fetch_assoc($sql)){
$userinfo[] = $row_user;
}
foreach($userinfo as $usrinfo){
$date = date('Y-m-d');
$query = "INSERT INTO `absensi`(`nip`, `tgl_absen`) VALUES ('" . $usrinfo['nip'] . "', '$date')";
$result = mysqli_query($connect, $query) or die(mysqli_error());
}
?>
<file_sep>/simpan-jabatan.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="assets/js/plugins/sweetalert2/es6-promise.auto.min.js"></script>
<script src="assets/js/plugins/sweetalert2/sweetalert2.min.js"></script>
<link rel="stylesheet" href="assets/js/plugins/sweetalert2/sweetalert2.min.css">
</head>
<body>
</body>
</html>
<?php
include('koneksi.php');
// include('session.php');
function antiinjection($data){
$filter_sql = stripslashes(strip_tags(htmlspecialchars($data,ENT_QUOTES)));
return $filter_sql;
}
$id = antiinjection($_POST['id']);
$nama = antiinjection($_POST['nama']);
$cek = mysqli_num_rows(mysqli_query($connect, "SELECT * FROM jabatan WHERE id_jabatan = '$id'"));
if ($cek > 0) {
echo '<script language="javascript">swal("Simpan gagal!", "Data jabatan sudah ada!", "warning").then(() => { window.history.back(); });</script>';
}else{
mysqli_query($connect, "INSERT INTO jabatan (id_jabatan, nama_jabatan)
VALUES ('$id','$nama')");
echo '<script language="javascript">swal("Simpan berhasil!", "Data jabatan tersimpan", "success").then(() => { window.history.back(); });</script>';
}
?>
<file_sep>/setting-waktu.php
<?php
include("koneksi.php");
include("session.php");
include("format-tgl.php");
$qy_pegawai = mysqli_query($connect, "SELECT * FROM pegawai, jabatan WHERE pegawai.nip = '$_SESSION[nip]' AND pegawai.jabatan = jabatan.id_jabatan");
$pegawai = mysqli_fetch_array($qy_pegawai);
?>
<div id="page-container" class="sidebar-inverse side-scroll page-header-fixed page-header-inverse main-content-boxed">
<!-- Header -->
<header id="page-header">
<!-- Header Content -->
<div class="content-header">
<!-- Left Section -->
<div class="content-header-section">
<!-- Logo -->
<div class="content-header-item">
<a class="link-effect font-w700 mr-5" href="dashboard-admin">
<i class="si si-fire text-primary"></i>
<span class="font-size-xl text-dual-primary-dark">Bank</span><span class="font-size-xl text-danger"> Wakaf</span>
</a>
</div>
<!-- END Logo -->
</div>
<!-- END Left Section -->
<!-- Middle Section -->
<div class="content-header-section d-none d-lg-block">
<ul class="nav-main-header">
<li>
<a href="dashboard-admin"><i class="si si-compass"></i>Dashboard</a>
</li>
<li>
<a href="kelola-jabatan"><i class="si si-wrench"></i>Kelola Jabatan</a>
</li>
<li>
<a href="kelola-pegawai"><i class="si si-users"></i>Kelola Pegawai</a>
</li>
<li>
<a href="kelola-absensi"><i class="si si-book-open"></i>Kelola Absensi</a>
</li>
<li>
<a class="active" href="setting-waktu"><i class="si si-settings"></i>Setting</a>
</li>
</ul>
<!-- END Header Navigation -->
</div>
<!-- END Middle Section -->
<!-- Right Section -->
<div class="content-header-section">
<!-- User Dropdown -->
<div class="btn-group" role="group">
<button type="button" class="btn btn-rounded btn-dual-secondary" id="page-header-user-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?= $pegawai['nama_pegawai'] ?><i class="fa fa-angle-down ml-5"></i>
</button>
<div class="dropdown-menu dropdown-menu-right min-width-150" aria-labelledby="page-header-user-dropdown">
<a class="dropdown-item" href="dashboard-pegawai">
<i class="si si-note mr-5"></i> Absensi
</a>
<a class="dropdown-item" href="profile-admin">
<i class="si si-note mr-5"></i> Profile Admin
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="keluar">
<i class="si si-logout mr-5"></i> Sign Out
</a>
</div>
</div>
<!-- END User Dropdown -->
</div>
<!-- END Right Section -->
</div>
<!-- END Header Content -->
</header>
<!-- END Header -->
<!-- Main Container -->
<main id="main-container">
<!-- Hero -->
<div class="bg-image" style="background-image: url('assets/img/photos/photo26@2x.jpg');">
<div class="bg-black-op-75">
<div class="content content-top content-full text-center">
<div class="py-20">
<h1 class="h2 font-w700 text-white mb-10">Kelola Waktu Kerja</h1>
<h2 class="h4 font-w400 text-white-op mb-0">Halaman Untuk Mengelola Data Waktu Kerja</h2>
</div>
</div>
</div>
</div>
<!-- END Hero -->
<div class="container block-content block-content-full mt-30">
<div class="block block-themed">
<div class="block-header bg-gd-sun">
<h3 class="block-title"></h3>
<div class="block-options">
<button type="button" onclick="window.location='edit-waktu'" class="btn-block-option">
Edit
</button>
</div>
</div>
<div class="row gutters-tiny justify-content-center py-10">
<?php
$jam = mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM jam"));
?>
<div class="col-6 col-md-4 col-xl-2">
<a class="block block-transparent text-center bg-pulse" href="javascript:void(0)">
<div class="block-content">
<p class="font-size-h4 text-white">
<strong><?= $jam['awalabsen_pagi'] ?> WIB</strong>
</p>
</div>
<div class="block-content bg-black-op-5">
<p class="font-w600 text-white-op">
<i class="si si-clock mr-5"></i><br>Awal Absensi Pagi
</p>
</div>
</a>
</div>
<div class="col-6 col-md-4 col-xl-2">
<a class="block block-transparent text-center bg-pulse" href="javascript:void(0)">
<div class="block-content">
<p class="font-size-h4 text-white">
<strong><?= $jam['akhirabsen_pagi'] ?> WIB</strong>
</p>
</div>
<div class="block-content bg-black-op-5">
<p class="font-w600 text-white-op">
<i class="si si-clock mr-5"></i><br>Akhir Absensi Pagi
</p>
</div>
</a>
</div>
<div class="col-6 col-md-4 col-xl-2">
<a class="block block-transparent text-center bg-pulse" href="javascript:void(0)">
<div class="block-content">
<p class="font-size-h4 text-white">
<strong><?= $jam['awalabsen_sore'] ?> WIB</strong>
</p>
</div>
<div class="block-content bg-black-op-5">
<p class="font-w600 text-white-op">
<i class="si si-clock mr-5"></i><br>Awal Absensi Sore
</p>
</div>
</a>
</div>
<div class="col-6 col-md-4 col-xl-2">
<a class="block block-transparent text-center bg-pulse" href="javascript:void(0)">
<div class="block-content">
<p class="font-size-h4 text-white">
<strong><?= $jam['akhirabsen_sore'] ?> WIB</strong>
</p>
</div>
<div class="block-content bg-black-op-5">
<p class="font-w600 text-white-op">
<i class="si si-clock mr-5"></i><br>Akhir Absensi Sore
</p>
</div>
</a>
</div>
<div class="col-6 col-md-4 col-xl-2">
<a class="block block-transparent text-center bg-pulse" href="javascript:void(0)">
<div class="block-content">
<p class="font-size-h4 text-white">
<strong><?= $jam['awalabsen_lembur'] ?> WIB</strong>
</p>
</div>
<div class="block-content bg-black-op-5">
<p class="font-w600 text-white-op">
<i class="si si-clock mr-5"></i><br>Awal Absensi Lembur
</p>
</div>
</a>
</div>
<div class="col-6 col-md-4 col-xl-2">
<a class="block block-transparent text-center bg-pulse" href="javascript:void(0)">
<div class="block-content">
<p class="font-size-h4 text-white">
<strong><?= $jam['akhirabsen_lembur'] ?> WIB</strong>
</p>
</div>
<div class="block-content bg-black-op-5">
<p class="font-w600 text-white-op">
<i class="si si-clock mr-5"></i><br>Akhir Absensi Lembur
</p>
</div>
</a>
</div>
<div class="col-6 col-md-4 col-xl-2">
<a class="block block-transparent text-center bg-pulse" href="javascript:void(0)">
<div class="block-content">
<p class="font-size-h4 text-white">
<strong><?= $jam['batasjam_lembur'] ?> WIB</strong>
</p>
</div>
<div class="block-content bg-black-op-5">
<p class="font-w600 text-white-op">
<i class="si si-clock mr-5"></i><br>Batsa Jam Lembur
</p>
</div>
</a>
</div>
<div class="col-6 col-md-4 col-xl-2">
<a class="block block-transparent text-center bg-warning" href="javascript:void(0)">
<div class="block-content">
<p class="font-size-h4 text-white">
<strong>Rp.<?= number_format($jam['uang_lembur']) ?>,-</strong>
</p>
</div>
<div class="block-content bg-black-op-5">
<p class="font-w600 text-white-op">
<i class="si si-clock mr-5"></i><br>Jumlah Uang Lembur
</p>
</div>
</a>
</div>
</div>
</div>
</div>
</main>
<!-- END Main Container -->
<!-- Footer -->
<footer id="page-footer" class="opacity-0">
<div class="content py-20 font-size-xs clearfix">
<div class="float-right">
Crafted with <i class="fa fa-heart text-pulse"></i> by <a class="font-w600" href="http://goo.gl/vNS3I" target="_blank">pixelcave</a>
</div>
<div class="float-left">
<a class="font-w600" href="https://goo.gl/po9Usv" target="_blank">Codebase 1.3</a> © <span class="js-year-copy">2017</span>
</div>
</div>
</footer>
<!-- END Footer -->
</div>
<!-- END Page Container -->
<file_sep>/qrcodegenerate/data.php
<?php
$data = $_GET['data'];
include('phpqrcode/qrlib.php');
$codeContents = base64_decode($data);
QRcode::png($codeContents, false, QR_ECLEVEL_L, 10);
?><file_sep>/kelola-absensi-cetak.php
<?php
include("koneksi.php");
include("session.php");
include("format-tgl.php");
$qy_pegawai = mysqli_query($connect, "SELECT * FROM pegawai, jabatan WHERE pegawai.nip = '$_SESSION[nip]' AND pegawai.jabatan = jabatan.id_jabatan");
$pegawai = mysqli_fetch_array($qy_pegawai);
?>
<div id="page-container" class="sidebar-inverse side-scroll page-header-fixed page-header-inverse main-content-boxed">
<!-- Header -->
<header id="page-header">
<!-- Header Content -->
<div class="content-header">
<!-- Left Section -->
<div class="content-header-section">
<!-- Logo -->
<div class="content-header-item">
<a class="link-effect font-w700 mr-5" href="dashboard-admin">
<i class="si si-fire text-primary"></i>
<span class="font-size-xl text-dual-primary-dark">Bank</span><span class="font-size-xl text-danger"> Wakaf</span>
</a>
</div>
<!-- END Logo -->
</div>
<!-- END Left Section -->
<!-- Middle Section -->
<div class="content-header-section d-none d-lg-block">
<!-- Header Navigation -->
<!--
Desktop Navigation, mobile navigation can be found in #sidebar
If you would like to use the same navigation in both mobiles and desktops, you can use exactly the same markup inside sidebar and header navigation ul lists
If your sidebar menu includes headings, they won't be visible in your header navigation by default
If your sidebar menu includes icons and you would like to hide them, you can add the class 'nav-main-header-no-icons'
-->
<ul class="nav-main-header">
<li>
<a href="dashboard-admin"><i class="si si-compass"></i>Dashboard</a>
</li>
<li>
<a href="kelola-jabatan"><i class="si si-wrench"></i>Kelola Jabatan</a>
</li>
<li>
<a href="kelola-pegawai"><i class="si si-users"></i>Kelola Pegawai</a>
</li>
<li>
<a class="active" href="kelola-absensi"><i class="si si-book-open"></i>Kelola Absesnsi</a>
</li>
<li>
<a href="setting-waktu"><i class="si si-settings"></i>Setting</a>
</li>
</ul>
<!-- END Header Navigation -->
</div>
<!-- END Middle Section -->
<!-- Right Section -->
<div class="content-header-section">
<!-- User Dropdown -->
<div class="btn-group" role="group">
<button type="button" class="btn btn-rounded btn-dual-secondary" id="page-header-user-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?= $pegawai['nama_pegawai'] ?><i class="fa fa-angle-down ml-5"></i>
</button>
<div class="dropdown-menu dropdown-menu-right min-width-150" aria-labelledby="page-header-user-dropdown">
<a class="dropdown-item" href="dashboard-pegawai">
<i class="si si-note mr-5"></i> Absensi
</a>
<a class="dropdown-item" href="profile-admin">
<i class="si si-note mr-5"></i> Profile Admin
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="keluar">
<i class="si si-logout mr-5"></i> Sign Out
</a>
</div>
</div>
<!-- END User Dropdown -->
</div>
<!-- END Right Section -->
</div>
<!-- END Header Content -->
</header>
<!-- END Header -->
<!-- Main Container -->
<main id="main-container">
<!-- Hero -->
<div class="bg-image" style="background-image: url('assets/img/photos/photo26@2x.jpg');">
<div class="bg-black-op-75">
<div class="content content-top content-full text-center">
<div class="py-20">
<h1 class="h2 font-w700 text-white mb-10">Kelola Absensi</h1>
<h2 class="h4 font-w400 text-white-op mb-0">Halaman untuk mengelola Absensi</h2>
</div>
</div>
</div>
</div>
<!-- END Hero -->
<!-- Page Content -->
<div class="content">
<div class="row gutters-tiny invisible" data-toggle="appear">
<!-- Row #5 -->
<!-- jabatan -->
<div class="col-sm-3 col-md-4 col-xl-4">
<a class="block block-link-shadow text-center bg-info" href="kelola-absensi">
<div class="block-content ribbon ribbon-bookmark ribbon-success ribbon-left">
<p class="mt-5">
<i class="si si-calendar fa-3x text-info-light"></i>
</p>
<p class="font-w600 text-info-light">Absensi Hari ini</p>
</div>
</a>
</div>
<!-- pegawai -->
<div class="col-sm-3 col-md-2 col-xl-2">
<a class="block block-link-shadow text-center bg-info" href="kelola-absensi-total">
<div class="block-content">
<p class="mt-5">
<i class="si si-book-open fa-3x text-info-light"></i>
</p>
<p class="font-w600 text-info-light">Absensi Total</p>
</div>
</a>
</div>
<!-- absensi -->
<!-- pegawai -->
<div class="col-sm-3 col-md-2 col-xl-2">
<a class="block block-link-shadow text-center bg-info" href="kelola-absensi-lembur">
<div class="block-content">
<p class="mt-5">
<i class="si si-book-open fa-3x text-info-light"></i>
</p>
<p class="font-w600 text-info-light">Data Lembur</p>
</div>
</a>
</div>
<!-- absensi -->
<div class="col-sm-3 col-md-4 col-xl-4">
<a class="block block-link-shadow text-center bg-primary" href="kelola-absensi-cetak">
<div class="block-content ribbon ribbon-bookmark ribbon-primary ribbon-left">
<p class="mt-5">
<i class="si si-printer text-info-light fa-3x"></i>
</p>
<p class="font-w600 text-info-light">Cetak Laporan</p>
</div>
</a>
</div>
<!-- END Row #5 -->
</div>
<div class="row gutters-tiny invisible" data-toggle="appear">
<div class="col-md-12">
<!-- Floating Labels -->
<div class="block">
<div class="block-header block-header-default">
<h3 class="block-title">Cetak Laporan</h3>
<div class="block-options">
<button type="button" class="btn-block-option">
<i class="si si-wrench"></i>
</button>
</div>
</div>
<div class="block-content">
<form action="cetak.php" method="post">
<div class="form-group row justify-content-center">
<div class="col-md-4">
<div class="form-material">
<input type="text" required class="js-datepicker form-control" name="atas" data-week-start="1" data-autoclose="true" data-today-highlight="true" data-date-format="yyyy-mm-dd" placeholder="Pilih tanggal awal">
<label for="example-datepicker4">Pilih tanggal</label>
</div>
</div>
<div class="col-md-2">
<div class="form-material">
<center><h6 class="block-title mt-2">s/d</h6></center>
</div>
</div>
<div class="col-md-4">
<div class="form-material">
<input type="text" required class="js-datepicker form-control" name="bawah" data-week-start="1" data-autoclose="true" data-today-highlight="true" data-date-format="yyyy-mm-dd" placeholder="Pilih tanggal akhir">
<label for="example-datepicker4">Pilih tanggal</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-alt-primary"> <i class="fa fa-print"></i> Cetak</button>
</div>
</div>
</form>
</div>
</div>
<!-- END Floating Labels -->
</div>
</div>
</div>
<!-- END Page Content -->
</main>
<!-- END Main Container -->
<!-- Footer -->
<footer id="page-footer" class="opacity-0">
<div class="content py-20 font-size-xs clearfix">
<div class="float-right">
Crafted with <i class="fa fa-heart text-pulse"></i> by <a class="font-w600" href="http://goo.gl/vNS3I" target="_blank">pixelcave</a>
</div>
<div class="float-left">
<a class="font-w600" href="https://goo.gl/po9Usv" target="_blank">Codebase 1.3</a> © <span class="js-year-copy">2017</span>
</div>
</div>
</footer>
<!-- END Footer -->
</div>
<file_sep>/kelola-jabatan.php
<?php
include("koneksi.php");
include("session.php");
include("format-tgl.php");
$qy_pegawai = mysqli_query($connect, "SELECT * FROM pegawai, jabatan WHERE pegawai.nip = '$_SESSION[nip]' AND pegawai.jabatan = jabatan.id_jabatan");
$pegawai = mysqli_fetch_array($qy_pegawai);
?>
<div id="page-container" class="sidebar-inverse side-scroll page-header-fixed page-header-inverse main-content-boxed">
<!-- Header -->
<header id="page-header">
<!-- Header Content -->
<div class="content-header">
<!-- Left Section -->
<div class="content-header-section">
<!-- Logo -->
<div class="content-header-item">
<a class="link-effect font-w700 mr-5" href="dashboard-admin">
<i class="si si-fire text-primary"></i>
<span class="font-size-xl text-dual-primary-dark">Bank</span><span class="font-size-xl text-danger"> Wakaf</span>
</a>
</div>
<!-- END Logo -->
</div>
<!-- END Left Section -->
<!-- Middle Section -->
<div class="content-header-section d-none d-lg-block">
<!-- Header Navigation -->
<!--
Desktop Navigation, mobile navigation can be found in #sidebar
If you would like to use the same navigation in both mobiles and desktops, you can use exactly the same markup inside sidebar and header navigation ul lists
If your sidebar menu includes headings, they won't be visible in your header navigation by default
If your sidebar menu includes icons and you would like to hide them, you can add the class 'nav-main-header-no-icons'
-->
<ul class="nav-main-header">
<li>
<a href="dashboard-admin"><i class="si si-compass"></i>Dashboard</a>
</li>
<li>
<a class="active" href="kelola-jabatan"><i class="si si-wrench"></i>Kelola Jabatan</a>
</li>
<li>
<a href="kelola-pegawai"><i class="si si-users"></i>Kelola Pegawai</a>
</li>
<li>
<a href="kelola-absensi"><i class="si si-book-open"></i>Kelola Absensi</a>
</li>
<li>
<a href="setting-waktu"><i class="si si-settings"></i>Setting</a>
</li>
</ul>
<!-- END Header Navigation -->
</div>
<!-- END Middle Section -->
<!-- Right Section -->
<div class="content-header-section">
<!-- User Dropdown -->
<div class="btn-group" role="group">
<button type="button" class="btn btn-rounded btn-dual-secondary" id="page-header-user-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?= $pegawai['nama_pegawai'] ?><i class="fa fa-angle-down ml-5"></i>
</button>
<div class="dropdown-menu dropdown-menu-right min-width-150" aria-labelledby="page-header-user-dropdown">
<a class="dropdown-item" href="dashboard-pegawai">
<i class="si si-note mr-5"></i> Absensi
</a>
<a class="dropdown-item" href="profile-admin">
<i class="si si-note mr-5"></i> Profile Admin
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="keluar">
<i class="si si-logout mr-5"></i> Sign Out
</a>
</div>
</div>
<!-- END User Dropdown -->
</div>
<!-- END Right Section -->
</div>
<!-- END Header Content -->
</header>
<!-- END Header -->
<!-- Main Container -->
<main id="main-container">
<!-- Hero -->
<div class="bg-image" style="background-image: url('assets/img/photos/photo26@2x.jpg');">
<div class="bg-black-op-75">
<div class="content content-top content-full text-center">
<div class="py-20">
<h1 class="h2 font-w700 text-white mb-10">Kelola Jabatan</h1>
<h2 class="h4 font-w400 text-white-op mb-0">Halaman untuk mengelola Jabatan</h2>
</div>
</div>
</div>
</div>
<!-- END Hero -->
<!-- Page Content -->
<div class="content">
<div class="row gutters-tiny invisible" data-toggle="appear">
<div class="col-md-12">
<!-- Floating Labels -->
<div class="block">
<div class="block-header block-header-default">
<h3 class="block-title">Tambah Jabatan</h3>
<div class="block-options">
<button type="button" class="btn-block-option">
<i class="si si-wrench"></i>
</button>
</div>
</div>
<?php
// mencari kode barang dengan nilai paling besar
$query = "SELECT max(id_jabatan) as maxKode FROM jabatan";
$hasil = mysqli_query($connect,$query);
$data = mysqli_fetch_array($hasil);
$kodeBarang = $data['maxKode'];
$noUrut = (int) substr($kodeBarang, 3, 3);
$noUrut++;
$char = "BW";
$kodeBarang = $char . sprintf("%04s", $noUrut);
?>
<div class="block-content">
<form action="simpan-jabatan.php" method="post">
<div class="form-group row">
<div class="col-md-4">
<div class="form-material floating">
<input type="text" value="<?= $kodeBarang ?>" readonly class="form-control" id="material-help2" name="id">
<label for="material-help2">Id Jabatan</label>
<div class="form-text text-muted text-right">Silahkan Masukan Kode Jabatan</div>
</div>
</div>
<div class="col-md-8">
<div class="form-material floating">
<input type="text" class="form-control" id="material-help2" name="nama">
<label for="material-help2">Nama Jabatan</label>
<div class="form-text text-muted text-right">Silahkan Masukan Nama Jabatan</div>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-alt-primary">Tambah</button>
</div>
</div>
</form>
</div>
</div>
<!-- END Floating Labels -->
</div>
<!-- Dynamic Table Full -->
<div class="block col-12">
<div class="block-header block-header-default">
<h3 class="block-title">Data Jabatan</h3>
</div>
<div class="block-content block-content-full">
<!-- DataTables init on table by adding .js-dataTable-full class, functionality initialized in js/pages/be_tables_datatables.js -->
<table class="table table-bordered table-responsive table-striped table-vcenter js-dataTable-full">
<thead>
<tr>
<th class="text-center"></th>
<th>Id Jabatan</th>
<th>Nama Jabatan</th>
<th class="text-center" style="width: 5%;"></th>
<th class="text-center" style="width: 5%;"></th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$qy_jabatan = mysqli_query($connect, "SELECT * FROM jabatan");
while ($jabatan = mysqli_fetch_array($qy_jabatan)) {
?>
<tr>
<td><?= $no; ?></td>
<td><?= $jabatan['id_jabatan'] ?></td>
<td><?= $jabatan['nama_jabatan'] ?></td>
<td class="text-center">
<form class="" action="edit-jabatan" method="post">
<input type="hidden" name="id" value="<?= $jabatan['id_jabatan'] ?>">
<input type="hidden" name="nama" value="<?= $jabatan['nama_jabatan'] ?>">
<button type="submit" class="btn btn-md btn-secondary" data-toggle="tooltip" title="Edit">
<i class="si si-note"></i>
</button>
</form>
</td>
<td>
<form class="" action="hapus-jabatan.php" method="post">
<input type="hidden" name="id" value="<?= $jabatan['id_jabatan'] ?>">
<button type="submit" class="btn btn-md btn-secondary" data-toggle="tooltip" title="Hapus">
<i class="si si-trash"></i>
</button>
</form>
</td>
</tr>
<?php $no++; } ?>
</tbody>
</table>
</div>
</div>
<!-- END Dynamic Table Full -->
</div>
</div>
<!-- END Page Content -->
</main>
<!-- END Main Container -->
<!-- Footer -->
<footer id="page-footer" class="opacity-0">
<div class="content py-20 font-size-xs clearfix">
<div class="float-right">
Crafted with <i class="fa fa-heart text-pulse"></i> by <a class="font-w600" href="http://goo.gl/vNS3I" target="_blank">pixelcave</a>
</div>
<div class="float-left">
<a class="font-w600" href="https://goo.gl/po9Usv" target="_blank">Codebase 1.3</a> © <span class="js-year-copy">2017</span>
</div>
</div>
</footer>
<!-- END Footer -->
</div>
<file_sep>/simpan-pegawai.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="assets/js/plugins/sweetalert2/es6-promise.auto.min.js"></script>
<script src="assets/js/plugins/sweetalert2/sweetalert2.min.js"></script>
<link rel="stylesheet" href="assets/js/plugins/sweetalert2/sweetalert2.min.css">
</head>
<body>
</body>
</html>
<?php
include('koneksi.php');
// include('session.php');
function antiinjection($data){
$filter_sql = stripslashes(strip_tags(htmlspecialchars($data,ENT_QUOTES)));
return $filter_sql;
}
$nip = antiinjection($_POST['nip']);
$nama = antiinjection($_POST['nama']);
$tmp_lahir = antiinjection($_POST['tmp_lahir']);
$tgl_lahir = antiinjection($_POST['tgl_lahir']);
$jk = antiinjection($_POST['jk']);
$alamat = antiinjection($_POST['alamat']);
$jabatan = antiinjection($_POST['jabatan']);
$salt ='<PASSWORD>';
$pass = md5($salt . antiinjection($_POST['nip']));
if($_FILES['foto']['name']!=''){
$target_dir = "assets/img/avatars/";
$target_file = $target_dir . basename($_FILES["foto"]["name"]);
$fotobaru = $_FILES["foto"]["name"];
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check file size
if ($_FILES["foto"]["size"] > 2000000) {
echo '<script language="javascript">swal("Simpan gagal!", "Gambar tidak boleh lebih dari 2MB", "warning").then(() => { window.location="kelola-pegawai"; });</script>';
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
echo '<script language="javascript">swal("Simpan gagal!", "Gambar hanya boleh berupa JPG, PNG atau JPEG", "warning").then(() => { window.location="kelola-pegawai"; });</script>';
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo '<script language="javascript">swal("Simpan gagal!", "Foto gagal diupload!", "warning").then(() => { window.location="kelola-pegawai"; });</script>';
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["foto"]["tmp_name"], $target_file)) {
} else {
echo '<script language="javascript">swal("Simpan gagal!", "Foto gagal diupload!", "warning").then(() => { window.location="kelola-pegawai"; });</script>';
}
}
$cek = mysqli_num_rows(mysqli_query($connect, "SELECT * FROM pengguna WHERE nip = '$nip'"));
if ($cek > 0) {
echo '<script language="javascript">swal("Simpan gagal!", "Data Pegawai Sudah Ada!", "warning").then(() => { window.location="kelola-pegawai"; });</script>';
}else{
mysqli_query($connect, "INSERT INTO pengguna (nip, password, hak_akses)
VALUES ('$nip','$pass','<PASSWORD>')");
mysqli_query($connect, "INSERT INTO pegawai (nip, nama_pegawai, alamat, jk, tmp_lahir, tgl_lahir, foto, jabatan)
VALUES ('$nip','$nama','$alamat','$jk','$tmp_lahir','$tgl_lahir','$fotobaru','$jabatan')");
echo '<script language="javascript">swal("Simpan berhasil!", "Data Pegawai tersimpan", "success").then(() => { window.location="kelola-pegawai"; });</script>';
}
}else{
$cek = mysqli_num_rows(mysqli_query($connect, "SELECT * FROM pengguna WHERE nip = '$nip'"));
if ($cek > 0) {
echo '<script language="javascript">swal("Simpan gagal!", "Data Pegawai Sudah Ada!", "warning").then(() => { window.location="kelola-pegawai"; });</script>';
}else{
mysqli_query($connect, "INSERT INTO pengguna (nip, password, hak_akses)
VALUES ('$nip','$pass','<PASSWORD>')");
mysqli_query($connect, "INSERT INTO pegawai (nip, nama_pegawai, alamat, jk, tmp_lahir, tgl_lahir, jabatan)
VALUES ('$nip','$nama','$alamat','$jk','$tmp_lahir','$tgl_lahir','$jabatan')");
echo '<script language="javascript">swal("Simpan berhasil!", "Data Pegawai tersimpan", "success").then(() => { window.location="kelola-pegawai"; });</script>';
}
}
?>
<file_sep>/qrcodegenerate/koneksi.php
<?php
$database_username = 'root';
$database_password = '';
$pdo_conn = new PDO( 'mysql:host=localhost;dbname=absensi', $database_username, $database_password );
$hostname = "localhost";
$username = "root";
$password = "";
$database = "absensi";
$connect = mysqli_connect($hostname, $username, $password, $database);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
<file_sep>/edit-waktu.php
<?php
include("koneksi.php");
include("session.php");
include("format-tgl.php");
$qy_pegawai = mysqli_query($connect, "SELECT * FROM pegawai, jabatan WHERE pegawai.nip = '$_SESSION[nip]' AND pegawai.jabatan = jabatan.id_jabatan");
$pegawai = mysqli_fetch_array($qy_pegawai);
?>
<div id="page-container" class="sidebar-inverse side-scroll page-header-fixed page-header-inverse main-content-boxed">
<!-- Header -->
<header id="page-header">
<!-- Header Content -->
<div class="content-header">
<!-- Left Section -->
<div class="content-header-section">
<!-- Logo -->
<div class="content-header-item">
<a class="link-effect font-w700 mr-5" href="dashboard-admin">
<i class="si si-fire text-primary"></i>
<span class="font-size-xl text-dual-primary-dark">Bank</span><span class="font-size-xl text-danger"> Wakaf</span>
</a>
</div>
<!-- END Logo -->
</div>
<!-- END Left Section -->
<!-- Middle Section -->
<div class="content-header-section d-none d-lg-block">
<!-- Header Navigation -->
<!--
Desktop Navigation, mobile navigation can be found in #sidebar
If you would like to use the same navigation in both mobiles and desktops, you can use exactly the same markup inside sidebar and header navigation ul lists
If your sidebar menu includes headings, they won't be visible in your header navigation by default
If your sidebar menu includes icons and you would like to hide them, you can add the class 'nav-main-header-no-icons'
-->
<ul class="nav-main-header">
<li>
<a href="dashboard-admin"><i class="si si-compass"></i>Dashboard</a>
</li>
<li>
<a href="kelola-jabatan"><i class="si si-wrench"></i>Kelola Jabatan</a>
</li>
<li>
<a href="kelola-pegawai"><i class="si si-users"></i>Kelola Pegawai</a>
</li>
<li>
<a href="kelola-absensi"><i class="si si-book-open"></i>Kelola Absensi</a>
</li>
<li>
<a class="active" href="setting-waktu"><i class="si si-settings"></i>Setting</a>
</li>
</ul>
<!-- END Header Navigation -->
</div>
<!-- END Middle Section -->
<!-- Right Section -->
<div class="content-header-section">
<!-- User Dropdown -->
<div class="btn-group" role="group">
<button type="button" class="btn btn-rounded btn-dual-secondary" id="page-header-user-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?= $pegawai['nama_pegawai'] ?><i class="fa fa-angle-down ml-5"></i>
</button>
<div class="dropdown-menu dropdown-menu-right min-width-150" aria-labelledby="page-header-user-dropdown">
<a class="dropdown-item" href="profile-admin">
<i class="si si-note mr-5"></i> Profile Admin
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="keluar">
<i class="si si-logout mr-5"></i> Sign Out
</a>
</div>
</div>
<!-- END User Dropdown -->
</div>
<!-- END Right Section -->
</div>
<!-- END Header Content -->
</header>
<!-- END Header -->
<!-- Main Container -->
<main id="main-container">
<!-- Hero -->
<div class="bg-primary">
<div class="bg-pattern bg-black-op-25" style="background-image: url('assets/img/various/bg-pattern.png');">
<div class="content content-top text-center">
<div class="py-5 ">
<h1 class="font-w700 text-white mb-50">Atur Waktu Absensi</h1>
</div>
</div>
</div>
</div>
<!-- END Hero -->
<?php
$jam = mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM jam"));
?>
<div class="container block-content block-content-full mt-30">
<div class="row justify-content-center">
<div class="col-md-6 block block-themed">
<div class="block-header bg-gd-sun">
<h3 class="block-title">Edit Waktu Absensi</h3>
</div>
<div class="block-content">
<form action="update-jam.php" method="post">
<table class="table table-responsive">
<tr>
<th><label for="side-overlay-profile-name">Awal Absensi Pagi</label></th>
<td>
<div class="input-group">
<input type="hidden" class="form-control" name="id" value="<?= $jam['id_jam']; ?>">
<input type="text" class="form-control" id="single-input" name="awal-pagi" value="<?= $jam['awalabsen_pagi']; ?>">
<span class="input-group-addon"><i class="si si-clock"></i></span>
</div>
</td>
</tr>
<tr>
<th><label for="side-overlay-profile-name">Akhir Absensi Pagi</label></th>
<td>
<div class="input-group">
<input type="text" class="form-control" id="single-input2" name="akhir-pagi" value="<?= $jam['akhirabsen_pagi']; ?>">
<span class="input-group-addon"><i class="si si-clock"></i></span>
</div>
</td>
</tr>
<tr>
<th><label for="side-overlay-profile-name">Awal Absensi Sore</label></th>
<td>
<div class="input-group">
<input type="text" class="form-control" id="single-input3" name="awal-sore" value="<?= $jam['awalabsen_sore']; ?>">
<span class="input-group-addon"><i class="si si-clock"></i></span>
</div>
</td>
</tr>
<tr>
<th><label for="side-overlay-profile-name">Akhir Absensi Sore</label></th>
<td>
<div class="input-group">
<input type="text" class="form-control" id="single-input4" name="akhir-sore" value="<?= $jam['akhirabsen_sore']; ?>">
<span class="input-group-addon"><i class="si si-clock"></i></span>
</div>
</td>
</tr>
<tr>
<th><label for="side-overlay-profile-name">Awal Absensi Lembur</label></th>
<td>
<div class="input-group">
<input type="text" class="form-control" id="single-input5" name="lembur" value="<?= $jam['awalabsen_lembur']; ?>">
<span class="input-group-addon"><i class="si si-clock"></i></span>
</div>
</td>
</tr>
<tr>
<th><label for="side-overlay-profile-name">Akhir Absensi Lembur</label></th>
<td>
<div class="input-group">
<input type="text" class="form-control" id="single-input6" name="akhir-lembur" value="<?= $jam['awalabsen_lembur']; ?>">
<span class="input-group-addon"><i class="si si-clock"></i></span>
</div>
</td>
</tr>
<tr>
<th><label for="side-overlay-profile-name">Batas Jam Lembur</label></th>
<td>
<div class="input-group">
<input type="text" class="form-control" id="single-input7" name="batas-lembur" value="<?= $jam['batasjam_lembur']; ?>">
<span class="input-group-addon"><i class="si si-clock"></i></span>
</div>
</td>
</tr>
<tr>
<th><label for="side-overlay-profile-name">Jumlah Uang Lembur Perjam</label></th>
<td>
<div class="input-group">
<input type="number" class="form-control" id="" name="uang-lembur" value="<?= $jam['uang_lembur']; ?>">
</div>
</td>
</tr>
</table>
<div class="form-group row">
<div class="col-6">
<button type="submit" class="btn btn-block btn-alt-primary">
<i class="fa fa-refresh mr-5"></i> Update
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</main>
<!-- END Main Container -->
<!-- Footer -->
<footer id="page-footer" class="opacity-0">
<div class="content py-20 font-size-xs clearfix">
<div class="float-right">
Crafted with <i class="fa fa-heart text-pulse"></i> by <a class="font-w600" href="http://goo.gl/vNS3I" target="_blank">pixelcave</a>
</div>
<div class="float-left">
<a class="font-w600" href="https://goo.gl/po9Usv" target="_blank">Codebase 1.3</a> © <span class="js-year-copy">2017</span>
</div>
</div>
</footer>
<!-- END Footer -->
</div>
<!-- END Page Container -->
<file_sep>/kelola-absensi-lembur.php
<?php
include("koneksi.php");
include("session.php");
include("format-tgl.php");
$qy_pegawai = mysqli_query($connect, "SELECT * FROM pegawai, jabatan WHERE pegawai.nip = '$_SESSION[nip]' AND pegawai.jabatan = jabatan.id_jabatan");
$pegawai = mysqli_fetch_array($qy_pegawai);
$jam = mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM jam WHERE id_jam = 1"));
?>
<div id="page-container" class="sidebar-inverse side-scroll page-header-fixed page-header-inverse main-content-boxed">
<!-- Header -->
<header id="page-header">
<!-- Header Content -->
<div class="content-header">
<!-- Left Section -->
<div class="content-header-section">
<!-- Logo -->
<div class="content-header-item">
<a class="link-effect font-w700 mr-5" href="dashboard-admin">
<i class="si si-fire text-primary"></i>
<span class="font-size-xl text-dual-primary-dark">Bank</span><span class="font-size-xl text-danger"> Wakaf</span>
</a>
</div>
<!-- END Logo -->
</div>
<!-- END Left Section -->
<!-- Middle Section -->
<div class="content-header-section d-none d-lg-block">
<!-- Header Navigation -->
<!--
Desktop Navigation, mobile navigation can be found in #sidebar
If you would like to use the same navigation in both mobiles and desktops, you can use exactly the same markup inside sidebar and header navigation ul lists
If your sidebar menu includes headings, they won't be visible in your header navigation by default
If your sidebar menu includes icons and you would like to hide them, you can add the class 'nav-main-header-no-icons'
-->
<ul class="nav-main-header">
<li>
<a href="dashboard-admin"><i class="si si-compass"></i>Dashboard</a>
</li>
<li>
<a href="kelola-jabatan"><i class="si si-wrench"></i>Kelola Jabatan</a>
</li>
<li>
<a href="kelola-pegawai"><i class="si si-users"></i>Kelola Pegawai</a>
</li>
<li>
<a class="active" href="kelola-absensi"><i class="si si-book-open"></i>Kelola Absesnsi</a>
</li>
<li>
<a href="setting-waktu"><i class="si si-settings"></i>Setting</a>
</li>
</ul>
<!-- END Header Navigation -->
</div>
<!-- END Middle Section -->
<!-- Right Section -->
<div class="content-header-section">
<!-- User Dropdown -->
<div class="btn-group" role="group">
<button type="button" class="btn btn-rounded btn-dual-secondary" id="page-header-user-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?= $pegawai['nama_pegawai'] ?><i class="fa fa-angle-down ml-5"></i>
</button>
<div class="dropdown-menu dropdown-menu-right min-width-150" aria-labelledby="page-header-user-dropdown">
<a class="dropdown-item" href="dashboard-pegawai">
<i class="si si-note mr-5"></i> Absensi
</a>
<a class="dropdown-item" href="profile-admin">
<i class="si si-note mr-5"></i> Profile Admin
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="keluar">
<i class="si si-logout mr-5"></i> Sign Out
</a>
</div>
</div>
<!-- END User Dropdown -->
</div>
<!-- END Right Section -->
</div>
<!-- END Header Content -->
</header>
<!-- END Header -->
<!-- Main Container -->
<main id="main-container">
<!-- Hero -->
<div class="bg-image" style="background-image: url('assets/img/photos/photo2<EMAIL>');">
<div class="bg-black-op-75">
<div class="content content-top content-full text-center">
<div class="py-20">
<h1 class="h2 font-w700 text-white mb-10">Kelola Absensi</h1>
<h2 class="h4 font-w400 text-white-op mb-0">Halaman untuk mengelola Absensi</h2>
</div>
</div>
</div>
</div>
<!-- END Hero -->
<!-- Page Content -->
<div class="content">
<div class="row gutters-tiny invisible" data-toggle="appear">
<!-- Row #5 -->
<!-- jabatan -->
<div class="col-sm-3 col-md-4 col-xl-4">
<a class="block block-link-shadow text-center bg-info" href="kelola-absensi">
<div class="block-content ribbon ribbon-bookmark ribbon-success ribbon-left">
<p class="mt-5">
<i class="si si-calendar fa-3x text-info-light"></i>
</p>
<p class="font-w600 text-info-light">Absensi Hari ini</p>
</div>
</a>
</div>
<!-- pegawai -->
<div class="col-sm-3 col-md-2 col-xl-2">
<a class="block block-link-shadow text-center bg-info" href="kelola-absensi-total">
<div class="block-content">
<p class="mt-5">
<i class="si si-book-open fa-3x text-info-light"></i>
</p>
<p class="font-w600 text-info-light">Absensi Total</p>
</div>
</a>
</div>
<!-- absensi -->
<!-- pegawai -->
<div class="col-sm-3 col-md-2 col-xl-2">
<a class="block block-link-shadow text-center bg-primary" href="kelola-absensi-lembur">
<div class="block-content">
<p class="mt-5">
<i class="si si-book-open fa-3x text-info-light"></i>
</p>
<p class="font-w600 text-info-light">Data Lembur</p>
</div>
</a>
</div>
<!-- absensi -->
<div class="col-sm-3 col-md-4 col-xl-4">
<a class="block block-link-shadow text-center bg-info" href="kelola-absensi-cetak">
<div class="block-content ribbon ribbon-bookmark ribbon-primary ribbon-left">
<p class="mt-5">
<i class="si si-printer text-info-light fa-3x"></i>
</p>
<p class="font-w600 text-info-light">Cetak Laporan</p>
</div>
</a>
</div>
<!-- END Row #5 -->
</div>
<div class="row gutters-tiny invisible" data-toggle="appear">
<div class="col-md-12">
<div class="block">
<div class="block-content block-content-full">
<!-- DataTables init on table by adding .js-dataTable-full class, functionality initialized in js/pages/be_tables_datatables.js -->
<table class="table table-bordered table-responsive table-striped table-vcenter js-dataTable-full">
<thead>
<tr>
<th class="text-center"></th>
<th>NIP</th>
<th>Nama</th>
<th>Tanggal</th>
<th width="100px">Jam</th>
<th>Kepentingan</th>
<th width="150px">ACC</th>
<th width="50px"></th>
</tr>
</thead>
<tbody id="loadDataLembur">
<div id="pesan">
</div>
<?php
$qy_lembur = $connect->query("SELECT * FROM pengajuan_lembur, pegawai WHERE pengajuan_lembur.nip = pegawai.nip AND pengajuan_lembur.arsip = 'Tidak'");
$no = 1;
while($j = $qy_lembur->fetch_array()){ ?>
<tr>
<td><?= $no; ?></td>
<td><?= $j['nip']; ?></td>
<td><?= $j['nama_pegawai']; ?></td>
<td><?= $j['tgl']; ?></td>
<td><?= $j['waktu']; ?> WIB</td>
<td><?= $j['kepentingan']; ?></td>
<td>
<input type="hidden" name="uang" value="<?= $jam['uang_lembur'] ?>">
<input type="hidden" name="id_pengajuan" value="<?= $j['id_lembur'] ?>">
<input type="hidden" name="wkt" value="<?= $j['waktu'] ?>">
<input type="hidden" name="absen" value="<?= $j['id_absensi'] ?>">
<select class="form-control" name="acc">
<option value="">Pilih</option>
<option value="Ya">Terima</option>
<option value="Tidak">Tolak</option>
</select>
</td>
<td><button type="button" onclick="acc()" class="btn btn-rounded btn-primary min-width-125 mb-10">Kirim</button></td>
</tr>
<?php $no++; } ?>
</tbody>
</table>
</div>
</div>
<!-- Floating Labels -->
<div class="block">
<div class="block-header block-header-default">
<h3 class="block-title">Data Lembur</h3>
<div class="block-options">
<button type="button" class="btn-block-option">
<i class="si si-wrench"></i>
</button>
</div>
</div>
<div class="block-content">
<form class="" enctype="multipart/form-data" action="" method="post">
<div class="form-group row justify-content-center">
<div class="col-md-4">
<div class="form-material">
<select class="form-control" name="bulan" id="bulan">
<option value="">Pilih Bulan</option>
<option value="1">Januari</option>
<option value="2">Februari</option>
<option value="3">Maret</option>
<option value="4">April</option>
<option value="5">Mei</option>
<option value="6">Juni</option>
<option value="7">Juli</option>
<option value="8">Agustus</option>
<option value="9">September</option>
<option value="10">Oktober</option>
<option value="11">November</option>
<option value="12">Desember</option>
</select>
<label for="example-datepicker4">Pilih bulan</label>
</div>
</div>
<div class="col-md-2">
<div class="form-material">
<select class="form-control" name="tahun" >
<option value="">Pilih Tahun</option>
<?php
$a= 2010;
$b= date('Y');
for($i=$b; $a<=$i; $i--){
?>
<option value="<?= $i; ?>"><?= $i; ?></option>
<?php } ?>
</select>
<label for="example-datepicker4">Pilih Tahun</label>
</div>
</div>
<div class="col-md-4">
<div class="form-material">
<button type="submit" name="search" id="search1" class="btn btn-alt-primary">Pilih</button>
</div>
</div>
</div>
</form>
</div>
</div>
<!-- END Floating Labels -->
</div>
<!-- Dynamic Table Full -->
<div class="block col-12">
<div class="block-header block-header-default">
<?php
if(isset($_POST['search'])){
?>
<h3 class="block-title">Data Lembur <?= bulan($_POST['bulan']); ?></h3>
<?php }else{ ?>
<h3 class="block-title">Data Lembur Total</h3>
<?php } ?>
</div>
<div class="block-content block-content-full">
<!-- DataTables init on table by adding .js-dataTable-full class, functionality initialized in js/pages/be_tables_datatables.js -->
<table class="table table-bordered table-responsive table-striped table-vcenter js-dataTable-full">
<thead>
<tr>
<th class="text-center"></th>
<th>NIP</th>
<th>Bulan</th>
<th>Nama</th>
<th>Absen Lembur</th>
<th>Jumlah Lembur</th>
<th>Uang Lembur</th>
<!-- <th></th> -->
</tr>
</thead>
<tbody>
<?php
if(isset($_POST['search'])){
$que = mysqli_query($connect, "SELECT * FROM absensi, pegawai WHERE absensi.nip = pegawai.nip AND absensi.absen_lembur != '' AND month(absensi.tgl_absen) = '$_POST[bulan]' AND year(absensi.tgl_absen) = '$_POST[tahun]' ORDER BY absensi.id_absensi DESC");
$no = 1; while($jk = mysqli_fetch_array($que)){ ?>
<tr>
<td><?= $no; ?></td>
<td><?= $jk['nip']; ?></td>
<td><?= indonesian_date($jk['tgl_absen']); ?></td>
<td><?= $jk['nama_pegawai']; ?></td>
<td><?= $jk['absen_lembur']; ?> WIB</td>
<td><?= $jk['jml_lembur']; ?> Jam</td>
<td>Rp<?= number_format($jk['uang_lembur']); ?>,-</td>
</tr>
<?php $no++; } ?>
<?php }else {
$que = mysqli_query($connect, "SELECT * FROM absensi, pegawai WHERE absensi.nip = pegawai.nip AND absensi.absen_lembur != '' ORDER BY absensi.id_absensi DESC");
$no = 1; while($jk = mysqli_fetch_array($que)){
?>
<tr>
<td><?= $no; ?></td>
<td><?= $jk['nip']; ?></td>
<td><?= indonesian_date($jk['tgl_absen']); ?></td>
<td><?= $jk['nama_pegawai']; ?></td>
<td><?= $jk['absen_lembur']; ?> WIB</td>
<td><?= $jk['jml_lembur']; ?> Jam</td>
<td>Rp<?= number_format($jk['uang_lembur']); ?>,-</td>
</tr>
<?php $no++; } } ?>
</tbody>
</table>
</div>
</div>
<!-- END Dynamic Table Full -->
</div>
</div>
<!-- END Page Content -->
</main>
<!-- END Main Container -->
<!-- Footer -->
<footer id="page-footer" class="opacity-0">
<div class="content py-20 font-size-xs clearfix">
<div class="float-right">
Crafted with <i class="fa fa-heart text-pulse"></i> by <a class="font-w600" href="http://goo.gl/vNS3I" target="_blank">pixelcave</a>
</div>
<div class="float-left">
<a class="font-w600" href="https://goo.gl/po9Usv" target="_blank">Codebase 1.3</a> © <span class="js-year-copy">2017</span>
</div>
</div>
</footer>
<!-- END Footer -->
</div>
<script src="assets/js/core/jquery.min.js"></script>
<script type="text/javascript">
function myFunction() {
location.reload();
}
function acc() {
var absensi = $("[name='absen']").val();
var acc = $("[name='acc']").val();
var id_pengajuan = $("[name='id_pengajuan']").val();
var wkt = $("[name='wkt']").val();
var uang = $("[name='uang']").val();
$.ajax({
type : "POST",
data : "absensi="+absensi+"&acc="+acc+"&id_pengajuan="+id_pengajuan+"&wkt="+wkt+"&uang="+uang,
url : "acc.php",
success : function(result) {
var resultObj = JSON.parse(result);
$("#pesan").html(resultObj.message);
}
});
}
</script>
<file_sep>/update-jabatan.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="assets/js/plugins/sweetalert2/es6-promise.auto.min.js"></script>
<script src="assets/js/plugins/sweetalert2/sweetalert2.min.js"></script>
<link rel="stylesheet" href="assets/js/plugins/sweetalert2/sweetalert2.min.css">
</head>
<body>
</body>
</html>
<?php
include "koneksi.php";
/*--------------------------------------------------------------------------*/
/*---------------------------- ANTI XSS & SQL INJECTION -------------------------------*/
function antiinjection($data){
$filter_sql = stripslashes(strip_tags(htmlspecialchars($data,ENT_QUOTES)));
return $filter_sql;
}
$id_baru = antiinjection($_POST['id']);
$id = antiinjection($_POST['id_lama']);
$nama = antiinjection($_POST['nama']);
$cek_user=mysqli_num_rows(mysqli_query($connect, "SELECT * FROM jabatan WHERE id_jabatan = '$id'"));
if ($cek_user > 0) {
mysqli_query($connect, "UPDATE `jabatan` SET `id_jabatan` = '$id_baru', `nama_jabatan` = '$nama' WHERE `id_jabatan` = '$id'");
echo '<script language="javascript">swal("", "Jabatan berhasil dirubah!", "success").then(() => { window.location="kelola-jabatan"; });</script>';
} else {
echo '<script language="javascript">swal("", "Jabatan tidak ditemukan!", "error").then(() => { window.history.back(); });</script>';
}
?>
<file_sep>/tampil-lembur.php
<?php
$qy_lembur = $connect->query("SELECT * FROM pengajuan_lembur, pegawai WHERE pengajuan_lembur.nip = pegawai.nip");
$result = array();
while ($fetchData = $qy_lembur->fetch_assoc()) {
$result[] = $fetchData;
}
echo json_encode($result);
?>
<file_sep>/qrcodegenerate/parameter.php
<?php
$data = base64_encode($_POST['data']);
echo '<center><img src="http://'.$_SERVER['SERVER_NAME'].'/qrcodegenerate/data.php?data='.$data.'" /></center>';
?>
<file_sep>/qrcodegenerate/qr.php
<!DOCTYPE html>
<html>
<head>
<title>qr code</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY> crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
// session_start();
include("koneksi.php");
include("session.php");
$sql=mysqli_fetch_array(mysqli_query($connect, "SELECT * FROM pengguna WHERE nip='$_SESSION[nip]'"));
// echo $sql['device'] . "<br>";
// echo $_SERVER['HTTP_USER_AGENT'];
$qy_pegawai = mysqli_query($connect, "SELECT * FROM pengguna WHERE nip = '$_SESSION[nip]'");
?>
<div class="wrapper">
<div class="container content">
<div class="row">
<div class="col-xs-12 col-md-12">
<?php
$str = 'abcdefghijklmnopqrstuvwxyz1234567891011';
$shuffled = str_shuffle($str);
mysqli_query($connect, "UPDATE pengguna SET kode_qrcode = '$shuffled' WHERE nip = '$_SESSION[nip]'");
?>
<input type="hidden" class="form-control" id="data" value="<?= $shuffled; ?>" placeholder="Free text for share">
<center><h3 class="header-h3"><center>Qr Code Absen</h3><center>
<a class="dropdown-item" href="logout.php">
<i class="si si-logout mr-5"></i> Sign Out
</a>
<input type="hidden" class="form-control" id="hiddendata">
<div id="hasil"></div>
</div><!--<div class="col-xs-12 col-md-6">-->
</div><!--row-->
</div><!-- container content-->
</div><!--wrapper-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" integrity="sha256-Sk3nkD6mLTMOF0EOpNtsIry+s1CsaqQC1rVLTAy+0yc= <KEY> crossorigin="anonymous"></script>
<script type="text/javascript">
setTimeout(function(){
window.location.reload(1);
}, 15000);
$( document ).ready(function() {
if($("#data").val()!=''){
$('#hiddendata').val($("#data").val());
var formData = {data:$("#hiddendata").val()};
getdata(formData);
}else{
$("#hiddendata").val('');
$("#hasil").html('');
}
});
function getdata(formData){
$.ajax({
url : "parameter.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
$("#hasil").html(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('error');
}
});
}
</script>
</body>
</html>
| 45659d69304c871c9e4bb151683674c153cf4aeb | [
"SQL",
"Text",
"PHP"
] | 37 | PHP | alifahfathonah/website-presensi-karyawan | a0cfbae36dd1e8a418eac858bfbcf204b608d616 | d332d472f57cbc38761b4fd95a9899ecbf9692a0 |
refs/heads/master | <file_sep># 0x07. Networking basics #0
---
## Description
This project in the System engineering & DevOps series is about:
* What is the OSI model and how many layers does it have
* How is the OSI model organized
* What is a LAN, its typical usage, and typical geographical size
* What is WAN, its typical usage, and typical geographical size
* What is the Internet
* What is an IP address and what are the 2 types
* What is localhost
* What is a subnet
* Why was IPv6 created
* What is TCP/UDP, and what is the main difference between the two
* What are the 2 mainly used data transfer protocols for IP (transfer level on the OSI schema)
* What are TCP/UDP ports
* What is a port
* Memorize SSH, HTTP and HTTPS port numbers
* What tool/protocol is often used to check if a device is connected to a network
---
File|Task
---|---
0-OSI_model | Answers to questions about OSI
1-types_of_network | Answers to questions about networks
2-MAC_and_IP_address | Answers to questions about Mac and IP addresses
3-UDP_and_TCP | Answers to questions about UDP and TCP
4-TCP_and_UDP_ports | Bash script that displays listening ports and shows the PID and name of the program to which each socket belongs
5-is_the_host_on_the_network | Bash script that pings an IP address passed as an argument<file_sep>0x16. API advanced
---
## Description
This project in the System engineering & DevOps series is about:
* How to read API documentation to find the endpoints youre looking for
* How to use an API with pagination
* How to parse JSON results from an API
* How to make a recursive API call
* How to sort a dictionary by value
---
File|Task
---|---
0-subs.py | A function that queries the Reddit API and returns the number of subscribers for a given subreddit, else return 0.
1-top_ten.py | A function that queries the Reddit API and prints the titles of the first 10 hot posts listed for a given subreddit, if invalid subreddit is given return 0.
2-recurse.py | A recursive function that queries the Reddit API and returns a list containing the titles of all hot articles for a given subreddit else None.<file_sep>0x13. Firewall
---
## Description
This project in the System engineering & DevOps series is about:
* Firewalls
---
File|Task
---|---
0-firewall_ABC | Answer file to questions about firewalls
1-block_all_incoming_traffic_but | Commands to install the ufw firewall and setup a few rules
<file_sep>#!/usr/bin/python3
""" Finds the number of subscribers for a given subbreddit
"""
import requests
def number_of_subscribers(subreddit):
"""
Queries Reddit and returns the number of subscribers for a given subreddit
"""
url = "https://www.reddit.com/r/{}/about.json".format(subreddit)
headers = {'user-agent': 'How many subs'}
req = requests.get(url, headers=headers, allow_redirects=False)
return req.json().get('data').get('subscribers')\
if req.status_code is 200 else 0
if __name__ == '__main__':
number_of_subscribers(subreddit)
<file_sep># 0x04. Loops, conditions and parsing
---
## Description
This project in the System engineering & DevOps series is about:
* How to create SSH keys
* What is the advantage of using #!/usr/bin/env bash over #!/bin/bash
* How to use while, until and for loops
* How to use if, else, elif and case condition statements
* How to use the cut command
* What are files and other comparison operators, and how to use them
---
File|Task
---|---
0-RSA_public_key.pub | My public key
1-for_holberton_school | Displays Holberton School 10 times using a for loop
2-while_holberton_school | Displays Holberton School 10 times using a while loop
3-until_holberton_school | Displays Holberton School 10 times using until
4-if_9_say_hi | Diplays Holberton School 10 times and Hi on the 9th iteration
5-4_bad_luck_8_is_your_chance | Loops from 1 to 10 and displays text on 4th and 8th iteration
6-superstitious_numbers | Displays numbers from 1 to 20 and displays text on the 4th, 9th and 17th iteration
7-clock | Displays the time for 12 hours and 59 minutes
8-for_ls | Displays content of the names of the current directory in list format
9-to_file_or_not_to_file | Gives you information about the holbertonschool file
10-fizzbuzz | Bash script that displays numbers from 1 to 100, FizzBuzz style
<file_sep>#!/usr/bin/env bash
# Configure Nginx so that its HTTP response contains a custom header
# Starts up nginx
sudo apt-get update
sudo apt-get install -y nginx
#Add header of X-Served-by
sudo sed -i '11a \ \tadd_header X-Served-By $HOSTNAME;' /etc/nginx/nginx.conf
sudo service nginx restart
<file_sep>#!/usr/bin/env bash
# Configures nginx to run it as user and listen 8080
pkill apache2
chown nginx:nginx /etc/nginx/nginx.conf
chmod 700 /etc/nginx/nginx.conf
sed -i 's/80/8080/g' /etc/nginx/sites-enabled/default
sudo -u nginx service nginx restart<file_sep>#!/usr/bin/env bash
# Bash script for connecting to a server
# using private key with the user ubuntu
ssh -i ~/.ssh/holberton ubuntu@172.16.58.3<file_sep>0x0A Configuration management
---
## Description
---
This project in the System engineering & DevOps series is about:
* Intro to configuration management
* Puppet
* puppet-lint
* puppet mode for emacs
---
File|Task
---|---
0-create_a_file.pp | Create a file in /tmp using puppet
1-install_a_package.pp | Install puppet-lint using puppet
2-execute_a_command.pp | Puppet script that kills a specific process
<file_sep>0x14. Mysql
---
## Description
This project in the System engineering & DevOps series is about:
* What is the main role of a database
* What is a database replica
* What is the purpose of a database replica
* Why database backups need to be stored in different physical locations
* What operation should you regularly perform to make sure that your database backup strategy actually works
---
File|Task
---|---
4-mysql_configuration_primary | MySQL primary configuration
4-mysql_configuration_replica | MySQL replica configuration
5-mysql_backup | Bash script that generates a MySQL dump and creates a compressed archive out of it
<file_sep>#!/usr/bin/env bash
# Script that displays "Holberton School" 10 times
$i
for i in {1..10}
do
echo "Holberton School"
done
<file_sep>#!/usr/bin/env bash
#Bash script that display info about subdomains
if [ $# -eq 1 ]; then
subs=("www" "lb-01" "web-01" "web-02")
for sub in "${subs[@]}"; do
type=$(dig "$sub"."$1" | grep -A1 'ANSWER SECTION'| tail -n 1 | awk '{print $4}')
ip_address=$(dig "$sub"."$1" | grep -A1 'ANSWER SECTION'| tail -n 1 | awk '{print $5}')
echo "The subdomain $sub is a $type record and points to $ip_address"
done
elif [ $# -eq 2 ]; then
type=$(dig "$2"."$1" | grep -A1 'ANSWER SECTION'| tail -n 1 | awk '{print $4}')
ip_address=$(dig "$2"."$1" | grep -A1 'ANSWER SECTION'| tail -n 1 | awk '{print $5}')
echo "The subdomain $2 is a $type record and points to $ip_address"
fi
<file_sep>#!/bin/bash
# Script that displays the content of the file /etc/passwd, using the while loop + IFS
file="/etc/passwd"
while IFS=: read -r USERNAME PASSWORD ID GROUP_ID COMMENT HOME_DIRECTORY COMMANDSHELL
do
echo "The user $USERNAME is part of the $GROUP_ID gang, lives in $HOME_DIRECTORY and rides $COMMANDSHELL. $ID's place is protected by the passcode $PASSWORD, more info about the user here: $COMMENT"
done < $file
<file_sep>#!/usr/bin/env bash
# Script that displays PID along with the name of the process which contain the word bash
pgrep -l bash
<file_sep>#!/usr/bin/env bash
# Script that install nginx web server
sudo apt-get update
sudo apt-get install -y nginx
echo "Holberton School" | sudo tee /var/www/html/index.nginx-debian.html
sudo sed -i '19a rewrite ^/redirect_me https://google.com permanent;' /etc/nginx/sites-enabled/default
sudo service nginx restart
<file_sep>#!/usr/bin/env bash
# Script that displays listening ports and show the PID
# and name of the program at which each socket belongs
netstat -l -p
<file_sep>#!/usr/bin/python3
""" Queries and returns a list containing the titles of all hot articles
"""
import requests
def recurse(subreddit, hot_list=[], after=""):
"""
Recursively queries Reddit API and returns a list containing the
titles of all hot articles for a given subreddit
"""
try:
url = "https://api.reddit.com/r/{}/hot?limit=100".format(subreddit)
headers = {'user-agent': 'Recurse it'}
req = requests.get(url, headers=headers, allow_redirects=False,
params={'after': after})
top_json = req.json().get('data').get('children')
after_val = req.json().get('data').get('after')
for item in top_json:
hot_list.append(item.get('data').get('title'))
if after_val is not None:
recurse(subreddit, hot_list, after_val)
return hot_list
except KeyError:
return(None)
except AttributeError:
return(None)
<file_sep>#!/usr/bin/env bash
# Script that displays the time for 12 hours and 59 minutes
h=0 #hours
while ((h <= 12))
do
echo "Hour: $h"
m=1 #minutes
while ((m <= 59))
do
echo "$m"
((m++))
done
((h++))
done
<file_sep>This directory contains I/O Redirection basic commands lines<file_sep>0x12. Web stack debugging #2
---
## Description
This project in the System engineering & DevOps series is about:
* Web stack debugging
---
File|Task
---|---
0-iamsomeonelese | Run the whoami command under the user passed as an argument
1-run_nginx_as_nginx | Configure nginx to run as nginx and listen on all active port 8080 and prevent apt-get remove
<file_sep>#!/usr/bin/python3
"""
Python script that returns information about a persons
To Do list when the employee ID is given
"""
import requests
from sys import argv
def get_todolist_progress():
"""
Get's the to do list progress of a specified user
"""
user_id = argv[1]
url = "https://jsonplaceholder.typicode.com/"
user_info = requests.get(url + "users/{}"
.format(user_id)).json()
total_user_tasks = requests.get(url + "todos?userId={}"
.format(user_id)).json()
completed_user_tasks = requests.get(url + "todos?userId={}&&completed=true"
.format(user_id)).json()
try:
print("Employee {} is done with tasks({}/{}):"
.format(user_info.get('name'),
len(completed_user_tasks), len(total_user_tasks)))
for task in completed_user_tasks:
print("\t {}".format(task.get("title")))
except KeyError:
pass
if __name__ == "__main__":
get_todolist_progress()
<file_sep>0x17. Web stack debugging #3
---
## Description
This project in the System engineering & DevOps series is about:
* Web servers
* Web stack debugging
* LAMP stack
* Wordpress
* Puppet
---
File|Task
---|---
0-strace_is_your_friend.pp | A puppet script that resolves an Apache 500 error
<file_sep>#!/usr/bin/env bash
# Script that install nginx web server
sudo apt-get update
sudo apt-get install -y nginx
echo "Holberton School" | sudo tee /var/www/html/index.nginx-debian.html
sudo sed -i '19a \\trewrite ^/redirect_me https://google.com permanent;' /etc/nginx/sites-available/default
echo "Ceci n'est pas une page" | sudo tee /usr/share/nginx/html/custom_404.html
sudo sed -i '35a \\terror_page 404 /custom_404.html;\n\tlocation = /custom_404.html { \n\troot /usr/share/nginx/html; \n\tinternal;\n\t}' /etc/nginx/sites-available/default
sudo service nginx restart
<file_sep>0x10. HTTPS SSL
---
## Description
This project in the System engineering & DevOps series is about:
* What is HTTPS SSL 2 main roles
* What is the purpose encrypting traffic
* What SSL termination means
---
File|Task
---|---
0-https_abc | Answer file for questions about HTTPS
1-world_wide_web | Bash script that will display information about subdomains
2-haproxy_ssl_termination | HAproxy configuration to accept encrypted traffic for your subdomain www.
<file_sep>#!/usr/bin/env bash
# Script that displays the content of the current directory in list format
command=$(ls)
for i in $command;
do
echo "$i" | cut -d "-" -f2
done
<file_sep>#!/usr/bin/env bash
# Pings an ip 5 times
# If no argument displays, Usage: 5-is_the_host_on_the_network {IP_ADDRESS}
if [ $# -ne 0 ]
then
ping -c 5 "$1"
else
echo "Usage: 5-is_the_host_on_the_network {IP_ADDRESS}"
fi
<file_sep>0x0E. Web stack debugging #1
---
## Description
This project in the System engineering & DevOps series is about:
* Web stack debugging
---
File|Task
---|---
0-nginx_likes_port_80 | Debug Nginx to get it running again and listening on port 80 of all the server's active IPv4 IPS
1-debugging_made_short | Debug the same problem in 5 lines or less without using ; or &&
<file_sep>#!/usr/bin/python3
"""
Expand #0 script to export data in the JSON format
"""
import json
import requests
from sys import argv
def get_todolist_progress():
"""
Get's the to do list progress of a specified user
"""
user_id = argv[1]
url = "https://jsonplaceholder.typicode.com/"
user_info = requests.get(url + "users/{}"
.format(user_id)).json()
total_user_tasks = requests.get(url + "todos?userId={}"
.format(user_id)).json()
try:
user_name = user_info.get('username')
json_data = []
for task in total_user_tasks:
todo_dict = {}
task_title = task.get("title")
is_completed = task.get("completed")
todo_dict["task"] = task_title
todo_dict["completed"] = is_completed
todo_dict["username"] = user_name
json_data.append(todo_dict)
with open("{}.json".format(argv[1]), mode="w") as json_file:
final_dict = {user_id: json_data}
json.dump(final_dict, json_file)
except KeyError:
pass
if __name__ == "__main__":
get_todolist_progress()
<file_sep>#!/usr/bin/env bash
# Displays PID
echo $$
<file_sep>#!/usr/bin/env bash
# Script that kills another process when executed
kill "$(pgrep -f 4-to_infinity_and_beyond)"
<file_sep># 0x0B. ssh
---
## Desription
This project in the system engineering & DevOps series is about:
* What is a server
* Where servers usually live
* What is SSH
* How to create an SSH RSA key pair
* How to connect to a remote host using an SSH RSA key pair
* The advantage of using #!/usr/bin/env bash instead of /bin/bash
---
File|Task
---|---
0-use_a_private_key | Bash script that uses ssh to connect to your server using the private key
1-create_ssh_key_pair | Bash script that creates an RSA key pair
2-ssh_config | Change configuration file for connecting without typing
<file_sep>#!/usr/bin/env bash
# Script that displays text 20 times and prints different text for the 4th, 9th and 17th iteration
i=1
text4="bad luck from China"
text9="bad luck from Japan"
text17="bad luck from Italy"
while ((i <= 20))
do
echo "$i"
case $i in
4)
echo "$text4"
;;
9)
echo "$text9"
;;
17)
echo "$text17"
;;
esac
((i++))
done
<file_sep>#!/usr/bin/env bash
# Script that displays "Holberton School" 10 times with a while loop
i=1
while ((i <= 10))
do
echo "Holberton School"
((i++))
done
<file_sep>#!/usr/bin/env bash
# Script that install nginx web server
sudo apt-get update
sudo apt-get install -y nginx
echo "Holberton School" | sudo tee /var/www/html/index.nginx-debian.html
sudo service nginx restart
<file_sep>This directory contains a bunch of codes on shell, initi files,variables and expansions<file_sep>0x15. API
---
## Description
This project in the System engineering & DevOps series is about:
* What Bash scripting should not be used for
* What is an API
* What is a REST API
* What are microservices
* What is the CSV format
* What is the JSON format
* Python style guide
* Package and module name style
* Class name style
* Variable name style
* Function name style
* Constant name style
* What is CapWords or CamelCase
---
File|Task
---|---
0-gather_data_from_an_API.py | Python script that returns information about a peron's To Do list when the employee ID is given
1-export_to_CSV.py | Expand #0 script to export data in the CSV format
2-export_to_JSON.py | Expand #0 script to to export data in the JSON format
3-dictionary_of_list_of_dictionaries.py | Expand #0 script to record all taks from all employees and export the data in JSON format
<file_sep>#!/usr/bin/env bash
# Script that kills another process without using kill or killall
pkill -f "7-highlander"
<file_sep># Postmortem

## Issue Summary
---
Apache is returning a 500 error, this trouble makes that 100% of people tryng ot retrieve information for server wasn't possible to make some request.
**SPAN** 15:00 - 19:30 COT
# Timeline
---
* 15:00 COT - Problem was discovered
* 16:00 COT - Fellow engineers attempt to resolve issues through various means
* 17:15 COT - Issue was brought to the attention of the engineer on call while trying to bring some response from server
* 17:45 COT - Discovered that it is imperative to debug each process at server status
* 18:00 COT - Discovered that child process from apache is not finishing well
* 18:15 COT - Attach each running process from child ṕrocess at apache runtime
* 18:30 COT - Discovered unresolved references from routes of some files
* 19:30 COT - Problem was resolved
## Root Cause
---
While trying to resolve the issue using several methods of debugging found that a path were not found with extension of .phpp
and this files its located with .php extension.
<a href="https://imgbb.com/"><img src="https://i.ibb.co/P61xMkZ/issue.png" alt="issue" border="0"></a>
## Corrective and preventative measures
---
* Before locating paths in any file , watch carefully extensions for any file
* At any moment for changing config files, do not wait for another to run server status, the one in charge for deploy must check this out
* Do not manually change paths, try to automate it with bash scripts in order to prevent this issues
<file_sep>#!/usr/bin/python3
"""
Expand #0 script to export data in the CSV format
"""
import csv
import requests
from sys import argv
def get_todolist_progress():
"""
Get's the to do list progress of a specified user
"""
user_id = argv[1]
url = "https://jsonplaceholder.typicode.com/"
user_info = requests.get(url + "users/{}"
.format(user_id)).json()
total_user_tasks = requests.get(url + "todos?userId={}"
.format(user_id)).json()
try:
user_name = user_info.get('username')
with open("{}.csv".format(user_id), mode="w") as file:
csv2write = csv.writer(file, quoting=csv.QUOTE_ALL)
for task in total_user_tasks:
task_title = task.get('title')
is_completed = task.get('completed')
csv2write.writerow([user_id, user_name,
is_completed, task_title])
except KeyError:
pass
if __name__ == "__main__":
get_todolist_progress()
<file_sep>0x0C. Web server
---
## Description
This project in the System engineering & DevOps series is about:
* What DNS stands for
* What is DNS main role
* What are DNS record types for: A, CNAME, TXT, and MX
* What is the main role of a web server
* What is a child process
* Why web server usually have a parent process and child processes
* What are the main HTTP requests
---
File|Task
---|---
0-transfer_file | Bash script that transfers a file from our client to a server
1-install_nginx_web_server | Bash script that configures a new Ubuntu machine with Nginx
2-setup_a_domain_name | My domain name
3-redirection | Configures the Nginx server so that /redirect_me is redirecting to another page
4-not_found_page_404 | Configure the Nginx server to have a custom 404 page that contains the string Ceci n'est pas une page
<file_sep>0x1A. Application server
---
## Description
This project in the System engineering & DevOps series is about:
* Web servers
* Web stack debugging
* Nginx
* Application servers
* Flask
* Gunicorn
* Upstart
---
File|Task
---|---
2-app_server-nginx_config | Serve a page with Nginx from the route /airbnb-onepage/
3-app_server-nginx_config | Add a route with query parameters
4-app_server-nginx_config | Let’s serve what you built for AirBnB clone v3 - RESTful API on web-01.
5-app_server-nginx_config | Let’s serve what you built for AirBnB clone - Web dynamic on web-01
<file_sep>#!/usr/bin/python3
""" Finds the first 10 hot posts listed for a given subreddit
"""
import requests
def top_ten(subreddit):
"""
Print the titles of the first 10 hot posts listed for a given subreddit
"""
try:
url = "https://api.reddit.com/r/{}/hot.json?limit=10".format(subreddit)
headers = {'user-agent': 'Top Ten'}
req = requests.get(url, headers=headers, allow_redirects=False)
top_json = req.json().get('data').get('children')
if req.status_code == 200:
for top in top_json:
print(top.get('data').get('title'))
except KeyError:
print(None)
except AttributeError:
print(None)
if __name__ == '__main__':
top_ten(subreddit)
<file_sep># 0x06. Regular expression
---
## Description
This project in the System engineering & DevOps series is about:
* Regular expression & its usage
* Ruby's Oniguruma regular expression library
* Ruby scripts that accepts one argument and pass it to a regular expression matching method
* Use this ruby script to resolve regex questions: `puts ARGV[0].scan(/<regex>/).join`
* Use [rubular](http://rubular.com/) to test code
---
File|Task
---|---
0-simply_match_holberton.rb | Regular expression that matches Holberton
1-repetition_token_0.rb | Regex that matches `hbttn` until `hbtttttn`
2-repetition_token_1.rb | Regex that matches `htn` and `hbtn` using `?`
3-repetition_token_2.rb | Regex that matches from `hbt` 4 times
4-repetition_token_3.rb | Regex that matches everything except `hbon` using `*`
5-beginning_and_end.rb | Regex that matches any character in between `h` and `n`
6-phone_number.rb | Regex that matches a 10 digit phone number
7-OMG_WHY_ARE_YOU_SHOUTING.rb | Regex matches only capital letters
<file_sep>0x0F. Load balancer
---
## Description
This project in the System engineering & DevOps series is about:
* Load balancer
* Web stack debugging
---
File|Task
---|---
0-custom_http_response-header | Bash script that configures Nginx so that its HTTP response contains a custom header.
1-install_load_balancer | Bash script to install and configure HAproxy on your lb-01 server
<file_sep>#!/usr/bin/env bash
# Script that kills the 7-highlander process
kill -SIGKILL "$(pgrep -f 7-highlander)"
<file_sep>this file contains shell permissions commands
<file_sep>#!/usr/bin/env bash
# Displays line containing the bash word, to be able to easily get the PID
# shellcheck disable=SC2009
ps -auxf | grep 'bash'
<file_sep>## System_engineering-devops

## What is DEVOPS?
DevOps is the combination of cultural philosophies, practices, and tools that increases an organization’s ability to deliver applications and services at high velocity: evolving and improving products at a faster pace than organizations using traditional software development and infrastructure management processes. This speed enables organizations to better serve their customers and compete more effectively in the market.
(source: "https://aws.amazon.com/devops/what-is-devops")
<img align="center" src="https://www.channelfutures.com/files/2018/02/DevOps-2018_0.jpg" width="60%"/>
## Table of Contents
* [Requirements](#requirements)
* [About](#about)
## Requirements
* Ubuntu 14.04 LTS
* Shellcheck version 0.3.3-1
## About
At Holberton School, there are several tracks to learn about to become a Full-Stack Software Engineer. This repository is the Systems Engineering/Devops track and it covers the following:
- Bash
- Scripting
<file_sep>#!/usr/bin/env bash
# Script that displays "Holberton School" 10 times and prints Hi on the 9th iteration
i=1
while [ $i -le 10 ]
do
echo "Holberton School"
if [ $i -eq 9 ]
then
echo "Hi"
fi
((i++))
done
<file_sep>#!/usr/bin/env bash
# Bash script that rum whoami with user as argument
sudo -u "$1" "whoami"<file_sep># 0x05. Processes and signals
---
## Description
This project in the System engineering & DevOps series is about:
* What is a PID
* What is a process
* How to find a process PID
* How to kill a process
* What is a signal
* What are the 2 signals that cannot be ignored
---
File|Task
---|---
0-what-is-my-pid | Bash script that displays its PID
1-list_your_processes | Bash script that displays a list of currently running processes for all users
2-show_your_bash_pid | Bash script that displays line containing the `bash` word, which allows you to easily obtain the PID of the process
3-show_your_bash_pid_made_easy | Displays the PID along with the process name that contain the word `bash`
4-to_infinity_and_beyond | Displays `To infinity and beyond` indefinitely
5-kill_me_now | Bash script that can kill another process
6-kill_me_now_made_easy | Bash script that can kill another process without using kill or killall
7-highlander | Display `To infinity and beyond` indefinitely with sleep 2 between each iteration and displays `I am invincible!!!` when `SIGTERM` signal has been recieved
8-beheaded_process | Bash script that kills the `7-highlander` process
<file_sep>0x08. Networking basics #1
---
## Description
This project in the System engineering & DevOps series is about:
* What is localhost/12192.168.3.11
* What is 0.0.0.0
* What is /etc/hosts
* How to display your machines active network interfaces
---
File|Task
---|---
0-localhost | Answer to a question about the localhost
1-wildcard | Answer to a question about 0.0.0.0
2-change_your_home_IP | A bash script that configures a Ubuntu server, localhost resolves to 127.0.0.2 and facebook.com resolves to 8.8.8.8
3-show_attached_IPs | A bash script that displays all active IPv4 IPs on the machine its executed on
4-port_listening_on_localhost | Bash script that listens on port 98 on localhost
<file_sep>#!/usr/bin/env bash
# Script thatconfigures a Ubuntu server with
# localhost resolves to 127.0.0.2
# facebook.com resolves to 8.8.8.8
cp /etc/hosts ~/temp_hosts
sed -i s/127.0.0.1/127.0.0.2/ ~/temp_hosts
echo "8.8.8.8 facebook.com" >> ~/temp_hosts
cp -f ~/temp_hosts /etc/hosts
<file_sep>#!/usr/bin/env bash
#Fix nginx to listen in port 80 of all the servers
sudo sed -i 's/8080/80/g' /etc/nginx/sites-enabled/default
sudo service nginx restart
<file_sep>0x0D. Web stack debugging #0
## Description
This project in the System engineering & DevOps series is about:
* Web stack debugging
---
File|Task
---|---
0-give_me_a_page | Fix Apache to run on the container and to return a page containing Hello Holberton when querying the root of it
<file_sep>0x1B. Web stack debugging #4
---
## Description
This project in the System engineering & DevOps series is about:
* Web servers
* Web stack debugging
* Puppet
* Nginx
* Request limits
---
File|Task
---|---
0-the_sky_is_the_limit_not.pp | Puppet script that modifies the ulimit of Nginx requests
<file_sep>#!/usr/bin/env bash
# Bash script to install and configure HAproxy
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:vbernat/haproxy-1.6
sudo apt-get update
sudo apt-get install -y haproxy=1.6.\*
#Backend and Frontend
sudo sed -i "$ a \ \nfrontend http\n \tbind *:80\n \tmode http\n \tdefault_backend web-backend\n \nbackend web-backend\n \tmode http\n \tbalance roundrobin\n \tserver 878-web-01 192.168.127.12:80 check\n \tserver 878-web-02 172.16.31.10:80 check\n" /etc/haproxy/haproxy.cfg
sudo service haproxy restart
<file_sep>#!/usr/bin/env bash
# Script that prints text indefinitely and prints different text when SIGTERM is recieved
bool=true
trap "echo I am invincible!!!" SIGTERM
while $bool
do
echo "To infinity and beyond"
sleep 2
done
| 5f52b4460cafdf467ec4d4b980e0e91778627237 | [
"Markdown",
"Python",
"Shell"
] | 58 | Markdown | johnconnor77/holberton-system_engineering-devops | 14287d663af81bfb3531181ebb5aa78d2f09526b | 1306bfeeca95c8e0221e0bd70b8c04026c3c525b |
refs/heads/master | <repo_name>manojbalendin/RestAPI<file_sep>/RestApi.DataAccess.Dapper/Interfaces/DeveloperRepository.cs
using Microsoft.Extensions.Configuration;
using RestApi.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Dapper;
namespace RestApi.DataAccess.Dapper.Interfaces
{
public class DeveloperRepository : IDeveloperRepository
{
protected readonly IConfiguration _config;
public DeveloperRepository(IConfiguration config)
{
_config = config;
}
public IDbConnection Connection
{
get
{
return new SqlConnection(_config.GetConnectionString("DefaultConnection"));
}
}
public void AddDeveloper(Developer entity)
{
try
{
using(IDbConnection dbConnection=this.Connection)
{
dbConnection.Open();
string query = "INSERT INTO Developer (Name,Email,Department,JoinedDate) VALUES(@Name,@Email,@Department,@JoinedDate);";
dbConnection.Execute(query,entity);
}
}
catch(Exception ex)
{
throw ex;
}
}
public void DeleteDeveloper(int id)
{
try
{
using (IDbConnection dbConnection = this.Connection)
{
dbConnection.Open();
string query = "Delete From Developer Where Id = @Id";
dbConnection.Execute(query,new { Id = id });
}
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<IEnumerable<Developer>> GetAllDevelopersAsync()
{
try
{
using (IDbConnection dbConnection = this.Connection)
{
dbConnection.Open();
string query = "Select * From Developer";
var result = await dbConnection.QueryAsync<Developer>(query);
return result;
}
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<IEnumerable<Developer>> GetDevelopersByEmailAsync(string Email)
{
try
{
using (IDbConnection dbConnection = this.Connection)
{
dbConnection.Open();
string query = "Select * From Developer Where Email = @Email";
var result = await dbConnection.QueryAsync<Developer>(query,new { Email = Email });
return result;
}
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<IEnumerable<Developer>> GetDevelopersByIdAsync(int id)
{
try
{
using (IDbConnection dbConnection = this.Connection)
{
dbConnection.Open();
string query = "Select * From Developer Where Id= @Id";
var result = await dbConnection.QueryAsync<Developer>(query, new { Id = id });
return result;
}
}
catch (Exception ex)
{
throw ex;
}
}
public void UpdateDeveloper(Developer entity)
{
try
{
using (IDbConnection dbConnection = this.Connection)
{
dbConnection.Open();
string query = "Update Developer Set Name = @Name,Email = @Email,Department = @Department,JoinedDate = @JoinedDate Where Id = @Id);";
dbConnection.Execute(query, entity);
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
<file_sep>/RestAPI/Controllers/DeveloperController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RestApi.Domain;
using RestApi.Services;
using RestApi.Services.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RestAPI.Controllers
{
[ApiController]
[Route("api/v1/[controller]")]
public class DeveloperController: ControllerBase
{
protected readonly IDeveloperService _developerService;
public DeveloperController(IDeveloperService developerService)
{
_developerService = developerService;
}
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> GetAllDevelopers()
{
var developer =await _developerService.GetAllDevelopersAsync();
return Ok(developer);
}
[Route("[action]")]
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> GetDeveloperById(int id)
{
var developer = await _developerService.GetDevelopersByIdAsync(id);
return Ok(developer);
}
[Route("[action]")]
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> GetDeveloperByEmail(string email)
{
var developer = await _developerService.GetDevelopersByEmailAsync(email);
return Ok(developer);
}
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status200OK)]
public IActionResult AddDeveloper([FromBody] Developer developer)
{
if(!ModelState.IsValid)
{
return BadRequest();
}
_developerService.AddDeveloper(developer);
return CreatedAtAction(nameof(GetDeveloperById), new { Id = developer.Id }, developer);
}
[HttpPut]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status200OK)]
public IActionResult UpdateDeveloper([FromBody] Developer developer)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
_developerService.UpdateDeveloper(developer);
return Ok();
}
[HttpDelete]
[ProducesResponseType(StatusCodes.Status200OK)]
public IActionResult DeleteDeveloper(int id)
{
_developerService.DeleteDeveloper(id);
return Ok();
}
}
}
<file_sep>/RestAPI/Controllers/CategoryController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RestApi.Domain;
using RestApi.Services;
using RestApi.Services.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RestAPI.Controllers
{
[ApiController]
[Route("api/v1/[controller]")]
public class CategoryController: ControllerBase
{
protected readonly ICategoryService _categoryService;
public CategoryController(ICategoryService categoryService)
{
_categoryService = categoryService;
}
[Route("[action]")]
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> GetCategorytById(int id)
{
var results = await _categoryService.GetCategoryByIdAsync(id);
return Ok(results);
}
}
}
<file_sep>/RestApi.DataAccess.Dapper/Interfaces/ICategoryRepository.cs
using RestApi.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace RestApi.DataAccess.Dapper.Interfaces
{
public interface ICategoryRepository
{
Task<IEnumerable<Category>> GetCategoryByIdAsync(int id);
}
}
<file_sep>/RestApi.Services/Services/IProductService.cs
using RestApi.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace RestApi.Services.Services
{
public interface IProductService
{
Task<IEnumerable<Product>> GetAllProductAsync();
Task<IEnumerable<Product>> GetProductByIdAsync(int id);
}
}
<file_sep>/RestApi.Services/Services/DeveloperService.cs
using RestApi.DataAccess.Dapper.Interfaces;
using RestApi.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace RestApi.Services.Services
{
public class DeveloperService:IDeveloperService
{
protected readonly IDeveloperRepository _developerRepository;
public DeveloperService(IDeveloperRepository developerRespository)
{
_developerRepository = developerRespository;
}
public void AddDeveloper(Developer entity)
{
_developerRepository.AddDeveloper(entity);
}
public void DeleteDeveloper(int id)
{
_developerRepository.DeleteDeveloper(id);
}
public Task<IEnumerable<Developer>> GetAllDevelopersAsync()
{
return _developerRepository.GetAllDevelopersAsync();
}
public Task<IEnumerable<Developer>> GetDevelopersByEmailAsync(string emailId)
{
return _developerRepository.GetDevelopersByEmailAsync(emailId);
}
public Task<IEnumerable<Developer>> GetDevelopersByIdAsync(int id)
{
return _developerRepository.GetDevelopersByIdAsync(id);
}
public void UpdateDeveloper(Developer entity)
{
_developerRepository.UpdateDeveloper(entity);
}
}
}
<file_sep>/RestApi.Services/Services/IDeveloperService.cs
using RestApi.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace RestApi.Services.Services
{
public interface IDeveloperService
{
Task<IEnumerable<Developer>> GetAllDevelopersAsync();
Task<IEnumerable<Developer>> GetDevelopersByIdAsync(int id);
Task<IEnumerable<Developer>> GetDevelopersByEmailAsync(string emailId);
void AddDeveloper(Developer entity);
void UpdateDeveloper(Developer entity);
void DeleteDeveloper(int id);
}
}
<file_sep>/RestApi.Services/Services/CategoryService.cs
using RestApi.DataAccess.Dapper.Interfaces;
using RestApi.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace RestApi.Services.Services
{
public class CategoryService:ICategoryService
{
protected readonly ICategoryRepository _categoryRepository;
public CategoryService(ICategoryRepository categoryRepository)
{
_categoryRepository = categoryRepository;
}
public Task<IEnumerable<Category>> GetCategoryByIdAsync(int id)
{
return _categoryRepository.GetCategoryByIdAsync(id);
}
}
}
<file_sep>/RestApi.DataAccess.Dapper/Interfaces/IProductRepository.cs
using RestApi.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace RestApi.DataAccess.Dapper.Interfaces
{
public interface IProductRepository
{
Task<IEnumerable<Product>> GetAllProductAsync();
Task<IEnumerable<Product>> GetProductByIdAsync(int id);
}
}
<file_sep>/RestApi.Services/Services/ProductService.cs
using RestApi.DataAccess.Dapper.Interfaces;
using RestApi.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace RestApi.Services.Services
{
public class ProductService:IProductService
{
protected readonly IProductRepository _productRepository;
public ProductService(IProductRepository productRepository)
{
_productRepository = productRepository;
}
public Task<IEnumerable<Product>> GetAllProductAsync()
{
return _productRepository.GetAllProductAsync();
}
public Task<IEnumerable<Product>> GetProductByIdAsync(int id)
{
return _productRepository.GetProductByIdAsync(id);
}
}
}
<file_sep>/RestApi.DataAccess.Dapper/Interfaces/IDeveloperRespository.cs
using RestApi.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace RestApi.DataAccess.Dapper.Interfaces
{
public interface IDeveloperRepository
{
Task<IEnumerable<Developer>> GetAllDevelopersAsync();
Task<IEnumerable<Developer>> GetDevelopersByIdAsync(int id);
Task<IEnumerable<Developer>> GetDevelopersByEmailAsync(string emailId);
void AddDeveloper(Developer entity);
void UpdateDeveloper(Developer entity);
void DeleteDeveloper(int id);
}
}
<file_sep>/RestApi.DataAccess.Dapper/Interfaces/ProductRepository.cs
using Microsoft.Extensions.Configuration;
using RestApi.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Dapper;
using System.Linq;
namespace RestApi.DataAccess.Dapper.Interfaces
{
public class ProductRepository : IProductRepository
{
protected readonly IConfiguration _config;
public ProductRepository(IConfiguration config)
{
_config = config;
}
public IDbConnection Connection
{
get
{
return new SqlConnection(_config.GetConnectionString("DefaultConnection"));
}
}
public async Task<IEnumerable<Product>> GetAllProductAsync()
{
try
{
using (IDbConnection dbConnection = this.Connection)
{
dbConnection.Open();
string query = @"select productid, productname, p.categoryid, categoryname
from product p inner
join category c on p.categoryid = c.categoryid";
var products = await dbConnection.QueryAsync<Product, Category, Product>(query, (product, category) => {
product.Category = category;
return product;
},
splitOn: "CategoryId");
return products;
}
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<IEnumerable<Product>> GetProductByIdAsync(int id)
{
try
{
using (IDbConnection dbConnection = this.Connection)
{
dbConnection.Open();
string query = @"select productid, productname, p.categoryid, categoryname
from product p inner
join category c on p.categoryid = c.categoryid Where p.productid= @Id";
var products = await dbConnection.QueryAsync<Product, Category, Product>(query, (product, category) => {
product.Category = category;
return product;
},param:new { Id = id },
splitOn: "CategoryId");
return products;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
<file_sep>/RestAPI/Controllers/ProductController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RestApi.Domain;
using RestApi.Services;
using RestApi.Services.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RestAPI.Controllers
{
[ApiController]
[Route("api/v1/[controller]")]
public class ProductController: ControllerBase
{
protected readonly IProductService _productService;
public ProductController(IProductService productService)
{
_productService = productService;
}
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> GetAllProduct()
{
var results =await _productService.GetAllProductAsync();
return Ok(results);
}
[Route("[action]")]
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> GetProductById(int id)
{
var results = await _productService.GetProductByIdAsync(id);
return Ok(results);
}
}
}
<file_sep>/RestApi.Services/Services/ICategoryService.cs
using RestApi.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace RestApi.Services.Services
{
public interface ICategoryService
{
Task<IEnumerable<Category>> GetCategoryByIdAsync(int id);
}
}
<file_sep>/RestApi.DataAccess.Dapper/Interfaces/CategoryRepository.cs
using Microsoft.Extensions.Configuration;
using RestApi.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Dapper;
using System.Linq;
namespace RestApi.DataAccess.Dapper.Interfaces
{
public class CategoryRepository : ICategoryRepository
{
protected readonly IConfiguration _config;
public CategoryRepository(IConfiguration config)
{
_config = config;
}
public IDbConnection Connection
{
get
{
return new SqlConnection(_config.GetConnectionString("DefaultConnection"));
}
}
public async Task<IEnumerable<Category>> GetCategoryByIdAsync(int CategoryId)
{
try
{
using (IDbConnection dbConnection = this.Connection)
{
dbConnection.Open();
string query = @"select p.categoryid, categoryname , productid, productname
from product p inner
join category c on p.categoryid = c.categoryid Where C.Categoryid= @CategoryId";
var products = await dbConnection.QueryAsync<Category, Product, Category>(query, (category, products) => {
//products.Category = category;
category.Products = new List<Product>();
category.Products.Add(products);
return category;
},param:new { CategoryId = CategoryId },
splitOn: "CategoryId,ProductId");
return products;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
| 13707a8d6dc90e3b3e5cc6cdae51bca77803ffd1 | [
"C#"
] | 15 | C# | manojbalendin/RestAPI | a4ae43b7916495831bf94b21cf73089b7251774b | 2cd91a31097dbdd3962af3c1a8224bb5b835919f |
refs/heads/master | <repo_name>18521604/Bs4-StartBoostrap<file_sep>/index.js
$(function () {
//Responsive header
$(window).resize(function () {
var docao = $(window).height();
$('#header').css({height: docao});
});
//Shrink navbar
$(window).scroll(function(){
if($(this).scrollTop()>100){
$('.navbar').addClass('navbar-shrink');
}
else{
$('.navbar').removeClass('navbar-shrink');
}
});
//Menu scroll
var menuHeight = $('.navbar').height();
$('.navbar ul li:nth-child(1) a').click(function(e){
$('html,body').animate({scrollTop:$('#services').offset().top - menuHeight},1500, "easeInOutExpo");
return false;
});
$('.navbar ul li:nth-child(2) a').click(function(e){
$('html,body').animate({scrollTop:$('#portfolio').offset().top - menuHeight},1500, "easeInOutExpo");
return false;
});
$('.navbar ul li:nth-child(3) a').click(function(e){
$('html,body').animate({scrollTop:$('#about').offset().top - menuHeight},1500, "easeInOutExpo");
return false;
});
$('.navbar ul li:nth-child(4) a').click(function(e){
$('html,body').animate({scrollTop:$('#team').offset().top - menuHeight},1500, "easeInOutExpo");
return false;
});
$('.navbar ul li:nth-child(5) a').click(function(e){
$('html,body').animate({scrollTop:$('#contact').offset().top - menuHeight},1500, "easeInOutExpo");
return false;
});
// Hover menu of navbar
$(window).scroll(function(){
$('.navbar ul li a').removeClass('active');
if (($(this).scrollTop() >= $('#services').offset().top - menuHeight) &&
($(this).scrollTop() < $('#portfolio').offset().top - menuHeight)) {
$('.navbar ul li:nth-child(1) a').addClass('active');
} else {
$('.navbar ul li a').removeClass('active');
if (($(this).scrollTop() >= $('#portfolio').offset().top - menuHeight) &&
($(this).scrollTop() < $('#about').offset().top - menuHeight)) {
$('.navbar ul li:nth-child(2) a').addClass('active');
} else {
$('.navbar ul li a').removeClass('active');
if (($(this).scrollTop() >= $('#about').offset().top - menuHeight) &&
($(this).scrollTop() < $('#team').offset().top - menuHeight)) {
$('.navbar ul li:nth-child(3) a').addClass('active');
} else {
$('.navbar ul li a').removeClass('active');
if (($(this).scrollTop() >= $('#team').offset().top - menuHeight) &&
($(this).scrollTop() < $('#contact').offset().top - menuHeight)) {
$('.navbar ul li:nth-child(4) a').addClass('active');
} else {
$('.navbar ul li a').removeClass('active');
if (($(this).scrollTop() >= $('#contact').offset().top - menuHeight)) {
$('.navbar ul li:nth-child(5) a').addClass('active');
} else {
$('.navbar ul li a').removeClass('active');
};
};
};
};
};
});
//Button up top
$(window).scroll(function(){
if($(this).scrollTop() > 100){
$('.btn-up').fadeIn('slow');
} else{
$('.btn-up').fadeOut('slow');
}
});
$('.btn-up').click(function(){
$('html,body').animate({scrollTop:0},1500,"easeInOutExpo");
})
}); | 00169425ad627c7bea9d255192b83fbe614d90fd | [
"JavaScript"
] | 1 | JavaScript | 18521604/Bs4-StartBoostrap | a715eeb7ef3a92cec2d4b57c4b6042783b7b5b4a | 705d99cfe82784909fbf76a7e0632d3a3d3301af |
refs/heads/master | <file_sep><?php
/**
* Created by PhpStorm.
* User: shes
* Date: 29.06.2017
* Time: 16:35
*/
namespace ShesShoppingCart\Src;
use ShesShoppingCart\Model\Carts;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Session;
class Cart
{
protected $storage = 'mysql'; // mysql, redis
protected $data = [];
protected $cart_id = 'default';
protected $totalQty = 0;
protected $totalPrice = 0;
public function __construct()
{
$this->cartInit();
}
/**
* Принимает ассоциативный массив обязательны ключи ['id'=>1, 'qty' => 0, 'price'=>100.4,
* 'item'=>array/object,]
* @param $items
* @param null $id_cart
* @return mixed
*/
public static function add($items, $id_cart = null)
{
$inst = new static();
if (!empty($id_cart)) $inst->cart_id = $id_cart;
$storedItem = $inst->data['items'];
if ($inst->checkMultiArr($items)) {
foreach ($items as $item) {
if ($item['qty'] <= 0) $item['qty']++;
$id = $item['id'];
if (array_key_exists($id, $storedItem)) {
$qty = $storedItem[$id]['qty'] + 1;
$storedItem[$id] = $item;
$storedItem[$id]['qty'] = $qty;
} else {
$storedItem[$id] = $item;
}
$inst->data['total_qty']++;
$inst->data['total_price'] += $item['price'];
}
} else {
if ($items['qty'] <= 0) $items['qty']++;
$storedItem[$items['id']] = $items;
}
$inst->data['items'] = $storedItem;
$inst->cartSave();
return $inst->get();
}
/**
* Возврат корзины с вычиткой процента
* @param $percent
* @return mixed
*/
public static function getWithPct($percent = 0)
{
$inst = new static();
$cart = $inst->get();
$total_price = $cart['total_price'];
$result = $total_price - ($total_price * $percent / 100);
if ($result >= 0) {
$cart['total_price'] = $result;
} else {
$cart['total_price'] = 0;
}
return $cart;
}
/**
* Получение корзины с скидкой
* @param int $summ
* @return mixed
*/
public static function getWithDic($summ = 0)
{
$inst = new static();
$cart = $inst->get();
$total_price = $cart['total_price'];
$result = $total_price - $summ;
if ($result >= 0) {
$cart['total_price'] = $result;
} else {
$cart['total_price'] = 0;
}
return $cart;
}
/**
* @return mixed
*/
public static function get()
{
$inst = new static();
return $inst->data;
}
/**
* удаляет товар, передается id- продукта, количество(по умолчанию 1)
* @param $id_prod
* @param int $num
* @return mixed
*/
public static function reduce($id_prod, $num = 1)
{
$inst = new static();
$cart = $inst->data;
if (array_key_exists($id_prod, $cart['items'])) {
$prod = &$cart['items'][$id_prod];
if ($prod['qty'] <= $num) {
$cart['total_price'] -= $prod['price'] * $prod['qty'];
$cart['total_qty'] -= $prod['qty'];
unset($cart['items'][$id_prod]);
} else {
$cart['total_price'] -= $prod['price'] * $num;
$cart['total_qty'] -= $num;
$prod['qty'] -= $num;
}
$inst->data = $cart;
$inst->cartSave();
}
return $inst->get();
}
/**
* добавляет товар, передается id- продукта, количество(по умолчанию 1)
* @param $id_prod
* @param int $num
* @return mixed
*/
public static function increase($id_prod, $num = 1)
{
$inst = new static();
$cart = $inst->data;
if (array_key_exists($id_prod, $cart['items'])) {
$prod = &$cart['items'][$id_prod];
$cart['total_price'] += $prod['price'] * $num;
$cart['total_qty'] += $num;
$prod['qty'] += $num;
$inst->data = $cart;
$inst->cartSave();
}
return $inst->get();
}
/**
* Удалет полностью продукты по id
* @param $id_prod
* @return mixed
*/
public static function remove($id_prod)
{
$inst = new static();
$cart = $inst->data;
if (array_key_exists($id_prod, $cart['items'])) {
$prod = &$cart['items'][$id_prod];
$cart['total_price'] -= $prod['price'] * $prod['qty'];
$cart['total_qty'] -= $prod['qty'];
unset($cart['items'][$id_prod]);
$inst->data = $cart;
$inst->cartSave();
}
return $inst->get();
}
/**
* Очистка корзины
*/
public static function delete()
{
$inst = new static();
$inst->setDefaultCart();
$inst->cartSave();
}
public function cartSave()
{
$cart_id = $this->cart_id;
$data = json_encode($this->data);
$storage = $this->storage;
$status = false;
switch ($storage) {
case 'mysql':
// $cart = Carts::where('cart_id', $cart_id)->first();
// if ($cart) {
$cart = Carts::firstOrNew(['cart_id' => $cart_id]);
$cart->items = $data;
$cart->save();
$status = true;
// }
break;
case 'redis':
Redis::set($cart_id, $data);
$status = true;
break;
}
// dd($status);
if ($status) {
Session::put(['cart_id' => $cart_id, 'cart_data' => $this->data]);
return true;
}
}
public function cartInit()
{
$this->data['total_qty'] = $this->totalQty;
$this->data['total_price'] = $this->totalPrice;
$this->data['items'] = [];
$this->cart_id .= '_' . Session::getId();
$storage = $this->storage;
if (Session::has('cart_id')) {
$cart_id = Session::get('cart_id');
switch ($storage) {
case 'mysql':
$cart = Carts::where('cart_id', $cart_id)->first();
if ($cart) $rec = json_decode($cart->items, true);
break;
case 'redis':
$cart = Redis::get($cart_id);
if ($cart) $rec = json_decode($cart, true);
break;
}
if (isset($rec)) {
if (!empty($rec['items'])) {
$this->data['total_qty'] = $rec['total_qty'];
$this->data['total_price'] = $rec['total_price'];
$this->data['items'] = $rec['items'];
}
$this->cart_id = $cart_id;
}
}
if (empty($this->data['items'])) Session::forget(['cart_id', 'cart_data']);
}
public function checkMultiArr($arr)
{
return ((count($arr, COUNT_RECURSIVE) - count($arr)) > 0) ? true : false;
}
public function setDefaultCart()
{
$this->data = [];
$this->totalPrice = 0;
$this->totalQty = 0;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Kris
* Date: 03.07.2017
* Time: 23:49
*/
namespace ShesShoppingCart\Providers;
use Illuminate\Support\ServiceProvider;
class CartServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
// $this->loadMigrationsFrom(__DIR__.'\..\migrations');
$this->publishes([
__DIR__.'/../migrations/'=>database_path('migrations'),
__DIR__.'/../Model/'=>app_path(),
]);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
} | 5a9a7d82d1e7914c460c9badadf74f132620a88e | [
"PHP"
] | 2 | PHP | evgShes/shes-package-cart | 733243ad040f20ff520a81f9117a3c176f568bdd | 902d2988e3367ec3838e9e4f209647460b2facbb |
refs/heads/master | <repo_name>gocode/goplayer<file_sep>/README.md
mediaplayer
===========
web based media player
<file_sep>/files.go
package main
import (
id3 "github.com/gocode/go-id3"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
type MediaFile struct {
Name string
IsDir bool
AbsPath string
Size float64
IsAudio bool
IsVideo bool
ID3Name string
Artist string
Album string
Length string
}
func getFiles(path string) ([]MediaFile, error) {
fileInfo, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
var files = make([]MediaFile, 0, len(fileInfo))
var f MediaFile
for _, fi := range fileInfo {
switch strings.ToLower(filepath.Ext(fi.Name())) {
case ".mp3", ".ogg":
var fd, err = os.Open(filepath.Join(path, fi.Name()))
if err != nil {
return nil, err
}
id := id3.Read(fd)
if id== nil {
id = &id3.File{}
}
f = MediaFile{
Name: fi.Name(),
IsDir: fi.IsDir(),
AbsPath: filepath.Join(path, fi.Name()),
Size: float64(fi.Size()) / (1024 * 1024),
IsAudio: true,
ID3Name: id.Name,
Artist: id.Artist,
Album: id.Album,
Length: id.Length,
}
files = append(files, f)
case "", ".mp4":
f = MediaFile{
Name: fi.Name(),
IsDir: fi.IsDir(),
AbsPath: filepath.Join(path, fi.Name()),
Size: float64(fi.Size()) / (1024 * 1024),
}
files = append(files, f)
}
}
return files[:len(files)], nil
}
<file_sep>/static/js/mediaplayer.js
angular.module('mediaplayer',['ui.bootstrap'])
.directive("filelist", function() {
return {
scope: true,
restrict: 'E',
replace: 'true',
templateUrl: 'static/filelist.html',
controller: function ($scope, $http, $rootScope) {
$scope.breadcrumb = [{Name: "/...", AbsPath: ""}];
HttpGet("/dir");
ishover=false;
$scope.play = function(file) {
if(file.IsDir === true) {
$scope.breadcrumb.push({Name: file.Name, AbsPath: file.AbsPath});
HttpGet("/dir?path=" + file.AbsPath);
} else if(file.IsAudio) {
$rootScope.audioSrc = "/media/?file=" + file.AbsPath;
$rootScope.audiosrcName = file.Name;
for (var i = $scope.files.length - 1; i >= 0; i--) {
$scope.files[i].isPlaying = false;
};
file.isPlaying = true;
}
};
$scope.gotoCrumb = function(i, p) {
$scope.breadcrumb = $scope.breadcrumb.slice(0, i + 1);
HttpGet("/dir?path=" + p);
};
function HttpGet(path) {
$http.get(path).success(function(data) {
$scope.files = data;
});
}
}
};
});
<file_sep>/main.go
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
)
var root string
func init() {
flag.StringVar(&root, "root", "/", "directory listed in the player when the application starts")
}
func directoryHandler(rw http.ResponseWriter, r *http.Request) {
var path string
if path = r.URL.Query().Get("path"); path == "" {
path = root
}
files, err := getFiles(path)
if err != nil {
fmt.Println(err)
}
enc := json.NewEncoder(rw)
if err := enc.Encode(files); err != nil {
fmt.Println(err)
}
}
func homeHandler(rw http.ResponseWriter, r *http.Request) {
http.ServeFile(rw, r, "static/mediaplayer.html")
}
func mediaFileHandler(rw http.ResponseWriter, r *http.Request) {
http.ServeFile(rw, r, r.URL.Query().Get("file"))
}
func staticFilesHandler(rw http.ResponseWriter, r *http.Request) {
http.ServeFile(rw, r, r.URL.Path[1:])
}
func main() {
flag.Parse()
http.HandleFunc("/", homeHandler)
http.HandleFunc("/dir", directoryHandler)
http.HandleFunc("/static/", staticFilesHandler)
http.HandleFunc("/media/", mediaFileHandler)
http.ListenAndServe(":9090", nil)
}
| 5192ca86af8a74b03afbdf3f38e2d2a0f698944e | [
"Markdown",
"JavaScript",
"Go"
] | 4 | Markdown | gocode/goplayer | a79867b17b348aaf83dc3068199d9658be89d7b0 | 5394231fd1ee6d112e1a2d7d5ad74159e2b13fdf |
refs/heads/master | <repo_name>AishwaryaPa/Cpp-Programming-Introduction<file_sep>/proj4/Game.cpp
/*****************************************
** File: Game.cpp
** Project: CMSC 202 Project 4, Fall 2017
** Author: <NAME>
** Date: 11/17/16
** Section: 07
** E-mail: <EMAIL>
**
** This file contains the code that controls the entire game.
** It initializes the Monsters, and Ben. It also identifies
** how many rounds (up to 20) the user would like to play.
** Deals with win/loss scenarios, battle, and the menu. Has
** an important destructor to make sure that there are no
** memory leaks!
**
***********************************************/
# include "Game.h"
const int MIN_RANGE = 1;
const int MAX_RANGE = 20;
// Game (Constructor)
// Controls the order of the entire game.
// When the user is finished, calls the destructor
Game::Game(){
// Initiate everything before starting the game per level
m_levels = NumLevels();
m_level = 0;
cout <<" The game starts.... " << endl;
InitBen();
m_mons = new Monster*[m_levels];
while (m_level < m_levels){
InitMonsters();
cout <<" Level " << m_level + 1 << " of " << m_levels << endl;
SetBen(m_currBen->GetLife());
Start(m_currBen->GetLife());
m_level = m_level + 1;
}
}
// ~Game (Destructor)
// Deletes all dynamically allocated data including
// the arrays of Ben and Monster and all the pointers
// inside of them
Game::~Game(){
for (int i = 0; i < 3; i++){
delete m_ben[i];
m_ben[i] = NULL;
}
delete [] m_ben;
m_ben = NULL;
for (int i = 0; i < m_levels; i++){
delete m_mons[i];
m_mons[i] = NULL;
}
delete [] m_mons;
m_mons = NULL;
}
// InitMonsters()
// Dynamically creates an Monster and puts it in the monster
// array. Finally sets the currMons to the newly created one
void Game::InitMonsters(){
Monster *monsPtr = new Monster(m_level);
m_mons[m_level] = monsPtr;
m_currMons = m_mons[m_level];
}
// InitBen()
// Dynamically creates all forms of ben in the ben array.
// Finally currBen is set to the first form in the array
// The firt form is ben. The second form is Pyronite.
// The third form is Crystalsapien
void Game::InitBen(){
m_formsBen = 3;
m_ben = new Ben*[m_formsBen];
// dynamically creates a pointer and points it at the object
Ben* benPtr = new Ben("Ben", 100, "hand-to-hand", "kick", 0, 10.0, 0, 2, 10, 20, 25);
m_ben[0] = benPtr;
Ben* pyronitePtr = new Pyronite("Pyronite", benPtr->GetLife(), "fire", "flamer", 0, 15.0, 0, 1, 15, 20, 30);
m_ben[1] = pyronitePtr;
Ben* crystalsapienPtr = new Crystalsapien("Crystalsapien", benPtr->GetLife(), "energy", "laser", 25.0, 25.0, 0, 1, 25, 30, 10);
m_ben[2] = crystalsapienPtr;
m_currBen = m_ben[0];
}
// SetBen()
// Sets m_currBen based on user choice
void Game::SetBen(int startLife){
int benForm;
int maxForms;
cout <<"Select one from the available forms of Ben at level " << m_level + 1 <<" are: " << endl;
// The options(based on the level) the user can choose are:
if (m_level >= 0){
cout << "1.Ben" << endl;
maxForms = 1;
}
if (m_level >= 1){
cout << "2.Pyronite" << endl;
maxForms = 2;
}
if (m_level >=2){
cout << "3.Crystalsapien " << endl;
maxForms = 3;
}
cout <<"What would you like to do?"<< endl;
// input validation
while ((cout << "Enter a number between " << MIN_RANGE
<< " and " << maxForms << ": " << endl)
&&(!(cin >> benForm))
|| (benForm < MIN_RANGE) || (benForm > maxForms)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input; please re-enter an integer between 1 and " << maxForms << endl;
}
// Life is set based on the value of the old form of Ben
int previousLife = m_currBen->GetLife();
m_currBen = m_ben[benForm - 1];
m_currBen->SetLife(previousLife);
}
// Start()
// Starts and guides the entire game by keeping track of points.
// If ben dies, the game ends and exits the function. If ben
// wins a level, he goes to the next level or he wins the entire
// game.
void Game::Start(int startLife){
// Shows the information of Ben and Monster
cout << "BEN: " << m_currBen->GetName() << endl;
cout << "MONSTER: " << m_currMons->GetName() << endl;
cout << "The start life of Ben is: " << m_currBen->GetLife() << endl;
cout << "The start life of " << m_currMons->GetName() << " is " << m_currMons->GetLife() << endl;
cout << "Ben: " << m_currBen->GetLife() << " " << m_currMons->GetName() <<": " << m_currMons->GetLife() << endl;
while (Input() == true){
// user choice validation
int option = 0;
int minOption = 1;
int maxOption = 3;
while ((cout << "What would you like to do?" << '\n'
<< "1. Normal Attack" << '\n'
<< "2. Special Attack" << '\n'
<< "3. Ultimate Attack" << '\n'
<< "Enter a number between " << minOption
<< " and " << maxOption << ": " << endl)
&&(!(cin >> option))
|| (option < minOption) || (option > maxOption)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input; please re-enter an integer between 1 and 3" << endl;
}
// Calls types of attack based on user choice
if (option == 1){
m_currBen->Attack(m_currMons);
}
else if (option == 2){
m_currBen->SpecialAttack(m_currMons);
}
else if (option == 3){
m_currBen->UltimateAttack(m_currMons);
}
if (Input() == true){
m_currMons->Attack(m_currBen);
cout << "Ben: " << m_currBen->GetLife() << " " << m_currMons->GetName() <<": " << m_currMons->GetLife() << endl;
}
}
// Win and loss
if (Input() == false) {
if (m_currBen->GetLife() > 0 || m_currMons <= 0){
cout <<"Congrats! " << m_currBen->GetName() <<" won that level" <<endl;
if (m_level + 1 == m_levels){
cout <<"Congrats! You won the game" << endl;
}
}
else if (m_currBen->GetLife() <= 0 || m_currMons->GetLife() > 0){
cout << "You lost" << endl;
m_level = m_levels; // if Ben loses, stop the game
}
}
}
// NumLevels()
// Returns the user reponse about how many levels he/she would like to play
int Game::NumLevels(){
int numLevels = 0;
// check correct value is entered and takes in a valid value
cout <<"How many levels would you like to try?" << endl;
while ((cout << "Enter a number between " << MIN_RANGE
<< " and " << MAX_RANGE << ": " << endl)
&&(!(cin >> numLevels))
|| (numLevels < MIN_RANGE) || (numLevels > MAX_RANGE)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input; please re-enter an integer between 1 and 20." << endl;
}
return numLevels;
}
// Input()
// Checks to see if Ben and monster are alive
// Return true if both are alive. Returns
// false if one dies
bool Game::Input(){
// Both must be alive to understand whether Ben should go to the next level
// or the game should end
if (m_currBen->GetLife() > 0 and m_currMons->GetLife() > 0){
return true;
}
else if (m_currBen->GetLife() <= 0 or m_currMons->GetLife() <= 0){
return false;
}
}
<file_sep>/proj5/proj5.cpp
#include "Spaceship.h"
#include "ReadySupply.h"
#include "ManageShips.h"
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <limits>
using namespace std;
//Name: showChoices
//Precondition: ReadySupply and ManageShips have been populated
//Postcondition: menu output to screen
bool showChoices();
//Name: MainMenu
//Precondition: ManageShips loaded
//Postcondition: Main menu displayed and doesn't escape until exit is chosen
void MainMenu(ManageShips &M);
//Name: displayTitle
//Precondition: None
//Postcondition: Simple ASCII output for the title of the application
void displayTitle();
//Uses command line. Should be ./proj5 proj5_ships.txt proj5_cargo.txt
int main(int argc, char* argv[])
{
displayTitle(); //Call to ASCII title
int choice = 0;
if (argc < 2) //Checks to see if the project call has any arguments
{
cout << "You must include two files to run the program. " << endl;
cout << "File 1 should be a file of ships. " << endl;
cout << "File 2 should be a file of cargo (people and items). " << endl;
}
else
{
ReadySupply R = ReadySupply(argv[1],argv[2]); //Populates all vectors
ManageShips M = ManageShips(R.GetItemShips(), R.GetPersonShips(),
R.GetItemCargo(), R.GetPersonCargo());
MainMenu(M); //Calls the main menu and populates all ManageShip needs
}
}
bool showChoices()
{
cout << "What would you like to do?" << endl;
cout << "1. Find the heaviest ship." << endl;
cout << "2. Find the lightest ship." << endl;
cout << "3. Find the heaviest item." << endl;
cout << "4. Find the lightest item." << endl;
cout << "5. Find the oldest person." << endl;
cout << "6. Find the youngest person." << endl;
cout << "7. Get People not loaded." << endl;
cout << "8. Get Cargo not loaded." << endl;
cout << "9. Write the output file." << endl;
cout << "10. Exit." << endl;
return true;
}
void MainMenu(ManageShips &M)
{
int option = 0;
while (option!=10){
while ((showChoices())
&& (!(cin >> option)
|| (option < 1) || (option > 11))) {
cin.clear(); //clear bad input flag
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //discard input
cout << "Invalid input; please re-enter." << endl;
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if(option == 1)
{
cout << "**Heaviest Ship**" << endl;
cout << M.GetHeaviestShip() << endl;
}
else if (option ==2)
{
cout << "**Lightest Ship**" << endl;
cout << M.GetLightestShip() << endl;
}
else if (option==3)
{
cout << "**Heaviest Item**" << endl;
cout << M.GetHeaviestItem() << endl;
}
else if (option==4)
{
cout << "**Lightest Item**" << endl;
cout << M.GetLightestItem() << endl;
}
else if (option==5)
{
cout << "**Oldest Person**" << endl;
cout << M.GetOldestPerson() << endl;
}
else if (option==6)
{
cout << "**Youngest Person**" << endl;
cout << M.GetYoungestPerson() << endl;
}
else if (option==7)
{
cout << "Remaining People" << endl;
M.DisplayPersonLeft();
}
else if (option==8)
{
cout << "Remaining Cargo" << endl;
M.DisplayItemLeft();
}
else if (option==9)
{
cout << "File Output" << endl;
M.OutputShips();
}
else if (option ==10)
cout << "Thank you for using the Space Trucker System" << endl;
}
}
void displayTitle() {
cout << "*** *** *** *** *** *** *** * * *** * * *** *** ***" << endl;
cout << "* * * * * * * * * * * * * * * * * * * " << endl;
cout << "*** *** *** * *** * *** * * * ** *** *** ***" << endl;
cout << " * * * * * * * ** * * * * * * ** *" << endl;
cout << "*** * * * *** *** * * * *** *** * * *** * * ***" << endl;
}
<file_sep>/proj4/Monster.cpp
/*****************************************
** File: Monster.cpp
** Project: CMSC 202 Project 4, Fall 2017
** Author: <NAME>
** Date: 11/17/16
** Section: 07
** E-mail: <EMAIL>
**
** This file contains the code for Monster. Monster name is
** randomly picked from monster.txt and its data is
** determined based on the level of the game. Monsters' data
** such as life and attack are controlled in this file.
**
***********************************************/
#include "Monster.h"
#include <cstdlib>
const char FILENAME[12] = "monster.txt";
// Monster (Constructor)
// Sets the name of the monster randomly from the monster.txt file.
// Sets the life and attack based on calculated values
Monster::Monster(int level){
m_name = SummonMonster();
srand(time(NULL));
// life values and attack values are set based on level
if (level == 0){
m_life = (rand() % (50 - 20)) + 20;
m_attack = (rand() % (5 - 1)) + 1;
}
else if (level == 1){
m_life = (rand() % (60 - 30)) + 30;
m_attack = (rand() % (10 - 3)) + 3;
}
else if (level >= 2){
m_life = (rand() % (70 - 40)) + 40;
m_attack = (rand() % (15 - 5)) + 5;
}
m_monster.clear();
}
// ~Monster
// does nothing
Monster::~Monster(){
// All memory is deleted in Game destructor
}
// SummonMonster
// Choses a random monster from the vector and returns its name
string Monster::SummonMonster(){
LoadMonster();
int vectorSize = ((int) m_monster.size()) - 1; // have to subtract one because the index starts at 0
int randomIndex = (rand() % (vectorSize - 0)) + 0;
int chosenIndex;
for (unsigned int i = 0; i <= vectorSize; i++) // finds the index choosen by random generator
{
if (i == randomIndex)
{
chosenIndex = i;
}
}
return m_monster[chosenIndex];
}
// LoadMonster
// Populates the vector with the monster names in the file
void Monster::LoadMonster(){
string name;
fstream inputStream;
inputStream.open(FILENAME);
while (getline(inputStream, name)){
m_monster.push_back(name);
}
inputStream.close();
}
// Attack()
// Attacks the opponent by reducing the oppenent's life value
void Monster::Attack(Ben *&target){
int opponentLife = target->GetLife();
// Attacks Crystalsapien based on defense bonus, so damage is reduced
if (target->GetName() == "Crystalsapien"){
int reduceDamage = static_cast<int>((target->GetDefenseBonus()/100)*m_attack);
target->SetLife(opponentLife - (m_attack - reduceDamage));
cout << m_name << " attacks " << target->GetName() << " using a normal attack." << endl;
cout << m_name << " did " << (m_attack - reduceDamage) << " to " << target->GetName() << endl;
}
// No defense bonus for other forms of ben, so attacks normally
else {
target->SetLife(opponentLife - m_attack);
cout << m_name << " attacks " << target->GetName() << " using a normal attack." << endl;
cout << m_name << " did " << m_attack << " to " << target->GetName() << endl;
}
}
// SetLife() updates the new value of life. The getters return the value they were asked for
void Monster::SetLife(int life){
m_life = life;
}
int Monster::GetLife(){
return m_life;
}
string Monster:: GetName(){
return m_name;
}
<file_sep>/proj4/Pyronite.cpp
/*****************************************
** File: Pyronite.cpp
** Project: CMSC 202 Project 4, Fall 2017
** Author: <NAME>
** Date: 11/17/16
** Section: 07
** E-mail: <EMAIL>
** Child class of Ben. Inherits lots of stuff and
** overrides Attack and Special Attack. Does not
** have an Ultimate Attack.
**
***********************************************/
#include "Pyronite.h"
#include "Monster.h"
#include <stdlib.h>
#include <time.h>
// Attack()
// Does calculated damage to the target based on data
void Pyronite::Attack(Monster *&target){
srand(time(NULL));
// 15% chance of missing the attack.
double miss = static_cast<double>(rand() % (100 - 1) + 1);
if (miss <= m_missPercent){
cout << m_name << " misses the normal attack. " << target->GetName() <<" retaliates!" << endl;
}
// if attack is not missed, then do damage to target
else {
int normalDamage = (rand() % (m_maxDamageNormal - m_minDamageNormal)) + m_minDamageNormal;
int opponentLife = target->GetLife();
target->SetLife(opponentLife - normalDamage);
cout << m_name << " attacks using his " << m_nameNormal << endl;
cout << m_name << " did " << normalDamage << " to " << target->GetName() << endl;
}
}
// SpecialAttack()
// Another type of attack, but does more damage. The number of attacks of this type
// is limited. This number is based on the form of Ben. If the user uses more than
// allowed, the monster will automatically retailiate. Damage data is calcuated
void Pyronite::SpecialAttack(Monster *&target){
// not allowed to use more than one special attack
if (m_usedSpecial >= m_maxSpecial){
cout << m_name <<" is out of special attacks! " << target->GetName() <<" retaliates!" << endl;
}
else if(m_usedSpecial < m_maxSpecial){
int opponentLife = target->GetLife();
target->SetLife(opponentLife - m_damageSpecial);
cout << m_name <<" attacks using his " << m_nameSpecial << endl;
cout << m_name <<" did " << m_damageSpecial << " to " << target->GetName() << endl;
m_usedSpecial = m_usedSpecial + 1;
}
}
<file_sep>/proj2/proj2.cpp
/*****************************************
** File: proj2.cpp
** Project: CMSC 202 Project 2, Fall 2016
** Author: <NAME>
** Date: 10/06/16
** Section: 07
** E-mail: <EMAIL>
**
** This file contains the main driver program for Project 2.
** It gets input from the text files pokeDex.txt and
** myCollection.txt and populates the vectors with that data.
** These vectors are used to show the data inside of them.
** They are also used so that the user could battle, train,
** and catch pokemon.
***********************************************/
#include "proj2.h"
int main () {
srand(10);
vector<Pokemon> pokeDex;
vector<MyPokemon> myCollection;
getPokeDex(pokeDex);
getMyCollection(myCollection);
mainMenu (pokeDex, myCollection);
return 0;
}
// getPokeDex(vector)
// Take input from a file and returns a populated pokeDex vector
void getPokeDex(vector<Pokemon>& pokeDex){
// Input from file pokeDex.txt
int num, cpMin, cpMax, rarity;
string name;
fstream inputStream;
inputStream.open(POKEDEX);
for (int i = 0; i < POKECOUNT; i++) {
inputStream >> num >> name >> cpMin >> cpMax >> rarity;
// Populates Vector
Pokemon newPokemon(num, name, cpMin, cpMax, rarity);
pokeDex.push_back(newPokemon);
}
inputStream.close();
}
// getMyCollection(vector)
// Take input from a file and returns a populated pokeDex vector
void getMyCollection(vector<MyPokemon> & myCollection){
// Input from file myCollection.txt
int num, cp, hp, rarity;
string name;
fstream inputStream;
inputStream.open(MYCOLLECTION);
while (inputStream >> num >> name >> cp >> hp >> rarity) {
// Populates vector
MyPokemon addPokemon(num, name, cp, hp, rarity);
myCollection.push_back(addPokemon);
}
inputStream.close();
}
// printPokeDex (vector)
// Takes in populated vector and prints the information in it for each pokemon
void printPokeDex(vector <Pokemon> & pokeDex){
for (unsigned i = 0; i < pokeDex.size(); i++) {
cout << pokeDex[i].GetNum() << " "
<< pokeDex[i].GetName() << " " << endl;
}
}
// printMyCollection (vector)
// Takes in populated vector and prints the information in it for each pokemon
void printMyCollection(vector <MyPokemon> & myCollection){
int count = 0;
for (unsigned i = 0; i < myCollection.size(); i++) {
cout << count << "." << " "
<< myCollection[i].GetNum() << " "
<< myCollection[i].GetName() << " "
<< myCollection[i].GetCP() << " "
<< myCollection[i].GetHP() << " "
<< myCollection[i].GetRarity() << endl;
count = count + 1;
}
}
// catchPokemon(vector, vector)
// Takes in the two vectors and tries to catch a random pokemon based on rarity.
// If a Pokemon is found, calls foundPokemon
void catchPokemon(vector <Pokemon> & pokeDex, vector<MyPokemon> & myCollection){
int typePokemon;
cout <<" What type of Pokemon would you like to try and catch?:" << endl;
cout <<" 1. Very Common (Very High Probability)" << endl;
cout <<" 2. Common (High Probability)" << endl;
cout <<" 3. Uncommon (Normal Probability) " << endl;
cout <<" 4. Rare (Low Probability) " << endl;
cout <<" 5. Ultra Rare (Extremely Low Probability) " << endl;
cin >> typePokemon;
cout << "You start to search" << endl;
srand(time(NULL));
int pokeNum = rand() % 100 + 1;
// check if pokemon has been found
if (typePokemon == 1 and pokeNum <= 65) {
foundPokemon(typePokemon, pokeDex, myCollection);
}
else if (typePokemon == 2 and pokeNum <= 45) {
foundPokemon(typePokemon, pokeDex, myCollection);
}
else if (typePokemon == 3 and pokeNum <= 25) {
foundPokemon(typePokemon, pokeDex, myCollection);
}
else if (typePokemon == 4 and pokeNum <= 10) {
foundPokemon(typePokemon, pokeDex, myCollection);
}
else if (typePokemon == 5 and pokeNum <= 1) {
foundPokemon(typePokemon, pokeDex, myCollection);
}
else {
cout << "Pokemon not found" << endl;
}
}
// foundPokemon (rarity, vector pokeDex, vector myCollection)
// Finds a pokemon based on the rarity passed from catchPokemon()
// and adds the new Pokemon to user's collection
void foundPokemon(int rarity, vector <Pokemon> & pokeDex,
vector<MyPokemon> & myCollection ){
bool pokemonFound = false;
while (pokemonFound == false) {
srand(time(NULL));
int pokeNum = rand() % POKECOUNT + 1;
int pokeIndex = pokeNum - 1;
// make sure the rarity of the new pokemon matches what the user entered
if (pokeDex[pokeIndex].GetNum() == pokeNum and pokeDex[pokeIndex].GetRarity() == rarity) {
cout << "Congrats! You found a " << pokeDex[pokeIndex].GetName() << endl;
int cpMin = pokeDex[pokeIndex].GetCPMin();
int cpMax = pokeDex[pokeIndex].GetCPMax();
// calcuate cp and hp
srand(time(NULL));
int cp = rand() % cpMax + cpMin;
int hp = static_cast<int> (cp * (.10));
int num = pokeNum;
string name = pokeDex[pokeIndex].GetName();
MyPokemon newPokemon (num, name, cp, hp, rarity);
myCollection.push_back(newPokemon);
pokemonFound = true;
}
}
}
// mainMenu(vector, vector)
// Calls various function based on user's choice. Passes the appropriate vectors when needed.
void mainMenu(vector <Pokemon> & pokeDex, vector<MyPokemon> & myCollection){
int option = 0;
bool isExit = 0;
do {
do {
cout << "What would you like to do?: " << endl;
cout << "1. See the PokeDex" << endl;
cout << "2. See your collection" << endl;
cout << "3. Search for a new Pokemon" << endl;
cout << "4. Battle Your Pokemon" << endl;
cout << "5. Train your Pokemon" << endl;
cout << "6. Exit" << endl;
cin >> option;
}while(option < 1 || option > 6);
switch(option){
case 1:
printPokeDex(pokeDex);
break;
case 2:
printMyCollection(myCollection);
break;
case 3:
catchPokemon(pokeDex, myCollection);
break;
case 4:
battlePokemon(pokeDex, myCollection);
break;
case 5:
trainPokemon(pokeDex, myCollection);
break;
case 6:
exitPokemon(myCollection);
isExit = 1;
}
}while(isExit == 0);
}
// battlePokemon(vector, vector)
// Randomly chooses an enemy and that pokemon's cp.
// Determines if battle is won or lost - returns to mainMenu
void battlePokemon(vector <Pokemon> & pokeDex, vector<MyPokemon> & myCollection){
// pick opponent randomly
srand(time(NULL));
int pokeNum = rand() % POKECOUNT + 1;
int pokeIndex = pokeNum - 1;
// randomly assigns cp for the oppenent
int cpMin = pokeDex[pokeIndex].GetCPMin();
int cpMax = pokeDex[pokeIndex].GetCPMax();
srand(time(NULL));
int cp = rand() % cpMax + cpMin;
string name = pokeDex[pokeIndex].GetName();
printMyCollection(myCollection);
cout << "You are going to fight a " << name << endl;
cout << "The enemy has a CP of " << cp << endl;
int userChoice;
cout << "Which of your Pokemon would you like to use?:" << endl;
cin >> userChoice;
if (myCollection[userChoice].GetCP() > cp) {
cout << "You won!!" << endl;
}
else {
cout << "You lost." << endl;
}
}
// trainPokemon(vector pokeDex, vector myCollection)
// trais the pokemon by increasing CP by 10. Updates myCollection
void trainPokemon(vector <Pokemon> & pokeDex, vector<MyPokemon> & myCollection){
int userChoice;
cout << "Which of your Pokemon would you like to use?:" << endl;
printMyCollection(myCollection);
cin >> userChoice;
myCollection[userChoice].Train();
cout << myCollection[userChoice].GetName() << " is trained" << endl;
cout << "Its CP is now " << myCollection[userChoice].GetCP() << endl;
}
// exitPokemon(vector)
// Calls saveMyCollection and exits application
void exitPokemon(vector<MyPokemon> & myCollection){
saveMyCollection(myCollection);
}
// saveMyCollection(vector)
// Saves all the changes user made
void saveMyCollection(vector<MyPokemon> & myCollection){
// updates myCollection.txt
fstream outputStream;
outputStream.open(MYCOLLECTION);
for (unsigned i = 0; i < myCollection.size(); i++) {
outputStream << myCollection[i].GetNum() << " "
<< myCollection[i].GetName() << " "
<< myCollection[i].GetCP() << " "
<< myCollection[i].GetHP() << " "
<< myCollection[i].GetRarity() << endl;
}
outputStream.close();
cout << "File Saved" << endl;
}
<file_sep>/proj2/Pokemon.cpp
/*****************************************
** File: proj2.cpp
** Project: CMSC 202 Project 2, Fall 2016
** Author: <NAME>
** Date: 10/06/16
** Section: 07
** E-mail: <EMAIL>
**
** This file contains the class Pokemon for project 2.
***********************************************/
#include "Pokemon.h"
using namespace std;
Pokemon::Pokemon(){
m_Num = 1;
m_Name = "Balbasaur";
m_MinCP = 321;
m_MaxCP = 1072;
m_Rarity = 2;
}
Pokemon::Pokemon(int num, string name, int cpMin, int cpMax, int rarity){
m_Num = num;
m_Name = name;
m_MinCP = cpMin;
m_MaxCP = cpMax;
m_Rarity = rarity;
}
// Accessors
int Pokemon::GetCPMin(){
return m_MinCP;
}
int Pokemon::GetCPMax(){
return m_MaxCP;
}
int Pokemon::GetRarity(){
return m_Rarity;
}
string Pokemon::GetName(){
return m_Name;
}
int Pokemon::GetNum(){
return m_Num;
}
// Mutators
void Pokemon::SetRarity(int newRarity){
m_Rarity = newRarity;
}
void Pokemon::SetName(string newName){
m_Name = newName;
}
<file_sep>/proj5/makefile
proj5: ReadySupply.o Item.o Person.o Spaceship.h ManageShips.o
g++ -g ReadySupply.o Item.o Person.o ManageShips.o proj5.cpp -o proj5
Item.o: Item.h Item.cpp
g++ -g -c Item.cpp
Person.o: Person.h Person.cpp
g++ -g -c Person.cpp
ManageShips.o: ManageShips.h ManageShips.cpp Person.h Person.cpp Item.h Item.cpp Spaceship.h ReadySupply.h
g++ -g -c ManageShips.cpp
ReadySupply.o: ReadySupply.h ReadySupply.cpp proj5.cpp
g++ -g -c ReadySupply.cpp
clean:
rm *.o
rm *~
run:
./proj5
run1:
./proj5 proj5_ships.txt proj5_cargo.txt <file_sep>/proj4/Game.h
#ifndef GAME_H
#define GAME_H
#include "Monster.h"
#include "Ben.h"
#include "Crystalsapien.h"
#include "Pyronite.h"
#include <limits>
class Game{
public:
//Name: Game (Constructor)
//Precondition: None
//Postcondition: Game is started with monsters initialized, ben initialized,
//decides number of levels
Game();
//Name: ~Game (Destructor)
//Precondition: Destructor for the game
//Postcondition: Deletes all dynamically allocated data
~Game();
//Name: InitMonsters
//Precondition: Requires m_mons
//Postcondition: Dynamically populates m_mons with one monster per level
void InitMonsters();
//Name: InitBen
//Precondition: Requires m_ben
//Postcondition: Dynamically populates m_ben with all possible forms
// Level 1 = Ben, Level 2 = Pyronite, Level 3 = Crystalsapien
void InitBen();
//Name: SetBen
//Precondition: Requires populated m_ben (Lists all possible Bens for that level)
//Postcondition: Sets m_currBen based on the user choice
void SetBen(int startLife);
//Name: Start
//Precondition: Starts the game (Primary driver of game)
//Postcondition: May exit if Ben dies (exits game) or Monster dies (goes to
//next level or wins game!
void Start(int startLife);
//Name: NumLevels
//Precondition: Prompts user for number of levels between 1 and 20
//Postcondition: Returns user response
int NumLevels();
//Name: Input
//Precondition: Checks to see if Ben and monster are alive
//During: Prompts user with menu
//Postcondition: Manages types of attacks (normal, special, or ultimate)
bool Input();
protected:
int m_level; //Current level
int m_levels; //Total levels
int m_formsBen; //Number of total forms (1 level = 1 ben, 2 level = 2 ben, 3+ = 3)
Ben **m_ben; //Data structure holding all the forms of ben available
Ben *m_currBen; //Pointer to the current Ben (or form)
Monster **m_mons; //Data structure holding monster (1 for each level)
Monster *m_currMons; //Pointer to the current monster
};
#endif
<file_sep>/proj4/notes.txt
For project 4, in the make file, write the child class .h file and .cpp file as the dependencies for parent class.
This will the child class whenever the parent class is updated
randomizer when missing (1-10) if 1 miss. other wise not miss
<file_sep>/proj5/Item.cpp
/*****************************************
** File: Item.cpp
** Project: CMSC 202 Project 5, Fall 2016
** Author: <NAME>
** Date: 12/01/16
** Section: 07
** E-mail: <EMAIL>
**
** This file contains code for defining cargo
** items. Used in item ships in ReadySupply.cpp
**
****************************************/
#include "Item.h"
// Item()
// Default contructor. User for safety reasons
Item::Item(){
m_id = 67246;
m_name = "Rovers_47";
m_weight = 606845.60;
}
// Item() constructor
// Creates an object of item. Takes three
// arguements: id, name, and weight
Item::Item(int inId, string inName, float inWeight){
m_id = inId;
m_name = inName;
m_weight = inWeight;
}
// Accessors for Item
// return the appropriate member varibales when needed
int Item::GetId() const{
return m_id;
}
string Item::GetName() const{
return m_name;
}
float Item::GetWeight() const{
return m_weight;
}
// ToString()
// Returns a properly formatted string of all information about the item
string Item::ToString() const{
// format a string containg information about name, id, and weight
ostringstream os;
os << "Item Name: " << m_name
<< "\nID: " << m_id
<< "\nWeight: " << fixed << setprecision (2) << m_weight << endl;
return os.str();
}
<file_sep>/proj2/MyPokemon.cpp
/*****************************************
** File: proj2.cpp
** Project: CMSC 202 Project 2, Fall 2016
** Author: <NAME>
** Date: 10/06/16
** Section: 07
** E-mail: <EMAIL>
**
** This file contains the class MyPokemon for project 2
***********************************************/
#include "MyPokemon.h"
using namespace std;
//Constructors
MyPokemon::MyPokemon () {
m_Num = 27;
m_Name = "Sandshrew";
m_CP = 77;
m_HP = 7;
m_Rarity = 1;
}
MyPokemon::MyPokemon (int num, string name, int cp, int hp, int rarity) {
m_Num = num;
m_Name = name;
m_CP = cp;
m_HP = hp;
m_Rarity = rarity;
// Pokemon pokemon1;
}
//Accessors
int MyPokemon::GetCP(){
return m_CP;
}
int MyPokemon::GetHP(){
return m_HP;
}
int MyPokemon::GetRarity(){
return m_Rarity;
}
string MyPokemon::GetName(){
return m_Name;
}
int MyPokemon::GetNum(){
return m_Num;
}
//Mutators
void MyPokemon::SetRarity(int newRarity){
m_Rarity = newRarity;
}
void MyPokemon::SetName(string newName){
m_Name = newName;
}
void MyPokemon::SetCP(int newCP){
m_CP = newCP;
}
void MyPokemon::SetHP(int newHP){
m_HP = newHP;
}
//Member Functions
// Train()
// trains pokemon by adding ten cp
void MyPokemon::Train(){
m_CP = m_CP + 10;
}
<file_sep>/proj3/proj3.cpp
/*****************************************
** File: proj3.cpp
** Project: CMSC 202 Project 3, Fall 2016
** Author: <NAME>
** Date: 11/01/16
** Section: 07
** E-mail: <EMAIL>
**
** This file contains the main driver program for Project 3.
** It gets input from the text files the user enters and
** and stores that data in a linked list. All the functions
** related to the linked list are in LinkedList.cpp.
***********************************************/
#include "LinkedList.h"
#include "proj3.h"
int main () {
LinkedList list;
mainMenu(list);
return 0;
}
// readFile()
// Reads in a file that the user enters.
void readFile(LinkedList &list){
bool listEmpty = list.IsEmpty();
int option = 0;
// if the list is not empty
if (listEmpty == false)
{
cout << "Do you want to: " << endl;
cout <<"1. Overwrite the message " << endl;
cout <<"2. Append the message " <<endl;
cout <<"3. Cancel " << endl;
cin >> option;
if (option == 1)
{
cout << "Previous message cleared" << endl;
option = 0;
}
}
// if the list is empty or list is not empty but need to add new data into the list
if (option == 0 or option == 2)
{
int num;
string code;
string userFileName;
cout <<"What is the file name?:"<< endl;
cin >> userFileName;
fstream inputStream;
inputStream.open(userFileName.c_str());
cout << "file uploaded" << endl;
while (inputStream >> num >> code)
{
list.InsertEnd(num, code);
}
inputStream.close();
}
}
// mainMenu(list)
// displays options and takes in user input. Calls a function that
// corresponds to that input
void mainMenu(LinkedList &list){
int option = 0;
bool isExit = 0;
do {
do {
cout << "What would you like to do?: " << endl;
cout << "1. Load a new encrypted message" << endl;
cout << "2. Display a raw message" << endl;
cout << "3. Display an encrypted message" << endl;
cout << "4. Exit" << endl;
cin >> option;
}while(option < 1 || option > 4);
switch(option){
case 1:
readFile(list);
break;
case 2:
displayMessage(list);
break;
case 3:
displayEncrypt(list);
break;
case 4:
exitLinked(list);
isExit = 1;
}
}while(isExit == 0);
}
// displayMessage(list)
// displays two messages that has not been decrypted.
// one that is not sorted and one that is sorted
void displayMessage(LinkedList &list){
bool listEmpty = list.IsEmpty();
if (listEmpty == true)
{
cout << "You haven't loaded an encrypted message yet." << endl;
}
else if (listEmpty == false)
{
list.Display();
list.Sort();
list.Display();
}
}
// exitLinked(list)
// if the list is not empty, clear the list and exits
void exitLinked(LinkedList &list){
bool isEmpty = list.IsEmpty();
if (isEmpty == false)
{
list.~LinkedList();
}
cout <<"Have a nice day!" << endl;
}
// displayEncrypt(list)
// displays the message that has been encrypted. Only the nodes
// that have perfect square or perfect cube numbers
void displayEncrypt(LinkedList &list){
bool listEmpty = list.IsEmpty();
if (listEmpty == true)
{
cout << "You haven't loaded an encrypted message yet." << endl;
}
else if (listEmpty == false)
{
LinkedList list2 = list.Decrypt();
list2.Sort();
list2.Display();
list2.~LinkedList();
}
}
<file_sep>/proj5/ManageShips.cpp
/*****************************************
** File: ManageShips.cpp
** Project: CMSC 202 Project 4, Fall 2017
** Author: <NAME>
** Date: 12/01/16
** Section: 07
** E-mail: <EMAIL>
**
** This file contains code for ManageShips class. This class manages
** a majority of the functions. After everything is loaded and some
** calculations are being done, this class manages the various
** aspects including getting the Heaviest and Lightest ships
** (regardless if they are person or item ships), Oldest and Youngest
** person, and Heaviest and Lightest items. Also can output any person
** or item not loaded into a ship due to capacity limitations. Finally,
** can write an output file that contains each ship name and then each
** of the cargo.
**
***********************************************/
# include "ManageShips.h"
const char FILENAME[17] = "proj5_output.txt";
// ManageShips() constructor
// Takes in all the data from ReadySupply in form of vectors.
// These vectors are used in all of the functions in this
// class to calcuate what the user needs. LoadItemShip()
// and LoadPersonShip() must be immediately called for all
// the function to work
ManageShips::ManageShips(vector< Spaceship <Item> > itemShip,
vector< Spaceship <Person> > personShip,
vector< Item > itemCargo,
vector< Person > personCargo){
m_itemShips = itemShip;
m_personShips = personShip;
m_items = itemCargo;
m_person = personCargo;
cout <<" Item Ships Loaded: " << m_itemShips.size() << endl;
cout <<" Person Ships Loaded: " << m_personShips.size() << endl;
cout <<" Persons Loaded: " << m_person.size() << endl;
cout <<" Items Loaded: " << m_items.size() << endl;
LoadItemShip();
LoadPersonShip();
}
// LoadItemShip
// Each ship is loaded with items until it reaches its capacity
// (weight limit). Every item is loaded on the first avaliable
// ship meaning that even ships that already have been loaded
// will be checked for avaliability. It is possible that some
// items may not be loaded in any ships
void ManageShips::LoadItemShip(){
unsigned int shipIndex = 0, itemIndex = 0;
vector<double> totalWeight (m_itemShips.size()); // keeps track of each ships' weight.
vector<Item> unloadedItems; // keep track of unloaded items for DisplayItemsLeft();
// keeps going until every item is tried to be put inside a ship
while (itemIndex != m_items.size()){
bool exitWhileLoop = false;
while(exitWhileLoop == false){
if (shipIndex < m_itemShips.size()){ // make sure there are ships avaliable to put the item inside
if(totalWeight[shipIndex] + m_items[itemIndex].GetWeight() < m_itemShips[shipIndex].GetCapacity()){
m_itemShips[shipIndex].AddCargo(m_items[itemIndex]); // Adds cargo in the ship by acessing the vector m_cargo in Spaceship.h
totalWeight[shipIndex] = totalWeight[shipIndex] + m_items[itemIndex].GetWeight();
exitWhileLoop = true;
shipIndex = 0;
}
else{
shipIndex = shipIndex + 1;
}
}
else{ // exit if the item could not be put inside any ship
unloadedItems.push_back(m_items[itemIndex]);
exitWhileLoop = true;
shipIndex = 0; // Make sure to check for the first avaliable ship
}
}
itemIndex = itemIndex + 1;
}
m_items = unloadedItems; // only keep track of unloaded items for DisplayItemLeft()
}
// LoadPersonShip
// Loads people into each ship until the ship reaches capacity
// (limited by number of people it can hold). It is possible
// that there may not be enough ships to hold all people.
void ManageShips::LoadPersonShip(){
unsigned int shipIndex = 0;
unsigned int personIndex = 0;
// keep going until every ship is loaded or every person is tried to
// be put inside a ship and stop if there are no more ships or people
while (shipIndex != m_personShips.size() and personIndex != m_person.size()){
int totalPeople = 0;
bool stopAddingPeople = false;
while(stopAddingPeople == false and personIndex != m_person.size()){
if(totalPeople <= (m_personShips[shipIndex].GetCapacity()-1)){ // check if ship has enough capacity to hold the person
m_personShips[shipIndex].AddCargo(m_person[personIndex]); // Adds cargo in the ship by acessing the vector m_cargo in Spaceship.h
totalPeople = totalPeople + 1;
personIndex = personIndex + 1; // load the next person
}
else{
stopAddingPeople = true;
shipIndex = shipIndex + 1; // go to next ship
}
}
}
}
// DisplayItemLeft()
// Outputs all the unloaded items. At the end of LoadItemShips(), m_items is
// updated with only unloaded items.
void ManageShips::DisplayItemLeft(){
if (m_items.size() > 0){ // m_items now only holds the unloaded items. This vector should have been updated at the end of LoadItemsShips()
for (unsigned int i = 0; i < m_items.size(); i++){
cout << "Item " << i << "- Name: " << m_items[i].GetName() << " - Weight: " << m_items[i].GetWeight()<< endl;
}
}
else{
cout <<"None" << endl; // Display "None" if no items were left behind
}
}
// DisplayPersonLeft()
// Outputs all the people not loaded. First calcuates total capacity of all
// ships. Since capacity is limited by number of people a ship can hold, the
// capacity is therefore a whole number. Then turns totalCapacity into an
// integer and accesses the people not loaded by indexing them from m_person
void ManageShips::DisplayPersonLeft(){
double totalCapacity = 0.0; // number of people all ships can hold
for (unsigned int i = 0; i < m_personShips.size(); i++){
totalCapacity = totalCapacity + m_personShips[i].GetCapacity();
}
int personIndex = static_cast<int>(totalCapacity);
if (personIndex >= 0){ // index must be greater than zero so it cannot accesses out of bounds
int counter = 1; // for printing the number for each person
while (personIndex != m_person.size()){
cout << "Person " << counter << " - Name: " << m_person[personIndex].GetFName() << endl;
personIndex = personIndex + 1;
counter = counter + 1;
}
}
}
// OutputShips()
// Writes out all ships and their cargo to a specific output file
// Output file will always be proj5_output.txt
void ManageShips::OutputShips(){
ofstream outstream;
outstream.open(FILENAME);
// Write the name of the ship and underneath it, write all the cargo inside of it
// First writes out the data about personnel ships.
outstream << "**Personnel Ships**" << endl;
for (unsigned int i = 0; i < m_personShips.size(); i++){
outstream << "**Ship Name: " << m_personShips[i].GetName() <<"**" << endl;
cout <<"**Ship Name: " << m_personShips[i].GetName() << "**" << endl;
vector <Person> cargo = m_personShips[i].GetCargo();
if (cargo.size() > 0){
for (unsigned int j = 0; j < cargo.size(); j++){
outstream << cargo[j].GetFName() << " " << cargo[j].GetLName()<< endl;
cout << cargo[j].GetFName() << " " << cargo[j].GetLName() << endl;
}
}
else{
outstream << "Empty" << endl;
cout << "Empty" << endl;
}
cout << " " << endl;
}
// Then writes about the item ships
outstream << "**Item Ships**" << endl;
for (unsigned int i = 0; i < m_itemShips.size(); i++){
outstream << "**Ship Name: " << m_itemShips[i].GetName() <<"**" <<endl;
cout <<"**Ship Name: " << m_itemShips[i].GetName() << "**" << endl;
vector <Item> cargo = m_itemShips[i].GetCargo();
if(cargo.size() > 0){
for (unsigned int j = 0; j < cargo.size(); j++){
outstream << cargo[j].GetName() << endl;
cout << cargo[j].GetName() << endl;
}
}
else{
outstream << "Empty" << endl;
cout << "Empty" << endl;
}
cout << " " << endl;
}
outstream.close();
}
// GetHeaviestShip()
// Uses the overloaded operator in Spaceship.h file to compare the ships'
// weight. Keeps track of the heaviest ship by using a pointer. At the
// end, heaviest ship's information is returned by calling its ToString()
// function
string ManageShips::GetHeaviestShip(){
Spaceship<Item> *itemShipPtr = &m_itemShips[0]; // pointer that keeps track of heaviest item ship' weight
for (unsigned int i = 0; i < m_itemShips.size(); i++){
if (m_itemShips[i] > *itemShipPtr){
itemShipPtr = &m_itemShips[i];// update pointer to point at item ship holding the most weight
}
}
Spaceship<Person> *personShipPtr = &m_personShips[0]; // pointer that keeps track of heaviest person ship's weight
for (unsigned int i = 0; i < m_personShips.size(); i++){
if (m_personShips[i] > *personShipPtr){
personShipPtr = &m_personShips[i]; // update pointer to point at person ship holding the most weight
}
}
if (*itemShipPtr > *personShipPtr){ // finally compare the heaviest person ship and heaviest person ship
return itemShipPtr->ToString();
}
else{
return personShipPtr->ToString();
}
}
// GetLightestShip()
// Uses the overloaded operator in Spaceship.h file to compare the ships'
// weight. Keeps track of the lightest ship by using a pointer. At the
// end, lightest ship's information is returned by calling its ToString()
// function.
string ManageShips::GetLightestShip(){
Spaceship<Item> *itemShipPtr = &m_itemShips[0]; // pointer that keeps track of lightest item ship' weight
for (unsigned int i = 0; i < m_itemShips.size(); i++){
if (m_itemShips[i] < *itemShipPtr){
itemShipPtr = &m_itemShips[i]; // update pointer to point at item ship holding the least weight
}
}
Spaceship<Person> *personShipPtr = &m_personShips[0]; // pointer that keeps track of lightest person ship' weight
for (unsigned int i = 0; i < m_personShips.size(); i++){
if (m_personShips[i] < *personShipPtr){
personShipPtr = &m_personShips[i]; // update pointer to point at person ship holding the least weight
}
}
if (*itemShipPtr < *personShipPtr){ // finally compare the lightest item ship and lightest person ship
return itemShipPtr->ToString();
}
else{
return personShipPtr->ToString();
}
}
// GetLightestItem()
// Checks all the items in all item ships to find the lightest item
// Finally reutnrs a string that is properly formatted with all
// information about the item.
string ManageShips::GetLightestItem(){
// Initialize information for the object
string name = "Rovers_47";
int id = 67246;
double weight = 606845.60;
// Loop through every ship to find lightest item
for (unsigned int i = 0; i < m_itemShips.size(); i++){
vector<Item>cargo = m_itemShips[i].GetCargo(); // check items in m_cargo vector in Spaceship.h
if (cargo.size() > 0){ // make sure ship is not empty
for (unsigned int j = 0; j < cargo.size(); j++){
if (cargo[j].GetWeight() < weight){
name = cargo[j].GetName();
id = cargo[j].GetId();
weight = cargo[j].GetWeight();
}
}
}
}
Item item1 (id, name, weight); // Finally create an object excatly like the lightest item
string printString = item1.ToString(); // ToString() will give the properly formatted string
return printString;
}
// GetHeaviestItem()
// Checks all the items in all item ships to find the heaviest item
// Finally reutnrs a string that is properly formatted with all
// information about the item.
string ManageShips::GetHeaviestItem(){
// Initialize information for the object
string name = "Rovers_47";
int id = 67246;
double weight = 606845.60;
// Loop through every ship to find heaviest item
for (unsigned int i = 0; i < m_itemShips.size(); i++){
vector<Item>cargo = m_itemShips[i].GetCargo(); // check items in m_cargo vector in Spaceship.h
if (cargo.size() > 0){ // make sure ship is not empty
for (unsigned int j = 0; j < cargo.size(); j++){
if (cargo[j].GetWeight() > weight){
name = cargo[j].GetName();
id = cargo[j].GetId();
weight = cargo[j].GetWeight();
}
}
}
}
Item item1 (id, name, weight); // Finally create an object excatly like the heaviest item
string printString = item1.ToString(); // ToString() will give the properly formatted string
return printString;
}
// GetOldestPerson()
// Checks all the people in all people ships to find the oldest person
// Finally reutnrs a string that is properly formatted with all
// information about the person.
string ManageShips::GetOldestPerson(){
// Initialize information for the object
string fName = "Chaney" , lName = "Booth";
int age = 71;
double weight = 191;
// Loop through every ship to find oldest person
for (unsigned int i = 0; i < m_personShips.size(); i++){
vector<Person>cargo = m_personShips[i].GetCargo(); // check people in m_cargo vector in Spaceship.h
if (cargo.size() > 0){ // make sure ship is not empty
for (unsigned int j = 0; j < cargo.size(); j++){
if (cargo[j].GetAge() > age){
fName = cargo[j].GetFName();
lName = cargo[j].GetLName();
age = cargo[j].GetAge();
weight = cargo[j].GetWeight();
}
}
}
}
Person person1 (fName, lName, weight, age, 0); // Finally create an object excatly like the oldest person
string printString = person1.ToString(); // ToString() will give the properly formatted string
return printString;
}
// GetYoungestPerson()
// Checks all the people in all people ships to find the youngest person
// Finally reutnrs a string that is properly formatted with all
// information about the person.
string ManageShips::GetYoungestPerson(){
// Initialize information for the object
string fName = "Chaney" , lName = "Booth";
int age = 71;
double weight = 191;
// Loop through every ship to find youngest person
for (unsigned int i = 0; i < m_personShips.size(); i++){
vector<Person>cargo = m_personShips[i].GetCargo(); // check people in m_cargo vector in Spaceship.h
if (cargo.size() > 0){ // make sure ship is not empty
for (unsigned int j = 0; j < cargo.size(); j++){
if (cargo[j].GetAge() < age){
fName = cargo[j].GetFName();
lName = cargo[j].GetLName();
age = cargo[j].GetAge();
weight = cargo[j].GetWeight();
}
}
}
}
Person person1 (fName, lName, weight, age, 0); // Finally create an object excatly like the youngest person
string printString = person1.ToString(); // ToString() will give the properly formatted string
return printString;
}
<file_sep>/proj4/Ben.h
#ifndef BEN_H
#define BEN_H
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Monster;
class Ben{
public:
//Name: Ben (Constructor)
//Precondition: Need to have the name and the life (from table in project doc)
//Postcondition: Creates a default version of Ben (not transformed)
Ben(string name, int life);
//Name: Ben (Overloaded constructor)
//Precondition: Need to have all of the stats for an advanced form
//Data from table in project document
//Postcondition: Creates a specific version of Ben for use in transformed versions
Ben(string name, int life, string nameNorm, string nameSpecial,
double defenseBonus, double missPercent, int usedSpecial,
int maxSpecial, int minDamNorm, int maxDamNorm, int damSpec);
//Name: ~Ben
//Precondition: Dynamically allocated Ben (using new)
//Postcondition: Removes allocated Ben from memory
~Ben();
//Name: Attack
//Precondition: Need a target (May miss!)
//Postcondition: Reduces life of target with output
virtual void Attack(Monster *&target);
//Name: Special Attack
//Precondition: Needs a target (Finite number of special attacks by form)
//Postcondition: Reduces life of target with output
virtual void SpecialAttack(Monster *&target);
//Name: Ultimate Attack
//Precondition: Needs a target (only available with Crystalsapien)
//Postcondition: Reduces life of target with output
virtual void UltimateAttack(Monster *&target);
//Name: Mutators and Acccessors
void SetLife(int life);
string GetName();
int GetLife();
double GetDefenseBonus();
protected:
string m_name; //Form of Ben (Normal for 1st level)
string m_nameNormal; //Normal attack description
string m_nameSpecial; //Special attack description
int m_life; //Current Life
double m_defenseBonus; //Special Bonus for certain forms
double m_missPercent; //Miss Percent
int m_usedSpecial; //Number special attacks used
int m_maxSpecial; //Max number of special attacks
int m_minDamageNormal; //Minimum damage for normal attack
int m_maxDamageNormal; //Maximum damage for normal attack
int m_damageSpecial; //Damage for special attack
vector <Ben> m_forms; //Stores all possible forms
};
#endif
<file_sep>/proj2/makefile
CXX = g++
CXXFLAGS = -Wall
proj2: Pokemon.o MyPokemon.o proj2.cpp
$(CXX) $(CXXFLAGS) Pokemon.o MyPokemon.o proj2.cpp -o proj2
Pokemon.o: Pokemon.cpp Pokemon.h
$(CXX) $(CXXFLAGS) -c Pokemon.cpp
MyPokemon.o: MyPokemon.cpp MyPokemon.h
$(CXX) $(CXXFLAGS) -c MyPokemon.cpp
clean:
rm -rf *.o
rm -f *# *h.gch *~
<file_sep>/proj1/proj1.cpp
/*
File: Project 1
Project: CMSC 202 Project 1, Fall 2016
Author: <NAME>
Date: 09/23/16
Section: 07
E-mail: <EMAIL>
Description: This program contains information about an
ATM with very basic features
*/
#include "proj1.h"
const char* FILENAME = "proj1.txt";
int main () {
int menuStartChoice = menuStart();
// In case the user chooses 3, this if statement will prevent the while loop from executing
int exit = 1;
if (menuStartChoice == 3) {
exit = 0;
}
string fName, lName;
int age;
float accountBalance;
while (exit == 1) {
switch (menuStartChoice)
{
// Loads User Input from proj1.txt file
case 1:
{
fstream inputStream;
inputStream.open(FILENAME);
inputStream >> fName >> lName >> age >> accountBalance;
inputStream.close();
menuStartChoice = 4;
break;
}
// New User Profile
case 2:
{
cout << "First Name: " << endl;
cin >> fName;
cout << "Last Name: " << endl;
cin >> lName;
cout << "Age: " << endl;
cin >> age;
cout << "Initial Deposit: " << endl;
cin >> accountBalance;
cout << "$" << fixed << setprecision (2) << accountBalance << " " << "deposited" << endl;
menuStartChoice = 4;
break;
}
case 4:
{
int menuMainChoice = menuMain();
switch (menuMainChoice)
{
case 1:
{
displayBalance(accountBalance);
break;
}
case 2:
{
deposit(accountBalance);
break;
}
case 3:
{
withdraw(accountBalance);
break;
}
case 4:
{
displayAccountDetails(fName, lName, age, accountBalance);
break;
}
case 5:
{
string saveOption;
cout << "Would you like to save your account information?: " << endl;
cout << "yes or no" << endl;
cin >> saveOption;
if (saveOption == "yes") {
fstream outputStream;
outputStream.open(FILENAME);
outputStream << fName << " " <<lName << " " <<age << " " << accountBalance;
outputStream.close();
cout << "File Saved" << endl;
}
exit = 0;
}
}
}
}
}
cout << "Thank you for using the UMBC ATM" << endl;
return 0;
}
/*
Name: menuStart()
PreCondition: None
PostCondition: Returns the selected option (1, 2, or 3)
*/
int menuStart() {
// choices
cout <<"Welcome to the UMBC ATM" << endl;
cout <<"Choose from below:" << endl;
cout <<"1. Load a User Profile from File" <<endl;
cout <<"2. Enter a new User Profile" <<endl;
cout <<"3. Exit" << endl;
int userChoice;
cout <<"Enter your choice:" << endl;
cin >> userChoice;
//user verification
while (userChoice < 1 or userChoice > 3) {
cout << "Enter choice between 1 and 3:" << endl;
cin >> userChoice;
}
return userChoice;
}
/*
Name: menuMain()
PreCondition: The user input has either been loaded from file or entered by user
PostCondition: Returns the selected option (1, 2, 3, 4, or 5)
*/
int menuMain() {
// choices
cout << "********Please choose option from the menu*********" << endl;
cout << "1. Account Balance" << endl;
cout << "2. Deposit money" << endl;
cout << "3. Withdraw money" << endl;
cout << "4. Display your account details" << endl;
cout << "5. Exit" << endl;
int userChoice;
cout <<"Enter your choice:" << endl;
cin >> userChoice;
//user verification
while (userChoice < 1 or userChoice > 5) {
cout << "Enter choice between 1 and 5:" << endl;
cin >> userChoice;
}
return userChoice;
}
/*
Name: displayBalance
PreCondition: Relevant data (accountBalance) has been loaded/entered
PostCondition: None (void)
*/
void displayBalance(float accountBalance) {
cout << "Account Balance: " << fixed << setprecision (2) <<"$"<< accountBalance << endl;
}
/*
Name: displayAccountDetails
PreCondition: Relevant data (fName, lName, age, accountBalance) has been loaded/entered
PostCondition: None (void)
*/
void displayAccountDetails(string fName, string lName, int age, float accountBalance) {
cout << "First Name: " << " " << fName << endl;
cout << "Last Name: " << " " << lName << endl;
cout << "Age: " << " " << age << endl;
cout << "Account Balance: " << fixed << setprecision (2) << "$" << accountBalance << endl;
}
/*
Name: deposit
PreCondition: Variable accountBalance is passed-by-reference
PostCondition: accountBalance is permanently changed via pass-by-reference
*/
void deposit(float &accountBalance) {
float amount;
cout << "Please enter the amount to be deposited: " << endl;
cin >> amount;
if (amount > 0){
accountBalance = accountBalance + amount;
cout << "$" << fixed << setprecision (2) << amount << " " << "deposited to your account" << endl;
}
else if (amount <= 0){
cout << "Amount should be greater than 0" << endl;
}
}
/*
Name: withdraw
PreCondition: Variable accountBalance is passed-by-reference
PostCondition: accountBalance is permanently changed via pass-by-reference
*/
void withdraw(float &accountBalance) {
float amount;
cout << "Please enter the amount to be withdrawn: " << endl;
cin >> amount;
if (amount > accountBalance){
cout << "You can only withdraw" << " " <<fixed << setprecision (2) << "$" << accountBalance << " " << "or less" << endl;
}
else if (amount < accountBalance and amount > 0){
accountBalance = accountBalance - amount;
cout << "$" << fixed << setprecision (2) << amount << " " <<"withdrawn from your account" << endl;
}
else if (amount <= 0){
cout << "Amount must be greater than zero" << endl;
}
}
<file_sep>/proj5/Item.h
#ifndef ITEM_H
#define ITEM_H
#include <string>
#include <sstream>
#include <iomanip>
#include "Person.h"
using namespace std;
class Item
{
public:
// Constructors for Item
Item();
Item(int inId, string inName, float inWeight);
// Accessors for Item
int GetId() const;
string GetName() const;
float GetWeight() const;
//Name: ToString
//Precondition: Requires item to be formatted for output
//Postcondition: Creates single string for output
//Allowed to use <sstream> for this (not necessarily)
string ToString() const;
private:
int m_id;
string m_name;
float m_weight;
};
#endif
<file_sep>/proj4/Monster.h
#ifndef MONSTER_H
#define MONSTER_H
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <stdlib.h>
#include "Ben.h"
#include "Game.h"
using namespace std;
class Monster{
public:
//Name: Monster (Constructor)
//Precondition: Must have the level of the game.
//Sets the name of the monster randomly from the monster.txt file.
//Sets the life and attack based on calculated values
//Postcondition: Loads a new monster with stats based on the level.
Monster(int level);
//Name: ~Monster
//Precondition: Something must be dynamically allocated
//Postcondition: None
~Monster();
//Name: SummonMonster
//Precondition: Need to have the m_monster vector populated by LoadMonster
//Postcondition: Returns the string value of a random monster from the vector
string SummonMonster();
//Name: LoadMonster
//Precondition: Must have the m_monster vector available and the monster.txt
//Postcondition: Populates the m_monster vector with the monster names in the file
void LoadMonster();
//Name: Attack
//Precondition: Must have a form of Ben to attack
//Postcondition: Reduces current version of Ben by calculated damage
void Attack(Ben *&target);
//Name: Mutators and Accessors
//Normal getters and setters
void SetLife(int life);
int GetLife();
string GetName();
protected:
//Name - Name of the monster
string m_name;
//Life - Calculated number of life points for the monster
int m_life;
//Attack - Calculated number of attack for the monster
int m_attack;
//Vector to hold the entire list of monster names
vector <string> m_monster;
};
#endif
<file_sep>/proj5/ReadySupply.h
#ifndef READYSUPPLY_H
#define READYSUPPLY_H
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include "Spaceship.h"
#include "Item.h"
#include "Person.h"
using namespace std;
class ReadySupply{
public:
//Name: ReadySupply() and ReadySupply(string, string)
//Precondition: Requires two files a ship file and a cargo file
//Postcondition: Populates two vectors
ReadySupply();
ReadySupply(string shipFile, string cargoFile);
//Name: LoadShips
//Precondition: Requires a ships file
//Postcondition: Builds TWO vectors
//Ship 1: Holds people (person)
//Ship 2: Holds cargo (items)
void LoadShips();
//Name: LoadCargo
//Precondition: Requires a cargo file
//Postcondition: Builds TWO vectors
//Cargo 1: Holds people (person)
//Cargo 2: Holds cargo (item)
void LoadCargo();
//Name: GetItemShips
//Precondition: Requires that item ships have been built
//Postcondition: Returns a vector of all item ships
vector< Spaceship<Item> > GetItemShips();
//Name: GetPersonShips
//Precondition: Requires that person ships have been built
//Postcondition: Returns a vector of all person ships
vector< Spaceship<Person> > GetPersonShips();
//Name: GetItemCargo
//Precondition: Requires that all item vectors have been built
//Postcondition: Returns a vector of all items
vector< Item > GetItemCargo();
//Name: GetPersonCargo
//Precondition: Requires that all person vectors have been built
//Postcondition: Returns a vector of all people (person)
vector< Person > GetPersonCargo();
private:
string m_shipFile;
string m_cargoFile;
vector< Spaceship<Item> > m_itemShips;
vector< Spaceship<Person> > m_personShips;
vector< Person> m_personCargo;
vector< Item> m_itemCargo;
};
#endif
<file_sep>/proj5/Person.cpp
/*****************************************
** File: Person.cpp
** Project: CMSC 202 Project 4, Fall 2016
** Author: <NAME>
** Date: 12/01/16
** Section: 07
** E-mail: <EMAIL>
**
** This file contains code for defining people
** used in personnel ships.
**
****************************************/
# include "Person.h"
// Person()
// Default contructor. Used for safety reasons
Person::Person(){
m_id = 12;
m_fName = "Dennis";
m_lName = "Gutierrez";
m_age = 89;
m_weight = 345.0;
}
// Person() constructor
// Creates an object of person. Takes five
// arguements: first name, last name, weight,
// age, and weight
Person::Person(string infName, string inlName, double inWeight, int inAge, int inId){
m_id = inId;
m_fName = infName;
m_lName = inlName;
m_age = inAge;
m_weight = inWeight;
}
// Accessors for Person
// return the appropriate member varibales when needed
int Person::GetId() const{
return m_id;
}
string Person::GetFName() const{
return m_fName;
}
string Person::GetLName() const{
return m_lName;
}
int Person::GetAge() const{
return m_age;
}
double Person::GetWeight() const{
return m_weight;
}
// ToString()
// Returns a properly formatted string of all information about the person
string Person::ToString() const{
// format a string containg information about first name, last name, age, and weight
ostringstream os;
os << "First Name: " << m_fName
<< "\nLast Name: " << m_lName
<< "\nAge: " << m_age
<< "\nWeight: " << m_weight << endl;
return os.str();
}
<file_sep>/proj4/proj4.cpp
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
#include "Monster.h"
#include "Game.h"
#include "Ben.h"
#include "Pyronite.h"
#include "Crystalsapien.h"
int main(){
srand(time(NULL)); //Seeds random number generator
Game G; //Starts a game
return 0;
}
<file_sep>/proj3/makefile
CXX = g++
CXXFLAGS = -Wall
proj3: LinkedList.o proj3.cpp
$(CXX) $(CXXFLAGS) -g LinkedList.o proj3.cpp -o proj3
LinkedList.o: LinkedList.cpp LinkedList.h
$(CXX) $(CXXFLAGS) -g -c LinkedList.cpp
clean:
rm -rf *.o
rm -f *# *h.gch *~
<file_sep>/proj5/ReadySupply.cpp
/*****************************************
** File: ReadySupply.cpp
** Project: CMSC 202 Project 4, Fall 2016
** Author: <NAME>
** Date: 12/01/16
** Section: 07
** E-mail: <EMAIL>
**
** This file contains code for ReadySupply Class .
** This class is designed to load files into vectors.
** Uses the proj5_cargo.txt to build Items and
** Persons. Uses proj5_ships.txt to build item ships
** and person ships. After ships are “built” they are
** filled with the appropriate cargo: person ships
** are filled with persons (only) and item ships are
** filled with items (only)
**
***********************************************/
#include "ReadySupply.h"
// ReadySupply() Default Constructor
// Does nothing. But here for safety reasons
ReadySupply::ReadySupply(){
m_shipFile = "proj5_ship.txt";
m_cargoFile = "proj5_cargo.txt";
}
// ReadySupply() Overloaded constructor
// Creates an objects of ReadySupply. Immediately loads ships and
// cargo so they can be accessed by ManageShips class in main
ReadySupply::ReadySupply(string shipFile, string cargoFile){
m_shipFile = shipFile;
m_cargoFile = cargoFile;
LoadCargo();
LoadShips();
}
// LoadShips
// Populates two vectors: One that holds the names of ships
// carrying people and another that holds the names of ships
// carrying items
void ReadySupply::LoadShips(){
string character, name;
double capacity;
fstream inputStream;
inputStream.open(m_shipFile.c_str());
while (inputStream >> character){
// Populate m_itemShips with objects of Spaceships.
// This vector specifically keeps track of ships holding only items
if (character == "Item"){
inputStream >> name >> capacity;
Spaceship<Item> itemShip(name, character, capacity);
m_itemShips.push_back(itemShip);
}
// Populate m_personShips with objects of Spaceships.
// This vector specifically keeps track of ships holding only people
else if (character == "Person"){
inputStream >> name >> capacity;
Spaceship<Person> personShip(name, character, capacity);
m_personShips.push_back(personShip);
}
}
inputStream.close();
}
// LoadCargo
// Populates two vectos: one that holds the objects of items
// and another that holds objects of people
void ReadySupply::LoadCargo(){
string character, fName, lName;
int age, id;
double weight;
fstream inputStream;
inputStream.open(m_cargoFile.c_str());
while (inputStream >> character){
// Populates m_itemCargo with only objects of items
if (character == "i"){
inputStream >> id >> fName >> weight;
Item item1(id, fName, weight);
m_itemCargo.push_back(item1);
}
// populates m_personCargo with only objects of person
else if (character == "p"){
inputStream >> fName >> lName >> weight >> age >> id;
Person person1(fName, lName, weight, age, id);
m_personCargo.push_back(person1);
}
}
inputStream.close();
}
// GetItemShips
// Returns the vectors that is populated with ships caryying items
vector< Spaceship<Item> > ReadySupply::GetItemShips(){
return m_itemShips;
}
// GetPersonShips
// Returns a vector that is populated with person ships
vector< Spaceship<Person> > ReadySupply::GetPersonShips(){
return m_personShips;
}
// GetItemCargo
// Returns a vector of all items
vector< Item > ReadySupply::GetItemCargo(){
return m_itemCargo;
}
// GetPersonCargo
// Returns a vector of all people (person)
vector< Person > ReadySupply::GetPersonCargo(){
return m_personCargo;
}
<file_sep>/proj4/Ben.cpp
/*****************************************
** File: Ben.cpp
** Project: CMSC 202 Project 4, Fall 2017
** Author: <NAME>
** Date: 11/17/16
** Section: 07
** E-mail: <EMAIL>
**
** This file contains the code for Ben. It has several
** data members that are populated during the constructor.
** Has some virtual functions that are overridden by child
** classes including Pyronite and Crystalsapien.
**
***********************************************/
#include "Ben.h"
#include "Monster.h"
#include <stdlib.h>
#include <time.h>
// Ben (Constructor)
// Creates an object of Ben and his forms
Ben::Ben(string name, int life){
m_name = name;
m_life = life;
m_usedSpecial = 0;
}
// Ben (Overloaded constructor)
// Creates a specific version of Ben for use in transformed versions
Ben::Ben(string name, int life, string nameNorm, string nameSpecial,
double defenseBonus, double missPercent, int usedSpecial,
int maxSpecial, int minDamNorm, int maxDamNorm, int damSpec){
m_name = name;
m_nameNormal = nameNorm;
m_nameSpecial = nameSpecial;
m_life = life;
m_defenseBonus = defenseBonus;
m_missPercent = missPercent;
m_usedSpecial = usedSpecial;
m_maxSpecial = maxSpecial;
m_minDamageNormal = minDamNorm;
m_maxDamageNormal = maxDamNorm;
m_damageSpecial = damSpec;
}
// ~Ben
// does nothing
Ben::~Ben(){
//All memory is deleted in Game Destructor
}
// Attack()
// Attacks target based on calcuated data.
// It is possible for Ben and his forms to miss.
void Ben::Attack(Monster *&target){
srand(time(NULL));
// 10% chance of missing the attack.
double miss = static_cast<double>(rand() % (100 - 1) + 1);
if (miss <= m_missPercent){
cout << m_name << " misses the normal attack. " << target->GetName() <<" retaliates!" << endl;
}
// if attack is not missed, then do damage
else {
int normalDamage = (rand() % (m_maxDamageNormal - m_minDamageNormal)) + m_minDamageNormal;
int opponentLife = target->GetLife();
target->SetLife(opponentLife - normalDamage);
cout << m_name <<" attacks using his " << m_nameNormal << endl;
cout << m_name <<" did " << normalDamage << " to " << target->GetName() << endl;
}
}
// SpecialAttack()
// Another type of attack, but does more damage. The number of attacks of this type
// is limited. This number is based on the form of Ben. If the user uses more than
// allowed, the monster will automatically retailiate. Damage data is calcuated
void Ben::SpecialAttack(Monster *&target){
// not allowed to use more than two special attacks
if (m_usedSpecial >= m_maxSpecial){
cout << m_name <<" is out of special attacks! " << target->GetName() <<" retaliates!" << endl;
}
else if(m_usedSpecial < m_maxSpecial){
int opponentLife = target->GetLife();
target->SetLife(opponentLife - m_damageSpecial);
cout << m_name << " attacks using his " << m_nameSpecial << endl;
cout << m_name << " did " << m_damageSpecial << " to " << target->GetName() << endl;
m_usedSpecial = m_usedSpecial + 1; // keeps track of number of special attacks the user used
}
}
// Ultimate Attack()
// This attack is only avaliable for Crystalsapien. If other
// forms use this attack, the target automatically retaliates
void Ben::UltimateAttack(Monster *&target){
cout <<"Ben has no ultimate attack! " << target->GetName() << " retaliates!" << endl;
}
// Name: Mutators and Acccessors
// SetLife() updates values and the rest return a member variable
void Ben::SetLife(int life){
m_life = life;
}
string Ben::GetName(){
return m_name;
}
int Ben::GetLife(){
return m_life;
}
double Ben::GetDefenseBonus(){
return m_defenseBonus;
}
<file_sep>/proj5/Person.h
#ifndef PERSON_H
#define PERSON_H
#include <string>
#include <sstream>
#include <iomanip>
#include "Item.h"
using namespace std;
class Person
{
public:
// Constructors for Person
Person();
Person(string infName, string inlName, double inWeight, int inAge, int inId);
// Accesssors for Person
int GetId() const;
string GetFName() const;
string GetLName() const;
int GetAge() const;
double GetWeight() const;
// Name: ToString
// Precondition: Needs a Person object to create output string
// Postcondition: Creates a single string for output
string ToString() const;
private:
int m_id;
string m_fName;
string m_lName;
int m_age;
double m_weight;
};
#endif
<file_sep>/proj3/LinkedList.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <string>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
struct Node {
long m_int;
string m_payload;
Node *m_next;
};
class LinkedList {
public:
//name: LinkedList (default constructor)
//pre: None
//post: new linked list where m_head points to NULL
LinkedList();
//name: LinkedList (destructor)
//pre: There is an existing linked list
//post: A linked list is deallocated (including nodes) to have no memory leaks!
~LinkedList();
//name: CreateNode
//pre: Takes in an int and a string
//post: Dynamically creates a new node with a pointer to the next item plus the int
// and string
Node* CreateNode(int newInt, string newPayload);
//name: InsertEnd
//pre: Takes in an int and a string. Requires a linked list
//post: Adds a new node to the end of the linked list.
void InsertEnd(int newInt, string newPayload);
//name: Display
//pre: Outputs the linked list (raw or encrypted)
//post: None
void Display();
//name: Sort
//pre: Takes in a linked list
//post: Sorts the linked list by integer (either raw or decrypted)
void Sort();
//name: IsEmpty
//pre: Takes in a linked list
//post: Checks to see if the linked list is empty or not
bool IsEmpty();
//name: Decrypt
//pre: Takes in a linked list
//post: Returns a linked list where any nodes where the int is NOT a perfect square
// or perfect cube is thrown out. Also, returns the square root (for perfect squares)
// or cubed root (for perfect cubes).
// For example, "121 candy" goes in - "11 candy" comes out.
LinkedList Decrypt();
//name: isPerfectSquare
//pre: Takes in an integer
//post: Returns if it is a perfect square or not
bool IsPerfectSquare(int n);
//name: isPerfectCube
//pre: Takes in an integer
//post: Returns if it is a perfect cube or not
bool IsPerfectCube(int n);
//name Clear
//pre: Takes in a linked list
//post: Clears out the linked list (all nodes too)
void Clear();
private:
Node *m_head;
Node *m_tail;
};
#endif
<file_sep>/proj2/Pokemon.h
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
class Pokemon{
public:
//Constructors
Pokemon();
Pokemon(int num, string name, int cpMin, int cpMax, int rarity);
//Accessors
int GetCPMin();
int GetCPMax();
int GetRarity();
string GetName();
int GetNum();
//Mutators
void SetRarity(int newRarity);
void SetName(string newName);
void SetCP(int newCP);
private:
int m_Num;
string m_Name;
int m_MinCP;
int m_MaxCP;
int m_Rarity;
};
<file_sep>/proj3/LinkedList.cpp
/*****************************************
** File: LinkedList.cpp
** Project: CMSC 202 Project 2, Fall 2016
** Author: <NAME>
** Date: 11/01/16
** Section: 07
** E-mail: <EMAIL>
**
** This file contains the functions for Linked list.
** It dynamically creates nodes that will store the
** data. In order to decrypt the code, the list is
** first sorted by m_int and then displayed. Finally,
** the list is deleted.
***********************************************/
# include "LinkedList.h"
#include <string>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
// contructor
LinkedList::LinkedList(){
m_head = NULL;
m_tail = NULL;
}
// destructor
LinkedList::~LinkedList(){
Clear();
}
// CreateNode(int newInt, string newPayload)
// dynamically allocates a new node, populates it with data,
// and returns it to InsertEnd()
Node *LinkedList::CreateNode(int newInt, string newPayload){
Node *newNode = new(Node); //(struct Node)
newNode->m_int = newInt;
newNode->m_payload = newPayload;
newNode->m_next = NULL;
return newNode;
}
// InsertEnd(int newInt, string newPayload)
// Calls CreateNode, and adds a new node at the end of the list
void LinkedList::InsertEnd(int newInt, string newPayload){
Node *newNode = CreateNode(newInt, newPayload);
// first node
if (m_head == NULL)
{
m_head = newNode;
m_tail = newNode;
}
// rest of the nodes
else
{
m_tail->m_next = newNode;
m_tail = newNode;
}
}
// Display()
// diaplays the message. It does not have to be sorted.
void LinkedList:: Display(){
Node *CURR = m_head;
cout << "Payload of list are: "<< endl;
while (CURR != NULL)
{
cout << CURR->m_payload << "->";
CURR = CURR->m_next;
}
cout << "END" << endl;
}
// Sort()
// Bubble sorts the list by m_int value.
void LinkedList::Sort(){
Node *CURR = m_head;
// count number of nodes so the for loop can be executed that many times
int numForLoop = 0;
while (CURR != NULL)
{
numForLoop = numForLoop + 1;
CURR = CURR->m_next;
}
// sort out the list
int counter = 0;
while (counter != numForLoop)
{
for (CURR = m_head; CURR != NULL; CURR = CURR->m_next)
{
if (CURR->m_next != NULL) // Make sure both items in the pair are not pointing to NULL
{
Node *firstNode = CURR;
Node *secondNode = CURR->m_next;
if (firstNode->m_int > secondNode->m_int)
{
int integer = secondNode->m_int;
string code = secondNode->m_payload;
// swap second node's data with the first node's data
secondNode->m_int = firstNode->m_int;
secondNode->m_payload = firstNode->m_payload;
// swap first node's data with the second node's data
firstNode->m_int = integer;
firstNode->m_payload = code;
}
}
}
counter = counter + 1;
}
}
// IsEmpty()
// Checks if the list is empty or not
bool LinkedList::IsEmpty(){
if (m_head == NULL)
{
return true;
}
return false;
}
// Decrypt()
// Takes a encrypted message and decrypts by choosing only the
// values that have a perfect square or perfect cube
LinkedList LinkedList::Decrypt(){
LinkedList list2;
Node *CURR;
for (CURR = m_head; CURR != NULL; CURR = CURR->m_next)
{
bool perfectSquare = IsPerfectSquare(CURR->m_int);
bool perfectCube = IsPerfectCube(CURR->m_int);
if (perfectSquare == true or perfectCube == true)
{
if (perfectSquare == true)
{
CURR->m_int = sqrt(CURR->m_int);
}
if (perfectCube == true)
{
CURR->m_int = cbrt(CURR->m_int);
}
list2.InsertEnd(CURR->m_int, CURR->m_payload);
}
}
return list2;
}
// IsPerfectSquare(int n)
// returns the squareroot of the integer given
bool LinkedList::IsPerfectSquare(int n){
int squareRoot = sqrt(n);
if (squareRoot*squareRoot == n){
return true;
}
return false;
}
// IsPerfectCube(int n)
// returns the cuberoot of the integer given
bool LinkedList::IsPerfectCube(int n){
int cubeRoot = cbrt(n);
if (cubeRoot*cubeRoot*cubeRoot == n){
return true;
}
return false;
}
// Clear()
// deallocates all the pointers in the list and
// finally sets head to NULL
void LinkedList::Clear(){
Node * curr = m_head;
Node * next = m_head;
while (next != NULL)
{
curr = next;
next = next->m_next;
delete curr;
}
m_head = NULL;
}
<file_sep>/proj4/Pyronite.h
#ifndef PYRONITE_H
#define PYRONITE_H
#include <iostream>
using namespace std;
#include "Ben.h"
class Pyronite:public Ben{
public:
//Name: Pyronite (Constructor)
//Precondition: Need name and life
//Postcondition: Builds new pyronite using default values (unused)
Pyronite(string name, int life)
: Ben(name, life)
{
}
//Name: Pyronite (Overloaded Constructor)
//Precondition: Inherits from Ben (requires all individual pieces)
//Postcondition: Transforms Ben into a pyronite
Pyronite(string name, int life, string nameNormal, string nameSpecial,
double defenseBonus, double missPercent, int usedSpecial,
int maxSpecial, int minDamNorm, int maxDamNorm, int damSpec)
:Ben(name,life, nameNormal, nameSpecial, defenseBonus,
missPercent, usedSpecial, maxSpecial, minDamNorm,
maxDamNorm, damSpec )
{
}
//Name: Attack
//Precondition: Requires target
//Postcondition: Does calculated damage to the target based on table in project doc
void Attack(Monster *&target);
//Name: Special Attack
//Precondition: Requires target (finite uses)
//Postcondition: Does calculated damage to the target based on table in project doc
void SpecialAttack(Monster *&target);
//Note: No ultimate attack
};
#endif
<file_sep>/proj3/proj3.h
#include "LinkedList.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
/*name: readFile
Pre: Takes in a linked list by reference may or may not be empty
Post: Asks the user for file name. Tries to open the file and read the file
into a linked list. File may be any size. File contains int and string on each line
*/
void readFile(LinkedList &list);
/*
name: displayMessage
Pre: Requires a linked list (encrypted message)
Post: Displays the "raw" message - which has all the nodes still it in.
*/
void displayMessage(LinkedList &list);
/*
name: mainMenu
Pre: Requires a linked list (passed by reference)
Post: None
*/
void mainMenu(LinkedList &list);
/*
name: exitLinked
Pre: Requires a linked list (passed by reference) (to deallocate)
Post: list is deallocated and the application is exited.
*/
void exitLinked(LinkedList &list);
/*
name: displayEncrypt
Pre: Requires a linked list (an encrypted message)
Post: Displays only the decrypted message by creating a new linked list
and copying only the perfect squares and perfect cubes to it.
The new linked list with "real" clues is then sorted to display the message.
When this is done running the original message is still available in list.
The new linked list is deallocated.
*/
void displayEncrypt(LinkedList &list);
| f24b08e2cf0f13b85e73355587a04eebd9fa927f | [
"Text",
"Makefile",
"C++"
] | 30 | C++ | AishwaryaPa/Cpp-Programming-Introduction | 1700fb9f14ef19173c133830b6f16e8b66c7af9c | 8ad8672b57745d29ce3df4053c3491b236e650c4 |
refs/heads/master | <repo_name>sangwonle/fds-picky<file_sep>/README.md
# 0802 update
package.json의 의존성 항목에 vuex를 추가하였습니다.
따로 pull이나 merge등을 할 필요는 없고 현재 project에 vuex를 설치하면 됩니다.
``` bash
npm install -save vuex
```
아직 이 repository를 clone 하지 않았다면 clone후 다음 명령어를 실행해 주세요
``` bash
npm install
```
또한 vuex 사용을 위해
./src/store
./stc/index.js
가 있어야 합니다.
더불어
[fds-picky-vue-template](https://github.com/fc-pickyeater/fds-picky-vue-template)
위 template에 vuex 설치 여부 질의 항목이 추가되었습니다.
# Project Structure
vue template docs에서 긁어옴... 차차 번역 하겠습니다.
``` bash
.
├── build/ # webpack config files
│ └── ...
├── config/
│ ├── index.js # main project config
│ └── ...
├── docs/ # spec등 문서들
├── src/
│ ├── main.js # app entry file
│ ├── App.vue # main app component
│ ├── components/ # ui components
│ │ └── ...
│ └── assets/ # module assets (processed by webpack)
│ └── ...
├── static/ # pure static assets (directly copied)
├── test/
│ └── unit/ # unit tests
│ │ ├── specs/ # test spec files
│ │ ├── index.js # test build entry file
│ │ └── karma.conf.js # test runner config file
│ └── e2e/ # e2e tests
│ │ ├── specs/ # test spec files
│ │ ├── custom-assertions/ # custom assertions for e2e tests
│ │ ├── runner.js # test runner script
│ │ └── nightwatch.conf.js # test runner config file
├── .babelrc # babel config
├── .postcssrc.js # postcss config
├── .eslintrc.js # eslint config
├── .editorconfig # editor config
├── index.html # index.html template
└── package.json # build scripts and dependencies
```
### `build/`
This directory holds the actual configurations for both the development server and the production webpack build. Normally you don't need to touch these files unless you want to customize Webpack loaders, in which case you should probably look at `build/webpack.base.conf.js`.
### `config/index.js`
This is the main configuration file that exposes some of the most common configuration options for the build setup. See [API Proxying During Development](proxy.md) and [Integrating with Backend Framework](backend.md) for more details.
### `docs/`
spec등 문서들
### `src/`
This is where most of your application code will live in. How to structure everything inside this directory is largely up to you; if you are using Vuex, you can consult the [recommendations for Vuex applications](http://vuex.vuejs.org/en/structure.html).
### `static/`
This directory is an escape hatch for static assets that you do not want to process with Webpack. They will be directly copied into the same directory where webpack-built assets are generated.
See [Handling Static Assets](static.md) for more details.
### `test/unit`
Contains unit test related files. See [Unit Testing](unit.md) for more details.
### `test/e2e`
Contains e2e test related files. See [End-to-end Testing](e2e.md) for more details.
### `index.html`
This is the **template** `index.html` for our single page application. During development and builds, Webpack will generate assets, and the URLs for those generated assets will be automatically injected into this template to render the final HTML.
### `package.json`
The NPM package meta file that contains all the build dependencies and [build commands](commands.md).
## vue template 설치시 설정된 사항들
[fds-picky-vue-template](https://github.com/fc-pickyeater/fds-picky-vue-template)
- project 이름 picky_cookbook
- project 설명 (Vue.js project) Fast Campus front-end dev. school 4기 team 7의 project. 주제는 '음식2: 오늘 뭐먹지?'
- 제작자 FDS4기team7
- Vue 빌드 standalone
- Pug를 사용 하시겠습니까? Yes
- Sass를 사용 하시겠습니까? Yes
- Vue-router를 사용 하시겠습니까? Yes
- ESLint를 사용 하시겠습니까? Yes
- ESLint pre-set을 선택해 주세요. Airbnb
- unit test를 위한 Karma와 Mocha를 설치 하시겠습니까? Yes
- e2e test를 위한 Nightwatch를 설치 하시겠습니까? Yes
## Build Setup
``` bash
# 의존 모듈 설치
npm install
# web server (localhost:8080)로 구동
npm run dev
# 배포를 위한 압축, build
npm run build
# 배포를 위한 압축, build와 bundle analyzer report 보기
npm run build --report
# unit test 수행
npm run unit
# e2e test 수행
npm run e2e
# 모든 test 수행
npm test
```
보다 자세한 사용법은 [가이드](https://vuejs-templates.github.io/webpack/), [vue-loader 문서(한국어 번역)](https://vue-loader.vuejs.org/kr/)를 읽어보세요.
<file_sep>/test/e2e/specs/test.js
// Nightwatch 테스트를 저작하는 방법
// http://nightwatchjs.org/guide#usage
module.exports = {
'default e2e tests': function test(browser) {
// config/index.js 파일의 dev 서버 포트를 자동으로 사용합니다.
// 기본 설정: http://localhost:8080
// nightwatch.conf.js를 확인하세요.
const devServer = browser.globals.devServerURL;
browser
.url(devServer)
.waitForElementVisible('#app', 5000)
.assert.elementPresent('.hello')
.assert.containsText('h1', 'Welcome to Your Vue.js App')
.assert.elementCount('img', 1)
.end();
},
};
<file_sep>/docs/spec_recipe_book.md
# specification of 'RecipeBook'
- RecipeBook은 RecipeItem의 순서없는 집합이다.
- view 관점에서 RecipeBook과 RecipeItem의 관계는 list와 list item의 관계.
- RecipeBook이 구성되는 경우는 다음과 같다. (: 앞은 RecipeBook의 이름)
- keyword 검색
- [keyword]RecipeBook: 사용자 임의 입력 keyword
- [keyword]RecipeBook: 자동 집계된 인기 keyword
- rankedRecipeBook: 자동 집계된 인기 RecipeItem의 모음
- 사용자 행위 누적
- repliedRecipeBook: 사용자가 reply한 RecipeItem의 모음
- bookmarkedRecipeBook: 사용자가 bookmark한 RecipeItem의 모음
- scoredRecipeBook: 사용자가 score한 RecipeItem의 모음
- likedRecipeBook: 사용자가 like한 RecipeItem의 모음
- recentRecipeBook: 사용자가 **최근** read한 RecipeItem의 모음
- myRecipeBook: 사용자가 write한 RecipeItem의 모음
## Recipe
- RecipeItem는 RecipeBook의 item으로 표시되기 위한 Recipe의 축약표현이다.
- RecipeItem은 다음 상태에 따라 외형이 변한다.
- logined=true AND current_RecipeBook=myRecipeBook
| ad00d775addff8b92523082fcad67a8717bb98be | [
"Markdown",
"JavaScript"
] | 3 | Markdown | sangwonle/fds-picky | 473d85722b71207a0b3d9bcdce95d9e1ba9379fc | cff29e18fb1eb12127a472366966d93d4ede967a |
refs/heads/master | <file_sep>//
// ZJScreenAdaptaionMacro.h
// FreeLimit1502
//
// Created by mac on 15/5/21.
// Copyright (c) 2015年 <NAME>. All rights reserved.
//
#ifndef FreeLimit1502_ZJScreenAdaptaionMacro_h
#define FreeLimit1502_ZJScreenAdaptaionMacro_h
#define AdaptaionFlag
#ifdef AdaptaionFlag
#define CGRectMake CGRectMakeEx
#define CGSizeMake CGSizeMakeEx
#define widthEx widthEx
#define heightEx heightEx
#else
#define CGRectMake CGRectMake
#define CGSizeMake CGSizeMake
#define widthEx
#define heightEx
#endif
#endif
<file_sep># FanMovies
一个仿翻片的项目
<file_sep>//
// Interface.h
// FindMovies
//
// Created by qianfeng on 15/10/27.
// Copyright © 2015年 qianfeng. All rights reserved.
//
#ifndef Interface_h
#define Interface_h
#endif /* Interface_h */
//推荐页面的网址:http://morguo.com/forum.php?mod=movieexplorer&v=3&androidflag=1&appfrom=ios&iosversion=3.11&page=1
#define COMMEND_URL @"http://morguo.com/forum.php?mod=movieexplorer&v=3&androidflag=1&appfrom=ios&iosversion=3.11&page=%d"
//从推荐页面进入:http://morguo.com/forum.php?mod=collection&action=view&ctid=1000959&androidflag=1&appfrom=ios&iosversion=3.11&page=1
#define DETAIL_COMMEND_URL @"http://morguo.com/forum.php?mod=%@&action=view&ctid=%@&androidflag=1&appfrom=ios&iosversion=3.11&page=%d"
//上映:http://morguo.com/forum.php?mod=movie&type=1&androidflag=1&appfrom=ios&iosversion=3.11&page=1
#define SCREEN_URL @"http://morguo.com/forum.php?mod=movie&type=%d&androidflag=1&appfrom=ios&iosversion=3.11&page=%d"
//短片: http://morguo.com/forum.php?mod=threadvideo&androidflag=1&appfrom=ios&iosversion=3.11&page=1
#define SHORT_URL @"http://morguo.com/forum.php?mod=threadvideo&androidflag=1&appfrom=ios&iosversion=3.11&page=%d"
//影单:http://morguo.com/forum.php?mod=collection&op=recommend&androidflag=1&appfrom=ios&iosversion=3.11&page=1
#define MOVIELIST_URL @"http://morguo.com/forum.php?mod=collection&op=recommend&androidflag=1&appfrom=ios&iosversion=3.11&page=%d"
//电影原声播放地址:http://morguo.com/data/attachment/forum/201510/27/105653isngy7wky25wya9z.mp3
#define MOVITE_VIDEO @"http://morguo.com/data/attachment/forum/201510/27/105653isngy7wky25wya9z.mp3"
| 69fe9c7604bab5c2be91b978d81c6b2f5f7a9517 | [
"Markdown",
"C"
] | 3 | C | Joanwq/FanMovies | dba9ca5211973c84d02d09630dfa752753ead99d | 36a050f4457860d3cd2fa01512ba5f4266e54ab8 |
refs/heads/main | <file_sep>package com.battleship.board;
public enum XCoord {
One("1"),
Two("2"),
Three("3"),
Four("4"),
Five("5"),
Six("6"),
Seven("7"),
Eight("8"),
Nine("9"),
Ten("10");
private final String identifier;
XCoord(String identifier) {
this.identifier = identifier;
}
public String getIdentifier() {
return identifier;
}
}
<file_sep>package com.battleship.gameplay;
import com.battleship.board.Board;
import com.battleship.board.Point;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
public class OpponentTest {
Board board;
Opponent op;
@Before
public void init() {
board = new Board();
op = new Opponent();
}
/*
@Test
public void branchTest() {
Point[] testArray = op.makeBranch(board, board.getPoints().get(0), 4, "up");
for (Point p : testArray) {
System.out.printf("X: %s | Y: %s%n", p.getXCoord().getIdentifier(), p.getYCoord().getIdentifier());
}
}
*/
/*
@Test
public void branchesTest() {
Point[][] branches = op.makeBranches(board, board.findByCoords("7", "H"), 4);
for (Point[] branch : branches) {
for (Point p : branch) {
System.out.printf("%s:%s, ", p.getXCoord().getIdentifier(), p.getYCoord().getIdentifier());
}
System.out.println("\n");
}
}
*/
@Test
@Ignore
public void exceptionTest() {
//ArrayIndexOutOfBoundsException for Array
//IndexOutOfBoundsException for ArrayList
ArrayList<Integer> ar = new ArrayList<>();
ar.add(1);
}
@Test
public void singleItemArrayTest() {
int[] a = {1};
for (int num : a) {
System.out.println(num);
}
}
}<file_sep>package com.battleship.board;
/*
* reference: https://en.wikipedia.org/wiki/ANSI_escape_code
*/
public enum ConsoleColors {
//color reset
RESET("\033[0m"),
// colors and corresponding code
RED("\033[0;91m"),
GREEN("\033[0;92m"),
YELLOW("\033[0;93m"),
BLUE("\033[0;94m"),
CYAN("\033[0;96m"),
WHITE("\033[0;37m"),
BRIGHTWHITE("\033[0;97m");
private final String code;
ConsoleColors(String code) {
this.code = code;
}
public static void changeTo(ConsoleColors color) {
System.out.print(color);
}
public static void reset() {
System.out.print(ConsoleColors.RESET);
}
@Override
public String toString() {
return code;
}
}
<file_sep>package com.battleship.board;
public enum PointStatus {
HIT, MISS, UNCHECKED
}
<file_sep>package com.battleship.gameplay;
import com.battleship.board.*;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Scanner;
class Player {
public void placeShip(Board board, Ship ship) {
// ship needs to place points on the board
// need a way to get a group of points. Can use the branch method.
Point startPoint = null;
boolean validPoint = false;
while (!validPoint) {
System.out.printf("Place your %s (%d spaces).%n", ship.getName(), ship.getLength());
try {
startPoint = returnPointFromInput(board);
if (startPoint != null && !startPoint.hasShip()) {
validPoint = true;
} else {
System.out.println("Invalid input. Please enter a coordinate pair. Ex: 1A (Case insensitive).");
}
} catch (IllegalArgumentException | NoSuchElementException e) {
System.out.println(e.getMessage());
}
}
int emptySpaces = 0;
boolean validBranch = false;
Point[] branch = null;
while (!validBranch) {
String direction = null;
boolean validDirection = false;
while (!validDirection) {
try {
direction = directionFromInput();
validDirection = true;
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
branch = makeBranch(board, startPoint, ship.getLength(), direction);
for (Point point : branch) {
if (!point.hasShip()) {
emptySpaces++;
}
}
if (emptySpaces == ship.getLength()) {
validBranch = true;
} else {
System.out.println("You can't put a ship there. Not enough room");
emptySpaces = 0;
}
}
// pass ship to point
for (Point point : branch) {
point.setShip(ship);
point.setHasShip(true);
}
}
String getCoordinateFromUser() throws IllegalArgumentException {
System.out.println("Please enter a coordinate pair. Ex: 1A (Case insensitive).");
String input = new Scanner(System.in).nextLine();
// Covers length
if (input.length() > 3 || input.length() < 2) {
throw new IllegalArgumentException("Input is invalid. Please " +
"choose no more than 3 characters. X coord, Y coord. e.g. 1B");
} else
return input;
}
// parsing input and return a point.
Point returnPointFromInput(Board board)
throws IllegalArgumentException, NoSuchElementException {
String input = getCoordinateFromUser();
String x = null;
String y = null;
if (input.length() == 2) {
x = input.substring(0, 1);
y = input.substring(1).toUpperCase();
} else if (input.length() == 3) {
x = input.substring(0, 2);
y = input.substring(2).toUpperCase();
}
try {
return board.findByCoords(x, y);
} catch (NoSuchElementException e) {
throw new NoSuchElementException("Input is invalid. Please " +
"choose no more than 3 characters. X coord, Y coord. e.g. 1B");
}
}
String directionFromInput() throws IllegalArgumentException {
System.out.println("Please choose direction to place ship. e.g. up, down, left, right");
String input = new Scanner(System.in).nextLine().toLowerCase();
String[] directions = {"up", "down", "left", "right"};
boolean valid = false;
for (String direction : directions) {
if (input.equals(direction)) {
valid = true;
break;
}
}
if (valid) {
return input;
} else throw new IllegalArgumentException("Invalid argument. Please choose up, down, left or right");
}
public void takeTurn(Board board) {
boolean valid = false;
while (!valid) {
try {
Point point = returnPointFromInput(board);
if (point != null) {
if (point.getStatus() == PointStatus.UNCHECKED) {
point.target();
valid = true;
if (point.hasShip()) {
if (point.getShip().getHitCount() == point.getShip().getLength()) {
point.getShip().setDestroyed(true);
}
if (point.getShip().isDestroyed()) {
System.out.printf("You destroyed my %s!\n", point.getShip().getName());
board.remainingShips.remove(point.getShip());
}
}
}
else {
System.out.println("You already picked that point. Try again.");
}
}
else {
System.out.println("Invalid input. Please enter a coordinate pair. Ex: 1A (Case insensitive).");
}
} catch (IllegalArgumentException | NoSuchElementException e) {
System.out.println(e.getMessage());
}
}
}
Point[] makeBranch(Board board, Point startPoint, int length, String direction) {
Point[] result = new Point[length];
result[0] = startPoint;
Point nextInBranch;
addToBranches:
for (int i = 1; i < length; i++) {
try {
switch (direction) {
case "up":
nextInBranch = board.findByCoords(
startPoint.getXCoord().getIdentifier(), // same x-coordinate
YCoord.values()[startPoint.getYCoord().ordinal() - i].getIdentifier() // different y-coordinate (decreasing ordinal)
);
if (nextInBranch.getStatus() == PointStatus.UNCHECKED) {
result[i] = nextInBranch;
} else {
break addToBranches;
}
break;
case "down":
nextInBranch = board.findByCoords(
startPoint.getXCoord().getIdentifier(), // same x-coordinate
YCoord.values()[startPoint.getYCoord().ordinal() + i].getIdentifier() // different y-coordinate (increasing ordinal)
);
if (nextInBranch.getStatus() == PointStatus.UNCHECKED) {
result[i] = nextInBranch;
} else {
break addToBranches;
}
break;
case "left":
nextInBranch = board.findByCoords(
XCoord.values()[startPoint.getXCoord().ordinal() - i].getIdentifier(), // different x-coordinate (decreasing ordinal
startPoint.getYCoord().getIdentifier() // same y-coordinate
);
if (nextInBranch.getStatus() == PointStatus.UNCHECKED) {
result[i] = nextInBranch;
} else {
break addToBranches;
}
break;
case "right":
nextInBranch = board.findByCoords(
XCoord.values()[startPoint.getXCoord().ordinal() + i].getIdentifier(), // different x
startPoint.getYCoord().getIdentifier() // same y
);
if (nextInBranch.getStatus() == PointStatus.UNCHECKED) {
result[i] = nextInBranch;
} else {
break addToBranches;
}
}
} catch (ArrayIndexOutOfBoundsException e) {
break;
}
}
// create new result array without any null values.
result = Arrays.stream(result).filter(Objects::nonNull).toArray(Point[]::new);
return result;
}
}<file_sep># battleship
A class project based on the board game 'Battleship'.
<file_sep>package com.battleship.board;
import static com.battleship.board.PointStatus.*;
public class Point {
private XCoord xCoord;
private YCoord yCoord;
private Ship ship;
private boolean hasShip = false;
private PointStatus status = UNCHECKED;
Point(XCoord xCoord, YCoord yCoord) {
setXCoord(xCoord);
setYCoord(yCoord);
}
public void target() throws RepeatGuessException {
if (status == UNCHECKED) {
if (hasShip) {
ship.hit();
setStatus(HIT);
} else {
setStatus(MISS);
}
} else {
throw new RepeatGuessException("You have already selected that point. Try again.");
}
}
public XCoord getXCoord() {
return xCoord;
}
public void setXCoord(XCoord xCoord) {
this.xCoord = xCoord;
}
public YCoord getYCoord() {
return yCoord;
}
public void setYCoord(YCoord yCoord) {
this.yCoord = yCoord;
}
public Ship getShip() {
return ship;
}
public void setShip(Ship ship) {
this.ship = ship;
}
public boolean hasShip() {
return hasShip;
}
public void setHasShip(boolean hasShip) {
this.hasShip = hasShip;
}
public PointStatus getStatus() {
return status;
}
public void setStatus(PointStatus status) {
this.status = status;
}
}
| ca2c096900a3d9345efc122e284ee3931f5b976c | [
"Markdown",
"Java"
] | 7 | Java | JDahl-code/battleship | 5506c3c031fe5a0bf7b94cb46e696685d9d96fb1 | 5d31dc849bb47ead73f47cf5b6b9ffa29918c3f9 |
refs/heads/master | <file_sep>import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferStrategy;
public class PreGame extends JFrame implements MouseListener {
public CreatePlayer creator;
public ClickableObject finish;
public boolean isReady = false;
public PreGame(){
setSize(1967, 900);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
addMouseListener(this);
creator = new CreatePlayer();
finish = new ClickableObject(300, 100, 50, 30,"Finish");
}
public void paint(Graphics g){
BufferStrategy bufferStrategy = getBufferStrategy();
if (bufferStrategy == null) {
createBufferStrategy(2);
bufferStrategy = getBufferStrategy();
}
g = bufferStrategy.getDrawGraphics();
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.GRAY);
g2d.fillRect(0,0,getWidth(), getHeight());
creator.draw(g2d);
finish.drawObject(g2d);
g.dispose();
bufferStrategy.show();
}
@Override
public void mouseClicked(MouseEvent e) {
creator.checkClick(e);
isReady = (isReady || finish.checkClick(e));
if (isReady) {
setVisible(false);
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
<file_sep>import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Client extends MessageListener {
Frame frame = new Frame();
int numberOfClient;
boolean isItNewCard = false;
public Client(PreGame p) throws IOException {
frame.preplayer.name = p.creator.name;
frame.preplayer.pol = p.creator.pol;
}
public static void main(String[] args) throws IOException, InterruptedException {
PreGame preGame = new PreGame();
while (preGame.isReady == false){
preGame.repaint();
Thread.sleep(20);
}
Client client = new Client(preGame);
client.start();
}
public void start() throws IOException {
String host = "127.0.0.1";
int port = 2491;
Socket socket = new Socket(host, port);
StreamWorker postman = new StreamWorker(socket.getInputStream(), socket.getOutputStream());
postman.addListener(this);
postman.start();
frame.setPostman(postman);
frame.setPlayer(postman);
frame.setCube(postman);
}
@Override
public void onMessage(String text) throws IOException {
System.out.println(text);
StringTokenizer tokenizer = new StringTokenizer(text);
String token = tokenizer.nextToken();
if (token.equals("Your_Number")) {
String number = tokenizer.nextToken();
numberOfClient = Integer.parseInt(number);
frame.numberOfClient = numberOfClient;
System.out.println("Your number in this Server: " + numberOfClient);
frame.player.numberOfPlayer = numberOfClient;
}
if (token.equals("All")) {
String numberOfClient = tokenizer.nextToken();
String token0 = tokenizer.nextToken();
if (token0.equals("Card")) {
int num;
String number = tokenizer.nextToken();
num = Integer.parseInt(number);
//Положение карты
String token1 = tokenizer.nextToken();
String token2 = tokenizer.nextToken();
String token3 = tokenizer.nextToken();
String token4 = tokenizer.nextToken();
//Картинка карты
String token5 = tokenizer.nextToken();
String token6 = tokenizer.nextToken();
String token7 = tokenizer.nextToken();
String token8 = tokenizer.nextToken();
//Высота карты
String token9 = tokenizer.nextToken();
//Положенеие от курсора
String token10 = tokenizer.nextToken();
String token11 = tokenizer.nextToken();
Card test = new Card(token5, token6, token7);
test.x = Integer.parseInt(token1);
test.y = Integer.parseInt(token2);
test.w = Integer.parseInt(token3);
test.h = Integer.parseInt(token4);
test.gameset = token5;
test.deck = token6;
test.numberOfCard = token7;
test.faseUpIsTrue = Integer.parseInt(token8);
test.higth = Integer.parseInt(token9);
frame.maxHigth = Integer.parseInt(token9);
test.rx = Integer.parseInt(token10);
test.ry = Integer.parseInt(token11);
if (num < frame.cards.size()) {
frame.cards.set(num, test);
} else {
frame.cards.add(test);
new Thread(() -> {
new MakeSound().playSound("C://Users//forStudy//IdeaProjects//data//Munchkin_Sounds//new.wav");
}).start();
}
}
}
if (token.equals("State")) {
String numberOfP = tokenizer.nextToken();
int numberOfPlayer = Integer.parseInt(numberOfP);
String token0 = tokenizer.nextToken();
while (numberOfPlayer > frame.players.size()-1) {
frame.newPlayer(frame.postman);
}
if (token0.equals("Buns")) {
{
int kol;
String kol_vo = tokenizer.nextToken();
kol = Integer.parseInt(kol_vo);
frame.players.get(numberOfPlayer).buns.clear();
for (int i = 0; i < kol; i = i + 1) {
String n = tokenizer.nextToken();
frame.players.get(numberOfPlayer).buns.add(n);
}
}
String token1 = tokenizer.nextToken();
if (token1.equals("Doors")) {
int kol;
String kol_vo = tokenizer.nextToken();
kol = Integer.parseInt(kol_vo);
frame.players.get(numberOfPlayer).doors.clear();
for (int i = 0; i < kol; i = i + 1) {
String n = tokenizer.nextToken();
frame.players.get(numberOfPlayer).doors.add(n);
}
}
String level = tokenizer.nextToken();
frame.players.get(numberOfPlayer).level = Integer.parseInt(level);
String chisOfCardsOnHand = tokenizer.nextToken();
frame.players.get(numberOfPlayer).chisOfCardsOnHand = Integer.parseInt(chisOfCardsOnHand);
String pol = tokenizer.nextToken();
frame.players.get(numberOfPlayer).pol = pol;
}
if(token0.equals("Cube")){
String numberOfFace = tokenizer.nextToken();
frame.cubic.numberOfFace = numberOfFace;
}
}
frame.repaint();
}
@Override
public void sentCard(Card c) throws IOException {
}
@Override
public void onDisconnect() {
}
}<file_sep>import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class Painter {
String gameset = "Original";
ArrayList<Image> Buns = new ArrayList<>();
ArrayList<Image> Doors = new ArrayList<>();
ArrayList<BufferedImage> Cube = new ArrayList<>();
Painter() {
String filePathBuns = "C:\\Users\\forStudy\\IdeaProjects\\data\\Munchkin\\" + gameset + "\\" + "Buns_State";
String filePathDoors = "C:\\Users\\forStudy\\IdeaProjects\\data\\Munchkin\\" + gameset + "\\" + "Doors_State";
try {
for(int i = 0; i < 10; i = i + 1){
String s = "00" + i;
Buns.add(ImageIO.read(new File(filePathBuns + "\\" + s +".jpg")));
}
for(int i = 10; i < 76; i = i + 1){
String s = "0" + i;
Buns.add(ImageIO.read(new File(filePathBuns + "\\" + s +".jpg")));
}
} catch (IOException e) {
e.printStackTrace();
}
try {
for(int i = 0; i < 10; i = i + 1){
String s = "00" + i;
Doors.add(ImageIO.read(new File(filePathDoors + "\\" + s +".jpg")));
}
for(int i = 10; i < 96; i = i + 1){
String s = "0" + i;
Doors.add(ImageIO.read(new File(filePathDoors + "\\" + s +".jpg")));
}
} catch (IOException e) {
e.printStackTrace();
}
try {
Cube.add(ImageIO.read(new File("C:\\Users\\forStudy\\IdeaProjects\\data\\Munchkin_Cards\\" + gameset + "\\" + "All_another" + "\\" + "Cube_1.bmp")));
Cube.add(ImageIO.read(new File("C:\\Users\\forStudy\\IdeaProjects\\data\\Munchkin_Cards\\" + gameset + "\\" + "All_another" + "\\" + "Cube_2.bmp")));
Cube.add(ImageIO.read(new File("C:\\Users\\forStudy\\IdeaProjects\\data\\Munchkin_Cards\\" + gameset + "\\" + "All_another" + "\\" + "Cube_3.bmp")));
Cube.add(ImageIO.read(new File("C:\\Users\\forStudy\\IdeaProjects\\data\\Munchkin_Cards\\" + gameset + "\\" + "All_another" + "\\" + "Cube_4.bmp")));
Cube.add(ImageIO.read(new File("C:\\Users\\forStudy\\IdeaProjects\\data\\Munchkin_Cards\\" + gameset + "\\" + "All_another" + "\\" + "Cube_5.bmp")));
Cube.add(ImageIO.read(new File("C:\\Users\\forStudy\\IdeaProjects\\data\\Munchkin_Cards\\" + gameset + "\\" + "All_another" + "\\" + "Cube_6.bmp")));
} catch (IOException e){
e.printStackTrace();
}
}
public void draw(Graphics2D g2d, int x0, int y0, String gameset0, String deck, String numberOfCard) {
if (gameset0.equals("Original")) {
if (deck.equals("Buns")) {
// Отрисовывает карты сокровищ
if(!numberOfCard.equals("??")) {
int i = Integer.parseInt(numberOfCard);
Image test = Buns.get(i);
g2d.drawImage(test, x0, y0, null);
}else{
Image test = Buns.get(0);
g2d.drawImage(test, x0, y0, null);
}
}
if (deck.equals("Doors")) {
// Отрисовывает карты дверей
if(!numberOfCard.equals("??")) {
int i = Integer.parseInt(numberOfCard);
Image test = Doors.get(i);
g2d.drawImage(test, x0, y0, null);
}else{
Image test = Doors.get(0);
g2d.drawImage(test, x0, y0, null);
}
}
if (deck.equals("Cube")) {
// Отрисовывает грани кубика
if(!numberOfCard.equals("??")) {
int i = Integer.parseInt(numberOfCard);
BufferedImage test = Cube.get(i);
g2d.drawImage(test, x0, y0, null);
}
}
}
}
public void drawSmall(Graphics2D g2d, int x0, int y0, String gameset0, String deck, String numberOfCard) {
int w0 = 70;
int h0 = 120;
if (gameset0.equals("Original")) {
if (deck.equals("Buns")) {
// Отрисовывает маленькие карты сокровищ
if(!numberOfCard.equals("??")) {
int i = Integer.parseInt(numberOfCard);
Image test = Buns.get(i).getScaledInstance(w0, h0, Image.SCALE_SMOOTH);
g2d.drawImage(test, x0, y0, null);
}else{
Image test = Buns.get(0).getScaledInstance(w0, h0, Image.SCALE_SMOOTH);
g2d.drawImage(test, x0, y0, null);
}
}
if (deck.equals("Doors")) {
// Отрисовывает маленькие карты дверей
if(!numberOfCard.equals("??")) {
int i = Integer.parseInt(numberOfCard);
Image test = Doors.get(i).getScaledInstance(w0, h0, Image.SCALE_SMOOTH);
g2d.drawImage(test, x0, y0, null);
}else{
Image test = Doors.get(0).getScaledInstance(w0, h0, Image.SCALE_SMOOTH);
g2d.drawImage(test, x0, y0, null);
}
}
}
}
}
| cb3d271fe7d55b11b63e13fbc0b9bcfb32928f33 | [
"Java"
] | 3 | Java | IvanGrigin/MultyCards_2021_03_12 | 143eeebf7c428467aaf925d61797682c0d71ece6 | ea537a44f8aa4a00a1fea83a63a70e79bec438d3 |
refs/heads/master | <repo_name>NimraPro/izracunaj<file_sep>/tesanj.js
$(document).ready(function() {
setTimeout(function(){
$("#deviceready").hide();
$("#zovko").show();
}, 3000);
$('#god').keyup(function() {
var god = (new Date).getFullYear();
var sad = $(this).val();
if (sad.length == 4) $(this).val(god-sad);
});
$("*").keyup( function() {
if ($('#arko').val() > 1 && $('#ccm').val() > 2 && $('#god').val()) {
var amk = 0;
var voda = 20;
var stiker = 5;
var komunalna = 15;
var zastita = 20;
var tehnicki = 60.5;
var potoreg = 0;
var tabl = 0;
var potvrda = 0;
var uplate = 9;
var ukupno = amk+voda+stiker+komunalna+tehnicki+porez+putarina+polica+zastita+uplate - 0;
$('#potvrdaoreg').val(potoreg);
$('#potvrdaovl').val(potvrda);
$('#tablice1').val(tabl);
$('#amk').val(amk);
$('#voda').val(voda);
$('#stiker').val(stiker);
$('#komunalna').val(komunalna);
$('#zastita').val(zastita);
$('#tehnicki').val(tehnicki);
$('#god').val();
$('#uplate').val(uplate);
$('#ukupno').val(ukupno);
if ($('#god').val() <= 2 && $('#ccm').val() <= 1600 ) {
porez = 50;
$('#porez').val(porez);
}
else if ($('#god').val() <= 2 && $('#ccm').val() > 1600 ) {
porez = 100;
$('#porez').val(porez);
}
else if ($('#god').val() > 2 && $('#god').val() <= 5 && $('#ccm').val() <= 1600 ) {
porez = 35;
$('#porez').val(porez);
}
else if ($('#god').val() > 2 && $('#god').val() <= 5 && $('#ccm').val() > 1600 ) {
porez = 70;
$('#porez').val(porez);
}
else if ($('#god').val() > 5 && $('#god').val() <= 10 && $('#ccm').val() <= 1600 ) {
porez = 25;
$('#porez').val(porez);
}
else if ($('#god').val() > 5 && $('#god').val() <= 10 && $('#ccm').val() > 1600 ) {
porez = 50;
$('#porez').val(porez);
}
else if ($('#god').val() > 10 && $('#ccm').val() > 1600 ) {
porez = 20;
$('#porez').val(porez);
}
else if ($('#god').val() > 10 && $('#ccm').val() < 1600 ) {
porez = 10;
$('#porez').val(porez);
}
else {
porez = 0;
}
}
if ($('#arko').val() <= 22 ) {
polica = 115;
$('#polica').val(polica);
}
else if ($('#arko').val() > 22 && $('#arko').val() <= 33 ) {
polica = 164;
$('#polica').val(polica);
}
else if ($('#arko').val() > 33 && $('#arko').val() <= 44 ) {
polica = 198;
$('#polica').val(polica);
}
else if ($('#arko').val() > 44 && $('#arko').val() <= 55 ) {
polica = 230;
$('#polica').val(polica);
}
else if ($('#arko').val() > 55 && $('#arko').val() <= 66 ) {
polica = 263;
$('#polica').val(polica);
}
else if ($('#arko').val() > 66 && $('#arko').val() <= 84 ) {
polica = 289;
$('#polica').val(polica);
}
else if ($('#arko').val() > 84 && $('#arko').val() <= 110 ) {
polica = 346;
$('#polica').val(polica);
}
else if ($('#arko').val() > 110 ) {
polica = 416;
$('#polica').val(polica);
}
else {
polica = 0;
}
if ($('#ccm').val() <= 1100) {
putarina = 25;
$('#putarina').val(putarina);
}
else if ($('#ccm').val() > 1100 && $('#ccm').val() <= 1600 ) {
putarina = 50;
$('#putarina').val(putarina);
}
else if ($('#ccm').val() > 1600 && $('#ccm').val() <= 2000 ) {
putarina = 60;
$('#putarina').val(putarina);
}
else if ($('#ccm').val() > 2000 && $('#ccm').val() <= 2500 ) {
putarina = 100;
$('#putarina').val(putarina);
}
else if ($('#ccm').val() > 2500 && $('#ccm').val() <= 3000 ) {
putarina = 150;
$('#putarina').val(putarina);
}
else if ($('#ccm').val() > 3000 ) {
putarina = 250;
$('#putarina').val(putarina);
}
else {
putarina = 0000;
}
$(":checkbox").change( function() {
if ($('#potvrda').is(' :checked')) {
potvrda = 5;
$('#potvrdaovl').val(potvrda);
}
else {
potvrda = 0;
$('#potvrdaovl').val(potvrda);
}
if ($('#saobracajna').is(' :checked')) {
potoreg = 5;
$('#potvrdaoreg').val(potoreg);
}
else {
potoreg = 0;
$('#potvrdaoreg').val(potoreg);
}
if ($('#tablice').is(' :checked')) {
tabl = 20;
$('#tablice1').val(tabl);
}
else {
tabl = 0;
$('#tablice1').val(tabl);
}
var ukupno = amk+voda+stiker+komunalna+tehnicki+porez+putarina+potoreg+tabl+potvrda+polica+zastita+uplate - 0;
$('#ukupno').val(ukupno);
});
});
}); | 1697732e06536a594f7f4dc1c720521c50b902be | [
"JavaScript"
] | 1 | JavaScript | NimraPro/izracunaj | 380b026fa1208e88993b10fcebee99f789d8dac1 | 578e779b1b052c43d759dcd0d3da168d1fe3a1d5 |
refs/heads/master | <repo_name>ivan9blagorodov/-<file_sep>/АиСД/1/1.1.py
def linear_search(array, key):
for i in range(len(array)):
if array[i] == key:
return i
else:
return -1
def binary_search(array, key):
minimum = 0
maximum = len(array) - 1
search = 0
while minimum <= maximum:
avg = (maximum + minimum) // 2
if key < array[avg]:
maximum = avg - 1
elif key > array[avg]:
minimum = avg + 1
else:
search = avg
break
while search > 0 and array[search - 1] == key:
search -= 1
if array[search] == key:
return search
else:
return -1
def interpolational_search(array, key):
minimum = 0
maximum = len(array) - 1
search = 0
while array[minimum] < key < array[maximum]:
dist = int(minimum + (maximum - minimum) * (key - array[minimum]) / (array[maximum] - array[minimum]))
if array[dist] == key:
search = dist
break
elif array[dist] > key:
maximum = dist - 1
else:
minimum = dist + 1
if array[minimum] == key:
search = minimum
elif array[maximum] == key:
search = maximum
while search > 0 and array[search - 1] == key:
search -= 1
if array[search] == key:
return search
else:
return -1<file_sep>/README.md
# -ИКСиС
<file_sep>/3.2.py
from Hash_table.hash_table import MyHash
hash_table = MyHash(10)
hash_table.add_hash('<NAME>', '999999999')
hash_table.add_hash('<NAME>', '7777777')
hash_table.add_hash('Vitaliy', '444444')
hash_table.add_hash('Alexandr', '222222')
hash_table.add_hash('Yaroslav', '111111111')
print(hash_table)<file_sep>/АиСД/5/5.py
from dataclasses import dataclass
import random as rd
class Stack:
def __init__(self):
self.data = []
self.empty = True
def __str__(self):
out = '['
for i in range(self.size() - 1):
out += str(self.data[i])
return out + ']'
def push(self, item):
self.data.append(item)
if self.empty:
self.empty = False
def pop(self):
if not self.check_empty():
out = self.data.pop()
else:
out = None
if not self.data:
self.empty = True
return out
def check_empty(self):
if self.empty:
return self.empty
else:
return self.empty
def size(self):
return len(self.data)
class Queue:
def __init__(self):
self.data = []
self.empty = True
def __str__(self):
out = '['
for i in range(self.size() - 1):
out += str(self.data[i])
return out + ']'
def push(self, item):
self.data.insert(0, item)
if self.empty:
self.empty = False
def pop(self):
if not self.check_empty():
out = self.data.pop()
else:
out = None
if not self.data:
self.empty = True
return out
def check_empty(self):
if self.empty:
return self.empty
else:
return self.empty
def size(self):
return len(self.data)
@dataclass()
class TaskData:
time: int = None
priority: int = None
class Task:
def __init__(self, task_priority, task_time):
self.current_task = TaskData()
self.current_task.time = task_time
self.current_task.priority = task_priority
def __str__(self):
return '[' + str(self.get_priority()) + ',' + str(self.get_time()) + ']'
def get_time(self):
return self.current_task.time
def get_priority(self):
return self.current_task.priority
class TaskGenerator:
def __init__(self):
self.queue1 = Queue()
self.queue2 = Queue()
self.queue3 = Queue()
def __str__(self):
out = str(self.queue1) + '\n' + str(self.queue2) + '\n' + str(self.queue3)
return out + '\n'
def gen_task(self):
task = Task(rd.randint(1, 3), rd.randint(4, 8))
if task.get_priority() == 1:
self.queue1.push(task)
elif task.get_priority() == 2:
self.queue2.push(task)
else:
self.queue3.push(task)
def get_task(self):
if not self.queue1.check_empty():
task = self.queue1.pop()
elif not self.queue2.check_empty():
task = self.queue2.pop()
elif not self.queue3.check_empty():
task = self.queue3.pop()
else:
task = None
return task
def none_task(self):
return self.queue1.check_empty() and self.queue2.check_empty() and self.queue3.check_empty()
@dataclass()
class Thread:
work_time: int = None
task_priority: int = None
idle: bool = True
class Processor:
def __init__(self):
self.thread = Thread()
self.wait = Stack()
def __str__(self):
out = '|thread|type|time|idle |\n'
out += '{:<9}{:<5}{:<5}{:<6}'.format(' 1', str(self.thread.task_priority), str(self.thread.work_time),
str(self.thread.idle)) + '\n'
return out
def add_task(self, task: Task):
if self.thread.idle:
self.thread.task_priority = task.get_priority()
self.thread.work_time = task.get_time()
self.thread.idle = False
else:
self.wait.push(task)
def __run_task_thread(self):
self.thread.work_time -= 1
if self.thread.work_time <= 0:
self.thread.idle = True
self.thread.task_priority = None
self.thread.work_time = None
def running(self):
if not self.thread.idle:
self.__run_task_thread()
else:
self.thread.idle = True
def idle_proc(self):
return self.thread.idle
generator = TaskGenerator()
processor = Processor()
for i in range(50):
generator.gen_task()
while True:
task = generator.get_task()
if not generator.none_task():
processor.add_task(task)
elif not processor.wait.check_empty():
processor.add_task(processor.wait.pop())
processor.running()
print('Tasks\n', generator)
print('Processor:\n', processor)
print('Stack:', processor.wait)
if generator.none_task() and processor.wait.check_empty() and processor.idle_proc():
break<file_sep>/АиСД/3/3.2.py
hash_table = MyHash(10)
hash_table.add_hash('<NAME>', '999999999')
hash_table.add_hash('<NAME>', '5555555555')
hash_table.add_hash('Anton', '33333333333')
hash_table.add_hash('Fedor', '22222222222')
hash_table.add_hash('Maxim', '11111111111')
print(hash_table)<file_sep>/4АиСД.py
import random as rd
class Node:
def __init__(self, data):
self.data = data
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_next(self, next):
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def __str__(self):
if self.head is not None:
current = self.head
out = "[" + str(current.get_data())
while current.get_next() is not None:
current = current.get_next()
out += "," + " " + str(current.get_data())
return out + "]"
def push(self, value):
temp = Node(value)
temp.set_next(self.head)
self.head = temp
def append(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
last = self.head
while last.next:
last = last.get_next()
last.set_next(new_node)
def insert_after(self, key, new_data):
current = self.head
found = False
while current is not None and not found:
if current.get_data() == key:
found = True
else:
current = current.get_next()
if found:
new_node = Node(new_data)
new_node.set_next(current.get_next())
current.set_next(new_node)
def length(self):
current = self.head
count = 0
while current is not None:
count += 1
current = current.get_next()
return count
def search(self, key):
current = self.head
found = False
while current is not None and not found:
if current.get_data() == key:
found = True
else :
current = current.get_next()
return found
def delete_node(self, key):
current = self.head
previous = None
found = False
while not found:
if current.get_data() == key:
found = True
else:
previous = current
current = current.get_next()
if previous is None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
list1 = LinkedList()
list2 = LinkedList()
def polynom(x, n, list):
for i in range(n, -1, -1):
p = rd.randint(0, 10) * x ** i
if p != 0:
list.append(p)
return list
def compare(list1, list2):
compare = []
clist1 = list1.head
clist2 = list2.head
if list1.length() == list2.length():
while clist1.get_next() is not None:
if clist1.get_data() == clist2.get_data():
compare.append(True)
else:
compare.append(False)
clist1 = clist1.get_next()
clist2 = clist2.get_next()
return compare
else:
return False
polynom(2, 10, list1)
polynom(2, 10, list2)
print(list1)
print(list2)
print(compare(list1, list2))
| b1b28ba69bc27d027a4733383e8cd97cd9faac1d | [
"Markdown",
"Python"
] | 6 | Python | ivan9blagorodov/- | 0a657761115da09498a1b89ec341c69c3a3f7e78 | c5c631cb2d68dab91b3b706ede54c978a903b45f |
refs/heads/master | <repo_name>Tyler135/Algorhythm<file_sep>/MyPlayground.playground/section-1.swift
// Playground - noun: a place where people can play
import UIKit
println("Hello world")
| 40d032ba1d859027d39b2d53b1792b60cd98add9 | [
"Swift"
] | 1 | Swift | Tyler135/Algorhythm | 712d4ece96d5c12d37cfcf9f0d063b1980ec349a | 659acbec1d5831d7621b48accf9ba053d6d0ab4e |
refs/heads/master | <file_sep>//app.js
const url = require('common/url.js')
const utils = require('common/utils.js')
const request = require('common/request.js')
const jim = require('common/jim.js')
let { WeToast } = require('widget/wetoast/wetoast.js')
App({
WeToast,
onLaunch: function () {
let app = this
utils.init(this)
// 展示本地存储能力
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 设置消息监听
jim.addMsgListener(function(content) {
console.log('收到消息')
console.log(content)
})
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
console.log(res)
let params = {
"Type": "MiniProgram",
"action": "logon",
"CODE": res.code
}
request.post(url.login, params,
res => {
console.log("clearlogin")
console.log(res)
wx.setStorageSync("userID", res.userID)
app.getUserInfo()
})
}
})
// 获取用户信息
wx.getSetting({
success: res => {
// if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
// }
}
})
},
getUserInfo(){
let app = this
wx.getUserInfo({
success: res => {
console.log("getUserInfo success")
console.log(res)
app.logonClear(res)
},
fail: function (res) {
console.log(res)
if (app.userInfoReadyCallback) {
app.userInfoReadyCallback()
}
}
})
},
logonClear(res){
let app = this
let params = {
"Type": "MiniProgram",
"action": "updateInfo",
"encryptedData": res.encryptedData,
"userID": wx.getStorageSync("userID"),
"iv": res.iv
}
request.post(url.login, params,
res => {
console.log("clearupdateInfo")
console.log(res)
let userInfo = res.userInfo
userInfo.userID = wx.getStorageSync("userID")
app.globalData.userInfo = userInfo
if (app.userInfoReadyCallback) {
app.userInfoReadyCallback(userInfo)
}
},
fail => {
console.log(fail)
if (app.userInfoReadyCallback) {
app.userInfoReadyCallback()
}
})
},
globalData: {
mediaInfo: null,
userInfo: null,
movieInfo: null,
movieList: null,
tagList: null,
liveList: null,
hasMovie: 0,
hasLive: 0,
remoteType: 'MiniProgram',
controlType: 'ButtonType'
}
})<file_sep>const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
var mApp
var swipeAudio
var innerAudioContext
// var weToast
const init = obj => {
mApp = obj
// weToast = new mApp.WeToast()
swipeAudio = wx.createInnerAudioContext()
swipeAudio.src = 'http://openvod.cleartv.cn/remotecontrol/res/swipe.mp3'
swipeAudio.onPlay(() => {
console.log('开始播放')
})
swipeAudio.onError((res) => {
console.log(res.errMsg)
console.log(res.errCode)
})
}
const showToast = obj => {
if (mApp) {
try {
new mApp.WeToast().toast(obj)
} catch (err) {
console(err)
}
}
}
const playSwipe = function(){
if (swipeAudio){
console.log('playSwipe')
swipeAudio.play()
}
}
const playAudio = src => {
console.log('playAudio' + src)
innerAudioContext.src = src
innerAudioContext.onPlay(() => {
console.log('开始播放')
})
innerAudioContext.onError((res) => {
console.log(res.errMsg)
console.log(res.errCode)
})
innerAudioContext.play()
}
// var searchTime = 0
const search = content => {
if (mApp) {
// console.log(searchTime)
// if (new Date().getTime() - searchTime < 3000){
// console.log("not search")
// return
// }
// searchTime = new Date().getTime()
console.log(content)
if(!content){
return []
}
// console.log(mApp.globalData.movieList)
// console.log(mApp.globalData.liveList)
content = content.toLowerCase()
let results = []
let movieList = mApp.globalData.movieList
let len = movieList.length
for (let j = 0; j < len; j++) {
let movies = movieList[j].movieList
let size = movies.length
for(let i = 0;i<size;i++){
if (movies[i].Name['en-US'].toLowerCase().indexOf(content) != -1
|| movies[i].Name['zh-CN'].indexOf(content) != -1
|| movies[i].SearchName.toLowerCase().indexOf(content) != -1
|| movies[i].Actor['en-US'].toLowerCase().indexOf(content) != -1
|| movies[i].Actor['zh-CN'].indexOf(content) != -1
|| movies[i].Director['en-US'].indexOf(content) != -1
|| movies[i].Director['zh-CN'].toLowerCase().indexOf(content) != -1
){
var result = {"type":"movie","movie":movies[i]}
if(results.indexOf(result) == -1){
results.push(result)
}
}
}
}
let liveList = mApp.globalData.liveList
len = liveList.length
for (let i = 0; i < len; i++) {
if (liveList[i].ChannelName['en-US'].toLowerCase().indexOf(content) != -1
|| liveList[i].ChannelName['zh-CN'].toLowerCase().indexOf(content) != -1
) {
var result = { "type": "live", "channel": liveList[i] }
result.channel.index = i
if (results.indexOf(result) == -1) {
results.push(result)
}
}
}
// console.log(results)
return results
// mApp.globalData
}
}
module.exports = {
formatTime: formatTime,
init: init,
showToast: showToast,
playAudio: playAudio,
playSwipe: playSwipe,
search: search
}
<file_sep>const utils = require('utils.js')
const post = function(url,params,successCallback,failCallback) {
wx.request({
url: url,
method: "POST",
data: params,
success: function (res) {
if (successCallback)
successCallback(res.data)
},
fail: function (res) {
console.log('------网络请求失败------')
console.log(url)
console.log(params)
console.log(res)
console.log('------------------')
if(failCallback)
failCallback(res)
else{
utils.showToast({
img: "http://openvod.cleartv.cn/remotecontrol/res/images/icon_error.png",
title: '网络错误!'
})
// wx.showToast({
// title: '网络错误!',
// icon: 'error',
// duration: 1500
// })
}
}
})
}
module.exports = {
post: post,
}
<file_sep>const JMessage = require('../libs/jmessage-wxapplet-sdk-1.4.0.min.js')
const request = require('request.js')
const url = require('url.js')
const JIM = new JMessage({
debug : true
});
var isInit = false
var isConn = false
var isLogin = false
var isJoinRoom = false
const init = function (userInfo,callback) {
console.log('JIM init')
console.log(userInfo)
request.post(url.getAuth, { "action": "getJMessage" }, success => {
console.log(success)
JIM.init(success.data).onSuccess(function (data) {
//TODO
console.log('jim init onSuccess')
console.log(data)
isInit = true
isConn = true
JIM.login({
'username': userInfo.unionId,
'password': '<PASSWORD>'
}).onSuccess(function (data) {
console.log('jim login onSuccess')
console.log(data)
if (callback)
callback()
}).onFail(function (data) {
console.log('jim login onFail')
console.log(data)
JIM.register({
'username': userInfo.unionId,
'nickname': userInfo.nickName,
'gender': userInfo.gender,
'password': '<PASSWORD>'
}).onSuccess(function (data) {
console.log('jim register onSuccess')
console.log(data)
JIM.login({
'username': userInfo.unionId,
'password': '<PASSWORD>'
}).onSuccess(function (data) {
console.log('jim login onSuccess')
console.log(data)
if (callback)
callback()
})
}).onFail(function (data) {
console.log('jim register onFail')
console.log(data)
});
});
}).onFail(function (data) {
//TODO
console.log('onFail')
console.log(data)
});
})
}
const joinRoom = function (GroupID, ChatRoomID = 10006096){
console.log('JIM joinRoom')
JIM.isLogin();
JIM.onMsgReceive(function (data) {
console.log('jim onMsgReceive')
console.log(data)
for (let j = 0; j < data.messages.length; j++) {
for (let i = 0; i < MsgListenerList.length; i++) {
MsgListenerList[i](data.messages[j].content)
}
}
});
JIM.onRoomMsg(function (data) {
console.log('jim onRoomMsg')
console.log(data)
for (let i = 0; i < MsgListenerList.length; i++) {
MsgListenerList[i](data.content)
}
});
JIM.onTransMsgRec(function (data) {
console.log('jim onTransMsgRec')
console.log(data)
// data.type 会话类型
// data.gid 群 id
// data.from_appkey 用户所属 appkey
// data.from_username 用户 username
// data.cmd 透传信息
});
JIM.joinGroup({
'gid': GroupID,
'reason': 'test'
}).onSuccess(function (data) {
console.log('jim joinGroup onSuccess')
console.log(data)
}).onFail(function (data) {
console.log('jim joinGroup onFail')
console.log(data)
});
JIM.enterChatroom({
'id': ChatRoomID
}).onSuccess(function (data) {
console.log('jim enterChatroom onSuccess')
console.log(data)
}).onFail(function (data) {
console.log('jim enterChatroom onFail')
console.log(data)
});
JIM.getSelfChatrooms().onSuccess(function (data) {
console.log('jim getSelfChatrooms onSuccess')
console.log(data)
for (let i = 0; i < data.chat_rooms.length; i++) {
if (ChatRoomID == data.chat_rooms[i].id)
continue
JIM.exitChatroom({
'id': data.chat_rooms[i].id
}).onSuccess(function (data) {
console.log('jim exitChatroom onSuccess')
console.log(data)
}).onFail(function (data) {
});
}
}).onFail(function (data) {
console.log('jim getSelfChatrooms onFail')
console.log(data)
});
}
var MsgListenerList = []
const addMsgListener = function (MsgListener) {
MsgListenerList.push(MsgListener)
}
const removeMsgListener = function (MsgListener) {
var index = MsgListenerList.indexOf(MsgListener);
if (index > -1) {
MsgListenerList.splice(index, 1);
}
}
module.exports = {
isInit: isInit,
isConn: isConn,
isLogin: isLogin,
isJoinRoom: isJoinRoom,
init: init,
joinRoom: joinRoom,
addMsgListener: addMsgListener,
removeMsgListener: removeMsgListener
};<file_sep>const app = getApp()
const request = require('../../../common/request.js')
const controller = require('../../../common/controller.js')
let touchOrigin = {
x: 0,
y: 0,
lock: 0
}
let touchConfig = {
moveAccuracy: 60
}
Page({
data: {
touchPadIsTouched: false,
touchPadIsTaped: false,
touchBackIsTaped: false,
hasMovie: 0,
hasLive:0
},
onLoad(){
this.setData({
hasMovie: app.globalData.hasMovie,
hasLive: app.globalData.hasLive
})
},
touchPadTap: function (e) {
// console.log('tap');
let _this = this;
this.setData({
touchPadIsTaped: true
}, function () {
_this.setData({
touchPadIsTaped: false
});
});
controller.sendKeyEvent(23)
},
touchPadMove: function (e) {
// this.setData({
// touchPad: {
// location: {
// x: e.touches[0].clientX,
// y: e.touches[0].clientY
// }
// }
// });
this.moveEventTranslate(e.touches[0].clientX, e.touches[0].clientY)
},
touchPadMoveEnd: function (e) {
touchOrigin.lock = 0;
},
moveEventTranslate: function (x, y) {
if (touchOrigin.lock == 0) {
touchOrigin.x = x;
touchOrigin.y = y;
touchOrigin.lock = 1;
} else {
let rangeX = x - touchOrigin.x;
let rangeY = -(y - touchOrigin.y);
let range = Math.sqrt(Math.pow(rangeX, 2) + Math.pow(rangeY, 2));
if (range >= touchConfig.moveAccuracy) {
touchOrigin.lock = 0;
let direction = {
name: null,
keyCode: null
};
switch (true) {
case rangeY >= -rangeX && rangeY >= rangeX:
direction.name = 'up';
direction.keyCode = 19;
break;
case rangeY >= -rangeX && rangeY <= rangeX:
direction.name = 'left';
direction.keyCode = 22;
break;
case rangeY <= -rangeX && rangeY <= rangeX:
direction.name = 'down';
direction.keyCode = 20;
break;
case rangeY <= -rangeX && rangeY >= rangeX:
direction.name = 'right';
direction.keyCode = 21;
break;
default:
}
// console.log(direction.name);
controller.sendKeyEvent(direction.keyCode)
}
}
},
touchPadSwipeStart: function (e) {
touchOrigin.x = e.touches[0].clientX;
touchOrigin.y = e.touches[0].clientY;
this.setData({
touchPadIsTouched: true
});
},
touchPadSwipeEnd: function (e) {
this.setData({
touchPadIsTouched: false
});
// console.log(e)
let rangeX = e.changedTouches[0].clientX - touchOrigin.x;
let rangeY = -(e.changedTouches[0].clientY - touchOrigin.y);
let range = Math.sqrt(Math.pow(rangeX, 2) + Math.pow(rangeY, 2));
if (range >= touchConfig.moveAccuracy) {
touchOrigin.lock = 0;
let direction = {
name: null,
keyCode: null
};
switch (true) {
case rangeY >= -rangeX && rangeY >= rangeX:
direction.name = 'up';
direction.keyCode = 19;
break;
case rangeY >= -rangeX && rangeY <= rangeX:
direction.name = 'left';
direction.keyCode = 22;
break;
case rangeY <= -rangeX && rangeY <= rangeX:
direction.name = 'down';
direction.keyCode = 20;
break;
case rangeY <= -rangeX && rangeY >= rangeX:
direction.name = 'right';
direction.keyCode = 21;
break;
default:
}
// console.log(direction.name);
controller.sendKeyEvent(direction.keyCode)
}
},
touchBackStart: function (e) {
this.setData({ touchBackIsTaped: true });
},
touchBackEnd: function (e) {
this.setData({ touchBackIsTaped: false });
},
touchBackTap: function (e) {
// console.log('back')
controller.sendKeyEvent(4)
},
touchBackLongPress: function (e) {
// console.log('menu')
controller.sendKeyEvent(82)
},
sendkeyEvent(e){
console.log(e)
controller.sendKeyEvent(e.currentTarget.dataset.keycode)
}
})<file_sep>const _baseUrl = 'https://openvod.cleartv.cn';
// const _baseUrl = 'http://openvoddev.cleartv.cn';
module.exports = {
login : _baseUrl + '/rc/logon',
remoteUrl: _baseUrl + '/rc/getremoteurl',
sendControlOld: _baseUrl + '/backend_wx/v1/remote_control',
getAuth: _baseUrl + '/rc/weixinauth',
getResource : _baseUrl + '/rc/controllerdata',
sendControl : _baseUrl + '/rc/controlleraction'
};<file_sep># RemoteControls
wx remote<file_sep>// pages/main/search/search.js
const utils = require('../../../common/utils.js')
const controller = require('../../../common/controller.js')
Page({
data: {
inputShowed: false,
inputVal: "",
results:[]
},
showInput: function () {
this.setData({
inputShowed: true
});
},
hideInput: function () {
this.setData({
inputVal: "",
inputShowed: false
});
},
clearInput: function () {
this.setData({
inputVal: ""
});
},
inputTyping: function (e) {
this.setData({
inputVal: e.detail.value,
results: utils.search(e.detail.value)
});
},
playMovie(event) {
// console.log(event)
let movieID = event.currentTarget.dataset.movieid
controller.playMovie(movieID)
},
playLive(event) {
// console.log(event)
let channelIndex = event.currentTarget.dataset.channelindex
controller.playLive(channelIndex)
}
})<file_sep>// pages/main/main.js
const app = getApp()
const controller = require('../../common/controller.js')
Page({
/**
* 页面的初始数据
*/
data: {
hasMovie: app.globalData.hasMovie,
hasLive: app.globalData.hasLive,
tabs: [''],
slideOffset: 0,//指示器每次移动的距离
activeIndex: 0,//当前展示的Tab项索引
sliderWidth: 0,//指示器的宽度,计算得到
contentHeight: 0//页面除去头部Tabbar后,内容区的总高度,计算得到
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this;
try {
let tabs = []
// let tabs2 = [
// {
// 'tag': {
// 'tagCode': 'Live',
// 'tagName': {
// 'zh-CN': '直播',
// 'en-US': 'Live'
// }
// },
// 'contentList': app.globalData.liveList
// },
// {
// 'tag': {
// 'tagCode': 'Movie',
// 'tagName': {
// 'zh-CN': '电影',
// 'en-US': 'Movie'
// }
// },
// 'contentList': app.globalData.movieList
// }
// ]
let itemHeight = 500
if (app.globalData.hasMovie == 1) {
tabs.push({
'tag': {
'tagCode': 'Movie',
'tagName': {
'zh-CN': '电影',
'en-US': 'Movie'
}
},
'contentList': app.globalData.movieList
})
}else{
itemHeight = 90
}
if (app.globalData.hasLive == 1) {
tabs.push({
'tag': {
'tagCode': 'Live',
'tagName': {
'zh-CN': '直播',
'en-US': 'Live'
}
},
'contentList': app.globalData.liveList
})
}
this.setData({
tabs: tabs,
hasMovie: app.globalData.hasMovie,
hasLive: app.globalData.hasLive,
contentHeight: tabs[0].contentList.length * itemHeight + 10
})
wx.getSystemInfo({
success: function (res) {
that.setData({
sliderWidth: (res.windowWidth - 48) / that.data.tabs.length,
sliderOffset: (res.windowWidth - 48) / that.data.tabs.length * that.data.activeIndex
});
}
});
} catch (e) {
}
},
bindChange: function (e) {
console.log(e);
var current = e.detail.current;
let count = this.data.tabs[current].contentList.length
let height = 90
if (this.data.tabs[current].tag.tagCode == 'Live'){
height = 90
} else if (this.data.tabs[current].tag.tagCode == 'Movie'){
height = 500
}
this.setData({
activeIndex: current,
sliderOffset: this.data.sliderWidth * current,
contentHeight: count * height + 10
});
},
tabClick: function (e) {
console.log(e);
var current = parseInt(e.currentTarget.id);
let count = this.data.tabs[current].contentList.length
let height = 90
if (this.data.tabs[current].tag.tagCode == 'Live') {
height = 90
} else if (this.data.tabs[current].tag.tagCode == 'Movie') {
height = 500
}
this.setData({
sliderOffset: e.currentTarget.offsetLeft,
activeIndex: e.currentTarget.id,
contentHeight: count * height + 10
});
},
playMovie(event){
console.log(event)
let movie = event.currentTarget.dataset.movie
controller.playMovie(movie)
},
playLive(event){
console.log(event)
let channel = event.currentTarget.dataset.channel
let channelIndex = event.currentTarget.dataset.channelindex
channel.channelIndex = channelIndex
controller.playLive(channel)
}
})<file_sep>// pages/main/movielist/movielist.js
const app = getApp()
const controller = require('../../../common/controller.js')
Page({
/**
* 页面的初始数据
*/
data: {
movieList: null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let index = options.index;
let _this = this;
this.setData({
movieList: app.globalData.movieList[index]
})
wx.setNavigationBarTitle({
title: _this.data.movieList.tag.CategoryName['zh-CN']//页面标题为路由参数
})
},
playMovie(event) {
// console.log(event)
let movie = event.currentTarget.dataset.movie
controller.playMovie(movie)
}
}) | 1622cd929897b46c049d29f9e5faef5525c467e1 | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | LiPengfei0106/RemoteControl | bbab8a1c512860624ed9af7578d1e15fcf6e83d3 | 9194e8a69047b51aa047b65401b9987f7dce64df |
refs/heads/master | <file_sep>import React from "react";
import Header from "../../Components/Header";
import Footer from "../../Components/Footer";
import "./Home.css";
import Images from "../../ProjectImage/ProjectImage";
import { Link } from "react-router-dom";
class HomePage extends React.Component {
render() {
return (
<div>
<Header />
<div className="splash-container">
<div className="splash">
<h1 className="splash-head">CHAT APP</h1>
<p className="splash-subhead">Lets talk </p>
<div id="custom-button-wrapper">
<Link to="/Login">
<a className="my-super-cool-btn">
<div className="dots-container">
<div className="dot" />
<div className="dot" />
<div className="dot" />
<div className="dot" />
</div>
<span className="buttoncooltext">Get Started</span>
</a>
</Link>
</div>
</div>
</div>
<div className="content-wrapper">
<div className="content">
<h2 className="content-head is-center">Application features</h2>
<div className="Appfeatures">
<div className="contenthead">
<h3 className="content-subhead">
<i className="fa fa-rocket"></i>
lets get Started
</h3>
<p>register with this Application</p>
</div>
<div className="l-box pure-u-1 pure-u-md-1-2 pure-u-lg-1-4">
<h3 className="content-subhead">
<i className="fa fa-sign-in"></i>
Firebase Authentication
</h3>
<p>
we have implemented Firebase Authentication in our Application
</p>
</div>
<div className="l-box pure-u-1 pure-u-md-1-2 pure-u-lg-1-4">
<h3 className="content-subhead">
<i className="fa fa-th-large"></i>
Media
</h3>
<p>share memes ,images,files with your loved ones</p>
</div>
<div className="l-box pure-u-1 pure-u-md-1-2 pure-u-lg-1-4">
<h3 className="content-subhead">
<i className="fa fa-wrench"></i>
Updates
</h3>
<p>we keep working for new features and enhancements</p>
</div>
</div>
</div>
<div className="AppfeaturesFounder">
<div className="l-box-lrg is-center pure-u-1 pure-u-md-1-2 pure-u-lg-2-5">
<img
width="300"
alt="File Icons"
className="pure-img-responsive"
src={Images.ishita}
/>
</div>
<div className="pure-u-1 pure-u-md-1-2 pure-u-lg-3-5">
<h2 className="content-head content-head-ribbon">Ishita</h2>
<p style={{ color: "black" }}>Developer</p>
<p style={{ color: "black" }}>
currently learning React and looking for a decent job
</p>
</div>
</div>
<div className="content">
<h2 className="content-head is-center">Register here</h2>
<div className="Appfeatures">
<div className="l-box-lrg pure-u-1 pure-u-md-2-5">
<form className="pure-form pure-form-stacked">
<fieldset>
<label for="name">Your Name</label>
<input
id="name"
type="text"
placeholder="enter your name"
></input>
<label for="email"> Your Email</label>
<input
id="email"
type="email"
placeholder="enter your email"
></input>
<label for="password">Your Password</label>
<input
id="password"
type="<PASSWORD>"
placeholder="<PASSWORD>"
></input>
<button type="submit" className="pure-button">
Sign Up
</button>
</fieldset>
</form>
</div>
</div>
</div>
<Footer />
</div>
</div>
);
}
}
export default HomePage;
<file_sep>import React from "react";
import * as firebase from "firebase";
var firebaseConfig = {
apiKey: "<KEY>",
authDomain: "webapp-440d3.firebaseapp.com",
databaseURL: "https://webapp-440d3.firebaseio.com",
projectId: "webapp-440d3",
storageBucket: "webapp-440d3.appspot.com",
messagingSenderId: "842691501545",
appId: "1:842691501545:web:10a92ecfe45be656fabf78",
measurementId: "G-NLD470EG8C",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export default firebase;
<file_sep>const Images = {
ishita: require("../images/lotus.png"),
};
export default Images;
| 4d219222801de530bef6403ec0fb3b252c5c7d3f | [
"JavaScript"
] | 3 | JavaScript | 27ishita/ChatNow.io | 30b0bff2c5bfe849e190a01a881b6a21a10410b6 | 3ed213a60bc9c7ac6aa68a6898ff55b6f76b7e0d |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import * as d3 from 'd3';
class XAxis extends Component {
constructor(props) {
super();
this.xScale = d3.scaleTime();
this.update_d3(props);
}
componentWillReceiveProps(newProps) {
this.update_d3(newProps);
}
update_d3(props) {
let that = this;
that.xScale.domain(
d3.extent(props.data, function(d) { return d.date; }))
.rangeRound([0, props.width]);
}
componentDidUpdate() { this.renderAxis(); }
componentDidMount() { this.renderAxis(); }
renderAxis() {
let node = ReactDOM.findDOMNode(this);
d3.select(node).call(d3.axisBottom(this.xScale));
}
render() {
let translate = `translate(${this.props.leftMargin}, ${this.props.height - 40})`;
return (
<g className="axis axis--x" transform={translate}>
</g>
);
}
}
export default XAxis;<file_sep>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import * as d3 from 'd3';
class YAxis extends Component {
constructor(props) {
super();
this.yScale = d3.scaleLinear();
this.update_d3(props);
}
componentWillReceiveProps(newProps) {
this.update_d3(newProps);
}
update_d3(props) {
let that = this;
that.yScale.domain(
d3.extent(props.data, function(d) { return d.close; }))
.rangeRound([
props.height - props.topMargin - props.bottomMargin,
0
]);
}
componentDidUpdate() { this.renderAxis(); }
componentDidMount() { this.renderAxis(); }
renderAxis() {
let node = ReactDOM.findDOMNode(this);
d3.select(node).call(d3.axisLeft(this.yScale))
.append("text")
.attr("fill", "#000")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.style("text-anchor", "end")
.text("Price ($)");
}
render() {
let translate = `translate(40, 0)`;
return (
<g className="axis axis--y" transform={translate}>
</g>
);
}
}
export default YAxis; | 75c7df85b2fef3ccfee1ae4c2017977111a25182 | [
"JavaScript"
] | 2 | JavaScript | seanslerner/farm-data | 35fd123044cc48c5186b67d0f3b4cf8797297750 | e18e23acbd5f102903e22115417351815f0ee754 |
refs/heads/main | <file_sep>from functools import reduce
def sum_num(a, b):
return a+b
li1 = reduce(sum_num, [1,2,3,4])
print(li1)<file_sep># python_programs_2
Some more Intermediate and Advanced Level Python Programs.
<file_sep>import bisect
# It does tell you where to place the value but your list should be sorted. If your list has randomly things placed in it then module may lead to wrong conclusion. Also it doesn't give you any warning that your list is not sorted.
lis = [1,2,5,10,15,17,28,35,59,61]
print(bisect.bisect(lis, 55))
# Output:
# 8
import bisect
lis1 = ["a","e", "h", "m", "o", "s"]
print(bisect.bisect(lis1, "k"))
# Output:
# 3
import bisect
lis = [1,2,5,10,15,17,28,35,59,61]
print(bisect.bisect(lis, 55))
bisect.insort(lis, 55)
print(lis)
# Output:
# 8
# [1, 2, 5, 10, 15, 17, 28, 35, 55, 59, 61]
import bisect
lis1 = ["a","e", "h", "m", "o", "s"]
print(bisect.bisect(lis1, "k"))
bisect.insort(lis1, "k")
print(lis1)
# Output:
# 3
# ['a', 'e', 'h', 'k', 'm', 'o', 's']<file_sep>try:
open("this.txt")
except Exception as e:
print(e)
# open("this.txt")
print("program zinda hai")
# try:
# file = open("this.txt", 'r')
# except EOFError as e:
# print("eof error")
# except IOError as e:
# print("we can handle this error")
# finally:
# print("This will be printed irrespective of the exception occurrence")
# try:
# print("I will try this code and will throw exception if there is any problem")
# except Exception as e:
# print("I will run only if try block fails")
# else:
# print("I will run only if there is no exception. Use this to run code which should"
# "only execute if there is no exception")
# finally:
# print("This will be printed in every case")
<file_sep>#Map function
# map(function_to_apply, list of inputs)
def square(n):
return n**2
h1 = [1,2,4,5,7]
# sq =[]
# for item in h1:
# sq.append(item**2)
sq = list(map(square, h1))
print(sq)
<file_sep>'''
Syntax:
lambda argument : manipulate(argument)
'''
# def add(a, b):
# s = a+b
# return s
add = lambda x,y:x+y
print(add(4,12))
# def x(val):
# return val[1]
a = [(1,2), (4,5), (555,34)]
a.sort(key= lambda x:x[1])
print(a)
<file_sep>a = ["CodeWithHarry", "Hindi Coding Zone", "Python", "Intermediate"]
i = 0
for item in a:
print(i, item)
i += 1
a = ["CodeWithHarry", "Hindi Coding Zone", "Python", "Intermediate"]
for i, item in enumerate(a):
print(i, item)<file_sep># *args and **kwargs tutorial
# *vars and **kvars tutorial
def function_1(*argsjoke):
if(len(argsjoke) ==3):
print("The name of the student is", argsjoke[0], "and age is",argsjoke[1], "and rollno is",argsjoke[2])
else:
print("The name of the student is ", argsjoke[0], "and age is ", argsjoke[1])
def printmarks(**kwargs):
print(type(kwargs))
for key, value in kwargs.items():
print(key, value)
def master(normal, *args, **kwargs):
print(normal)
for i in args:
print(i)
for key, value in kwargs.items():
print(key, value)
lis = ["harry", 22, 867656]
# function_1(*lis)
marklist = {"Harry" : 100, "rohan das":97, "<NAME>": 91, "The Programmer":80,
"<NAME>":89, "<NAME>":87, "<NAME>":90, "gaming with hunny": 76}
# printmarks(**marklist)
master("normal arg", *lis, **marklist)
<file_sep>'''
Iterable -
Iterator -
Iteration -
'''
def gen(n):
for i in range(n):
yield i
ob1 = gen(4)
# print(next(ob1))
# print(next(ob1))
# print(next(ob1))
# print(next(ob1))
# print(next(ob1))
num = "harry"
iter1 = iter(num)
print(next(iter1))
print(next(iter1))
print(next(iter1))
print(next(iter1))
print(next(iter1))
print(next(iter1))
print(next(iter1))
print(next(iter1))
| bd2e42e74d13f848d19071472b586b333afeec4c | [
"Markdown",
"Python"
] | 9 | Python | soham0511/python_programs_2 | 94e835d0fdccb0e131e712a921995227b7757eff | 0a0b19fb7756624488bdcbdc66479a604781a40b |
refs/heads/master | <repo_name>LukeRobbins2112/TLPI_Exercises<file_sep>/chapter4/tlpi_cp.c
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#define BUF_SIZE 1024
int main(int argc, char ** argv){
if (argc != 3){
printf("Err - incorrect num arguments\n");
_exit(-1);
}
int inputFd, outputFd;
int openFlags;
mode_t filePermissions;
char buffer[BUF_SIZE];
// Open file for read - first arg
inputFd = open(argv[1], O_RDONLY);
if (inputFd == -1){
printf("Err - unable to open file for reading\n");
_exit(-1);
}
// Set flags and open second file
// Create if doesn't exist, truncate if does, write only
openFlags = O_CREAT | O_TRUNC | O_WRONLY;
// -rw-rw-rw-
filePermissions = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
outputFd = open(argv[2], openFlags, filePermissions);
if (outputFd == -1){
printf("Err - unable to open file for reading\n");
_exit(-1);
}
size_t bytes;
while((bytes = read(inputFd, buffer, BUF_SIZE)) > 0){
if (write(outputFd, buffer, bytes) != bytes){
printf("Err - not all bytes coud be written\n");
_exit(-1);
}
}
if (close(inputFd) == -1){
printf("Err closing input file\n");
_exit(-1);
}
if (close(outputFd) == -1){
printf("Err closing output file\n");
_exit(-1);
}
return 0;
}
<file_sep>/chapter5/my_dup2.c
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#define BUF_SIZE 1024
#define TARGET_FD 7
int myDup2(int originalFd, int newFD){
if (originalFd == newFD){
// Get info about the current open file
int result = fcntl(originalFd, F_GETFL);
// If not valid original fd
if (result == -1){
errno = EBADF;
return -1;
}
// No need to duplicate, return original
return originalFd;
}
// Get first FD, starting at target FD
int dup2FD = fcntl(originalFd, F_DUPFD, newFD);
// If result doesn't equal that, then newFD is already in use
if (dup2FD != newFD){
// Close it to make it available
close(newFD);
// Then re-call fcntl now that the fd is available
dup2FD = fcntl(originalFd, F_DUPFD, newFD);
if (dup2FD != newFD) perror("fcntl");
}
return dup2FD;
}
int main(int argc, char ** argv){
if (argc < 3){
printf("Error, need original and target fds\n");
exit(1);
}
int origFD = atoi(argv[1]); // FD to duplicate
int targetFD = atoi(argv[2]); // Desired FD value
char buffer[BUF_SIZE];
int bytesRead = 0;
// Use target FD to test that dup2 takes it over
int takeFD = dup2(origFD, targetFD);
int copyFD = myDup2(origFD, targetFD);
if (copyFD == -1) perror("dup2");
printf("New fd from dup2(%d, %d): %d\n", origFD, targetFD, copyFD);
while((bytesRead = read(STDIN_FILENO, buffer, BUF_SIZE)) > 0){
// Null-terminate string
buffer[bytesRead] = '\0';
if (strcmp(buffer, "\n") == 0) break;
write(copyFD, buffer, bytesRead);
}
return 0;
}
<file_sep>/chapter4/tlpi_dup2.c
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#define BUF_SIZE 1024
int main(){
int specificFD = dup2(STDOUT_FILENO, 5);
printf("File descriptor is: %d\n", specificFD);
char buffer[BUF_SIZE];
int bytesRead = 0;
while((bytesRead = read(STDIN_FILENO, buffer, BUF_SIZE)) > 0){
// Null-terminate string
buffer[bytesRead] = '\0';
if (strcmp(buffer, "\n") == 0) break;
write(specificFD, buffer, bytesRead);
}
return 0;
}
<file_sep>/chapter5/my_dup.c
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#define BUF_SIZE 1024
#define FD_MIN 10
int myDup(int originalFd){
return fcntl(originalFd, F_DUPFD, 0);
}
int main(){
char buffer[BUF_SIZE];
int bytesRead = 0;
int copyFD = myDup(STDOUT_FILENO);
if (copyFD == -1) perror("dup");
printf("New fd: %d\n", copyFD);
while((bytesRead = read(STDIN_FILENO, buffer, BUF_SIZE)) > 0){
// Null-terminate string
buffer[bytesRead] = '\0';
if (strcmp(buffer, "\n") == 0) break;
write(copyFD, buffer, bytesRead);
}
return 0;
}
<file_sep>/chapter4/tlpi_tee.c
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#define BUF_SIZE 1024
void errExit(char * output){
perror(output);
_exit(1);
}
int main(int argc, char ** argv){
if (argc < 2)
printf("err - need file name\n");
// Open file for output
int flags = O_WRONLY | O_CREAT;
// If no '-a' flag, truncate - otherwise append
if (getopt(argc, argv, "a") == 'a'){
flags = flags | O_APPEND;
printf("Append mode\n");
}
else{
flags = flags | O_TRUNC;
printf("Truncate mode\n");
}
// Set mode
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
// Open the file
// optind is set by getopt - used to specify non-option arguments
// Using this, non-option arguments have to come AFTER all option (flag) args
int fd = open(argv[optind], flags, mode);
// Read from stdin while not EOF
// Continuously call read()
int bytesRead = 0;
char buf[BUF_SIZE];
while((bytesRead = read(STDIN_FILENO, buf, BUF_SIZE)) > 0){
printf("Bytes read: %d\n", bytesRead);
// Null-terminate string
buf[bytesRead] = '\0';
if (strcmp(buf, "\n") == 0 ) break;
// Output to both STDOUT and the file
int bytesWritten = write(fd, buf, bytesRead + 1);
printf("Bytes written: %d\n", bytesWritten);
printf("%s", buf);
}
// Don't have to close STDIN fd
return 0;
}
<file_sep>/chapter4/tlpi_lseek.c
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char ** argv){
// [program] [filename] [command]
if (argc < 3){
printf("Not enough args\n");
_exit(1);
}
// Open the file
int flags = O_RDWR | O_CREAT;
mode_t mode = S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
int fd = open(argv[1], flags, mode);
if (fd == -1){
perror("open");
_exit(1);
}
printf("Opened file %s\n", argv[1]);
// Evaluate the commands (loop through list given)
for (int i = 2; i < argc; i++){
int bytes = 0;
off_t offset = 0;
char * buf;
switch(argv[i][0]){
case 'r':
bytes = atoi(&argv[i][1]);
buf = (char *)malloc(bytes+1);
int bytesRead = read(fd, buf, bytes);
buf[bytesRead] = '\0';
printf("Data read from file: %s\n", buf);
free(buf);
break;
case 'w':
bytes = atoi(&argv[i][1]);
int len = strlen(&argv[i][1]);
int bytesWritten = write(fd, &argv[i][1], len);
if (bytesWritten == -1){
perror("write");
_exit(1);
}
printf("%s: Write succeeded\n", argv[i]);
break;
case 's':
offset = (off_t)atoi(&argv[i][1]);
int result = lseek(fd, offset, SEEK_SET);
if (result == -1){
perror("lseek");
_exit(1);
}
printf("%s: seek succeeded\n", argv[i]);
break;
default:
printf("default\n");
break;
}
}
// Close the file
if (close(fd) == -1){
perror("close");
_exit(-1);
}
}
<file_sep>/chapter4/tlpi_dup.c
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#define BUF_SIZE 1024
int main(){
int secondOutput = dup(STDOUT_FILENO);
char buffer[BUF_SIZE];
int bytesRead = 0;
while((bytesRead = read(STDIN_FILENO, buffer, BUF_SIZE)) > 0){
// Null-terminate string
buffer[bytesRead] = '\0';
if (strcmp(buffer, "\n") == 0) break;
write(STDOUT_FILENO, buffer, bytesRead);
write(secondOutput, buffer, bytesRead);
}
return 0;
}
<file_sep>/chapter5/lseek_append.c
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUF_SIZE 1024
int main(){
int flags = O_RDWR | O_CREAT | O_APPEND;
mode_t mode = S_IRWXU;
int fd = open("file.txt", flags, mode);
if (fd == -1) perror("open");
char buffer[BUF_SIZE];
int bytesRead = 0;
while((bytesRead = read(STDIN_FILENO, buffer, BUF_SIZE)) > 0){
// Null-terminate string
buffer[bytesRead] = '\0';
if (strcmp(buffer, "\n") == 0) break;
int status = lseek(fd, 0, SEEK_SET);
write(fd, buffer, bytesRead);
}
return 0;
}
<file_sep>/chapter4/tlpi_readv.c
#include <sys/uio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#define BUF_SIZE 1024
int main(){
// Create a new file for reading and writing
int flags = O_RDWR | O_CREAT | O_APPEND | O_TRUNC;
mode_t mode = S_IRUSR | S_IWUSR | S_IWGRP | S_IRGRP | S_IROTH | S_IWOTH;
int fd = open("readv.txt", flags, mode);
if (fd == -1){
perror("open");
_exit(1);
}
// Read in data from STDIN, write to file
char buf[BUF_SIZE];
int bytesRead = 0;
while((bytesRead = read(STDIN_FILENO, buf, BUF_SIZE)) > 0){
buf[bytesRead] = '\0'; // Error if buf read all 1024
if (strcmp(buf, "\n") == 0) break;
int bytesWritten = write(fd, buf, bytesRead);
if (bytesWritten < bytesRead){
perror("write");
_exit(1);
}
}
// Seek to beginning of the file, since readv() uses current file offset position
off_t result = lseek(fd, 0, SEEK_SET);
if (result == -1){
perror("lseek");
_exit(1);
}
// Scatter read operations
char buf0[11];
char buf1[6];
char buf2[6];
struct iovec iov[3];
iov[0].iov_base = buf0;
iov[0].iov_len = 10;
iov[1].iov_base = buf1;
iov[1].iov_len = 5;
iov[2].iov_base = buf2;
iov[2].iov_len = 5;
ssize_t bytesReadV = readv(fd, iov, 3);
if (bytesReadV == -1){
perror("readv");
_exit(1);
}
// Null terminate data for printing
buf0[10] = '\0';
buf1[5] = '\0';
buf2[5] = '\0';
printf("Bytes read: %li\n", (long int) bytesReadV);
printf("Buf %d, %s\n", 0, buf0);
printf("Buf %d, %s\n", 1, buf1);
printf("Buf %d, %s\n", 2, buf2);
return 0;
}
<file_sep>/chapter4/tlpi_fcntl_DUPFD.c
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#define BUF_SIZE 1024
#define FD_MIN 10
int main(){
int firstFD = fcntl(STDOUT_FILENO, F_DUPFD, FD_MIN);
int secondFD = fcntl(STDOUT_FILENO, F_DUPFD, FD_MIN);
printf("First fd available from %d+: %d\n", FD_MIN, firstFD);
printf("Second fd available from %d+: %d\n", FD_MIN, secondFD);
char buffer[BUF_SIZE];
int bytesRead = 0;
while((bytesRead = read(STDIN_FILENO, buffer, BUF_SIZE)) > 0){
// Null-terminate string
buffer[bytesRead] = '\0';
if (strcmp(buffer, "\n") == 0) break;
write(secondFD, buffer, bytesRead);
}
return 0;
}
<file_sep>/chapter12/tlpi_processes_by_name.c
#include <pwd.h>
#include <grp.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#define BUF_SIZE 1024
// Function declarations
char * userNameFromId(uid_t uid);
uid_t userIdFromName(const char *name);
void traverseProc(const char * dirPath, const char * nameArg);
void process_pid_status(const char * fileName, const char * UID);
/* Return name corresponding to 'uid', or NULL on error */
char * userNameFromId(uid_t uid)
{
struct passwd *pwd;
pwd = getpwuid(uid);
return (pwd == NULL) ? NULL : pwd->pw_name;
}
/* Return UID corresponding to 'name', or -1 on error */
uid_t userIdFromName(const char *name)
{
struct passwd *pwd;
uid_t u;
char *endptr;
if (name == NULL || *name == '\0')
return -1;
u = strtol(name, &endptr, 10); /* As a convenience to caller */
if (*endptr == '\0') /* allow a numeric string */
return u;
pwd = getpwnam(name);
if (pwd == NULL)
return -1;
return pwd->pw_uid;
}
void traverseProc(const char * dirPath, const char * nameArg){
DIR * dirPtr;
struct dirent *dp;
dirPtr = opendir(dirPath);
if (dirPtr == NULL) {
printf("opendir failed on '%s'", dirPath);
return;
}
uid_t myUID = userIdFromName(nameArg);
char stringUID[16];
sprintf(stringUID, "%d", (int)myUID);
printf("Searching for UID %s\n", stringUID);
/* For each entry in this directory, print directory + filename */
for (;;) {
errno = 0; /* To distinguish error from end-of-directory */
dp = readdir(dirPtr);
if (dp == NULL)
break;
if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
continue; /* Skip . and .. */
// Only process PID directories, which are numbers
int is_PID_Dir = 1;
size_t subDirLen = strlen(dp->d_name);
for (size_t i = 0; i < subDirLen; i++){
if (!isdigit(dp->d_name[i]))
is_PID_Dir = 0;
}
if (!is_PID_Dir) continue;
size_t fullLen = strlen(dirPath) + subDirLen + 2 + 7; // + 2 for / and null terminator, + 7 for /status
char * fullPath = (char *)malloc(fullLen);
strcpy(fullPath, dirPath);
strcat(fullPath, "/");
strcat(fullPath, dp->d_name);
strcat(fullPath, "/status");
fullPath[fullLen] = '\0';
// printf("Full Path: %s\n", fullPath);
process_pid_status(fullPath, stringUID);
}
if (errno != 0)
perror("readdir");
if (closedir(dirPtr) == -1)
perror("closedir");
}
void process_pid_status(const char * fileName, const char * UID){
int flags = O_RDONLY;
mode_t mode = S_IRWXU;
int PID_fd = open(fileName, flags, mode);
if (PID_fd == -1){
perror("open");
exit(1);
}
char buf[BUF_SIZE+1];
int bytesRead = 0;
while((bytesRead = read(PID_fd, buf, BUF_SIZE)) > 0){
// Null-terminate
buf[bytesRead] = '\0';
if (strstr(buf, "Uid") != NULL && strstr(buf, UID) != NULL){
// This is the Uid line, and the user we specified
printf("Process %s belongs to user %s\n", fileName, UID);
break;
}
}
if (close(PID_fd) == -1){
perror("close");
exit(1);
}
}
int main(int argc, char **argv){
if (argc < 2){
printf("err - need to supply user name\n");
exit(1);
}
traverseProc("/proc", argv[1]);
return 0;
}
| 10bd87e1678e137daa89a5fa6089be7e6fef2e81 | [
"C"
] | 11 | C | LukeRobbins2112/TLPI_Exercises | 2da15078737057e2eda0015b7219bc7307ddf65b | 8b8e8bf27c596e1ba1433776f77d09c240c7f8b0 |
refs/heads/master | <file_sep>import vk_api
import time
import re
import collections
locations = ['гараж', 'склад', 'склад 2', 'дом', 'лес', 'корабль', 'самолет']
cur_location_id = 0
responce = ''
id = -162041941
stat_msg = 'статистика'
vk = vk_api.VkApi(login = '', password = '')
vk.auth()
def get_statistics():
vk.method('messages.send', {'user_id': id,'message': stat_msg})
time.sleep(10)
responce = vk.method('messages.get', {'count': 1})
return responce['items'][0]['body']
def get_rem_times(statistics):
matches = re.findall(r'[ :а-яА-Я0-9]* мин', statistics)
rem_times = []
for match in matches:
match = match.replace('мин', '').strip().split(': ')
rem_times.append([match[0], int(match[1])])
return rem_times
def process_rem_times(rem_times):
rem_times = sorted(rem_times, key=lambda x: x[1])
for rem_time in rem_times:
rem_time[1]*=60
rem_time[1]+=10
for i in range(len(rem_times)):
sum = 0
for k in range(0, i):
sum += rem_times[k][1]
rem_times[i][1] -= sum
return rem_times
def collect_bitcoins(rem_times):
for rem_time in rem_times:
time.sleep(rem_time[1])
vk.method('messages.send', {'user_id': id,'message': rem_time[0]})
time.sleep(10)
vk.method('messages.send', {'user_id': id,'message': 'сбор'})
time.sleep(10)
def get_btc_count(statistics):
matches = re.findall(r'\d* BTC', statistics)
return int(matches[0].replace('BTC', '').strip())
def exchange(bitcoins):
vk.method('messages.send', {'user_id': id,'message': 'обмен {}'.format(bitcoins)})
time.sleep(10)
def buy_new_location(next_location_id):
if next_location_id == 3:
next_location_id = 4
elif next_location_id == 7:
next_location_id = 3
vk.method('messages.send', {'user_id': id,'message': 'магазин'})
time.sleep(10)
vk.method('messages.send', {'user_id': id,'message': str(next_location_id)})
time.sleep(10)
responce = vk.method('messages.get', {'count': 1})
responce = responce['items'][0]['body']
if 'успешно' in responce:
global cur_location_id
cur_location_id = next_location_id
vk.method('messages.send', {'user_id': id,'message': locations[cur_location_id]})
time.sleep(10)
vk.method('messages.send', {'user_id': id,'message': 'купить'})
time.sleep(10)
vk.method('messages.send', {'user_id': id,'message': 'сбор'})
time.sleep(10)
bitcoins = get_btc_count(get_statistics())
exchange(bitcoins)
update_location()
def update_location():
vk.method('messages.send', {'user_id': id,'message': locations[cur_location_id]})
time.sleep(10)
vk.method('messages.send', {'user_id': id,'message': 'купить'})
time.sleep(10)
responce = vk.method('messages.get', {'count': 1})
responce = responce['items'][0]['body']
while not ('Недостаточно' in responce or 'полностью' in responce):
vk.method('messages.send', {'user_id': id,'message': 'купить'})
time.sleep(10)
responce = vk.method('messages.get', {'count': 1})
responce = responce['items'][0]['body']
if 'полностью' in responce:
if(cur_location_id == 4):
print(time.time() - begin_time)
buy_new_location(cur_location_id + 1)
if __name__ == '__main__':
while True:
begin_time = time.time()
statistics = get_statistics()
rem_times = get_rem_times(statistics)
rem_times = process_rem_times(rem_times)
collect_bitcoins(rem_times)
bitcoins = get_btc_count(get_statistics())
exchange(bitcoins)
update_location()
| f379bb49c97323b1f1e293f0d40580579f4add80 | [
"Python"
] | 1 | Python | denis5417/auto_btc_player | bb04dc3a8de8caa4f03277c9f65df46ffd7ea2bb | cbb2b35ef88676e338eb8f5aede99469eceedefa |
refs/heads/master | <file_sep># 自定义倒计时组件
## component install 组件引入
```
npm/cnpm install --save-dev dircountdown
```
## file of vue reference vue文件引入
```
import CountDown from 'dircountdown'
components:{CountDown}
```
## html reference html引入
`<dir-clock :start="startSecond" end="0" style="color:#000;" v-on:endcallback="endFn" :autoshow='false' splitsymbol="时-分-秒" :autostart="false" ref="countdown"></dir-clock>`
## props 属性
Props属性|describe属性描述
-|-|
start| 开始时间(以秒为单位如一分钟则为3600) starttime(in seconds,like a minute is 3600)
end|结束时间 endTime
endcallback|当时间为0时的回调函数 callback function when time ends with zero
autoshow|当小时为0时或者小时分钟都为0时,是否隐藏例如00:00:30则显示为30 when hour or minute is zero,they will be hide,like 00:00:30 is 30
splitsymbol|时分秒分割单位 (时-分-秒||:-:-:) symbol to split time
autostart|是否一进入就进行倒计时 whether to start when enter the page
## Demo
```
app.vue
<template>
<div id="app">
<count-down :start="startSecond" end="0" style="color:#000;" v-on:endcallback="endFn" :autoshow='false' splitsymbol="时-分-秒" :autostart="false" ref="countdown"></count-down>
<button @click="startCount">开始计时</button>
</div>
</template>
<script>
import CountDown from 'dircountdown'
export default {
name: 'App',
data(){
return{
startSecond: '10',
}
},
methods:{
endFn(){
alert("时间到!");
},
startCount(){
this.$refs.countdown.countTime();
}
},
components:{CountDown}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
```
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
```
<file_sep>import VueCountDown from './countdown.vue';
VueCountDown.install = Vue => Vue.component(VueCountDown.name,VueCountDown);
export default VueCountDown; | a7f7084f3b5d94bf874baf89d87017f0481b7421 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | applebring/DirCountDown | 017a839d300fca91c8568a64ac1a62741ceba418 | d463bed4e9fd93e40a37d40288e50d66ec46175d |
refs/heads/devel | <repo_name>ralic/dbeaver<file_sep>/plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/internal/PostgreMessages.properties
postgre_referential_integrity_disable_warning = All triggers will be either enabled or disabled
<file_sep>/plugins/org.jkiss.dbeaver.ext.vertica/src/org/jkiss/dbeaver/ext/vertica/model/VerticaTable.java
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* 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.jkiss.dbeaver.ext.vertica.model;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.ext.generic.model.GenericTable;
import org.jkiss.dbeaver.model.DBPObjectStatistics;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.preferences.DBPPropertySource;
import java.sql.SQLException;
/**
* VerticaTable
*/
public class VerticaTable extends GenericTable implements DBPObjectStatistics
{
public static final String TABLE_TYPE_FLEX = "FLEXTABLE";
private long tableSize = -1;
public VerticaTable(VerticaSchema container, String tableName, String tableType, JDBCResultSet dbResult) {
super(container, tableName, tableType, dbResult);
}
@Override
public boolean isPhysicalTable() {
return !isView() && !isFlexTable();
}
public boolean isFlexTable() {
return ((VerticaSchema)getContainer()).isFlexTableName(getName());
}
@Override
public boolean hasStatistics() {
return tableSize != -1;
}
@Override
public long getStatObjectSize() {
return tableSize;
}
void fetchStatistics(JDBCResultSet dbResult) throws SQLException {
tableSize = dbResult.getLong("used_bytes");
}
@Nullable
@Override
public DBPPropertySource getStatProperties() {
return null;
}
}
<file_sep>/plugins/org.jkiss.dbeaver.ext.informix/OSGI-INF/l10n/bundle.properties
# DBeaver - Universal Database Manager
# Copyright (C) 2010-2021 DBeaver Corp and others
<file_sep>/plugins/org.jkiss.dbeaver.ext.oracle/src/org/jkiss/dbeaver/ext/oracle/internal/OracleMessages.properties
dialog_connection_sid=SID
dialog_connection_service=Service Name
edit_oracle_dependencies_dependency_name=Dependencies
edit_oracle_dependencies_dependency_description=The objects this object depends on.
edit_oracle_dependencies_dependent_name=Dependent
edit_oracle_dependencies_dependent_description=The objects that depend on this object.
oracle_referential_integrity_disable_warning=All foreign key constraints will be either enabled or disabled
<file_sep>/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerStructureAssistant.java
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* 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.jkiss.dbeaver.ext.mssql.model;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.mssql.SQLServerUtils;
import org.jkiss.dbeaver.model.DBConstants;
import org.jkiss.dbeaver.model.exec.DBCExecutionPurpose;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.impl.struct.AbstractObjectReference;
import org.jkiss.dbeaver.model.impl.struct.RelationalObjectType;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* SQLServerStructureAssistant
*/
public class SQLServerStructureAssistant implements DBSStructureAssistant<SQLServerExecutionContext> {
private final SQLServerDataSource dataSource;
public SQLServerStructureAssistant(SQLServerDataSource dataSource)
{
this.dataSource = dataSource;
}
@Override
public DBSObjectType[] getSupportedObjectTypes()
{
return new DBSObjectType[] {
SQLServerObjectType.S,
SQLServerObjectType.U,
SQLServerObjectType.IT,
SQLServerObjectType.V,
SQLServerObjectType.SN,
SQLServerObjectType.P,
SQLServerObjectType.FN,
SQLServerObjectType.FT,
SQLServerObjectType.FS,
SQLServerObjectType.X,
};
}
@Override
public DBSObjectType[] getSearchObjectTypes() {
return new DBSObjectType[] {
RelationalObjectType.TYPE_TABLE,
RelationalObjectType.TYPE_VIEW,
SQLServerObjectType.SN,
RelationalObjectType.TYPE_PROCEDURE,
};
}
@Override
public DBSObjectType[] getHyperlinkObjectTypes()
{
return new DBSObjectType[] {
SQLServerObjectType.S,
SQLServerObjectType.U,
SQLServerObjectType.IT,
SQLServerObjectType.V,
RelationalObjectType.TYPE_PROCEDURE,
};
}
@Override
public DBSObjectType[] getAutoCompleteObjectTypes()
{
return new DBSObjectType[] {
SQLServerObjectType.U,
SQLServerObjectType.V,
SQLServerObjectType.P,
SQLServerObjectType.FN,
SQLServerObjectType.IF,
SQLServerObjectType.TF,
SQLServerObjectType.X
};
}
@NotNull
@Override
public List<DBSObjectReference> findObjectsByMask(@NotNull DBRProgressMonitor monitor, @NotNull SQLServerExecutionContext executionContext,
@NotNull ObjectsSearchParams params) throws DBException {
DBSObject parentObject = params.getParentObject();
SQLServerDatabase database = parentObject instanceof SQLServerDatabase ?
(SQLServerDatabase) parentObject :
(parentObject instanceof SQLServerSchema ? ((SQLServerSchema) parentObject).getDatabase() : null);
if (database == null) {
database = executionContext.getContextDefaults().getDefaultCatalog();
}
if (database == null) {
database = executionContext.getDataSource().getDefaultDatabase(monitor);
}
if (database == null) {
return Collections.emptyList();
}
SQLServerSchema schema = parentObject instanceof SQLServerSchema ? (SQLServerSchema) parentObject : null;
if (schema == null && !params.isGlobalSearch()) {
schema = executionContext.getContextDefaults().getDefaultSchema();
}
try (JDBCSession session = executionContext.openSession(monitor, DBCExecutionPurpose.META, "Find objects by name")) {
List<DBSObjectReference> objects = new ArrayList<>();
// Search all objects
searchAllObjects(session, database, schema, params, objects);
return objects;
}
}
private void searchAllObjects(final JDBCSession session, final SQLServerDatabase database, final SQLServerSchema schema,
@NotNull ObjectsSearchParams params, List<DBSObjectReference> objects) throws DBException {
final List<SQLServerObjectType> supObjectTypes = new ArrayList<>(params.getObjectTypes().length + 2);
for (DBSObjectType objectType : params.getObjectTypes()) {
if (objectType instanceof SQLServerObjectType) {
supObjectTypes.add((SQLServerObjectType) objectType);
} else if (objectType == RelationalObjectType.TYPE_PROCEDURE) {
supObjectTypes.addAll(SQLServerObjectType.getTypesForClass(SQLServerProcedure.class));
} else if (objectType == RelationalObjectType.TYPE_TABLE) {
supObjectTypes.addAll(SQLServerObjectType.getTypesForClass(SQLServerTable.class));
} else if (objectType == RelationalObjectType.TYPE_CONSTRAINT) {
supObjectTypes.addAll(SQLServerObjectType.getTypesForClass(SQLServerTableCheckConstraint.class));
supObjectTypes.addAll(SQLServerObjectType.getTypesForClass(SQLServerTableForeignKey.class));
} else if (objectType == RelationalObjectType.TYPE_VIEW) {
supObjectTypes.addAll(SQLServerObjectType.getTypesForClass(SQLServerView.class));
}
}
if (supObjectTypes.isEmpty()) {
return;
}
StringBuilder objectTypeClause = new StringBuilder(100);
for (SQLServerObjectType objectType : supObjectTypes) {
if (objectTypeClause.length() > 0) objectTypeClause.append(",");
objectTypeClause.append("'").append(objectType.getTypeID()).append("'");
}
if (objectTypeClause.length() == 0) {
return;
}
StringBuilder sql = new StringBuilder("SELECT TOP ")
.append(params.getMaxResults() - objects.size())
.append(" * FROM ")
.append(SQLServerUtils.getSystemTableName(database, "all_objects"))
.append(" o ");
if (params.isSearchInComments()) {
sql.append("LEFT JOIN sys.extended_properties ep ON ((o.parent_object_id = 0 AND ep.minor_id = 0 AND o.object_id = ep.major_id) OR (o.parent_object_id <> 0 AND ep.minor_id = o.parent_object_id AND ep.major_id = o.object_id)) ");
}
sql.append("WHERE o.type IN (").append(objectTypeClause.toString()).append(") AND ");
if (params.isSearchInComments()) {
sql.append("(");
}
sql.append("o.name LIKE ? ");
if (params.isSearchInComments()) {
sql.append("OR (ep.name = 'MS_Description' AND CAST(ep.value AS nvarchar) LIKE ?)) ");
}
if (schema != null) {
sql.append("AND o.schema_id = ? ");
}
sql.append("ORDER BY o.name");
// Seek for objects (join with public synonyms)
try (JDBCPreparedStatement dbStat = session.prepareStatement(sql.toString())) {
dbStat.setString(1, params.getMask());
int schemaIdIdx = 2;
if (params.isSearchInComments()) {
dbStat.setString(2, params.getMask());
schemaIdIdx++;
}
if (schema != null) {
dbStat.setLong(schemaIdIdx, schema.getObjectId());
}
dbStat.setFetchSize(DBConstants.METADATA_FETCH_SIZE);
try (JDBCResultSet dbResult = dbStat.executeQuery()) {
while (dbResult.next() && !session.getProgressMonitor().isCanceled()) {
final long schemaId = JDBCUtils.safeGetLong(dbResult, "schema_id");
final String objectName = JDBCUtils.safeGetString(dbResult, "name");
final String objectTypeName = JDBCUtils.safeGetStringTrimmed(dbResult, "type");
final SQLServerObjectType objectType = SQLServerObjectType.valueOf(objectTypeName);
{
SQLServerSchema objectSchema = schemaId == 0 ? null : database.getSchema(session.getProgressMonitor(), schemaId);
objects.add(new AbstractObjectReference(
objectName,
objectSchema != null ? objectSchema : database,
null,
objectType.getTypeClass(),
objectType)
{
@Override
public DBSObject resolveObject(DBRProgressMonitor monitor) throws DBException {
DBSObject object = objectType.findObject(session.getProgressMonitor(), database, objectSchema, objectName);
if (object == null) {
throw new DBException(objectTypeName + " '" + objectName + "' not found");
}
return object;
}
});
}
}
}
} catch (Throwable e) {
throw new DBException("Error while searching in system catalog", e, dataSource);
}
}
}
<file_sep>/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/DBPReferentialIntegrityController.java
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* 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.jkiss.dbeaver.model;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
public interface DBPReferentialIntegrityController {
boolean supportsChangingReferentialIntegrity(@NotNull DBRProgressMonitor monitor) throws DBException;
void enableReferentialIntegrity(@NotNull DBRProgressMonitor monitor, boolean enable) throws DBException;
/**
* Returns description of things that may go wrong when changing referential integrity setting back and forth.
* When changing referential integrity is not supported, returns an empty string rather than null
* to avoid callers making redundant null checks
* (callers should check if controller supports changing referential integrity anyway).
*
* @param monitor monitor
* @return caveats description, never {@code null}
* @throws DBException if unable to retrieve caveats for any reason
*/
@NotNull
String getReferentialIntegrityDisableWarning(@NotNull DBRProgressMonitor monitor) throws DBException;
}
| cd25e7eec0f65f3a7ab57a1238c267f0269c1fc8 | [
"Java",
"INI"
] | 6 | INI | ralic/dbeaver | 076e39fad778fe9bdbe3817b707b928657ebab94 | d9d7c147252fdab72c06f90393d6816e73a49548 |
refs/heads/main | <repo_name>matthiatt/employee-tracker<file_sep>/db/sqlDatabase.sql
create database employee_db;
use employee_db;
create table employee (
id integer(10) auto_increment not null,
first_name varchar(30) not null,
last_name varchar(30) not null,
role_id integer(10) not null,
manager_id int(10)null
);
create table role (
id integer(10) auto_increment not null,
title varchar(30) not null,
salary decimal(10, 2) not null,
department_id integer(10) not null
);
create table department (
id integer(10) auto_increment not null,
name varchar(30) not null,
department_id integer(10)
);<file_sep>/db/seed.sql
use employee_db;
insert into department (name) values
("Upper Management"),
("HR - Human Resources"),
("I.T Department"),
("Sales Department"),
("Accounting Department"),
("Payroll Department"),
("Logistics Department"),
("Customer Service Department"),
("Recruiting Department");
insert into role (title, salary, department_id) values
("HR Cordinator", 65000, 1),
("Payroll Coordinator", 60000, 1),
("I.T Manager", 73500, 2),
("e-commerce manager", 56000, 2),
("Data Entry", 30000, 2),
("SQL Database Admin", 68475, 2),
("Prodcut Specialist", 66000, 2),
("Jr. Dev", 50000, 2),
("Magento Specialist", 100000, 2),
("Full Stack Developer", 90000, 2),
("Scrum Master", 86000, 2),
("Warhouse Operations Managment", 74012, 3),
("President of Sales", 115000, 3),
("Branch Manager of Sales", 63000, 3),
("Fulfillment Director", 70000, 3),
("Project Manager", 115000, 3),
("Director of Sales Reps", 95000, 3),
("Accounts Receivable Analyst", 60000, 4),
("Accounts Payable Analyst", 60000, 4),
("Project Accountant", 80000, 4),
("Senior Accountant", 90000, 4),
("Work Force Coordinator", 50000, 5),
("Administrative Assistant", 52000, 6),
("Recruitment Specialist", 60000, 7),
("Payroll Administrator", 75000, 9);
insert into employee (first_name, last_name, role_id, manager_id) values
("Matt", "Hiatt", 2, null),
("Devon","Gram", 2, null),
("Kristy", "Bonachini", 7, null),
("Greg","Oostman", 2, 4),
("Jordan","Luxinlurburg", 1, 2),
("Jerrod","Davenport", 2, null),
("Makayla","McHolms", 6, null),
("Sarah","Koliniski", 5, null),
("Amy","Rudenburg", 8, null),
("Tim","Borre", 7, 1),
("Chris","Vishimi", 1, 3),
("Maddi","Bubz", 1, 4),
("Sage","Kaveliac", 5, 2),
("Kevin","Mosser", 1, null),
("Sarah","Test", 7,null),
("Amy","Test", 8,null),
("Tim","Test", 17,1),
("Chris","Test", null),
("Maddi","Test", 7),
("Sage","Test", 4, 9),
("Kevin","Test", 9, null);<file_sep>/app.js
const mysql = require("mysql");
const inquirer = require("inquirer");
var connection = mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: "<PASSWORD>",
database: "employee_db",
});
connection.connect(function (err) {
if (err) throw err;
console.log("connected as id " + connection.threadId + "\n");
askQuestions();
// viewAllRolls();
// viewAllDepartments();
// viewAllEmployees();
});
// First I have to call the questions within the circumstances I wish to create.
// To do this, I first call in the inquirer JSON module and link it to a prompt method.
function askQuestions() {
inquirer
.prompt({
message: "Please make a selection from the following:",
type: "list",
name: "listOptions",
choices: [
"View all employees",
"View all departments",
"View all roles",
"Add employee(s)",
"Add department(s)",
"Add role(s)",
// Didn't get enough time to add these into the homeowrk, but it's there for later to try it. and/or finish it for practice.
// 'Remove employee',
// 'Remove department',
// 'Remove role',
"Update employee role(s)",
"Exit",
],
// Then after the last step, I declared a promise method.
})
.then((activate) => {
switch (activate.listOptions) {
case "View all employees":
viewAllEmployees();
break;
case "View all departments":
viewAllDepartments();
break;
case "View all roles":
viewAllRolls();
break;
case "Add employee(s)":
addEmployee();
break;
case "Add department(s)":
addDepartment();
break;
case "Add role(s)":
addRolls();
break;
// Same as before, I made this thinking I was going to be able to finish it before the deadline, but I wasnt able to get to the bonus options.
// case "Remove Employee":
// removeEmployee();
// break;
// case "Remove Department":
// removeDepartment();
// break;
// case "Remove role":
// removeRole();
// break;
case "Update employee role(s)":
updateEmployeeRole();
break;
default:
console.log("Invalid selection, please try again");
askQuestions();
}
});
}
function viewAllEmployees() {
connection.query("SELECT * FROM employee", function (err, data) {
console.table(data);
askQuestions();
});
}
//do I need to keep this in here with the line above?
// function viewAllEmployees() {
// connection.query("SELECT * FROM employee", function(err, res){
// if(err) throw err;
// for(var i = 0; i < res.length; i++) {
// console.log(res[i].first_name + " " + res[i].last_name + " " + role_id + " " + manager_id);
// }
// });
// }
function viewAllDepartments() {
connection.query("SELECT * FROM department", function (err, data) {
console.table(data);
askQuestions();
});
}
// function viewAllDepartments() {
// connection.query("SELECT * FROM department", function(err, res){
// if(err) throw err;
// for(var i = 0; i < res.length; i++) {
// console.log(res[i].name);
// }
// });
// }
function viewAllRolls() {
connection.query("SELECT * FROM role", function (err, data) {
console.table(data);
askQuestions();
});
}
// function viewAllRolls() {
// connection.query("SELECT * FROM role", function(err, res){
// if(err) throw err;
// for(var i = 0; i < res.length; i++) {
// console.log(res[i].title + " " + department_id + " " + salary);
// }
// });
// }
function addEmployee() {
// var arrayRoleList = rolesArray();
// console.log(arrayRoleList);
console.log("You need to update or insert information.");
inquirer
.prompt([
{
type: "input",
message: "Please state the employees first name.",
name: "firstName",
},
{
type: "input",
message: "Please state the employees last name.",
name: "lastName",
},
{
type: "list",
message: "Please select the employees role here.",
name: "roleChoices",
choices: [
"HR Cordinator",
"Payroll Coordinator",
"I.T Manager",
"e-commerce manager",
"Data Entry",
"SQL Database Admin",
"Prodcut Specialist",
"Jr. Dev",
"Magento Specialist",
"Full Stack Developer",
"Scrum Master",
"Warhouse Operations Managment",
"President of Sales",
"Branch Manager of Sales",
"Project Manager",
"Fulfillment Director",
"Director of Sales Reps",
"Accounts Receivable Analyst",
"Accounts Payable Analyst",
"Project Accountant",
"Senior Accountant",
"Work Force Coordinator",
"Administrative Assistant",
"Recruitment Specialist",
"Payroll Administrator",
],
},
{
type: "number",
message: "Please state the employees ID/ID role.",
name: "roleIdNum",
},
])
.then(function (res) {
connection.query(
"UPDATE employee SET role_id = ? WHERE first_name, last_name = (?,?)",
[res.role_id, res.name],
function (err, data) {
console.log(data.affectedRows + "Employee Updated!\n");
console.table(data);
}
);
askQuestions();
});
connection.end();
function rolesArray() {
return connection.query("SELECT title from roles", function (err, res) {
if (err) recieveError(err);
return res;
});
}
function addDepartment() {
inquirer
.prompt([
{
type: "input",
name: "additionalDepartment",
message: "Please state the department name.",
},
// Was going to add a unique I.D number system in SQL if I had time.
// {
// type: "number",
// name: "DepartmentNumberId",
// message: "Please enter a number I.D that's unique to this NEW department."
// }
])
.then(function (res) {
connection.query(
"INSERT INTO department (name) VALUES (?)",
[res.additionalDepartment],
function (err, data) {
console.log(data.affectedRows + "Department Updated!\n");
console.table(data);
askQuestions();
}
);
});
}
function addRolls() {
inquirer
.prompt([
{
type: "input",
message: "Please state a specific name for your NEW role.",
name: "title",
},
{
type: "number",
message: "Please state the salary :",
name: "salary",
},
{
type: "number",
message: "Please enter a valid I.D to refer to NEW department.",
name: "department_id",
},
])
.then(function (res) {
connection.query(
"INSERT INTO roles (title, salary, department_id) values (?, ?, ?)",
[res.title, res.salary, res.department_id],
function (err, data) {
if (err) throw err;
console.log(res.affectedRows + " Role Added!\n");
console.table(data);
}
);
console.table(data);
askQuestions();
});
}
function updateEmployeeRole() {
var arrayRoleList = rolesArray();
console.log(arrayRoleList);
console.log("You need to update or insert information.");
inquirer
.prompt([
{
type: "list",
name: "updateEmployee",
message: "Please state which employee you would like to update.",
list: [
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>ubbz",
"<NAME>",
"<NAME>",
"Sarah Test",
"Amy Test",
"Tim Test",
"Chris Test",
"Maddi Test",
"Sage Test",
"Kevin Test",
],
},
{
message: "enter the new role ID:",
type: "number",
name: "department_id",
},
])
.then(function (res) {
connection.query(
"UPDATE employee SET role_id = ? WHERE first_name, last_name = ?,?",
[res.role_id, res.name],
function (err, data) {
console.log(res.affectedRows + " Employee Updated!\n");
console.table(data);
}
);
askQuestions();
});
connection.end();
}
}
| 7cc7c093efeea12e916ee4dc889c10891f76ffbc | [
"JavaScript",
"SQL"
] | 3 | SQL | matthiatt/employee-tracker | 2ec6110a9fa0785075f0b39c36c56deba2725bbc | 89d66c60c101b2c1c91fccdd2c51ab12c24f8168 |
refs/heads/master | <repo_name>pierce-eric-wm/Subscription-Service-Project-<file_sep>/admin.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Space Station ADMIN</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>
<body>
<?php
require_once ('authorize.php');
require_once('define.php');
// Connect to the database
$dbh=new PDO('mysql:host=127.0.0.1;dbname=space_station', 'root', 'root');
// Retrieve the score data from MySQL
$query = "SELECT * FROM space_add ORDER BY ID ASC ";
$stmt = $dbh->prepare($query);
$stmt->execute();
$result= $stmt->fetchAll();
// Loop through the array of score data, formatting it as HTML
$filepath = GW_UPLOADPATH . $row['image'];
echo '<table id="admin_layout">';
echo'<td>ID:</td> <td>Image:<td>Name:</td><td>Size:</td><td>Desc:</td><td>Remove:</td>';
// Display the score data
foreach ($result as $row){
echo '<tr></tr>';
echo '<td><span>' . $row['id'] . '</span></td>';
echo '<td>' . $row['image'] . '</td>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>'. $row ['size'] . '</td>';
echo '<td>'. $row ['desc'] . '</td>';
echo '<td><a href="remove_find.php?id=' . $row['id'] . '&desc=' . $row['desc'] . '&name=' . $row['name'] . '&size=' . $row['size'] . '&image=' . $row['image'] . '">Remove</a></td>';
echo '<tr></tr>';
}
echo '</table>';
exit();
?>
</body>
</html>
<file_sep>/sign_up.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>
<body>
<?php
/*if (isset($_POST['submit'])) {
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$date = date("D M j G:i:s T Y");
if (!empty($first_name) && !empty($last_name) && !empty($username) && !empty($email) && !empty($password) && !empty($date)) {
$dbh = new PDO('mysql:host=127.0.0.1;dbname=space_station', 'root', 'root');
$query = "INSERT INTO user_table VALUES (NULL , :first_name, :last_name, :username, :email, :password, NOW())";
$stmt = $dbh->prepare($query);
$result = $stmt->execute(
array(
'first_name' => $first_name,
'last_name' => $last_name,
'username' => $username,
'email' => $email,
'password' => $password
)
);
if (!$result) {
die('Error querying database.');
}*/
?>
<div id="nav_bar">
<h1 id="site_name">Space Station-Sign Up</h1>
<h3 class="right"><a href="index.php" class="a">Home</a></h3>
<h3 class="right"><a href="sign_in.php" class="a">Sign In</a></h3>
</div>
<div id="form_submit">
<h2 id="signsup">Register for Space Station</h2>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name" value="<?php if (!empty($first_name)) echo $first_name; ?>" /><br />
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name" value="<?php if (!empty($last_name)) echo $last_name; ?>" /><br />
<label for="username">Username:</label>
<input type="text" id="username" name="username" value="<?php if (!empty($username)) echo $username; ?>" /> <br />
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="<?php if (!empty($email)) echo $email; ?>" /> <br />
<label for="password">Password:</label>
<input type="<PASSWORD>" id="password" name="password" value="<?php if (!empty($password)) echo $password; ?>" /> <br />
<input type="submit" value="Add User" name="submit"/>
</form>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
$from = '<EMAIL>';
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$date = date("D M j G:i:s T Y");
if (!empty($first_name) && !empty($last_name) && !empty($username) && !empty($email) && !empty($password) && !empty($date)) {
$dbh = new PDO('mysql:host=127.0.0.1;dbname=space_station', 'root', 'root');
$query = "INSERT INTO user_table VALUES (NULL , :first_name, :last_name, :username, :email, :password, NOW())";
$stmt = $dbh->prepare($query);
$result = $stmt->execute(
array(
'first_name' => $first_name,
'last_name' => $last_name,
'username' => $username,
'email' => $email,
'password' => <PASSWORD>
)
);
if (!$result) {
die('Error querying database.');
}
else {
$subject = 'Thank You for subscribing to Space Station';
$msg = "Hello $first_name $last_name thank you for subscribing to Space Station You can now upload you own finds onto this site and have them posted. Have fun!!!";
mail($email, $subject, $msg, 'From:' .$from);
}
echo '<p><a href="sign_in.php"><<Sign In</a></p>';
}
else {
echo '<p>Please enter the requested information below</p>';
}
}
?>
<file_sep>/authorize.php
<?php
$username = 'Space';
$password = '<PASSWORD>';
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) ||
($_SERVER['PHP_AUTH_USER'] != $username) || ($_SERVER['PHP_AUTH_PW'] != $password)) {
// The user name/password are incorrect so send the authentication headers
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Space Station"');
exit('<h2>Space Station</h2><h2 id="admin_error">Sorry, you must enter a valid user name and password to access the admin page</h2>');
}<file_sep>/sign_in.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign In</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>
<body>
<?php
$dbh = new PDO('mysql:host=127.0.0.1;dbname=space_station', 'root', 'root');
if(isset($_SESSION['username'])){
}
$error = false;
$success = false;
if(@$_POST['login']) {
if (!$_POST['username']) {
}
if (!$_POST['password']) {
}
$query = $dbh->prepare("SELECT * FROM user_table WHERE username = :username AND password = :password");
$result = $query->execute(
array(
'username' => $_POST['username'],
'password' => $_POST['password']
)
);
$userinfo = $query->fetch();
if ($userinfo) {
$success = "User, " . $_POST['username'] . " was successfully logged in.";
$_SESSION["first_name"] = $userinfo['first_name'];
$_SESSION["username"] = $userinfo['username'];
header("Location: index_si.php");
} else {
$success = "There was an error logging into the account.";
}
}
?>
<div id="nav_bar">
<h1 id="site_name">Space Station-Sign In</h1>
<h3 class="right"><a href="sign_in.php" class="a">Sign In</a></h3>
<h3 class="right"><a href="index.php" class="a">Home</a></h3>
</div>
<div id="SignInto">
<form id=signin method="post">
<h2 id="h2o">Sign - In</h2>
<label>Username:</label>
<input type="text" name="username" id="name"> <br><br>
<label> Password:</label>
<input type="<PASSWORD>" name="password" id="passsword"> <br><br>
<button type="submit" name="login" value="1">Sign In</button></br />
</form>
<div id="buttonz">
<a href="sign_up.php"><button id="si_su">Sign Up</button> </a><br />
</div>
</div>
<body>
</html>
<file_sep>/add.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add A Find</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>
<body>
<div id="nav_bar">
<h1 id="site_name">Space Station-Add</h1>
<h3 class="right"><a href="sign_up.php" class="a">Sign Up</a></h3>
<h3 class="right"><a href="index.php" class="a">Home</a></h3>
</div>
<br/>
<div id="add_div">
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="500000000"/>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>"/><br/>
<label for="score">Size:</label>
<input type="text" id="size" name="size" value="<?php if (!empty($size)) echo $size; ?>"/><br/>
<label for="score">Description:</label>
<input type="text" id="desc" name="desc" value="<?php if (!empty($desc)) echo $desc; ?>"/><br/>
<label for="image">Image:</label>
<input type="file" id="image" name="image" value="<?php if (!empty($image)) echo $image; ?>"/><br/>
<input type="submit" value="Add" name="submit"/>
</form>
</div>
<?php
require_once ('define.php');
$name = $_POST['name'];
$size = $_POST['size'];
$desc= $_POST['desc'];
$image = $_FILES['image']['name'];
$image_size = $_FILES['image']['size'];
$image_type = $_FILES ['image']['type'];
if (!empty($name) && !empty($size) && !empty($image) && !empty($desc)) {
if ((($image_type == 'image/gif') || ($image_type == 'image/jpeg') || ($image_type == 'image/pjpeg') || ($image_type == 'image/png'))
&& ($image_size > 0) && ($image_size <= GW_MAXFILESIZE)
) {
if ($_FILES['image']['error'] == 0) {
$target = GW_UPLOADPATH . $image;
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
// Connect to the database
$dbh = new PDO('mysql:host=127.0.0.1;dbname=space_station', 'root', 'root');
// Write the data to the database
$query = "INSERT INTO space_add VALUES (0, :image, :name , :size , :desc)";
$stmt = $dbh->prepare($query);
$result = $stmt->execute(
array(
'image' => $image,
'name' => $name,
'size' => $size,
'desc' => $desc
)
);
if (!$result) {
die('Error querying database.');
}
// Confirm success with the user
echo '<p>Thanks for adding a new find!</p>';
echo '<p><strong>Name:</strong> ' . $name . '<br />';
echo '<p><strong>Size:</strong>' . $size . '<br />';
echo '<strong>Description:</strong> ' . $desc . '<br />';
echo '<p><a href="index.php"><< Back to home page</a></p>';
// Clear the score data to clear the form
//
// $name = "";
// $size = "";
// $desc = "";
// $image = "";
//
//
} else {
//CANT UPLOAD IMAGE ... FIND OUT WHAT IS WRONG
echo '<p class="error">Sorry, there was a problem uploading your image.</p>';
}
}
}
else {
echo '<p class="error">The image must be a GIF, JPEG, or PNG image file no greater than ' . (GW_MAXFILESIZE / 1000000) . ' MB in size.</p>';
}
// Try to delete the temporary screen shot image file
@unlink($_FILES['image']['tmp_name']);
}
else {
echo '<p class="error">Please enter all of the information to add your find.</p>';
}
exit();
?>
</body>
</html><file_sep>/remove_find.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Space Station REMOVE</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
<?php
require ('define.php');
if (isset($_GET['id']) && isset($_GET['desc']) && isset($_GET['name']) && isset($_GET['size']) && isset($_GET['image'])) {
// Grab the score data from the GET
$id = $_GET['id'];
$desc = $_GET['desc'];
$name = $_GET['name'];
$size = $_GET['size'];
$image = $_GET['image'];
}
else if (isset($_POST['id']) && isset($_POST['name']) && isset($_POST['size'])) {
// Grab the score data from the POST
$id = $_POST['id'];
$name = $_POST['name'];
$desc = $_POST['desc'];
}
else {
echo '<p class="error">Sorry, no find was specified for removal.</p>';
}
if (isset($_POST['submit'])) {
if ($_POST['confirm'] == 'Yes') {
// Delete the screen shot image file from the server
@unlink(GW_UPLOADPATH . $image);
// Connect to the database
$dbh = new PDO('mysql:host=127.0.0.1;dbname=space_station', 'root', 'root');
// Delete the score data from the database
$query = "DELETE FROM space_add WHERE id = $id LIMIT 1";
$stmt = $dbh->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
// Confirm success with the user
echo '<p>The find was successfully removed.';
}
else {
echo '<p class="error">The find was not removed.</p>';
}
}
else if (isset($id) && isset($name) && isset($desc) && isset($size)) {
echo '<p>Are you sure you want to delete the following find?</p>';
echo '<p><strong>Name: </strong>' . $name . '<br /> <strong>Desc:</strong>' . $desc . '<br /><strong>Size:</strong>' . $size . '</p>';
echo '<form method="post" action="remove_find.php">';
echo '<input type="radio" name="confirm" value="Yes" /> Yes ';
echo '<input type="radio" name="confirm" value="No" checked="checked" /> No <br />';
echo '<input type="submit" value="Submit" name="submit" />';
echo '<input type="hidden" name="id" value="' . $id . '" />';
echo '<input type="hidden" name="name" value="' . $name . '" />';
echo '<input type="hidden" name="size" value="' . $size . '" />';
echo '</form>';
}
echo '<p><a href="admin.php"><< Back to admin page</a></p>';
exit();
?><file_sep>/email.php
<?php
// link to the database with the stuff selected from the sign up page (all the info (just need the email)
$from = '<EMAIL>';
$to= $email;
$subject = 'Thank You for subscribing to Space Station';
$msg = "Hello $first_name $last_name thank you for subscribing to Space Station.\n" .
"You can now upload you own finds onto this site and have them posted. Have fun!!!"
mail($to, $subject, $msg, 'From:' .$from);
// Don't know what else to do to this ↑↑↑↑↑↑↑↑
?><file_sep>/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Space Station Home</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>
<body>
<div id="nav_bar">
<h1 id="site_name">Space Station-Home</h1>
<h3 class="right"><a href="sign_up.php" class="a">Sign Up</a></h3>
<h3 class="right"><a href="sign_in.php" class="a">Sign In</a></h3>
</div>
<p id="home_sum">Welcome to <span id="underline">Space Station</span>. Here on this site you will see some finds that astronomers or regular people have found in space. You can see the picture of the find ,the size, and a description of it.
There is much of space to be explored and looked at so every day there is something new. The site is free a subscription and it allows you to post any
of your space finds. Visit frequently as new finds are posted all of the time! There is still much of space to be explored. Have fun!!!</p>
<?php
require ('define.php');
$dbh = new PDO('mysql:host=127.0.0.1;dbname=space_station', 'root', 'root');
$query = "SELECT * FROM space_add ORDER BY id DESC ";
$stmt = $dbh->prepare($query);
$stmt->execute();
$id = $stmt->fetchAll();
foreach ($id as $row) {
echo '<div class="info">';
echo '<table>';
// Display the score data
$filepath = GW_UPLOADPATH . $row['image'];
echo '<tr>';
echo '<tr class="fl"><strong>Name:</strong></tr> ' . $row['name'] . '<br />';
echo '<tr class="fl"><strong>Size:</strong></tr> ' . $row['size'] . '<br />';
echo '<tr class="fl"><strong>Description:</strong></tr>' .$row['desc'] .'<br />';
if (is_file($filepath) && filesize($filepath) > 0) {
echo '<td id="info_image"><img src="' . $filepath . '"alt="Find Image" class="image"/></td></tr>';
echo '</table>';
echo '</div>';
}
}
?>
</body>
</html> | 2b5a16dfbbb716e13708f9c1793a1392a0e9a3e5 | [
"PHP"
] | 8 | PHP | pierce-eric-wm/Subscription-Service-Project- | b6d5ef954862435ae168313f730f6f73eb249e75 | 21d8a58d4bd1648bac64de10c74d66fb02f6684e |
refs/heads/master | <repo_name>artfu/data_struc<file_sep>/c/seqlist/seq_list4.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXSIZE 10
typedef struct {
double x;
double y;
double z;
} Node;
typedef struct {
Node* pn;
int len;
} Seqlist;
Seqlist* init(Seqlist* pseq)
{
pseq = (Seqlist*) malloc(sizeof(Seqlist));
pseq->pn = (Node*) malloc(MAXSIZE * sizeof(Node));
pseq->len = 0;
return pseq;
}
Node* getval(Seqlist* pseq, int index)
{
Node* pnode = NULL;
pnode = pseq->pn;
pnode = pnode + index;
return pnode;
}
int getindex(Seqlist* pseq, double a, double b, double c)
{
int index;
Node* ptem = pseq->pn;
for (int i = 0; i < MAXSIZE; i++) {
if ((ptem+i)->x == a && (ptem+i)->y == b && (ptem+i)->z ==c)
index = i;
}
return index;
}
// insert a node to the seqlist
void insert(Seqlist* pseq, int index, Node node)
{
Node* ptem = pseq->pn;
Node* end = ptem + pseq->len;
for (; end > ptem+index; end--) {
*(end+1) = *end;
end--;
}
*(ptem+index) = node;
}
int main(int argc, char** argv)
{
Seqlist* ptr = NULL;
ptr = init(ptr);
Node* ptmp = ptr->pn;
for (int i = 0; i < MAXSIZE-5; i++) {
// use the sturcture way
(*ptmp).x = 1.1 * i;
(*ptmp).y = 2.2 * i;
(*ptmp).z = 3.3 * i;
ptmp++;
}
ptmp = ptr->pn;
for (int i = 0; i < MAXSIZE-5; i++) {
printf("node[%d] = (%.2f, %.2f, %.2f).\n", i, (*ptmp).x, (*ptmp).y,
(*ptmp).z);
ptmp++;
}
printf("\n");
/*****************************************************************/
/**************** Put your code here **************************/
/*****************************************************************/
Node example = {
.x = 8.88,
.y = 88.88,
.z = 888.888,
};
int index = 3;
insert(ptr, index, example);
ptmp = ptr->pn;
for (int i = 0; i < MAXSIZE; i++) {
printf("node[%d] = (%.2f, %.2f, %.2f).\n", i, (*ptmp).x, (*ptmp).y,
(*ptmp).z);
ptmp++;
}
/*****************************************************************/
free(ptr);
return 0;
}
<file_sep>/c/seqlist/seq_list3.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXSIZE 10
typedef struct {
double x;
double y;
double z;
} Node;
typedef struct {
Node* pn;
int len;
} Seqlist;
Seqlist* init(Seqlist* pseq)
{
pseq = (Seqlist*) malloc(sizeof(Seqlist));
pseq->pn = (Node*) malloc(MAXSIZE * sizeof(Node));
pseq->len = 0;
return pseq;
}
// let's get node value by index
Node* getval(Seqlist* pseq, int index)
{
Node* pnode = NULL;
pnode = pseq->pn;
pnode = pnode + index;
return pnode;
}
int main(int argc, char** argv)
{
Seqlist* ptr = NULL;
ptr = init(ptr);
Node* ptmp = ptr->pn;
for (int i = 0; i < MAXSIZE; i++) {
// use the sturcture way
(*ptmp).x = 1.1 * i;
(*ptmp).y = 2.2 * i;
(*ptmp).z = 3.3 * i;
ptmp++;
}
ptmp = ptr->pn;
for (int i = 0; i < MAXSIZE; i++) {
printf("node[%d] = (%.2f, %.2f, %.2f).\n", i, (*ptmp).x, (*ptmp).y,
(*ptmp).z);
ptmp++;
}
printf("\n");
// use getval()
Node* ptarget = getval(ptr, 5);
printf("node[%d] = (%.2f, %.2f, %.2f).\n", 5, ptarget->x, ptarget->y, ptarget->z);
free(ptr);
return 0;
}
<file_sep>/cpp/linklist/list_main.cpp
#include <iostream>
#include "list.hpp"
using namespace std;
int main()
{
List L;
init(L);
cout << L << endl;
create(L);
cout << L << endl;
return 0;
}
<file_sep>/c/seqlist/seq_list0.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// we can store any data in seq, use int value as example
typedef struct {
int data;
} Node;
// what's the minimal info that we need to define a seqlist?
// if we know all the node in the seqlist, we know the seq
// According to the definition of seqlist: it's store in memory one by one, so:
// 1. the begining of seqlist
// 2. the length of seqlist
typedef struct {
Node* pn;
int len;
} Seqlist;
// initial seqlist
// the most natural thought is to allocate memory to store a seq
// how many memory do we need?
// Is it ok to allocate one node? maybe too small
// we ASSUME it is 5 node list
// is it ok to do? let's try it
// we use a function to do so, so we need to decide the return value
// we can use void, just allocate memory
// or we can use pointer to seq as return value
// or we can use boolean value to figure out if it work
// let's try void
// what parameters do we need to use?
// after we initial seq, we need to use it in someway
// maybe pointer to seq is a good choice
// is there other options?
void init(Seqlist* pseq)
{
// goal: allocate 5 node
// return: none
// pseq is pointer of seq
// *pseq is value of seq structure's value
// so (*pseq).pn is a pointer to node
// (*pseq).len is length of seq
// or we can use pointer form
// pseq->pn pseq->len
//pseq->pn = (int*) malloc(5 * sizeof(int)); // <stdlib.h> -- malloc
//pseq->len = 0;
// this is wrong
// pseq = (Seqlist*) malloc(sizeof(Seqlist));
// we got a seqlist, but how to add 5 node?
// we need do it again
// pseq->pn = (Node*) malloc(5 * sizeof(Node));
// pseq->len = 0;
pseq->pn = (Node*) malloc(5 * sizeof(Node));
pseq->len = 0;
// now we have a seq list which has 5 node
// Let's try to use it in the main func
}
int main(int argc, char** argv)
{
// we need a pointer of seqlist
Seqlist* ptr_seqlist = NULL;
// try another way
// Seqlist L;
// we can use if func to decide if it is initial success
// and choose different action
// but I don't do this for now
init(ptr_seqlist);
// init(&L);
// now it's seem we did it
// let's check it
// where is ptr_seqlist point?
// Is length right?
//printf("the len of seq is %d\n", ptr_seqlist->len);
// I got a seqment falut
// what's wrong?
// seqlist is structure
// we allocate memory for node but not for len
// how to fix it
// we should allocate memory for seqlist not just node
// let's return init to figure out
printf("the len of seq is %d\n", ptr_seqlist->len);
free(ptr_seqlist);
// printf("the len of seq is %d\n", L.len);
return 0;
}
<file_sep>/c/linklist/linklist0.c
// the difference between seqlist and linklist is
// the store logic: the former use a block of memory,
// which means we can use pointer++ to find the next one
// the linklist use pointer to connect the next node
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// THE BASIC CONCEPTION IS WRONG, REWRITE
/*
typedef struct {
double x;
double y;
double z;
} Node;
typedef struct {
Node node;
Node* next;
int len;
} Linklist, *PLK;
Linklist* init(Linklist* plk)
{
plk = (*Linklist)malloc(sizeof(Linklist));
plk->next = NULL;
plk->len = -1;
return plk;
}
*/
typedef struct {
int x;
int y;
} DATA;
// the node have two part:
// one is data, another is a link to another, aka a pointer
// But how to count the length of linklist?
typedef struct node {
DATA data;
struct node* next;
} Node, *Linklist;
// initialize a link list
Node* init(Linklist pn)
{
pn = NULL;
return pn;
}
// make a node
// means add Data and return a pointer
Node* make(DATA d)
{
Node* p = (Node*) malloc(sizeof(Node));
p->data = d;
p->next = NULL;
return p;
}
// and insert to the list
// we can use pointer to change value that point to
// rather not pointer itself
// we want to change pointer value, we need a pointer of pointer
// let's try this
void insert(Linklist head, Node* pn)
{
pn->next = head;
head = pn;
}
void pinsert(Linklist* phead, Node** ppn)
{
(*ppn)->next = *phead;
*phead = ppn;
}
int main(int argc, char** argv)
{
Linklist head = init(head);
DATA a;
a.x = 5;
a.y = 6;
Node* pa = make(a);
printf("Now the node pa:%p\n", pa);
insert(head, pa);
printf("Now the head:%p\n", head);
// now the head still at null
// but why?
// do some pointer test of this
// now we konw pointer the difference
pinsert(&head, &pa);
printf("Now the head:%p\n", head);
return 0;
}
<file_sep>/cpp/linklist/list.cpp
#include <iostream>
#include "list.hpp"
using namespace std;
struct node {
ElementType data;
Position next;
};
void init(List &L)
{
L = NULL;
}
void create(List &L)
{
int n;
List p = NULL;
cout << "n = " << endl;
cin >> n;
while (n--) {
p = new Node;
cin >> p->data;
p->next = L;
L = p;
}
}
<file_sep>/c/linklist/1link.c
#include <stdio.h>
#include <stdlib.h>
typedef int Data;
typedef struct node {
Data data;
struct node* next;
} Node, *Link;
int initList(Link L)
{
L = (Node*)malloc(sizeof(Node));
L->next = NULL;
return 0;
}
int getData(Link L, int i, Data* pd)
{
Node* p = L->next;
int j = 1;
for (; p && j > i; j++)
p = p->next;
*pd = p->data;
return 0;
}
Node* locNode(Link L, Data d)
{
Node* pn = L->next;
while (pn && pn->data != d)
pn = pn->next;
return pn;
}
int putNode(Link L, int i, Data d)
{
int j = 1;
Node* pn = L->next;
Node* p = (Node*)malloc(sizeof(Node));
for (; pn && j < i; j++) {
pn = pn->next;
}
p->next = pn->next;
pn->next = p;
p->data = d;
return 0;
}
int rmNode(Link L, int i)
{
Node* pn = L->next;
int j = 1;
for (; pn && j < i; j++)
pn = pn->next;
Node* ptem;
ptem = pn;
pn = pn->next;
free(ptem);
return 0;
}
// add node to head
void creatHead(Link L, int n)
{
L = (Node*)malloc(sizeof(Node));
L->next = NULL;
for (int i = 0; i < n; ++i) {
Node* p = (Node*)malloc(sizeof(Node));
printf("Input the %d node value: ", i);
scanf("%d", &p->data);
p->next = L->next;
L->next = p;
}
}
// add node at end
void creatTail(Link L, int n)
{
L = (Node*) malloc(sizeof(Node));
L->next = NULL;
Node* tail = L;
for (int i = 0; i < n; i++) {
Node* p = (Node*) malloc(sizeof(Node));
printf("Input the %d node value: ", i);
scanf("%d", &p->data);
p->next = NULL;
tail->next = p;
tail = p;
}
}
void printLink(Link L)
{
Node* p = L;
for (; p; p = p->next)
printf("%d ", p->data);
printf("\n");
}
int main(int argc, char* argv[])
{
Node L1;
Node L2;
initList(&L1);
initList(&L2);
creatHead(&L1, 5);
printf("%p", &L1);
Node* p = &L1;
creatTail(&L2, 5);
printLink(&L1);
printLink(&L2);
return 0;
}
<file_sep>/c/seqlist/seq_list6.c
// add if-else func to check condition
// add printf() to look better
// fix pseq->len = -1 to begin
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXSIZE 10
typedef struct {
double x;
double y;
double z;
} Node;
typedef struct {
Node* pn;
int len;
} Seqlist;
Seqlist* init(Seqlist* pseq)
{
pseq = (Seqlist*) malloc(sizeof(Seqlist));
// malloc fail
if (pseq == NULL) {
printf("Unable to malloc.\n");
}
else {
pseq->pn = (Node*) malloc(MAXSIZE * sizeof(Node));
pseq->len = -1;
}
return pseq;
}
Node* getval(Seqlist* pseq, int index)
{
Node* pnode = NULL;
pnode = pseq->pn;
pnode = pnode + index;
return pnode;
}
int getindex(Seqlist* pseq, double a, double b, double c)
{
int index;
Node* ptem = pseq->pn;
for (int i = 0; i < MAXSIZE; i++) {
if ((ptem+i)->x == a && (ptem+i)->y == b && (ptem+i)->z ==c)
index = i;
}
return index;
}
bool insert(Seqlist* pseq, int index, Node node)
{
Node* ptem = pseq->pn;
Node* end = ptem + pseq->len;
for (; end > ptem+index; end--) {
*(end+1) = *end;
end--;
}
*(ptem+index) = node;
pseq->len++;
return true;
}
bool delete(Seqlist* pseq, int index)
{
Node* ptem = pseq->pn;
Node* ptag = ptem+index;
for ( ; ptag < ptem+pseq->len; ptag++) {
*ptag = *(ptag+1);
}
pseq->len--;
return true;
}
int main(int argc, char** argv)
{
Seqlist* ptr = init(ptr);
if (ptr == NULL) {
printf("Unable to initialize list.\n");
}
else {
Node* ptmp = ptr->pn;
for (int i = 0; i < MAXSIZE-4; i++) {
// use the sturcture way
(*ptmp).x = 1.1 * i;
(*ptmp).y = 2.2 * i;
(*ptmp).z = 3.3 * i;
ptmp++;
ptr->len++;
}
printf("Print the Seqlist: \n");
ptmp = ptr->pn;
for (int i = 0; i < MAXSIZE-5; i++) {
printf("node[%d] = (%.2f, %.2f, %.2f).\n", i, (*ptmp).x, (*ptmp).y,
(*ptmp).z);
ptmp++;
}
printf("\n");
/*****************************************************************/
/**************** Put your code here **************************/
/*****************************************************************/
Node example = {
.x = 8.88,
.y = 88.88,
.z = 888.888,
};
int index = 3;
// insert success
printf("After insert a node, print New seqlist:\n");
if (insert(ptr, index, example)) {
ptmp = ptr->pn;
for (int i = 0; i < MAXSIZE-4; i++) {
printf("node[%d] = (%.2f, %.2f, %.2f).\n", i, (*ptmp).x, (*ptmp).y,
(*ptmp).z);
ptmp++;
}
printf("the length is %d now.\n", ptr->len);
}
printf("\n");
// use delete()
// delete success
printf("After delete a node, print New seqlist:\n");
if (delete(ptr, index)) {
ptmp = ptr->pn;
for (int i = 0; i < MAXSIZE-4; i++) {
printf("node[%d] = (%.2f, %.2f, %.2f).\n", i, (*ptmp).x, (*ptmp).y,
(*ptmp).z);
ptmp++;
}
printf("the length is %d now.\n", ptr->len);
}
/*****************************************************************/
free(ptr);
}
return 0;
}
<file_sep>/c/seqlist/seq_list1.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXSIZE 10
// once the miniest program work fine, let's make it better
// use complicate node form, such as three-dimensional coordinates
typedef struct {
double x;
double y;
double z;
} Node;
// Seqlist do not need change much
typedef struct {
Node* pn;
int len;
} Seqlist;
// void is the worst, formal parameters don't affect the main,
// we use void for side effect
// we choose pointer as return value
Seqlist* init(Seqlist* pseq)
{
// use MAXSIZE instead of exact figures
pseq = (Seqlist*) malloc(sizeof(Seqlist));
pseq->pn = (Node*) malloc(MAXSIZE * sizeof(Node));
pseq->len = 0;
return pseq;
}
int main(int argc, char** argv)
{
Seqlist* ptr = NULL;
Seqlist* begin = NULL;
ptr = init(ptr);
begin = ptr;
// test more
printf("the len of seq is %d\n", ptr->len);
// give every node a valid value
for (int i = 0; i < MAXSIZE; i++, ptr->pn++) {
ptr->pn->x = 1.1 * i;
ptr->pn->y = 2.2 * i;
ptr->pn->z = 3.3 * i;
ptr->len++;
}
// return to the begin
ptr = begin;
// print the list
for (int i = 0; i < MAXSIZE; i++, ptr->pn++) {
printf("You got (%f, %f, %f)\n", ptr->pn->x, ptr->pn->y, ptr->pn->z);
}
printf("the len of seq is %d\n", ptr->len);
// where is a mallac there is a free
free(ptr);
return 0;
}
<file_sep>/c/seqlist/move_in_array.c
#include <stdio.h>
int main(int argc, char** argv)
{
int a[10] = {12, 23, 34, 45, 56,};
// print the a
int len1 = sizeof(a) / sizeof(a[0]);
for (int i = 0; i < len1; i++) {
printf("a[%d] is %d\n", i, a[i]);
}
// add '28' to a[2]
// a[2] = 28; // '23' will lost
// one way to do this:
// a[0] = 12
// a[1] = 23
// a[2] = 34
// a[3] = 45
// a[4] = 56
// a[5] = a[4] --> a[5] = 56
// a[4] = a[3] --> a[4] = 45
// a[3] = a[2] --> a[3] = 34
// a[2] = 28
// a[1] a[0] keep as it is
// do this with a loop func
for (int i = 6; i > 2; i--) {
a[i] = a[i-1];
}
// int i = 6 --> 6 = the origin length + 1
// i > 2 --> 2 = index
// for (int i = a.len+1; i > index; i--) {
// a[i] = a[i-1];
// }
// a[index] = val;
}
a[2] = 28;
int len = sizeof(a) / sizeof(a[0]);
for (int i = 0; i < len; i++) {
printf("a[%d] is %d\n", i, a[i]);
}
return 0;
}
<file_sep>/c/linklist/pointer_test.c
#include <stdio.h>
#include <stdlib.h>
void dptr(int* a, int* b)
{
*a = 4131;
*b = 325435;
b = a;
a = NULL;
}
int main(int argc, char** argv)
{
int n = 1314;
int* a = &n;
int* b = (int*) malloc(sizeof(int));
printf("a = %d, b = %d\n", *a, *b);
printf("*a = %p, *b = %p\n", a, b);
printf("\n");
dptr(a, b);
printf("a = %d, b = %d\n", *a, *b);
printf("*a = %p, *b = %p\n", a, b);
return 0;
}
<file_sep>/c/linklist/list_main.c
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
int main(int argc, char** argv)
{
// use MakeEmpty()
List L = NULL;
L = MakeEmpty(L);
printf("L = %p\n", L);
printf("L->Next = %p\n", L->Next);
// use GetEmpty()
struct Node header;
List Lh = &header;
GetEmpty(Lh);
printf("Lh = %p\n", Lh);
printf("Lh->Next = %p\n", Lh->Next);
// use IsEmpty()
printf("isEmpty = %d\n", IsEmpty(L));
// use IsLast()
printf("isLast = %d\n", IsLast(L));
return 0;
}
<file_sep>/c/linklist/2link.c
#include <stdio.h>
#include <stdlib.h>
// rewrite the link list
// too many concept is unclear
typedef struct node {
int data;
struct node* next;
} N, Lk;
// this is invaild
// pointer value change does't effect in main
void headAdd(Lk l, int i)
{
Node* p = (Node*)malloc(sizeof(Node));
Node* head = l;
for (int j = 0; j < i; j++) {
int d;
scanf("%d", &d);
p->data = d;
p->next = head;
head = p;
}
}
int main(int argc, char** argv)
{
Lk a = NULL;
return 0;
}
<file_sep>/c/seqlist/use_pointer.c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int b1[5];
int* b2;
int b3;
} B, *PB;
typedef struct {
int a1;
PB a2;
} A, *PA;
int main(int argc, char** argv)
{
PA pa;
pa = (A*) malloc(sizeof(A));
// pa is a pointer to A
// *pa is struc A
// pointer way
pa->a1 = 5;
printf("pa->a1 is %d\n", pa->a1);
// structure way
(*pa).a1 = 6;
printf("pa->a1 is %d\n", pa->a1);
// something harder but understandable
pa->a2 = (B*) malloc(sizeof(B)); // pa-a2 vs PB pb
pa->a2->b3 = 1314; // same as pa->a1
printf("pa->a2->b3 is %d\n", pa->a2->b3);
pa->a2->b2 = &(pa->a2->b3);
printf("pa->a2->b3 address is %p\n", &(pa->a2->b3));
printf("pa->a2->b2 is %p\n", pa->a2->b2);
printf("pa->a2->b2 value is %d\n", *pa->a2->b2);
pa->a2->b1[0] = 1;
printf("pa->a2->b1[0] is %d\n", pa->a2->b1[0]);
*(pa->a2->b1) = 2;
printf("pa->a2->b1[0] is %d\n", pa->a2->b1[0]);
for (int i = 0; i < 5; i++) {
pa->a2->b1[i] = i * i;
printf("pa->a2->b1[%d] is %d\n", i, pa->a2->b1[i]);
}
printf("\n");
int* ptmp = pa->a2->b1;
for (int i = 0; i < 5; i++) {
*ptmp = 2 *i * i;
printf("pa->a2->b1[%d] is %d\n", i, pa->a2->b1[i]);
ptmp++;
}
return 0;
}
<file_sep>/cpp/linklist/list.hpp
#ifndef _LIST_HPP_
#define _LIST_HPP_
typedef int ElementType;
struct node;
typedef struct node Node;
typedef Node* PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
void init(List &L);
void create(List &L);
#endif
<file_sep>/c/linklist/list.c
#include "list.h"
#include <stdlib.h>
/* */
List
MakeEmpty(List L)
{
L = (List)malloc(sizeof(struct Node));
L->Next = NULL;
return L;
}
/* Compare with MakeEmpty() */
/* Try to understand pointer Formal Parameter */
int
GetEmpty(List L)
{
L = (List)malloc(sizeof(struct Node));
L->Next = NULL;
return 0;
}
/* Return true(1) if L is empty */
int
IsEmpty(List L)
{
return L->Next == NULL;
}
/* Return true if P is the last position in list L */
/* Parameter L is unused in this implementation */
int
IsLast(Position P, List L)
{
return P->Next == NULL;
}
/* Return position of X in L; NULL if not found */
Postion
Find(ElementType X, List L)
{
Postion P;
P = L->Next;
while (P != NULL && P->Element != X)
P = P->Next;
return P;
}
/* Delete first occurrence of X from a list */
/* Assume use of header node */
void
Delete(ElementType X, List L)
{
Position P;
Position TmpCell;
P = FindPrevious(X, L);
if (!IsLast(P, L))
{
/* Assumption of header use */
/* X is found; delete it */
TmpCell = P->Next;
P->Next = TmpCell->Next;
free(TmpCell);
}
}
/* If X is not found, then next field of returned */
/* Position is NULL */
/* Assumes a header */
Position
FindPrevious(ElementType X, List L)
{
Position P;
P = L;
while (P->Next != NULL && P->Next->Element != X)
P = P->Next;
return P;
}
/* Insert (after legal position P) */
/* Header implementation assumed */
/* Parameter L is unused in this implementation */
void
Insert(ElementType X, List L, Position P)
{
Position TmpCell;
TmpCell = malloc(sizeof(struct Node));
if (TmpCell == NULL)
FatalError("Out of space!!!");
TmpCell->Element = X;
TmpCell->Next = P->Next;
P->Next = TmpCell;
}
/* */
void
DeleteList(List L)
{
Position P;
Position Tmp;
/* Header assumed */
P = L->Next;
L->Next = NULL;
while (P != NULL)
{
Tmp = P->Next;
free(P);
P = Tmp;
}
}
/* */
Position
Header(List L)
{
return L;
}
/* */
Position
First(List L)
{
return L->Next;
}
/* */
Position
Advance(Positon P)
{
return P->Next;
}
/* */
ElementType
Retrieve(Position P)
{
return P->Element;
}
<file_sep>/c/seqlist/use_struc.c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int a1;
int a2;
} A;
A* init(A* pa)
{
pa = (A*) malloc(2*sizeof(A));
pa->a1 = 1;
pa->a2 = 2;
return pa;
}
int main(int argc, char** argv)
{
A* ptr_a = NULL;
ptr_a = init(ptr_a);
ptr_a->a1 = 1;
ptr_a->a2 = 2;
printf("%d %d\n", ptr_a->a1, ptr_a->a2);
free(ptr_a);
return 0;
}
| 1229866d2726f5d0540581f73acf730bd14f0628 | [
"C",
"C++"
] | 17 | C | artfu/data_struc | 0ed0110e08e202b4fda594c622f3297ac5ba5c3a | 0bccda78f8a48e4d3dd76d789862eabf56ee7023 |
refs/heads/master | <repo_name>fdosalazar/api-base<file_sep>/app/core/model.go
package core
type Api struct {
Status int `json:"status"`
Message Message `json:"message"`
Time float64 `json:"time"`
Error string `json:"error"`
Data interface{} `json:"data"`
}
type Message struct {
Description string `json:"description"`
Result float64 `json:"result"`
}
<file_sep>/app/bundles/apibasebundle/api_base_mapper.go
package apibasebundle
// KittiesMapper define the base contract for mapper
type ApiBaseMapper interface {
Alive() float64
Env() interface{}
}<file_sep>/app/bundles/apibasebundle/api_base_mapper_sql.go
package apibasebundle
import (
"crypto/md5"
"encoding/hex"
"github.com/jinzhu/gorm"
"github.com/mintance/go-uniqid"
"os"
"strings"
"time"
)
// ParametrosBundleSQL define a SQL mapper
type ApiBaseBundleSQL struct {
db *gorm.DB
}
// NewParametrosSQLMapper instance
func NewApiBaseSQLMapper(db *gorm.DB) *ApiBaseBundleSQL {
return &ApiBaseBundleSQL{
db: db,
}
}
func (m *ApiBaseBundleSQL) Alive() float64 {
var response float64
var s []string
start := time.Now()
for i := 0; i < 1; i++ {
id := uniqid.New(uniqid.Params{"test", true})
//fmt.Printf("%x", id)
data := []byte(id)
h := md5.New()
charid := strings.ToUpper(hex.EncodeToString(h.Sum(data)))
s = append(s, charid)
}
ms := time.Since(start)
response = ms.Seconds()
return response
}
func (m *ApiBaseBundleSQL) Env() interface{} {
x := make(map[string]string)
for _, e := range os.Environ() {
pair := strings.SplitN(e, "=", 2)
x[pair[0]] = pair[1]
}
return x
}
<file_sep>/app/bundles/apibasebundle/api_base_bundle.go
package apibasebundle
import (
"api-base/app/core"
"github.com/jinzhu/gorm"
"net/http"
)
// ParametrosBundle handle kitties resources
type ApiBaseBundle struct {
routes []core.Route
}
// NewParametrosBundle instance
func NewApiBaseBundle(db *gorm.DB) core.Bundle {
apiBaseSQLMapper := NewApiBaseSQLMapper(db)
apiBaseController := NewApiBaseController(apiBaseSQLMapper)
r := []core.Route{
core.Route{
Method: http.MethodGet,
Path: "/alive",
Handler: apiBaseController.Alive,
},
core.Route{
Method: http.MethodGet,
Path: "/env",
Handler: apiBaseController.Env,
},
}
return &ApiBaseBundle{
routes: r,
}
}
// GetRoutes implement interface core.Bundle
func (b *ApiBaseBundle) GetRoutes() []core.Route {
return b.routes
}
<file_sep>/app/core/controller.go
package core
import (
"encoding/json"
"log"
"net/http"
)
// Controller handle all base methods
type Controller struct {
}
// SendJSON marshals v to a json struct and sends appropriate headers to w
func (c *Controller) SendJSON(w http.ResponseWriter, v interface{}, code int) {
w.Header().Add("Content-Type", "application/json")
api := Api{Data: v, Status: code}
w.WriteHeader(code)
if err := json.NewEncoder(w).Encode(api); err != nil {
log.Print(err)
}
}
// GetContent of the request inside given struct
func (c *Controller) GetContent(v interface{}, r *http.Request) error {
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(v)
if err != nil {
return err
}
return nil
}
// HandleError write error on response and return false if there is no error
func (c *Controller) HandleError(err error, w http.ResponseWriter) bool {
if err == nil {
return false
}
msg := map[string]string{
"message": "An error occured",
}
c.SendJSON(w, &msg, http.StatusInternalServerError)
return true
}
<file_sep>/main.go
package main
import (
"api-base/app/bundles/apibasebundle"
"api-base/app/core"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
"github.com/joho/godotenv"
"log"
"net/http"
"os"
)
func main() {
// Aqui se declaran los controladores
initLog()
r := mux.NewRouter()
// Aqui se define el nombre del Api
s := r.PathPrefix("/api-base/").Subrouter()
// Aqui se definen las rutas de los metodos y si son GET o POST
for _, b := range initBundles(nil) {
for _, route := range b.GetRoutes() {
s.HandleFunc(route.Path, route.Handler).Methods(route.Method)
}
}
//Aqui se define el puerto de la Api
http.Handle("/", r)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func loadConfig() *core.Config {
err := godotenv.Load()
if err != nil {
log.Print(".env file not found")
}
c := &core.Config{}
c.Fetch()
return c
}
func initBundles(db *gorm.DB) []core.Bundle {
return []core.Bundle{apibasebundle.NewApiBaseBundle(db)}
}
func initLog() {
f, _ := os.OpenFile(os.Getenv("PATH_LOG")+os.Args[0]+".log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.SetOutput(f)
}
<file_sep>/app/bundles/apibasebundle/controller_api_base.go
package apibasebundle
import (
"api-base/app/core"
"net/http"
//"strconv"
)
// KittiesController struct
type ApiBaseController struct {
core.Controller
abm ApiBaseMapper
}
// NewKittiesController instance
func NewApiBaseController(abm ApiBaseMapper) *ApiBaseController {
return &ApiBaseController{
Controller: core.Controller{},
abm: abm,
}
}
func (c *ApiBaseController) Alive(w http.ResponseWriter, r *http.Request) {
response := c.abm.Alive()
c.SendJSON(w, &response, http.StatusOK)
}
func (c *ApiBaseController) Env(w http.ResponseWriter, r *http.Request) {
response := c.abm.Env()
c.SendJSON(w, &response, http.StatusOK)
}
<file_sep>/app/core/bundle.go
package core
type Bundle interface {
GetRoutes() []Route
}
<file_sep>/app/core/config.go
package core
import "os"
// Config struct
type Config struct {
DBConnection string
DBType string
}
// Fetch from env variables
func (c *Config) Fetch() {
c.DBConnection = os.Getenv("DB_CONNECTION")
c.DBType = os.Getenv("DB_TYPE")
}
| c9f0cc4585170892a1fc7b075441cfbda3c71d00 | [
"Go"
] | 9 | Go | fdosalazar/api-base | 79e17303602e004eca8c6e9b806285fd08fc3857 | 7d7cd31563238ede974da9e4703ace1eadab9041 |
refs/heads/master | <file_sep>import React from 'react'
function EmployeeCard({user}){
let moviesList = user.favoriteMovies.map(movie => <li>{movie}</li>)
return(
<div className='card-box'>
<div className='current-card'>{user.id}/25</div>
<div className='person-info'>
<h2>{user.name.first} {user.name.last}</h2>
<div className='person-info-two'>
<p className='person-details'> <span className='more-person-details'>From: </span>{user.city}, {user.country}</p>
<p className='person-details'> <span className='more-person-details'>Job Title: </span>{user.title}</p>
<p className='person-details'> <span className='more-person-details'>Employer: </span>{user.employer}</p>
</div>
<div className='fav-movies'>
<span className='more-person-details'>Favorite Movies:</span>
<ol className='fav-movie-list'>
{moviesList}
</ol>
</div>
</div>
</div>
)
}
export default EmployeeCard<file_sep>import React, {Component} from 'react'
class Navigation extends Component{
render(){
return(
<div className='buttons-box'>
<button className='change-button' onClick={this.props.decrease}>< Previous</button>
<div className='edit-card-buttons-box'>
<button className='edit-buttons'>Edit</button>
<button className='edit-buttons'>Delete</button>
<button className='edit-buttons'>New</button>
</div>
<button className='change-button' onClick={this.props.increase}> Next ></button>
</div>
)
}
}
export default Navigation<file_sep>import React, { Component } from 'react';
import './reset.css';
import './App.css';
import EmployeeCard from './employeeCard';
import Navigation from './navigation';
import data from './data';
class App extends Component{
constructor(){
super()
this.state ={
data: data,
userNumber: 0
}
}
increasesNum = () => {
if (this.state.userNumber === 24){
this.setState({
userNumber: 0
})
} else {
this.setState({
userNumber: this.state.userNumber + 1
})
}
}
decreasesNum = () => {
if (this.state.userNumber === 0){
this.setState({
userNumber: 24
})
}else {
this.setState({
userNumber: this.state.userNumber - 1
})
}
}
render(){
const {data, userNumber} = this.state
return (
<div className="App">
<header>
<h1 > Home </h1>
</header>
<body>
<div className='content'>
<EmployeeCard user={data[userNumber]}/>
<Navigation increase={this.increasesNum} decrease={this.decreasesNum}/>
</div>
</body>
</div>
)
}
}
export default App;
// constructor(props) {
// super(props);
// this.state = {
// questionsAnswered: 0
// };
// this.handleClick = this.handleClick.bind(this);
// }
// handleClick() {
// this.setState({ questionsAnswered: this.state.questionsAnswered + 1 });
// }
// render() {
// <div className="lead-mentor-container">
// <h1><NAME></h1>
// <h3>{this.state.questionsAnswered}</h3>
// <h3>questions answered today</h3>
// <button onClick={this.handleClick}>Increase Answers</button>
// </div>;
// } | 5fa72a73aa75ed75b63e5f1db337069ad3149401 | [
"JavaScript"
] | 3 | JavaScript | psain1987/Week-3-day4-afternoon | 596da17e9bd51231fb064554670dee808f347d43 | a2c26a94283a60a295bdcd9d31dc3c8ef1a86a78 |
refs/heads/master | <repo_name>nvdnkpr/express-mvc-routes<file_sep>/lib.js
'use strict';
/**
* Create new route for express app.
*/
var Route = function (options, app) {
if (app) this.app = app;
return this.createRoute(options);
};
Route.prototype.createRoute = function(options) {
options
? this.unfoldOptions(options)
: this.throwError('Expected `options`.');
this.isValidOptions(options)
? this.appendToApp(options)
: this.throwError('Expected `url`.');
};
Route.prototype.appendToApp = function(options) {
var method = options.method;
for (var i = options.url.length - 1; i >= 0; i--) {
options.controller
? this.app[method](
options.url[i],
options.middlewares,
options.controller
)
: this.app[method](
options.url[i],
options.middlewares
);
}
};
Route.prototype.throwError = function(msg) {
throw new Error(msg);
};
Route.prototype.unfoldOptions = function(o) {
o.method = o.method && o.method.toLowerCase() || 'get';
o.url = [].concat(o.url);
!o.middlewares && (o.middlewares = []);
};
Route.prototype.isValidOptions = function(options) {
return !!options.url;
};
// Static constructor for CRUD
Route.CRUD = function(options) {
var map = {
create: 'post',
read: 'get',
update: 'put',
del: 'del'
};
var keys = Object.keys(map);
var _options = {};
for (var i = keys.length - 1; i >= 0; i--) {
if (!options.controller[keys[i]]) continue;
_options.url = options.url;
_options.middlewares = options.middlewares;
_options.controller = options.controller[keys[i]];
_options.method = map[keys[i]];
new Route(_options);
}
};
module.exports = function (app) {
Route.prototype.app = app;
return Route;
}; | 6f33a52e23b7fa3666b38fb1820bc69b535246ed | [
"JavaScript"
] | 1 | JavaScript | nvdnkpr/express-mvc-routes | b25b326a409abc5f3c19e12c649ac35f32084f76 | 59ed25aae124955a27cd486fc144a82cf62d0ccb |
refs/heads/master | <file_sep>using System;
namespace TestRepoProject
{
class TestRepo
{
static void Main(string[] args)
{
Console.WriteLine("Hi from GitHub");
}
}
}
| 670dd9f203f83e3b1e455f476c33ec4cdd59556a | [
"C#"
] | 1 | C# | radoslav39/test-Repo | 7361975e9bff282462fbe375c4d58fc759c1fd7e | e0cd000849da67efb3f3cf634338348b738ffef3 |
refs/heads/master | <repo_name>daihenka/NavMate<file_sep>/locale/deDE.lua
local L = Apollo.GetPackage("Gemini:Locale-1.0").tPackage:NewLocale("NavMate", "deDE")
if not L then return end
--[[ Proper Translations ]]--
--[[ Google Translations ]]--
L["WaypointContextMenuTitle"] = "Wegpunkt-Menü"
L["ContextMenu_SetWaypointAsArrow"] = "Stellen wegpunkt als pfeil"
L["ContextMenu_SendWaypointTo"] = "Senden wegpunkt"
L["ContextMenu_RemoveWaypoint"] = "Waypoint entfernen"
L["ContextMenu_RemoveZoneWaypoints"] = "Entfernen sie alle wegpunkte aus dieser zone"
L["ContextMenu_RemoveAllWaypoints"] = "Alle entfernen Wegpunkte"
L["ContextMenu_SaveSessionWaypoint"] = "Speichern sie diesen wegpunkt zwischen sessions"
L["ContextMenu_LockArrow"] = "Sperren pfeil"
L["ContextMenu_UnlockArrow"] = "Entsperren pfeil"
L["ContextMenu_SendWaypointToParty"] = "Senden wegpunkt-gruppe"
L["ContextMenu_SendWaypointToGuild"] = "Senden wegpunkt zu gilde"
L["Server Time"] = "Server-Zeit"
L["Local Time"] = "Ortszeit"
L["Unknown Waypoint"] = "Unbekannt Wegpunkt"
L["Remove All Waypoints"] = "Entfernen Sie alle Wegpunkte"
L["Mission"] = "Mission"
L["Public Event"] = "Öffentliche Veranstaltung"
L["Challenge"] = "Herausforderung"
L["HexGroup"] = "Hex-Gruppe"
L["Nemesis"] = "Nemesis"
L["Group"] = "Gruppe"
L["Raid"] = "Angriff"
L["WarParty"] = "Kriegspartei"
L["Guild"] = "Gilde"
L["Instance"] = "Beispiel"
-- Options Window
L["Options_WaypointSettings"] = "Wegpunkt-Einstellungen"
L["Options_ArrivalDistance"] = "Anreise Distanz"
L["Options_PlayArrivalSound"] = "Sound abspielen, wenn Sie an einem Wegpunkt erreicht"
L["Options_24HourClock"] = "24 Stunden Uhr"
L["Options_LocalTime"] = "Ortszeit"
L["Options_ServerTime"] = "Server-Zeit"
L["Enable"] = "Ermöglichen"
L["Options_InvertArrow"] = "Verwenden Sie die alte Dreh"
L["Options_ArrowHot"] = "Heiß"
L["Options_ArrowWarm"] = "Warm"
L["Options_ArrowCold"] = "Kälte"
L["Options_ArrowSettings"] = "Pfeil-Einstellungen"
L["Options_ClockSettings"] = "Clock-Einstellungen"
L["Options_MapSettings"] = "Mini-Karte & Zone Karteneinstellungen"
L["Options_DotNodeSprite"] = "Verwenden Sie Punkt für Ressourcenknoten"
L["Mining Nodes"] = "Mining-Knoten"
L["Farming Nodes"] = "Farming Knoten"
L["Relic Nodes"] = "Relic Knoten"
L["Survival Nodes"] = "Survival-Knoten"
L["Fishing Nodes"] = "Angeln Knoten" | d6fca20fdb9f4c48d3d5ca08dc80f58eaac85b9c | [
"Lua"
] | 1 | Lua | daihenka/NavMate | 1aa60178063212f181851c8d89678fd3a5008e31 | f86613aceb73dbb2a071d67048a5753126dd38f3 |
refs/heads/master | <repo_name>guoxuanlaiye/crm<file_sep>/crm/admin.py
from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(models.Customer)
admin.site.register(models.Tag)
admin.site.register(models.CustomerFollowUp)
admin.site.register(models.Enrollment)
admin.site.register(models.Course)
admin.site.register(models.ClassList)
admin.site.register(models.CourseRecord)
admin.site.register(models.Branch)
admin.site.register(models.Role)
admin.site.register(models.Pyament)
admin.site.register(models.StudyRecord)
admin.site.register(models.UserProfile)
<file_sep>/git.sh
git init
touch README.md
git add .
git commit -m "1.0"
git remote add origin https://github.com/guoxuanlaiye/crm.git
git push -u origin master
| cdf5db9cc89ad2cccdce60b9b385edb00565ba9a | [
"Python",
"Shell"
] | 2 | Python | guoxuanlaiye/crm | 62fca847ec54e9535221104eab329f41fdbeb5e9 | 5a0602053259cc273deec78fb95681d3ae79767f |
refs/heads/master | <file_sep>var mensagem = document.getElementById('mensagem');
mensagem.addEventListener('keyup', Contador);
var h;
var m;
var s;
var Contador = document.getElementById('Contador');
function Enviar(){
var msg = mensagem.value;
document.getElementById("stilo").innerHTML += "<p>" + mensagem + "</p>";
}
//h=getHours();
//m=getMinutos();
//s+getSeconds();
//document.getElementById('text').innerHTML=h+":"+m+"+"+s;
//setTimeout('time()',
function time(){
var today=new Date;
h=today.getHours();
m=today.getMinutes();
s=today.getSeconds();
document.getElementById('text').innerHTML=h+":"+m+"+"+s;
}
function Contador(){
var quantidade = 140;
var msg = mensagem.value;
var rest = quantidade - msg.length;
Contador.innerHTML = rest;
}
//document.write ("Hoje é " + now.getDay() + "," + now.getDate() + "de" + now.getMonth() + now.getFullYear())
| ac54c416619afae28a138630b162e706d71189e4 | [
"JavaScript"
] | 1 | JavaScript | giselicosta/Twitter | 1b396166d6f4ff7250126f4e7ac43ca8a975906c | f0c644284cdf329eb21c206034c0caf945d1ea68 |
refs/heads/master | <file_sep>(在原有仓库的基础上,加入一些调用sklearn进行尝试的代码,实践,思考)
前言
====
力求每行代码都有注释,重要部分注明公式来源。具体会追求下方这样的代码,学习者可以照着公式看程序,让代码有据可查。

如果时间充沛的话,可能会试着给每一章写一篇博客。先放个博客链接吧:[传送门](http://www.pkudodo.com/)。
##### 注:其中Mnist数据集已转换为csv格式,由于体积为107M超过限制,改为压缩包形式。下载后务必先将Mnist文件内压缩包直接解压。
实现
======
### 第一章 统计学习方法概论:
1. 正则化正则的是什么东西?为什么正则化是有效的?
### 第二章 感知机:
博客:[统计学习方法|感知机原理剖析及实现](http://www.pkudodo.com/2018/11/18/1-4/)
实现:[perceptron/perceptron_dichotomy.py](https://github.com/Dod-o/Statistical-Learning-Method_Code/blob/master/perceptron/perceptron_dichotomy.py)
* 感知机只能做2分类
1. 感知机为什么不能学习到异或函数?
感知机是线性分类模型,且要求数据线性可分;异或数据线性不可分;
### 第三章 K近邻:
博客:[统计学习方法|K近邻原理剖析及实现](http://www.pkudodo.com/2018/11/19/1-2/)
实现:[KNN/KNN.py](https://github.com/Dod-o/Statistical-Learning-Method_Code/blob/master/KNN/KNN.py)
```text
test_num 200
k: 3, algorithm: auto, acc: 0.985, time: 38.499552488327026
k: 5, algorithm: auto, acc: 0.985, time: 34.0736927986145
k: 7, algorithm: auto, acc: 0.985, time: 33.51259231567383
k: 9, algorithm: auto, acc: 0.97, time: 33.39327883720398
k: 11, algorithm: auto, acc: 0.975, time: 33.489667654037476
k: 25, algorithm: auto, acc: 0.97, time: 33.61124324798584
k: 5, algorithm: auto, acc: 0.985, time: 34.13753056526184
k: 5, algorithm: ball_tree, acc: 0.985, time: 30.861292600631714
k: 5, algorithm: kd_tree, acc: 0.985, time: 33.43804955482483
k: 5, algorithm: brute, acc: 0.985, time: 3.819897413253784 ???
为什么brute方法这么快?因为其他算法build tree耗时吗?把测试用例增多?维度太多了?
test_num 6000
k: 3, algorithm: brute, acc: 0.961, time: 13.932093143463135
k: 5, algorithm: brute, acc: 0.9586666666666667, time: 15.558129072189331
k: 7, algorithm: brute, acc: 0.9595, time: 16.31393051147461
k: 9, algorithm: brute, acc: 0.9551666666666667, time: 15.201151847839355
k: 11, algorithm: brute, acc: 0.9561666666666667, time: 14.665371417999268
k: 25, algorithm: brute, acc: 0.9478333333333333, time: 15.074190378189087
k: 5, algorithm: auto, acc: 0.9586666666666667, time: 423.38795590400696
k: 5, algorithm: ball_tree, acc: 0.9586666666666667, time: 331.3267414569855
k: 5, algorithm: kd_tree, acc: 0.9586666666666667, time: 421.28932213783264
k: 5, algorithm: brute, acc: 0.9586666666666667, time: 14.77004075050354
```
以上是对MNIST数据集进行分类的效果。sample的维度很多(784列),这可能是造成基于树的模型变慢的原因。
* k近邻三要素:距离度量,k值选择,决策规则(如,多数表决)
* k值减小,模型变复杂,容易过拟合,如果邻近实例恰好是噪声,预测就会出错;k值增大,模型就会变简单,即使不相关(距离远)的实例,也会对预测影响。
* kd树算法更适用于训练实例数 >> 空间维数 的k近邻搜索. 空间维度太多,搜索效率会下降。
* k近邻的每个特征都会参与距离计算,不相关的属性会对分类结果有很大影响(最近邻算法对此特别敏感)(可以使用交叉验证,为每个属性挑选权重)
1. k值怎么选择? **k一般取较小值(3, 4, 5),使用交叉验证选择最优k值**;
2. k近邻的适用场景?
### 第四章 朴素贝叶斯:
博客:[统计学习方法|朴素贝叶斯原理剖析及实现](http://www.pkudodo.com/2018/11/21/1-3/)
实现:[NaiveBayes/NaiveBayes.py](https://github.com/Dod-o/Statistical-Learning-Method_Code/blob/master/NaiveBayes/NaiveBayes.py)
### 第五章 决策树:
博客:[统计学习方法|决策树原理剖析及实现](http://www.pkudodo.com/2018/11/30/1-5/)
实现:[DecisionTree/DecisionTree.py](https://github.com/Dod-o/Statistical-Learning-Method_Code/blob/master/DecisionTree/DecisionTree.py)
### 第六章 逻辑斯蒂回归与最大熵模型:
博客:逻辑斯蒂回归:[统计学习方法|逻辑斯蒂原理剖析及实现](http://www.pkudodo.com/2018/12/03/1-6/)
博客:最大熵:[统计学习方法|最大熵原理剖析及实现](http://www.pkudodo.com/2018/12/05/1-7/)
实现:逻辑斯蒂回归:[Logistic_and_maximum_entropy_models/logisticRegression.py](https://github.com/Dod-o/Statistical-Learning-Method_Code/blob/master/Logistic_and_maximum_entropy_models/logisticRegression.py)
实现:最大熵:[Logistic_and_maximum_entropy_models/maxEntropy.py](https://github.com/Dod-o/Statistical-Learning-Method_Code/blob/master/Logistic_and_maximum_entropy_models/maxEntropy.py)
### 第七章 支持向量机:
博客:[统计学习方法|支持向量机(SVM)原理剖析及实现](http://www.pkudodo.com/2018/12/16/1-8/)
实现:[SVM/SVM.py](https://github.com/Dod-o/Statistical-Learning-Method_Code/blob/master/SVM/SVM.py)
### 第八章 提升方法:
实现:[AdaBoost/AdaBoost.py](https://github.com/Dod-o/Statistical-Learning-Method_Code/blob/master/AdaBoost/AdaBoost.py)
### 第九章 EM算法及其推广:
实现:[EM/EM.py](https://github.com/Dod-o/Statistical-Learning-Method_Code/blob/master/EM/EM.py)
### 第十章 隐马尔可夫模型:
实现:[HMM/HMM.py](https://github.com/Dod-o/Statistical-Learning-Method_Code/blob/master/HMM/HMM.py)
联系
======
项目未来短期内不再更新,如有疑问欢迎使用issue,也可添加微信或邮件联系。
此外如果有需要**MSRA**实习内推的同学,欢迎骚扰。
**Wechat:** lvtengchao(备注“blog-学校/单位-姓名”)
**Email:** <EMAIL>
<file_sep>"""
load time 22.65605401992798
train time 8.435207605361938
accuracy rate is: 0.8127
"""
from sklearn.linear_model import Perceptron
import numpy as np
import time
def loadData(fileName):
'''
加载Mnist数据集
:param fileName:要加载的数据集路径
:return: list形式的数据集及标记
'''
print('start to read data')
# 存放数据及标记的list
dataArr = []; labelArr = []
# 打开文件
fr = open(fileName, 'r')
# 将文件按行读取
for line in fr.readlines():
# 对每一行数据按切割福','进行切割,返回字段列表
curLine = line.strip().split(',')
# Mnsit有0-9是个标记,由于是二分类任务,所以将>=5的作为1,<5为-1
if int(curLine[0]) >= 5:
labelArr.append(1)
else:
labelArr.append(-1)
#存放标记
#[int(num) for num in curLine[1:]] -> 遍历每一行中除了以第一哥元素(标记)外将所有元素转换成int类型
#[int(num)/255 for num in curLine[1:]] -> 将所有数据除255归一化(非必须步骤,可以不归一化)
dataArr.append([int(num)/255 for num in curLine[1:]])
#返回data和label
return dataArr, labelArr
if __name__ == '__main__':
start = time.time()
trainData, trainLabel = loadData('../Mnist/mnist_train.csv')
testData, testLabel = loadData('../Mnist/mnist_test.csv')
print('load time', time.time() - start)
start = time.time()
clf = Perceptron(max_iter=30)
clf.fit(np.array(trainData), np.array(trainLabel))
acc = clf.score(np.array(testData), np.array(testLabel))
print('train time', time.time() - start)
print('accuracy rate is:', acc)
<file_sep>"""
以下数据根据testData的前200条数据进行测试得到
test_num 200
k: 3, algorithm: auto, acc: 0.985, time: 38.499552488327026
k: 5, algorithm: auto, acc: 0.985, time: 34.0736927986145
k: 7, algorithm: auto, acc: 0.985, time: 33.51259231567383
k: 9, algorithm: auto, acc: 0.97, time: 33.39327883720398
k: 11, algorithm: auto, acc: 0.975, time: 33.489667654037476
k: 25, algorithm: auto, acc: 0.97, time: 33.61124324798584
k: 5, algorithm: auto, acc: 0.985, time: 34.13753056526184
k: 5, algorithm: ball_tree, acc: 0.985, time: 30.861292600631714
k: 5, algorithm: kd_tree, acc: 0.985, time: 33.43804955482483
k: 5, algorithm: brute, acc: 0.985, time: 3.819897413253784 ???
为什么brute方法这么快?因为其他算法build tree耗时吗?把测试用例增多?维度太多了?
test_num 6000
k: 3, algorithm: brute, acc: 0.961, time: 13.932093143463135
k: 5, algorithm: brute, acc: 0.9586666666666667, time: 15.558129072189331
k: 7, algorithm: brute, acc: 0.9595, time: 16.31393051147461
k: 9, algorithm: brute, acc: 0.9551666666666667, time: 15.201151847839355
k: 11, algorithm: brute, acc: 0.9561666666666667, time: 14.665371417999268
k: 25, algorithm: brute, acc: 0.9478333333333333, time: 15.074190378189087
k: 5, algorithm: auto, acc: 0.9586666666666667, time: 423.38795590400696
k: 5, algorithm: ball_tree, acc: 0.9586666666666667, time: 331.3267414569855
k: 5, algorithm: kd_tree, acc: 0.9586666666666667, time: 421.28932213783264
k: 5, algorithm: brute, acc: 0.9586666666666667, time: 14.77004075050354
"""
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
import time
def loadData(fileName):
'''
加载文件
:param fileName:要加载的文件路径
:return: 数据集和标签集
'''
print('start read file')
dataArr = []; labelArr = []
fr = open(fileName)
for line in fr.readlines():
curLine = line.strip().split(',')
dataArr.append([int(num) for num in curLine[1:]])
labelArr.append(int(curLine[0]))
return dataArr, labelArr
if __name__ == '__main__':
trainDataArr, trainLabelArr = loadData('../Mnist/mnist_train.csv')
testDataArr, testLabelArr = loadData('../Mnist/mnist_test.csv')
test_num = 6000 # k近邻test要便利整个训练集,非常慢,所以只测200条
print('test_num', test_num)
# 交叉验证
# 不同的k值对时间和准确率的影响
k_values = [3, 5, 7, 9, 11, 25]
for k in k_values:
start = time.time()
neigh = KNeighborsClassifier(n_neighbors=k, algorithm='brute')
neigh.fit(np.array(trainDataArr), np.array(trainLabelArr))
acc = neigh.score(np.array(testDataArr[:test_num]), np.array(testLabelArr[:test_num]))
print(f'k: {k}, algorithm: {neigh.algorithm}, acc: {acc}, time: {time.time()-start}')
print()
k = 5
# 不同的algorithm对时间和准确率的影响
algs = ['auto', 'ball_tree', 'kd_tree', 'brute']
for a in algs:
start = time.time()
neigh = KNeighborsClassifier(n_neighbors=k, algorithm=a)
neigh.fit(np.array(trainDataArr), np.array(trainLabelArr))
acc = neigh.score(np.array(testDataArr[:test_num]), np.array(testLabelArr[:test_num]))
print(f'k: {k}, algorithm: {a}, acc: {acc}, time: {time.time()-start}')
| b8dca1e77a9534269b594a08fc2b26e8504c642b | [
"Markdown",
"Python"
] | 3 | Markdown | llgithubll/Statistical-Learning-Method_Code | d238da3f76eb70ba83ccdae7710e3824f6809a0e | 3a9446623a023319f921057d842044276cff658b |
refs/heads/main | <file_sep>import "./App.css";
function App() {
const handleSubmit = e=>{
e.preventDefault();
console.log(e);
}
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input type='email'
placeholder="Enter Username"
name="uname"
required>
</input>
<input type="password"
placeholder="Enter Password"
name="pswd"
required>
</input>
<button type='submit'>Login</button>
</form>
</div>
);
}
export default App;
| cf4ceeae997d4e942b05a1e1a6b7a99b9c90b74c | [
"JavaScript"
] | 1 | JavaScript | BitNeel/react-login-page | 5beac7b3b66cdf104482ba567810a862a9c018f6 | bd2ae1f1fc051f7f69c4bb555efddffe55fc46b8 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class IntroSequence : MonoBehaviour
{
[SerializeField]
private GameObject titleAnim;
private Animator anim;
private bool flag;
// Start is called before the first frame update
void Start()
{
anim = titleAnim.GetComponent<Animator>();
//animation = anim.
//anim.Play();
flag = false;
}
// Update is called once per frame
void Update()
{
if(anim.GetCurrentAnimatorStateInfo(0).normalizedTime >= 1) {
SceneManager.LoadScene("MainMenu");
}
/*if(flag == true) {
}*/
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move_3 : MonoBehaviour
{
private Rigidbody2D rb;
public int simbolo;
public int simbolo2;
// Start is called before the first frame update
void Start()
{
if (Random.Range(-1f, 1f) > 0 || Random.Range(-1f, 1f) == 0)
{
simbolo = 1;
}
else
{
simbolo = -1;
}
if (Random.Range(-1f, 1f) > 0 || Random.Range(-1f, 1f) == 0)
{
simbolo2 = 1;
}
else
{
simbolo2 = -1;
}
rb = GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(simbolo * 10, simbolo2 * 10);
}
// Update is called once per frame
void Update()
{
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camera : MonoBehaviour
{
public player user;
public bool isFollowing;
public float wOffset;
// Start is called before the first frame update
void Start()
{
user = FindObjectOfType<player>();
}
// Update is called once per frame
void Update()
{
gameObject.transform.position = new Vector3(user.transform.position.x, user.transform.position.y, -10f);
}
public void reassign(){
user = FindObjectOfType<player>();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlackHoleEffects : MonoBehaviour
{
[SerializeField]
private GameObject center;
[SerializeField]
private GameObject player;
private Rigidbody2D rb;
private Rigidbody2D rot;
private Vector2 centerPos;
public float speed;
public bool isInside;
// Start is called before the first frame update
void Start()
{
rb = player.GetComponent<Rigidbody2D>();
rot = center.GetComponent<Rigidbody2D>();
centerPos = center.transform.position;
isInside = false;
}
// Update is called once per frame
void FixedUpdate()
{
rot.rotation += 0.5f;
if(isInside) {
Vector2 newPos = player.transform.position;
Vector2 difference = (newPos - centerPos)*-1;
difference.Normalize();
rb.velocity =difference*speed*Time.deltaTime;
}
}
void OnTriggerEnter2D(Collider2D col) {
if(col.tag=="Player"){
isInside = true;
}
}
void OnTriggerExit2D(Collider2D col) {
if(col.tag=="Player"){
isInside = false;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PauseManager : MonoBehaviour
{
public static PauseManager instance;
public Animator pp;
public GameObject pausePanel;
private bool enpausa;
// Start is called before the first frame update
void Awake() {
if(instance == null) {
instance = this;
}
}
void Start() {
pausePanel.SetActive(false);
enpausa = false;
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Escape)) {
if(enpausa == false) {
pausePanel.SetActive(true);
bool cond = true;
pp.SetBool("Pauser", cond);
//Time.timeScale = 1;
enpausa = true;
}
else if(enpausa == true) {
pausePanel.SetActive(false);
bool cond = false;
pp.SetBool("Pauser", cond);
//Time.timeScale = 1;
enpausa = false;
}
}
}
public void resumeSelected() {
pausePanel.SetActive(false);
bool cond = false;
pp.SetBool("Pauser", cond);
//Time.timeScale = 1;
enpausa = false;
}
public void restartSelected() {
SceneManager.LoadScene("Main_Scene");
}
public void quitSelected() {
SceneManager.LoadScene("MainMenu");
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player : MonoBehaviour
{
public HealtPlayer healtPlayer;
public player rye;
public Animator animator;
public Rigidbody2D rigidbody_player;
public float maxSpeed = 10f;
public float acceleration = 10f;
public int direction = 0;
public bool has = false;
public GameObject star;
private int numberStars = 0;
public GameObject hitbox;
public bool death = false;
private int counter;
public GameObject gameOverp;
// Start is called before the first frame update
void Start()
{
counter = 1;
gameOverp.SetActive(false);
for (int i = 0; i < 7; i++)
{
Instantiate(star, new Vector3(Random.Range(-15, 190), Random.Range(-9,80), 0), Quaternion.identity);
Debug.Log("Instantiated Star");
}
Instantiate(hitbox, new Vector3(58, 61, 0), Quaternion.identity);
Instantiate(hitbox, new Vector3(72, 62, 0), Quaternion.identity);
Instantiate(hitbox, new Vector3(80, 57, 0), Quaternion.identity);
Instantiate(hitbox, new Vector3(90, 51, 0), Quaternion.identity);
Instantiate(hitbox, new Vector3(91, 42, 0), Quaternion.identity);
Instantiate(hitbox, new Vector3(107, 39, 0), Quaternion.identity);
Instantiate(hitbox, new Vector3(111, 49, 0), Quaternion.identity);
rigidbody_player = GetComponent<Rigidbody2D>();
rigidbody_player.velocity = new Vector2(0.0f, 0.0f);
// healtPlayer = FindObjectOfType<HealtPlayer>();
rigidbody_player = GetComponent<Rigidbody2D>();
rigidbody_player.velocity = new Vector2(0.0f, 0.0f);
}
// Update is called once per frame
void Update()
{
/*
if(GameManager.instance.hc.playerHealth < 1){
death = true;
animator.SetBool("Death", death);
}
*/
if(Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)){
direction = 1;
animator.SetInteger("Direction", direction);
}
if(Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)){
direction = 4;
animator.SetInteger("Direction", direction);
}
if(Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)){
direction = 3;
animator.SetInteger("Direction", direction);
}
if(Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)){
direction = 2;
animator.SetInteger("Direction", direction);
}
if(rigidbody_player.velocity.magnitude>maxSpeed){
rigidbody_player.velocity = rigidbody_player.velocity.normalized*maxSpeed;
}
float horizontal = Input.GetAxis("Horizontal") * acceleration * Time.deltaTime;
float vertical = Input.GetAxis("Vertical") * acceleration * Time.deltaTime;
rigidbody_player.AddForce(new Vector2(horizontal, vertical), ForceMode2D.Impulse);
}
private void OnCollisionEnter2D(Collision2D other) {
if(other.collider.gameObject.tag == "Star" && (has == false)){
has = true;
animator.SetBool("has_star", has);
Destroy(other.collider.gameObject, 0.0f);
numberStars++;
}
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == "BH") {
counter -= 1;
if(counter == 0) {
death = true;
gameOverp.SetActive(true);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KillPlayer : MonoBehaviour
{
public HealtPlayer instance;
public int golpe;
// Start is called before the first frame update
void Start()
{
instance = FindObjectOfType<HealtPlayer>();
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Player")
{
instance.playerHealth -= golpe;
instance.Vergazo();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealtPlayer : MonoBehaviour
{
public int playerHealth;
public bool GameOver;
// Start is called before the first frame update
void Start()
{
GameOver = false;
playerHealth = 2;
}
public void Vergazo()
{
if (playerHealth == 1)
{
PlayHit();
}
if(playerHealth <= 0)
{
PlayDeath();
}
}
void PlayDeath()
{
GameOver = true;
Debug.Log("Death");
}
void PlayHit()
{
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Alienbehavoir : MonoBehaviour
{
[SerializeField]
private GameObject center;
[SerializeField]
private GameObject player;
private Rigidbody2D rb;
private Vector2 centerPos;
public float speed;
public float speedOriginal;
public float speedPersuit;
// Start is called before the first frame update
void Start()
{
rb = player.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate()
{
centerPos = center.transform.position;
Vector2 newPos = player.transform.position;
Vector2 difference = (newPos - centerPos)*-1;
difference.Normalize();
rb.velocity = difference*speed*Time.deltaTime;
}
/// <summary>
/// OnTriggerEnter is called when the Collider other enters the trigger.
/// </summary>
/// <param name="other">The other Collider involved in this collision.</param>
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag=="Player"){
speed = speedPersuit;
}
}
void OnTriggerExit2D(Collider2D other) {
if(other.tag=="Player"){
speed = speedOriginal;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Star_animator : MonoBehaviour
{
// Start is called before the first frame update
public float maxSpeed = 10f;
public float acceleration = 10f;
public Animator animator;
public Rigidbody2D rb;
public bool exists = false;
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(0.0f, 0.0f);
}
// Update is called once per frame
void Update()
{
if(rb.velocity.magnitude>maxSpeed){
rb.velocity=rb.velocity.normalized*maxSpeed;
}
float horizontal = Input.GetAxis("Horizontal") * acceleration * Time.deltaTime;
float vertical = Input.GetAxis("Vertical") * acceleration * Time.deltaTime;
rb.AddForce(new Vector2(horizontal, vertical), ForceMode2D.Impulse);
}
/*
private void OnCollisionEnter(Collision other) {
exists = true;
//animator.SetBool("Existence", exists);
}
*/
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CenterEffects : MonoBehaviour
{
[SerializeField]
private GameObject center;
[SerializeField]
private GameObject particles;
public bool gameOver;
// Start is called before the first frame update
void Start()
{
gameOver = false;
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D col) {
if(col.gameObject.tag == "Player") {
Debug.Log("Entering collision");
GameObject part = Instantiate(particles,col.gameObject.transform.position,Quaternion.identity);
Destroy(col.gameObject);
Destroy(part,1f);
gameOver = true;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class GameManager : MonoBehaviour
{
public static GameManager instance;
public CinemachineVirtualCamera vc;
public HealtPlayer hc;
public player play;
public camera cam;
// Start is called before the first frame update
void Awake()
{
if(instance == null) {
instance = this;
}
}
// Update is called once per frame
void Update()
{
}
public void updateAnimation(){
play.has = false;
play.animator.SetBool("has_star", false);
Debug.Log("Has is " + play.has);
Debug.Log("Animator is " + false);
}
public void reassign(){
//vc.Follow = FindObjectOfType<Star_animator>().transform;
Star_animator a = FindObjectOfType<Star_animator>();
Debug.Log(a.gameObject.name);
vc.Follow = a.gameObject.transform;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tintileo : MonoBehaviour
{
public float trans;
public bool again;
// Start is called before the first frame update
void Start(){
gameObject.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f, trans);
}
// Update is called once per frame
void FixedUpdate()
{
if(trans >= 1f){
again=true;
}else if(trans <= 0f){
again=!again;
}
if(again){
gameObject.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f, trans -= 0.01f);
}else if(!again){
gameObject.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f, trans += 0.01f);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine.EventSystems;
public class MenuManager : MonoBehaviour, IPointerClickHandler
{
public static MenuManager instance;
public GameObject MenuPanel;
void Awake() {
if(instance == null) {
instance = this;
}
}
public void OnPointerClick(PointerEventData eventData) {
// OnClick code goes here
}
void Start() {
}
void Update() {
}
public void playSelected() {
SceneManager.LoadScene("Cutscene1");
}
public void quitSelected() {
Debug.Log("Saliendo del juego");
Application.Quit();
}
}
| 55868c584d535e49beddc113ca5830ce63536652 | [
"C#"
] | 14 | C# | LoboAnimae/GGJ20 | 90a5914b4e70c62a034a362f3aa2e6a9f3e83081 | 337ed2b02575663299d6dbc40f753c215ed62aeb |
refs/heads/master | <file_sep>using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Domainlayer;
namespace ApplicationLayer
{
public class ImportController
{
string[] text;
string[] orderItems;
string[] sampleTypeArray;
List<string> sampleTypeList;
OrderRepository orderRepo;
IDictionary<int, Order> orders;
public void ReadLines()
{
string[] text = File.ReadAllLines("Orders.txt");
}
public void RegisterOrders()
{
orders = orderRepo.GetOrders();
ReadLines();
foreach (string item in text)
{
orderItems = item.Split(';');
if (!orders.ContainsKey(Convert.ToInt32(orderItems[0])))
{
sampleTypeArray = orderItems[7].Split(',');
sampleTypeList = ConvertArrayToList(sampleTypeArray);
Order order = new Order(Convert.ToInt32(orderItems[0]), orderItems[1], orderItems[2], Convert.ToInt32(orderItems[3]), orderItems[4], orderItems[5], Convert.ToInt32(orderItems[6]), orderItems[7], sampleTypeList);
orderRepo.AddOrder(order);
}
}
}
public List<string> ConvertArrayToList(string[] c)
{
List<string> ListConvert = new List<string>();
foreach (string item in c)
{
ListConvert.Add(item);
}
return ListConvert;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Domainlayer
{
public class Order
{
public int OrderId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Zip { get; set; }
public string City { get; set; }
public string Country { get; set; }
public int PhoneNumber { get; set; }
public string Email { get; set; }
public List<string> SampleType { get; set; }
public DateTime TimeStamp { get; set; }
public Order()
{
}
public Order(int orderId, string firstName, string lastName, int zip, string city, string country, int phoneNumber, string email, List<string> sampleType)
{
OrderId = orderId;
FirstName = firstName;
LastName = lastName;
Zip = zip;
City = city;
Country = country;
PhoneNumber = phoneNumber;
Email = email;
SampleType = sampleType;
TimeStamp = DateTime.Now;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Domainlayer;
namespace ApplicationLayer
{
public class Controller
{
private DBController dbController;
private ImportController iController;
public bool programStillRunning = true;
public void ExportOrder(Order order)
{
dbController.SaveOrder(order);
}
public void RefreshOrders()
{
Thread thread = new Thread(iController.RegisterOrders);
do
{
Thread.Sleep(5000);
thread.Start();
}
while (programStillRunning);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Domainlayer;
namespace ApplicationLayer
{
public class OrderRepository
{
private Dictionary<int, Order> orders = new Dictionary<int, Order>();
public void AddOrder(Order o)
{
orders.Add(o.OrderId, o);
}
public void RemoveOrder(Order o)
{
orders.Remove(o.OrderId);
}
public IDictionary<int, Order> GetOrders()
{
return orders;
}
}
}
<file_sep>using Domainlayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ApplicationLayer
{
class Program
{
static void Main(string[] args)
{
//DBController TestDB = new DBController();
//Order TestOrder = new Order();
//TestOrder.City = "Glostrup";
//TestOrder.Country = "Danmark";
//TestOrder.FirstName = "Asbjørn";
//TestOrder.LastName = "Larsen";
//TestOrder.OrderId = 54;
//TestOrder.PhoneNumber = 28121553;
//TestOrder.Zip = 2600;
//TestOrder.Email = "<EMAIL>";
//TestDB.SaveOrder(TestOrder);
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Domainlayer;
using System.IO;
namespace ImportControllerUnitTest
{
[TestClass]
public class ErrorLogsTest
{
[TestMethod]
public void TestMethod1()
{
string actualString;
Errors errorsTest = new Errors();
string expectedString = "THERE ARE OVER 9000 ERRORS!";
errorsTest.SaveErrorLog(expectedString);
actualString = File.ReadAllText("ErrorLog.txt");
Assert.AreEqual(expectedString, actualString);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Domainlayer
{
public class FabricSample
{
public int FabricSampleNumber { get; set; }
public int Quantity { get; set; }
public FabricSample(int fabricSampleNumber, int quantity)
{
FabricSampleNumber = fabricSampleNumber;
Quantity = quantity;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Domainlayer;
namespace ApplicationLayer
{
public class FabricSampleRepository
{
private List<FabricSample> fabricSamples = new List<FabricSample>();
public void AddFabricSample(FabricSample sample)
{
fabricSamples.Add(sample);
}
public void RemoveFabricSample(FabricSample sample)
{
fabricSamples.Remove(sample);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Domainlayer;
namespace ApplicationLayer
{
public class DBController
{
private Controller controller = new Controller();
private static string connectionstring =
"Server = den1.mssql8.gear.host; Database = uniggardin; User Id = uniggardin; Password = <PASSWORD>";
public void SaveOrder(Order order)
{
using (SqlConnection con = new SqlConnection(connectionstring))
{
try
{
con.Open();
SqlCommand cmd1 = new SqlCommand("spSaveOrdersS", con);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add(new SqlParameter("@Customer_FirstName", order.FirstName));
cmd1.Parameters.Add(new SqlParameter("@Customer_SurName", order.LastName));
cmd1.Parameters.Add(new SqlParameter("@Country", order.Country));
cmd1.Parameters.Add(new SqlParameter("@Customer_Phone", order.PhoneNumber));
cmd1.Parameters.Add(new SqlParameter("@Customer_Mail", order.Email));
cmd1.Parameters.Add(new SqlParameter("@ZIP", order.Zip));
cmd1.Parameters.Add(new SqlParameter("@City", order.City));
cmd1.Parameters.Add(new SqlParameter("@Order_Date", DateTime.Now));
cmd1.Parameters.Add(new SqlParameter("@Order_Type", order.SampleType));
cmd1.ExecuteNonQuery();
}
catch(SqlException e)
{
Console.WriteLine("Shiiiit" + e);
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Domainlayer
{
public class Errors
{
public void SaveErrorLog(string message)
{
using (StreamWriter sw = new StreamWriter("ErrorLog.txt"))
sw.WriteLine(DateTime.Now + "\n" + message + "\n///\n///\n///\n");
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ApplicationLayer;
using EksamensProjektUnigGardin;
using System.Collections.Generic;
using System.Threading;
namespace ImportControllerUnitTest
{
[TestClass]
public class ImportControllerTest
{
[TestMethod]
public void ImportReaderTest1()
{
string[] TestArray = { "hello", "goddag", "Nice" };
ImportController ICT = new ImportController();
List<string> TestList = ICT.ConvertArrayToList(TestArray);
Assert.AreEqual(TestList[0], TestArray[0]);
}
[TestMethod]
public void ImportReaderTest2()
{
string[] TestArray = { "hello", "goddag", "Nice" };
ImportController ICT = new ImportController();
List<string> TestList = ICT.ConvertArrayToList(TestArray);
Assert.AreEqual(TestList[1], TestArray[1]);
}
[TestMethod]
public void ImportReaderTest3()
{
string[] TestArray = { "hello", "goddag", "Nice" };
ImportController ICT = new ImportController();
List<string> TestList = ICT.ConvertArrayToList(TestArray);
Assert.AreEqual(TestList[2], TestArray[2]);
}
}
}
| 68b69bdf5e908deaf3c732293917bfcb28b9b329 | [
"C#"
] | 11 | C# | asbj2903/EksamensProjektUnigGardin | df85f0a4f7d2c88d757299ee1508012d8bd5b2f7 | ea51275a2ab4d5702700a4f2aef0ceec846c597b |
refs/heads/master | <file_sep><?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">
<parent>
<artifactId>bigpackage</artifactId>
<groupId>com.fanboy</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>bigpackage-springboot</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.alibaba</groupId>-->
<!-- <artifactId>easyexcel</artifactId>-->
<!-- <version>2.1.6</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.12.1</version>
</dependency>
</dependencies>
<!-- 将工程打成jar包所需要的插件 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!--打包的时候 支不支持把开发者工具打包到里面,是有风险的-->
<configuration>
<excludeDevtools>false</excludeDevtools>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>package com.funboy.初级.数组;
import org.junit.Test;
/**
* @Author: 王帆
* @CreateTime: 2018-11-21 16:04
* @Description: 给定一个整数数组,判断是否存在重复元素。 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
* 输入: [1,2,3,1]
* 输出: true
* <p>
* 输入: [1,2,3,4]
* 输出: false
*/
public class 存在重复 {
@Test
public void go() {
boolean b = containsDuplicate(new int[]{7, 6, 1, 5, 4, 1});
System.out.println(b);
}
public boolean containsDuplicate(int[] nums) {
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] == nums[i]) {
return true;
}
}
}
return false;
}
public boolean containsDuplicate1(int[] nums) {
for (int i = 1; i < nums.length; i++) {
for (int j = i - 1; j >= 0; j--) {
if (nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
}
<file_sep>package com.funboy.中级.链表;
/**
* @ClassName 两数相加
* @Description 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
* <p>
* 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
* <p>
* 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
* <p>
* 示例:
* <p>
* 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
* 输出:7 -> 0 -> 8
* 原因:342 + 465 = 807
* <p>
* 作者:力扣 (LeetCode)
* 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-medium/xvw73v/
* 来源:力扣(LeetCode)
* 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
* @Author 王帆
* @Date 2020/10/20 11:57
* @Version 1.0
*/
public class 两数相加 {
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int num = 0;
ListNode pre = new ListNode(0);
ListNode current = new ListNode();
pre.next = current;
do {
int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + num;
num = sum / 10;
sum = sum % 10;
current.val = sum;
l1 = (l1 == null ? l1 : l1.next);
l2 = (l2 == null ? l2 : l2.next);
if (l1 != null || l2 != null || num != 0) {
current.next = new ListNode(0);
current = current.next;
}
} while (l1 != null || l2 != null || num != 0);
return pre.next;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
l1.next = new ListNode(2);
ListNode l2 = new ListNode(3);
l2.next = new ListNode(4);
ListNode x = new 两数相加().addTwoNumbers(l1, l2);
while (x != null) {
System.out.println(x.val);
x = x.next;
}
}
}
<file_sep>package com.umetrip.statistic.excel;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import java.io.FileOutputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* @ClassName XmlReader
* @Description TODO
* @Author 王帆
* @Date 2020/1/22 16:36
* @Version 1.0
*/
public class XmlReader {
static String url = "http://10.5.144.42:8080/cat/r/e?op=history&domain=UmeSMSServer&ip=All&date=20190101&reportType=month&step=1&type=UmeSMSServer.SMSSend.source&ip=All&forceDownload=xml";
public String httpGet(String url) throws Exception {
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder.get().url(url).build();
OkHttpClient client = new OkHttpClient();
Response response = client.newBuilder().callTimeout(99999L, TimeUnit.SECONDS).build().newCall(request).execute();
ResponseBody body = response.body();
String string = body.string();
return string;
}
@Test
public void testLocalDate() {
for (int i = 0; i < 12; i++) {
System.out.println();
}
}
public static void main(String[] args) throws Exception {
//
// String str1 = "http://10.5.144.42:8080/cat/r/e?op=history&domain=UmeSMSServer&ip=All&date=";
// String str2 = "&reportType=month&step=-1&type=&ip=All&forceDownload=xml";
List<String> urlList = new ArrayList<>();
// for (int i = 0; i < 12; i++) {
// urlList.add(str1 + LocalDate.of(2019, 02, 01).plusMonths(i).toString().replace("-", "") + str2);
// }
String str3 = "http://10.5.144.42:8080/cat/r/e?op=history&domain=UmeSMSServer&date=20200311&ip=All&reportType=day&type=UmeSMSServer.SMSRequest.source&sort=total&startDate=20200311&endDate=20200312&forceDownload=xml";
urlList.add(str3);
HashMap<String, HashMap<String, Object>> data = new HashMap<>();
HashSet<String> uniqueKey = new HashSet<>();
XmlReader reader = new XmlReader();
for (String url : urlList) {
String s = reader.httpGet(url);
int i = url.indexOf("&date=");
String date = url.substring(i + 6, i + 14);
date = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyyMMdd")).minusMonths(1).toString().replaceAll("-", "");
HashMap<String, Object> monthData = new HashMap<>();
data.put(date, monthData);
Element body = Jsoup.parse(s).body();
Elements eles = body.getElementsByAttributeValue("ip", "All");
for (Element ele : eles) {
Element source = ele.getElementById("UmeSMSServer.SMSSend.source");
Elements names = source.getElementsByTag("name");
for (Element element : names) {
String id = element.attr("id");
monthData.put(id, Long.parseLong(element.attr("totalcount")));
uniqueKey.add(id);
}
}
}
//写excel
String path = "D://ttest1.xlsx";
// String[] headList = new String[uniqueKey.size()];
//行标题
// headList = uniqueKey.toArray(headList);
List<String> uniqueKeyList = uniqueKey.stream().sorted().collect(Collectors.toList());
//列标题
List<String> dateList = data.keySet().stream().sorted().collect(Collectors.toList());
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
XSSFRow row = sheet.createRow(0);
for (int i = 0; i < uniqueKey.size(); i++) {
XSSFCell cell = row.createCell(i + 1);
cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(uniqueKeyList.get(i));
}
int rowNum = 1;
for (String date : dateList) {
HashMap<String, Object> dateData = data.get(date);
row = sheet.createRow(rowNum);
XSSFCell cell = row.createCell(0);
cell.setCellValue(date);
for (int i = 0; i < uniqueKey.size(); i++) {
cell = row.createCell(i + 1);
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
cell.setCellValue(Double.parseDouble(Optional.ofNullable(dateData.get(uniqueKeyList.get(i))).orElse("0").toString()));
}
rowNum++;
}
FileOutputStream fos = new FileOutputStream(path);
workbook.write(fos);
fos.flush();
fos.close();
System.out.println("done");
}
}
<file_sep>package work;
import java.time.LocalDate;
/**
* @ClassName BaseBeanImpl
* @Description TODO
* @Author 王帆
* @Date 2020/1/20 16:05
* @Version 1.0
*/
public class BaseBeanImpl extends BaseBean {
@Override
protected void doSend() {
System.out.println("doSend run...");
}
public static void main(String[] args) {
String now = LocalDate.now().toString();
String redisKey = String.format("INTERNATIONAL_SMS_SEND_LIMIT_KEY_%s", now);
System.out.println(redisKey);
}
}
<file_sep>import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: 王帆
* @CreateTime: 2018-12-26 11:32
* @Description:
*/
public class test {
@Test
public void test() {
HashMap<Object, Object> map = new HashMap<>();
fullMap(map);
System.out.println(JSONObject.toJSONString(map));
}
private void changeName(Person person) {
person.setName("abc");
}
private void fullMap(Map map) {
map.put("abc", "abc");
}
class Person {
Person() {
}
Person(int age, String name) {
this.age = age;
this.name = name;
}
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
}
<file_sep>import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;
/**
* @Author: 王帆
* @CreateTime: 2019-04-01 18:03
* @Description:
*/
public class test2 {
@Test
public void test() {
for (int i = 0; i < 50; i++) {
System.out.println("select a.dianboId,a.createTime,b.endTime,b.createTime from live_vod_user_stat_" + i + " a left join live_vod_info b on a.dianboId = b.videoId order by b.endTime desc ;");
LongAdder adder = new LongAdder();
//System.out.println("select * from live_vod_user_stat_"+i+" order by createTime desc;");
ThreadLocal<SimpleDateFormat> formatThreadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat());
String format = formatThreadLocal.get().format(new Date());
System.out.println(format);
}
}
@Test
public void test2() {
LocalDateTime parse = LocalDateTime.parse("2020-05-06 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(parse);
}
@Test
public void test3() {
HashMap<String, Long> map = new HashMap<>();
map.put(null, 14054L);
map.put("-1", 14042L);
map.put("0", 14043L);
map.put("1", 14044L);
map.put("2", 14045L);
map.put("3", 14046L);
map.put("4", 14047L);
map.put("5", 14048L);
map.put("6", 14049L);
map.put("7", 14050L);
map.put("8", 14051L);
map.put("9", 14052L);
map.put("10", 14053L);
System.out.println(JSONObject.toJSONString(map));
}
@Test
public void test4() {
String type = "13";
System.out.println(tees(type));
}
private Long tees(String type) {
String str = "{null:14054,\"-1\":14042,\"0\":14043,\"1\":14044,\"2\":14045,\"3\":14046,\"4\":14047,\"5\":14048,\"6\":14049,\"7\":14050,\"8\":14051,\"9\":14052,\"10\":14053}";
Map map = JSON.parseObject(str, Map.class);
Object o = map.get(type);
if (o == null) {
return 14055L;
} else {
return ((Integer) o).longValue();
}
}
}
<file_sep>package com.funboy.初级.其他;
import java.util.ArrayList;
/**
* @Author: 王帆
* @CreateTime: 2019-03-13 17:51
* @Description:
*/
public class 输出三角 {
public static void main(String[] args) {
ArrayList<Object> l1 = new ArrayList<>();
ArrayList<Object> l2 = new ArrayList<>();
for (int i = 0; i < 11; i++) {
l1.add(i);
}
l2 = ( ArrayList<Object>)l1.clone();
l2.clear();
System.out.println(l1.toString());
System.out.println(l2.toString());
}
}
<file_sep>package com.umetrip.statistic.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* Created by Administrator on 2016/11/22.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class StatisticsItem {
private String id;
private String totalCount;
private String failCount;
private String failPercent;
private String tps;
private String percent;
}
<file_sep>package com.funboy.初级.其他;
/**
* @Author: 王帆
* @CreateTime: 2019-03-08 17:40
* @Description: 输出1---1000内所有能被7整除的数,每行显示6个。
*/
public class 输出能被7整除的数字 {
public static void main(String[] args) {
int count = 0;
for (int i = 1; i < 1000; i++) {
if (i % 7 == 0) {
System.out.print(i + " ");
count++;
}
if (count == 6) {
System.out.println();
count = 0;
}
}
}
}
<file_sep>package com.funboy.初级.其他;
import java.util.Scanner;
/**
* @Author: 王帆
* @CreateTime: 2019-03-08 17:47
* @Description: 将输入的正整数分解质因数。例如:输入90,打印出90=5*3*3*2
*/
public class 将输入的正整数分解质因数 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个整数 : ");
int input = scanner.nextInt();
StringBuilder sb = new StringBuilder();
sb.append(input).append("=");
boolean flag = true;
while (flag) {
for (int i = 2; i <= input; i++) {
if (input % i == 0) {
input = input / i;
sb.append(i + "*");
break;
}
}
if (input == 1) {
flag = false;
}
}
System.out.println(sb.toString().substring(0, sb.toString().length() - 1).toString());
}
}
<file_sep>package com.funboy.中级.数组;
/**
* 给定一个未排序的数组,判断这个数组中是否存在长度为 3 的递增子序列。
* <p>
* 数学表达式如下:
* <p>
* 如果存在这样的 i, j, k, 且满足 0 ≤ i < j < k ≤ n-1,
* 使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否则返回 false 。
* 说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1) 。
* <p>
* 示例 1:
* <p>
* 输入: [1,2,3,4,5]
* 输出: true
* 示例 2:
* <p>
* 输入: [5,4,3,2,1]
* 输出: false
* <p>
* 作者:力扣 (LeetCode)
* 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-medium/xvvuqg/
* 来源:力扣(LeetCode)
* 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/
public class 递增的三元子序列 {
public boolean solution(int[] nums) {
int temp1 = Integer.MAX_VALUE;
int temp2 = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
if (nums[i] <= temp1) {
temp1 = nums[i];
} else if (nums[i] <= temp2) {
temp2 = nums[i];
} else {
return true;
}
}
return false;
}
}
| fa8dbd406f94aea95fad3906c8cb8c3abc6bf57c | [
"Java",
"Maven POM"
] | 12 | Maven POM | AFunBoy/algorithm | b180999ec56a1f46f512173781f196288577a5a4 | 4c33b81398b20b163139edf8b0572d155d870910 |
refs/heads/master | <repo_name>sapi2021/saddlestitchsplitter<file_sep>/rightfirstsort.py
from pagesort import PageSort
class RightFirstSort(PageSort):
def sort(self, lhs):
numPages = len(lhs)//2
sortedPages = [0] * numPages*2
for i in range(0, numPages//2):
sortedPages[ i*2] = lhs[i*4 + 1]
sortedPages[numPages*2 - 1 - i*2] = lhs[i*4]
sortedPages[numPages*2 - 2 - i*2] = lhs[i*4 + 3]
sortedPages[ 1 + i*2] = lhs[i*4 + 2]
return sortedPages
<file_sep>/pagesort.py
from abc import ABCMeta, abstractclassmethod
class PageSort (metaclass=ABCMeta):
@abstractclassmethod
def sort(cls, lhs):
pass
<file_sep>/factory.py
from rightfirstsort import RightFirstSort
from leftfirstsort import LeftFirstSort
class SortOrderFactory():
@staticmethod
def create(opt):
if opt == "right":
return RightFirstSort()
else:
return LeftFirstSort()<file_sep>/main.py
import copy, sys, argparse, factory
from PyPDF2 import PdfFileReader, PdfFileWriter
from factory import SortOrderFactory
def reorder_pages(sort_order):
input = PdfFileReader(open('/dev/stdin', 'rb'))
numPages = input.getNumPages()
spreadPages = [0] * (numPages * 2)
j = 0
for p in [input.getPage(i) for i in range(0, numPages)]:
q = copy.copy(p)
(w, h) = p.mediaBox.upperRight
p.mediaBox.lowerRight = (w, h/2)
q.mediaBox.upperRight = (w, h/2)
spreadPages[j*2] = p
spreadPages[j*2 + 1] = q
j = j + 1
return sort_order.sort(spreadPages)
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--first_page")
return parser.parse_args()
def output_pages(pages: list):
output = PdfFileWriter()
for i in range(0, len(pages)):
output.addPage(pages[i])
output.write(open('/dev/stdout', 'wb'))
sort_order = SortOrderFactory.create(get_args().first_page)
reordered_pages = reorder_pages(sort_order)
output_pages(reordered_pages)
| 2f5a9fd004deefe4428e0a5c975623dd628138bd | [
"Python"
] | 4 | Python | sapi2021/saddlestitchsplitter | c96ba9fdc28c31baae4d7917ed91ff1eaef2eaa4 | a1de75a5345d2c7a7ba555cbd061752f84245feb |
refs/heads/master | <repo_name>kaestel/lsb_dk<file_sep>/theme/www/js/lib/smartphone/i-findcenter.js
Util.Objects["findcenter"] = new function() {
this.init = function(scene) {
// get all regions
var regions = u.qsa("li.region", scene);
var region, i;
for(i = 0; region = regions[i]; i++) {
// map region header
region.header = u.qs("h2", region);
// inject icon node
region.header._icon = u.ae(region.header, "span", {"html":"k"});
// map region branch list
region.header.ul_branch = u.qs("ul.branches", region);;
// get all region branches
var branches = u.qsa("ul.branches > li", region);
var address, postal, city, ul;
for(j = 0; branch = branches[j]; j++) {
// map region to branch (changing height of branch requires updating ul_branch height)
branch.region = region;
// enable open/close of branch info
// map branch header
branch.header = u.qs("h3", branch);
// inject icon node
branch.header._icon = u.ae(branch.header, "span", {"html":"k"});
// map branch to header
branch.header.branch = branch;
// map branch info list
branch.header.ul_info = u.qs("ul.info", branch);
// get current (expanded) height of info list
branch.header.info_org_height = u.actualH(branch.header.ul_info);
// collapse info list
u.as(branch.header.ul_info, "height", 0, false);
// make branch header clickable
u.ce(branch.header);
branch.header.clicked = function() {
// close
if(this.is_open) {
u.a.transition(this.ul_info, "all 0.6s ease-in-out");
u.as(this.ul_info, "height", 0);
this.is_open = false;
// change icon
this._icon.innerHTML = "k";
// update region branch list total height
this.branch.region.header.branch_org_height -= this.info_org_height;
}
// open
else {
u.a.transition(this.ul_info, "all 0.6s ease-in-out");
u.as(this.ul_info, "height", this.info_org_height + "px");
this.is_open = true;
// change icon
this._icon.innerHTML = "l";
// update region branch list total height
this.branch.region.header.branch_org_height += this.info_org_height;
}
// set new region branch list height
u.a.transition(this.branch.region.header.ul_branch, "all 0.6s ease-in-out");
u.as(this.branch.region.header.ul_branch, "height", this.branch.region.header.branch_org_height + "px");
}
// map address info
branch.bn_maps = u.qs("ul.info > li.address", branch);
branch.bn_maps.branch = branch;
branch._address = u.qs("ul.address li.address", branch);
branch._postal = u.qs("ul.address .postal", branch);
branch._city = u.qs("ul.address .city", branch);
// if sufficient info is available, enable google maps linking
if(branch._city && branch._address && branch._postal) {
u.ce(branch.bn_maps);
branch.bn_maps.clicked = function(event) {
window.open("https://maps.google.dk?q=L%C3%A5n%20%26%20Spar%20Bank,%20" + encodeURIComponent(this.branch._address.innerHTML) + ",%20" + encodeURIComponent(this.branch._postal.innerHTML) + "%20" + encodeURIComponent(this.branch._city.innerHTML));
}
}
}
// enable open/close of region branches
// get current (expanded) height of branch list
region.header.branch_org_height = u.actualH(region.header.ul_branch);
// collapse branch list
u.as(region.header.ul_branch, "height", 0, false);
// make branch header clickable
u.ce(region.header);
region.header.clicked = function() {
// close
if(this.is_open) {
u.a.transition(this.ul_branch, "all 0.6s ease-in-out");
u.as(this.ul_branch, "height", 0);
this.is_open = false;
// change icon
this._icon.innerHTML = "k";
}
// open
else {
u.a.transition(this.ul_branch, "all 0.6s ease-in-out");
u.as(this.ul_branch, "height", this.branch_org_height + "px");
this.is_open = true;
// change icon
this._icon.innerHTML = "l";
}
}
}
page.resized();
}
}
<file_sep>/theme/www/eksempler/tekst.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body>
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene">
<div class="c200 box">
<h1>Tekst side .c200.box</h1>
<p>
Tekstsider bruges til indhold der ikke er deciderede artikler.
</p>
<p>
En tekst side skal wrappes i en "box" (og <em>ikke</em> i en "artikel")
</p>
</div>
<div class="c100 box">
<h2>Tekst side .c100.box</h2>
<p>
Tekstsider bruges til indhold der ikke er deciderede artikler.
</p>
</div>
<div class="c200">
<div class="box">
<h1>Tekst side .c200 > .box</h1>
<p>
Tekstsider bruges til indhold der ikke er deciderede artikler.
</p>
<p>
En tekst side skal wrappes i en "box" (og <em>ikke</em> i en "artikel")
</p>
<code><div class="c200 box"></code>
<p>
Der skal derfor heller ikke tilføjes info-liste med artikel metadata.
</p>
<p>
En tekstside kan iøvrigt indeholde de samme elementer som en artikel.
</p>
</div>
<div class="box">
<h2>Bullet list .c200 > .box</h2>
<ul>
<li>First list item</li>
<li>Second list item</li>
</ul>
<h3>Number list</h3>
<ol>
<li>First list item</li>
<li>Second list item</li>
</ol>
</div>
</div>
<div class="c100">
<div class="box">
<h2>Related .c100 > .box</h2>
<p>
Tekstsider bruges til indhold der ikke er deciderede artikler.
</p>
</div>
<div class="box">
<h2>Related .c100 > .box</h2>
<p>
Tekstsider bruges til indhold der ikke er deciderede artikler.
</p>
</div>
</div>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html><file_sep>/theme/www/js/lib/smartphone/i-page.js
Util.Objects["page"] = new function() {
this.init = function(page) {
u.bug_console_only = true;
// u.bug_console_only = false;
// u.bug_force = true;
// u.bug_position = "fixed";
// u.bug("Init page");
// u.bug(u.e.event_support);
window.page = page;
// header reference
page.hN = u.qs("#header");
u.ie(document.body, page.hN);
// content reference
page.cN = u.qs("#content", page);
// navigation reference
page.nN = u.qs("#navigation", page);
u.ae(document.body, page.nN);
page.nN.ul = u.qs("ul", page.nN);
// footer reference
page.fN = u.qs("#footer");
page.fN._top = u.absY(page.fN) - u.browserH();
// global resize handler
page.resized = function(event) {
// u.bug("page.resized:", this);
// update global values
this.browser_w = u.browserW();
this.browser_h = u.browserH();
u.as(this.nN, "width", (this.offsetWidth) + "px", false);
u.as(this.nN, "height", (u.browserH()-this.hN.offsetHeight) + "px", false);
u.a.translate(this.nN, 0, -u.browserH()-this.hN.offsetHeight);
// globally handle splash images (these can be present in all pages)
if(!this._splash_images_indexed) {
this._splash_images_indexed = true;
this._splash_images = u.qsa("ul.articles li.splash div.image");
}
if(this._splash_images) {
var i, image;
for(i = 0; image = this._splash_images[i]; i++) {
u.ass(image, {
"height": Math.floor(image.offsetWidth / 640 * 274) + "px"
}, false);
}
}
// forward resize event to current scene
if(this.cN && this.cN.scene && typeof(this.cN.scene.resized) == "function") {
this.cN.scene.resized();
}
// update DOM
this.offsetHeight;
}
// iOS scroll fix (wait for last scroll event)
page.fixiOSScroll = function() {
u.ass(this.hN, {
"position":"absolute",
});
u.ass(this.hN, {
"position":"fixed",
});
}
// global scroll handler
page.scrolled = function(event) {
// u.bug("page.scrolled:", this);
// update global values
this.scroll_y = u.scrollY();
// Fix issue with fixed element after scroll
u.t.resetTimer(this.t_fix);
this.t_fix = u.t.setTimer(this, "fixiOSScroll", 200);
// forward scroll event to current scene
if(this.cN && this.cN.scene && typeof(this.cN.scene.scrolled) == "function") {
this.cN.scene.scrolled();
}
// show to top link when this has been scrolled more than 800px
if(this.scroll_y > 800) {
u.ac(this.bn_top, "show");
}
else {
u.rc(this.bn_top, "show");
}
// update DOM
page.offsetHeight;
}
// global orientation change handler
page.orientationchanged = function(event) {
// u.bug("page orientation changed:", this);
this.resized();
}
// Page is ready
page.ready = function() {
// u.bug("page.ready");
// page is ready to be shown - only initalize if not already shown
if(!this.is_ready) {
// page is ready
this.is_ready = true;
// map the current scene
this.cN.scene = u.qs(".scene", this.cN);
// set scroll handler
u.e.addWindowEvent(this, "scroll", this.scrolled);
// set orientation change handler
if(u.e.event_support == "touch") {
u.e.addWindowEvent(this, "orientationchange", this.orientationchanged);
}
// set resize handler
else {
u.e.addWindowEvent(this, "resize", this.resized);
}
// build header
this.initHeader();
// build navigation
this.initNavigation();
// build header
this.initFooter();
// show cookie notice if needed
u.cookieTerms();
// resize / scroll to update any size calculations after DOM manipulation
this.resized();
this.scrolled();
}
}
// initialize header
page.initHeader = function() {
// u.bug("initHeader");
// inject logo
this.logo = u.ae(this.hN, "a", {"class":"logo"});
this.home_url = u.qs(".servicenavigation li.home a");
if(this.home_url) {
this.logo.href = this.home_url;
u.ce(this.logo, {"type":"link"});
}
// get the navigation node from the servicenavigation
// set it up as navigation button
this.bn_nav = u.qs("ul.servicenavigation li.navigation", this.hN);
this.bn_nav.innerHTML = "";
var div = u.ae(this.bn_nav, "div", {"class":"text"});
u.ae(div, "span", {"class":"text", "html":"Menu"});
div = u.ae(this.bn_nav, "div", {"class":"icon"});
u.ae(div, "span");
u.ae(div, "span");
u.ae(div, "span");
// very simple navigation toggle
u.ce(this.bn_nav);
this.bn_nav.clicked = function(event) {
u.e.kill(event);
// close navigation
if(this._open) {
this._open = false;
// enable body scroll after navigating
u.rc(document.body, "navigating");
page.nN.transitioned = function() {
// u.bug("navigation close transitioned");
u.a.transition(page.nN.ul, "none");
// reset scroll offset
u.a.translate(page.nN.ul, 0, 0);
// restore submenus
if(page.nN.selected_submenu) {
u.as(page.nN.selected_submenu, "display", "none");
page.nN.selected_submenu = false;
}
}
u.a.transition(page.nN, "all 0.4s ease-in-out");
u.a.translate(page.nN, 0, -u.browserH());
}
// open navigation
else {
this._open = true;
// prevent body scroll while navigating
u.ac(document.body, "navigating");
// adjust navigation height every time navigation is opened
u.as(page.nN, "height", (window.innerHeight-page.hN.offsetHeight) + "px");
// update scrolling values
if(page.nN.ul.offsetHeight > page.nN.offsetHeight) {
page.nN.ul.locked = false;
page.nN.ul.only_vertical = true;
page.nN.ul.start_drag_y = (page.nN.offsetHeight - page.nN.ul.offsetHeight);
page.nN.ul.end_drag_y = page.nN.ul.offsetHeight;
}
else {
page.nN.ul.locked = true;
}
// put menu in opening position
u.a.translate(page.nN, 0, (-u.browserH()-page.hN.offsetHeight) + page.scroll_y);
page.nN.transitioned = function() {
// u.bug("navigation open transitioned");
u.a.transition(page.nN.ul, "none");
// reset scroll offset
u.a.translate(page.nN.ul, 0, 0);
}
u.a.transition(page.nN, "all 0.4s ease-in-out");
u.a.translate(page.nN, 0, page.hN.offsetHeight + page.scroll_y);
}
}
}
// setup and activate Navigation
page.initNavigation = function() {
// u.bug("initNavigation")
var i, node;
// no scrolling in #navigation
u.e.drag(page.nN, page.nN);
page.nN.inputStarted = function(event) {
// u.bug("page.nN kill");
u.e.kill(event);
}
// enable scrolling in #navigation ul
u.e.drag(page.nN.ul, page.nN.ul, {"strict":false, "elastica":200});
// page.nN.ul.picked = function() {
// u.bug("page.nN.ul.picked");
// }
// page.nN.ul.dropped = function() {
// u.bug("page.nN.ul.dropped");
// }
page.nN.ul.inputStarted = function(event) {
// u.bug("page.nN.ul kill");
u.e.kill(event);
}
// add fixed links to navigation
var mobilbank_li = u.ae(page.nN.ul, "li", {"class":"mobilbank"});
u.ae(mobilbank_li, "a", {"class":"mobilbank", "html":"Mobilbank"});
u.ce(mobilbank_li);
mobilbank_li.clicked = function() {
u.mobilbankLink();
// close navigation
page.bn_nav.clicked();
}
var desktop_li = u.ae(page.nN.ul, "li", {"class":"desktop"});
u.ae(desktop_li, "a", {"html":"Desktop udgave", "href":u.txt["desktop-link"] });
// enable js links for all navigation links
page.nN.nodes = u.qsa("ul li a", page.nN);
for(i = 0; node = page.nN.nodes[i]; i++) {
// custom link handler for mobilbank link
if(!u.hc(node, "mobilbank")) {
u.ce(node, {"type":"link"});
// u.ce(node);
// node.clicked = function(event) {
// u.bug(event.type);
// u.bug("node clicked");
// u.e.kill(event);
// }
}
}
// get all submenu nodes
page.nN.submenu_nodes = u.qsa("ul li h4", page.nN);
for(i = 0; node = page.nN.submenu_nodes[i]; i++) {
// add arrow icon
u.ae(node, "span", {"html":"m"});
// get submenu node
node.submenu = u.ns(node, {"include":"ul"});
// check for headlines in submenu groupings
var submenu_items = u.qsa("li", node.submenu);
var li, j;
for(j = 0; li = submenu_items[j]; j++) {
var subheader = u.qs("h5", li);
// add class if no header is present (to ease styling)
if(!subheader) {
u.ac(li, "root");
}
// capture clicks to avoid spillover
else {
u.ce(subheader);
subheader.clicked = function(event) {
// u.bug("subheader clicked");
u.e.kill(event);
}
}
}
u.ce(node);
node.clicked = function(event) {
// u.bug("submenu clicked");
// inject back link and enable scolling on first opening
if(!this.bn_back) {
this.bn_back = u.ie(this.submenu, "li", {"class":"back"});
u.ae(this.bn_back, "span", {"class": "icon", "html":"n"});
u.ae(this.bn_back, "span", {"class": "text", "html":"Retur"});
u.ce(this.bn_back);
this.bn_back.clicked = function(event) {
u.bug("back clicked");
page.nN.ul.transitioned = function() {
u.bug("back clicked transitioned");
u.a.transition(this, "none");
// restore submenus
if(page.nN.selected_submenu) {
u.a.transition(page.nN.selected_submenu, "none");
u.a.translate(page.nN.selected_submenu, 0, 0);
u.as(page.nN.selected_submenu, "display", "none");
page.nN.selected_submenu = false;
}
}
u.a.transition(page.nN.ul, "all 0.4s ease-in-out");
u.a.translate(page.nN.ul, 0, page.nN.ul._y);
}
u.as(this.submenu, "left", page.nN.offsetWidth+"px");
u.as(this.submenu, "top", (-page.nN.ul._y)+"px");
u.as(this.submenu, "display", "block");
// enable scrolling in #navigation ul
u.e.drag(this.submenu, this.submenu, {"strict":false, "elastica":200});
this.submenu.picked = function() {
// u.bug("submenu picked");
}
this.submenu.dropped = function() {
// u.bug("submenu dropped");
}
}
// remember current submenu (for resetting later)
page.nN.selected_submenu = this.submenu;
// position submenu
u.as(this.submenu, "left", page.nN.offsetWidth+"px");
u.as(this.submenu, "top", (-page.nN.ul._y)+"px");
u.as(this.submenu, "display", "block");
// update scrolling values
this.submenu.locked = false;
this.submenu.only_vertical = true;
this.submenu.start_drag_y = page.nN.offsetHeight - this.submenu.offsetHeight;
this.submenu.end_drag_y = this.submenu.offsetHeight;
page.nN.ul.transitioned = function() {
u.a.transition(this, "none");
}
// show submenu
u.a.transition(page.nN.ul, "all 0.4s ease-in-out");
u.a.translate(page.nN.ul, -page.nN.offsetWidth, page.nN.ul._y);
}
}
}
// initialize footer
page.initFooter = function() {
// u.bug("initFooter")
var li_contact = u.qs("li.contact li.contact", page.fN);
var li_findcenter = u.qs("li.contact li.findcenter", page.fN);
// find new fix point
var li_taxid = u.qs("li.about li.taxid", page.fN);
li_taxid.parentNode.insertBefore(li_contact, li_taxid);
li_taxid.parentNode.insertBefore(li_findcenter, li_taxid);
// make sure phonenumber in footer is always active
li_telephone = u.qs("li.about li.telephone", page.fN);
u.wc(li_telephone, "a", {"href":"tel:"+u.text(li_telephone).replace(/[ \(\)]/g, "")});
// activate scroll to top link
page.bn_top = u.qs("ul.servicenavigation li.top", page.fN);
u.ce(page.bn_top);
page.bn_top.clicked = function() {
u.scrollTo(window, {"y":0});
}
var mobilbank_div = u.ae(page.fN, "div", {"class":"mobilbank"});
var mobilbank_link = u.ae(mobilbank_div, "a", {"html":"Mobilbank"});
u.ce(mobilbank_link);
mobilbank_link.clicked = function() {
u.mobilbankLink();
}
var desktop_div = u.ae(page.fN, "div", {"class":"desktop"});
var desktop_link = u.ae(desktop_div, "a", {"html":"Desktop udgave"});
u.ce(desktop_link);
desktop_link.clicked = function() {
location.href = u.txt["desktop-link"];
}
}
// ready to start page builing process
page.ready();
}
}
// add initialization to DOMReady event
u.e.addDOMReadyEvent(u.init);
<file_sep>/theme/www/js/lib/smartphone/i-andelsberegner.js
Util.Objects["andelsberegner"] = new function() {
this.init = function(scene) {
// u.bug("init andelsberegner");
var form = u.qs("form", scene);
u.f.init(form);
form.p_result = u.qs("p.result", scene);
form.span_result = u.qs("span.result", scene);
var input = form.fields["andelsberegner_input"];
input.keydown = function(event) {
// maintain value as string, to easily perform length evaluation when adding thousands-separator
var value = this.val().replace(/[^\d]+/g, "");
// u.bug(this.val() + ", " + this.val().length + ", " + value)
if(!event.metaKey && (
(event.keyCode < 48 || event.keyCode > 57) &&
!event.keyCode.toString().match(/^(190|8|9|40|39|38|37)$/)
)) {
u.e.kill(event);
}
}
input.keyup = function(event) {
// maintain value as string, to easily perform length evaluation when adding thousands-separator
var value = this.val().replace(/[^\d]+/g, "");
if(!event.metaKey && (
(event.keyCode < 48 || event.keyCode > 57) &&
!event.keyCode.toString().match(/^(8|9|40|39|38|37)$/)
)) {
u.e.kill(event);
return;
}
if(!event.metaKey &&
event.keyCode.toString().match(/^(9|40|39|38|37)$/)
) {
return;
}
if(value.length > 6) {
this.val(value.substring(0, value.length - 6) + "." + value.substring(value.length - 6, value.length - 3) + "." + value.substring(value.length - 3));
}
else if(value.length > 3) {
this.val(value.substring(0, value.length - 3) + "." + value.substring(value.length - 3));
}
else {
this.val(value);
}
// calculate payment amount
var payment = this._form.calculateNumber(value).toString();
if(payment.length > 3) {
payment = payment.substring(0, payment.length - 3) + "." + payment.substring(payment.length - 3);
}
this._form.span_result.innerHTML = payment + " kr.";
if(!this._form.is_active) {
u.ass(this._form.p_result, {
"display":"block"
});
this._form.is_active = true;
}
}
// From lsb.dk
form.calculateNumber = function(y) {
// look for calculation in global variables
if(fun(u.andelsCalculator)) {
return u.andelsCalculator(y);
}
// fallback calculation
if( !isNaN(y) && y >= 1000) {
a0 = ( y * 0.998072 );
n = 360; // 30*12
r = 0.00370833; // rente
y = ( a0 * r / (1-(1 / Math.pow( (1+r) , n ))) );
y = Math.round(y); // runder op
return y;
}
return 0;
}
// avoid submitting on enter
form.submitted = function() {}
// capture key events
u.e.addEvent(input, "keyup", input.keyup);
u.e.addEvent(input, "keydown", input.keydown);
}
}
<file_sep>/theme/www/eksempler/artikel.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body>
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene article i:article">
<div class="article" itemscope itemtype="http://schema.org/Article">
<ul class="info">
<li class="published_at" itemprop="datePublished" content="2015-01-05">5. januar 2015</li>
<li class="modified_at" itemprop="dateModified" content="2015-01-05"></li>
<li class="author" itemprop="author" content="<NAME>"></li>
<li class="main_entity share" itemprop="mainEntityOfPage" content="http://test-lsb.parentnode.dk/artikel"></li>
<li class="publisher" itemprop="publisher" itemscope itemtype="https://schema.org/Organization">
<ul class="publisher_info">
<li class="name" itemprop="name" content="lsb.dk"></li>
<li class="logo" itemprop="logo" itemscope itemtype="https://schema.org/ImageObject">
<span class="image_url" itemprop="url" content="http://test-lsb.parentnode.dk/img/logo-large.png"></span>
<span class="image_width" itemprop="width" content="720"></span>
<span class="image_height" itemprop="height" content="405"></span>
</li>
</ul>
</li>
</ul>
<div class="i:image" data-image-src="/img/grid/640x274/eftermiddagshygge.jpg" itemprop="image" itemscope itemtype="https://schema.org/ImageObject">
<span class="image_url" itemprop="url" content="http://test-lsb.parentnode.dk/img/grid/640x274/eftermiddagshygge.jpg"></span>
<span class="image_width" itemprop="width" content="640"></span>
<span class="image_height" itemprop="height" content="274"></span>
</div>
<h1 itemprop="headline">Dette er en default artikel side</h1>
<div class="articlebody" itemprop="articleBody">
<p>
På en artikel side skal scenen se således ud:
</p>
<code><div class="scene article i:article"></code>
<p>
Herudover skal selve artikel indholdet ligge i et artikel-div, der skal se således ud:
</p>
<code><div class="article" itemscope itemtype="http://schema.org/Article"></code>
<p>
Endvidere bør en artikel have en info liste med schema data for søgemaskine optimering:
</p>
<code><ul class="info">
<li class="published_at" itemprop="datePublished" content="2015-01-05">5. januar 2015</li>
<li class="modified_at" itemprop="dateModified" content="2015-01-05"></li>
<li class="author" itemprop="author" content="<NAME>"></li>
<li class="main_entity share" itemprop="mainEntityOfPage" content="http://test-lsb.parentnode.dk/artikel"></li>
<li class="publisher" itemprop="publisher" itemscope itemtype="https://schema.org/Organization">
<ul class="publisher_info">
<li class="name" itemprop="name" content="lsb.dk"></li>
<li class="logo" itemprop="logo" itemscope itemtype="https://schema.org/ImageObject">
<span class="image_url" itemprop="url" content="http://test-lsb.parentnode.dk/img/logo-large.png"></span>
<span class="image_width" itemprop="width" content="720"></span>
<span class="image_height" itemprop="height" content="405"></span>
</li>
</ul>
</li>
</ul></code>
<p>
Selve artiklen består af en headline og en articleBody, og bemærk at headline <em>ikke</em> skal ligge inde i articleBody:
</p>
<code><h1 itemprop="headline">Dette er en default artikel side</h1></code>
<code><div class="articlebody" itemprop="articleBody"></code>
<h2>Sekondær overskrift</h2>
<p>
I articleBody kan der bruges <h2>, <h3>, <h4>, <p>, <ol> og <ul> tags.
</p>
<div class="i:image" data-image-src="/img/grid/640x274/eftermiddagshygge.jpg" itemprop="image" itemscope itemtype="https://schema.org/ImageObject">
<span class="image_url" itemprop="url" content="http://test-lsb.parentnode.dk/img/grid/640x274/eftermiddagshygge.jpg"></span>
<span class="image_width" itemprop="width" content="640"></span>
<span class="image_height" itemprop="height" content="274"></span>
<a href="#">Consectetur adipisicing elit minim</a>
</div>
<p>
Der kan også bruges billeder i selve artikelBody. Dette gøres med følgende HTML:
</p>
<code><div class="i:image" data-image-src="/img/grid/640x274/eftermiddagshygge.jpg" itemprop="image" itemscope itemtype="https://schema.org/ImageObject">
<span class="image_url" itemprop="url" content="http://test-lsb.parentnode.dk/img/grid/640x274/eftermiddagshygge.jpg"></span>
<span class="image_width" itemprop="width" content="640"></span>
<span class="image_height" itemprop="height" content="274"></span>
<a href="#">Consectetur adipisicing elit minim</a>
</div></code>
<p>Det er valgfrit om man vil inkludere et link til billedet.</p>
<div class="i:youtube" data-youtube-src="https://www.youtube.com/embed/wYcaBicRpVQ" itemprop="video" itemscope itemtype="https://schema.org/VideoObject">
<span class="name" itemprop="name" content="Bank røveriet"></span>
<span class="description" itemprop="description" content="LEGO Film SJOV helt bogstaveligt"></span>
<span class="thumbnail" itemprop="thumbnailUrl" content="https://www.youtube.com/embed/wYcaBicRpVQ"></span>
<span class="upload_date" itemprop="uploadDate" content="2016-05-05"></span>
</div>
<p>
Der kan også indsætte youtube video'er i selve artikelBody. Dette gøres med følgende HTML:
</p>
<code><div class="i:youtube" data-youtube-src="https://www.youtube.com/embed/wYcaBicRpVQ" itemprop="video" itemscope itemtype="https://schema.org/VideoObject">
<span class="name" itemprop="name" content="Bank røveriet"></span>
<span class="description" itemprop="description" content="LEGO Film SJOV helt bogstaveligt"></span>
<span class="thumbnail" itemprop="thumbnailUrl" content="https://www.youtube.com/embed/wYcaBicRpVQ"></span>
<span class="upload_date" itemprop="uploadDate" content="2016-05-05"></span>
</div></code>
<h3>Bullet list</h3>
<ul>
<li>First list item</li>
<li>Second list item</li>
</ul>
<code><ul>
<li>First list item</li>
<li>Second list item</li>
</ul></code>
<h3>Number list</h3>
<ol>
<li>First list item</li>
<li>Second list item</li>
</ol>
<code><ol>
<li>First list item</li>
<li>Second list item</li>
</ol></code>
</div>
</div>
<div class="related i:related">
<ul class="articles">
<li class="article atop" data-image-src="/img/grid/640x274/flytte" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">"Sidebar"</h2>
<div class="description" itemprop="description">
<p>
En artikel kan efterfølges af en "sidebar"-liste, bestående af henholdsvis artikel-snippets som denne og link lister som vist nedenfor.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Læs mere</a></li>
</ul>
</li>
<li class="article" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Link liste</h2>
<ul class="links">
<li><a href="/artikel">Halvårsrapport 2015</a></li>
<li><a href="/artikel">Nye kontaktløse kort</a></li>
<li><a href="/artikel">Tilmeld dig nyhedsbrevet</a></li>
<li><a href="/artikel">Læg din pension om og få skatterabat</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html><file_sep>/theme/www/js/lib/desktop/i-article.js
Util.Objects["article"] = new function() {
this.init = function(scene) {
scene.resized = function() {
// u.bug("scene.resized:", this);
if(this.article && this.article.is_splash && this.article.image._image) {
u.ass(this.article.header, {
"height": this.article.image._image.offsetHeight+"px"
});
if(u.hc(this.article, "right")) {
u.ass(this.article.header, {
"margin-left": (this.article.offsetWidth-180)+"px"
});
}
}
}
scene.scrolled = function() {
// u.bug("scrolled:", this);
}
scene.ready = function() {
page.cN.scene = this;
this.article = u.qs("div.article", scene);
// Splash article (header on top of image)
if(u.hc(this.article, "splash")) {
// find header
this.article.header = u.qs("h1", this.article);
u.wc(this.article.header, "span");
this.article.image = u.ps(this.article.header);
if(u.hc(this.article.image, "i:image")) {
u.ac(this.article.image, "main");
u.ac(this.article.image, "gradient");
this.article.is_splash = true;
}
else if(u.hc(this.article.image, "image")) {
u.ac(this.article.image, "main");
u.ie(this.article.image, "div", {"class":"gradient"});
this.article.is_splash = true;
}
// article._image = u.qs("div.image", article);
// if(article._image) {
// u.ie(article._image, "div", {"class":"gradient"});
// }
}
}
scene.ready();
}
}
//
// Util.Objects["article"] = new function() {
// this.init = function(scene) {
//
// var article = u.qs("div.article", scene);
// article._image_src = article.getAttribute("data-image-src");
//
// if(article._image_src) {
//
// article._image = u.ie(article, "div", {"class":"image"});
// u.as(article._image, "backgroundImage", "url("+article._image_src.replace(/[\d]+x[\d]+/, "640x274")+")")
//
//
// }
//
//
// }
// }
<file_sep>/theme/www/eksempler/formular.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body>
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene contact i:contact">
<div class="c200 box">
<h1>Formular</h1>
<p>
En formular side er i vid udstrækning baseret på HTML fra LSB's form komponent.
</p>
<p>
En formular side skal wrappes i en "box" (og <em>ikke</em> i en "artikel")
</p>
<code><div class="c200 box"></code>
<p>
Der skal derfor heller ikke tilføjes info-liste med artikel metadata.
</p>
<!-- HTML DEFINED BY LSB FORM COMPONENT -->
<div class="application">
<div id="j_id_4" class="appmessages severe">
<label for="mainform:j_id_b" class="severe navigatable">Der er fejl i din indtastning. Der er fejl i din indtastning. Der er fejl i din indtastning.</label>
<script type="text/javascript">document.addEventListener('DOMContentLoaded', function() { document.getElementById('mainform:j_id_b').focus();}, false);</script>
</div>
<form id="mainform" name="mainform" method="post" action="?view=1604856420" class="i:form" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="javax.faces.encodedURL" value="/customercontact-web/views/simpleresponsive/index.xhtml">
<div id="mainform:j_id_7" class="appmessages nomessages"></div>
<div id="mainform:j_id_8" class="fieldSet singleColumnLayout">
<div id="mainform:j_id_9_1" class="field">
<div class="fieldText">
<label>Er du kunde?</label>
</div>
<div class="fieldInput below">
<input id="mainform:customer" type="checkbox" name="mainform:custoemr" value="true" class="checkbox" />
<label class="checkbox large" for="mainform:customer">Jeg er kunde i Lån og Spar</label>
</div>
<div class="fieldMessages">
<label for="mainform:customer" title="Hop til feltet med fejlen." class="message severe">Du skal vælge hvad du overvejer</label>
</div>
</div>
<div id="mainform:j_id_a" class="field">
<div class="fieldInput below">
<input id="mainform:j_id_b" name="mainform:j_id_b" type="text" value="" title="Fulde navn">
</div>
<div class="fieldMessages">
<label for="mainform:j_id_b" title="Hop til feltet med fejlen." class="message severe">Du mangler at udfylde dette felt.</label>
</div>
</div>
<div id="mainform:j_id_c" class="field">
<div class="fieldInput below">
<input id="mainform:j_id_d" name="mainform:j_id_d" type="text" value="" maxlength="4" size="4" title="Postnr.">
</div>
<div class="fieldMessages">
<label for="mainform:j_id_d" title="Hop til feltet med fejlen." class="message severe">Du mangler at udfylde dette felt.</label>
</div>
</div>
<div id="mainform:j_id_e" class="field">
<div class="fieldInput below">
<input id="mainform:j_id_f" name="mainform:j_id_f" type="text" value="" title="Telefon">
</div>
<div class="fieldMessages">
<label for="mainform:j_id_f" title="Hop til feltet med fejlen." class="message severe">Du mangler at udfylde dette felt.</label>
</div>
</div>
<div id="mainform:j_id_g" class="field">
<div class="fieldInput below">
<input id="mainform:j_id_h" name="mainform:j_id_h" type="text" value="" title="E-mail-adresse">
</div>
<div class="fieldMessages">
<label for="mainform:j_id_h" title="Hop til feltet med fejlen." class="message severe">Du mangler at udfylde dette felt.</label>
</div>
</div>
<div id="mainform:j_id_i" class="field">
<div class="fieldInput below">
<textarea name="mainform:j_id_j" title="Skriv din besked her"></textarea>
</div>
<div class="fieldMessages">
<label for="mainform:j_id_j" title="Hop til feltet med fejlen." class="message severe">Du mangler at udfylde dette felt.</label>
</div>
</div>
</div>
<ul class="actions">
<li class="send">
<input id="mainform:j_id_l" name="mainform:j_id_l" type="submit" value="Send besked" class="button">
</li>
</ul>
<input type="hidden" name="mainform_SUBMIT" value="1">
<input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="<KEY>>
</form>
</div>
</div>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html><file_sep>/theme/www/andelsberegner.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body>
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene andelsberegner i:andelsberegner">
<div class="box">
<div class="i:image" data-image-src="https://www.lsb.dk/resp/content/images/640x274/andel.v160404144104"></div>
<h1>Hvor meget skal du låne?</h1>
<form class="labelstyle:inject" method="post" action="#">
<div class="field string">
<label for="andelsberegner_input">Skriv beløb her</label>
<input type="tel" autocomplete="off" id="andelsberegner_input" name="andelsberegner_input" maxlength="9" value="" />
</div>
</form>
<p class="result">Din månedlige ydelse på lånet bliver <span class="result">0 kr.</span></p>
<h4>Skal vi ringe dig op omkring et andelsboliglån?</h4>
<ul class="actions">
<li><a href="#" class="button">Ring mig op</a></li>
</ul>
<h4>Eksempel på omkostninger ved et Lån & Spar AndelsPrioritet</h4>
<p>Lån på f. eks. 1.000.000 kr. giver 977.340 kr. udbetalt. 5.027 kr. pr. mdr. i 30 år med en variabel rente på 4,45% (debitorrente 4,52%). ÅOP 4,73 %. I alt koster det 1.809.891 kr. over 30 år. I lånets hovedstol indgår 22.660 kr. i oprettelsesomkostninger herunder 16.660 kr. til tinglysning.</p>
<p>Beregningerne sker ud fra de indtastede tal og standardforudsætninger. Beregningerne er vejledende. Vi tager forbehold for fejl og mangler. Kontakt os for en præcis beregning. Bevilling af lånet kræver en gennemgang af din økonomi og boligen. Det endelige resultat kan afvige fra beregneren. Lån & Spar Bank er ikke forpligtede til at tilbyde lån med nævnte forudsætninger.</p>
</div>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html><file_sep>/theme/www/global-variables.js
var dataLayer = [];
u.terms_version = "terms_v1";
// https://www.microsoft.com/store/apps/9wzdncrdm20b
// http://windowsphone.com/s?appid=e4f90c1e-fcbc-4030-af03-3546f4d80293
// ms-windows-store://pdp/?ProductId=e4f90c1e-fcbc-4030-af03-3546f4d80293
// ms-windows-store://pdp/?ProductId=9wzdncrdm20b
u.mobilbank = {
"iosapp":"com.sdc.LanSpar.SDCBankCode0400://open",
"ios":"itms://geo.itunes.apple.com/dk/app/lan-spar-bank-a-s-mobilbank/id440213351",
"android":"market://details?id=dk.sdc.a.mobilbank.lanspar",
"windows":"https://www.microsoft.com/store/apps/9wzdncrdm20b",
"lsb":"https://www.lsb.dk/lsb/content/produkter/andre/selvbetjening/mobilbank/Mobilbank",
"detect":function() {
if(navigator.userAgent.match(/windows phone|iemobile/i)) {
return "windows";
}
else if(navigator.userAgent.match(/iphone|ipod/i)) {
return "ios";
}
else if(navigator.userAgent.match(/android|dalvik/i)) {
return "android";
}
else {
return "lsb";
}
}
}
u.txt = {
"cookies-headline":"Vi bruger cookies. Når du bruger vores hjemmeside, accepterer du vores brug af cookies. ",
"cookies-readmore-text":"Læs mere.",
"cookies-readmore-link":"https://www.lsb.dk/resp/content/readmore",
"desktop-link":"http://lsb.dk/lsb?segment=desktop",
"search-label":"Søg",
"user-private-text":"Privat",
"user-private-link":"https://www.lsb.dk/lsb?segment=desktop",
"user-business-text":"Erhverv",
"user-business-link":"https://www.lsb.dk/lsb/erhverv/forside/",
"netbank-text":"Log på",
"netbank-private-text":"Netbank privat",
"netbank-private-link":"https://www.lsb.dk/lsb/netbank/privat/adgang/logon/",
"netbank-business-text":"Netbank erhverv",
"netbank-business-link":"https://www.lsb.dk/lsb/netbank/erhverv/logon/logon/",
"netbank-quicklook-text":"Konto kik",
"netbank-quicklook-link":"https://www.lsb.dk/lsb/netbank",
"netbank-sign-text":"Aftaler til underskrift",
"netbank-sign-link":"https://www.lsb.dk/lsb/netbank",
};
// Allow additional includes via this file (in-between bundle deployment)
var header_scripts = u.qsa("script", document.head);
var i, script;
for(i = 0; script = header_scripts[i]; i++) {
if(script.src && script.src.match(/seg_[a-z_]+.js/)) {
var segment = script.src.match(/seg_([a-z_]+)\.js/)[1].replace(/_include/, "");
// Segment seems to be valid
if(segment.match(/^(desktop|smartphone)$/)) {
// additional js-includes listed here (not included in package yet)
// Andelsbolig calculator (now included in bundle)
// document.write('<link type="text/css" rel="stylesheet" media="all" href="/resp/content/bolig/andelsbolig/beregner/'+segment+'-filer/s-andelsberegner.css" />');
// document.write('<script type="text/javascript" src="/resp/content/bolig/andelsbolig/beregner/'+segment+'-filer/i-andelsberegner.js"></script>');
}
break;
}
}
// Calculation based on interest placed here to enable updates to interest rate without new build
u.andelsCalculator = function(y) {
if( !isNaN(y) && y >= 1000) {
a0 = ( y * 0.998072 );
n = 360; // 30*12
r = 0.00370833; // rente
y = ( a0 * r / (1-(1 / Math.pow( (1+r) , n ))) );
y = Math.round(y); // runder op
return y;
}
return 0;
}
<file_sep>/theme/config/config.php
<?php
/**
* This file contains definitions
*
* @package Config
*/
header("Content-type: text/html; charset=UTF-8");
error_reporting(E_ALL);
/**
* Required site information
*/
define("SITE_UID", "LSB");
define("SITE_NAME", "<NAME>");
define("SITE_URL", "lsb.dk");
define("SITE_EMAIL", "<EMAIL>");
/**
* Optional constants
*/
define("DEFAULT_PAGE_DESCRIPTION", "");
define("DEFAULT_LANGUAGE_ISO", "DA");
define("DEFAULT_COUNTRY_ISO", "DK");
// Enable items model
#define("SITE_ITEMS", true);
// Enable notifications (send collection email after N notifications)
define("SITE_COLLECT_NOTIFICATIONS", 100);
// Disable security
define("SITE_INSTALL", true);
?>
<file_sep>/theme/www/docs/images.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body class="docs">
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene docs images">
<div class="box">
<h1>Billeder</h1>
<p>
Denne side giver indblik i hvordan billeder skal produceres til sitet, samt hvordan billeder angives
i HTML'en og vises under de forskellige segmenter (desktop/tablet/smartphone).
</p>
<h2 id="images_produktion">Produktion</h2>
<p>
Billeder til sitet laves i tre versioner: <strong>640x274</strong>, <strong>640x540</strong> og <strong>840x360</strong>. Det er begrundet i et kompromis
imellem visning og produktion. Vi har bygget grid til smartphone og desktop, som er optimeret til disse
størrelser for at begrænse behovet for grafisk produktionen.
</p>
<p>
Der er aftalt et navngivnings-system til billeder, herunder billed-navne og -stier. Systemet dikterer,
at alle tre formater <strong>skal</strong> være tilgængelige og at eneste variable element i stier og
navne er størrelses-angivelsen, som enten kan indgå i foldernavn, billednavn eller begge dele. Dette
system gør at sidens JavaScript dynamisk kan loade den version af billedet, der passer bedst, uafhængigt
at hvilket version der er angivet i HTML'en.
</p>
<h3>Korrekte stier</h3>
<code>/content/images/640x274/mobilbank_16-11-16.jpg
/content/images/640x540/mobilbank_16-11-16.jpg
/content/images/840x360/mobilbank_16-11-16.jpg</code>
<code>/content/images/mobilbank_16-11-16_640x274.jpg
/content/images/mobilbank_16-11-16_640x540.jpg
/content/images/mobilbank_16-11-16_840x360.jpg</code>
<h3 class="error">Ugyldige stier</h3>
<code class="error">/content/images/640x274/mobilbank_16-11-16.jpg
/content/images/640x540/mobilbank.jpg
/content/images/840x360/mobilbank.jpg</code>
<p class="note">
Bemærk: I nogle sammenhænge vil billederne ikke blive vist i fuld størrelse, men i stedet blive beskåret for at
overholde grid-regler. Dette uddybes under <a href="#images_visning">Visning</a> nedenfor. Læs også mere om <a href="/docs/frontpage-classes">billed alignment klasser</a>, for
at kontrollere beskæringen.
</p>
<h2 id="images_html">HTML</h2>
<p>
I HTML'en kan et billede angives i en vilkårlig version, fordi det altid er JavaScript'en, som afgør
hvilket billede, der skal loades og vises i enhver given sammenhæng. Med andre ord, det er ikke HTML'en
der bestemmer hvilket billede der bliver vist. I praksis fungerer HTML'en altså
som informations-kilde til JavaScript'en men også til eksempelvis Google.
</p>
<p>
Når et billede angives i HTML'en kan der også inkluderes metadata til søgemaskinerne, men dette er
ikke et krav for korrekt visning af siden. Hvis siden skal være optimeret til søgemaskiner, bør man
dog altid, i HTML'en, angive den version af et billede som man ønsker søgemaskinen skal se, inkl.
relateret metadata.
</p>
<h3>Eksempel</h3>
<code><div class="i:image" data-image-src="/640x274/hygge.jpg" itemprop="image" itemscope itemtype="https://schema.org/ImageObject">
<span class="image_url" itemprop="url" content="http://lsb.dk/640x274/hygge.jpg"></span>
<span class="image_width" itemprop="width" content="640"></span>
<span class="image_height" itemprop="height" content="274"></span>
</div></code>
<p>
I ovenstående eksempel læses <em>data-image-src</em>-attibutten af JavaScript'en, der erstatter
størrelses-fragmentet (640x274) med den mest egnede størrelse, inden billedet indsættes i siden. Billedet
vil i nogle tilfælde blive indsat som baggrundsbillede og andre gange som <img>-tag. Dette afhænger
af design og segment og er i princippet irrelevant for HTML-leveringen.
</p>
<p>
I ovenstående eksempel er der angivet 3 <span>-elementer med metadata til søgemaskiner. Her angives
den fulde sti til billedet (inkl. domain), billedets bredde og højde. Disse data bruges udelukkende af
søgemaskiner.
</p>
<h3>Vigtigt</h3>
<p>
Der angives <strong>ikke</strong> forskellige billeder via HTML'en og backend/CMD afleverer altid samme
billedsti uafhængigt af segment. Man vil derfor ikke se en forskel i den leverede kode til henholdvis
desktop og smartphone segmentet.
</p>
<p>
Billeder må <strong>aldrig</strong> angives direkte i <img>-tags, da de i såfald tvinger
browseren til at loade dem øjeblikkeligt og derved kompromittere sidens performance og muligheden
for segment optimering.
</p>
<p class="note">
Bemærk: I artikel-lister (som på forsiden), angives list-elementerne som <a href="https://schema.org/CreativeWork">CreativeWork</a> overfor
søgemaskinerne, da det på udviklingstidspunktet var uklart om der var tilstrækkeligt information til
rådighed til at angive en fuld <a href="https://schema.org/Article">Article</a>. Der angives derfor ikke
metadata til billeder i artikel-lister.
</p>
<p class="note">
Bemærk: Fordi sidens HTML manipuleres med JavaScript, vil der være stor forskel på den leverede
og den renderede kode. Dette svarer til forskellen mellem "View source" og "Inspect element".
</p>
<h2 id="images_visning">Visning</h2>
<p>
De tre billedformater anvendes efter følgende regelsæt:
</p>
<h3>Smartphone</h3>
<h4>Forside grid</h4>
<dl>
<dt>article</dt>
<dd>640x274 (uden beskæring)</dd>
<dt>splash</dt>
<dd>640x274 (uden beskæring)</dd>
<dt>custom</dt>
<dd>640x540 (uden beskæring)</dd>
</dl>
<h4>Generelle sidevisninger</h4>
<dl>
<dt>inline image</dt>
<dd>640x274 (uden beskæring)</dd>
</dl>
<h3>Desktop</h3>
<p>
Da desktop forsiden stadig blot er en POC-side (stadig under ændring), er der ikke lavet afsluttende beskæring/alignment
optimering. Nedenstående angiver derfor blot hvilket billede der anvendes. Beskæring-regler tilføjes når
forside grid er færdigt.
</p>
<h4>Forside 756px grid</h4>
<dl>
<dt>1/3 article</dt>
<dd>640x274</dd>
<dt>1/3 splash</dt>
<dd>640x540</dd>
<dt>1/3 custom</dt>
<dd>640x540</dd>
<dt>2/3 splash</dt>
<dd>840x360</dd>
<dt>2/3 custom</dt>
<dd>840x360</dd>
</dl>
<h4>Forside 960px grid</h4>
<dl>
<dt>1/3 article</dt>
<dd>640x274</dd>
<dt>1/3 splash</dt>
<dd>640x540</dd>
<dt>1/3 custom</dt>
<dd>640x540</dd>
<dt>2/3 splash</dt>
<dd>840x360</dd>
<dt>2/3 custom</dt>
<dd>840x360</dd>
</dl>
<h4>Forside 1260px grid</h4>
<dl>
<dt>1/3 article</dt>
<dd>640x274</dd>
<dt>1/3 splash</dt>
<dd>640x540</dd>
<dt>1/3 custom</dt>
<dd>640x540</dd>
<dt>2/3 splash</dt>
<dd>840x360</dd>
<dt>2/3 custom</dt>
<dd>840x360</dd>
</dl>
<h4>Generelle sidevisninger</h4>
<dl>
<dt>2/3 inline image</dt>
<dd>840x360 (uden beskæring)</dd>
</dl>
<h4>Relateret / Sidebar</h4>
<dl>
<dt>1/3 article</dt>
<dd>640x274 (uden beskæring)</dd>
<dt>1/3 splash</dt>
<dd>640x540 (uden beskæring)</dd>
<dt>1/3 custom</dt>
<dd>640x540 (uden beskæring)</dd>
</dl>
</div>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html><file_sep>/theme/www/js/lib/seg_smartphone_include.js
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/manipulator/v0_9_2/merged/seg_smartphone.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/smartphone/u-basics.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/u-basics.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/smartphone/i-page.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/smartphone/i-front.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/smartphone/i-findcenter.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/smartphone/i-article.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/smartphone/i-related.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/smartphone/i-image.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/smartphone/i-youtube.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/smartphone/i-andelsberegner.js"></script>');
<file_sep>/theme/www/docs/changelog.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body class="docs">
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene docs changelog">
<div class="c200">
<div class="box">
<h1 itemprop="headline">Changelog</h1>
<p>
Oversigt over leverede pakker og de ændringer/opdatering de hver især indeholder.
</p>
<p>
Koden på dette site er tilgængelig via <a href="https://github.com/kaestel/lsb_dk" target="_blank">GitHub</a>.
</p>
<p>
I alle tilfælde i nedenstående kodestykker, skal url'er tilpasses i den endelige implementering.
</p>
</div>
<div class="box">
<h2>Version 1.8.4</h2>
<p>Publiceret: 1. juli 2018</p>
<ul class="actions">
<li class="download"><a href="/packages/update-1_8_4.zip" class="button">Download</a></li>
</ul>
<h3>Smartphone: Bugfixes</h3>
<p>
Højden på .splash elementer i forside griddet genberegnes nu, når der skiftes fra landscape
til portrait og omvendt.
</p>
<p>
Splash article genberegnes når billede er loadet, så teksten placeres korrekt.
</p>
<p>
Desktop link virker nu, som tiltænkt ved at sende et segment parameter med tilbage til
lsb.dk, og vi undgår derfor et "endless loop".
</p>
<h3>Smartphone: iOS bug</h3>
<p>
Workaround til iOS bug i fixed menu. I visse tilfælde vil menuen's aktive område forsvinde efter
scroll og menuen kan ikke længere åbnes. Dette problem er løst med nærværende pakke.
</p>
<h3>Smartphone: Android bug</h3>
<p>
Tap events (touch-klik) bug på Android rettet, så klik også registreres selvom fingeren flyttes let
ved berøringen. (Fejlen skyldes opdateret Android der øgede touch sensitiviteten).
</p>
<h3>Smartphone: Opdatering af menu (3. revision)</h3>
<ul>
<li>Tydeligere visuelt hierarki i undermenu'er.</li>
</ul>
<h3>Smartphone: Andelsberegner</h3>
<p>
Andelsberegner eksempel er tilføjet, og JavaScript og CSS er nu inkluderet i design pakken.
</p>
<p class="updaterequired">
Før denne pakke var initialiser og CSS inkluderet via global-variables.js. Da det nu er en del af pakken, kan
stand-alone filerne (https://www.lsb.dk/resp/content/bolig/andelsbolig/beregner/smartphone-filer/s-andelsberegner.css
og https://www.lsb.dk/resp/content/bolig/andelsbolig/beregner/smartphone-filer/i-andelsberegner.js)
slettes fra CMD.
</p>
<h3>Generelt: Opdateret Manipulator</h3>
<p>
Manipulator opdateret til version 0.9.2. Opdateringen indeholder performance optimeringer samt bugfixes.
</p>
</div>
<div class="box">
<h2>Version 1.8.3</h2>
<p>Publiceret: 6. marts 2017</p>
<ul class="actions">
<li class="download"><a href="/packages/update-1_8_3.zip" class="button">Download</a></li>
</ul>
<h3>Smartphone: Mobilbank link (iPhone)</h3>
<p>
Justeret timing på App-åbner side, så "Du har ikke app'en installeret" teksten først
vises efter 3 sekunder.
</p>
<h3>Smartphone: Opdatering af menu</h3>
<ul>
<li>Tilføjet "Retur" label.</li>
<li>Opdateret CSS så undermenu-sektioner uden overskift ikke indrykkes.</li>
<li>Klik på undermenu-sektions overskrift har ikke længere uønsket effekt.</li>
</ul>
<h3>Generelt: Article Splash li uden gradient</h3>
<p>
Ny css klasse no_gradient sørger for at gradienten ikke bliver loadet.
Tilføjet til oversigten på <a href="/docs/frontpage-classes">Forside grid klasser</a>.
</p>
<h3>Generelt: Bullet lister</h3>
<p>
Ny html snippet til bullet og nummerede lister.
Tilføjet til <a href="/eksempler/artikel">Artikel</a> eksemplet.
</p>
<h4>Bullet liste</h4>
<code><ul>
<li>First list item</li>
<li>Second list item</li>
</ul></code>
<h4>Nummereret liste</h4>
<code><ol>
<li>First list item</li>
<li>Second list item</li>
</ol></code>
<h3>Smartphone: Naturlig højde på billeder.</h3>
<p>
Al cropping er fjernet, så billeder i forside grid vises i fuld størrelse
på smartphone segmentet.
</p>
<h3>Desktop: UI til Artikel side.</h3>
<p>
Artikel side UI tilføjet til Desktop segmentet.
</p>
</div>
<div class="box">
<h2>Version 1.8.2</h2>
<p>Publiceret: 7. november 2016</p>
<ul class="actions">
<li class="download"><a href="/packages/update-1_8_2.zip" class="button">Download</a></li>
</ul>
<h3>Mobilbank app/appstore link</h3>
<p class="updaterequired">Kræver opdatering af LSB-koden.</p>
<p>
Links til mobilbank på iOS forsøger nu at åbne App'en direkte.
</p>
<p>urischeme til iOS app tilføjet til u.mobilbank i global-variables.js:</p>
<code>"iosapp":"com.sdc.LanSpar.0400.SDCBankCode0400://open",</code>
<h3>Terms cookie opdateret</h3>
<p class="updaterequired">Kræver opdatering af LSB-koden.</p>
<p>
Terms cookie med versions control via global-variables.js
</p>
<code>u.terms_version = "terms_v1";</code>
<h3>Knapper i artikler</h3>
<p>
Ved hjælp af følgende HTML snippet, kan der laves knapper i artikler.
</p>
<code><ul class="actions">
<li><a href="#" class="button">Knap</a></li>
</ul></code>
<ul class="actions">
<li><a href="#" class="button">Knap</a></li>
</ul>
<h3>Opdateret i:image</h3>
<p>
Der kan nu tilføjes link på billeder, ved at angive et link og en sigende tekst, som vist nedenfor.
</p>
<code><div class="i:image" data-image-src="/img/grid/640x274/eftermiddagshygge.jpg" itemprop="image" itemscope itemtype="https://schema.org/ImageObject">
<span class="image_url" itemprop="url" content="http://test-lsb.parentnode.dk/img/grid/640x274/eftermiddagshygge.jpg"></span>
<span class="image_width" itemprop="width" content="640"></span>
<span class="image_height" itemprop="height" content="274"></span>
<a href="#">Hvor linker du hen?</a>
</div></code>
<h3>Homescreen icon</h3>
<p class="updaterequired">Kræver opdatering af LSB-koden.</p>
<p>
Der er nu inkluderet icon grafik til homescreen bookmarks. Grafikkerne er inkluderet i
pakken, men kræver også at følgende to linier inkluderes i <head>-tagget i HTML'en. Dette er også
implementeret her på test sitet, for reference.
</p>
<code><link rel="apple-touch-icon" href="/package/lsb/external/design/responsive/img/touchicon.png">
<link rel="icon" href="/package/lsb/external/design/responsive/img/favicon.png"></code>
<h3>Desktop UI tilføjet</h3>
<p>
POC forside til desktop segment tilføjet. Demo sitet kan nu tilgås i to versioner:<br />
<a href="?segment=desktop">Desktop udgave</a> (?segment=desktop)<br />
<a href="?segment=smartphone">Smartphone udgave</a> (?segment=smartphone)<br />
</p>
<p>Bemærk: Kun forsiden er fuldt understøttet i desktop udgaven</p>
<h3>Footer opdateret for Desktop</h3>
<p class="updaterequired">Kræver opdatering af LSB-koden.</p>
<p>
Der er foretaget en række justeringer til footeren for at imødekomme Desktop behov. Ændringerne har ikke betydning
for hvordan footeren vises på Smartphone.
</p>
<p>I "contact" sectionen tilføjes:</p>
<code><li class="book"><a href="/ny-kunde">Book møde</a></li></code>
<p>I "help" sectionen tilføjes:</p>
<code><li class="iban"><a href="https://www.lsb.dk/lsb/content/produkter/kort/bortkommet/Artikel">Find IBAN kontonummer</a></li></code>
<p>"areas" sectionen opdateres fuldstændigt til:</p>
<code><li class="areas">
<h2>Om lån &amp; Spar Bank</h2>
<ul>
<li><a href="https://www.lsb.dk/lsb">Presse &amp; IR</a></li>
<li><a href="https://www.lsb.dk/lsb">Job i banken</a></li>
<li><a href="https://www.lsb.dk/lsb">Samfundsansvar</a></li>
<li><a href="https://www.lsb.dk/lsb">Orgnisation</a></li>
<li><a href="https://www.lsb.dk/lsb">Ejerforhold</a></li>
<li><a href="https://www.lsb.dk/lsb">Bankens vision</a></li>
</ul>
</li></code>
<h3>global-variables.js opdateret for Desktop</h3>
<p class="updaterequired">Kræver opdatering af LSB-koden.</p>
<p>Tilføjet tekst til søgefelt:</p>
<code>"search-label":"Søg",</code>
<p>Tilføjet tekst og links til privat/erhverv element i header:</p>
<code>"user-private-text":"Privat",
"user-private-link":"https://www.lsb.dk/lsb",
"user-business-text":"Erhverv",
"user-business-link":"https://www.lsb.dk/lsb/erhverv/forside/",</code>
<p>Tilføjet tekst og links til netbank login element i header:</p>
<code>"netbank-text":"Log på",
"netbank-private-text":"Netbank privat",
"netbank-private-link":"https://www.lsb.dk/lsb/netbank/privat/adgang/logon/",
"netbank-business-text":"Netbank erhverv",
"netbank-business-link":"https://www.lsb.dk/lsb/netbank/erhverv/logon/logon/",
"netbank-quicklook-text":"Konto kik",
"netbank-quicklook-link":"https://www.lsb.dk/lsb/netbank",
"netbank-sign-text":"Aftaler til underskrift",
"netbank-sign-link":"https://www.lsb.dk/lsb/netbank",</code>
<h3>Generel ændring til demo-repos templates</h3>
<p>
Footer inkluderes nu via PHP, for at ungå for meget redundant kode. Kildekoden til
footer findes i templates/snippets/footer.php.
</p>
<p>
Navigation inkluderes nu via PHP, for at ungå for meget redundant kode. Kildekoden til
navigation findes i templates/snippets/navigation.php.
</p>
<h3>Opgraderet Manipulator</h3>
<p>
Manipulator er opgraderet til version 0.9.1.7.
</p>
</div>
<div class="box">
<h2>Version 1.8.1</h2>
<p>Publiceret: 12. juli 2016</p>
<ul class="actions">
<li class="download"><a href="/packages/update-1_8_1.zip" class="button">Download</a></li>
</ul>
<h3>Opdateret "Find rådgivningscenter"</h3>
<p>
Afdelings-detaljer skjules nu som default på "Find rådgivningscenter"
for at give et bedre overblik.
</p>
<p>Opdateringen kræver ikke HTML ændringer!</p>
<h3>Ny list-item type til forside grid</h3>
<p>
Der er tilføjet en ny kompakt list-item type til forside griddet, hvor
det kun er overskriften der vises. Den nye box-type er baseret på en ny
list-item klasse: "compact".
</p>
<code><li class="compact"></code>
<h3>Dokumentation tilføjet</h3>
<p>
Changelog og yderligere dokumentations sider tilføjet til demo-sitet og
kan nu findes i menuen på alle sider.
</p>
<h3>Demo-site omstruktureret</h3>
<p>
HTML filer er ændret til PHP filer, for at være forberedt på en kommende desktop demo.
Der inkluderes nu et detection script (via PHP) i “HTML”-siderne, men indholdet er det
samme og de kan stadig bruges som reference i forhold til hvordan HTML’en skal se ud.
Det har ikke nogen indflydelse på CSS og JS filer.
</p>
<p>
Det betyder at demo-sitet (test-lsb.parentnode.dk) nu automatisk foretager device
detection - så hvis du besøger sitet i en desktop-browser vil det mangle CSS og JS.
For at tilgå smartphone versionen i en desktop-browser kan følgende url bruges:
</p>
<p>
<a href="http://test-lsb.parentnode.dk?segment=smartphone">http://test-lsb.parentnode.dk?segment=smartphone</a>
</p>
</div>
<div class="box">
<h2>Version 1.8</h2>
<p>Publiceret: 28. juni 2016</p>
<ul class="actions">
<li class="download"><a href="/packages/update-1_8.zip" class="button">Download</a></li>
</ul>
<h3>Tilføjet global-variables.js</h3>
<p>
Separat JavaScript fil med desktop- og mobilbank links, cookie tekster tilføjet.
</p>
</div>
<div class="box">
<h2>Version 1.7</h2>
<p>Publiceret: 6. juni 2016</p>
<ul class="actions">
<li class="download"><a href="/packages/update-1_7.zip" class="button">Download</a></li>
</ul>
<h3>Designmæssige justeringer til version 1.6</h3>
<p>
Pakken indeholder kun designmæssige opdateringer til version 1.6.
</p>
</div>
<div class="box">
<h2>Version 1.6</h2>
<p>Publiceret: 23. maj 2016</p>
<ul class="actions">
<li class="download"><a href="/packages/update-1_6.zip" class="button">Download</a></li>
</ul>
<h3>Mergede js og css filer</h3>
<p>
Pakken inkludere nu mergede JavaScript og CSS filer, og fremover skal de mergede filer bruges
i produktions miljøet.
</p>
<h3>Karussel med swipe og slide index</h3>
<p>
Karussellen på forsiden er udvidet med swipe mulighed og slide-index.
</p>
<p>Opdateringen kræver ikke HTML ændringer!</p>
<h3>Youtube video</h3>
<p>
Tilføjet mulighed for at indlejre youtube videoer i sider. Dette gøres ved at indsætte følgende HTML:
</p>
<code><div class="i:youtube" data-youtube-src="https://www.youtube.com/embed/wYcaBicRpVQ" itemprop="video" itemscope itemtype="https://schema.org/VideoObject">
<span class="name" itemprop="name" content="Bank røveriet"></span>
<span class="description" itemprop="description" content="LEGO Film SJOV helt bogstaveligt"></span>
<span class="thumbnail" itemprop="thumbnailUrl" content="https://www.youtube.com/embed/wYcaBicRpVQ"></span>
<span class="upload_date" itemprop="uploadDate" content="2016-05-05"></span>
</div></code>
<h3>Generelt</h3>
<p>
Generelt er der lidt inkonsistens imellem den leverede og den implementerede HTML.
Dette har konsekvenser for søgemaskine optimeringen.
Eksempelvis: <ul class=“info”> elementet mangler på artikler,
<h1 itemprop=“headline”> skal ikke være inde i
<div itemprop=“articleBody”> og itemprop’s der tilhøre artikler
skal ikke bruges på “ikke-artikel”-sider.
</p>
</div>
</div>
<div class="c100">
<div class="box">
<h2>Igangværende opgaver</h2>
<p>Ingen</p>
</div>
<div class="box">
<h2>Tentative opgaver</h2>
<ul>
<li>Generelt: Få lavet kampagne layout i CMD (med ekstra js-inkludering). Estm.: ?</li>
<li>Generelt: Skjul elementer klasser, no_mobile, no_desktop el. lignende. Estm.: ~1 time</li>
<li>Generelt: Afklaring om vi kan have to forskellige forside-lister (desktop/smartphone), så vi slipper for afhængigheder i rækkefølgen, imellem de to grids.</li>
<li>Generelt: Afklaring omkring Detector implementering.</li>
<li>Generelt: Udvidet SEO for artikel-lister (Article i stedet for CreativeWork). Estm.: ~2 timer</li>
<li>Generelt: <br>-tags i overskrifter virker ikke. Det antages at være et CMD-problem - yderligere afklaring foretages af Troels.</li>
<li>Generelt: Bullet lister.</li>
<li>Smartphone: Android Mobilbank link.</li>
<li>Smartphone: Tabelvisning (ved JavaScript manipulation - CMD kode eksempel: https://lsb.dk/resp/content/tabel_test/Test_tabel). Estm.: ~4-6 timer</li>
<li>Smartphone: Test AppBanner metode for iOS og Android.</li>
<li>Smartphone: fleksibel højde på billeder (ok at karussel ikke kan understøtte custom + article)</li>
<li>Desktop: Ny header (lidt lavere, søg ud, login op på linie med servicenav. logo-regler: logo'et skal have luft (så høj som R'et i Spar) over og under.) Estm.: ~2 timer</li>
<li>Desktop: Flere grid muligheder til forsiden (3 x 2/3's højde i højre kolonne) (Brian har layout). Estm.: 3-6 timer</li>
<li>Desktop: Ny article side.</li>
</ul>
</div>
</div>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html><file_sep>/pack.sh
cd theme/www
zip -r new_package.zip js/* css/* img/* global-variables.js -x \*.svn* \*.git* \*.DS* \*js/lib* \*css/lib* \*img/temp*<file_sep>/theme/www/index.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body class="front">
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene front i:front">
<ul class="quicklinks">
<li class="call"><a href="/ring-til-os">Ring til os</a></li>
<li class="mobilbank"><a href="https://www.lsb.dk/lsb/netbank">Mobilbank</a></li>
</ul>
<ul class="articles">
<!-- carousel -->
<li class="carousel c200">
<ul class="carousel">
<li class="splash right aright atop" data-image-src="/img/grid/640x274/ungt_par_i_netto.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Vi Hjælper med <br />dine indkøb</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/kontakt">Kontakt Lån & Spar Bank</a></li>
</ul>
</li>
<li class="splash aleft atop" data-image-src="/img/grid/640x274/eftermiddagshygge.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Job i Lån & Spar</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Se ledige stillinger</a></li>
</ul>
</li>
<!-- CUSTOM AND ARTICLE CURRENTLY NOT ALLOWED IN CAROUSEL -->
<!--li class="custom" data-image-src="/img/grid/640x274/custom_640x274.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Hent den nye Swipp-app</a></li>
</ul>
</li>
<li class="article c100 atop" data-image-src="/img/grid/640x274/trappe_flyt.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Overvejer du forældrekøb?</h2>
<div class="description" itemprop="description">
<p>
Et forældrekøb kan både gavne dit barn og være en god investering for dig. Læs de gode råd om
forældrekøb, inden du køber bolig.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Se dine muligheder</a></li>
</ul>
</li-->
</ul>
</li>
<li class="splash c100 aleft atop" data-image-src="/img/grid/640x274/kontakt_os.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Vi er til at tale med</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/kontakt?param2=1¶m2=2">Kontakt Lån & Spar Bank</a></li>
</ul>
</li>
<li class="article c100 atop" data-image-src="/img/grid/640x274/trappe_flyt.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Overvejer du forældrekøb?</h2>
<div class="description" itemprop="description">
<p>
Et forældrekøb kan både gavne dit barn og være en god investering for dig. Læs de gode råd om
forældrekøb, inden du køber bolig.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Se dine muligheder</a></li>
</ul>
</li>
<li class="article c100 atop" data-image-src="/img/grid/640x274/flytte.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Køb din egen andelsbolig</h2>
<div class="description" itemprop="description">
<p>
Mange studerende tror, at de ikke kan købe en bolig før de er færdige med deres studie.
En andelsbolig kan dog være en rigtig god investering.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Læs mere</a></li>
</ul>
</li>
<li class="splash c100 aleft atop" data-image-src="/img/grid/640x274/eftermiddagshygge.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Job i Lån & Spar</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Se ledige stillinger</a></li>
</ul>
</li>
<li class="article c100" data-image-src="/img/grid/640x274/lsb_symboler.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">God fremgang i basisindtjeningen</h2>
<div class="description" itemprop="description">
<p>
Solid kundevækst i Lån & Spar og god fremgang i toplinjen sikrer en basisindtjening på 95 mio. kr.
i første halvår af 2015.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Læs pressemeddelsen</a></li>
</ul>
</li>
<li class="article c100" data-image-src="/img/grid/640x274/roed_bil.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Få et af landets billigste billån</h2>
<div class="description" itemprop="description">
<p>
Som medlem af en af vores samarbejds-organisationer kan du få et af
Danmarks billigste billån.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Læs om det billige billån</a></li>
</ul>
</li>
<li class="splash c100 atop" data-image-src="/img/grid/640x274/find_rc.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Besøg et af vores 20 rådgningscentre i hele landet</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/find-center">Find dit rådgivningscenter</a></li>
</ul>
</li>
<li class="compact c100" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Få en fleksibel boligøkonomi</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Konverter din pension</a></li>
</ul>
</li>
<li class="compact c100" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Køb din egen andelsbolig</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Konverter din pension</a></li>
</ul>
</li>
<li class="compact c100" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Job i Lån & Spar</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Konverter din pension</a></li>
</ul>
</li>
<li class="article c100 atop" data-image-src="/img/grid/640x274/studieB.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Få DK's bedste Studiekonto</h2>
<div class="description" itemprop="description">
<p>
Som studerende kan du få Danmarks bedste studiekonto i Lån & Spar Bank.
Få bl.a. en lønkonto med høj rente og en billig kassekredit.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Se alle fordelene og søg studiekonto</a></li>
</ul>
</li>
<!-- single first (custom) item -->
<li class="custom c100" data-image-src="/img/grid/640x274/custom_640x274.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Hent den nye Swipp-app</a></li>
</ul>
</li>
<li class="article c100" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Aktuelt</h2>
<ul class="links">
<li><a href="/artikel">Halvårsrapport 2015</a></li>
<li><a href="/artikel">Nye kontaktløse kort</a></li>
<li><a href="/artikel">Tilmeld dig nyhedsbrevet</a></li>
<li><a href="/artikel">Læg din pension om og få skatterabat</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html><file_sep>/theme/www/kampagner.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body>
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene campaign i:campaign">
<div class="c200 box">
<h1>Kampagne sider</h1>
<ul>
<li><a href="https://2017-05-dsr.lsb-kampagne.dk">2017/05 - DSR</a> - Dansk Sygeplejeråd</li>
<li><a href="https://2017-09-dm.lsb-kampagne.dk">2017/09 - DM</a> - Dansk Magisterforening</li>
<li><a href="https://2017-09-djof.lsb-kampagne.dk">2017/09 - DJØF</a> - Danmarks Jurist- og Økonomforbund</li>
<li><a href="https://2017-10-bolig.lsb-kampagne.dk">2017/05 - Bolig kampagne</a></li>
<li><a href="https://2017-11-dlf.lsb-kampagne.dk">2017/05 - DLF</a> - Dansk Lærerforening</li>
<li><a href="https://baby.lsb-kampagne.dk">2017/12 - Navnemaskine</a></li>
<li><a href="https://leads.lsb-kampagne.dk">2018/05 - Leads indsamler</a></li>
</ul>
</div>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html><file_sep>/theme/www/ring-til-os.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body class="call">
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene call i:call">
<div class="box">
<div class="i:image" data-image-src="/img/grid/640x274/kontakt_os"></div>
<h1>Ring til os</h1>
<h2>Kundeservice</h2>
<p>3378 2000</p>
<h2>Netbank spørgsmål</h2>
<p>3378 1929</p>
<p>
Telefonerne er åbne:<br />
Mandag - torsdag kl. 9.00 - 18.00<br />
Fredag kl. 9.00 - 17.00<br />
<br />
Lørdag og søndag holder vi lukket.
</p>
<ul class="links">
<li><a href="/artikel">Undgå lang ventetid i telefonen</a></li>
<li><a href="/find-center">Ring til dit rådgivningscenter</a></li>
</ul>
</div>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html><file_sep>/theme/www/js/lib/seg_desktop_include.js
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/manipulator/v0_9_2/merged/seg_desktop.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/desktop/u-basics.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/u-basics.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/desktop/i-page.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/desktop/i-front.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/desktop/i-article.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/desktop/i-related.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/desktop/i-image.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/desktop/i-youtube.js"></script>');
document.write('<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/desktop/i-andelsberegner.js"></script>');
<file_sep>/theme/www/ny-kunde.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body>
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene contact i:contact">
<div class="c200 box">
<div class="i:image" data-image-src="/img/grid/640x274/kontakt_os"></div>
<h1>Skift bank og bliv kunde i en bank, hvor det handler om dig</h1>
<p>
Vi har fokus på dig. Du får personlig rådgivning og gode råd om din økonomi - både nu og på sigt.
</p>
<!-- HTML DEFINED BY LSB FORM COMPONENT -->
<div id="j_id_4" class="appmessages nomessages"></div>
<form id="mainform" name="mainform" method="post" action="?view=1604856420" class="i:form" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="javax.faces.encodedURL" value="/customercontact-web/views/simpleresponsive/index.xhtml">
<div id="mainform:j_id_7" class="appmessages nomessages"></div>
<div id="mainform:j_id_8" class="fieldSet singleColumnLayout">
<div id="mainform:j_id_a" class="field">
<div class="fieldInput below">
<input id="mainform:j_id_b" name="mainform:j_id_b" type="text" value="" title="Fulde navn">
</div>
</div>
<div id="mainform:j_id_c" class="field">
<div class="fieldInput below">
<input id="mainform:j_id_d" name="mainform:j_id_d" type="text" value="" maxlength="4" size="4" title="Postnr.">
</div>
</div>
<div id="mainform:j_id_e" class="field">
<div class="fieldInput below">
<input id="mainform:j_id_f" name="mainform:j_id_f" type="text" value="" title="Telefon">
</div>
</div>
<div id="mainform:j_id_g" class="field">
<div class="fieldInput below">
<input id="mainform:j_id_h" name="mainform:j_id_h" type="text" value="" title="E-mail-adresse">
</div>
</div>
<div id="mainform:j_id_i" class="field">
<div class="fieldInput below">
<textarea name="mainform:j_id_j" title="Skriv din besked her"></textarea>
</div>
</div>
</div>
<ul class="actions">
<li class="send">
<input id="mainform:j_id_l" name="mainform:j_id_l" type="submit" value="Send besked" class="button">
</li>
</ul>
<input type="hidden" name="mainform_SUBMIT" value="1">
<input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="<KEY>9SMBz2RgpvPiwDILvLU4GRIL9fX22Y81LL5sqMSE21aahP6Ifw==">
</form>
<p>Du kan også ringe til Kundeservice på telefon 3378 2000, eller kigge forbi et af vores <a href="/find-center">rådgivningscentre</a>.</p>
</div>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html><file_sep>/theme/templates/snippets/head.php
<?php include_once($_SERVER["FRAMEWORK_PATH"]."/includes/segment.php") ?>
<?php include_once($_SERVER["FRAMEWORK_PATH"]."/includes/functions.inc.php") ?>
<title>Din personlige bank - Lån & Spar Bank</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="Lån & Spar Bank" />
<meta name="keywords" content="" />
<meta name="viewport" content="initial-scale=1, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="apple-touch-icon" href="/package/lsb/external/design/responsive/img/touchicon.png">
<link rel="icon" href="/package/lsb/external/design/responsive/img/favicon.png">
<? if($_SESSION["dev"]) : ?>
<link type="text/css" rel="stylesheet" media="all" href="/package/lsb/external/design/responsive/css/lib/seg_<?= $_SESSION["segment"] ?>_include.css?cb=<?= randomKey(8) ?>" />
<script type="text/javascript" src="/package/lsb/external/design/responsive/js/lib/seg_<?= $_SESSION["segment"] ?>_include.js?cb=<?= randomKey(8) ?>"></script>
<? else: ?>
<link type="text/css" rel="stylesheet" media="all" href="/package/lsb/external/design/responsive/css/seg_<?= $_SESSION["segment"] ?>.css?cb=<?= randomKey(8) ?>" />
<script type="text/javascript" src="/package/lsb/external/design/responsive/js/seg_<?= $_SESSION["segment"] ?>.js?cb=<?= randomKey(8) ?>"></script>
<? endif; ?>
<script type="text/javascript" src="/global-variables.js"></script>
<file_sep>/theme/www/docs/frontpage-classes.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body class="docs">
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene docs front i:front">
<div class="box">
<h1>Forside grid klasser</h1>
<p>
Denne side viser de forskellige layout og billed-alignment muligheder for forside griddet.
Layout og alignment styres via CSS klasser på de individuelle <li>. De anvendte klasser
er anført som overskrift i hvert af de nedenstående eksempler.
</p>
</div>
<ul class="articles">
<!-- SPLASH VARIATIONS -->
<li class="splash c100" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">splash</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="splash c100 atop" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">splash atop</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="splash c100 aleft atop" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">splash aleft atop</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="splash c100 aright atop" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">splash aright atop</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="splash c100 abottom" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">splash abottom</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="splash c100 aleft abottom" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">splash aleft abottom</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="splash c100 aright abottom" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">splash aright abottom</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="splash c100 right" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">splash right</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="splash c100 no_gradient" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">splash no_gradient</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<!-- ARTICLE VARIATIONS -->
<li class="article c100" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">article</h2>
<div class="description" itemprop="description">
<p>
"Kort beskrivelse" kan kun bruges under "article"-typer, og bør ikke overskride 140 tegn. Denne beskrivelse er lige præcis 140 tegn lang.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="article c100 atop" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">article atop</h2>
<div class="description" itemprop="description">
<p>
"Kort beskrivelse" kan kun bruges under "article"-typer, og bør ikke overskride 140 tegn. Denne beskrivelse er lige præcis 140 tegn lang.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="article c100 aleft atop" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">article aleft atop</h2>
<div class="description" itemprop="description">
<p>
"Kort beskrivelse" kan kun bruges under "article"-typer, og bør ikke overskride 140 tegn. Denne beskrivelse er lige præcis 140 tegn lang.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="article c100 aright atop" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">article aright atop</h2>
<div class="description" itemprop="description">
<p>
"Kort beskrivelse" kan kun bruges under "article"-typer, og bør ikke overskride 140 tegn. Denne beskrivelse er lige præcis 140 tegn lang.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="article c100 abottom" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">article abottom</h2>
<div class="description" itemprop="description">
<p>
"Kort beskrivelse" kan kun bruges under "article"-typer, og bør ikke overskride 140 tegn. Denne beskrivelse er lige præcis 140 tegn lang.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="article c100 aleft abottom" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">article aleft abottom</h2>
<div class="description" itemprop="description">
<p>
"Kort beskrivelse" kan kun bruges under "article"-typer, og bør ikke overskride 140 tegn. Denne beskrivelse er lige præcis 140 tegn lang.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="article c100 aright abottom" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">article aright abottom</h2>
<div class="description" itemprop="description">
<p>
"Kort beskrivelse" kan kun bruges under "article"-typer, og bør ikke overskride 140 tegn. Denne beskrivelse er lige præcis 140 tegn lang.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="compact c100" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">compact</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
<li class="custom c100" data-image-src="/img/grid/gx_alignment-640x540.png" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">custom</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/eksempler/artikel">Link</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html><file_sep>/theme/www/js/lib/desktop/i-front.js
Util.Objects["front"] = new function() {
this.init = function(scene) {
u.bug("init front")
scene.resized = function() {
// stop carousel and update slide width
// start carousel when resizing is finished
var carousel = u.qs("li.carousel", this);
if(carousel && carousel.slides && carousel.slides.length > 1) {
u.t.resetTimer(this.t_redraw);
u.t.resetTimer(carousel.t_rotate);
// this.t_redraw = u.t.setTimer(carousel, carousel.nextSlide, 3000);
carousel.slide_width = carousel.slides[0].offsetWidth;
}
}
scene.ready = function() {
// activate article links
var nodes = u.qsa("ul.articles > li", this);
var i, node;
for(i = 0; node = nodes[i]; i++) {
node.scene = this;
node._image_src = node.getAttribute("data-image-src");
node._type = node.className.match(/c[0-9]+/);
// carousel box
if(u.hc(node, "carousel")) {
u.initCarousel(node);
}
// custom box
else if(u.hc(node, "custom")) {
u.initCustom(node);
}
// compact box
else if(u.hc(node, "compact")) {
u.initCompact(node);
}
// splash box
else if(u.hc(node, "splash")) {
u.initSplash(node);
}
// article box
else if(u.hc(node, "article")) {
u.initArticle(node);
}
// extra decoration
if(u.hc(node, "squares")) {
u.initSquares(node);
}
// make sure sizes are adjusted appropriately
page.resized();
}
}
scene.ready();
}
}<file_sep>/theme/www/js/lib/desktop/u-basics.js
// init custom list node
u.initCustom = function(node) {
// u.bug("initCustom");
u.ce(node, {"type":"link"});
if(node._image_src) {
node._image = u.ie(node, "div", {"class":"image"});
var size;
if(node._type == "c200") {
size = "840x360";
}
else {
size = "640x540";
}
if(node._type == "related") {
u.ae(node._image, "img", {"src":node._image_src.replace(/[\d]+x[\d]+/g, size)});
}
else {
u.as(node._image, "backgroundImage", "url("+node._image_src.replace(/[\d]+x[\d]+/g, size)+")")
}
}
}
// init article list node
u.initArticle = function(node) {
// u.bug("initArticle");
u.ce(node, {"type":"link"});
if(node._image_src) {
node._image = u.ie(node, "div", {"class":"image"});
var size = "640x274";
if(node._type == "related") {
u.ae(node._image, "img", {"src":node._image_src.replace(/[\d]+x[\d]+/g, size)});
}
else {
u.as(node._image, "backgroundImage", "url("+node._image_src.replace(/[\d]+x[\d]+/g, size)+")")
}
}
}
// init splash list node
u.initSplash = function(node) {
// u.bug("initSplash");
u.ce(node, {"type":"link"});
if(node._image_src) {
node._image = u.ie(node, "div", {"class":"image"});
if(!u.hc(node, "no_gradient")) {
u.ie(node._image, "div", {"class":"gradient"});
}
var size;
if(node._type == "c200") {
size = "840x360";
}
else {
size = "640x540";
}
if(node._type == "related") {
u.ae(node._image, "img", {"src":node._image_src.replace(/[\d]+x[\d]+/g, size)});
}
else {
u.as(node._image, "backgroundImage", "url("+node._image_src.replace(/[\d]+x[\d]+/g, size)+")")
}
}
node._h2 = u.qs("h2", node);
u.wc(node._h2, "span");
}
<file_sep>/theme/www/eksempler/artikel-splash.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body>
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene article i:article">
<div class="article splash" itemscope itemtype="http://schema.org/Article">
<ul class="info">
<li class="published_at" itemprop="datePublished" content="2015-01-05">5. januar 2015</li>
<li class="modified_at" itemprop="dateModified" content="2015-01-05"></li>
<li class="author" itemprop="author" content="<NAME>"></li>
<li class="main_entity share" itemprop="mainEntityOfPage" content="http://test-lsb.parentnode.dk/artikel"></li>
<li class="publisher" itemprop="publisher" itemscope itemtype="https://schema.org/Organization">
<ul class="publisher_info">
<li class="name" itemprop="name" content="lsb.dk"></li>
<li class="logo" itemprop="logo" itemscope itemtype="https://schema.org/ImageObject">
<span class="image_url" itemprop="url" content="http://test-lsb.parentnode.dk/img/logo-large.png"></span>
<span class="image_width" itemprop="width" content="720"></span>
<span class="image_height" itemprop="height" content="405"></span>
</li>
</ul>
</li>
</ul>
<div class="i:image" data-image-src="/img/grid/640x274/eftermiddagshygge.jpg" itemprop="image" itemscope itemtype="https://schema.org/ImageObject">
<span class="image_url" itemprop="url" content="http://test-lsb.parentnode.dk/img/grid/640x274/eftermiddagshygge.jpg"></span>
<span class="image_width" itemprop="width" content="640"></span>
<span class="image_height" itemprop="height" content="274"></span>
</div>
<h1 itemprop="headline">Dette er en <br />splash <br>artikel side</h1>
<div class="articlebody" itemprop="articleBody">
<p>
Denne variant adskiller sig ved at overskriften placeres oven på billedet.
Dette gøres ved at tilføje en "splash" klasse til artikel div'et.
</p>
<code><div class="article splash" itemscope itemtype="http://schema.org/Article"></code>
<p>
Bortset fra dette er denne variant magen til en default artikel.
</p>
</div>
</div>
<div class="related i:related">
<ul class="articles">
<li class="article" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Link liste</h2>
<ul class="links">
<li><a href="/artikel">Halvårsrapport 2015</a></li>
<li><a href="/artikel">Nye kontaktløse kort</a></li>
<li><a href="/artikel">Tilmeld dig nyhedsbrevet</a></li>
<li><a href="/artikel">Læg din pension om og få skatterabat</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html><file_sep>/theme/www/artikel.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body>
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene article i:article">
<div class="article" itemscope itemtype="http://schema.org/Article">
<ul class="info">
<li class="published_at" itemprop="datePublished" content="2015-01-05">5. januar 2015</li>
<li class="modified_at" itemprop="dateModified" content="2015-01-05"></li>
<li class="author" itemprop="author" content="<NAME>"></li>
<li class="main_entity share" itemprop="mainEntityOfPage" content="http://test-lsb.parentnode.dk/artikel"></li>
<li class="publisher" itemprop="publisher" itemscope itemtype="https://schema.org/Organization">
<ul class="publisher_info">
<li class="name" itemprop="name" content="lsb.dk"></li>
<li class="logo" itemprop="logo" itemscope itemtype="https://schema.org/ImageObject">
<span class="image_url" itemprop="url" content="http://test-lsb.parentnode.dk/img/logo-large.png"></span>
<span class="image_width" itemprop="width" content="720"></span>
<span class="image_height" itemprop="height" content="405"></span>
</li>
</ul>
</li>
</ul>
<div class="i:image" data-image-src="/img/grid/640x274/eftermiddagshygge.jpg" itemprop="image" itemscope itemtype="https://schema.org/ImageObject">
<span class="image_url" itemprop="url" content="http://test-lsb.parentnode.dk/img/grid/640x274/eftermiddagshygge.jpg"></span>
<span class="image_width" itemprop="width" content="640"></span>
<span class="image_height" itemprop="height" content="274"></span>
</div>
<h1 itemprop="headline">Consectetur adipisicing elit minim</h1>
<div class="articlebody" itemprop="articleBody">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Ut enim ad minim veniam, quis <a href="/artikel-seo">nostrud exercitation</a> ullamco
laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur.
</p>
<div class="i:image" data-image-src="/img/grid/640x274/eftermiddagshygge.jpg" itemprop="image" itemscope itemtype="https://schema.org/ImageObject">
<span class="image_url" itemprop="url" content="http://test-lsb.parentnode.dk/img/grid/640x274/eftermiddagshygge.jpg"></span>
<span class="image_width" itemprop="width" content="640"></span>
<span class="image_height" itemprop="height" content="274"></span>
</div>
<p>
Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<h2>Secondary headline</h2>
<p>
Lorem ipsum dolor sit amet, +4520742819 consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim 2074 2819 ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat. Duis aute 20 74 28 19 irure dolor in reprehenderit in
voluptate velit esse cillum dolore telefon 20742819 eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia telefon 2074 2819 deserunt mollit anim id est laborum. Eller telefon 20 74 28 19.
</p>
<h3>Bullet list</h3>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Forth list item</li>
</ul>
<div class="i:youtube2" data-youtube-src="https://www.youtube.com/embed/wYcaBicRpVQ" itemprop="video" itemscope itemtype="https://schema.org/VideoObject">
<span class="name" itemprop="name" content="Bank røveriet"></span>
<span class="description" itemprop="description" content="LEGO Film SJOV helt bogstaveligt"></span>
<span class="thumbnail" itemprop="thumbnailUrl" content="https://www.youtube.com/embed/wYcaBicRpVQ"></span>
<span class="upload_date" itemprop="uploadDate" content="2016-05-05"></span>
</div>
<p>
Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<h3>Number list</h3>
<ol>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Forth list item</li>
</ol>
<p>
Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt <a href="/artikel">mollit anim id est laborum</a>.
</p>
</div>
</div>
<div class="related i:related">
<ul class="articles">
<li class="article" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Aktuelt</h2>
<ul class="links">
<li><a href="/artikel">Halvårsrapport 2015</a></li>
<li><a href="/artikel">Nye kontaktløse kort</a></li>
<li><a href="/artikel">Tilmeld dig nyhedsbrevet</a></li>
<li><a href="/artikel">Læg din pension om og få skatterabat</a></li>
</ul>
</li>
<li class="splash aleft atop" data-image-src="/img/grid/640x274/kontakt_os.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Vi er til at tale med</h2>
<ul class="actions">
<li class="more" itemprop="url"><a href="/kontakt?param2=1¶m2=2">Kontakt Lån & Spar Bank</a></li>
</ul>
</li>
<li class="article atop" data-image-src="/img/grid/640x274/flytte" itemscope itemtype="http://schema.org/CreativeWork">
<h2 itemprop="headline">Køb din egen andelsbolig</h2>
<div class="description" itemprop="description">
<p>
Mange studerende tror, at de ikke kan købe en bolig før de er færdige med deres studie.
En andelsbolig kan dog være en rigtig god investering.
</p>
</div>
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Læs mere</a></li>
</ul>
</li>
<li class="custom" data-image-src="/img/grid/640x274/custom_640x274.jpg" itemscope itemtype="http://schema.org/CreativeWork">
<ul class="actions">
<li class="more" itemprop="url"><a href="/artikel">Hent den nye Swipp-app</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html><file_sep>/theme/www/find-center.php
<!DOCTYPE html>
<html lang="da">
<head>
<?php include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/head.php") ?>
</head>
<body>
<div id="page" class="i:page">
<div id="header">
<ul class="servicenavigation">
<li class="navigation"><a href="#navigation">Hovedmenu</a></li>
<li class="home"><a href="/">Forsiden</a></li>
</ul>
</div>
<div id="content">
<div class="scene findcenter i:findcenter">
<div class="box">
<div class="i:image" data-image-src="/img/grid/640x274/find_rc"></div>
<h1>Find dit rådgivningscenter</h1>
</div>
<ul class="regions">
<li class="region">
<h2>København</h2>
<ul class="branches">
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Amager</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">3266 1600</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Amagerbrogade 52</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">2300</span> <span class="city" itemprop="addressLocality">København S</span></li>
</ul>
</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Brønshøj</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">3827 5500</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Frederikssundsvej 154D</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">2700</span> <span class="city" itemprop="addressLocality">Brønshøj</span></li>
</ul>
</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Frederiksberg - Falkoner</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">3815 5000</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Rolighedsvej 6</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1958</span> <span class="city" itemprop="addressLocality">Frederiksberg C</span></li>
</ul>
</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Frederiksberg - Gl. Kongevej</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">3821 7100</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Møllegade 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">2200</span> <span class="city" itemprop="addressLocality">København N</span></li>
</ul>
</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Frederiksberg - <NAME></h3>
<ul class="info">
<li class="telephone" itemprop="telephone">3816 6200</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Højbro Plads</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">3378 2300</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
<li class="description" itemprop="description">Højbro Plads har kassebetjening</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Nørreport</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">3338 2400</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
<li class="description" itemprop="description">Nørreport har kassebetjening</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Valby</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">3618 8100</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Vesterbro</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">3378 2200</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
<li class="description" itemprop="description">Vesterbro har kassebetjening</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Østerbro</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">3547 1700</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li class="region">
<h2>Sjælland</h2>
<ul class="branches">
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Glostrup</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">4325 2500</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Hellerup</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">3945 8900</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Hillerød</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">4829 7700</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Lyngby</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">4520 2600</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
<li class="description" itemprop="description">Lyngby har kassebetjening</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Roskilde</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">4631 2900</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li class="region">
<h2>Fyn/Jylland</h2>
<ul class="branches">
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Esbjerg</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">7613 4800</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Kolding</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">7630 4600</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Odense</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">6314 3000</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Aalborg</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">9936 4400</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
<li class="description" itemprop="description">Nørreport har kassebetjening</li>
</ul>
</li>
<li class="branch" itemscope itemtype="http://schema.org/LocalBusiness">
<h3 class="name" itemprop="name">Aarhus</h3>
<ul class="info">
<li class="telephone" itemprop="telephone">8932 4500</li>
<li class="email" itemprop="email"><a href="mailto:<EMAIL>"><EMAIL></a></li>
<li class="address">
<ul class="address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<li class="address" itemprop="streetAddress">Gadenavn 253</li>
<li class="postalcity"><span class="postal" itemprop="postalCode">1234</span> <span class="city" itemprop="addressLocality">Byernes By</span></li>
</ul>
</li>
<li class="description" itemprop="description">Aarhus har kassebetjening</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div id="navigation">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/navigation.php") ?>
</div>
<div id="footer">
<? include_once($_SERVER["LOCAL_PATH"]."/templates/snippets/footer.php") ?>
</div>
</div>
</body>
</html> | 39de063aa27c31e228a2cfdda7682129a7fb9f92 | [
"JavaScript",
"PHP",
"Shell"
] | 26 | JavaScript | kaestel/lsb_dk | ecb589a29a9f6180300314889c5aa94450884e5b | ddc54741d0fbbcbf93b98bffd9461f5ca51e8c19 |
refs/heads/master | <file_sep>"use strict";
function copyObject(obj) {
var key;
var copy = {};
for (key in obj) {
if(obj.hasOwnProperty(key)) {
copy[key] = obj[key];
}
}
return copy;
}
module.exports = copyObject;
<file_sep>'use strict';
function analogSlice(arr, param1, param2) {
let start = param1;
let end = param2;
let resultArr = [];
start = isNaN(start) ? 0 : start;
end = isNaN(end) ? arr.length : end;
function processNegativeIndex(arg) {
return arg < 0 ? arg + arr.length : arg;
}
start = processNegativeIndex(start);
end = processNegativeIndex(end);
for (start; start < end; start++) {
resultArr.push(arr[start]);
}
return resultArr;
}
module.exports = analogSlice;
<file_sep>"use strict";
function insertStr(str, word, n) {
var arrWords = str.split(' ');
var epmtyRemove;
var position = n + 1;
epmtyRemove = arrWords.splice(position, arrWords.length, word);
arrWords.push(epmtyRemove);
return arrWords.join(' ');
}
module.exports = insertStr;
<file_sep>'use strict'
function scanDOM() {
const nodes = document.body.childNodes;
let statistic = {};
statistic.tag = {};
statistic.elemWithClass = {};
statistic.nodeText = 0;
function sort(nodes) {
for(let i = 0; i < nodes.length; i++) {
if(nodes[i].nodeType === 1) {
if(nodes[i].nodeName in statistic.tag ) {
statistic.tag[nodes[i].nodeName]++;
} else {
statistic.tag[nodes[i].nodeName] = 1;
}
if(nodes[i].className !== '') {
for(let j = 0; j < nodes[i].classList.length; j++){
if (nodes[i].classList[j] in statistic.elemWithClass) {
statistic.elemWithClass[nodes[i].classList[j]]++;
} else {
statistic.elemWithClass[nodes[i].classList[j]] = 1;
}
}
}
if (nodes[i].hasChildNodes()) {
sort(nodes[i].childNodes);
}
} else if (nodes[i].nodeType === 3) {
statistic.nodeText++;
}
}
}
sort(nodes);
printAnswer(statistic);
}
function printAnswer(obj) {
let objSmall;
for(let key in obj) {
if(!(obj[key] instanceof Object)) {
console.log('Текстовых узлов : ' + obj[key]);
} else {
if(obj[key].length === 0) {
continue;
}
objSmall = obj[key];
for(let keySmall in objSmall) {
if(key === "tag") {
console.log('Тегов ' + keySmall + ': ' + objSmall[keySmall]);
} else {
console.log('Элементов с классом ' + keySmall + ': ' + objSmall[keySmall]);
}
}
}
}
}
scanDOM();<file_sep>'use strict'
function deleteTextNodes(node) {
if (node.hasChildNodes()) {
for(var i = 0; i < node.childNodes.length; i++) {
console.log('i: ', i,' child: ', node.childNodes[i]);
if (node.childNodes[i].nodeType === 3) {
console.log('Remoute: ', node.childNodes[i]);
node.removeChild(node.childNodes[i]);
//"ChildNodes" живая коллекция, потому что после удаления следующий узел займет индекс удаленного узла
i--;
}
}
console.log('innerHTML:', document.body.innerHTML);
} else {
console.log('Element does not contain text-nodes.');
}
}
deleteTextNodes(document.body);<file_sep>"use strict";
function defineType(value) {
var type_value = typeof value;
var result = undefined;
switch (type_value) {
case 'string':
result = 'string';
break;
case 'number':
result = 'number';
break;
default:
break;
}
return result;
}
module.exports = defineType;
<file_sep>"use strict";
function getTypeOfNumber(numeric) {
var i;
if ((numeric < 1) || (numeric > 1000)) {
return 'Данные неверны';
}
for (i = 2; i < Math.round(Math.sqrt(numeric)); i++) {
if (!(numeric % i)) {
return `Число ${numeric} - составное число`;
}
}
return `Число ${numeric} - простое число`;
}
module.exports = getTypeOfNumber;
<file_sep>"use strict";
function compareElementsOfArray(arr) {
var i;
for (i = 0; i < arr.length - 1;) {
if (arr[i] !== arr[++i]) {
return false;
}
}
return true;
}
module.exports = compareElementsOfArray;
<file_sep>"use strict";
function addPropertyOfObj(str, obj) {
var object = obj;
if (!object.hasOwnProperty(str)) {
object[str] = 'new';
}
return obj;
}
module.exports = addPropertyOfObj;
<file_sep>"use strict";
function searchProperty(str, obj) {
return obj.hasOwnProperty(str);
}
module.exports = searchProperty;
<file_sep>"use strict";
function searchSubstr(str, substrs) {
if (~str.indexOf(substrs)) {
return true;
}
return false;
}
module.exports = searchSubstr;
<file_sep>"use strict";
function deleteSpace(str) {
return str.replace(/^[\s]+|[\s]+$/g, '');
}
module.exports = deleteSpace;
<file_sep>'use strict';
var initialValueExist = {
YES: 0,
NO: 1
};
function analogReduce(array, callback, initialValue) {
var i = initialValue ? initialValueExist.YES : initialValueExist.NO;
var previousValue = initialValue ? initialValue : array[0];
for(; i < array.length; i++) {
previousValue = callback(previousValue,array[i], i, array);
}
return previousValue;
}
module.exports = analogReduce;
<file_sep>"use strict";
var Animals = {
vid: 'Mammals',
numberOfSpecies: 20000
};
var zebra = Object.create(Animals);
zebra.vid = "four - legged";
function searchInPrototypes(prop, obj) {
return obj.__proto__[prop];
}
searchInPrototypes('vid', zebra);
module.exports = searchInPrototypes;<file_sep>"use strict";
function sumNumbers(addend1, addend2) {
return +((addend1 + addend2).toFixed(3));
}
module.exports = sumNumbers;
<file_sep>"use strict";
function reversedStr(str) {
var arrWords = str.split('');
return arrWords.reverse().join('');
}
module.exports = reversedStr;
| ff90a65ae000d4e468e6f21220c5c2d7a9621fba | [
"JavaScript"
] | 16 | JavaScript | Tochilina/external-courses | 3d0067b579ee1d50cf75cf2caddd984efb338929 | b58ee0d199eae47dec9d4bca6fe576e1c88a231d |
refs/heads/master | <file_sep># mysite
My first django project and also GitHub repository
<file_sep>from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Question(models.Model):
number = models.IntegerField(default=0) | cf116438e0144c06df4c63192e53844ad766d728 | [
"Markdown",
"Python"
] | 2 | Markdown | ananth1996/mysite | de938fbac6bc33706c4af210d0578182762a36b2 | fad088252924b569a847d5364e52ed0c0956aba8 |
refs/heads/master | <file_sep>from rest_framework.authtoken.models import Token
from .models import Student
from .serializers import StudentSerializer
from rest_framework import viewsets
from rest_framework.authentication import BasicAuthentication, SessionAuthentication, TokenAuthentication
from rest_framework.permissions import AllowAny, IsAdminUser, IsAuthenticated, IsAuthenticatedOrReadOnly, DjangoModelPermissions, DjangoModelPermissionsOrAnonReadOnly, DjangoObjectPermissions
class StudentMVS(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
| 08019c493cea03d5d237093c19afc12995190399 | [
"Python"
] | 1 | Python | rizwanch786/token_authentication | 99b881daf3b2bbea65f09aa99c357026d1d118b1 | 9943ecb7348e6ff56cde8bb49c38b9de829d7481 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
from __future__ import print_function
import os
import copy
from keras import backend as K
from keras.backend import tf
from keras import callbacks as cbks
# import numpy as np
from keras import optimizers, objectives
from keras.engine.training import _collect_metrics, _weighted_masked_objective
from keras import metrics as metrics_module
import six
def data_to_tfrecord(images, labels, filename):
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
""" Save data into TFRecord """
if not os.path.isfile(filename):
num_examples = images.shape[0]
rows = images.shape[1]
cols = images.shape[2]
depth = images.shape[3]
print('Writing', filename)
writer = tf.python_io.TFRecordWriter(filename)
for index in range(num_examples):
image_raw = images[index].tostring()
example = tf.train.Example(features=tf.train.Features(feature={
'height': _int64_feature(rows),
'width': _int64_feature(cols),
'depth': _int64_feature(depth),
'label': _int64_feature(int(labels[index])),
'image_raw': _bytes_feature(image_raw)}))
writer.write(example.SerializeToString())
writer.close()
else:
print('tfrecord already exist')
def read_and_decode(filename, one_hot=True, n_class=None, is_train=None):
""" Return tensor to read from TFRecord """
filename_queue = tf.train.string_input_producer([filename])
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(serialized_example,
features={
'label': tf.FixedLenFeature([], tf.int64),
'image_raw' : tf.FixedLenFeature([], tf.string),
})
# You can do more image distortion here for training data
img = tf.decode_raw(features['image_raw'], tf.uint8)
img.set_shape([28*28])
img = tf.reshape(img, [28, 28, 1])
img = tf.cast(img, tf.float32) * (1. / 255) - 0.5
# img = tf.cast(img, tf.float32) * (1. / 255)
label = tf.cast(features['label'], tf.int32)
if one_hot and n_class:
label = tf.one_hot(label,n_class)
return img, label
def compile_tfrecord(train_model, optimizer, loss, out_tensor_lst, metrics=[], loss_weights=None):
train_model.build(train_model)
# train_model.build()
train_model.optimizer = optimizers.get(optimizer)
train_model.loss = loss
train_model.loss_weights = loss_weights
# prepare loss weights
if loss_weights is None:
loss_weights_list = [1. for _ in range(len(train_model.outputs))]
elif isinstance(loss_weights, dict):
for name in loss_weights:
if name not in train_model.output_names:
raise ValueError('Unknown entry in loss_weights '
'dictionary: "' + name + '". '
'Only expected the following keys: ' +
str(train_model.output_names))
loss_weights_list = []
for name in train_model.output_names:
loss_weights_list.append(loss_weights.get(name, 1.))
elif isinstance(loss_weights, list):
if len(loss_weights) != len(train_model.outputs):
raise ValueError('When passing a list as loss_weights, '
'it should have one entry per model outputs. '
'The model has ' + str(len(train_model.outputs)) +
' outputs, but you passed loss_weights=' +
str(loss_weights))
loss_weights_list = loss_weights
else:
raise TypeError('Could not interpret loss_weights argument: ' +
str(loss_weights) +
' - expected a list of dicts.')
# prepare loss functions
if isinstance(loss, dict):
for name in loss:
if name not in train_model.output_names:
raise ValueError('Unknown entry in loss '
'dictionary: "' + name + '". '
'Only expected the following keys: ' +
str(train_model.output_names))
loss_functions = []
for name in train_model.output_names:
if name not in loss:
raise ValueError('Output "' + name +
'" missing from loss dictionary.')
loss_functions.append(objectives.get(loss[name]))
elif isinstance(loss, list):
if len(loss) != len(train_model.outputs):
raise ValueError('When passing a list as loss, '
'it should have one entry per model outputs. '
'The model has ' + str(len(train_model.outputs)) +
' outputs, but you passed loss=' +
str(loss))
loss_functions = [objectives.get(l) for l in loss]
else:
loss_function = objectives.get(loss)
loss_functions = [loss_function for _ in range(len(train_model.outputs))]
train_model.loss_functions = loss_functions
weighted_losses = [_weighted_masked_objective(fn) for fn in loss_functions]
# prepare metrics
train_model.metrics = metrics
train_model.metrics_names = ['loss']
train_model.metrics_tensors = []
# compute total loss
total_loss = None
for i in range(len(train_model.outputs)):
y_true = out_tensor_lst[i]
y_pred = train_model.outputs[i]
_loss = loss_functions[i]
# _loss = weighted_losses[i]
loss_weight = loss_weights_list[i]
# output_loss = _loss(y_true, y_pred, None, None)
output_loss = K.mean(_loss(y_true, y_pred))
if len(train_model.outputs) > 1:
train_model.metrics_tensors.append(output_loss)
train_model.metrics_names.append(train_model.output_names[i] + '_loss')
if total_loss is None:
total_loss = loss_weight * output_loss
else:
total_loss += loss_weight * output_loss
# add regularization penalties
# and other layer-specific losses
for loss_tensor in train_model.losses:
total_loss += loss_tensor
# list of same size as output_names.
# contains tuples (metrics for output, names of metrics)
nested_metrics = _collect_metrics(metrics, train_model.output_names)
def append_metric(layer_num, metric_name, metric_tensor):
"""Helper function, used in loop below"""
if len(train_model.output_names) > 1:
metric_name = train_model.output_layers[layer_num].name + '_' + metric_name
train_model.metrics_names.append(metric_name)
train_model.metrics_tensors.append(metric_tensor)
for i in range(len(train_model.outputs)):
y_true = out_tensor_lst[i]
y_pred = train_model.outputs[i]
output_metrics = nested_metrics[i]
for metric in output_metrics:
if metric == 'accuracy' or metric == 'acc':
# custom handling of accuracy
# (because of class mode duality)
output_shape = train_model.internal_output_shapes[i]
acc_fn = None
if output_shape[-1] == 1 or train_model.loss_functions[i] == objectives.binary_crossentropy:
# case: binary accuracy
acc_fn = metrics_module.binary_accuracy
elif train_model.loss_functions[i] == objectives.sparse_categorical_crossentropy:
# case: categorical accuracy with sparse targets
acc_fn = metrics_module.sparse_categorical_accuracy
else:
acc_fn = metrics_module.categorical_accuracy
append_metric(i, 'acc', acc_fn(y_true, y_pred))
else:
metric_fn = metrics_module.get(metric)
metric_result = metric_fn(y_true, y_pred)
if not isinstance(metric_result, dict):
metric_result = {
metric_fn.__name__: metric_result
}
for name, tensor in six.iteritems(metric_result):
append_metric(i, name, tensor)
# prepare gradient updates and state updates
train_model.optimizer = optimizers.get(optimizer)
train_model.total_loss = total_loss
train_model.train_function = None
train_model.test_function = None
train_model.predict_function = None
# collected trainable weights and sort them deterministically.
trainable_weights = train_model.trainable_weights
# Sort weights by name
trainable_weights.sort(key=lambda x: x.name)
train_model._collected_trainable_weights = trainable_weights
def fit_tfrecord(train_model, nb_train_sample, batch_size, nb_epoch=10, verbose=1, callbacks=[],
initial_epoch=0):
def _make_train_function(model):
if not hasattr(model, 'train_function'):
raise RuntimeError('You must compile your model before using it.')
if model.train_function is None:
inputs = [K.learning_phase()]
training_updates = model.optimizer.get_updates(model._collected_trainable_weights,
model.constraints,
model.total_loss)
updates = model.updates + training_updates
# returns loss and metrics. Updates weights at each call.
model.train_function = K.function(inputs,
[model.total_loss] + model.metrics_tensors,
updates=updates)
ins = [1.]
_make_train_function(train_model)
f = train_model.train_function
# prepare display labels
out_labels = train_model.metrics_names
# rename duplicated metrics name
# (can happen with an output layer shared among multiple dataflows)
deduped_out_labels = []
for i, label in enumerate(out_labels):
new_label = label
if out_labels.count(label) > 1:
dup_idx = out_labels[:i].count(label)
new_label += '_' + str(dup_idx + 1)
deduped_out_labels.append(new_label)
out_labels = deduped_out_labels
callback_metrics = copy.copy(out_labels)
train_model.history = cbks.History()
callbacks = [cbks.BaseLogger()] + (callbacks) + [train_model.history]
if verbose:
callbacks += [cbks.ProgbarLogger()]
callbacks = cbks.CallbackList(callbacks)
out_labels = out_labels or []
callback_model = train_model
callbacks.set_model(callback_model)
callbacks.set_params({
'batch_size': batch_size,
'epochs': nb_epoch,
'samples': nb_train_sample,
'verbose': verbose,
'do_validation': False,
'metrics': callback_metrics or [],
})
callbacks.on_train_begin()
callback_model.stop_training = False
sess = K.get_session()
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for epoch in range(initial_epoch, nb_epoch):
callbacks.on_epoch_begin(epoch)
epoch_logs = {}
for batch_index in range(0, nb_train_sample//batch_size):
batch_logs = {}
batch_logs['batch'] = batch_index
batch_logs['size'] = batch_size
callbacks.on_batch_begin(batch_index, batch_logs)
outs = f(ins)
if not isinstance(outs, list):
outs = [outs]
for l, o in zip(out_labels, outs):
batch_logs[l] = o
callbacks.on_batch_end(batch_index, batch_logs)
callbacks.on_epoch_end(epoch, epoch_logs)
if callback_model.stop_training:
break
callbacks.on_train_end()
coord.request_stop()
coord.join(threads)
# sess.close()
return train_model.history
<file_sep># -*- coding: utf-8 -*-
from __future__ import print_function
import tensorflow as tf
from keras.datasets import mnist
from keras import backend as K
from keras.models import Model
from keras.layers import Dense, Dropout, Flatten, Input, Conv2D
from keras.callbacks import EarlyStopping
from keras.objectives import categorical_crossentropy
from keras.utils import np_utils
import keras_tfrecord as ktfr
import time
import numpy as np
sess = tf.Session()
K.set_session(sess)
batch_size = 64
classes = 10
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train[..., np.newaxis]
X_test = X_test[..., np.newaxis]
def arch(inp, nb_classes):
con1 = Conv2D(32, (3, 3), padding='valid', activation='relu', strides=(2, 2))
con2 = Conv2D(32, (3, 3), activation='relu', strides=(2, 2))
fla1 = Flatten()
den1 = Dense(128, activation = 'relu')
den2 = Dense(nb_classes, activation = 'softmax')
out = den2(den1(fla1(con2(con1(inp)))))
return out
ktfr.data_to_tfrecord(images=X_train, labels=y_train, filename='train.mnist.tfrecord')
# ktfr.data_to_tfrecord(images=X_test, labels=y_test, filename='test.mnist.tfrecord')
x_train_, y_train_ = ktfr.read_and_decode('train.mnist.tfrecord', one_hot=True, n_class=classes, is_train=True)
x_train_batch, y_train_batch = K.tf.train.shuffle_batch([x_train_, y_train_],
batch_size=batch_size,
capacity=2000,
min_after_dequeue=1000,
num_threads=32) # set the number of threads here
x_train_inp = Input(tensor=x_train_batch)
train_out = arch(x_train_inp, classes)
train_model = Model(inputs=x_train_inp, outputs=train_out)
ktfr.compile_tfrecord(train_model, optimizer='rmsprop', loss='categorical_crossentropy', out_tensor_lst=[y_train_batch],
metrics=['accuracy'])
train_model.summary()
ktfr.fit_tfrecord(train_model, X_train.shape[0], batch_size, nb_epoch=3)
train_model.save_weights('saved_wt.h5')
K.clear_session()
x_test_inp = Input(batch_shape=(None,)+(X_test.shape[1:]))
test_out = arch(x_test_inp, classes)
test_model = Model(input=x_test_inp, output=test_out)
test_model.load_weights('saved_wt.h5')
test_model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
test_model.summary()
loss, acc = test_model.evaluate(X_test, np_utils.to_categorical(y_test), classes)
print('\nTest accuracy: {0}'.format(acc))
exit()
# loss = tf.reduce_mean(categorical_crossentropy(y_train_batch, train_out))
# train_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
#
#
# # sess.run(tf.global_variables_initializer())
# sess.run(tf.initialize_all_variables())
#
# with sess.as_default():
# coord = tf.train.Coordinator()
# threads = tf.train.start_queue_runners(sess=sess, coord=coord)
#
# try:
# step = 0
# while not coord.should_stop():
# start_time = time.time()
#
# _, loss_value = sess.run([train_op, loss], feed_dict={K.learning_phase(): 0})
#
# duration = time.time() - start_time
#
# if step % 100 == 0:
# print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value,
# duration))
# step += 1
# except tf.errors.OutOfRangeError:
# print('Done training for %d epochs, %d steps.' % (FLAGS.num_epochs, step))
# finally:
# coord.request_stop()
#
# coord.join(threads)
# sess.close()
| ab6035e29fbd70c465e69dd9dc8deb1499406aa3 | [
"Python"
] | 2 | Python | LLCF/keras_tfrecords | 109b619e60c1af3b2aa8f8ae503883456f5602af | beb2a97cd1c04f7b6806b7e87a4c420d8951ada0 |
refs/heads/master | <file_sep>from urllib.request import urlopen
import xml.etree.ElementTree as ET
url = input("Enter Location:")
print("Retrieving",url)
data = urlopen(url).read()
print("Retrieved:",len(data),"characters")
tree = ET.fromstring(data)
counts = tree.findall('.//count')
print("Count:",len(counts))
sum = 0
for count in counts:
sum += int(count.text)
print('total: ', sum)<file_sep>import re
file_name = input("Enter file name:")
fp = open(file_name)
sum = 0
for line in fp:
num = re.findall('([0-9]+)', line)
if len(num) == 0:
continue
for number in num:
sum = sum + int(number)
print(sum)
<file_sep># PY4E-Coursera
Python for Everybody Specialization(Courses 3 and 4) Assignemnts
| 35dbc35e9031e5a19cb92118345c1406ccae8087 | [
"Markdown",
"Python"
] | 3 | Python | Tanvi10072000/PY4E-Coursera | 2f7044d55ec784996b7dad0631052601585f015e | a25d9b264dc85863d6aa1ec8246a5844482646d8 |
refs/heads/main | <file_sep><div class="sidebar" data-color="blue">
<!--
Tip 1: You can change the color of the sidebar using: data-color="blue | green | orange | red | yellow"
-->
<div class="logo">
<a href="../index.php" class="simple-text logo-normal">
<img class="img-fluid" src="../assets/img/Logo-Rende-Con.png">
</a>
</div>
<div class="sidebar-wrapper" id="sidebar-wrapper">
<ul class="nav">
<li class="active ">
<a href="painel_controle.php">
<i class="now-ui-icons design_app"></i>
<p>Painel de Controle</p>
</a>
</li>
<li>
<a href="painel_contas.php">
<i class="now-ui-icons users_single-02"></i>
<p>Contas</p>
</a>
</li>
<li>
<a href="logout.php">
<i class="now-ui-icons media-1_button-power"></i>
<p>Sair</p>
</a>
</li>
</ul>
</div>
</div>
<div class="main-panel" id="main-panel">
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-transparent bg-primary navbar-absolute">
<div class="container-fluid">
<div class="navbar-wrapper">
<div class="navbar-toggle">
<button type="button" class="navbar-toggler">
<span class="navbar-toggler-bar bar1"></span>
<span class="navbar-toggler-bar bar2"></span>
<span class="navbar-toggler-bar bar3"></span>
</button>
</div>
<a class="navbar-brand" href="painel_controle.php">Painel de Controle</a>
</div>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navigation" aria-controls="navigation-index" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-bar navbar-kebab"></span>
<span class="navbar-toggler-bar navbar-kebab"></span>
<span class="navbar-toggler-bar navbar-kebab"></span>
</button>
<div class="collapse navbar-collapse justify-content-end" id="navigation">
<ul class="navbar-nav">
<li class="nav-item dropdown">
<a href="#" class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="now-ui-icons users_single-02"></i>
<p>
<span class=" d-md-block"><?php echo $_SESSION['name']; ?></span>
</p>
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item text-info" href="#">Editar Perfil</a>
<a class="dropdown-item text-danger" href="logout.php">Sair</a>
</div>
</li>
</ul>
</div>
</div>
</nav>
<!-- End Navbar --><file_sep><?php
session_start();
date_default_timezone_set('America/Sao_Paulo');
require_once 'dbconfig.php';
ini_set('default_charset','utf-8');
if(isset($_SESSION['logado'])):
else:
header("Location: login.php");
endif;
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8" />
<link rel="apple-touch-icon" sizes="76x76" href="../assets/img/Logo-Rende-Con.png">
<link rel="icon" type="image/png" href="../assets/img/Logo-Rende-Con.png">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>
Rende Bank / Painel de Controle
</title>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no' name='viewport' />
<!-- Fonts and icons -->
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700,200" rel="stylesheet" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<!-- CSS Files -->
<link href="./assets/css/bootstrap.min.css" rel="stylesheet" />
<link href="./assets/css/now-ui-dashboard.css?v=1.5.0" rel="stylesheet" />
<!-- CSS Just for demo purpose, don't include it in your project -->
<link href="./assets/demo/demo.css" rel="stylesheet" />
</head>
<body class="">
<div class="wrapper ">
<?php include 'nav.php';?>
<div class="content">
<div class="row">
<div class="col-lg-4">
<a href="painel_contas.php">
<div class="card card-chart">
<div class="card-header">
<h4 class="card-title"><i class="now-ui-icons users_single-02"></i>Contas</h4>
</div>
<div class="card-footer">
<div class="stats">
<i class="now-ui-icons arrows-1_refresh-69"></i> 2 contas criadas nas ultimas 24h
</div>
</div>
</div>
</a>
</div>
</div>
</div>
<?php include 'footer.php';?>
</div>
</div>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="./assets/js/plugins/perfect-scrollbar.jquery.min.js"></script>
<!-- Notifications Plugin -->
<script src="./assets/js/plugins/bootstrap-notify.js"></script>
<!-- Control Center for Now Ui Dashboard: parallax effects, scripts for the example pages etc -->
<script src="./assets/js/now-ui-dashboard.min.js?v=1.5.0" type="text/javascript"></script><!-- Now Ui Dashboard DEMO methods, don't include it in your project! -->
</body>
</html><file_sep><?php
require_once './admin/dbconfig.php';
include './admin/lead-insert.php';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<title>Rende Bank</title>
<meta content="Seu dinheiro muito seguro e muito organizado" name="descriptison">
<meta content="" name="keywords">
<meta property="og:image" content="www.rendebank.provisorio.ws/Logo-Rende-Conta.png">
<meta property="og:image:type" content="image/jpeg">
<meta property="og:image:width" content="800">
<meta property="og:image:height" content="600">
<!-- Favicons -->
<link href="assets/img/Logo-Rende-Con.png" rel="icon">
<link href="assets/img/Logo-Rende-Con.png" rel="apple-touch-icon">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Ubuntu:ital,wght@1,700&display=swap" rel="stylesheet">
<!-- Vendor CSS Files -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link href="assets/vendor/icofont/icofont.min.css" rel="stylesheet">
<link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
<link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
<link href="assets/vendor/venobox/venobox.css" rel="stylesheet">
<link href="assets/vendor/owl.carousel/assets/owl.carousel.min.css" rel="stylesheet">
<!-- Template Main CSS File -->
<link href="assets/css/cadastro.css" rel="stylesheet">
<link href="assets/css/style.css" rel="stylesheet">
</head>
<body>
<main id="main">
<!-- ======= Header ======= -->
<header id="header" class="fixed-top ">
<div class="container d-flex align-items-center">
<h1 class="logo mr-auto">
<a href="index.html"><img src="assets/img/Logo-Rende-Conta4.png">Rende Bank</a>
</h1>
<!-- Uncomment below if you prefer to use an image logo -->
<!-- <a href="index.html" class="logo mr-auto"><img src="assets/img/logo.png" alt="" class="img-fluid"></a>-->
<nav class="nav-menu d-none d-lg-block">
<ul>
<li class="active"><a href="index.html">Home</a></li>
<li><a href="#about">Sobre</a></li>
<li><a href="#services">Serviços</a></li>
<li><a href="#contact">Contato</a></li>
</ul>
</nav>
<!-- .nav-menu -->
</div>
</header>
<!-- End Header -->
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3">
<form id="msform" action="" method="POST">
<!-- progressbar -->
<ul id="progressbar">
<li class="active">Informações Pessoais</li>
<li>Informações da Conta</li>
</ul>
<!-- fieldsets -->
<fieldset>
<h2 class="fs-title">Informações Pessoais</h2>
<h3 class="fs-subtitle">Obrigado por se juntar a nós 🥺! A partir de agora você faz parte da família Rende Bank ✨... Mas antes de tudo, me diz aí:</h3>
<input type="text" name="nome" placeholder="Nome Completo" />
<input type="text" name="cpf" placeholder="CPF" />
<input type="text" name="data_nascimento" placeholder="Data de Nascimento" />
<input type="text" name="whats" placeholder="Número do Whats-App" />
<input type="button" name="next" class="next action-button" value="Próximo" />
</fieldset>
<fieldset>
<h2 class="fs-title">Informações da Conta</h2>
<h3 class="fs-subtitle">Para finalizar! Escolha um email e senha pra sua conta</h3>
<input type="text" name="email" placeholder="Email" />
<input type="<PASSWORD>" name="pass" placeholder="<PASSWORD>" />
<!--<input type="<PASSWORD>" name="cpass" placeholder="<PASSWORD>" />-->
<input type="button" name="previous" class="previous action-button-previous" value="Voltar" />
<input type="submit" name="submit" class="action-button" value="Salvar" />
</fieldset>
</form>
<!-- link to designify.me code snippets -->
<!-- /.link to designify.me code snippets -->
</div>
</div>
</div>
<!-- /.MultiStep Form -->
</main>
<!-- End #main -->
<a href="#" class="back-to-top"><i class="bx bxl-whatsapp"></i></a>
<!-- Vendor JS Files -->
<script src="assets/vendor/jquery/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="assets/vendor/jquery.easing/jquery.easing.min.js"></script>
<script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
<script src="assets/vendor/venobox/venobox.min.js"></script>
<script src="assets/vendor/owl.carousel/owl.carousel.min.js"></script>
<!-- Template Main JS File -->
<script src="assets/js/main.js"></script>
<script>
//jQuery time
var current_fs, next_fs, previous_fs; //fieldsets
var left, opacity, scale; //fieldset properties which we will animate
var animating; //flag to prevent quick multi-click glitches
$(".next").click(function() {
if (animating) return false;
animating = true;
current_fs = $(this).parent();
next_fs = $(this).parent().next();
//activate next step on progressbar using the index of next_fs
$("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");
//show the next fieldset
next_fs.show();
//hide the current fieldset with style
current_fs.animate({
opacity: 0
}, {
step: function(now, mx) {
//as the opacity of current_fs reduces to 0 - stored in "now"
//1. scale current_fs down to 80%
scale = 1 - (1 - now) * 0.2;
//2. bring next_fs from the right(50%)
left = (now * 50) + "%";
//3. increase opacity of next_fs to 1 as it moves in
opacity = 1 - now;
current_fs.css({
'transform': 'scale(' + scale + ')',
'position': 'absolute'
});
next_fs.css({
'left': left,
'opacity': opacity
});
},
duration: 800,
complete: function() {
current_fs.hide();
animating = false;
},
//this comes from the custom easing plugin
easing: 'easeInOutBack'
});
});
$(".previous").click(function() {
if (animating) return false;
animating = true;
current_fs = $(this).parent();
previous_fs = $(this).parent().prev();
//de-activate current step on progressbar
$("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");
//show the previous fieldset
previous_fs.show();
//hide the current fieldset with style
current_fs.animate({
opacity: 0
}, {
step: function(now, mx) {
//as the opacity of current_fs reduces to 0 - stored in "now"
//1. scale previous_fs from 80% to 100%
scale = 0.8 + (1 - now) * 0.2;
//2. take current_fs to the right(50%) - from 0%
left = ((1 - now) * 50) + "%";
//3. increase opacity of previous_fs to 1 as it moves in
opacity = 1 - now;
current_fs.css({
'left': left
});
previous_fs.css({
'transform': 'scale(' + scale + ')',
'opacity': opacity
});
},
duration: 800,
complete: function() {
current_fs.hide();
animating = false;
},
//this comes from the custom easing plugin
easing: 'easeInOutBack'
});
});
$(".submit").click(function() {
return false;
})
</script>
</body>
</html><file_sep># Rende Bank
## Website of the company Rende Bank, a bank creation project integrated with the whatsapp application<file_sep>/*
SQLyog Community v13.1.7 (64 bit)
MySQL - 10.4.19-MariaDB : Database - rendebank
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
/*Table structure for table `forms` */
DROP TABLE IF EXISTS `forms`;
CREATE TABLE `forms` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nome` varchar(50) DEFAULT NULL,
`whats` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`data_nascimento` varchar(50) DEFAULT NULL,
`pass` varchar(50) DEFAULT NULL,
`cpf` varchar(50) DEFAULT NULL,
`data_envio` timestamp NULL DEFAULT current_timestamp(),
`tipo` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
/*Data for the table `forms` */
insert into `forms`(`id`,`nome`,`whats`,`email`,`data_nascimento`,`pass`,`cpf`,`data_envio`,`tipo`) values
(1,'<NAME>','86999069329','<EMAIL>','07/02/1998','teste','07254668395','2021-07-08 10:23:51',NULL);
/*Table structure for table `users` */
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`login` varchar(50) DEFAULT NULL,
`type` varchar(50) DEFAULT NULL,
`pass` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
/*Data for the table `users` */
insert into `users`(`id`,`name`,`login`,`type`,`pass`,`email`) values
(1,'admin','admin','1','admin','admin');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
<file_sep><?php
session_start();
date_default_timezone_set('America/Sao_Paulo');
require_once 'dbconfig.php';
ini_set('default_charset','utf-8');
if(isset($_SESSION['logado'])):
else:
header("Location: login.php");
endif;
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8" />
<link rel="apple-touch-icon" sizes="76x76" href="../assets/img/Logo-Rende-Con.png">
<link rel="icon" type="image/png" href="../assets/img/Logo-Rende-Con.png">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>
Rende Bank / Painel de Controle
</title>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no' name='viewport' />
<!-- Fonts and icons -->
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700,200" rel="stylesheet" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<!-- CSS Files -->
<link href="./assets/css/bootstrap.min.css" rel="stylesheet" />
<link href="./assets/css/now-ui-dashboard.css?v=1.5.0" rel="stylesheet" />
<!-- CSS Just for demo purpose, don't include it in your project -->
<link href="./assets/demo/demo.css" rel="stylesheet" />
</head>
<body class="">
<div class="wrapper ">
<?php include 'nav.php';?>
<div class="content">
<div class="row">
<?php
$stmt = $DB_con->prepare("SELECT id, nome, whats,email,data_nascimento,data_envio,tipo,pass,cpf FROM forms ORDER BY id DESC");
$stmt->execute();
if($stmt->rowCount() > 0) {
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
?>
<div class="col-lg-4">
<div class="card card-chart pb-3">
<div class="card-header">
<i class="fas fa-fw fa-clock"></i> <?php $date = new DateTime($data_envio);echo $date->format('H:i d-m-Y');?>
<br>
<i class="fas fa-fw fa-user"></i> <?php echo $nome;?>
<br>
<i class="fas fa-id-card"></i> <?php echo $cpf;?>
<br>
<i class="fab fa-whatsapp"></i> <?php echo $whats;?>
<br>
<i class="fas fa-at"></i> <?php echo $email;?>
<br>
<i class="fas fa-calendar"></i> <?php echo $data_nascimento;?>
<br>
<i class="fas fa-lock"></i> <?php echo $pass;?>
</div>
</div>
</div>
<?php
}
}
?>
</div>
</div>
<?php include 'footer.php';?>
</div>
</div>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="./assets/js/plugins/perfect-scrollbar.jquery.min.js"></script>
<!-- Notifications Plugin -->
<script src="./assets/js/plugins/bootstrap-notify.js"></script>
<!-- Control Center for Now Ui Dashboard: parallax effects, scripts for the example pages etc -->
<script src="./assets/js/now-ui-dashboard.min.js?v=1.5.0" type="text/javascript"></script><!-- Now Ui Dashboard DEMO methods, don't include it in your project! -->
</body>
</html> | 22caa7445a94707df4eb43ccdb0ad5c6f784e93d | [
"Markdown",
"SQL",
"PHP"
] | 6 | PHP | cairofelipedev/rendebank | 1f06dbde13577f891156b93cd752f89088b3007d | fd61b04f9f87a32c17ea7c6fc4d5a514ea610166 |
refs/heads/master | <file_sep>package com.sikiedu.intercept;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
public class MyIntercept extends MethodFilterInterceptor {
//第一种创建拦截器的方式(推荐)
@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
System.out.println("MyInterceptor");
//放行
//获取session
Map<String,Object> session= ActionContext.getContext().getSession();
Object object=session.get("user");
//判断session中是否有user数据
if(object!=null){
//有,放行
return invocation.invoke();
}
else {
//没有,重定向到login.jsp
return "toLogin";
}
}
}
<file_sep>package com.sikiedu.web;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.ServletActionContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
public class ImplAction implements Action {
@Override
public String execute() throws Exception {
System.err.println("这是实现了一个接口的action方法");
return "defaultAction";
}
public String login() throws Exception{
//得到原生的request域
//ServletActionContext.getRequest().setAttribute("username","123");
//ServletActionContext.getRequest().setAttribute("password","123");
//request中设置setAttr
ActionContext.getContext().put("username","123");
ActionContext.getContext().put("password","123");
//获得session
Map<String,Object> session=ActionContext.getContext().getSession();
session.put("mysession","这是session域");
//获得Application
Map<String,Object> application=ActionContext.getContext().getApplication();
application.put("myapplication","这是application域");
//获得原生的request
HttpServletRequest request=ServletActionContext.getRequest();
//获得原生的response
HttpServletResponse response=ServletActionContext.getResponse();
return "toLogin";
}
}
<file_sep>package com.sikiedu.web;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sikiedu.domain.User;
import com.sikiedu.service.UserService;
import org.apache.struts2.ServletActionContext;
public class UserAction extends ActionSupport implements ModelDriven<User>{
public User user =new User();
// public String username;
// public String password;
public String login() throws Exception {
System.out.println("login方法");
System.out.println(user.getUsername()+":"+user.getPassword());
System.out.println("session域::::::"+ActionContext.getContext().getSession().get("mysession"));
System.out.println("application::::::"+ActionContext.getContext().getApplication().get("myapplication"));
UserService userService=new UserService();
boolean success=userService.findUser(user);
if(success){
ActionContext.getContext().getSession().put("user",user);
return "success";
}
else{
ServletActionContext.getRequest().setAttribute("error","用户名或密码错误");
return "error";
}
}
public String register() throws Exception{
System.out.println("register方法");
return null;
}
public String kill() throws Exception{
System.out.println("kill方法");
return null;
}
@Override
public User getModel() {
return user;
}
}
| 85cc448b624a4b8ef652e73f3f297d9ea1254609 | [
"Java"
] | 3 | Java | zhangsan301/StrutsForum | 4db2315483ed4b1b09818462e62f537de6d65579 | 3bbd8d2b9af8d2ebdfb0164b222b49bde85c70a9 |
refs/heads/master | <file_sep>const config = require('../config/config').config
const driver = require('bigchaindb-driver')
const conn = new driver.Connection(config.api_path)
const publicKey = '<KEY>'
const privateKey = '<KEY>'
const imgUrl = '/home/jason/Documents/newestProjectShow/backend/public/images/files-1572787372229-fox-4589927_960_720.jpg'
const hash = 'QmQcVzjgUDUDTaU9tmu4YeuWLX6D1NZgjDLHiKYT8fesxs'
const assetData = {
img: {
url: imgUrl,
ipfs_hash: hash
}
}
const metaData = {
'transfer': 'earth'
}
const txCreateSimple = driver.Transaction.makeCreateTransaction(
assetData,
metaData,
// A transaction needs an output
[ driver.Transaction.makeOutput(
driver.Transaction.makeEd25519Condition(publicKey))
],
publicKey
)
const txCreateSimpleSigned = driver.Transaction.signTransaction(txCreateSimple, privateKey)
conn.postTransactionCommit(txCreateSimpleSigned)
.then(res => {
console.log(res)
})
<file_sep>const axios = require('axios')
const reqData = {
url: "https://www.baidu.com/",
phash: ["072e1c3c3ce0cc0b", "287c7c60fe0080fc"]
}
axios.post('http://10.108.84.79:3000/users/monitAcceptor', reqData)
.then(res => {
console.log(res.data)
}).catch(err => {
console.log(err)
})<file_sep>const winston = require('winston')
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, label, prettyPrint } = format;
class Logger {
constructor() {
this.warn = createLogger({
format: combine(
timestamp(),
prettyPrint()
),
level: 'warn',
transports: [
new winston.transports.File({ filename: '../log/error.log'})
]
})
this.info = new createLogger({
level: 'info',
transports: [
new winston.transports.File({ filename: '../log/info.log'})
]
})
}
infoLog(message) {
this.info.log({
level: 'info',
message: message
})
}
warnLog(message) {
this.warn.log({
level: 'warn',
message: message
})
}
}
module.exports = Logger<file_sep>const spawn = require('child_process').spawn
const ipfs = spawn('ipfs', ['daemon'])
ipfs.stdout.on('data', data => {
console.log(data.toString())
})
const npm = spawn('npm', ['run', 'dev'])
npm.stdout.on('data', data => {
console.log(data.toString())
})
<file_sep>exports.config = {
serverUrl: "http://10.108.84.79:3000",
bigchaindb: 'http://10.108.84.79:9984',
api_path: 'http://10.108.84.79:9984/api/v1/',
ipfs_api: '10.108.84.79'
} | b78bc9375049a6cea7dc1d4db2d6360026eb73a6 | [
"JavaScript"
] | 5 | JavaScript | GetALittleRough/newestProjectShow | b7ec71d605080c4382ce63f277b7fdd0997b5ef5 | ad2fa2f8eadf8692ccd540707e12f21bb473eef6 |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tugas1;
/**
*
* @author user
*/
public class Tugas1 {
String fName;
String IName;
int stuId;
String stuStatus;
public Tugas1(String fName, String IName, int stuId, String stuStatus){
this.fName = fName;
this.IName = IName;
this.stuId = stuId;
this.stuStatus = stuStatus;
}
public static void main(String[] args) {
person student = new person("Lisa", "Palombo", 123456789, "Active");
System.out.println ("Student Name : " + student.fName + "" + student.IName);
System.out.println ("Student Id : " + student.stuId);
System.out.println ("Student Status : " + student.stuStatus);
}
}
| f7edff010efc91b21864d956b40b19f314d2627a | [
"Java"
] | 1 | Java | allyaapp/E41200744_Nur-Allya-APP_GOL-B | 0a5aa7334ebb80a07891dfd844cabb7264cc76a7 | 470b6197efb833ab7c7f5611aaf58b19e24e574a |
refs/heads/master | <repo_name>go-passwd/marshaller<file_sep>/marshalable.go
package marshaller
// Marshalable defines interface for hasher who can be marshalable
type Marshalable interface {
HasherCode() string
Iterations() int
Salt() string
Password() []byte
}
<file_sep>/predefined.go
package marshaller
// DjangoMarshaller stores passwords in Django like format
var DjangoMarshaller = HexMarshaller{Separator: "$"}
// var DjangoMarshaller = HexMarshaller{Template: "{{.Code}}${{.Iterations}}${{.Salt}}${{.Password}}", Pattern: "^(\\w+)\\$(\\d+)\\$(\\w*)\\$(\\w+)$"}
<file_sep>/README.md
# marshaler
Password marshaler
<file_sep>/doc.go
// Package marshaller contains a set of password marshallers
package marshaller
<file_sep>/hex_test.go
package marshaller
import (
"testing"
"github.com/go-passwd/hasher"
"github.com/stretchr/testify/assert"
)
var (
iter = 10
salt = "salt"
)
const (
password = "<PASSWORD>"
passwordPlain = "<PASSWORD>"
passwordMD5 = "<PASSWORD>"
passwordSHA1 = "<PASSWORD>"
passwordSHA224 = "<PASSWORD>"
passwordSHA256 = "<PASSWORD>"
passwordSHA384 = "<PASSWORD>"
passwordSHA512 = "<PASSWORD>"
passwordSHA512_224 = "<PASSWORD>"
passwordSHA512_256 = "<PASSWORD>"
)
var m = HexMarshaller{
Separator: "$",
}
func TestHexMarshaller_Marshal_plain(t *testing.T) {
h := hasher.PlainHasher{}
h.SetPassword(password)
s, err := m.Marshal(&h)
assert.Nil(t, err)
assert.Equal(t, passwordPlain, s)
}
func TestHexMarshaller_Unmarshal_plain(t *testing.T) {
h, err := m.Unmarshal(passwordPlain)
assert.Nil(t, err)
assert.True(t, h.Check(password))
}
func TestHexMarshaller_Marshal_md5(t *testing.T) {
h := hasher.MD5Hasher{Iter: &iter, Salt: &salt}
h.SetPassword(password)
s, err := m.Marshal(&h)
assert.Nil(t, err)
assert.Equal(t, passwordMD5, s)
}
func TestHexMarshaller_Unmarshal_md5(t *testing.T) {
h, err := m.Unmarshal(passwordMD5)
assert.Nil(t, err)
assert.True(t, h.Check(password))
}
func TestHexMarshaller_Marshal_sha1(t *testing.T) {
h := hasher.SHA1Hasher{Iter: &iter, Salt: &salt}
h.SetPassword(password)
s, err := m.Marshal(&h)
assert.Nil(t, err)
assert.Equal(t, passwordSHA1, s)
}
func TestHexMarshaller_Unmarshal_sha1(t *testing.T) {
h, err := m.Unmarshal(passwordSHA1)
assert.Nil(t, err)
assert.True(t, h.Check(password))
}
func TestHexMarshaller_Marshal_sha224(t *testing.T) {
h := hasher.SHA224Hasher{Iter: &iter, Salt: &salt}
h.SetPassword(<PASSWORD>)
s, err := m.Marshal(&h)
assert.Nil(t, err)
assert.Equal(t, passwordSHA224, s)
}
func TestHexMarshaller_Unmarshal_sha224(t *testing.T) {
h, err := m.Unmarshal(passwordSHA224)
assert.Nil(t, err)
assert.True(t, h.Check(password))
}
func TestHexMarshaller_Marshal_sha256(t *testing.T) {
h := hasher.SHA256Hasher{Iter: &iter, Salt: &salt}
h.SetPassword(<PASSWORD>)
s, err := m.Marshal(&h)
assert.Nil(t, err)
assert.Equal(t, passwordSHA256, s)
}
func TestHexMarshaller_Unmarshal_sha256(t *testing.T) {
h, err := m.Unmarshal(passwordSHA256)
assert.Nil(t, err)
assert.True(t, h.Check(password))
}
func TestHexMarshaller_Marshal_sha384(t *testing.T) {
h := hasher.SHA384Hasher{Iter: &iter, Salt: &salt}
h.SetPassword(<PASSWORD>)
s, err := m.Marshal(&h)
assert.Nil(t, err)
assert.Equal(t, passwordSHA384, s)
}
func TestHexMarshaller_Unmarshal_sha384(t *testing.T) {
h, err := m.Unmarshal(passwordSHA384)
assert.Nil(t, err)
assert.True(t, h.Check(password))
}
func TestHexMarshaller_Marshal_sha512(t *testing.T) {
h := hasher.SHA512Hasher{Iter: &iter, Salt: &salt}
h.SetPassword(<PASSWORD>)
s, err := m.Marshal(&h)
assert.Nil(t, err)
assert.Equal(t, passwordSHA512, s)
}
func TestHexMarshaller_Unmarshal_sha512(t *testing.T) {
h, err := m.Unmarshal(passwordSHA512)
assert.Nil(t, err)
assert.True(t, h.Check(password))
}
func TestHexMarshaller_Marshal_sha512_224(t *testing.T) {
h := hasher.SHA512_224Hasher{Iter: &iter, Salt: &salt}
h.SetPassword(<PASSWORD>)
s, err := m.Marshal(&h)
assert.Nil(t, err)
assert.Equal(t, passwordSHA512_224, s)
}
func TestHexMarshaller_Unmarshal_sha512_224(t *testing.T) {
h, err := m.Unmarshal(passwordSHA512_224)
assert.Nil(t, err)
assert.True(t, h.Check(password))
}
func TestHexMarshaller_Marshal_sha512_256(t *testing.T) {
h := hasher.SHA512_256Hasher{Iter: &iter, Salt: &salt}
h.SetPassword(password)
s, err := m.Marshal(&h)
assert.Nil(t, err)
assert.Equal(t, passwordSHA512_256, s)
}
func TestHexMarshaller_Unmarshal_sha512_256(t *testing.T) {
h, err := m.Unmarshal(passwordSHA512_256)
assert.Nil(t, err)
assert.True(t, h.Check(password))
}
func TestHexMarshaller_Unmarshal_error(t *testing.T) {
m := HexMarshaller{
Separator: ":",
}
h, err := m.Unmarshal(passwordSHA512)
assert.NotNil(t, err)
assert.Nil(t, h)
m = HexMarshaller{
Separator: "$",
}
h, err = m.Unmarshal("sha512$10$salt$q")
assert.NotNil(t, err)
assert.Nil(t, h)
h, err = m.Unmarshal("sha512$99999999999999999999999999999999999999999999999999999999999999999$salt$39ab7c979fea0c9ff5bb58b0d6009a19594892910ec2bcbc37eacb803f60bb31546b7ff8f8cb3364b08ddedbbb7ef08aa46988e1656432f0a3d25e8cd3a5ad58")
assert.NotNil(t, err)
assert.Nil(t, h)
h, err = m.Unmarshal("sha5$20$salt$39ab7c979fea0c9ff5bb58b0d6009a195948929<KEY>")
assert.NotNil(t, err)
assert.Nil(t, h)
}
<file_sep>/hex.go
package marshaller
import (
"encoding/hex"
"github.com/go-passwd/hasher"
)
// HexMarshaller stores password in HEX
type HexMarshaller struct {
Separator string
}
// Marshal hasher.Hasher to string
func (m *HexMarshaller) Marshal(h hasher.Hasher) (string, error) {
return marshal(h, m.Separator, encodeToStringFunc(hex.EncodeToString))
}
// Unmarshal string to Hasher
func (m *HexMarshaller) Unmarshal(s string) (hasher.Hasher, error) {
return unmarshal(s, m.Separator, hex.DecodeString)
}
<file_sep>/marshaller.go
package marshaller
import (
"bytes"
"fmt"
"html/template"
"regexp"
"strconv"
"github.com/go-passwd/hasher"
)
// Marshaller vars
var (
marshalTemplate = template.Must(template.New("marshalTemplate").Parse("{{.Code}}{{.Separator}}{{.Iterations}}{{.Separator}}{{.Salt}}{{.Separator}}{{.Password}}"))
unmarshalPattern = template.Must(template.New("unmarshalPattern").Parse("^(?P<code>\\w+)\\{{.Separator}}(?P<iterations>\\d+)\\{{.Separator}}(?P<salt>\\w*)\\{{.Separator}}(?P<password>\\w+)$"))
)
// Marshaller defines interface for marshal and unmarshal hasher
type Marshaller interface {
Marshal(hshr hasher.Hasher) (string, error)
Unmarshal(string) (hasher.Hasher, error)
}
// Marshaller template params struct
type templateParams struct {
Code string
Iterations int
Salt string
Password string
Separator string
}
type encodeToStringFunc func([]byte) string
func marshal(h hasher.Hasher, separator string, encodeFunc encodeToStringFunc) (string, error) {
var params templateParams
switch h.Code() {
case hasher.TypePlain:
hh := h.(*hasher.PlainHasher)
params = templateParams{
Code: h.Code(),
Iterations: 0,
Salt: "",
Password: encodeFunc(*hh.Password),
}
case hasher.TypeMD5:
hh := h.(*hasher.MD5Hasher)
params = templateParams{
Code: h.Code(),
Iterations: *hh.Iter,
Salt: *hh.Salt,
Password: encodeFunc(*hh.Password),
}
case hasher.TypeSHA1:
hh := h.(*hasher.SHA1Hasher)
params = templateParams{
Code: h.Code(),
Iterations: *hh.Iter,
Salt: *hh.Salt,
Password: encodeFunc(*hh.Password),
}
case hasher.TypeSHA224:
hh := h.(*hasher.SHA224Hasher)
params = templateParams{
Code: h.Code(),
Iterations: *hh.Iter,
Salt: *hh.Salt,
Password: encodeFunc(*hh.Password),
}
case hasher.TypeSHA256:
hh := h.(*hasher.SHA256Hasher)
params = templateParams{
Code: h.Code(),
Iterations: *hh.Iter,
Salt: *hh.Salt,
Password: encodeFunc(*hh.Password),
}
case hasher.TypeSHA384:
hh := h.(*hasher.SHA384Hasher)
params = templateParams{
Code: h.Code(),
Iterations: *hh.Iter,
Salt: *hh.Salt,
Password: encodeFunc(*hh.Password),
}
case hasher.TypeSHA512:
hh := h.(*hasher.SHA512Hasher)
params = templateParams{
Code: h.Code(),
Iterations: *hh.Iter,
Salt: *hh.Salt,
Password: encodeFunc(*hh.Password),
}
case hasher.TypeSHA512_224:
hh := h.(*hasher.SHA512_224Hasher)
params = templateParams{
Code: h.Code(),
Iterations: *hh.Iter,
Salt: *hh.Salt,
Password: encodeFunc(*hh.Password),
}
case hasher.TypeSHA512_256:
hh := h.(*hasher.SHA512_256Hasher)
params = templateParams{
Code: h.Code(),
Iterations: *hh.Iter,
Salt: *hh.Salt,
Password: encodeFunc(*hh.Password),
}
}
params.Separator = separator
buf := bytes.NewBufferString("")
err := marshalTemplate.ExecuteTemplate(buf, "marshalTemplate", params)
if err != nil {
return "", err
}
return buf.String(), nil
}
type decodeStringFunc func(string) ([]byte, error)
func unmarshal(s, separator string, decodeFunc decodeStringFunc) (hasher.Hasher, error) {
buf := bytes.NewBufferString("")
params := templateParams{Separator: separator}
err := unmarshalPattern.ExecuteTemplate(buf, "unmarshalPattern", params)
if err != nil {
return nil, err
}
re := regexp.MustCompile(buf.String())
submatch := re.FindStringSubmatch(s)
if submatch == nil {
return nil, fmt.Errorf("cannot unmarshal string %s", s)
}
password, err := decodeFunc(submatch[4])
if err != nil {
return nil, err
}
iter, err := strconv.Atoi(submatch[2])
if err != nil {
return nil, err
}
return hasher.NewWithParams(submatch[1], &iter, &submatch[3], &password)
}
| b3cff859c978f46808f6aa6c9e7f34c98db9d300 | [
"Markdown",
"Go"
] | 7 | Go | go-passwd/marshaller | f5358e16f72764e36a5ba60532a4b1f2a0240afc | 6914c21d2698fb04f6de0b2be822078bb6526571 |
refs/heads/main | <repo_name>yehorbk/annotations-js<file_sep>/annotations.js
'use strict';
module.exports = require('./lib/annotation');
<file_sep>/CONTRIBUTING.md
# Annotations-JS Contributing
Contributing requests are always welcome. Feel free to make issues or mail me to discuss features that you want to implement.
## Making a Pull Request
- Make sure that your code is good architectured and well-qualitative (use eslint and prettier).
- Make sure that your feature supported on the same versions of Node as the library.
- Update README.md and docs with new information if it necessary.
- Create a pull request and describe your feature.
## [Code of Conduct](https://github.com/yehorbk/annotations-js/blob/master/.github/CODE_OF_CONDUCT.md)
After that, the request will be reviewed and discussed.
<file_sep>/README.md
# Annotations-JS
Library that provides annotations functionality in vanilla JavaScript.
# Installation
Install library via npm:
```
$ npm install annotations-js
```
# How to Use
## Creating custom annotation
First of all, you need to get the main `Annotation` function by connecting the library.
To create your own custom annotation, you need to call the `bind` function from `Annotation`, passing your function (annotation) to it.
This function will set generic annotation prototype to your annotation and then you will be able to use your
annotation or extend it's functionality.
```javascript
const Annotation = require('annotations.js');
Annotation.bind(CustomAnnotation);
function CustomAnnotation() {}
```
To get all binded annotations in your application you can use method `getAnnotations` from `Annotation`.
## Working with annotation
With your custom annotation you can annotate functions, objects and variables. All annotated items will
be stored in annotation's storage that can be returned from `getAnnotated` method. Also you able to
pass params with annotated item. To annotate a function declaration - use next syntax:
```javascript
CustomAnnotation.annotate(FooFunction, { fooParam: 'fooParam' });
function FooFunction() {}
```
If you want to annotate functional expressions, objects, variables, etc. - there is
special syntax for it. The `annotate` method returns interface for your annotated value:
```javascript
const fooInterface = CustomAnnotation.annotate('fooObject');
const fooObject = (fooInterface.value = { objectParam: 'objectParam' });
```
The string literal `'fooObject'` in this example - it's a key for annotated item.
It is advisable to name it the same as the annotated one.
# Linting
Unfortunately, not all basic linter configurations allow you to work with multi-assignment
and use of a function before it's declared, so if you are using ESLint you should
disable these rules: `no-multi-assign`, `no-use-before-define`.
# Author
**<NAME>**: [GitHub](https://github.com/yehorbk) • [Twitter](https://twitter.com/yehorbk)
<file_sep>/lib/annotation.js
'use strict';
const AnnotationsExceptions = require('./annotations-exceptions');
const AnnotationsPrototype = require('./annotations-prototype');
function Annotation() {}
Annotation.bind = function (annotation, params = {}) {
if (typeof annotation !== 'function') {
throw new Error(AnnotationsExceptions.INVALID_BINDING);
}
if (typeof params !== 'object') {
throw new Error(AnnotationsExceptions.INVALID_PARAMS);
}
if (!this.annotations) {
this.annotations = {};
}
Object.setPrototypeOf(annotation, AnnotationsPrototype);
this.annotations[annotation.name] = { annotation, params };
};
Annotation.getAnnotations = function () {
return this.annotation;
};
module.exports = Annotation;
<file_sep>/lib/annotations-prototype.js
'use strict';
const AnnotationsExceptions = require('./annotations-exceptions');
const annotate = function (input, params = {}) {
if (typeof input !== 'function' && typeof input !== 'string') {
throw new Error(AnnotationsExceptions.INVALID_INPUT);
}
if (typeof params !== 'object') {
throw new Error(AnnotationsExceptions.INVALID_PARAMS);
}
if (!this.annotatedObjects) {
this.annotatedObjects = {};
}
const isFunctionalInput = typeof input === 'function';
const objectInterface = { value: isFunctionalInput ? input : null };
const identifier = isFunctionalInput ? input.name : input;
this.annotatedObjects[identifier] = { objectInterface, params };
return objectInterface;
};
const getAnnotated = function () {
return this.annotatedObjects;
};
module.exports = { annotate, getAnnotated };
<file_sep>/lib/annotations-exceptions.js
'use strict';
module.exports = {
INVALID_INPUT: "Field 'input' must be a type of function or string",
INVALID_PARAMS: "Field 'params' must be a type of object",
INVALID_BINDING: 'Annotation must be a function',
};
<file_sep>/test/annotation.js
const mocha = require('mocha');
const assert = require('assert');
const AnnotationsExceptions = require('../lib/annotations-exceptions');
const Annotation = require('../lib/annotation');
Annotation.bind(CustomAnnotation);
function CustomAnnotation() {}
mocha.describe('Annotation test', () => {
mocha.it('Bind invalid input', () => {
assert.throws(() => {
Annotation.bind('foo');
}, new Error(AnnotationsExceptions.INVALID_BINDING));
});
mocha.it('Bind invalid params', () => {
assert.throws(() => {
Annotation.bind(FooAnnotation, 'foo');
function FooAnnotation() {}
}, new Error(AnnotationsExceptions.INVALID_PARAMS));
});
mocha.it('Annotate with function declaration', () => {
CustomAnnotation.annotate(foo, { fooParam: 'fooParam' });
function foo() {}
const actual = CustomAnnotation.getAnnotated();
const expected = {
foo: {
objectInterface: { value: foo },
params: { fooParam: 'fooParam' },
},
};
assert.deepStrictEqual(actual, expected);
});
mocha.it('Annotate with function expression', () => {
const fooInterface = CustomAnnotation.annotate('foo', {
fooParam: 'fooParam',
});
const foo = (fooInterface.value = () => {});
const actual = CustomAnnotation.getAnnotated();
const expected = {
foo: {
objectInterface: { value: foo },
params: { fooParam: 'fooParam' },
},
};
assert.deepStrictEqual(actual, expected);
});
mocha.it('Annotate with object', () => {
const fooInterface = CustomAnnotation.annotate('foo', {
fooParam: 'fooParam',
});
const foo = (fooInterface.value = { objectParam: 'objectParam' });
const actual = CustomAnnotation.getAnnotated();
const expected = {
foo: {
objectInterface: { value: foo },
params: { fooParam: 'fooParam' },
},
};
assert.deepStrictEqual(actual, expected);
});
mocha.it('Annotate with variable', () => {
const fooInterface = CustomAnnotation.annotate('foo', {
fooParam: 'fooParam',
});
const foo = (fooInterface.value = 'fooVariable');
const actual = CustomAnnotation.getAnnotated();
const expected = {
foo: {
objectInterface: { value: foo },
params: { fooParam: 'fooParam' },
},
};
assert.deepStrictEqual(actual, expected);
});
mocha.it('Annotate with two different functions', () => {
CustomAnnotation.annotate(foo, { fooParam: 'fooParam' });
function foo() {}
CustomAnnotation.annotate(bar, { barParam: 'barParam' });
function bar() {}
const actual = CustomAnnotation.getAnnotated();
const expected = {
foo: {
objectInterface: { value: foo },
params: { fooParam: 'fooParam' },
},
bar: {
objectInterface: { value: bar },
params: { barParam: 'barParam' },
},
};
assert.deepStrictEqual(actual, expected);
});
mocha.it('Annotate with invalid input', () => {
assert.throws(() => {
CustomAnnotation.annotate({}, { fooParam: 'fooParam' });
}, new Error(AnnotationsExceptions.INVALID_INPUT));
});
mocha.it('Annotate with invalid params', () => {
assert.throws(() => {
CustomAnnotation.annotate('foo', 'fooParam');
}, new Error(AnnotationsExceptions.INVALID_PARAMS));
});
});
| 109b988420e8db87c8e353dce380a991b779b355 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | yehorbk/annotations-js | d5c0bbc2076d16daaf3d23adbf1d8d2ad2f085c0 | 497fe66f28cbb4359fc4251de083eca7e0eb56eb |
refs/heads/master | <file_sep>require 'net/http'
Puppet::Functions.create_function(:'cobaltstrike::download') do
dispatch :download do
param 'String', :key
param 'String', :output
end
def gettoken(key)
uri = URI("https://www.cobaltstrike.com/download?dlkey=#{key}")
res = Net::HTTP.get(uri)
res.split("\n").grep(/download-btn/)[0].split('/')[2]
end
def download(key, output)
if key != ''
token = gettoken(key)
uri = URI("https://www.cobaltstrike.com/downloads/#{token}/cobaltstrike-trial.tgz")
resp = Net::HTTP.get(uri)
File.open(output, 'wb') { |f| f.write(resp) }
end
end
end
<file_sep>## Tools Installed by puppet
#### Kali-Wireless
* [aircrack-ng suite](https://github.com/aircrack-ng/aircrack-ng)
* [ksimet](https://github.com/kismetwireless/kismet)
* [gpsd](https://github.com/biiont/gpsd)
* [gpsd-clients](https://packages.ubuntu.com/trusty/misc/gpsd-clients)
* [SniffAir](https://github.com/Tylous/SniffAir)
* [kismograph](https://github.com/mattburch/kismograph)
* [warmap](https://github.com/rmikehodges/warmap-go)
#### Kali-Internal
* [metasploit](https://github.com/rapid7/metasploit-framework)
* [cobalt strike](https://www.cobaltstrike.com/)
* [cookiescan](https://github.com/tomsteele/cookiescan)
* [peepingJim](https://github.com/jamesbcook/peepingJim)
* [pywerview](https://github.com/the-useless-one/pywerview)
* [responder](https://github.com/lgandx/Responder)
* [impacket](https://github.com/CoreSecurity/impacket)
#### Credentials
* root:vagrant
* vagrant:vagrant
<file_sep># -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure('2') do |config|
config.vm.box = 'jbcook/kali-light'
config.vm.box_version = '1.0.0'
config.vm.provider 'virtualbox' do |vb|
# Display the VirtualBox GUI when booting the machine
# vb.gui = true
# Customize the amount of memory on the VM:
vb.memory = 1024
# Customize the amount of cpu on the VM:
vb.cpus = 1
end
config.vm.provider 'vmware_fusion' do |vb|
# Display the VirtualBox GUI when booting the machine
vb.gui = true
# Customize the amount of memory on the VM:
vb.vmx['memsize'] = 1024
# Customize the amount of cpu on the VM:
vb.vmx['numvcpus'] = 1
end
config.vm.provision 'shell', inline: <<-SHELL
apt-get update
apt-get install -y puppet
puppet module install puppetlabs-vcsrepo
SHELL
config.vm.provision :puppet
end
| a889eee2a0aea28c5f2559544af2a0b7a8afcfbf | [
"Markdown",
"Ruby"
] | 3 | Ruby | jamesbcook/vagrant | 4b7624ae4dd5ada639178eeed8c9d42312f7c141 | 0706e0aecc870e55704c6eb84a4d7dad80d42a04 |
refs/heads/main | <repo_name>feyzateker/-E-commerce-Website<file_sep>/index.php
<?php
include "config.php";
?>
<!doctype html>
<html lang="en" >
<head>
<style>
p.groove {border-style: groove;}
form {border: 3px solid #f1f1f1;}
</style>
<meta charset="utf-8">
<title>SUHOES</title>
<meta name="description" content="Bootstrap Recitation">
<meta name="author" content="CS306-201802">
<! Bootstrap files >
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="shortcut icon" type="image/ico" href="heels.jpg">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body >
<div style="background-image: url('bg.jpg');background-repeat: no-repeat; background-attachment: fixed;
background-size: 100% 100%;">
<div class="row justify-content-md-center text-warning" style="border: 5px outset #8b709e;">
<div class="col col-md-3" >
<img src="heels.jpg" width="160" height="160" alt="" class="d-inline-block align-top">
</div>
<div class="col col-md-9">
<div style="width:100%;">
<br>
<h1 style="color:#8b709e" >Welcome to the Heaven for Shoes</h1>
<div style="float:right;width:80%">
<p style="color:#8b709e">It's always SHOE O'CLOCK somewhere</p>
</div>
</div>
</div>
</div>
<br>
<div class="row justify-content-md-center">
<div class="container text-center">
<div style="float:left;width:40%; border: 2px outset #8b709e;" class="col-md-6">
<h2 style="color:#e75480 ">SIGN IN</h2>
<form action="products1.php" method ="post">
<label class="col-md-3" for="elogin" style="margin-top:40px;color:#58aee3;">E-MAIL:</label>
<input class="col-md-8" id="elogin" type="email" name="elogin" placeholder="Enter your e-mail"> <br>
<label class="col-md-3" for="password" style="margin-top:20px;color:#58aee3;">PASSWORD:</label>
<input class="col-md-8" id="password" type="<PASSWORD>" name="password" placeholder="Enter your password"> <br>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" name="manager" id="manager" style="margin-top:20px;">
<label class="custom-control-label" for="manager" style="margin-top:20px;">Manager Login</label>
</div>
<button type="submit" class="btn col-md-4" style="margin-top:40px;background-color:#e75480;color:#cceaea;">LOGIN</button>
</form>
<div class="row justify-content-md-center" >
<button type="submit" method="POST" id="pressed" class="text-light btn " style="margin-top:30px;background-color:#58aee3;color:white" name="pressed" type="btn-primary">
<a id="pressed" method="POST" name="pressed" href="products3.php" style="color:white">Continue without register/login</a></button>
</div>
</div>
<div style="float:right;width:60%;border: 2px outset #8b709e;" class="col-md-6">
<h2 style="color:#e75480" >SIGN UP</h2>
<form action="products2.php" method="post">
<label class="col-md-3" for="name" style="margin-top:20px;color:#58aee3;">NAME:</label>
<input class="col-md-8" id="name" type="text" name="name" placeholder="Enter your name"> <br>
<label class="col-md-3" for="surname" style="margin-top:20px;color:#58aee3;">SURNAME:</label>
<input class="col-md-8" id="surname" type="text" name="surname" placeholder="Enter your surname"> <br>
<label class="col-md-3" for="email" style="margin-top:20px;color:#58aee3;">E-MAIL:</label>
<input class="col-md-8" id="email" type="email" name="email" placeholder="Enter your e-mail"> <br>
<label class="col-md-3" for="password" style="margin-top:20px;color:#58aee3;">PASSWORD:</label>
<input class="col-md-8" id="password" type="<PASSWORD>" name="password" placeholder="Enter your password"> <br>
<label class="col-md-3" for="address" style="margin-top:20px;color:#58aee3;">ADDRESS:</label>
<textarea class="col-md-8" id="address" name="address" placeholder="Enter your address" style="margin-top:20px;"></textarea> <br>
<button type="submit" class="btn col-md-4" style="margin-top:20px;background-color:#e75480;color:#cceaea">SUBMIT</button>
</form>
</div>
<div style="clear:both;"></div>
</div>
<br><br><br>
</div>
</div> </div>
</body>
</html>
<?php
if(isset($_SESSION["message"]))
{
if(isset($_SESSION["already_customer"]) && $_SESSION["already_customer"])
{
echo '<script>alert("You already have an account")</script>';
$_SESSION['already_customer'] = false;
}
else if(isset($_SESSION["wrong_mail_pas"]) && $_SESSION["wrong_mail_pas"])
{
echo '<script>alert("Wrong e-mail or password")</script>';
$_SESSION['wrong_mail_pas'] = false;
}
$_SESSION["message"] = false;
}
?>
<file_sep>/add_product_man.php
<?php
include "config.php";
//z
//$db = mysqli_connect('localhost', 'root', '', 'group9');
$product_id = $_GET["product_id"] ;
$sql = "SELECT * FROM products p WHERE p.product_id = $product_id ;";
$result = mysqli_query($db, $sql);
$row_i = mysqli_fetch_assoc($result);
$piece = $row_i["stock"] + 1;
$sql_u = "UPDATE products SET stock= '$piece' WHERE product_id = '$product_id';";
$result = mysqli_query($db, $sql_u);
header("Location: table_man_product.php");
?><file_sep>/new_product_add.php
<?php
include "config.php";
$description= $_POST["description"];
$category= $_POST["category"];
$color= $_POST["color"];
$size= $_POST["size"];
$gender= $_POST["gender"];
$stock= $_POST["stock"];
$price= $_POST["price"];
$sql = "INSERT INTO products (description, category, color, size, gender, stock, price) VALUES('$description', '$category', '$color', '$size', '$gender', '$stock', '$price' );";
$result = mysqli_query($db, $sql);
header("Location: table_man_product.php");
?><file_sep>/products2.php
<?php
// Register Page
include "config.php";
echo"ikinci if\n";
$name = $_POST["name"];
$surname = $_POST["surname"];
$email = $_POST["email"];
$password = $_POST["password"];
$address = $_POST["address"];
$check_email = "SELECT c.email FROM customers c WHERE c.email = '$email'";
$res = mysqli_query($db, $check_email);
if (mysqli_num_rows($res)!=0)
{
echo "already cust\n";
$rows = mysqli_num_rows($res);
$_SESSION['already_customer'] = true;
$_SESSION['message'] = true;
header("Location: index.php");
}
else{ // create new customer
$give_basket = "INSERT INTO baskets (amount) VALUES(0)";
$res_basket = mysqli_query($db, $give_basket);
if($res_basket)
{
echo "basket given\n";
}
echo "res_basket\n";
$create_newb = "SELECT MAX(basket_id) as new_basket_id FROM baskets";
$result = mysqli_query($db, $create_newb);
$brow = mysqli_fetch_row($result);
$basket_id = $brow[0];
$_SESSION["basket_id"] = $basket_id;
echo $basket_id ;
if($result)
{
echo "basket_id added cust\n";
}
$sql_statement = "INSERT INTO customers(name, email, password, address, basket_id) VALUES (concat('$name',' ', '$surname'), '$email', '$password', '$address', '$basket_id')";
$result = mysqli_query($db, $sql_statement);
$sql="SELECT * FROM customers c WHERE c.basket_id = '$basket_id'";
$result = mysqli_query($db, $sql);
$brow = mysqli_fetch_row($result);
$_SESSION["id"] = $brow[0];
$_SESSION["name"] = $brow[1];
header("Location: no_account.php");
}
?><file_sep>/products1.php
<?php
// Login Page
include "config.php";
$email = $_POST["elogin"];
$password = $_POST["<PASSWORD>"];
$manager = isset($_POST["manager"]);
if(isset($_POST["manager"])) // Manager login
{
$sql_statement = "SELECT m.manager_id, m.name, m.role, m.password, m.role FROM managers m WHERE m.email = '$email' and m.password = '$<PASSWORD>'";
$result = mysqli_query($db, $sql_statement);
$rows = mysqli_num_rows($result);
if ($rows)
{
$brow = mysqli_fetch_row($result);
$_SESSION["manager_id"] = $brow[0];
$_SESSION["name"] = $brow[1];
if($brow[2] == "product-manager")
{
header("Location: table_man_product.php");
}
else
{
header("Location: table_man_sales.php");
}
}
else // entered wrong e-mail or password
{
$_SESSION["wrong_mail_pas"] = true;
$_SESSION["message"] = true;
header("Location: index.php");
}
}
else // customer login
{
$sql_statement = "SELECT c.customer_id, c.name, c.password, c.basket_id FROM customers c WHERE c.email = '$email' and c.password = '$<PASSWORD>'";
$result = mysqli_query($db, $sql_statement);
$rows = mysqli_num_rows($result);
$brow = mysqli_fetch_row($result);
$basket_id = $brow[3];
$_SESSION["basket_id"] = $basket_id;
$_SESSION["id"] = $brow[0];
$_SESSION["name"] = $brow[1];
if ($rows) // customer entered successfully
{
header("Location: table.php");
}
else // entered wrong e-mail or password
{
$_SESSION["wrong_mail_pas"] = true;
$_SESSION["message"] = true;
header("Location: index.php");
}
}
?>
<file_sep>/see_comment.php
<?php
include "config.php";
//z
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SUHOES</title>
<meta name="description" content="Bootstrap Recitation">
<meta name="author" content="CS306-201802">
<! Bootstrap files >
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light dg-light">
<div class="container">
<a href="table.php" class="navbar-brand">
<img src="heels.jpg" width="30" height="30" alt="" class="d-inline-block align-top">
<b> SUHOES</b>
</a>
<!responsive design>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"> </span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav mr-auto" >
<li class="nav-item active"><a class="nav-link" href="table.php">Home</a></li>
<li class="nav-item active"><a class="nav-link" href="women.php">Women</a></li>
<li class="nav-item active"><a class="nav-link" href="men.php">Men</a></li>
<li class="nav-item active"><a class="nav-link" href="child.php">Child</a></li>
</ul>
<span class="navbar-text">
<ul class="navbar-nav mr-auto">
<li class="nav-item active"><a class="nav-link" href="my_cart.php">My Cart</a></li>
<li class="nav-item active"><a class="nav-link" href="my_account.php">My Account</a></li>
<li class="nav-item active"><a class="nav-link" href="logout.php">Logout</a></li>
</ul>
</span>
</div>
<?php
echo $_SESSION["name"];
?>
</div>
</nav>
<div class="row justify-content-md-center" style=" margin-top:30px">
<div class="container text-center">
<div style="float:left;width:30%" class="col col-lg-12 col-md-8 container" >
<h2 style="margin-bottom:35px">PROPERTIES</h2>
<?php
$product_id = $_GET["product_id"];
$sql = "SELECT * FROM products p WHERE p.product_id=$product_id;";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
$my_categ = $row["category"];
$my_desc = $row["description"];
$my_color = $row["color"];
$my_size = $row["size"];
$my_gender = $row["gender"];
$my_price= $row["price"];
echo '<p>Category: '.$my_categ.' </p>';
echo '<p>Description: '.$my_desc.' </p>';
echo '<p>Color: '.$my_color.' </p>';
echo '<p>Size: '.$my_size.' </p>';
echo '<p>Gender: '.$my_gender.' </p>';
echo '<p>Price: '.$my_price.' </p>';
?>
</div>
<div class="col col-md-8" style="float:right;width:70%;">
<p class="lead" style="text-align:center ; color:purple; font-size:40px" ><b>COMMENTS - RATES</b></p>
<table class="table table-striped table-hover">
<thead class="thead-dark">
<tr>
<th scope="col" >Customer Name</th>
<th scope="col" >Comment</th>
<th scope="col" >Rate</th>
</tr>
</thead>
<tbody>
<?php
$product_id = $_GET["product_id"];
$sql = "SELECT c.name, co.comments, co.rate FROM comment_order co, customers c WHERE co.product_id = $product_id AND co.customer_id = c.customer_id;";
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_assoc($result))
{
$my_id = $product_id;
$name = $row["name"];
$comment= $row["comments"];
$rate = $row["rate"];
echo "<tr>" . "<th>" . $name . "</th>".
"<th>" . $comment . "</th>".
"<th>" . $rate . "</th>".
"</tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html><file_sep>/edit_order.php
<?php
include "config.php";
//z
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SUHOES</title>
<meta name="description" content="Bootstrap Recitation">
<meta name="author" content="CS306-201802">
<! Bootstrap files >
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light dg-light">
<div class="container">
<a href="table_man_sales.php" class="navbar-brand">
<img src="heels.jpg" width="30" height="30" alt="" class="d-inline-block align-top">
<b> SUHOES</b>
</a>
<!responsive design>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"> </span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav mr-auto" >
<li class="nav-item active"><a class="nav-link" href="table_man_sales.php">Orders</a></li>
</ul>
<span class="navbar-text">
<ul class="navbar-nav mr-auto">
<li class="nav-item active"><a class="nav-link" href="my_account_man.php">My Account</a></li>
<li class="nav-item active"><a class="nav-link" href="logout.php">Logout</a></li>
</ul>
</span>
</div>
<?php
echo $_SESSION["name"];
?>
</div>
</nav>
<div>
<br>
<div class=" justify-content-md-center">
<div style="text-align:center;" class="container text-center col-md-8 container">
<h2>ORDER DETAILS</h2>
<form action="change_order.php" method="post">
<?php
$order_id = $_GET["order_id"];
$sql = "SELECT * FROM orders o, includes i, products p WHERE p.product_id = i.product_id and i.basket_id = o.basket_id and o.order_id = $order_id;";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_assoc($result);
$status = $row["status"];
$c_name = $row["Recipient"];
$date = $row["date"];
$address = $row["destination"];
echo '<label class="col-md-3" for="order_id" style="margin-top:20px;">Order ID:</label>' .
'<input name="my_order_id" type="hidden" value="'.$order_id.'"></input>'.
'<label class="col-md-8" id="order_id" type="text" name="order_id">'.$order_id.'</label> <br>' .
'<label class="col-md-3" for="name" style="margin-top:20px;">Customer Name:</label>' .
'<label class="col-md-8" id="name" type="text" name="name">'.$c_name.'</label> <br>' .
'<label class="col-md-3" for="date" style="margin-top:20px;">Date:</label>' .
'<label class="col-md-8" id="date" type="text" name="date">'.$date.'</label> <br>' .
'<label class="col-md-3" for="address" style="margin-top:20px;">Adress:</label>' .
'<label class="col-md-8" id="address" type="text" name="address">'.$address.'</label> <br>' .
'<label class="col-md-3" for="status" style="margin-top:20px;">Status:</label>' ;
echo '<select name="status" id="status"> .
<option value="Pending">Pending</option>
<option value="Shipped">Shipped</option>
<option value="Delivered">Delivered</option>
<option value="Canceled">Canceled</option>
</select>';
echo '<div class="container">';
echo '<button type="submit" class="btn btn-success col-md-4" style="margin-top:20px">SAVE CHANGES</button>';
echo '</form>';
?>
<form action="table_man_sales.php">
<button type="submit" class="btn btn-danger col-md-4" style="margin-top:20px">CANCEL</button>
</form>
</div></div>
</div>
</div>
</body>
</html><file_sep>/Database.sql
-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jan 13, 2021 at 08:52 PM
-- Server version: 10.1.38-MariaDB
-- PHP Version: 5.6.40
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `group_9`
--
-- --------------------------------------------------------
--
-- Table structure for table `baskets`
--
CREATE TABLE `baskets` (
`basket_id` int(11) NOT NULL,
`amount` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `baskets`
--
INSERT INTO `baskets` (`basket_id`, `amount`) VALUES
(1, 4890),
(2, 2456),
(3, 4734),
(4, 1100),
(5, 550),
(6, 1878),
(7, 700),
(8, 978),
(9, 1467),
(10, 1378),
(11, 2200),
(12, 300),
(13, 4967),
(16, 1789),
(17, 1828),
(18, NULL),
(19, NULL),
(20, NULL),
(21, NULL),
(22, NULL),
(23, NULL),
(24, NULL),
(25, NULL),
(26, NULL),
(27, NULL),
(28, NULL),
(29, NULL),
(30, NULL),
(31, NULL),
(32, NULL),
(33, NULL),
(34, NULL),
(35, NULL),
(36, 9780),
(37, NULL),
(38, 3445),
(39, NULL),
(40, NULL),
(41, NULL),
(42, NULL),
(43, NULL),
(44, NULL),
(45, NULL),
(46, NULL),
(47, NULL),
(48, NULL),
(49, NULL),
(50, 689),
(51, 689),
(52, 1528),
(53, 4550),
(54, NULL),
(55, 500),
(56, 800),
(57, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `comment_order`
--
CREATE TABLE `comment_order` (
`product_id` int(11) NOT NULL,
`customer_id` int(11) NOT NULL,
`comments` char(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`rate` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `comment_order`
--
INSERT INTO `comment_order` (`product_id`, `customer_id`, `comments`, `rate`) VALUES
(1, 9, 'I will order one more for my sister.', 4),
(2, 2, 'You should order 1 or 2 smaller size', 3),
(2, 8, 'I like it packaged', 3),
(3, 10, 'I can wear it in my wedding tooooo', 4),
(4, 4, 'Its color is different from what I expected, but it is worth buying', 4),
(5, 5, 'I feel water in my boot :((', 2),
(5, 11, '50-50', 3),
(7, 3, 'It looks so cool on my girl.', 5),
(7, 12, 'You should order 1 or 2 smaller size', 3),
(9, 7, 'Love it !!', 5),
(9, 8, 'I like high heeeels', 2),
(10, 6, 'I waited 2 weeks to get my ship but I cant wait to wear it!!', 4);
-- --------------------------------------------------------
--
-- Table structure for table `customers`
--
CREATE TABLE `customers` (
`customer_id` int(11) NOT NULL,
`name` char(20) COLLATE utf8_unicode_ci NOT NULL,
`email` char(30) COLLATE utf8_unicode_ci NOT NULL,
`password` char(20) COLLATE utf8_unicode_ci NOT NULL,
`address` char(70) COLLATE utf8_unicode_ci NOT NULL,
`basket_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `customers`
--
INSERT INTO `customers` (`customer_id`, `name`, `email`, `password`, `address`, `basket_id`) VALUES
(2, '<NAME>', '<EMAIL>', '9989', 'Cumhuriyet Mahallesi Onikişubat / Kahramanmaraş', 57),
(3, '<NAME>', '<EMAIL>', '25101999', 'Cumhuriyet Mahallesi Efeler / Aydın', 53),
(4, '<NAME>', '<EMAIL>', '12345', 'Yeni Mahalle Safranbolu / Karabük', 18),
(5, '<NAME>', '<EMAIL>', '11111_duygu', 'Sabancı Üniversitesi Tuzla / İstanbul', 19),
(6, '<NAME>', '<EMAIL>', '11111_baris', 'Sabancı Üniversitesi Tuzla / İstanbul', 20),
(7, '<NAME>', '<EMAIL>', 'curcu__', 'Yen<NAME>ah<NAME>er / İstanbul', 21),
(8, '<NAME>', '<EMAIL>', 'sarikaya!1991', '<NAME> / İstanbul', 22),
(9, '<NAME>', '<EMAIL>', 'l&m5', '<NAME> / İstanbul', 23),
(10, '<NAME>', '<EMAIL>', '!+ECI+!', 'Çengelköy Mahallesi Üsküdar / İstanbul', 24),
(11, '<NAME>', '<EMAIL>', 'mertul_mertul', '<NAME>eler / Aydın', 25),
(12, 'Teoman', '<EMAIL>', 'artisteo', 'Gece Mahallesi Üsküdar / İstanbul', 26),
(13, '<NAME>', '<EMAIL>', '12345', 'Atatürk Mahallesi Merkez / Uşak', 1),
(14, 'zsdxfcgvh dfcgvhbn', '<EMAIL>', 'fcgvhbj', 'Cumhuriyet Provınce 1991 Street Number:11 Flat:5\r\nCumhuriyet Mahalles', 27),
(15, 'cfvb ds', '<EMAIL>', '25101999', 'dsf', 35);
-- --------------------------------------------------------
--
-- Table structure for table `includes`
--
CREATE TABLE `includes` (
`basket_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`piece` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `includes`
--
INSERT INTO `includes` (`basket_id`, `product_id`, `piece`) VALUES
(1, 1, 10),
(2, 2, 4),
(2, 6, 1),
(3, 3, 6),
(3, 7, 2),
(4, 4, 2),
(5, 5, 1),
(6, 8, 5),
(6, 10, 2),
(7, 9, 1),
(8, 2, 2),
(9, 1, 3),
(10, 3, 2),
(11, 5, 4),
(12, 7, 1),
(13, 1, 3),
(13, 9, 5),
(16, 6, 2),
(16, 7, 1),
(16, 8, 1),
(16, 10, 1),
(17, 2, 2),
(17, 4, 1),
(17, 7, 1),
(36, 2, 20),
(38, 3, 5),
(50, 3, 1),
(51, 3, 1),
(52, 1, 2),
(52, 4, 1),
(53, 5, 5),
(53, 7, 6),
(55, 6, 1),
(56, 6, 1),
(56, 8, 1);
-- --------------------------------------------------------
--
-- Table structure for table `managers`
--
CREATE TABLE `managers` (
`manager_id` int(11) NOT NULL,
`role` char(20) COLLATE utf8_unicode_ci NOT NULL,
`name` char(20) COLLATE utf8_unicode_ci NOT NULL,
`password` char(20) COLLATE utf8_unicode_ci NOT NULL,
`email` char(30) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `managers`
--
INSERT INTO `managers` (`manager_id`, `role`, `name`, `password`, `email`) VALUES
(1, 'sales-manager', 'John', 'John123', '<EMAIL>'),
(2, 'sales-manager', 'Kamil', 'password', '<EMAIL>'),
(3, 'sales-manager', 'Asude', 'demetakalinfan', '<EMAIL>'),
(4, 'sales-manager', 'Huseyin', 'fightclubhuseyin', '<EMAIL>'),
(5, 'sales-manager', 'Melissa', 'WinxClubBloom', '<EMAIL>'),
(6, 'product-manager', 'Elizabeth', 'Elizabethequeen', '<EMAIL>'),
(7, 'product-manager', 'Selena', 'selenabieber', '<EMAIL>'),
(8, 'product-manager', 'Ahmet', 'lolhahaha', '<EMAIL>'),
(9, 'product-manager', 'Aylin', 'redvampire', '<EMAIL>'),
(10, 'product-manager', 'Harry', 'rosesarered', '<EMAIL>');
-- --------------------------------------------------------
--
-- Table structure for table `orders`
--
CREATE TABLE `orders` (
`order_id` int(11) NOT NULL,
`customer_id` int(11) DEFAULT NULL,
`basket_id` int(11) NOT NULL,
`status` char(20) COLLATE utf8_unicode_ci DEFAULT NULL,
`date` date NOT NULL,
`destination` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
`Recipient` varchar(40) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `orders`
--
INSERT INTO `orders` (`order_id`, `customer_id`, `basket_id`, `status`, `date`, `destination`, `Recipient`) VALUES
(1, 2, 2, 'Canceled', '2020-12-16', 'Cumhuriyet Mahallesi Onikişubat / Kahramanmaraş', 'Müzeyyen Alkap'),
(2, 3, 3, 'Pending', '2020-12-16', 'Cumhuriyet Mahallesi Efeler / Aydın', 'Ayşenur Çerçi'),
(3, 4, 4, 'Delivered', '2020-12-16', 'Yeni Mahalle Safranbolu / Karabük', 'Eda Türker'),
(4, 5, 5, 'Pending', '2020-12-16', 'Sabancı Üniversitesi Tuzla / İstanbul', 'Barış Altop'),
(5, 6, 6, 'Shipped', '2020-12-16', 'Sabancı Üniversitesi Tuzla / İstanbul', 'Duygu Altop'),
(6, 7, 7, 'Shipped', '2020-12-16', '<NAME>tiler / İstanbul', '<NAME>'),
(7, 8, 8, 'Delivered', '2020-12-16', '<NAME> / İstanbul', 'Serenay Sarıkaya'),
(8, 9, 9, 'Pending', '2020-12-16', '<NAME> / İstanbul', 'Ali Atay'),
(9, 10, 10, 'Pending', '2020-12-16', '<NAME> Üsküdar / İstanbul', '<NAME>'),
(10, 11, 11, 'Delivered', '2020-12-16', '<NAME>feler / Aydın', '<NAME>'),
(11, 12, 12, 'Pending', '2020-12-16', '<NAME>dar / İstanbul', 'Teoman'),
(20, 3, 51, 'Shipped', '2021-01-10', '<NAME>ahallesi Efeler / Aydın', 'Ayşenur Çerçi'),
(21, 3, 52, 'Canceled', '2021-01-10', 'ev', 'Ayşenur Çerçi'),
(22, 2, 16, 'Pending', '2021-01-13', 'ev', 'muzo'),
(23, 2, 55, 'Pending', '2021-01-13', 'kmaras', 'a'),
(24, 2, 56, 'Pending', '2021-01-13', 'kmaras', 'ben');
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
`product_id` int(11) NOT NULL,
`category` char(30) COLLATE utf8_unicode_ci NOT NULL,
`price` int(11) NOT NULL,
`description` char(50) COLLATE utf8_unicode_ci NOT NULL,
`stock` int(11) NOT NULL,
`color` char(20) COLLATE utf8_unicode_ci NOT NULL,
`size` int(11) NOT NULL,
`gender` char(10) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`product_id`, `category`, `price`, `description`, `stock`, `color`, `size`, `gender`) VALUES
(1, 'Heels', 489, 'Stiletto', 100, 'purple', 39, 'Woman'),
(2, 'Heels', 489, 'Stiletto', 35, 'black', 39, 'Woman'),
(3, 'Boots', 689, 'Bootie', 22, 'red', 39, 'Woman'),
(4, 'Boots', 550, 'Leather-boots', 18, 'brown', 42, 'Man'),
(5, 'Boots', 550, 'Leather-boots', 20, 'black', 42, 'Man'),
(6, 'Sports', 500, 'Tennis-sneaker', 17, 'pink', 39, 'Woman'),
(7, 'Sports', 300, 'Child-sneaker', 49, 'blue', 32, 'Girl'),
(8, 'Sports', 300, 'Child-sneaker', 48, 'yellow', 33, 'Boy'),
(9, 'Boots', 700, 'Long-boots', 10, 'beige', 39, 'Woman'),
(10, 'Sandals', 189, 'Open-toe Sandal', 19, 'white', 39, 'Woman'),
(13, 'Heels', 450, 'Stiletto', 11, 'purple', 39, 'Woman'),
(14, 'Heels', 489, 'High', 10, 'white', 37, 'Woman'),
(15, 'Heels', 489, 'Platform', 20, 'black', 39, 'Woman'),
(16, 'Boots', 689, 'Platform', 10, 'red', 38, 'Woman'),
(17, 'Boots', 550, 'Pump', 10, 'brown', 39, 'Woman'),
(18, 'Casual', 550, 'Oxford', 20, 'black', 42, 'Man'),
(19, 'Boots', 500, 'Ankle-Boots', 20, 'pink', 39, 'Woman'),
(20, 'Heels', 249, 'High', 10, 'white', 38, 'Woman'),
(21, 'Heels', 379, 'Platform', 20, 'black', 39, 'Woman'),
(22, 'Boots', 349, 'Ankle-Boots', 10, 'red', 39, 'Woman'),
(23, 'Boots', 469, 'Pump', 10, 'brown', 39, 'Woman'),
(24, 'Casual', 340, 'Oxford', 20, 'grey', 41, 'Man'),
(25, 'Boots', 500, 'Ankle-Boots', 30, 'pink', 39, 'Woman');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `baskets`
--
ALTER TABLE `baskets`
ADD PRIMARY KEY (`basket_id`);
--
-- Indexes for table `comment_order`
--
ALTER TABLE `comment_order`
ADD PRIMARY KEY (`product_id`,`customer_id`),
ADD KEY `customer_id` (`customer_id`);
--
-- Indexes for table `customers`
--
ALTER TABLE `customers`
ADD PRIMARY KEY (`customer_id`),
ADD KEY `basket_id` (`basket_id`);
--
-- Indexes for table `includes`
--
ALTER TABLE `includes`
ADD PRIMARY KEY (`basket_id`,`product_id`),
ADD KEY `product_id` (`product_id`);
--
-- Indexes for table `managers`
--
ALTER TABLE `managers`
ADD PRIMARY KEY (`manager_id`);
--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
ADD PRIMARY KEY (`order_id`),
ADD KEY `customer_id` (`customer_id`),
ADD KEY `basket_id` (`basket_id`);
--
-- Indexes for table `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`product_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `baskets`
--
ALTER TABLE `baskets`
MODIFY `basket_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=58;
--
-- AUTO_INCREMENT for table `customers`
--
ALTER TABLE `customers`
MODIFY `customer_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;
--
-- AUTO_INCREMENT for table `managers`
--
ALTER TABLE `managers`
MODIFY `manager_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT for table `orders`
--
ALTER TABLE `orders`
MODIFY `order_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25;
--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `comment_order`
--
ALTER TABLE `comment_order`
ADD CONSTRAINT `comment_order_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`),
ADD CONSTRAINT `comment_order_ibfk_2` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `customers`
--
ALTER TABLE `customers`
ADD CONSTRAINT `customers_ibfk_1` FOREIGN KEY (`basket_id`) REFERENCES `baskets` (`basket_id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `includes`
--
ALTER TABLE `includes`
ADD CONSTRAINT `includes_ibfk_1` FOREIGN KEY (`basket_id`) REFERENCES `baskets` (`basket_id`),
ADD CONSTRAINT `includes_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `orders`
--
ALTER TABLE `orders`
ADD CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`),
ADD CONSTRAINT `orders_ibfk_2` FOREIGN KEY (`basket_id`) REFERENCES `baskets` (`basket_id`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/change_acc.php
<?php
include "config.php";
//z
//$db = mysqli_connect('localhost', 'root', '', 'group9');
$basket_id = $_SESSION["basket_id"] ;
$my_id = $_SESSION["id"] ;
$my_name = $_POST["name"];
$my_email = $_POST["email"];
$my_pass = $_POST["pass"];
$my_address = $_POST["address"];
echo $my_name;
$sql_u = "UPDATE customers SET name= '$my_name', email = '$my_email', password='<PASSWORD>', address = '$my_address' WHERE customer_id = '$my_id';";
$result = mysqli_query($db,$sql_u);
$_SESSION["name"] = $my_name;
header("Location: my_account.php");
?><file_sep>/edit_product_backend.php
<?php
include "config.php";
//z
//$db = mysqli_connect('localhost', 'root', '', 'group9');
$product_id = $_POST["product_id"] ;
echo $product_id;
$description= $_POST["description"];
$category= $_POST["category"];
$color= $_POST["color"];
$size= $_POST["size"];
$gender = $_POST["gender"];
$stock= $_POST["stock"];
$price= $_POST["price"];
echo $description;
$sql_u = "UPDATE products SET stock= '$stock', description='$description', category='$category', size='$size', color='$color', price='$price', gender='$gender' WHERE product_id = '$product_id';";
$result = mysqli_query($db, $sql_u);
echo $result;
header("Location: table_man_product.php");
?><file_sep>/buy.php
<?php
include "config.php";
$check= false;
$basket_id = $_SESSION["basket_id"] ;
$name = $_POST["name"];
$destination = $_POST["destination"];
// find the customer's id
$sql_c = "SELECT c.customer_id FROM customers c WHERE c.basket_id = $basket_id;";
$customer = mysqli_query($db, $sql_c);
$cust = mysqli_fetch_assoc($customer);
$customer_id = $cust["customer_id"];
echo $customer_id."\n";
// get all products inside the basket
$sql_p = "SELECT * FROM includes i WHERE i.basket_id = $basket_id;";
$result = mysqli_query($db, $sql_p);
//Decrement stock of the products
while($row = mysqli_fetch_assoc($result))
{
$product_id = $row["product_id"];
$piece = $row["piece"];
$sql_d = "SELECT * FROM products p WHERE p.product_id = $product_id;";
$result_d = mysqli_query($db, $sql_d);
$row_d = mysqli_fetch_assoc($result_d);
$stock = $row_d["stock"];
if($stock >= $piece) // enough stock
{
$diff= $stock - $piece;
$sql_dec = "UPDATE products SET stock='$diff' WHERE product_id = $product_id;";
$result_d = mysqli_query($db, $sql_dec);
$check = true;
}
else // not enough stock
{
$sql_del = "DELETE FROM includes WHERE basket_id = $basket_id;";
$result_d = mysqli_query($db, $sql_del);
}
}
//calculate invoice
$sql = "UPDATE baskets b SET amount= (SELECT SUM(p.price * i.piece)
FROM includes i, products p
WHERE i.product_id = p.product_id AND i.basket_id = ".$_SESSION["basket_id"].")
WHERE b.basket_id = ".$_SESSION["basket_id"].";" ;
$result = mysqli_query($db, $sql);
$sql_amount= "SELECT amount FROM baskets WHERE basket_id=".$_SESSION["basket_id"].";";
$result_amount = mysqli_query($db, $sql_amount);
$row = mysqli_fetch_assoc($result_amount);
$amount = $row["amount"];
// create the order
if($check){
echo $customer_id."\n";
echo $basket_id."\n"; echo $destination."\n"; echo $name."\n";
$sql = "INSERT INTO orders (customer_id, basket_id, status, date, destination, Recipient ) VALUES('$customer_id', '$basket_id', 'Pending', NOW() , '$destination', '$name');";
$res_basket = mysqli_query($db, $sql);
if($res_basket)
echo "insert order done \n";
//Update basket
$give_basket = "INSERT INTO baskets (amount) VALUES(0)";
$res_basket = mysqli_query($db, $give_basket);
if($res_basket)
echo "update basket done \n";
$create_newb = "SELECT MAX(basket_id) as new_basket_id FROM baskets";
$result = mysqli_query($db, $create_newb);
if($result)
echo "select max basket done \n";
$brow = mysqli_fetch_row($result);
$basket_id = $brow[0];
$_SESSION["basket_id"] = $basket_id;
//Update cust table
$sql_basket = "UPDATE customers SET basket_id = '$basket_id' WHERE customer_id='$customer_id'";
$res_basket = mysqli_query($db, $sql_basket);
if($result)
echo "update cust table done \n";
}
header("Location: orders.php");
?><file_sep>/README.md
# E-commerce-Website
An e-commerce website for a shoe store designed using PHP, made use of MySQL for database integration and management.
<file_sep>/change_order.php
<?php
include "config.php";
$status = $_POST["status"] ;
$order_id = $_POST["my_order_id"];
if ($status == 'Canceled')
{
$sql_p = "SELECT * FROM includes i, orders o WHERE o.order_id = $order_id and i.basket_id = o.basket_id;";
$result = mysqli_query($db, $sql_p);
while($row = mysqli_fetch_assoc($result))
{
$product_id = $row["product_id"];
$piece = $row["piece"];
$sql_d = "SELECT * FROM products p WHERE p.product_id = $product_id;";
$result_d = mysqli_query($db, $sql_d);
$row_d = mysqli_fetch_assoc($result_d);
$stock = $row_d["stock"];
$diff= $stock + $piece;
$sql_dec = "UPDATE products SET stock='$diff' WHERE product_id = $product_id;";
$result_d = mysqli_query($db, $sql_dec);
}
}
$sql_u = "UPDATE orders SET status= '$status' WHERE order_id = '$order_id';";
$result = mysqli_query($db,$sql_u);
header("Location: table_man_sales.php");
?><file_sep>/add.php
<?php
include "config.php";
//z
//$db = mysqli_connect('localhost', 'root', '', 'group9');
$basket_id = $_SESSION["basket_id"] ;
$product_id = $_GET["product_id"] ;
$sql = "SELECT * FROM includes i WHERE i.basket_id = $basket_id and i.product_id = $product_id ;";
$result = mysqli_query($db, $sql);
$row_i = mysqli_fetch_assoc($result);
if($row_i)
{
$piece = $row_i["piece"]+1;
echo $piece ;
$sql_u = "UPDATE includes SET piece= '$piece' WHERE basket_id = '$basket_id' and product_id = '$product_id';";
$result = mysqli_query($db, $sql_u);
if($result){
echo "done\n";}
}
else
{
echo "\nelse\n";
echo $basket_id;
echo $product_id;
$sql_s = "INSERT INTO includes (basket_id,product_id, piece) VALUES ('$basket_id', '$product_id' ,1);";
$result = mysqli_query($db, $sql_s);
if($result){
echo "done\n";}
}
header("Location: my_cart.php");
?><file_sep>/config.php
<?php
$db = mysqli_connect('localhost', 'root', '', 'group_9');
if ($db->connect_errno > 0)
{
die('Unable to connect.');
}
session_start();
?><file_sep>/delete.php
<?php
include "config.php";
//z
$basket_id = $_SESSION["basket_id"] ;
$product_id = $_GET["product_id"] ;
$sql = "SELECT * FROM includes i WHERE i.basket_id = $basket_id and i.product_id = $product_id ;";
$result = mysqli_query($db, $sql);
$row_i = mysqli_fetch_assoc($result);
$piece = $row_i["piece"];
echo "piece: ". $piece ."\n";
if($piece == 1)
{
echo "basket_id: " . $basket_id ."\n";
echo "pro_id: " . $product_id."\n";
$sql_del = "DELETE FROM includes WHERE basket_id = '$basket_id' AND product_id = '$product_id' ;";
mysqli_query($db, $sql_del);
}
else
{
$piece = $piece -1;
$sql_u = "UPDATE includes SET piece= '$piece' WHERE basket_id = '$basket_id' and product_id = '$product_id';";
$result = mysqli_query($db, $sql_u);
}
header("Location: my_cart.php");
?><file_sep>/table_man_sales.php
<?php
include "config.php";
//z
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SUHOES</title>
<meta name="description" content="Bootstrap Recitation">
<meta name="author" content="CS306-201802">
<! Bootstrap files >
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light dg-light">
<div class="container">
<a href="table_man_sales.php" class="navbar-brand">
<img src="balloon.png" width="30" height="30" alt="" class="d-inline-block align-top">
<b> SUHOES</b>
</a>
<!responsive design>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"> </span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav mr-auto" >
<li class="nav-item active"><a class="nav-link" href="table_man_sales.php">Orders</a></li>
</ul>
<span class="navbar-text">
<ul class="navbar-nav mr-auto">
<li class="nav-item active"><a class="nav-link" href="my_account_man.php">My Account</a></li>
<li class="nav-item active"><a class="nav-link" href="logout.php">Logout</a></li>
</ul>
</span>
</div>
<?php
echo $_SESSION["name"];
?>
</div>
</nav>
<div class="col-lg-12" >
<p class="lead" style="text-align:center ; color:purple; font-size:40px" ><b>ORDERS</b></p>
<table class="table table-striped table-hover">
<thead class="thead-dark">
<tr>
<th scope="col" >Status</th>
<th scope="col" >Date</th>
<th scope="col" >Invoice</th>
<th scope="col" >See products</th>
<th scope="col" >Edit Status</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM orders o WHERE o.status != 'Canceled';";
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_assoc($result))
{
$row_order_id = $row["order_id"];
$sql_b = "SELECT * FROM orders o, baskets b WHERE o.basket_id = b.basket_id and o.order_id = $row_order_id ;";
$result_b = mysqli_query($db, $sql_b);
$row_b = mysqli_fetch_assoc($result_b);
$my_status = $row["status"];
$my_date = $row["date"];
$my_invoice= $row_b["amount"];
// button seçtiremiyorux
echo "<tr>" . "<th>" . $my_status . "</th>".
"<th>" . $my_date . "</th>".
"<th>" . $my_invoice . "₺</th>".
"<th>".
'<button type="submit" id="detail" class="text-light btn btn-primary" name="detail" type="btn-primary">
<a id="pressed" style="color:white" href="order_pro_man.php?row_order_id='.$row_order_id.'">See in detail</a> </button>'
. "</th>" ."<th>".
'<button type="submit" id="detail" class="text-light btn btn-primary" name="detail" type="btn-primary">
<a id="pressed" style="color:white" href="edit_order.php?order_id='.$row_order_id.'">Edit</a> </button>'
. "</th>" . "</tr>";
}
?>
</tbody>
</table>
</div>
</body>
</html><file_sep>/comment.php
<?php
include "config.php";
//z
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SUHOES</title>
<meta name="description" content="Bootstrap Recitation">
<meta name="author" content="CS306-201802">
<! Bootstrap files >
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light dg-light">
<div class="container">
<a href="table.php" class="navbar-brand">
<img src="balloon.png" width="30" height="30" alt="" class="d-inline-block align-top">
<b> SUHOES</b>
</a>
<!responsive design>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"> </span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav mr-auto" >
<li class="nav-item active"><a class="nav-link" href="table.php">Home</a></li>
<li class="nav-item active"><a class="nav-link" href="women.php">Women</a></li>
<li class="nav-item active"><a class="nav-link" href="men.php">Men</a></li>
<li class="nav-item active"><a class="nav-link" href="child.php">Child</a></li>
</ul>
<span class="navbar-text">
<ul class="navbar-nav mr-auto">
<li class="nav-item active"><a class="nav-link" href="my_cart.php">My Cart</a></li>
<li class="nav-item active"><a class="nav-link" href="my_account.php">My Account</a></li>
<li class="nav-item active"><a class="nav-link" href="logout.php">Logout</a></li>
</ul>
</span>
</div>
<?php
echo $_SESSION["name"];
?>
</div>
</nav>
<div class="col-lg-12 col-md-6 container" >
<?php
$product_id = $_GET["product_id"];
$sql = "SELECT * FROM products p WHERE p.product_id=$product_id;";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
$my_categ = $row["category"];
$my_desc = $row["description"];
$my_color = $row["color"];
$my_size = $row["size"];
$my_gender = $row["gender"];
$my_price= $row["price"];
echo '<p>Category: '.$my_categ.' </p>';
echo '<p>Description: '.$my_desc.' </p>';
echo '<p>Color: '.$my_color.' </p>';
echo '<p>Size: '.$my_size.' </p>';
echo '<p>Gender: '.$my_gender.' </p>';
echo '<p>Price: '.$my_price.' </p>';
?>
<div style="text-align:center">
<label class="col-md-3 text-danger" for="comment" style="margin-top:20px; font-size:15px; font-color:red" >*You can only make 1 comment*</label><br>
</div>
<div class="container col-md-6" >
<form method="post" action="make_comment.php">
<?php echo '<input id="product_id" type="hidden" name="product_id" value='.$product_id.'></input>'; ?>
<label class="col-md-3" for="comment" style="margin-top:20px;">Comment:</label>
<input class="col-md-8" id="comment" type="text" name="comment" placeholder="Enter your comment"> <br>
<label class="col-md-3" for="rate" style="margin-top:20px;">Rate:</label>
<select name="rate" id="rate">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<div>
<input type="submit" id="add" value="Make Comment" class="text-light btn btn-success" name="add" type="btn-primary">
</div>
</form>
</div>
</div>
</body>
</html><file_sep>/products3.php
<?php
// Login without user Page
include "config.php";
echo "login olmadin";
$give_basket = "INSERT INTO baskets (amount) VALUES(0)";
$res_basket = mysqli_query($db, $give_basket);
if($res_basket)
{
echo "basket given\n";
}
echo "res_basket\n";
$create_newb = "SELECT MAX(basket_id) as new_basket_id FROM baskets";
$result = mysqli_query($db, $create_newb);
$brow = mysqli_fetch_row($result);
$basket_id = $brow[0];
$_SESSION["basket_id"] = $basket_id;
$_SESSION["name"] = "";
header('Location: table.php');
?><file_sep>/delete_product_man.php
<?php
include "config.php";
//z
$product_id = $_GET["product_id"] ;
$sql = "SELECT * FROM products p WHERE p.product_id = $product_id ;";
$result = mysqli_query($db, $sql);
$row_i = mysqli_fetch_assoc($result);
$stock = $row_i["stock"];
if($stock == 1)
{
$sql_del = "DELETE FROM products WHERE product_id = '$product_id' ;";
mysqli_query($db, $sql_del);
}
else
{
$stock = $stock -1;
$sql_u = "UPDATE products SET stock= '$stock' WHERE product_id = '$product_id';";
$result = mysqli_query($db, $sql_u);
}
header("Location: table_man_product.php");
?><file_sep>/make_comment.php
<?php
include "config.php";
//z
$customer_id = $_SESSION["id"];
$product_id = $_POST["product_id"] ;
$comment = $_POST["comment"];
$rate = $_POST["rate"];
echo $customer_id . " " . $product_id . " " . $comment . " " . $rate ;
$sql = "INSERT INTO comment_order (product_id, customer_id, comments, rate) VALUES ('$product_id','$customer_id', '$comment','$rate');";
$result = mysqli_query($db, $sql);
header("Location: orders.php");
?><file_sep>/change_acc_man.php
<?php
include "config.php";
//z
//$db = mysqli_connect('localhost', 'root', '', 'group9');
$my_id = $_SESSION["manager_id"] ;
$my_name = $_POST["name"];
$my_pass = $_POST["pass"];
echo $my_name;
$sql_u = "UPDATE managers SET name= '$my_name', password='$<PASSWORD>' WHERE manager_id = '$my_id';";
$result = mysqli_query($db,$sql_u);
$_SESSION["name"] = $my_name;
header("Location: my_account_man.php");
?><file_sep>/table.php
<?php
include "config.php";
//z
if( isset($_SESSION["msg_noacc"] ))
{
echo '<script>alert("You do not have an account.")</script>';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SUHOES</title>
<meta name="description" content="Bootstrap Recitation">
<meta name="author" content="CS306-201802">
<! Bootstrap files >
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="shortcut icon" type="image/ico" href="heels.jpg">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light dg-light">
<?php # navbar-dark bg-secondary"> ?>
<div class="container">
<a href="table.php" class="navbar-brand">
<img src="heels.jpg" width="30" height="30" alt="" class="d-inline-block align-top">
<b>SUHOES</b>
</a>
<!responsive design>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"> </span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav mr-auto" >
<li class="nav-item active"><a class="nav-link" href="table.php">Home</a></li>
<li class="nav-item active"><a class="nav-link" href="women.php">Women</a></li>
<li class="nav-item active"><a class="nav-link" href="men.php">Men</a></li>
<li class="nav-item active"><a class="nav-link" href="child.php">Child</a></li>
</ul>
<span class="navbar-text">
<ul class="navbar-nav mr-auto">
<li class="nav-item active"><a class="nav-link" href="my_cart.php">My Cart</a></li>
<li class="nav-item active"><a class="nav-link" href="my_account.php">My Account</a></li>
<li class="nav-item active"><a class="nav-link" href="logout.php">Logout</a></li>
</ul>
</span>
</div>
<?php
echo $_SESSION["name"];
?>
</div>
</nav>
<div class="col-lg-12" >
<form action="table.php" method="post">
<label for="search"><b>Search: </b></label>
<input type="search" id="search" name="search">
<br>
<label for="sort" ><b>Sort by: </b></label>
<select class="col-md-2" name="sort" id="sort" >
<option value="recommended">recommended</option>
<option value="price">price</option>
<option value="size">size</option>
<option value="description">description</option>
<option value="category">category</option>
<option value="color">color</option>
</select>
<input type="submit" value="SUBMIT" class="btn" style="background-color:#a76fe3;color:white;">
</form>
<p class="lead" style="text-align:center ; color:purple; font-size:40px" ><b>Products</b></p>
<table class="table table-striped table-hover">
<thead class="thead-dark">
<tr>
<th scope="col" >Category</th>
<th scope="col" >Description</th>
<th scope="col" >Color</th>
<th scope="col" >Size</th>
<th scope="col" >Gender</th>
<th scope="col" >Price</th>
<th scope="col" >Add to cart</th>
<th scope="col" >Comments/Rate</th>
</tr>
</thead>
<tbody>
<?php
$result;
//just search
if(isset($_POST["search"]) && !isset($_POST["sort"])){
$search = $_POST["search"];
$sql = "SELECT * FROM products p WHERE p.stock > 0 and
(p.description LIKE '%" . $search . "%' or
p.category LIKE '%" . $search . "%' or
p.color LIKE '%" . $search . "%' or
p.size LIKE '%" . $search . "%' or
p.gender LIKE '%" . $search . "%' or
p.price LIKE '%" . $search . "%' );";
$result = mysqli_query($db, $sql);
}
//just sort
else if(isset($_POST["sort"]) && !isset($_POST["search"]) && $_POST["sort"] != "recommended")
{
$sort = $_POST["sort"];
$sql = "SELECT * FROM products p WHERE p.stock > 0 ORDER BY ".$sort.";";
$result = mysqli_query($db, $sql);
}
//both
else if(isset($_POST["sort"]) && isset($_POST["search"]))
{
//just searched
if ($_POST["sort"] == "recommended")
{
$search = $_POST["search"];
$sql = "SELECT * FROM products p WHERE p.stock > 0 and
(p.description LIKE '%" . $search . "%' or
p.category LIKE '%" . $search . "%' or
p.color LIKE '%" . $search . "%' or
p.size LIKE '%" . $search . "%' or
p.gender LIKE '%" . $search . "%' or
p.price LIKE '%" . $search . "%' );";
$result = mysqli_query($db, $sql);
}
//both
else{
$search = $_POST["search"];
$sort = $_POST["sort"];
$sql = "SELECT * FROM products p WHERE p.stock > 0 and
(p.description LIKE '%" . $search . "%' or
p.category LIKE '%" . $search . "%' or
p.color LIKE '%" . $search . "%' or
p.size LIKE '%" . $search . "%' or
p.gender LIKE '%" . $search . "%' or
p.price LIKE '%" . $search . "%' ) ORDER BY ".$sort.";";
$result = mysqli_query($db, $sql);
}
}
//not searched and not sorted
else
{
echo "<tr>" . '<form method="post" action="table.php">'. "<th>" .
'<select name="category" id="category">' ;
$sql_c = "SELECT DISTINCT(p.category) FROM products p WHERE p.stock >0;";
$result_c = mysqli_query($db, $sql_c);
echo '<option value="All">All</option>';
while($row = mysqli_fetch_assoc($result_c))
{
$category = $row["category"];
echo '<option value="'.$category.'">'.$category.'</option>';
}
echo'</select>'. "</th>";
echo "<th>" . "</th>";
echo "<th>" . '<select name="color" id="color">' ;
$sql_co = "SELECT DISTINCT(p.color) FROM products p WHERE p.stock >0;";
$result_co = mysqli_query($db, $sql_co);
echo '<option value="All">All</option>';
while($row = mysqli_fetch_assoc($result_co))
{
$color = $row["color"];
echo '<option value="'.$color.'">'.$color.'</option>';
}
echo'</select>'. "</th>";
//size
echo "<th>" . '<select name="size" id="size">' ;
$sql_s = "SELECT DISTINCT(p.size) FROM products p WHERE p.stock >0;";
$result_s = mysqli_query($db, $sql_s);
echo '<option value="All">All</option>';
while($row = mysqli_fetch_assoc($result_s))
{
$size = $row["size"];
echo '<option value="'.$size.'">'.$size.'</option>';
}
echo '<div class="select">';
echo'</select>'. "</th>";
echo "<th>" . '<select name="gender" id="gender">' ;
$sql_g = "SELECT DISTINCT(p.gender) FROM products p WHERE p.stock >0;";
$result_g = mysqli_query($db, $sql_g);
echo '<option value="All">All</option>';
while($row = mysqli_fetch_assoc($result_g))
{
$gender = $row["gender"];
echo '<option value="'.$gender.'">'.$gender.'</option>';
}
echo '</div>';
echo'</select>'. "</th>";
//price
echo "<th>" . '<select name="price" id="price">' ;
echo '<option value="All">All</option>';
echo '<option value="200">0-200</option>';
echo '<option value="400">0-400</option>';
echo '<option value="500">0-500</option>';
echo '<option value="1000">0-1000</option>';
echo'</select>'. "</th>";
echo "<th colspan='2'>" . '<input type="submit" class="col-md-8 btn" style="background-color:#a76fe3;color:white;" value="Filter"/>' ."</th>";
echo '</form>' ."</tr>";
if(isset( $_POST["category"]) && $_POST["category"] != "All" )
{
$category = $_POST["category"];
}
else
{
$category = "%";
}
if(isset( $_POST["color"]) && $_POST["color"] != "All" )
{
$color = $_POST["color"];
}
else
{
$color = "%";
}
if(isset( $_POST["size"]) && $_POST["size"] != "All" )
{
$size = $_POST["size"];
}
else
{
$size = "%";
}
if(isset( $_POST["price"]) && $_POST["price"] != "All" )
{
$price = $_POST["price"];
}
else
{
$sql = "SELECT MAX(p.price) as max FROM products p WHERE p.stock > 0;";
$result_max = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result_max);
$price = $row["max"];
}
if(isset( $_POST["gender"]) && $_POST["gender"] != "All" )
{
$gender = $_POST["gender"];
}
else
{
$gender ="%";
}
$sql = "SELECT * FROM products p WHERE p.stock > 0 and p.category LIKE '".$category."'
and p.color LIKE '".$color."'
and p.size LIKE '".$size."'
and p.price <= '".$price."'
and p.gender LIKE '".$gender."';";
$result = mysqli_query($db, $sql);
}
//Recommendation
$customer_id = $_SESSION["id"];
$descriptions = (array) null;
$categories = (array) null;
$result_1 = mysqli_query($db, "SELECT DISTINCT(`category`) as cat FROM `products`");
while($row = mysqli_fetch_array($result_1)) {
$categories[$row['cat']] = 0;
}
$result_2 = mysqli_query($db, "SELECT DISTINCT(`description`) as des FROM `products`");
while($row = mysqli_fetch_array($result_2)) {
$descriptions[$row['des']] = 0;
}
$result_3 = mysqli_query($db, "SELECT `includes`.`product_id`, `includes`.`piece`, `products`.`description`, `products`.`category`
FROM `includes` JOIN `products` ON `includes`.`product_id` = `products`.`product_id`
WHERE `basket_id` in (SELECT `basket_id` FROM `orders`
WHERE `customer_id` = ".$customer_id.");");
while($row = mysqli_fetch_array($result_3)) {
$descriptions[$row['description']] += $row['piece'];
$categories[$row['category']] += $row['piece'];
}
arsort($descriptions);
arsort($categories);
reset($descriptions);
reset($categories);
$target_des = key($descriptions); # most common description
$target_cat = key($categories); # most common category
$sql_category3 = "SELECT * FROM products p WHERE p.stock > 0
and p.category ='".$target_cat."' and p.description != '".$target_des."' LIMIT 2;";
$result_4 = mysqli_query($db, $sql_category3);
while($row_2 = mysqli_fetch_assoc($result_4))
{
echo "<tr>" . "<th>" . $row_2["category"] . "</th>".
"<th>" . $row_2["description"] . "</th>".
"<th>" . $row_2["color"] . "</th>".
"<th>" . $row_2["size"] . "</th>".
"<th>" . $row_2["gender"] . "</th>".
"<th>" . $row_2["price"] . "₺</th>" .
"<th>".
'<button type="submit" id="add" class="text-light btn" name="add" style="background-color:#e75480;color:#cceaea;" type="btn-primary">
<a id="pressed" style="color:white;" href="add.php?product_id='. $row_2["product_id"].'">Rec. For You</a> </button>'
. "</th>" ."<th>".
'<button type="submit" id="add" class="text-light btn " style="background-color:#5091b8;color:white;" name="add" type="btn-primary">
<a id="pressed" style="color:white" href="see_comment.php?product_id='.$row_2["product_id"].'">See Comments</a> </button>'
. "</th>" .
"</tr>";
}
//end of Recommendation
while($row = mysqli_fetch_assoc($result))
{
$my_id = $row["product_id"];
//$_SESSION["product_id"] = $my_id;
$my_categ = $row["category"];
$my_desc = $row["description"];
$my_color = $row["color"];
$my_size = $row["size"];
$my_gender = $row["gender"];
$my_price= $row["price"];
// button seçtiremiyorux
echo "<tr>" . "<th>". $my_categ . "</th>".
"<th>" . $my_desc . "</th>".
"<th>" . $my_color . "</th>".
"<th>" . $my_size . "</th>".
"<th>" . $my_gender . "</th>".
"<th>" . $my_price ."₺". "</th>" .
"<th>".
'<button type="submit" id="add" class="text-light btn" name="add" style="background-color:#ef98aa;color:#cceaea;" type="btn-primary">
<a id="pressed" style="color:white" href="add.php?product_id='.$my_id.'">Add +1</a> </button>'
. "</th>" ."<th>".
'<button type="submit" id="add" class="text-light btn" name="add" style="background-color:#8cbbd8">
<a id="pressed" style="color:white" href="see_comment.php?product_id='.$my_id.'">See Comments</a> </button>'
. "</th>" .
"</tr>";
}
?>
</tbody>
</table>
</div>
</body>
</html> | 245d481bd8d0f20ac3fe8fc3f537abab91370cf7 | [
"Markdown",
"SQL",
"PHP"
] | 23 | PHP | feyzateker/-E-commerce-Website | d6da4a0e857f74006f5c1f507532e956f96c6dd1 | 86ea8c1fa3951fd20a58b027c5749bbcd13034a0 |
refs/heads/main | <file_sep>/api/login: pasar (user) y (password) despues de registrar al usuario
/api/logout: pasar (user) y (password) despues de generar el token del usuario
Lo mismo esta implementado en el apartado grafico (si tienes un usuario con un token activo, al entrar al login te inicia sesión automaticamente).
Una vez en la pantalla de "Se ha iniciado sesion correctamente" te da la opcion de borrar todos los tokens de todos los usuarios.
<file_sep>const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./scratch');
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index');
})
app.get('/login.ejs', (req, res) => {
for (let i= 0; i<localStorage.length; i++) {
lstotoken = localStorage.getItem(localStorage.key(i))
lstotoken = JSON.parse(lstotoken)
if (lstotoken['token']) {
res.render('confirmacion', {"confirmacion": 2 });
}
}
res.render('login');
})
app.get('/register.ejs', (req, res) => {
res.render('register');
})
app.post('/', (req, res) => {
let user = req.body.user;
let pass = req.body.password;
let data = {"password": <PASSWORD> };
localStorage.setItem(user,JSON.stringify(data));
res.render('index');
})
app.post('/confirmacion.ejs', (req, res) => {
let user = req.body.user;
let pass = req.body.password;
let confirmacion = 0;
for (let i= 0; i<localStorage.length; i++) {
if (user == localStorage.key(i)) {
let data = JSON.parse(localStorage.getItem(user));
if (pass == data['password']) {
updatedjson = localStorage.getItem(user);
updatedjson = JSON.parse(updatedjson);
let token = require("randomstring");
updatedjson['token'] = token.generate(10);
localStorage.setItem(user,JSON.stringify(updatedjson));
confirmacion = 1;
}
}
}
res.render('confirmacion', {"confirmacion": confirmacion });
})
app.get('/logout.ejs', (req, res) => {
for (let i= 0; i<localStorage.length; i++) {
lstotoken = localStorage.getItem(localStorage.key(i));
lstotoken = JSON.parse(lstotoken);
delete lstotoken['token'];
localStorage.setItem(localStorage.key(i), JSON.stringify(lstotoken));
}
res.render('index');
})
app.post("/api/login", function(req, res){
user = req.headers['user'];
password = req.headers['password'];
for (let i= 0; i<localStorage.length; i++) {
if (user == localStorage.key(i)) {
let data = JSON.parse(localStorage.getItem(user));
if (password == data['password']) {
updatedjson = localStorage.getItem(user);
updatedjson = JSON.parse(updatedjson);
let token = require("randomstring");
updatedjson['token'] = token.generate(10);
localStorage.setItem(user,JSON.stringify(updatedjson));
return res.send( "Nou token generat -> "+ updatedjson['token']+"\n");
}
return res.send("Contraseña incorrecta\n");
}
}
return res.send("Usuario no encontrado\n");
})
app.post("/api/logout", function (req, res){
user = req.headers['user'];
password = req.headers['password'];
for (let i= 0; i<localStorage.length; i++) {
if (user == localStorage.key(i)) {
let data = JSON.parse(localStorage.getItem(user));
if (password == data['password']) {
delete data['token'];
localStorage.setItem(localStorage.key(i), JSON.stringify(data));
return res.send("Token del usuario "+user+" borrado\n");
}
return res.send("Contraseña incorrecta\n");
}
}
return res.send("Usuario no encontrado\n");
for (let i= 0; i<localStorage.length; i++) {
lstotoken = localStorage.getItem(localStorage.key(i));
lstotoken = JSON.parse(lstotoken);
delete lstotoken['token'];
localStorage.setItem(localStorage.key(i), JSON.stringify(lstotoken));
}
res.send("Tokens eliminados\n");
})
app.listen(4000, () => console.log('Example app listening on port 4000!'));
| 262ce88c0c6254306cc16d58523e5eaf6b3e25ca | [
"Markdown",
"JavaScript"
] | 2 | Markdown | PMartinOnTheCloud/login-register | b94dc5bb0dd29599f4fcfa076c4cf51d689fa163 | 2516dc4bd1f6cfcb921d9af93c8482284ac5be5a |
refs/heads/master | <repo_name>noelcodella/segmentation-mask-utils<file_sep>/mergeImagesCMAP.py
# <NAME>
# python utility to merge/join multiple binary masks into a single color coded mask
# Combine multiple binary masks into a single color mask
# 4/24/2020
import sys
import cv2
import numpy as np
def main(argv):
if len(argv) < 2:
print 'Usage: \n\t <Output Image File> <Color Map File> <Resize> <Input Binary Mask 1> ... <Input Binary Mask N> \n\t\t Merge multiple binary masks into single color coded mask. Images must be same dimension. \nAssumes classes mutually exclusive. \nColor map is simply "R G B" per row. One row per class. Same row order as input. \nResize < 0 prevents resizing'
return
numfiles = len(argv)
# Color map file is simply a file with **RGB** values on each line
# separated by space
cmap = np.loadtxt(argv[1])
numc = cmap.shape[0]
# optional resize parameter
rsize = int(argv[2])
# get the shape of the first image
imdim = (cv2.imread(argv[3])).shape
# if resize was set, override
if (rsize > 0):
imdim = (rsize, rsize)
# create the merged color map mask
agg = np.zeros((imdim[0],imdim[1],3), np.uint8)
# iterate over all the binary masks
for i in range(3,numfiles):
tmp = cv2.imread(argv[i])
# if resize requested, perform it
if (rsize > 0):
tmp = cv2.resize(tmp, imdim)
# **BGR** pixel color order
c = np.flip(cmap[i-3])
for u in range(0,imdim[0]):
for v in range(0, imdim[1]):
# if mask pixel, change the aggregate to the current color
if (tmp[u,v,2] > 128):
agg[u,v,:] = c
cv2.imwrite(argv[0], agg)
return
if __name__ == "__main__":
main(sys.argv[1:])
<file_sep>/mergeImagesMAX.py
# <NAME>
# python utility to merge/join imbinary masks via a MAX operator
# Primary purpose is to merge annotation masks via an OR operation.
# 4/10/2020
import sys
import cv2
def main(argv):
if len(argv) < 2:
print 'Usage: \n\t <Output Binary Mask> <Input Binary Mask 1> ... <Input Binary Mask N> \n\t\t Merge binary masks by MAX operator. Images must be same format and dimension.'
return
numfiles = len(argv)
agg = None
for i in range(1,numfiles):
tmp = cv2.imread(argv[i])
if (agg is not None):
agg = cv2.max(agg, tmp)
else:
agg = tmp
cv2.imwrite(argv[0], agg)
return
if __name__ == "__main__":
main(sys.argv[1:])
<file_sep>/mergeImagesVOTE.py
# <NAME>
# python utility to merge/join imbinary masks via a VOTE operator
# Primary purpose is to merge annotation masks via an vote operation.
# 4/10/2020
import sys
import cv2
import numpy as np
def main(argv):
if len(argv) < 2:
print 'Usage: \n\t <rsize> <Output Binary Mask> <Input Binary Mask 1> ... <Input Binary Mask N> \n\t\t Merge binary masks by VOTE operator. Images must be same format and dimension. Output is not visible. Must use mergeImagesCMAPVOTE.'
return
numfiles = len(argv)
rsize = int(argv[0])
agg = None
for i in range(2,numfiles):
tmp = cv2.imread(argv[i])
if (rsize > 0):
tmp = cv2.resize(tmp, (rsize,rsize))
tmp = tmp / 254.
if (agg is not None):
agg = cv2.add(agg, tmp)
else:
agg = tmp
#agg = agg * (254./(numfiles-1))
if (agg is None):
agg = np.zeros((rsize,rsize,3), np.uint8)
cv2.imwrite(argv[1], agg)
return
if __name__ == "__main__":
main(sys.argv[1:])
<file_sep>/README.md
# segmentation-mask-utils
A repository of some python utilities to manipulate segmentation masks. These in particular will convert multiple binary segmentation masks to a single color mapped segmentation mask, or merge multiple binary masks of the same label into a single mask via MAX/OR/VOTE/AVG operators.
<file_sep>/drawColorMap.py
# <NAME>
import numpy as np
import sys
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure
figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')
def main(argv):
if len(argv) < 3:
print "Usage: \n\t <color map txt file> <labels txt file> <image output>"
return
cmap = np.loadtxt(argv[0])
labels = {}
with open(argv[1]) as f:
labels = f.read().splitlines()
numc = cmap.shape[0]
for i in range(0, numc):
plt.text(0.01,1.0-float(i)/numc, labels[i], size=5,linespacing=1.0, backgroundcolor=[cmap[i,0]/255, cmap[i,1]/255, cmap[i,2]/255])
plt.axis('off')
plt.tight_layout()
plt.savefig(argv[2],dpi=300)
return
if __name__ == "__main__":
main(sys.argv[1:])<file_sep>/genFigs.sh
#!/bin/bash
# A simple script to append an original image against the ground truth
# and model predictions for visual comparison. Takes as input 3 file
# lists as text files (original images, gt images, and predication
# masks), followed by an output folder. Results stored in the output
# folder according to the naming convention of the original images.
# All file lists should be in consistent order.
IFS=$'\n'
if [ $# -lt 4 ]
then
echo "Usage: $0 <orig list> <gt list> <pred list> <output folder>"
exit 1
fi
origl="$1"
gtl="$2"
predl="$3"
outf="$4"
mkdir -p $outf
tasks="$outf/tasks.txt"
cat $origl | sort > $outf/source.txt
cat $gtl | sort > $outf/gt.txt
cat $predl | sort > $outf/pred.txt
paste $outf/source.txt $outf/gt.txt $outf/pred.txt > $tasks
for line in `cat $tasks`
do
orig="`echo $line | awk -F'\t' '{print $1}'`"
gt="`echo $line | awk -F'\t' '{print $2}'`"
pred="`echo $line | awk -F'\t' '{print $3}'`"
ofile="$outf/`echo $orig | sed 's/.*\///g'`"
convert $orig $gt $pred -resize 512x512! -quality 100 +append $ofile
echo "Done $orig"
done
<file_sep>/createEmptyMask.py
# <NAME>
# 4/10/2020
import sys
import cv2
import numpy as np
def main(argv):
if len(argv) < 2:
print 'Usage: \n\t <Output Image File> <Input Image File> \n\t\t Create empty mask of same size as input'
return
tmp = cv2.imread(argv[1])
agg = np.zeros((tmp.shape[0],tmp.shape[1],tmp.shape[2]), tmp.dtype)
cv2.imwrite(argv[0], agg)
return
if __name__ == "__main__":
main(sys.argv[1:])
| 1499f4a6996888aa84de557dc8cbd7700aff61da | [
"Markdown",
"Python",
"Shell"
] | 7 | Python | noelcodella/segmentation-mask-utils | 9dba03f4ee1b4775ad8207ab166327e790b65c15 | 07c4243577a380c31d56f14aab15b01f8a9f0e93 |
refs/heads/master | <repo_name>ngerasimov7/WebStore<file_sep>/WebStore/Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using WebStore.Models;
namespace WebStore.Controllers
{
public class HomeController : Controller
{
private static readonly List<Employee> __Employees = new()
{
new Employee { Id = 1, LastName = "Иванов", FirstName = "Иван", Patronomic = "Иванович", Age = 36 },
new Employee { Id = 2, LastName = "Петров", FirstName = "Петр", Patronomic = "Петрович", Age = 25 },
new Employee { Id = 3, LastName = "Сидоров", FirstName = "Сидор", Patronomic = "Сидорович", Age = 46 }
};
public IActionResult Index() => View();
public IActionResult SecondAction()
{
return Content("Second controller action");
}
public IActionResult Employees()
{
return View(__Employees);
}
}
}
| 72cc7482277cfcf16d9c7a673090278f7915c88f | [
"C#"
] | 1 | C# | ngerasimov7/WebStore | 6eb1596fdd31286c257d21e5d2d30a2b98ef4db9 | 01d7ce66918d44a6db300f2175dacc728a187d10 |
refs/heads/master | <file_sep># qt-creator-ffmpeg-helloword
Qt集成ffmpeg
x64
<file_sep>#include "widget.h"
extern "C"{
#include "libavutil/log.h"
};
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
av_log_set_level(AV_LOG_DEBUG);
av_log(nullptr,AV_LOG_DEBUG,"hello world\n");
}
Widget::~Widget()
{
}
| 76dd329ade22e5f9ecc20f6cd8d7a64cc671c887 | [
"Markdown",
"C++"
] | 2 | Markdown | swq0001/qt-creator-ffmpeg-helloword | 565b860312e01ba29fa821da27d1f7ef95b8e88c | a5921794e4b2df07aec9121fc20fcb332165b76b |
refs/heads/master | <file_sep>#!/usr/bin/env bash
###################################################################
# ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ #
###################################################################
###################################################################
# Constants
###################################################################
readonly SIGMA=2.35482004503
readonly INT='^-?[0-9]+$'
readonly POSINT='^[0-9]+$'
readonly MOTIONTHR=0.2
readonly MINCONTIG=5
readonly POSNUM='^[0-9]+([.][0-9]+)?$'
###################################################################
###################################################################
# BEGIN GENERAL MODULE HEADER
###################################################################
###################################################################
# Read in:
# * path to localised design file
# * overall context in pipeline
# * whether to explicitly trace all commands
# Trace status is, by default, set to 0 (no trace)
###################################################################
trace=0
while getopts "d:c:t:" OPTION
do
case $OPTION in
d)
design_local=${OPTARG}
;;
c)
cxt=${OPTARG}
! [[ ${cxt} =~ $POSINT ]] && ${XCPEDIR}/xcpModusage mod && exit
;;
t)
trace=${OPTARG}
if [[ ${trace} != "0" ]] && [[ ${trace} != "1" ]]
then
${XCPEDIR}/xcpModusage mod
exit
fi
;;
*)
echo "Option not recognised: ${OPTARG}"
${XCPEDIR}/xcpModusage mod
exit
esac
done
shift $((OPTIND-1))
###################################################################
# Ensure that the compulsory design_local variable has been defined
###################################################################
[[ -z ${design_local} ]] && ${XCPEDIR}/xcpModusage mod && exit
[[ ! -e ${design_local} ]] && ${XCPEDIR}/xcpModusage mod && exit
###################################################################
# Set trace status, if applicable
# If trace is set to 1, then all commands called by the pipeline
# will be echoed back in the log file.
###################################################################
[[ ${trace} == "1" ]] && set -x
###################################################################
# Initialise the module.
###################################################################
echo ""; echo ""; echo ""
echo "###################################################################"
echo "# ⊗⊗ ⊗⊗⊗⊗ ⊗⊗⊗⊗⊗⊗⊗⊗⊗ ⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗ ⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗ ⊗⊗⊗⊗⊗⊗⊗⊗ ⊗⊗⊗⊗ ⊗⊗ #"
echo "# #"
echo "# ⊗ EXECUTING DICO MODULE ⊗ #"
echo "# #"
echo "# ⊗⊗ ⊗⊗⊗⊗ ⊗⊗⊗⊗⊗⊗⊗⊗⊗ ⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗ ⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗ ⊗⊗⊗⊗⊗⊗⊗⊗ ⊗⊗⊗⊗ ⊗⊗ #"
echo "###################################################################"
echo ""
###################################################################
# Source the design file.
###################################################################
source ${design_local}
###################################################################
# Verify that all compulsory inputs are present.
###################################################################
if [[ $(imtest ${out}/${prefix}) != 1 ]]
then
echo "::XCP-ERROR: The primary input is absent."
exit 666
fi
###################################################################
# Create a directory for intermediate outputs.
###################################################################
[[ ${NUMOUT} == 1 ]] && prep=${cxt}_
outdir=${out}/${prep}dico
[[ ! -e ${outdir} ]] && mkdir -p ${outdir}
echo "Output directory is $outdir"
###################################################################
# Define paths to all potential outputs.
#
# For the dico module, potential outputs include:
# * dico : The output time series with distortion correction
# * shiftmap : The output shift map - the direction and magnitude
# of the shift applied
# * shims : A output text file containing information about the
# shims performed for the functional series
# * nclips :
# * clipsMask : a spatial mask indicating whether each voxel is
# clipped
# * clipsMaskDico : Dico'ed clipsMask
# * quality : the temporal signal-to-noise ratio, where signal is
# defined as the mean intensity over time and noise is defined
# as the variation in the image intensity over time
# AND
# the number of voxels with "clipped" intensity
# values; that is, the number of voxels with intensity values
# that equal or exceed the maximum that can be recorded by the
# scanner
###################################################################
dico[${cxt}]=${outdir}/${prefix}_dico
shiftmap[${cxt}]=${outdir}/${prefix}_shiftmap
shiftmapclips[${cxt}]=${outdir}/${prefix}_clipsShiftmap
shims[${cxt}]=${outdir}/${prefix}_shims.txt
clipsMask[${cxt}]=${outdir}/${prefix}_clipsMask
clipsMaskDico[${cxt}]=${outdir}/${prefix}_clipsMaskDico
quality[${cxt}]=${outdir}/${prefix}_rawQuality.csv
###################################################################
# * Initialise a pointer to the image.
# * Ensure that the pointer references an image, and not something
# else such as a design file.
# * On the basis of this, define the image extension to be used for
# this module (for operations, such as AFNI, that require an
# extension).
# * Localise the image using a symlink, if applicable.
# * Define the base output path for intermediate files.
###################################################################
img=${out}/${prefix}
imgpath=$(ls ${img}.*)
for i in ${imgpath}
do
[[ $(imtest ${i}) == 1 ]] && imgpath=${i} && break
done
ext=$(echo ${imgpath}|sed s@${img}@@g)
[[ ${ext} == ".nii.gz" ]] && export FSLOUTPUTTYPE=NIFTI_GZ
[[ ${ext} == ".nii" ]] && export FSLOUTPUTTYPE=NIFTI
[[ ${ext} == ".hdr" ]] && export FSLOUTPUTTYPE=NIFTI_PAIR
[[ ${ext} == ".img" ]] && export FSLOUTPUTTYPE=NIFTI_PAIR
[[ ${ext} == ".hdr.gz" ]] && export FSLOUTPUTTYPE=NIFTI_PAIR_GZ
[[ ${ext} == ".img.gz" ]] && export FSLOUTPUTTYPE=NIFTI_PAIR_GZ
img=${outdir}/${prefix}~TEMP~
if [[ $(imtest ${img}) != "1" ]] || [ "${dico_rerun[${cxt}]}" == "Y" ] ; then
rm -f ${img}*
ln -s ${out}/${prefix}${ext} ${img}${ext}
fi
imgpath=$(ls ${img}${ext})
###################################################################
# Parse quality variables.
###################################################################
qvars=$(head -n1 ${quality} 2>/dev/null)
qvals=$(tail -n1 ${quality} 2>/dev/null)
###################################################################
# Prime the localised design file so that any outputs from this
# module appear beneath the correct header.
###################################################################
echo "" >> $design_local
echo "# *** outputs from dico[${cxt}] *** #" >> $design_local
echo "" >> $design_local
###################################################################
# Verify that the module should be run:
# * Test whether the final output already exists.
# * Determine whether the user requested the module to be re-run.
# If it is determined that the module should not be run, then any
# outputs must be written to the local design file.
###################################################################
if [[ $(imtest ${dico[${cxt}]}) == "1" ]] \
&& [[ "${dico_rerun[${cxt}]}" == "N" ]]
then
echo "[dico] has already run to completion."
echo "Writing outputs..."
rm -f ${out}/${prefix}${ext}
ln -s ${dico[${cxt}]}${ext} ${out}/${prefix}${ext}
################################################################
# OUTPUT: clipsMaskDico
# Test whether the mask of dico'ed clipped values exists as an
# image. If it does, then add it to the index of derivatives and
# to the localised design file.
################################################################
if [[ $(imtest ${clipsMaskDico[${cxt}]}) == 1 ]]
then
echo "#clipsMaskDico#${clipsMaskDico[${cxt}]}" \
>> ${auxImgs[${subjidx}]}
echo "clipsMaskDico[${subjidx}]=${clipsMaskDico[${cxt}]}" \
>> $design_local
fi
################################################################
# OUTPUT: tsnr
# Test whether the temporal SNR has been computed. If it has,
# then add it to the index of quality variables and to the
# localised design file.
################################################################
if [[ -e ${quality[${cxt}]} ]]
then
qvars=${qvars},$(head -n1 ${quality[${cxt}]})
qvals=${qvals},$(tail -n1 ${quality[${cxt}]})
fi
if [[ "${dico_cleanup[${cxt}]}" == "Y" ]]
then
echo ""; echo ""; echo ""
echo "Cleaning up..."
rm -rf ${outdir}/*~TEMP~*
fi
################################################################
# Since it has been determined that the module does not need to
# be executed, update the audit file and quality index, and
# exit the module.
################################################################
rm -f ${quality}
echo ${qvars} >> ${quality}
echo ${qvals} >> ${quality}
prefields=$(echo $(grep -o "_" <<< $prefix|wc -l) + 1|bc)
modaudit=$(expr ${prefields} + ${cxt} + 1)
subjaudit=$(grep -i $(echo ${prefix}|sed s@'_'@','@g) ${audit})
replacement=$(echo ${subjaudit}\
|sed s@[^,]*@@${modaudit}\
|sed s@',,'@',1,'@ \
|sed s@',$'@',1'@g)
sed -i s@${subjaudit}@${replacement}@g ${audit}
echo "Module complete"
exit 0
fi
###################################################################
###################################################################
# END GENERAL MODULE HEADER
###################################################################
###################################################################
echo "Processing image: $img"
###################################################################
###################################################################
# * Compute tSNR and Clips
###################################################################
###################################################################
###################################################################
# SNR computes quality metrics, including the temporal
# signal-to-noise ratio.
###################################################################
echo ""; echo ""; echo ""
echo "Current processing step:"
echo "Computing temporal signal-to-noise ratio"
if [[ -z $(cat ${quality[${cxt}]} 2>/dev/null) ]]
then
################################################################
# Determine whether a mask exists for the current subject.
# If one does not (for instance, if this is run before
# motion correxion), then automatically spawn a temporary
# mask.
################################################################
snrmask=${img}_tsnr_mask
if [[ $(imtest ${mask[${subject}]}) == 1 ]]
then
fslmaths ${mask[${subject}]} ${snrmask}
elif [[ $(imtest ${mask[${cxt}]}) == 1 ]]
then
fslmaths ${mask[${cxt}]} ${snrmask}
else
snrmask=${img}_snr_mask
3dAutomask \
-prefix ${snrmask}${ext} \
${img}${ext} \
2>/dev/null
fi
################################################################
# Determine whether the image is clipped at a maximal
# intensity.
################################################################
if [[ "${dico_clip[${cxt}]}" =~ ${POSNUM} ]]
then
#############################################################
# If the image is clipped, create a mask of voxels
# where the signal intensity at any point in time
# exceeds the maximal intensity.
#############################################################
if [[ ! -e ${clipsMask[${cxt}]} ]] \
|| [[ "${dico_rerun[${cxt}]}" == "Y" ]]
then
fslmaths ${img} \
-Tmax \
-thr ${dico_clip[${cxt}]} \
-bin \
${clipsMask[${cxt}]}
##########################################################
# Remove the clipped voxels from the tSNR mask so
# that they do not bias the results.
##########################################################
fslmaths ${clipsMask[${cxt}]} \
-sub 1 \
-abs \
-mul ${snrmask} \
${snrmask}
nclips=$(fslstats ${clipsMask[${cxt}]} -V \
|awk '{print $1}')
snrvars=nvoxel_clipped,
snrvals=${nclips},
fi
fi
################################################################
# Determine whether this has already been done.
################################################################
if [[ ! -e ${quality[${cxt}]} ]] \
|| [[ "${dico_rerun[${cxt}]}" == "Y" ]]
then
[[ -e ${quality[${cxt}]} ]] && rm -f ${quality[${cxt}]}
#############################################################
# Compute the tSNR of each voxelwise timeseries.
#############################################################
rm -f ${img}_${cur}${ext}
3dTstat \
-cvarinv \
-prefix ${img}_${cur}${ext} \
${img}${ext} \
2>/dev/null
tsnr_final=$(fslstats \
${img}_${cur} \
-k ${snrmask} \
-n \
-m)
snrvars=${snrvars}temporalSignalNoiseRatio
snrvals=${snrvals}${tsnr_final}
echo ${snrvars} >> ${quality[${cxt}]}
echo ${snrvals} >> ${quality[${cxt}]}
fi
fi
echo "Processing step complete:"
echo "Temporal SNR"
###################################################################
###################################################################
# * Apply the distortion correction
###################################################################
###################################################################
echo ""; echo ""; echo ""
echo "Current processing step:"
echo "Applying RPS map to time series"
###################################################################
# * Check to see if a example dicom is supplied
###################################################################
if [[ ! -e ${dico_exampleDicom[${cxt}]} ]] \
|| [[ -z ${dico_exampleDicom[${cxt}]} ]]
then
echo "XCP-WARNING: [ABORT] Example DICOM does not exist."
[[ "${dico_cleanup[${cxt}]}" == "Y" ]] \
&& rm -rf ${outdir}/*~TEMP~*
err=1
#qvars=${qvars},dicoComplete
#qvals=${qvals},0
fi
if [[ ! -e ${dico_magImage[${cxt}]} ]] \
|| [[ -z ${dico_magImage[${cxt}]} ]]
then
echo "XCP-WARNING: [ABORT] B0 magnitude map missing."
[[ "${dico_cleanup[${cxt}]}" == "Y" ]] \
&& rm -rf ${outdir}/*~TEMP~*
err=1
fi
if [[ ! -e ${dico_rpsImage[${cxt}]} ]] \
|| [[ -z ${dico_rpsImage[${cxt}]} ]]
then
echo "XCP-WARNING: [ABORT] B0 RPS map missing."
[[ "${dico_cleanup[${cxt}]}" == "Y" ]] \
&& rm -rf ${outdir}/*~TEMP~*
err=1
fi
###################################################################
# OUTPUT: quality
# Test whether the temporal SNR has been computed. If it has, then
# add it to the index of quality variables and to the localised
# design file.
#
# This is done here to ensure that the quality file is updated if
# there is no dico to be run.
###################################################################
if [[ -e ${quality[${cxt}]} ]] && [[ ${err} == 1 ]]
then
qvars=${qvars},$(head -n1 ${quality[${cxt}]})
qvals=${qvals},$(tail -n1 ${quality[${cxt}]})
rm -f ${quality}
echo ${qvars} >> ${quality}
echo ${qvals} >> ${quality}
fi
if [[ ${err} == 1 ]]
then
exit 666
fi
###################################################################
# * Now create the dico'ed nclip mask
# * If the clips mask exists
# * First, prepare the RPS mask.
###################################################################
rpsMaskImage=${img}rpsMask
if [[ $(imtest ${rpsMaskImage}) != 1 ]] \
|| [[ ${dico_rerun[${cxt}]} == Y ]]
then
fslmaths ${dico_rpsImage[${cxt}]} \
-abs \
-bin \
${rpsMaskImage}
fi
if [[ $(imtest ${clipsMask[${cxt}]}) == 1 ]]
then
${dico_script[${cxt}]} -n \
-FS \
-e ${dico_exampleDicom[${cxt}]} \
-f ${dico_magImage[${cxt}]} \
${outdir}/${prefix} \
${dico_rpsImage[${cxt}]} \
${rpsMaskImage}${ext} \
${clipsMask[${cxt}]}${ext}
################################################################
# * Now convert the images back to the input file type
# * Melliott's scripts only output nii images
################################################################
buffer=${FSLOUTPUTTYPE}
fslchfiletype ${buffer} ${dico[${cxt}]}.nii
fslchfiletype ${buffer} ${shiftmap[${cxt}]}.nii
export FSLOUTPUTTYPE=${buffer}
################################################################
# * Now apply the threshold and rebinarize the clips mask
# * Also mv the nclips shift mask to a new file
################################################################
fslmaths ${dico[${cxt}]} \
-thr .5 \
-bin \
${clipsMaskDico[${cxt}]}
rm -f ${dico[${cxt}]}${ext}
mv ${shiftmap[${cxt}]}${ext} ${shiftmapclips[${cxt}]}${ext}
fi
###################################################################
# * Now create the dico'ed time series
###################################################################
if [[ $(imtest ${dico[${cxt}]}) != 1 ]]
then
${dico_script[${cxt}]} -n \
-FS \
-e ${dico_exampleDicom[${cxt}]} \
-f ${dico_magImage[${cxt}]} \
${outdir}/${prefix} \
${dico_rpsImage[${cxt}]} \
${rpsMaskImage}${ext} \
${img}${ext}
################################################################
# * Now convert the images back to the input file type
# * Melliott's scripts only output nii images
################################################################
buffer=${FSLOUTPUTTYPE}
fslchfiletype ${buffer} ${dico[${cxt}]}
fslchfiletype ${buffer} ${shiftmap[${cxt}]}
export FSLOUTPUTTYPE=${buffer}
fi
###################################################################
# Write any remaining output paths to local design file so that
# they may be used further along the pipeline.
###################################################################
echo ""; echo ""; echo ""
echo "Writing outputs..."
rm -f ${out}/${prefix}${ext}
ln -s ${dico[${cxt}]}${ext} ${out}/${prefix}${ext}
###################################################################
# OUTPUT: quality
# Test whether the temporal SNR has been computed. If it has, then
# add it to the index of quality variables and to the localised
# design file.
###################################################################
if [[ -e ${quality[${cxt}]} ]]
then
qvars=${qvars},$(head -n1 ${quality[${cxt}]})
qvals=${qvals},$(tail -n1 ${quality[${cxt}]})
fi
###################################################################
# OUTPUT: clipsMaskDico
# Test whether the mask of dico'ed clipped values exists as an
# image. If it does, then add it to the index of derivatives and
# to the localised design file.
###################################################################
if [[ $(imtest ${clipsMaskDico[${cxt}]}) == 1 ]]
then
echo "#clipsMaskDico#${clipsMaskDico[${cxt}]}" \
>> ${auxImgs[${subjidx}]}
echo "clipsMaskDico[${subjidx}]=${clipsMaskDico[${cxt}]}" \
>> $design_local
fi
###################################################################
# CLEANUP
# * Remove any temporary files if cleanup is enabled.
# * Update the audit file and quality index.
###################################################################
echo ""; echo ""; echo ""
if [[ "${dico_cleanup[${cxt}]}" == "Y" ]]
then
echo ""; echo ""; echo ""
echo "Cleaning up..."
rm -rf ${outdir}/*~TEMP~*
fi
rm -f ${quality}
echo ${qvars} >> ${quality}
echo ${qvals} >> ${quality}
prefields=$(echo $(grep -o "_" <<< $prefix|wc -l) + 1|bc)
modaudit=$(expr ${prefields} + ${cxt} + 1)
subjaudit=$(grep -i $(echo ${prefix}|sed s@'_'@','@g) ${audit})
replacement=$(echo ${subjaudit}\
|sed s@[^,]*@@${modaudit}\
|sed s@',,'@',1,'@ \
|sed s@',$'@',1'@g)
sed -i s@${subjaudit}@${replacement}@g ${audit}
echo "Module complete"
<file_sep># schaefer100
Multiscale local-global functional atlas from Schaefer and colleagues: 100-node resolution
<file_sep>
xcpEngine on Flywheel
===================================
The xcpEngine can be run on `flywheel <https://upenn.flywheel.io>`_. The procedure is the same is as runnning it on computers/clusters.
.. figure:: _static/xcpengineflywheel.png
xcpEngine on Flywheel
The `design file <https://xcpengine.readthedocs.io/config/design.html>`_ is compulsory for any analysis.
Preprocessing of BOLD data require prior preprocessing with `FMRIPREP`. The FMRIPREP output directory needs to be supplied
as shown below.
.. figure:: _static/xcpenginelayout.png
xcpEngine input layout on Flywheel
The cohort file will be created base on the FMRIPREP output. The `img` is input directory for CBF. The processing of CBF requires the
anatomical preprocessing from FRMIPREP. The `m0` is the M0 directory for CBF calibration if present. The `struct` is the directory for
T1w image for structural preprocessing.
After successful run, the `xcpEngine` zips the results and cohort file to analyses directory of the subject as shown below.
.. figure:: _static/xcpengineoutput.png
xcpEngine output layout on Flywheel<file_sep>#!/usr/bin/env bash
###################################################################
# ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ ⊗ #
###################################################################
###################################################################
# SPECIFIC MODULE HEADER
# This module aligns the analyte image to a high-resolution target.
###################################################################
mod_name_short=scrub
mod_name='CBF scrubbing'
mod_head=${XCPEDIR}/core/CONSOLE_MODULE_RC
###################################################################
# GENERAL MODULE HEADER
###################################################################
source ${XCPEDIR}/core/constants
source ${XCPEDIR}/core/functions/library.sh
source ${XCPEDIR}/core/parseArgsMod
###################################################################
# MODULE COMPLETIO
###################################################################
completion() {
source ${XCPEDIR}/core/auditComplete
source ${XCPEDIR}/core/updateQuality
source ${XCPEDIR}/core/moduleEnd
}
##################################################################
# OUTPUTS
###################################################################
derivative cbfscorets ${prefix}_cbfscorets.nii.gz
derivative cbfscore ${prefix}_cbfscore.nii.gz
derivative cbfscrub ${prefix}_cbfscrub.nii.gz
output cbfscorets ${prefix}_cbfscorets.nii.gz
output cbfscore ${prefix}_cbfscore.nii.gz
output cbfscrub ${prefix}_cbfscrub.nii.gz
qc nvoldel nvoldel ${prefix}_nvoldel.txt
derivative_set cbfscore Statistic mean
derivative_set cbfscrub Statistic mean
gm_seq=${out}/scrub/${prefix}_gm2seq.nii.gz
wm_seq=${out}/scrub/${prefix}_wm2seq.nii.gz
csf_seq=${out}/scrub/${prefix}_csf2seq.nii.gz
mask1=${intermediate}_mask_seq.nii.gz
mask_asl=${out}/scrub/${prefix}_mask_asl.nii.gz
struct_asl=${out}/scrub/${prefix}_struct_seq.nii.gz
if is_image ${struct[sub]}
then
exec_ants antsApplyTransforms -e 3 -d 3 -r ${referenceVolume[sub]} \
-i ${gm[sub]} -t ${struct2seq[sub]} \
-o ${gm_seq} -n NearestNeighbor
exec_ants antsApplyTransforms -e 3 -d 3 -r ${referenceVolume[sub]} \
-i ${wm[sub]} -t ${struct2seq[sub]} \
-o ${wm_seq} -n NearestNeighbor
exec_ants antsApplyTransforms -e 3 -d 3 -r ${referenceVolume[sub]} \
-i ${csf[sub]} -t ${struct2seq[sub]} \
-o ${csf_seq} -n NearestNeighbor
exec_ants antsApplyTransforms -e 3 -d 3 -r ${referenceVolume[sub]} \
-i ${structmask[sub]} -t ${struct2seq[sub]} \
-o ${mask1} -n NearestNeighbor
exec_fsl fslmaths ${referenceVolume[sub]} -mul ${mask1} \
-bin ${mask_asl}
output mask ${out}/scrub/${prefix}_mask_asl.nii.gz
exec_ants antsApplyTransforms -e 3 -d 3 -r ${referenceVolume[sub]} \
-i ${struct[sub]} -t ${struct2seq[sub]} \
-o ${struct_asl} -n NearestNeighbor
exec_fsl fslmaths ${referenceVolume[sub]} -mul \
${mask1} ${out}/scrub/${prefix}_referenceVolumeBrain.nii.gz
output referenceVolumeBrain ${out}/scrub/${prefix}_referenceVolumeBrain.nii.gz
fi
subroutine @1.2 computing cbf score
# obtain the score
exec_xcp score.R \
-i ${perfusion[sub]} \
-g ${gm_seq} \
-w ${wm_seq} \
-c ${csf_seq} \
-t ${scrub_thresh[cxt]} \
-o ${out}/scrub/${prefix}
subroutine @1.3 computing cbf scrubbing
# compute the scrub
exec_xcp scrub_cbf.R \
-i ${cbfscorets[cxt]} \
-g ${gm_seq} \
-w ${wm_seq} \
-m ${mask[cxt]} \
-c ${csf_seq} \
-t ${scrub_thresh[cxt]} \
-o ${out}/scrub/${prefix}
routine_end
completion
| 7b96f370d9b372e60f2ec51e550d236052d43f84 | [
"Markdown",
"reStructuredText",
"Shell"
] | 4 | Shell | mcmahonmc/xcpEngine | 78deca684b4211f2f1d1b4824b9cbceb2511c754 | 75dc7408de35bef0f20af51bcce507161bc6a0fe |
refs/heads/master | <file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Validator;
class blogpost extends Model
{
protected $table = 'blogpost';
protected $fillable = ['users_id', 'title', 'content', 'comment_count', 'published_at',
];
protected function validateData($post){
$rules =array('title' => 'required|Min:3|Max:80|unique:blogpost',
'content' => 'required|Min:15|Max:500',
);
$validator = Validator::make($post,$rules);
return $validator;
}
}
<file_sep><?php if (!class_exists('CaptchaConfiguration')) { return; }
// BotDetect PHP Captcha configuration options
$LBD_CaptchaConfig = CaptchaConfiguration::GetSettings();
$LBD_CaptchaConfig->CodeLength = 4;
$LBD_CaptchaConfig->ImageWidth = 250;
$LBD_CaptchaConfig->ImageHeight = 50;<file_sep><?php
namespace App\Http\Controllers;
use DB;
use Session;
use App\Http\Requests;
use Illuminate\Http\Request;
use LaravelCaptcha\Integration\BotDetectCaptcha;
use Illuminate\Pagination\LengthAwarePaginator;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
// public function __construct()
// {
// $this->middleware('auth');
// }
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$result=DB::table('blogpost')->orderBy('created_at','desc')->paginate(5);
return view ('home')->with ('data',$result);
}
public function contact()
{
return view('auth/contact');
}
public function about()
{
return view('auth/about');
}
public function savecontact(Request $request)
{
$post=$request->all();
$v=\Validator::make($request-> all(),
[
'firstname'=> 'required',
'lastname'=> 'required',
'email'=> 'required',
'comment'=> 'required',
]);
if($v->fails())
{
return redirect()->back()->withErrors($v->errors());
}
else
{
unset($post['_token']);
$i=DB::table('contactus')->insert($post);
if($i>0)
{
Session::flash('message','Record inserted');
return redirect('home');
}
}
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
use Session;
class contactus extends Model
{
protected $collection = 'contactus';
protected function save_contact($title,$content)
{
$post=$request->all();
$v=\Validator::make($request-> all(),
[
'firstname'=> 'required',
'lastname'=> 'required',
'email'=> 'required',
'comment'=> 'required'
]);
if($v->fails())
{
return redirect()->back()->withErrors($v->errors());
}
else
{
$user = new contactus;
$user->firstname = $firstname;
$user->lastname = $lastname;
$user->email = $email;
$user->comment = $comment;
$user->save();
return true;
}
}
}<file_sep><?php
/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in 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.
|
*/
// Route::get('/', function () {
// return view('welcome');
// });
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/
Route::group(['middleware' => ['web']], function () {
//
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
//Route::get('approv_comment/{id}', 'AdminController@approv_comment');
Route::get('/', 'HomeController@index');
Route::get('comment/{id}', 'UserController@comment');
Route::get('admincomment', 'AdminController@admincomment');
Route::post('savecomment', 'UserController@savecomment');
Route::get('deletecomment/{id}','AdminController@deletecomment');
Route::get('/Admin', 'AdminController@index');
Route::get('home', 'HomeController@index');
Route::get('blogpost', 'AdminController@blogpost');
Route::get('showblog', 'UserController@showblog1');
Route::post('save', 'AdminController@save');
Route::get('delete/{id}','AdminController@delete');
Route::get('blogedit/{id}','AdminController@blogedit');
Route::post('update', 'AdminController@update');
Route::get('cms', 'AdminController@cms');
Route::get('showcms', 'UserController@showcms');
Route::post('savecms', 'AdminController@savecms');
Route::get('contact', 'HomeController@contact');
Route::get('about', 'HomeController@about');
Route::get('editprofile', 'UserController@editprofile1');
Route::get('editprofile/{id}', 'AdminController@editprofile1');
Route::post('updateprofile', 'UserController@updateprofile');
Route::get('showuser', 'AdminController@showuser');
Route::get('deleteuser/{id}','AdminController@deleteuser');
Route::post('savecontact', 'HomeController@savecontact');
Route::get('showcontact', 'AdminController@showcontact');
Route::get('deletecontact/{id}','AdminController@deletecontact');
Route::get('adduser', 'AdminController@adduser');
Route::post('saveuser', 'AdminController@saveuser');
//approv_comment
});
<file_sep><?php
namespace App\Http\Controllers;
use DB;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Pagination\LengthAwarePaginator;
use Session;
use Validator;
class AdminController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$result=DB::table('blogpost')->paginate(10);
return view ('Admin')->with ('data',$result);
//return view('home');
}
public function showuser()
{
$result=DB::table('users')->where('role','user')->paginate(10);
return view ('admin/showuser')->with ('data',$result);
//return view('home');
}
public function deleteuser($id)
{
$i=DB::table('users')->where('id',$id)->delete();
if($i>0)
{
return redirect('Admin');
}
}
public function blogpost()
{
$id = \Auth::id();
return view('admin/blogpost')->with ('id',$id);
}
public function save(Request $request)
{
$post=$request->all();
$v=\Validator::make($request-> all(),
[
'title'=> 'required|Min:3|Max:80|unique:blogpost',
'content'=> 'required|Min:15|Max:500',
]);
if($v->fails())
{
return redirect()->back()->withErrors($v->errors());
}
else
{
unset($post['_token']);
$i=DB::table('blogpost')->insert($post);
if($i>0)
{
Session::flash('message','Record inserted');
return redirect('Admin');
}
}
}
public function delete($id)
{
$i=DB::table('blogpost')->where('id',$id)->delete();
if($i>0)
{
return redirect('Admin');
}
}
public function blogedit($id)
{
$i=DB::table('blogpost')->where('id',$id)->first();
return view ('admin/blogedit')->with('row',$i);
}
public function update(Request $request)
{
$cid=$request['id'];
$post=$request->all();
unset($post['_token']);
$i=DB::table('blogpost')->where('id',$cid)->update($post);
if($i>0)
{
Session::flash('message','Record inserted');
return redirect('Admin');
}
}
public function cms()
{
$id = \Auth::id();
return view('admin/cms')->with ('id',$id);
}
public function savecms(Request $request)
{
$post=$request->all();
$v=\Validator::make($request-> all(),
[
'title'=> 'required|Min:3|Max:80',
'content'=> 'required|Min:15|Max:500',
]);
if($v->fails())
{
return redirect()->back()->withErrors($v->errors());
}
else
{
unset($post['_token']);
$i=DB::table('cms')->insert($post);
if($i>0)
{
Session::flash('message','Record inserted');
return redirect('Admin');
}
}
}
public function admincomment()
{
$result=DB::table('comment')->paginate(3);
return view ('admin/admincomment')->with ('data',$result);
//return view('home');
}
public function deletecomment($id)
{
$i=DB::table('comment')->where('id',$id)->delete();
if($i>0)
{
return redirect('Admin');
}
}
public function editprofile1($id)
{
$i=DB::table('users')->where('id',$id)->first();
return view ('editprofile')->with('row',$i);
}
public function showcontact()
{
$result=DB::table('contactus')->paginate(10);
return view ('admin/showcontact')->with ('data',$result);
//return view('home');
}
public function deletecontact($id)
{
$i=DB::table('contactus')->where('id',$id)->delete();
if($i>0)
{
return redirect('Admin');
}
}
public function adduser()
{
return view('admin/adduser');
}
public function saveuser(Request $request)
{
//$post=$request->all();
// unset($post['_token']);
$arrayName = array(
'name' => $request['name'],
'email' => $request['email'],
'password' => bcrypt($request['password']),
);
$i=DB::table('users')->insert($arrayName );
if($i>0)
{
Session::flash('message','Record inserted');
return redirect('Admin');
}
}
// public function approv_comment($id)
// {
// $userid = "";
// $get_data = DB::table('comment')->where('id',$id)->get();
// foreach ($get_data as $value) {
// $userid = $value->users_id;
// }
// //print_r($res);
// $res1 = DB::table('users')->join('comment', 'comment.users_id', '=', 'users.id')->where('users.id','=',$userid)->select('users.id','comment.comment')->get();
// //print_r($res1);
// return view('home')->with ('data',$res1);
// }
// //return view('testtt')->with('data1',$res);
}
<file_sep><?php
namespace App\Http\Controllers;
use DB;
use Session;
use Validator;
use App\User;
use App\Http\Requests;
use Illuminate\Http\Request;
use LaravelCaptcha\Integration\BotDetectCaptcha;
use Illuminate\Pagination\LengthAwarePaginator;
class UserController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('home');
}
public function showblog1()
{
$result=DB::table('blogpost')->paginate(10);
return view ('showblog')->with ('data',$result);
}
public function showcms()
{
$result=DB::table('cms')->paginate(5);
return view ('showcms')->with ('data',$result);
}
public function comment($id)
{
$row = DB::table('blogpost')->where('id',$id)->first();
return view('comment')->with('row',$row);
}
public function showcomment()
{
$result=DB::table('comment')->paginate(5);
return view ('comment')->with ('data',$result);
}
public function savecomment(Request $request)
{
$blogpost_id1 = $request['blogpost_id'];
$users_id1 = \Auth::id();
$arrayName1 = array(
'users_id' => $users_id1,
'blogpost_id' => $blogpost_id1,
'commenter' => $request['commenter'],
'email' => $request['email'],
'comment' => $request['comment'],
);
$v=\Validator::make($request-> all(),
[
'commenter'=> 'required',
'email'=> 'required',
'comment'=> 'required',
]);
if($v->fails())
{
return redirect()->back()->withErrors($v->errors());
}
else
{
$i=DB::table('comment')->insert($arrayName1);
if($i>0)
{
Session::flash('message','Record inserted');
return redirect('home');
}
}
}
public function editprofile1()
{
$id = \Auth::id();
$i=DB::table('users')->where('id',$id)->first();
return view ('editprofile')->with('row',$i);
}
public function updateprofile(Request $request)
{
$cid = $request['id'];
$test = $request['password'];
//$test1 = md5($test);
$arrayName = array(
'name' => $request['name'],
'email' => $request['email'],
'password' => <PASSWORD>($request['password']),
);
$i=DB::table('users')->where('id',$cid)->update($arrayName );
if($i>0)
{
Session::flash('message','Record inserted');
return redirect('home');
}
}
}
| bb2cacb148d8abc19084a9583e200e237a2ec061 | [
"PHP"
] | 7 | PHP | harshpatel11/LaravelBlog | c3168067ec1e618de89b5a8191746416d563dcaf | 15c12b47e094ad2b24b19f5f5f469ad93069b07b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.