branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep># GGIS Research Map Web Application
Webmap for displaying the research of UIUC professors.
<file_sep>
'use strict';
const express = require('express');
const router = express.Router();
var ctrlResearchers = require('../controllers/researchers');
var ctrlProjects = require('../controllers/projects');
//var ctrlLocations = requine('../controllers/locations');
var ctrlAuth = require('../controllers/authentication');
// Researchers
router.get('/researchers', ctrlResearchers.getAllResearchers);
router.get('/researcher/:netId', ctrlResearchers.getResearcherProfile);
router.post('/researcher', ctrlResearchers.addNewResearcher);
// Projects
// router.get('/projects', ctrlProjects.???);
router.post('/project', ctrlProjects.addNewProject);
router.post('/register', ctrlAuth.register);
router.post('/login', ctrlAuth.login);
module.exports = router;
| 9cda13e997a7ce131dbe2d82de582161d7438635 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | edisondotme/research-map | 425bc5fd145183ef23bec77dd8791d13df8db2f8 | a8932a7b9bb02cfbfccb34f3587f3fbec1a5bd3e |
refs/heads/master | <file_sep>var chicas = new Array(db.length);
for (var i = 0; i < db.length; i++) {
chicas[i] = db[i].nombre;
};
//var chicas = ["seis","cinco","cuatro","tres","dos","uno"];
//Debo de el entero sacar el residuo [1,2,3], [3,2]:1 realizar las combinaciones con dichos elementos
//Luego debo de combinar 2:[3] y obtendriamos todos los arreglos
//tamaño - 1, de 0 hasta el nuevo tamaño, combinar;
var t = 0;
var full = 0;
for (var i = chicas.length-1; i > 0; i--) {
t = t + i;
};
var com = function(uno,dos) {
if (full < t) {
console.log(uno+" VS "+dos);
full++;
}else if (full == t) {
console.log("FIN");
};
}
var tamaño = chicas.length-1;//3
var i = 0;
while(i < tamaño){
com(chicas[tamaño],chicas[i]);
i++;
if(i == tamaño){
i = 0;
--tamaño;
if (tamaño == 1) {
com(chicas[tamaño],chicas[i]);
console.log("Son: "+t+" combinaciones");
};
};
};
<file_sep>Sistema de puntaje
================
Parte 1 - Sistema de puntuación Elo <NAME> (1903-1992)
```js
//Ejemplo : var ra = 300, rb = 400;
var res = Math.pow((1/1)+10,(ra-rb)/400);
var ros = Math.pow((1/1)+10,(rb-ra)/400);
var Ea = res;
var Eb = ros;
var C = 30;
var ga = 1.0,gb = 0.0;
//S = 1,0 para ganar, 0,5 para empate y 0,0 para la derrota.
var Rna = ra + C * ( ga - Ea);
var Rnb = rb + C * ( gb - Eb );
if (Rna > Rnb) {
console.log("Gano: Rna"+Rna+" Perdio: Rnb"+Rnb);
}else if(Rna > Rnb){
console.log("Gano: Rnb"+Rnb+" Perdio: Rna"+Rnb);
}else if(Rna == Rnb){
console.log("Empate: Rna"+Rna+" Empate: Rnb"+Rnb);
}
```
### Combinaciones posibles sin repeticion en pares:
* [1, 2, 3, 4]
* [1, 2]
* [1, 3]
* [1, 4]
* [2, 3]
* [2, 4]
* [3, 4]
#### Se observa que el objeto [0] del arreglo se convina con los 3 porteriores, restando 1 obtenermos que el objeto [1] con los 2 posteriores y asi continuamente, destacando que esta formula depende de el tamaño del arreglo.
```js
var com = function(uno,dos) {
if (full < t) {
console.log(uno+" VS "+dos);
full++;
}else if (full == t) {
console.log("FIN");
};
};
var tamaño = chicas.length-1;//3
var i = 0;
while(i < tamaño){
com(chicas[tamaño],chicas[i]);
i++;
if(i == tamaño){
i = 0;
--tamaño;
if (tamaño == 1) {
com(chicas[tamaño],chicas[i]);
console.log("Son: "+t+" combinaciones");
};
};
};
```
<file_sep>var db = [
{
"nombre": "cinco",
"puntaje": 0
},
{
"nombre": "cuatro",
"puntaje": 0
},
{
"nombre": "tres",
"puntaje": 0
},
{
"nombre": "dos",
"puntaje": 0
},
{
"nombre": "uno",
"puntaje": 0
}
];
| 9d739cb3e5805b81d0d6db619e15366c6a82678f | [
"JavaScript",
"Markdown"
]
| 3 | JavaScript | eliasruizhz/Parte1-ELO-NOOBS | 726fed4fd16c22bef33066d290a2133efbf3cd75 | 6d9fc4cc1d46466b018945a260a6a1c09ecf9217 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
import cv2
from matplotlib import pyplot as plt
if __name__ == '__main__':
img_src = cv2.imread('../images/Lenna.jpg', cv2.IMREAD_COLOR)
img_gry = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
# 二値化
thresholds = [50, 100, 150, 200, 250]
ret, img_dst1 = cv2.threshold(img_gry, thresholds[0], 255, cv2.THRESH_BINARY)
ret, img_dst2 = cv2.threshold(img_gry, thresholds[1], 255, cv2.THRESH_BINARY)
ret, img_dst3 = cv2.threshold(img_gry, thresholds[2], 255, cv2.THRESH_BINARY)
ret, img_dst4 = cv2.threshold(img_gry, thresholds[3], 255, cv2.THRESH_BINARY)
ret, img_dst5 = cv2.threshold(img_gry, thresholds[4], 255, cv2.THRESH_BINARY)
titles = ['original', 'threshold=50', 'threshold=100',
'threshold=150', 'threshold=200', 'threshold=250']
images = [img_gry, img_dst1, img_dst2, img_dst3, img_dst4, img_dst5]
for i in range(6):
plt.subplot(2, 3, i+1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.savefig('../output/cv2-binarization.jpg')
plt.show()
<file_sep># -*- coding: utf-8 -*-
import cv2
import numpy as np
from matplotlib import pyplot as plt
if __name__ == "__main__":
img_src = cv2.imread('../images/Lenna.jpg', cv2.IMREAD_COLOR)
img_gry = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
# モフォロジー処理
kernel = np.ones((5, 5), np.uint8)
img_elosion = cv2.erode(img_gry, kernel, iterations=1) # 収縮処理
img_dilation = cv2.dilate(img_gry, kernel, iterations=1) # 膨張処理
img_close = cv2.morphologyEx(img_gry, cv2.MORPH_CLOSE, kernel) # クロージング
img_open = cv2.morphologyEx(img_gry, cv2.MORPH_OPEN, kernel) # オープニング
images = [img_src, img_gry, img_elosion, img_dilation, img_close, img_open]
titles = ['original', 'gray', 'elosion', 'dilation', 'closing', 'opening']
for i in range(6):
plt.subplot(2, 3, i+1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.savefig('../output/cv2-morphology.jpg')
plt.show()
<file_sep># -*- coding: utf-8 -*-
import cv2
if __name__ == "__main__":
img_src = cv2.imread('../images/Lenna.jpg', cv2.IMREAD_UNCHANGED)
height, width, channels = img_src.shape[:3]
print('width: %s, height: %s, channels: %s, dtype: %s' %
(str(width), str(height), str(channels), str(img_src.dtype)))
# width: 400, height: 400, channels: 3, dtype: uint8
<file_sep># -*- coding: utf-8 -*-
import cv2
import copy
import random
import numpy as np
if __name__ == '__main__':
img_src = cv2.imread('../images/Label.jpg', cv2.IMREAD_COLOR)
height, width = img_src.shape[:2]
img_dst = copy.copy(img_src)
img_gry = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
# ラベリング
ret, th = cv2.threshold(img_gry, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
labels, img_obj = cv2.connectedComponents(th)
print('labels: %s' % labels)
colors = []
for i in range(1, labels+1):
colors.append(
np.array(
[random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255)]
)
)
for y in range(0, height):
for x in range(0, width):
if img_obj[y, x] > 0:
img_dst[y, x] = colors[img_obj[y, x]]
else:
img_dst[y, x] = [0, 0, 0]
output = cv2.connectedComponentsWithStats(
th,
connectivity=4,
ltype=cv2.CV_32S
)
labels, labels, stats, centroids = output[:4]
print(centroids)
cv2.namedWindow("Source", cv2.WINDOW_AUTOSIZE)
cv2.imshow("Source", img_src)
cv2.namedWindow("Connected Components", cv2.WINDOW_AUTOSIZE)
cv2.imshow("Connected Components", img_dst)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.imwrite('../output/cv2-labeling.jpg', img_dst)
cv2.destroyAllWindows()
<file_sep># -*- coding: utf-8 -*-
import cv2
def show_image(title, data):
cv2.imshow(title, data)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if __name__ == '__main__':
img_src = cv2.imread('../images/Lenna.jpg', cv2.IMREAD_GRAYSCALE)
img_msk = cv2.imread('../images/Mask.jpg', cv2.IMREAD_GRAYSCALE)
# マスク処理
img_dst = cv2.bitwise_and(img_src, img_src, mask=img_msk)
show_image('Masking', img_dst)
cv2.imwrite('../output/cv2-masking.jpg', img_dst)
cv2.destroyAllWindows()
<file_sep># -*- coding: utf-8 -*-
import cv2
import numpy as np
def histogram(src):
img_hist = np.zeros([100, 256]).astype("uint8")
rows, cols = img_hist.shape
# 度数分布
hdims = [256]
hranges = [0, 256]
hist = cv2.calcHist([src], [0], None, hdims, hranges)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(hist)
for i in range(0, 255):
v = hist[i]
cv2.line(img_hist,
(i, rows),
(i, rows - rows * (v / max_val)),
(255, 255, 255))
return img_hist
def show_image(title, data):
cv2.imshow(title, data)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if __name__ == '__main__':
img_src = cv2.imread('../images/Lenna.jpg', cv2.IMREAD_COLOR)
img_gry = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
# ヒストグラム
img_hist = histogram(img_gry)
show_image('Histogram', img_hist)
cv2.imwrite('../output/cv2-hist-of-org.jpg', img_hist)
# ヒストグラム均一化
img_dst = cv2.equalizeHist(img_gry)
show_image('Equalize Histogram', img_dst)
cv2.imwrite('../output/cv2-equalize-hist.jpg', img_dst)
cv2.destroyAllWindows()
<file_sep># -*- coding: utf-8 -*-
import cv2
import numpy as np
if __name__ == "__main__":
cols = 480
rows = 640
img_blk = np.zeros((rows, cols, 3), np.uint8)
height, width, channels = img_blk.shape[:3]
print('width: %s, height: %s, channels: %s, dtype: %s' %
(str(width), str(height), str(channels), str(img_blk.dtype)))
cv2.imshow('blank_image', img_blk)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.imwrite('../output/cv2-black.png', img_blk)
cv2.destroyAllWindows()
<file_sep># -*- coding: utf-8 -*-
import cv2
import numpy as np
def show_image(title, data):
cv2.imshow(title, data)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if __name__ == '__main__':
img_src = cv2.imread('../images/Lenna.jpg', cv2.IMREAD_COLOR)
# 鮮鋭化
k = 1.0
op = np.array([[-k, -k, -k], [-k, 1+8*k, -k], [-k, -k, -k]])
img_tmp = cv2.filter2D(img_src, ddepth=-1, kernel=op)
img_dst = cv2.convertScaleAbs(img_tmp)
show_image('Sharpening', img_dst)
cv2.imwrite('../output/cv2-sharpening.jpg', img_dst)
cv2.destroyAllWindows()
<file_sep>Learning OpenCV3 with Python
===
## Overview
OpenCV3 Examples with Python.
## References
* [OpenCVによる画像処理入門](http://bookclub.kodansha.co.jp/product?isbn=9784061538221)
* [opencv/opencv](https://github.com/opencv/opencv)
## Author
[t2sy](https://github.com/fisproject)<file_sep># -*- coding: utf-8 -*-
import cv2
import numpy as np
from matplotlib import pyplot as plt
def show_image(title, data):
cv2.imshow(title, data)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if __name__ == '__main__':
img_src = cv2.imread('../images/Label.jpg', cv2.IMREAD_GRAYSCALE)
img_bkg = cv2.imread('../images/Mask.jpg', cv2.IMREAD_GRAYSCALE)
# Background Substraction
img_diff = cv2.absdiff(img_src, img_bkg)
ret, img_bin = cv2.threshold(img_diff, 50, 255, cv2.THRESH_BINARY)
kernel = np.ones((3, 3), np.uint8)
# 膨張・収縮処理で小さな孔や連結部分を除去
img_dilation = cv2.dilate(img_bin, kernel, iterations=4) # 膨張処理
img_msk = cv2.erode(img_dilation, kernel, iterations=4) # 収縮処理
img_dst = cv2.bitwise_and(img_src, img_msk) # マスク画像で切り出す
images = [img_src, img_bkg, img_dst]
titles = ['original', 'background', 'background substraction']
for i in range(3):
plt.subplot(1, 3, i+1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.savefig('../output/cv2-background-sub.jpg')
plt.show()
<file_sep># -*- coding: utf-8 -*-
import cv2
def show_image(title, data):
cv2.imshow(title, data)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if __name__ == '__main__':
img_src1 = cv2.imread('../images/Lenna.jpg', cv2.IMREAD_GRAYSCALE)
img_src2 = cv2.imread('../images/Mask.jpg', cv2.IMREAD_GRAYSCALE)
# Alpha Blending
img_dst = cv2.addWeighted(
src1=img_src1,
alpha=0.5,
src2=img_src2,
beta=0.5,
gamma=0.0
)
show_image('Alpha Blending', img_dst)
cv2.imwrite('../output/cv2-alpha-blending.jpg', img_dst)
cv2.destroyAllWindows()
<file_sep># -*- coding: utf-8 -*-
import cv2
def show_image(title, data):
cv2.imshow(title, data)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if __name__ == '__main__':
img_src = cv2.imread('../images/Lenna.jpg', cv2.IMREAD_COLOR)
# Sobelオペレータ
img_tmp = cv2.Sobel(img_src, ddepth=cv2.CV_32F, dx=1, dy=0)
img_dst = cv2.convertScaleAbs(img_tmp)
show_image('Sobel', img_dst)
cv2.imwrite('../output/cv2-sobel.jpg', img_dst)
cv2.destroyAllWindows()
<file_sep># -*- coding: utf-8 -*-
import cv2
import numpy as np
if __name__ == '__main__':
img_src = cv2.imread('../images/Lenna.jpg', cv2.IMREAD_UNCHANGED)
height, width = img_src.shape[:2]
size = tuple(np.array([width, height]))
rad = np.pi/6 # 回転角度
move_x = width*0.1 # x方向平行移動
move_y = height*-0.3 # y方向平行移動
afn_mat = np.float32(
[[np.cos(rad), -1*np.sin(rad), move_x],
[np.sin(rad), np.cos(rad), move_y]]
)
img_dst = cv2.warpAffine(img_src, afn_mat, size, flags=cv2.INTER_LINEAR)
cv2.imshow('Affine Transformation', img_dst)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.imwrite('../output/cv2-affine.jpg', img_dst)
cv2.destroyAllWindows()
<file_sep># -*- coding: utf-8 -*-
import cv2
def show_image(title, data):
cv2.imshow(title, data)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if __name__ == '__main__':
img_src = cv2.imread('../images/Lenna.jpg', cv2.IMREAD_COLOR)
# 平均化オペレータ
img_dst = cv2.blur(img_src, ksize=(5, 5))
show_image('Normalized box filter', img_dst)
cv2.imwrite('../output/cv2-normalized.jpg', img_dst)
# Gaussianオペレータ
img_dst = cv2.GaussianBlur(img_src, ksize=(5, 5), sigmaX=1)
show_image('Gaussian', img_dst)
cv2.imwrite('../output/cv2-gaussian.jpg', img_dst)
# Bilateralオペレータ
img_dst = cv2.bilateralFilter(img_src, d=5, sigmaColor=50, sigmaSpace=100)
show_image('Bilateral', img_dst)
cv2.imwrite('../output/cv2-bilateral.jpg', img_dst)
# medianオペレータ
img_dst = cv2.medianBlur(img_src, ksize=5)
show_image('Median', img_dst)
cv2.imwrite('../output/cv2-median.jpg', img_dst)
cv2.destroyAllWindows()
<file_sep># -*- coding: utf-8 -*-
import cv2
import numpy as np
def histogram(src):
img_hist = np.zeros([100, 256]).astype("uint8")
rows, cols = img_hist.shape
# 度数分布
hdims = [256]
hranges = [0, 256]
hist = cv2.calcHist([src], [0], None, hdims, hranges)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(hist)
for i in range(0, 255):
v = hist[i]
cv2.line(img_hist,
(i, rows),
(i, rows - rows * (v / max_val)),
(255, 255, 255))
return img_hist
def craete_table(shift):
t = np.arange(256, dtype=np.uint8)
for i in range(0, 255):
j = i + shift
if j < 0:
t[i] = 0
elif j > 255:
t[i] = 255
else:
t[i] = j
return t
def craete_enhancement_table(min, max):
t = np.arange(256, dtype=np.uint8)
for i in range(0, min):
t[i] = 0
for i in range(min, max):
t[i] = 255 * (i - min) / (max - min)
for i in range(max, 255):
t[i] = 255
return t
def show_image(title, data):
cv2.imshow(title, data)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if __name__ == '__main__':
img_src = cv2.imread('../images/Lenna.jpg', cv2.IMREAD_COLOR)
img_gry = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
# ネガポジ変換
img_dst = 255 - img_gry
show_image('NP', img_dst)
cv2.imwrite('../output/cv2-np.jpg', img_dst)
# ネガポジ変換後のヒストグラム
img_hist = histogram(img_dst)
show_image('Histogram of NP', img_hist)
cv2.imwrite('../output/cv2-hist-of-np.jpg', img_hist)
# 明度調整
table = craete_table(shift=100)
img_dst = cv2.LUT(img_gry, table)
show_image('Value Adjustment', img_dst)
cv2.imwrite('../output/cv2-value-adjustment.jpg', img_dst)
# 明度調整後のヒストグラム
img_hist = histogram(img_dst)
show_image('Histogram of Value Adjustment', img_hist)
cv2.imwrite('../output/cv2-hist-of-va.jpg', img_hist)
# コントラスト低減
cv2.normalize(
img_gry,
img_dst,
alpha=100,
beta=200,
norm_type=cv2.NORM_MINMAX
)
show_image('Contrast Reducing', img_dst)
cv2.imwrite('../output/cv2-contrast-reducing.jpg', img_dst)
# コントラスト低減後のヒストグラム
img_hist = histogram(img_dst)
show_image('Histogram of Contrast Reducing', img_hist)
cv2.imwrite('../output/cv2-hist-of-cr.jpg', img_hist)
# コントラスト強調
table = craete_enhancement_table(min=150, max=200)
img_dst = cv2.LUT(img_gry, table)
show_image('Contrast Enhancement', img_dst)
cv2.imwrite('../output/cv2-contrast-enhancement.jpg', img_dst)
# コントラスト強調後のヒストグラム
img_hist = histogram(img_dst)
show_image('Histogram of Contrast Enhancement', img_hist)
cv2.imwrite('../output/cv2-hist-of-ce.jpg', img_hist)
cv2.destroyAllWindows()
<file_sep># -*- coding: utf-8 -*-
import cv2
from matplotlib import pyplot as plt
if __name__ == "__main__":
img_src = cv2.imread('../images/Lenna.jpg', cv2.IMREAD_COLOR)
# to HSV
img_hsv = cv2.cvtColor(img_src, cv2.COLOR_BGR2HSV)
plt.imshow(img_hsv)
plt.title('bgr2hsvs')
plt.savefig('../output/cv2-bgr2hsv.jpg')
plt.show()
# to GRAY
img_gry = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
# matplotlib require RGB format
cv2.imshow('COLOR_BGR2GRAY', img_gry)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.imwrite('../output/cv2-bgr2gray.jpg', img_gry)
cv2.destroyAllWindows()
| 1ca2a18d75aeca24ae0957be65efa1077fcd21e8 | [
"Markdown",
"Python"
]
| 16 | Python | fisproject/learning-opencv | d755ad1a4baea4a862c93f7869090c008021adfe | c7353d64760a4087273f8ee655e81186e5dec21e |
refs/heads/master | <repo_name>grexie/six-server<file_sep>/Sixfile.js
import Six from '@grexie/six';
import path from 'path';
import fs from 'fs';
export default Six.Library.extend({
onBuildDocs: function(builder) {
builder.globSync(path.join(builder.srcDir, 'server', 'routers', '**', '*.js')).forEach(function(file) {
var routerPath = path.relative(path.join(builder.srcDir, 'server', 'routers'), file);
if(path.basename(routerPath, '.js') === 'index') {
routerPath = path.dirname(routerPath);
} else {
routerPath = path.join(path.dirname(routerPath), path.basename(routerPath, '.js'));
}
var comments = [], tokens = [], content = fs.readFileSync(file).toString();
var ast = builder.acorn.parse(content, {
ranges: true, onComment: comments, onToken: tokens, ecmaVersion: 6, sourceType: 'module'
});
var routerName = 'router';
var section;
var unnamed = 1;
comments = comments.filter(function(x) {
if(x.type !== 'Block' && x.value[0] !== '*') return false;
var node = builder.acorn.parseExpressionAt(content.substring(x.end));
if(!node) return false;
if(node.type === 'CallExpression' &&
node.callee.object.type === 'Identifier' && node.callee.object.name === routerName &&
node.callee.property.type === 'Identifier') {
x.method = node.callee.property.name.toUpperCase();
x.url = '/' + path.join(routerPath, node.arguments[0].value);
}
var attributes = [];
var doc = x.value.split(/\n|\r\n/g).map(function (x) {
return x.replace(/^\s*\*\s*/, '').trim();
}).filter(function(line) {
if(/^@[a-zA-Z0-9-]+/.test(line)) {
var m = line.match(/^@([a-zA-Z0-9-]+)\s+(.*)/);
attributes.push({
name: m[1].trim(),
value: m[2].trim()
});
return false;
}
return true;
});
x.documentation = builder.marked(doc.filter(function(x) { return !!x; }).join('\n'));
x.attributes = attributes;
var params = x.attributes.filter(function(x) { return x.name === 'param'; });
if(params.length) {
var paramsTable = '<table class="params"><tbody>\n';
params.forEach(function(param) {
var parts = param.value.match(/^((?:@[a-zA-Z0-9-]+\s+)*)([a-zA-Z0-9$_\.\[\]-]+)\s+([a-zA-Z0-9$_\.\[\]-]+)\s+(.*)$/);
if(!parts) return;
var tags = parts[1].trim().split(/\s+/g).map(function(x) { return '<span class="tag">' + x.trim().substring(1) + '</span> '; });
var name = parts[2].trim();
var type = parts[3].trim();
var description = parts[4].trim();
paramsTable += '<tr>\n<td class="name">' + name + '</td>\n';
paramsTable += '<td class="type">' + type + '<br/><span class="tags">' + tags.join('') + '</span></td>\n';
paramsTable += '<td class="description">' + description + '</td>\n';
});
paramsTable += '</tbody></table>\n';
x.documentation = paramsTable + x.documentation;
}
if(x.url && x.method) {
x.documentation = '<div class="router"><span class="method method-' + x.method.toLowerCase() + '">' +
x.method + '</span> ' +
'<span class="url">' + x.url.replace(/(:[a-zA-Z0-9-_]+)/g, '<b>$1</b>') + '</span></div>\n' +
x.documentation;
}
x.title = x.attributes.filter(function(x) { return x.name === 'title'; })[0] ||
x.attributes.filter(function(x) { return x.name === 'section'; })[0];
if(x.title) {
x.documentation = '<h1>' + x.title.value + '</h1>\n' + x.documentation;
x.title = x.title.value;
}
return true;
}).forEach(function(comment) {
var basename = path.basename(routerPath);
if(comment.title) {
var slug = comment.title.toLowerCase().replace(/\s+/g, '-');
} else {
var slug = 'unnamed-' + unnamed++;
}
var file = path.join(builder.destDir, 'assets', 'docs', basename, slug) + '.html';
if(!fs.existsSync(path.join(builder.destDir, 'assets', 'docs', basename))) {
fs.mkdirSync(path.join(builder.destDir, 'assets', 'docs', basename));
}
fs.writeFileSync(file, comment.documentation);
builder.manifest.push({
section: [basename, slug],
file: '/assets/docs/' + basename + '/' + slug + '.html',
title: comment.title,
isSectionTitle: !!comment.attributes.filter(function(x) { return x.name === 'section' })[0]
});
});
});
}
});<file_sep>/README.md
# six-server
[](https://www.codacy.com/app/grexie-tim/six-server) [](https://circleci.com/gh/grexie/six-server)
Express Server for Grexie Six
| eb19c5bd06476f4fcd52a43edd352ebff7c7e773 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | grexie/six-server | 725f894edfca68c8c34f5ce56779eb7880bc4b23 | 404f1d600db5650612a6a1b9be547465cc3fba9a |
refs/heads/master | <repo_name>Ahmed-Masoud/HTTP-SERVER<file_sep>/server.py
import socket
import thread
def handleRequest(clientsocket,addr):
print("Got a connection from %s" % str(addr))
clientMsg = clientsocket.recv(512)
print(clientMsg+"\n")
webClient = False
# to know a client or browser and parse the request
if '/' in clientMsg:
webClient = True
webRequest = clientMsg.split('\n')
temp = webRequest[0].split(' ')
method = 'GET'
fileName = temp[1][1:]
else:
mylist = clientMsg.split(" ")
method = mylist[0]
fileName = mylist[1]
if method == "GET":
try:
f = open(fileName, 'r')
except:
clientsocket.send("404 Not Found")
clientsocket.close()
return
if not webClient:
clientsocket.send("200 OK")
while True:
data = f.readline(512)
if not data:
break
clientsocket.send(data)
f.close()
elif method == "POST":
text_file = open(fileName, "w+")
clientsocket.send("receiving")
while True:
msg = clientsocket.recv(512)
if not msg:
break
print(msg)
text_file.write(msg)
text_file.close()
else:
clientsocket.send("unknown command")
clientsocket.close()
# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 8888
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket, addr = serversocket.accept()
thread.start_new_thread(handleRequest, (clientsocket, addr,))
<file_sep>/client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# request input from user
request = raw_input('Enter a file request: ')
# parse input to get the port number
my_list = request.split(" ")
method = my_list[0]
fileName = my_list[1]
host = my_list[2]
if len(my_list) == 4:
port = int(my_list[3])
else:
port = 80
# connection to hostname on the port.
try:
s.connect((host, port))
except:
print("connection refused !!")
quit()
if method == "GET":
s.send(request)
response_code = s.recv(512)
print("Status Code : "+response_code+"\n")
if response_code == "404 Not Found":
quit()
text_file = open(fileName, "w+")
while True:
serverMsg = s.recv(512)
if not serverMsg:
break
print(serverMsg)
text_file.write(serverMsg)
text_file.close()
elif method == "POST":
try:
f = open(fileName, 'r')
except:
print("No Such File !!")
quit()
s.send(request)
response_code = s.recv(512)
print("Status Code : "+response_code+"\n")
while True:
data = f.readline(512)
if not data:
break
s.send(data)
f.close() | f2307fcc2c42e38d7a7699354cbc5db0fa737c3e | [
"Python"
]
| 2 | Python | Ahmed-Masoud/HTTP-SERVER | a25e997ab942de24b552dd6a3ef6a30ce3e32ac1 | 6b852406376c8c7361951a241eb3a4e063aea9ae |
refs/heads/master | <repo_name>modelm/mla-admin-bar<file_sep>/mla-admin-bar.php
<?php
/**
* customized admin bar for MLA Commons
*/
function mla_admin_bar_add_menus () {
global $wp_admin_bar;
// clean slate
remove_all_actions( 'admin_bar_menu' );
// restore debug bar menu for super admins
if ( isset( $GLOBALS['debug_bar'] ) && is_super_admin() ) {
add_action( 'admin_bar_menu', array( $GLOBALS['debug_bar'], 'admin_bar_menu' ), 1000 );
}
// 'top-secondary' is normally added by an action hooked on admin_bar_menu, which we just removed.
// in order to add anything to the group we must recreate it first.
$wp_admin_bar->add_group( array(
'id' => 'top-secondary',
'meta' => array(
'class' => 'ab-top-secondary',
),
) );
/**
* primary nodes
*/
$wp_admin_bar->add_menu( array(
'id' => 'mla-link',
'title' => __( 'MLA Commons' ),
'href' => network_home_url()
) );
$wp_admin_bar->add_menu( array(
'id' => 'mlaorg-link',
'title' => __( 'MLA.org' ),
'href' => 'https://www.mla.org'
) );
if ( is_user_logged_in() ) {
wp_admin_bar_my_sites_menu( $wp_admin_bar );
}
/**
* secondary nodes (added starting from the right)
*/
if ( is_user_logged_in() ) {
$avatar = get_avatar( get_current_user_id(), 28 );
$wp_admin_bar->add_menu( array(
'id' => 'me-avatar',
'parent' => 'top-secondary',
'title' => $avatar,
'href' => bp_get_loggedin_user_link(),
'meta' => array(
'class' => empty( $avatar ) ? '' : 'with-avatar',
),
) );
$wp_admin_bar->add_menu( array(
'id' => 'me-name',
'parent' => 'top-secondary',
'title' => bp_get_loggedin_user_username(),
'href' => bp_get_loggedin_user_link(),
) );
bp_notifications_toolbar_menu();
$wp_admin_bar->add_menu( array(
'id' => 'log-out',
'parent' => 'top-secondary',
'title' => 'Log Out',
'href' => wp_logout_url(),
) );
} else {
$wp_admin_bar->add_menu( array(
'id' => 'bp-login',
'parent' => 'top-secondary',
'title' => __( 'Log In' ),
'href' => wp_login_url( bp_get_requested_url() ),
) );
$wp_admin_bar->add_menu( array(
'id' => 'mla-join',
'parent' => 'top-secondary',
'title' => __( 'Register' ),
'href' => 'https://www.mla.org/join_new_intro',
) );
}
}
add_action( 'add_admin_bar_menus', 'mla_admin_bar_add_menus' );
function mla_admin_bar_add_style() {
wp_register_style( 'mla-admin-bar-style', plugins_url( 'assets/css/style.css', __FILE__ ) );
wp_enqueue_style( 'mla-admin-bar-style' );
}
add_action( 'wp_enqueue_scripts', 'mla_admin_bar_add_style' );
add_action( 'admin_enqueue_scripts', 'mla_admin_bar_add_style' );
| 18e30d5db0a3d1e97b7837939eda14c6186c9683 | [
"PHP"
]
| 1 | PHP | modelm/mla-admin-bar | a5c890fac3ee3c46edb7a22fa15626e5264cffa3 | c17bab508b5f5e041a453d202c285d4638fa6d90 |
refs/heads/master | <repo_name>ymyurdakul/Bulanik-Mantik-Camasir-Makinesi<file_sep>/Bulanık/Bulanık/Fonksiyonlar.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class Fonksiyonlar
{
public static List<String> UyeKumeAdıBul(double deger,string bulanık_kume_ismi)
{
if (bulanık_kume_ismi == "Hassaslık")
{
return HassasKumeAdıBul(deger);
}
else if (bulanık_kume_ismi == "Miktar")
{
return MiktarKumeAdıBul(deger);
}
else if (bulanık_kume_ismi == "Kirlilik")
{
return KirlilikKumeAdıBul(deger);
}
return null;
}
private static List<String> HassasKumeAdıBul(double deger)
{
List<String> temp = new List<string>();
if (deger<3)
{
temp.Add("sağlam");
}
if (deger >= 3 && deger<=4)
{
temp.Add("sağlam");
temp.Add("orta");
}
if (deger > 4 && deger < 5.5)
{
temp.Add("orta");
}
if (deger >= 5.5 && deger <7)
{
temp.Add("orta");
temp.Add("hassas");
}
if (deger >= 7)
{
temp.Add("hassas");
}
return temp;
}
private static List<String> KirlilikKumeAdıBul(double deger)
{
List<String> temp = new List<string>();
if (deger < 3)
{
temp.Add("küçük");
}
if (deger >= 3 && deger <= 4.5)
{
temp.Add("küçük");
temp.Add("orta");
}
if (deger > 4.5 && deger < 5.5)
{
temp.Add("orta");
}
if (deger >= 5.5 && deger < 7)
{
temp.Add("orta");
temp.Add("büyük");
}
if (deger >= 7)
{
temp.Add("büyük");
}
return temp;
}
private static List<String> MiktarKumeAdıBul(double deger)
{
List<String> temp = new List<string>();
if (deger < 3)
{
temp.Add("küçük");
}
if (deger >= 3 && deger <= 4)
{
temp.Add("küçük");
temp.Add("orta");
}
if (deger > 4 && deger < 5.5)
{
temp.Add("orta");
}
if (deger >= 5.5 && deger < 7)
{
temp.Add("orta");
temp.Add("büyük");
}
if (deger >= 7)
{
temp.Add("büyük");
}
return temp;
}
public static List<int> KuralAteşlemeIndexBul(List<String>hassaslıkKumeAdları,List<String>miktarKumeAdları,List<String>kirlilikKumeAdları)
{
List<int> ateşlenenKurallar = new List<int>();
for (int i = 0; i < hassaslıkKumeAdları.Count(); i++)
{
for (int j = 0; j < miktarKumeAdları.Count(); j++)
{
for (int k = 0; k < kirlilikKumeAdları.Count(); k++)
{
Kural temp = new Kural(hassaslıkKumeAdları[i],miktarKumeAdları[j],kirlilikKumeAdları[k]);
ateşlenenKurallar.Add(indexBul(temp));
}
}
}
return ateşlenenKurallar;
}
private static int indexBul(Kural temp)
{
for (int i = 0; i < Form1.KURAL_TABANI.Count(); i++)
{
if (Form1.KURAL_TABANI[i].Equals(temp))
{
return i;
}
}
return -1;
}
}
}
<file_sep>/Bulanık/Bulanık/DetayForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace WindowsFormsApplication1
{
public partial class DetayForm : Form
{
public DetayForm()
{
InitializeComponent();
}
private void DetayForm_Load(object sender, EventArgs e)
{
}
public void setChart(Chart cikisChart,String üyekümeAdı)
{
pbRenk1.BackColor = Color.Blue;
pbRenk2.BackColor = Color.Orange;
pbRenk3.BackColor = Color.Red;
lblLegend1.Text = cikisChart.Series[0].Name;
lblLegend2.Text = cikisChart.Series[1].Name;
lblLegend3.Text = cikisChart.Series[2].Name;
this.Text = üyekümeAdı.ToUpper() + " DETAY";
switch (üyekümeAdı)
{
case "hassasiyet":
{
textBox1.Text = "[ -4 , -1.5 , 2 , 4 ]";
textBox2.Text= "[ 3 , 5 , 7 ]";
textBox3.Text = "[ 5.5 , 8 , 12.5 , 14 ]";
}
break;
case "miktar":
{
textBox1.Text = "[ -4 , -1.5 , 2 , 4 ]";
textBox2.Text = "[ 3 , 5 , 7 ]";
textBox3.Text = "[ 5.5 , 8 , 12.5 , 14 ]";
}
break;
case "kirlilik":
{
textBox1.Text = "[ -4 , -2.5 , 2 , 4.5 ]";
textBox2.Text = "[ 3 , 5 , 7 ]";
textBox3.Text = "[ 5.5 , 8 , 12.5 , 15 ]";
}
break;
default:
break;
}
}
}
}
<file_sep>/Bulanık/Bulanık/Kural.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
public class Kural
{
//Aslında gerek yok ama indexleme için kullanıcam
public int Index_numarası { get; set; }
public string Hassaslık { get; set; }
public string Miktar { get; set; }
public string Kirlilik { get; set; }
public string Donus_Hizi { get; set; }
public string Sure { get; set; }
public string Deterjan { get; set; }
public Kural()
{ }
public Kural(int index_numarası, string hassaslık,
string miktar, string kirlilik, string donus_hizi, string sure, string deterjan)
{
this.Index_numarası = index_numarası;
this.Hassaslık = hassaslık;
this.Miktar = miktar;
this.Kirlilik = kirlilik;
this.Donus_Hizi = donus_hizi;
this.Sure = sure;
this.Deterjan = deterjan;
}
public Kural( string hassaslık,
string miktar, string kirlilik)
{
this.Hassaslık = hassaslık;
this.Miktar = miktar;
this.Kirlilik = kirlilik;
}
public override bool Equals(object obj)
{
Kural temp = (Kural)obj;
return (this.Hassaslık == temp.Hassaslık && this.Miktar == temp.Miktar && this.Kirlilik == temp.Kirlilik);
}
}
}
<file_sep>/Bulanık/Bulanık/BulanıkMantık.cs
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace WindowsFormsApplication1
{
class BulanıkMantık
{
public double[] hassasYamukBas = { -4,-1.5,2,4};
public double[] hassasUcgen = { 3, 5, 7 };
public double[] hassasYamukSon = { 5.5, 8, 12.5, 14 };
public double[] miktarYamukBas = { -4,-1.5,2,4};
public double[] miktarUcgen = { 3,5,7};
public double[] miktarYamukSon = { 5.5,8,12.5,14};
public double[] kirlilikYamukBas = { -4.5, -2.5,2, 4.5 };
public double[] kirlilikUcgen = { 3, 5, 7 };
public double[] kirlilikYamukSon = { 5.5, 8, 12.5, 15};
public double[] deterjanAzUcgen = {20,85,150 };
public double[] deterjanCokAzYamuk = {0,0,20,85 };
public double[] deterjanOrtaUcgen = {85,150,215 };
public double[] deterjanFazla = { 150,215,280};
public double[] deterjanCokFazla = { 215, 280, 300, 300 };
public double[] sureKısaYamuk = {-46.5,-25.28,22.3,39.9 };
public double[] sureNormalKısaUcgen = { 22.3, 39.9,57.5 };
public double[] sureOrtaUcgen = {39.9,57.5,75.1 };
public double[] sureNormalUzunUcgen = {57.5,75.1,92.7 };
public double[] sureUzunYamuk = {75,92.7,111.6,130 };
public double[] hızHassasYamuk = { -5.8,-2.8,0.5,1.5};
public double[] hızNormalHassasUcgen = {0.5,2.75,5 };
public double[] hızOrtaUcgen = {2.75,5,5 };
public double[] hızNormalGüçlüUcgen = {5,7.25,5 };
public double[] hızGüçlüYamuk = {8.5,9.5,12.8,15.2 };
public double GirisUyelikHesapla(String bulanıkKumeAdı,String üyelik,double deger)
{
switch (bulanıkKumeAdı)
{
case "Hassaslık":
{
if (üyelik == "sağlam")
return YamukUyelikHesapla(deger,hassasYamukBas);
if (üyelik == "orta")
return UcgenUyelikHesapla(deger,hassasUcgen);
if (üyelik == "hassas")
return YamukUyelikHesapla(deger,hassasYamukSon);
}break;
case "Miktar":
{
if (üyelik == "küçük")
return YamukUyelikHesapla(deger, miktarYamukBas);
if (üyelik == "orta")
return UcgenUyelikHesapla(deger, miktarUcgen);
if (üyelik == "büyük")
return YamukUyelikHesapla(deger, miktarYamukSon);
}
break;
case "Kirlilik":
{
if (üyelik == "küçük")
return YamukUyelikHesapla(deger, kirlilikYamukBas);
if (üyelik == "orta")
return UcgenUyelikHesapla(deger, kirlilikUcgen);
if (üyelik == "büyük")
return YamukUyelikHesapla(deger, kirlilikYamukSon);
}
break;
default:
break;
}
return 0;
}
public double YamukUyelikHesapla(double deger,double []yamuk)
{
double a = deger;
double a1, a2, a3, a4;
a1 = yamuk[0];
a2 = yamuk[1];
a3 = yamuk[2];
a4 = yamuk[3];
double s1 = (a - a1) / (a2 - a1);
double s2 = (a4 - a) / (a4 - a3);
return Math.Max(Math.Min(s1,Math.Min(1,s2)),0);
}
public double UcgenUyelikHesapla(double deger, double[] ucgen)
{
double a = deger;
double a1, a2, a3;
a1 = ucgen[0];
a2 = ucgen[1];
a3 = ucgen[2];
double s1 = (a - a1) / (a2-a1);
double s2 = (a3 - a) / (a3 - a2);
return Math.Max(Math.Min(s1,s2),0);
}
}
}
<file_sep>/README.md
# Bulanik-Mantik-Camasir-Makinesi
Degerler Matlab ortamında karşılaştırılmıştır.
<br>

<br>

<br>

<br>

<file_sep>/Bulanık/Bulanık/OzelKontrol.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace WindowsFormsApplication1
{
public partial class OzelKontrol : UserControl
{
Point labelSıfırNoktası;
public String Ad { get; set; }
public NumericUpDown numericUpDown{get;set;}
public OzelKontrol()
{
InitializeComponent();
}
DetayForm detayForm;
private void OzelKontrol_Load(object sender, EventArgs e)
{
labelSıfırNoktası = label1.Location;
chart1.Series["SAĞLAM"].Points.AddXY(0, 1);
chart1.Series["SAĞLAM"].Points.AddXY(1, 1);
chart1.Series["SAĞLAM"].Points.AddXY(2, 1);
chart1.Series["SAĞLAM"].Points.AddXY(4, 0);
chart1.Series["ORTA"].Points.AddXY(3, 0);
chart1.Series["ORTA"].Points.AddXY(5, 1);
chart1.Series["ORTA"].Points.AddXY(7, 0);
chart1.Series["HASSAS"].Points.AddXY(5.5, 0);
chart1.Series["HASSAS"].Points.AddXY(8, 1);
chart1.Series["HASSAS"].Points.AddXY(9, 1);
chart1.Series["HASSAS"].Points.AddXY(10, 1);
chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
chart1.ChartAreas[0].AxisX.IsMarginVisible = false;
}
private static decimal map(decimal deger, decimal fromLow, decimal fromHigh, decimal toLow, decimal toHigh)
{
return (deger - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow;
}
public void updateUi()
{
if (numericUpDown != null)
{
numericUpDown.Value = getValue();
}
}
public TrackBar getTrackBar()
{
return trackBar1;
}
public decimal getValue()
{
decimal x = map(trackBar1.Value, 0, 50, 0, 10);
return x;
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
label1.Location = new Point(labelSıfırNoktası.X +((int)(trackBar1.Value*5)) ,21);
updateUi();
}
public void changeLegends(String[]args) {
chart1.Series[0].Name = args[0];
chart1.Series[1].Name = args[1];
chart1.Series[2].Name= args[2];
}
private void trackBar1_ValueChanged(object sender, EventArgs e)
{
trackBar1_Scroll(sender,e);
}
public Chart getChart (){
return this.chart1;
}
private void chart1_Click(object sender, EventArgs e)
{
}
private void btnDetay_Click(object sender, EventArgs e)
{
detayForm = new DetayForm();
detayForm.setChart(this.chart1,Ad);
detayForm.Show();
}
}
}
<file_sep>/Bulanık/Bulanık/CıktıDetay.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class CıktıDetay : Form
{
public CıktıDetay()
{
InitializeComponent();
}
private void DeterjanDetay_Load(object sender, EventArgs e)
{
renkAyarla();
}
public void setDeterjanEkran()
{
textBox1.Text = "[ 0,0,20,85 ]";
textBox2.Text = "[ 20,85,150 ]";
textBox3.Text = "[ 85,150,215 ]";
textBox4.Text = "[ 150,215,280 ]";
textBox5.Text = "[ 215,280,300,300 ]";
}
public void setDonusHızıEkran()
{
textBox1.Text = "[ -5.8,-2.8,0,5,1.5 ]";
textBox2.Text = "[ 0.5,2.75,5 ]";
textBox3.Text = "[ 2.75,5,7.25 ]";
textBox4.Text = "[ 5,7.25,9.5 ]";
textBox5.Text = "[ 8.5,9.5,12.8,15.2 ]";
}
public void setSureEkran()
{
textBox1.Text = "[ -46.5,-25.28,22.3,39.9 ]";
textBox2.Text = "[ 22.3,39.9.57,5 ]";
textBox3.Text = "[ 39.9,57.5,75.1 ]";
textBox4.Text = "[ 57.5,75.1,92.7 ]";
textBox5.Text = "[ 75,92.7,111.6,130 ]";
}
public void renkAyarla()
{
pbRenk1.BackColor = Color.Yellow;
pbRenk2.BackColor = Color.Red;
pbRenk3.BackColor = Color.Pink;
pictureBox1.BackColor = Color.DeepPink;
pictureBox2.BackColor = Color.Orange;
}
}
}
<file_sep>/Bulanık/Bulanık/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
//tüm program boyunca bu kullanılacaktır
BulanıkMantık bulanıkMantık;
public static List<Kural> KURAL_TABANI;
public List<String> kirlilikkumeAdlari;
public List<String> miktarkumeAdlari;
List<String> hassasiyetkumeAdlari;
private double donusHızıAgırlıklıOrtalama;
Dictionary<string, double> deterjanKumeVeKestikleri = new Dictionary<string, double>();
Dictionary<string, double> hızKumeVeKestikleri = new Dictionary<string, double>();
Dictionary<string, double> sureKumeVeKestikleri = new Dictionary<string, double>();
CıktıDetay cıktıDetafForm;
public Dictionary<string, double> deterjanÇarpan = new Dictionary<string, double>()
{
{"çok az",20 }, {"az",85 }, {"orta",150 }, {"fazla",215 }, {"çok fazla",270 }
};
public Dictionary<string, double> hızÇarpan = new Dictionary<string, double>()
{
{"hassas",0.514 }, {"normal hassas",2.75 }, {"orta",5.0 }, {"normal güçlü",7.25 }, {"güçlü",9.5 }
};
public Dictionary<string, double> sureÇarpan = new Dictionary<string, double>()
{
{"kısa",22.3 }, {"normal kısa",39.9 }, {"orta",57.5 }, {"normal uzun",75.1 }, {"uzun",92.7 }
};
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
bulanıkMantık = new BulanıkMantık();
double a=bulanıkMantık.UcgenUyelikHesapla(6.7,bulanıkMantık.hassasUcgen);
// a=bulanıkMantık.GirisUyelikHesapla("Miktar", "küçük", 2.40);
// MessageBox.Show(a.ToString());
init();
}
public void init()
{
chrtDeterjan.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
chrtDeterjan.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
chrtDeterjan.ChartAreas[0].AxisX.IsMarginVisible = false;
chrtHız.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
chrtHız.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
chrtHız.ChartAreas[0].AxisX.IsMarginVisible = false;
chrtSure.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
chrtSure.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
chrtSure.ChartAreas[0].AxisX.IsMarginVisible = false;
KURAL_TABANI = new List<Kural>();
kuralTabanıDoldur();
grfHassasiyet.numericUpDown = nudHassasiyet;
grfHassasiyet.Ad = "hassasiyet";
grfKirlilik.numericUpDown = nudKirlilik;
grfKirlilik.Ad = "kirlilik";
grfMiktar.numericUpDown = nudMiktar;
grfMiktar.Ad = "miktar";
grfMiktar.changeLegends(new String[]{"KÜÇÜK","ORTA","BÜYÜK"});
grfKirlilik.changeLegends(new String[] { "KÜÇÜK", "ORTA", "BÜYÜK" });
grfKirlilik.getChart().Series["KÜÇÜK"].Points.RemoveAt(grfKirlilik.getChart().Series["KÜÇÜK"].Points.Count()-1);
grfKirlilik.getChart().Series["KÜÇÜK"].Points.AddXY(4.5,0);
hassasiyetkumeAdlari = new List<string>();
kirlilikkumeAdlari = new List<string>();
miktarkumeAdlari = new List<string>();
}
private void kuralTabanıDoldur()
{
KURAL_TABANI.Clear();
String[]kurallarListesi= File.ReadAllLines("kural_tabanı.txt");
for (int i = 0; i < kurallarListesi.Length; i++)
{
String[] kural = kurallarListesi[i].Split(',');
Kural temp = new Kural((i + 1), kural[0], kural[1], kural[2], kural[3], kural[4], kural[5]);
KURAL_TABANI.Add(temp);
mainGrid.Rows.Add(temp.Index_numarası,temp.Hassaslık,temp.Miktar,temp.Kirlilik,temp.Donus_Hizi,temp.Sure,temp.Deterjan);
}
}
private decimal aralık_dönüstür(decimal deger, decimal x1, decimal x2, decimal y1, decimal y2)
{
return (deger - x1) * (y2 - y1) / (x2 - x1) + y1;
}
private void nudHassasiyet_ValueChanged(object sender, EventArgs e)
{
nudHassaslıkSağlam.Value = 0;
nudHassasOrta.Value = 0;
nudHassaslıkHassas.Value = 0;
hassasiyetkumeAdlari.Clear();
lblHassasiyet.Text = "";
decimal x = aralık_dönüstür(nudHassasiyet.Value, 0, 10, 0, 50);
TrackBar temp = grfHassasiyet.getTrackBar();
temp.Value = ((int)x);
hassasiyetkumeAdlari=Fonksiyonlar.UyeKumeAdıBul(((double)nudHassasiyet.Value),"Hassaslık");
hassasiyetkumeAdlari.ForEach(uye=> {
double ax=bulanıkMantık.GirisUyelikHesapla("Hassaslık",uye,((double)nudHassasiyet.Value));
if(uye=="sağlam")
nudHassaslıkSağlam.Value = (decimal)ax;
else if (uye == "orta")
nudHassasOrta.Value = (decimal)ax;
else if (uye == "hassas")
nudHassaslıkHassas.Value = (decimal)ax;
lblHassasiyet.Text +="-"+ uye;
});
ateşle();
}
private void nudMiktar_ValueChanged(object sender, EventArgs e)
{
nudMiktarKücük.Value = 0;
nudMiktarOrta.Value = 0;
nudMiktarBüyük.Value = 0;
miktarkumeAdlari.Clear();
lblMiktar.Text = "";
decimal x = aralık_dönüstür(nudMiktar.Value, 0, 10, 0, 50);
TrackBar temp = grfMiktar.getTrackBar();
temp.Value = ((int)x);
miktarkumeAdlari= Fonksiyonlar.UyeKumeAdıBul(((double)nudMiktar.Value), "Miktar");
miktarkumeAdlari.ForEach(uye => {
double ax = bulanıkMantık.GirisUyelikHesapla("Miktar", uye, ((double)nudMiktar.Value));
if (uye == "küçük")
nudMiktarKücük.Value = (decimal)ax;
else if (uye == "orta")
nudMiktarOrta.Value = (decimal)ax;
else if (uye == "büyük")
nudMiktarBüyük.Value = (decimal)ax;
lblMiktar.Text += "-" + uye;
});
ateşle();
}
private void nudKirlilik_ValueChanged(object sender, EventArgs e)
{
nudKirlilikKüçük.Value = 0;
nudKirlilikOrta.Value = 0;
nudKirlilikBüyük.Value = 0;
kirlilikkumeAdlari.Clear();
lblKirlilik.Text = "";
decimal x = aralık_dönüstür(nudKirlilik.Value, 0, 10, 0, 50);
TrackBar temp = grfKirlilik.getTrackBar();
temp.Value = ((int)x);
kirlilikkumeAdlari = Fonksiyonlar.UyeKumeAdıBul(((double)nudKirlilik.Value), "Kirlilik");
kirlilikkumeAdlari.ForEach(uye => {
double ax = bulanıkMantık.GirisUyelikHesapla("Kirlilik", uye, ((double)nudKirlilik.Value));
if (uye == "küçük")
nudKirlilikKüçük.Value = (decimal)ax;
else if (uye == "orta")
nudKirlilikOrta.Value = (decimal)ax;
else if (uye == "büyük")
nudKirlilikBüyük.Value = (decimal)ax;
lblKirlilik.Text += "-"+uye;
});
ateşle();
}
public void ateşle() {
cikisChartTemizle();
/*
if (nudHassasiyet.Value == 0 || nudKirlilik.Value == 0 || nudMiktar.Value == 0)
return;
*/
List<int>indexler= Fonksiyonlar.KuralAteşlemeIndexBul(hassasiyetkumeAdlari, miktarkumeAdlari, kirlilikkumeAdlari);
gridisaretle(indexler);
indexler.Sort();
listBox1.Items.Clear();
for (int i = 0; i < indexler.Count(); i++)
{
kuralMandaniÇıkarımıYap(KURAL_TABANI[ indexler[i]]);
}
deterjanKumeVeKestikleri.Clear();
hızKumeVeKestikleri.Clear();
sureKumeVeKestikleri.Clear();
for (int i = 0; i < indexler.Count(); i++)
{
Kural temp = KURAL_TABANI[indexler[i]];
double yükseklik =(double) listBox1.Items[i];
cıkısGrafiğiKes(temp,yükseklik);
}
agirlikliOrtalamaHesapla();
}
public void agirlikliOrtalamaHesapla() {
StringBuilder builder = new StringBuilder();
double pay = 0.0;
double payda = 0.0;
foreach (string item in deterjanKumeVeKestikleri.Keys)
{
pay += (deterjanÇarpan[item] * deterjanKumeVeKestikleri[item]);
payda += deterjanKumeVeKestikleri[item];
builder.Append(item.ToUpper()+": " + deterjanKumeVeKestikleri[item]+" ");
}
lblDeterjanAgırlıklıOrtalama.Text =Math.Round( (pay/payda ),9).ToString();
lblDeterjanKume.Text = builder.ToString();
builder.Clear();
pay = 0.0;
payda = 0.0;
foreach (string item in hızKumeVeKestikleri.Keys)
{
pay += (hızÇarpan[item] * hızKumeVeKestikleri[item]);
payda += hızKumeVeKestikleri[item];
builder.Append(item.ToUpper() + " :" + hızKumeVeKestikleri[item]+" ");
}
lblHızAgırlıklıOrtalama.Text =Math.Round( (pay / payda),9).ToString();
lblHızKume.Text = builder.ToString();
builder.Clear();
pay = 0.0;
payda = 0.0;
foreach (string item in sureKumeVeKestikleri.Keys)
{
pay += (sureÇarpan[item] * sureKumeVeKestikleri[item]);
payda += sureKumeVeKestikleri[item];
builder.Append(item.ToUpper() + ": " + sureKumeVeKestikleri[item]+" ");
}
lblSureAgırlıklıOrtalama.Text =Math.Round( (pay / payda),9).ToString();
labelblSureKümel12.Text = builder.ToString();
}
public void cıkısGrafiğiKes(Kural temp, double aralık)
{
switch (temp.Deterjan)
{
case "çok az":
{
if (deterjanKumeVeKestikleri.ContainsKey("çok az") && deterjanKumeVeKestikleri["çok az"] < aralık)
{
deterjanKumeVeKestikleri.Remove("çok az");
deterjanKumeVeKestikleri.Add("çok az", aralık);
}
else if (deterjanKumeVeKestikleri.ContainsKey("çok az")) { }
else
{
deterjanKumeVeKestikleri.Add("çok az", aralık);
}
chrtDeterjan.Series["cıkıs"].Points.AddXY(0, aralık);
chrtDeterjan.Series["cıkıs"].Points.AddXY(85, aralık);
}
break;
case "az":
{
if (deterjanKumeVeKestikleri.ContainsKey("az") && deterjanKumeVeKestikleri["az"] < aralık)
{
deterjanKumeVeKestikleri.Remove("az");
deterjanKumeVeKestikleri.Add("az", aralık);
}
else if (deterjanKumeVeKestikleri.ContainsKey("az")){ }
else
{
deterjanKumeVeKestikleri.Add("az", aralık);
}
chrtDeterjan.Series["cıkıs"].Points.AddXY(bulanıkMantık.deterjanAzUcgen[0], aralık);
chrtDeterjan.Series["cıkıs"].Points.AddXY(bulanıkMantık.deterjanAzUcgen[2], aralık);
}
break;
case "orta":
{
if (deterjanKumeVeKestikleri.ContainsKey("orta") && deterjanKumeVeKestikleri["orta"] < aralık)
{
deterjanKumeVeKestikleri.Remove("orta");
deterjanKumeVeKestikleri.Add("orta", aralık);
}
else if(deterjanKumeVeKestikleri.ContainsKey("orta"))
{ }
else
{
deterjanKumeVeKestikleri.Add("orta", aralık);
}
chrtDeterjan.Series["cıkıs"].Points.AddXY(bulanıkMantık.deterjanOrtaUcgen[0], aralık);
chrtDeterjan.Series["cıkıs"].Points.AddXY(bulanıkMantık.deterjanOrtaUcgen[2], aralık);
}
break;
case "fazla":
{
if (deterjanKumeVeKestikleri.ContainsKey("fazla") && deterjanKumeVeKestikleri["fazla"] < aralık)
{
deterjanKumeVeKestikleri.Remove("fazla");
deterjanKumeVeKestikleri.Add("fazla", aralık);
}
else if (deterjanKumeVeKestikleri.ContainsKey("fazla"))
{ }
else
{
deterjanKumeVeKestikleri.Add("fazla", aralık);
}
chrtDeterjan.Series["cıkıs"].Points.AddXY(bulanıkMantık.deterjanFazla[0], aralık);
chrtDeterjan.Series["cıkıs"].Points.AddXY(bulanıkMantık.deterjanFazla[2], aralık);
}
break;
case "çok fazla":
{
if (deterjanKumeVeKestikleri.ContainsKey("çok fazla") && deterjanKumeVeKestikleri["çok fazla"] < aralık)
{
deterjanKumeVeKestikleri.Remove("çok fazla");
deterjanKumeVeKestikleri.Add("çok fazla", aralık);
}
else if (deterjanKumeVeKestikleri.ContainsKey("çok fazla"))
{ }
else
{
deterjanKumeVeKestikleri.Add("çok fazla", aralık);
}
chrtDeterjan.Series["cıkıs"].Points.AddXY(bulanıkMantık.deterjanCokFazla[0], aralık);
chrtDeterjan.Series["cıkıs"].Points.AddXY(bulanıkMantık.deterjanCokFazla[2], aralık);
}
break;
}
switch (temp.Donus_Hizi)
{
case "hassas":
{
if (hızKumeVeKestikleri.ContainsKey("hassas") && hızKumeVeKestikleri["hassas"] < aralık)
{
hızKumeVeKestikleri.Remove("hassas");
hızKumeVeKestikleri.Add("hassas", aralık);
}
else if (hızKumeVeKestikleri.ContainsKey("hassas")) { }
else
{
hızKumeVeKestikleri.Add("hassas", aralık);
}
chrtHız.Series["cıkıs"].Points.AddXY(0,aralık);
chrtHız.Series["cıkıs"].Points.AddXY(bulanıkMantık.hızHassasYamuk[3],aralık);
}
break;
case "normal hassas":
{
if (hızKumeVeKestikleri.ContainsKey("normal hassas") && hızKumeVeKestikleri["normal hassas"] < aralık)
{
hızKumeVeKestikleri.Remove("normal hassas");
hızKumeVeKestikleri.Add("normal hassas", aralık);
}
else if (hızKumeVeKestikleri.ContainsKey("normal hassas")) { }
else
{
hızKumeVeKestikleri.Add("normal hassas", aralık);
}
chrtHız.Series["cıkıs"].Points.AddXY(bulanıkMantık.hızNormalHassasUcgen[0], aralık);
chrtHız.Series["cıkıs"].Points.AddXY(bulanıkMantık.hızNormalHassasUcgen[2], aralık);
}
break;
case "orta":
{
if (hızKumeVeKestikleri.ContainsKey("orta") && hızKumeVeKestikleri["orta"] < aralık)
{
hızKumeVeKestikleri.Remove("orta");
hızKumeVeKestikleri.Add("orta", aralık);
}
else if (hızKumeVeKestikleri.ContainsKey("orta")) { }
else
{
hızKumeVeKestikleri.Add("orta", aralık);
}
chrtHız.Series["cıkıs"].Points.AddXY(3, aralık);
chrtHız.Series["cıkıs"].Points.AddXY(7, aralık);
}
break;
case "normal güçlü":
{
if (hızKumeVeKestikleri.ContainsKey("normal güçlü") && hızKumeVeKestikleri["normal güçlü"] < aralık)
{
hızKumeVeKestikleri.Remove("normal güçlü");
hızKumeVeKestikleri.Add("normal güçlü", aralık);
}
else if (hızKumeVeKestikleri.ContainsKey("normal güçlü")) { }
else
{
hızKumeVeKestikleri.Add("normal güçlü", aralık);
}
chrtHız.Series["cıkıs"].Points.AddXY(bulanıkMantık.hızNormalGüçlüUcgen[0], aralık);
chrtHız.Series["cıkıs"].Points.AddXY(bulanıkMantık.hızNormalGüçlüUcgen[2], aralık);
}
break;
case "güçlü":
{
if (hızKumeVeKestikleri.ContainsKey("güçlü") && hızKumeVeKestikleri["güçlü"] < aralık)
{
hızKumeVeKestikleri.Remove("güçlü");
hızKumeVeKestikleri.Add("güçlü", aralık);
}
else if (hızKumeVeKestikleri.ContainsKey("güçlü")) { }
else
{
hızKumeVeKestikleri.Add("güçlü", aralık);
}
chrtHız.Series["cıkıs"].Points.AddXY(bulanıkMantık.hızGüçlüYamuk[0], aralık);
chrtHız.Series["cıkıs"].Points.AddXY(10, aralık);
}
break;
}
switch (temp.Sure) {
case "kısa":
{
if (sureKumeVeKestikleri.ContainsKey("kısa") && sureKumeVeKestikleri["kısa"] < aralık)
{
sureKumeVeKestikleri.Remove("kısa");
sureKumeVeKestikleri.Add("kısa", aralık);
}
else if (sureKumeVeKestikleri.ContainsKey("kısa")) { }
else
{
sureKumeVeKestikleri.Add("kısa", aralık);
}
chrtSure.Series["cıkıs"].Points.AddXY(0,aralık);
chrtSure.Series["cıkıs"].Points.AddXY(40,aralık);
}
break;
case "normal kısa":
{
if (sureKumeVeKestikleri.ContainsKey("normal kısa") && sureKumeVeKestikleri["normal kısa"] < aralık)
{
sureKumeVeKestikleri.Remove("normal kısa");
sureKumeVeKestikleri.Add("normal kısa", aralık);
}
else if (sureKumeVeKestikleri.ContainsKey("normal kısa")) { }
else
{
sureKumeVeKestikleri.Add("normal kısa", aralık);
}
chrtSure.Series["cıkıs"].Points.AddXY(22, aralık);
chrtSure.Series["cıkıs"].Points.AddXY(60, aralık);
}
break;
case "orta":
{
if (sureKumeVeKestikleri.ContainsKey("orta") && sureKumeVeKestikleri["orta"] < aralık)
{
sureKumeVeKestikleri.Remove("orta");
sureKumeVeKestikleri.Add("orta", aralık);
}
else if (sureKumeVeKestikleri.ContainsKey("orta")) { }
else
{
sureKumeVeKestikleri.Add("orta", aralık);
}
chrtSure.Series["cıkıs"].Points.AddXY(40, aralık);
chrtSure.Series["cıkıs"].Points.AddXY(75, aralık);
}
break;
case "normal uzun":
{
if (sureKumeVeKestikleri.ContainsKey("normal uzun") && sureKumeVeKestikleri["normal uzun"] < aralık)
{
sureKumeVeKestikleri.Remove("normal uzun");
sureKumeVeKestikleri.Add("normal uzun", aralık);
}
else if (sureKumeVeKestikleri.ContainsKey("normal uzun")) { }
else
{
sureKumeVeKestikleri.Add("normal uzun", aralık);
}
chrtSure.Series["cıkıs"].Points.AddXY(58, aralık);
chrtSure.Series["cıkıs"].Points.AddXY(92, aralık);
}
break;
case "uzun":
{
if (sureKumeVeKestikleri.ContainsKey("uzun") && sureKumeVeKestikleri["uzun"] < aralık)
{
sureKumeVeKestikleri.Remove("uzun");
sureKumeVeKestikleri.Add("uzun", aralık);
}
else if (sureKumeVeKestikleri.ContainsKey("uzun")) { }
else
{
sureKumeVeKestikleri.Add("uzun", aralık);
}
chrtSure.Series["cıkıs"].Points.AddXY(73, aralık);
chrtSure.Series["cıkıs"].Points.AddXY(95, aralık);
}
break;
}
}
public void cikisChartTemizle() {
chrtDeterjan.Series["cıkıs"].Points.Clear();
chrtHız.Series["cıkıs"].Points.Clear();
chrtSure.Series["cıkıs"].Points.Clear();
}
public void kuralMandaniÇıkarımıYap(Kural kural) {
double hassaslık = 0.0;
double miktar = 0.0;
double kirlilik = 0.0;
switch (kural.Hassaslık)
{
case "hassas":
hassaslık =(double) nudHassaslıkHassas.Value;
break;
case "orta":
hassaslık = (double)nudHassasOrta.Value;
break;
case "sağlam":
hassaslık = (double)nudHassaslıkSağlam.Value;
break;
}
switch (kural.Miktar)
{
case "küçük":
miktar =(double) nudMiktarKücük.Value;
break;
case "orta":
miktar = (double)nudMiktarOrta.Value;
break;
case "büyük":
miktar = (double)nudMiktarBüyük.Value;
break;
}
switch (kural.Kirlilik)
{
case "küçük":
kirlilik = (double)nudKirlilikKüçük.Value;
break;
case "orta":
kirlilik = (double)nudKirlilikOrta.Value;
break;
case "büyük":
kirlilik = (double)nudKirlilikBüyük.Value;
break;
}
listBox1.Items.Add(Math.Min(Math.Min(kirlilik,miktar),hassaslık));
}
public void gridisaretle(List<int>indexler)
{
gridTemizle();
StringBuilder builder = new StringBuilder();
indexler.ForEach(index=> {
mainGrid.Rows[index].DefaultCellStyle.BackColor = Color.Red;
});
}
public void gridTemizle()
{
foreach (DataGridViewRow row in mainGrid.Rows)
{
row.DefaultCellStyle.BackColor = Color.White;
}
}
private void grfHassasiyet_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
this.Text = this.Text.Substring(1) + this.Text.Substring(0, 1);
}
private void deterjanDetayToolStripMenuItem_Click(object sender, EventArgs e)
{
CıktıDetay fx= new CıktıDetay();
fx.setDeterjanEkran();
fx.Show();
}
private void döndürmeHızıDetayToolStripMenuItem_Click(object sender, EventArgs e)
{
CıktıDetay fx = new CıktıDetay();
fx.setDonusHızıEkran();
fx.Show();
}
private void süreDetayToolStripMenuItem_Click(object sender, EventArgs e)
{
CıktıDetay fx = new CıktıDetay();
fx.setSureEkran();
fx.Show();
}
private void hassaslıkDetayToolStripMenuItem_Click(object sender, EventArgs e)
{
DetayForm formx = new DetayForm();
formx.setChart(grfHassasiyet.getChart(),"hassasiyet");
formx.Show();
}
private void miktarDetayToolStripMenuItem_Click(object sender, EventArgs e)
{
DetayForm formx = new DetayForm();
formx.setChart(grfMiktar.getChart(), "miktar");
formx.Show();
}
private void kirlilikDetayToolStripMenuItem_Click(object sender, EventArgs e)
{
DetayForm formx = new DetayForm();
formx.setChart(grfKirlilik.getChart(), "kirlilik");
formx.Show();
}
private void hakkındaToolStripMenuItem_Click(object sender, EventArgs e)
{
Hakkında hk = new Hakkında();
hk.Show();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("https://github.com/ymyurdakul");
}
}
}
| 2b607ab044563f92a6e0611504f674bdfbe88a7d | [
"Markdown",
"C#"
]
| 8 | C# | ymyurdakul/Bulanik-Mantik-Camasir-Makinesi | 229b7a913ba35704c27b94a842c9eb46a1a77765 | 82a9cadf08ebe5048d92bd086ff4ac0a12593bb1 |
refs/heads/master | <repo_name>asuengineering/FSE-Spoken-News<file_sep>/spokennews_options.php
<?php
/* Carbon Fields Customizations for Spoken Word Theme */
/* Requires Carbon Fields.
/* Carbon Fields installed in the theme via Composer. */
use Carbon_Fields\Container;
use Carbon_Fields\Field;
add_action( 'carbon_fields_register_fields', 'crb_attach_theme_options' );
function crb_attach_theme_options() {
Container::make( 'theme_options', __( 'Theme Options', 'asufse_spokenword' ) )
->add_fields( array(
Field::make( 'textarea', 'asufse_spokenword_openingtext', 'Opening Text' )->set_rows( 4 ),
Field::make( 'html', 'asufse_spokenword_information_text' )
->set_html( '<p><strong style="color:red;">Note: </strong>HTML tags like <code><phone></code> embedded within the options above will not be visible when viewing the human readable output for the skill. But any embedded code is still there when the skill is consumed by the end user.</p>' ),
Field::make( 'textarea', 'asufse_spokenword_closingtext', 'Closing Text' )->set_rows( 4 ),
) );
}
add_action( 'after_setup_theme', 'crb_load' );
function crb_load() {
require_once( 'vendor/autoload.php' );
\Carbon_Fields\Carbon_Fields::boot();
}<file_sep>/README.md
# Fulton Schools Spoken News Theme for WordPress #
A theme for [WordPress](http://wordpress.org) from the [Ira A. Fulton Schools of Engineering](http://engineering.asu.edu) at [Arizona State University](http://asu.edu). Intended to provide a managable news feed for an Amazon skill for Alexa to be consumed by residents of the Tooker House.
## Notes ##
This is a theme for WordPress hosted by ASU, but it is not ASU Brand Standard compliant. To build a web standards compliant website, there are a number of other products available. See [wordpress.asu.edu](https://wordpress.asu.edu) for a list of WebSpark alternatives.
Contains a Custom Post Type called `spokennews` and several theme files to render the correct output for the Alexa skill.
- The machine-readable page is the CPT achive page located at `/spokennews`
- A human-readable page can be rendered by creating a page using the **Spoken News for Humans** page template.

## Versions ##
- v0.4: Added heme options panel to allow for intro and outro text to be changed as needed.
- v0.3: More intro/outro text adjustments.
- v0.2: Adjusted hard coded values for intro and outro text.
- v0.1: Initial deployment to GitHub.
// ## To Do ##
<file_sep>/template-parts/spoken.php
<?php
/**
* Template part for displaying Spoken Word news items
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<hr>
<?php the_content(); ?>
</article>
<file_sep>/template-parts/spoken-human.php
<?php
/**
* Template part for displaying page content in spokennews-human.php
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header group">
<?php the_title( '<h2 class="entry-title">', '</h2>' ); ?>
<span class="post-meta">
<?php
echo "Word Count: " . str_word_count( get_the_content() ) ;
edit_post_link('Edit');
?>
</span>
</header><!-- .entry-header -->
<div class="entry-content">
<?php the_content(); ?>
</div><!-- .entry-content -->
<?php if ( get_edit_post_link() ) : ?>
<footer class="entry-footer">
<p>
<strong>Created: </strong>
<?php echo get_the_time('F j, Y \a\t g:i a'); ?>
</br>
<strong>Expires: </strong>
<?php echo do_shortcode('[postexpirator]'); ?>
</br></br>
<strong>Category: </strong>
<?php $terms = get_the_terms( $post->ID , 'spokennews_category' );
foreach ( $terms as $term ) {
if( $term->name == 'Expired' ) {
echo '<span class="red">' . $term->name . '</span>';
} else {
echo '<span>' . $term->name . '</span>';
}
}
?>
</p>
</footer><!-- .entry-footer -->
<?php endif; ?>
</article><!-- #post-<?php the_ID(); ?> -->
<file_sep>/spokennews-human.php
<?php
/*
* Template Name: Spoken News for Humans
* The template for displaying the user-friendly page that displays all spoken word items.
* Based on page.php
* @link https://codex.wordpress.org/Template_Hierarchy
*/
// Add specific CSS class by filter.
add_filter( 'body_class', function( $classes ) {
return array_merge( $classes, array( 'spokennews', 'spokennews-human' ) );
} );
/* Page Template
============================ */
get_header();?>
<?php
// get Carbon Field values for opening and closing text.
$opening = carbon_get_theme_option( 'asufse_spokenword_openingtext' );
$closing = carbon_get_theme_option( 'asufse_spokenword_closingtext' );
// Quick Page loop for the contents of the page.
while ( have_posts() ) : the_post();
the_content();
endwhile; // End of the loop.
?>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<article class="theme-option hentry">
<p class="spoken-wrap spoken-wrap-open"><strong>Preface text: </strong><?php echo $opening; ?></p>
</article>
<?php
/* Secondary Loop Posts */
$args = array(
'post_type' => 'spokennews',
'orderby' => 'menu_order title',
'order' => 'ASC',
'posts_per_page' => 8,
);
$spokennews_posts = new WP_Query($args);
while ( $spokennews_posts->have_posts() ) : $spokennews_posts->the_post(); ?>
<?php get_template_part( 'template-parts/spoken', 'human' );
endwhile; // End of the loop. ?>
<article class="theme-option hentry">
<p class="spoken-wrap spoken-wrap-close"><strong>Closing text: </strong><?php echo $closing;?></p>
</article>
<?php
$pagination_args = array(
'mid_size' => 2,
'prev_text' => __( 'Newer', 'textdomain' ),
'next_text' => __( 'Older', 'textdomain' ),
);
echo get_the_posts_pagination($pagination_args);
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_footer();
<file_sep>/template-parts/spoken-none.php
<?php
/**
* Template part for displaying a message that posts cannot be found
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package ASUFSE_SpokenWord
*/
?>
<section class="no-results not-found">
<p>At this time there is no news for the Fulton Schools of Engineering. Check back later, please.</p>
</section><!-- .no-results -->
<file_sep>/archive-spokennews.php
<?php
/**
* The template for displaying Spoken News Archives
* This is the page to be "scraped" by the service
*/
// Add specific CSS class by filter.
add_filter( 'body_class', function( $classes ) {
return array_merge( $classes, array( 'spokennews', 'spokennews-machine' ) );
} );
// get Carbon Field values for opening and closing text.
$opening = carbon_get_theme_option( 'asufse_spokenword_openingtext' );
$closing = carbon_get_theme_option( 'asufse_spokenword_closingtext' );
/* Page Template
============================ */
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main spokennews-start">
<?php if ( have_posts() ) : ?>
<h4 class="spoken-wrap spoken-wrap-open"><?php echo $opening; ?></h4>
<?php
/* Query Posts */
$args = array(
'post_type' => 'spokennews',
'orderby' => 'menu_order title',
'order' => 'ASC',
'nopaging' => 'true',
'posts_per_page' => 8,
'tax_query' => array (
array (
'taxonomy' => 'spokennews_category',
'field' => 'slug',
'terms' => 'expired',
'operator' => 'NOT IN',
),
),
);
query_posts($args);
/* Start the Loop */
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/spoken' );
endwhile;
?>
<hr>
<h4 class="spoken-wrap spoken-wrap-close"><?php echo $closing;?></h4>
<?php else :
get_template_part( 'template-parts/spoken', 'none' );
endif;
wp_reset_query(); ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_footer(); ?>
<file_sep>/single-spokennews.php
<?php
/**
* The template for displaying all single SpokenNews items
*/
// Add specific CSS class by filter.
add_filter( 'body_class', function( $classes ) {
return array_merge( $classes, array( 'spokennews', 'spokennews-human' ) );
} );
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<?php
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/spoken', 'human' );
endwhile; // End of the loop.
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_footer();
| 4efb64487a567ec6cfdbd20d15bfab4ca781d6ea | [
"Markdown",
"PHP"
]
| 8 | PHP | asuengineering/FSE-Spoken-News | 3ad67de79eb669bf61b4e4218ea18d2f11bb504d | 15a7f0bb43304cbe75b25651dcfcbd8572645c8e |
refs/heads/main | <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 admin;
/**
*
* @author lelezhao
*/
public class Student {
private String firstName;
private String lastName;
private double grade;
public Student(String first, String last, double grade){
this.setFirstName(first);
this.setLastName(last);
this.setGrade(grade);
}
public void setGrade(double n){
this.grade = n;
}
public double getGrade(){
return this.grade;
}
public void setFirstName(String first){
this.firstName=first;
}
public void setLastName(String last){
this.lastName = last;
}
public String getLastName(){
return this.lastName;
}
public String getFirstName(){
return this.firstName;
}
}
| 5ba252b20b8c9bf6e12b3d302a3eb5cd3b984703 | [
"Java"
]
| 1 | Java | vanessaDiM/test | fa00fd7f4730214b472eee842d3ed3fe88816a25 | fb027036505a938712d6b6b896653ac2381dacff |
refs/heads/master | <file_sep>---
title: Schichtkohl mit Hackfleisch
date: 2019-05-12
lastmod: 2023-05-23 17:00:30
tags:
- hack
- lowcarb
- pfanne
- schnell
- simple
aliases:
- ../../hauptgerichte/schichtkohl-mit-hackfleisch
---
Schichtkohl Rezepte sind simpel und schnell zubereitet und können beliebig variiert werden. Eine Variation von diesem Rezept ist zum Beispiel [Schichtkohl mit Blutwurst]({{< relref schichtkohl-mit-blutwurst >}}).

## Zutaten für 4 Portionen
- 1 große Zwiebel
- 850 g (½ Kopf) Kohlsorte: Weißkohl, Wirsingkohl, Spitzkohl
- Öl oder Fett
- Salz & Pfeffer
- 500 g Hackfleisch
- 200 ml Gemüsebrühe
Optional:
- 1 Knoblauchzehe
- 1 cm Ingwer
- Soyasoße
- Fischsoße
- Reis-Essig
- Sesamöl
- Sesam
## Zubereitung
1. Den Weißkohl in Streifen, die Zwiebel in Würfel schneiden.
1. Beides zusammen mit Öl portionsweise im Wok oder Bräter anbraten.
1. *Optional*: Knoblauchzehe und Ingwer schälen, kleinhacken und mit Öl in einer extra Pfanne anbraten.
1. Das Hackfleisch in die Pfanne geben und durchbraten.
1. Dann das Fleisch zum Kohl und den Zwiebeln in den Wok geben und mit der Brühe ablöschen.
1. Bei geschlossenem Deckel noch 10 - 15 Minuten bei mittlerer Hitze köcheln lassen und mit Salz und Pfeffer würzen.
1. *Optional*: alles mit Soyasoße, Fischsoße, etwas Reis-Essig, Sesamöl und Sesam abschmecken.
<file_sep>---
title: Eiweissreiche Brunch Pfannkuchen
date: 2015-05-03
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/eiweissreiche-brunch-pfannkuchen
---

## Zutaten
### Pfannkuchen (ca. 6 Stück)
- 4 Eier
- 250 g Hüttenkäse (körniger Frischkäse)
- 2 EL Flohsamenschalen
- 1 EL Kokoszucker
- 1 TL gemahlener Kardamom
- Abrieb von 1 Zitronenschale
- Kokosöl oder Butter zum Braten
### Beerenmousse
- 50 g Himbeeren oder andere dunkle Beeren
- ½ TL Vanillepulver
- 200 g Sahne
- etwas Süßstoff nach Bedarf
## Zubereitung
Für die Beerenmousse die Beeren zusammen mit der Vanille in einem kleinen Topf kurz aufkochen so dass die Beeren weich werden und wieder abkühlen lassen. Die Sahne steif schlagen und die Beerenmasse unterheben.
Für die Pfannkuchen Eier und Hüttenkäse mit einem Pürierstab durchmixen, bis sich die Brocken des Hüttenkäses aufgelöst haben. Die anderen Zutaten hinzufügen und nochmal durchmischen.
Butter oder Kokosöl in einer beschichteten Pfanne erhitzen und aus der Masse nacheinander Pfannkuchen braten. Immer mal wieder mit Butter oder dem Öl nachfetten. Mit dem Wenden warten, bis die Pfannkuchen eine gute Konsistenz erreicht haben, was je nach Dicke etwas dauern kann.
<file_sep>---
title: Nussmüsli
date: 2015-09-05
tags:
- lowcarb
- highfat
- simple
aliases:
- ../../snacks-und-shakes/nussmüsli
---
## Zutaten
- 200 g gemischte Nüsse (z.b. *Clarky's feinste Nussvariationen*)
- 100 g Mandeln, gestiftet
- 100 g Mandeln, blanchiert
- 30 g Kokosraspel
- 2 EL (28g) Leinsamen
- 50 g Sonnenblumenkerne
- 2 EL Kokosblütenzucker
## Zubereitung
Backofen auf 100 ℃ vorheizen, Nüsse grob hacken und alle Zutaten bis Sonnenblumenkerne auf einem Backblech mit Backpapier ausbreiten. Das Müsli ca 30 Minuten backen, ab und zu umrühren. Dann den Kokosblütenzucker, Vanillepulver und Zimt hinzufügen und in ein Einweckglas füllen.
Dazu passen gut griechischer Jogurt und Waldbeeren.
<file_sep>## Motivation
Why yet another recipe collection? There are already like a bazillion recipe sites and all sorts of online services and apps that let you manage your favorite recipes.
I want recipes without ads, without push notifications, without registration, without newsletter sign-up pop-ups, and all that other annoying stuff.
Also, most popular recipe blogs always have to tell you their whole life story before they can finally get to the point – present a "simple" recipe.
I just wanted recipes as a collection of simple step-by-step instructions in plain Markdown which can be easily searched and edited, garnished with a bit of metadata and just a touch of additional content pointing out specifics and variations.
## Installation
This repo is pretty self-contained, you only need `make`, `git`, `wget`, and `tar` which should be available for every Linux distribution. The targets `make serve` and `make test` will download the necessary dependencies for basic functionality.
## Usage
1. Edit your recipes in the fitting category in `content/`
2. Run `make serve` to take a look at the rendered result at <http://localhost:1313/>
3. Add newly created files with `git add`
4. Ship it with `make publish` and `git commit`
## Images
Images for recipes should be placed in `static/img`. For converting an image from JPG to the modern WebP format, place it in `assets/${imagename}` and run the make target `static/img/${imagename}.webp`.
You will need to have [`exiftran`](https://www.kraxel.org/blog/linux/fbida/) and [`cwebp`](https://developers.google.com/speed/webp/docs/precompiled) installed for this to work.
## Contributing
If you find bugs or have suggestions for improvement, feel free to submit an [issue](https://github.com/skoenig/einfachsatt/issues/new). The [UNLICENSE](LICENSE.txt) applies.
<file_sep>---
title: Pute Milano
date: 2018-05-22
tags:
- lowcarb
aliases:
- ../../hauptgerichte/pute-milano
---

## Zutaten für 2 Portionen
- 2 Putenschnitzel
- 1 Zwiebel
- 3 Zehen Knoblauch
- 1 große Zucchini
- 4 große Tomaten
- 250 g Champignons
- 125 g Schinkenwürfel
- 1 Becher Sahne
- Salz, Pfeffer, Oregano
- evtl. etwas Instant-Gemüsebrühe
## Zubereitung
Zwiebel und Knoblauchzehen abziehen, hacken, in eine Pfanne geben und in etwas Öl anbraten.
Die Putenschnitzel von beiden Seiten mit Salz, Pfeffer und Oregano würzen, mit in die Pfanne geben und von jeder Seite 2 min. anbraten. Die Schnitzel mit den Zwiebeln und dem Knoblauch ohne Bratsud aus der Pfanne nehmen und beiseite stellen.
Zucchini, Tomaten und Champignons in nicht zu kleine Stücke schneiden und in die Pfanne geben. Schinkenwürfel in die Pfanne geben und mit dem Gemüse kurz anschmoren. Sahne dazugeben und mit etwas Gemüsebrühe abschmecken.
Die Schnitzel mit den Zwiebeln in die Pfanne geben und unter das Gemüse heben. Hitze reduzieren und köcheln lassen, bis die Schnitzel durch sind.
<file_sep>---
title: Chinakohl Hackpfanne
date: 2020-03-15
lastmod: 2022-10-17
cookTime: PT35M
aliases:
- ../../hauptgerichte/chinakohl-hackpfanne
---

## Zutaten für 2 Portionen
- 125 g Langkornreis
- 2 große Karotten
- ½ Chinakohl
- 250 g Hackfleisch
- 150 ml Gemüsebrühe
- 3 Esslöffel Cashewkerne
- Salz & Pfeffer
- Currypaste
- Chilipulver
- etwas Schmand
- Öl für die Pfanne
## Zubereitung
1. Den Reis im kochenden Salzwasser garen.
1. Karotten schälen und in dünne Scheiben schneiden, den Chinakohl in Streifen schneiden.
1. In einer großen Pfanne oder Wok etwas Öl erhitzen und darin das Hackfleisch anbraten, mit Salz und Pfeffer würzen.
1. Die Karotten zugeben mit anbraten.
1. Den Chinakohl hinzugeben und mit Gemüsebrühe ablöschen und alles bei mittlerer Hitze köcheln lassen bis die Flüssigkeit fast verdampft ist.
1. Zum Schluss noch den abgetropften Reis, Cashewkerne, Currypaste und das Chilipulver zugeben und mit Salz und Pfeffer abschmecken.
1. Auf einem Teller anrichten und den Schmand dazu reichen.
<file_sep>---
title: Hähnchen in Tomatensauce mit Mascarpone
date: 2016-03-23
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/hähnchen-in-tomatensauce-mit-mascarpone
---

## Zutaten für 4 Portionen
- 600 g Hähnchenbrustfilet
- etwas Butter
- 2 große Zwiebeln
- 4 Knoblauchzehen
- 1 rote Chilischote
- 2 Dosen gehackte Tomaten a 400 g
- 2 EL konzentriertes Tomatenmark
- 1 Handvoll Basilikumblätter
- ¾ Bund frischer Thymian
- 1 EL getrockneter Rosmarin
- 1 EL kokosblütenzucker
- 250 g Mascarpone
- Salz & Pfeffer
- Kokosöl
## Zubereitung
Die Zwiebeln und Knoblauchzehen schälen und in kleine Würfel schneiden. Die Chilischote ebenfalls kleinhacken.
Den Backofen auf 200 Grad vorheizen. Eine feuerfeste Form mit Butter einfetten. Die Hähnchenbrustfilets abspülen, trocken tupfen und in mundgerechte Stücke schneiden. In die Form legen und einige Butterflöckchen darauf verteilen. Im Backofen etwa 20 Minuten backen.
Für die Tomatensoße in einen Topf Kokosöl zu lassen und zwiebeln, Knoblauch und Chili Schote bei mittlerer Temperatur beraten, bis die Zwiebeln glasig sind. Die gehackten Tomaten und das TomatenMark zufügen. Basilikum und thymian waschen, trockenschütteln und fein hacken. Einige gehackte Basilikumblätter beiseite legen. Rosmarin und kokoszucker in die Sauce geben.
Die soße eine weile zugedeckt köcheln lassen, dann die mascarpone darunterrühren, bis die Sauce eine cremige konsistenz hat. Die fertig gebratene Hähnchenbrustfilets hinzufügen und alles noch einmal aufkochen. Mit Salz und Pfeffer abschmecken.
Auf einer Platte anrichten mit Basilikumblättern bestreuen und eventuell [Blumenkohlreis]({{< relref "Blumenkohlreis" >}}) dazu reichen.
## Nährwerte pro Portion
- kcal: 581
- KH: 17g
- Fett: 36g
- EW: 43g
<file_sep>---
title: Lachssalat
date: 2020-09-04
tags:
- lowcarb
- highfat
aliases:
- ../../salate/lachssalat
---

## Zutaten für 2 Portionen
- 2 EL Mayonnaise
- 2 EL Creme fraiche
- etwas Meerrettich
- 1 EL Zitronensaft
- 200g Räucherlachs
- ¼ Spitzkohl
- 2 Stangen Sellerie
- ½ Apfel
- ½ <NAME>el
- 1 Stängel Dill
- 3 EL Olivenöl
- 3 TL Apfelessig
- Salz & Pfeffer
## Zubereitung
1. Mayonnaise, Creme fraiche, Meerrettich und Zitronensaft in einer Schüssel verrühren. Den Lachs in Würfel schneiden und unter die Masse heben, mit Salz und Pfeffer abschmecken.
2. Den Strunk und die äußeren Blätter vom Spitzkohl entfernen und in feine Streifen schneiden.
3. Sellerie und Apfel waschen, entkernen und in Scheiben schneiden. Die Zwiebel ebenfalls in Scheiben schneiden. Alles zusammen mit dem Dill in eine Schüssel geben.
4. Zusammen mit dem Lachssalat anrichten.
5. Aus dem Öl, Essig, Salz und Pfeffer ein Dressing mischen und über den Salat geben.
<file_sep>---
title: Khlav Kalash
date: 2016-03-03
tags:
- lowcarb
aliases:
- ../../hauptgerichte/khlav-kalash
---


## Zutaten für 2 Portionen
- 3 rote Zwiebeln
- 4 Knoblauchzehen
- 4 kleine Tomaten (120 g)
- 500 g Rinderhack (gemischtes Hack geht auch)
- 3 EL Guarkernmehl / Reismehl / Johannisbrotkernmehl
- 2 Eigelb
- 2 EL gehackte Petersilie
- Chilipulver
- Salz & Pfeffer
## Zubereitung
Die Zwiebeln und den Knoblauch pellen und sehr fein hacken. Die Tomaten waschen und sehr klein schneiden - ich würde sie allerdings gleich mir dem Mixer oder der Küchenmaschine zerkleinern. Alles zusammen mit dem Hackfleisch, dem Mehl und Eigelb in eine Schüssel geben.
Anschließend alle anderen Gewürze hinzugeben und die Masse kräftig durchkneten, so dass sich alles schön verteilt und eine sämige Masse entsteht. Nach dem Durchkneten alles nochmal abschmecken und gegebenenfalls nachwürzen.
Die Masse zu kleinen „Zigarren“, 12 bis 14 cm lang, 3 bis 4 cm Durchmesser, formen und anschließend auf Schaschlikspieße stecken.
Die Khlav Kalash auf dem Grill oder in der Pfanne garen, bis sie schön durch sind und mit einer Dose Krabbensaft servieren!
## Nährwerte pro Portion
- kca: 689
- KH: 10g
- Fett: 48g
- EW: 55g
<file_sep>---
title: Auberginenrollen mit Walnussfarce
date: 2015-10-18
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/auberginenrollen-mit-walnussfarce
---

## Zutaten für 4 Portionen
- 2-3 große Auberginen
- Salz
- Olivenöl
- 100g Pistazien, ungesalzen
- 2 Frühlingszwiebeln
- 1EL Kapern
- 75g Feta
- 400g gestückelte Tomaten
- 300g [Walnussfarce]({{< relref "Walnussfarce" >}})
## Zubereitung
Die Auberginen waschen, abtrocknen und längs in dünne Scheiben schneiden. Ein Blech mit Backpapier auslegen, die Auberginen darauflegen und mit reichlich Salz bestreuen und etwa 1 Stunde liegen lassen.
Inzwischen die Walnussfarce zubereiten, die Pistazien und Frühlingszwiebeln hacken. Dann die Walnussfarce mit der Hälfte von den Pistazien, den Frühlingszwiebeln und den Kapern vermischen.
Den Backofen auf 225℃ vorheizen. Die Auberginen noch einmal abspülen und abtrocknen. Mit Olivenöl bestreichen und auf der obersten Schiene im Backofen grillen, bis sie goldbraun sind. Dann die Temperatur auf 170℃ senken.
Auf jede Auberginenscheibe einen Esslöffel von der Walnussfarce geben und die Scheiben zusammenrollen und in eine eingefettete feuerfeste Form legen. Die gestückelten Tomaten darübergeben und zum Schluss den Feta darüberstreuen. Etwa 20 Minuten im Backofen backen.
Zum Servieren die restlichen Pistazien über das Gericht streuen.
## Nährwerte pro Portion
- kcal: 673
- KH: 24 g
- Fett: 56 g
- EW: 13 g
<file_sep>---
title: Eiersalat mit Avocado und Curry
date: 2016-02-17
tags:
- lowcarb
- highfat
- veggie
aliases:
- ../../salate/eiersalat-mit-avocado-und-curry
---

## Zutaten für 2 Portionen
- 4 EL Mayonnaise
- 1 EL Curry
- Salz
- 5 Eier
- 1 Avocado
- Kresse
## Zubereitung
Die Eier hart kochen. Währendessen Mayonnaise, Curry und etwas Salz in einer Schüssel verrühren. Die Eier abschrecken, schälen und in Würfel schneiden. Die Avocado ebenfalls entkernen, schälen und zu kleinen Würfeln verarbeiten. Die Avocado, die Eier und das Dressing vermischen. Frisch geschnittene Kresse darüberstreuen.
<file_sep>---
title: Chili Garnelen auf Quinoa Salat
date: '2022-03-22'
fat: 84
servings: 4
calories: 2040
carbohydrate: 184
protein: 116
cookTime: PT25M
tags:
- protein
aliases:
- ../../salate/chili-garnelen-auf-quinoa-salat
---
## Zutaten
- 2 Limetten
- 3 ELs Olivenöl
- 0.5 TLs Salz
- 100 ml Gemüsebrühe
- 100 g Kirschtomaten
- 1 Bund Petersilie
- 200 g Quinoa
- 400 g Garnelen
- 200 ml kochendem Wasser
- 1 Bund Lauchzwiebeln
- 0.5 Gurke
## Zubereitung
1. Quinoa mit Salz mischen und mit kochendem Wasser übergießen und zugedeckt quellen lassen.
[Quinoa: 200 g; Salz: 0.5 TLs; kochendem Wasser: 200 ml]
2. Limetten halbieren und Saft auspressen. Limettensaft mit Gemüsebrühe und Olivenöl verquirlen. Das Dressing mit Salz, Pfeffer und ein paar Chiliflocken abschmecken.
[Gemüsebrühe: 100 ml; Limetten: 2; Olivenöl: 3 ELs]
3. Kirschtomaten waschen und halbieren. Lauchzwiebeln putzen, waschen, in feine Ringe schneiden. Petersilie waschen und trocken schütteln. Die Petersilienblättchen von den Stielen zupfen und hacken. Gurke waschen und würfeln. Salat waschen und gut trocken schütteln.
[Gurke: 0.5; Kirschtomaten: 100 g; Lauchzwiebeln: 1 Bund; Petersilie: 1 Bund]
4. Garnelen abspülen und trocken tupfen. Olivenöl{1%EL} in einer Pfanne erhitzen und die Garnelen darin 4 Minuten braten. Mit Salz und etwas Chili würzen.
[Garnelen: 400 g]
5. Quinoa, Tomaten, Gurke, Salat und Lauchzwiebelringe mit dem Dressing vermengen. Garnelen darauf anrichten. Mit den Mandelstiften und der Petersilie bestreuen.
[–]
<file_sep>---
title: Raita
date: 2017-02-21
tags:
- lowcarb
- highfat
aliases:
- ../../beilagen/raita
---

## Zutaten für 4 Portionen
- 300g griechischer Jogurt
- 1 Knoblauchzehe
- ½ Chilischote
- 4-5 Minzeblätter
- 2 TL gemahlener Kreuzkümmel
- 1 EL Koriander
- ¼ Gurke
- 1 Tomate
- etwas Salz
## Zubereitung
Knoblauchzehe schälen und zusammen mit der Chilischote und der Minze kleinhacken, und zusammen mit dem Jogurt und den übrigen Gewürzen in einer Schüssel verrühren. Tomate und Gurke in kleine Würfel schneiden und ebenfalls unter den Jogurt rühren.
Etwa eine Stunde kalt stellen und ziehen lassen.
<file_sep>---
title: Salade Verte
date: 2016-01-10
lastmod: 2022-12-18
tags:
- lowcarb
- veggie
- paleo
aliases:
- ../../salate/salade-verte
---
## Zutaten für 4 Portionen




### Für den Salat
- 300 g Blattspinat
- 150 g Feldsalat
- 2 grüne Paprikaschoten
### Dressing
- 100 ml Olivenöl
- 50 ml Wasser
- 10 Mandeln (gestiftet oder gehobelt)
- ½ Knoblauchzehe
- 12 <NAME>
- 6 Stengel breitblättrige Petersilie
- 6 Stengel Minze
- 10 g Ingwer
- Saft und Schale von 1 Limette
- 1 TL Salz
- 1 TL Zucker
## Zubereitung
1. Spinat und Salat abspülen und gut abtropfen lassen.
2. Die grünen Paprikaschoten entkernen, in dünne Stäbchen schneiden und zum Salat geben.
3. Die Zutaten für das Dressing mit einem Pürierstab vermengen und unterheben.
Passt sehr gut zu Pulled Turkey.
<file_sep>---
title: <NAME>
date: 2017-03-06
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/scharfe-thaisuppe
---


## Zutaten für 4 Portionen
- 3 große Karotten
- 3 Paprika
- 1 Brokkoli
- 1 Zwiebel
- 4 Knoblauchzehen
- 1 EL gelbe Currypaste
- 30g frischer Ingwer
- 2 Stangen Zitronengras
- 2 rote Chilischoten
- 1 l Gemüsebrühe
- 2 Dosen Kokosmilch (á 400 ml)
- 200 ml trockener Weißwein
- 3 EL Fischsauce
- 1 Limette
- 1 Prise Kurkuma oder Safran
- Kokosöl zum Braten
## Zubereitung
Karotten, Paprika und Brokkoli waschen, Zwiebel schälen und dann alles kleinschneiden (muss nicht schön ausehen, später wird alles püriert). Den Ingwer und die Knoblauchzehen schälen und kleinhacken.
Kokosöl in einem großen Topf erhizten und Knoblauch, Zwiebel, Ingwer, Karotten und Currypaste hineingeben und anschwitzen lassen, bis die Karotten weich sind. Paprika, Brokkoli, Zitronengras, Chili, Brühe, Kokosmilch, Weißwein, Fischsauce und Limettensaft hinzugeben. Kurkuma oder Safran hinzugeben. Alles zusammen mit Deckel ca. 25 Minuten bei mittlerer Hitze köcheln lassen.
Danach etwas von der Flüssigkeit abgießen und beiseite stellen. Die restlichen Zutaten mit dem Pürierstab zu einer gleichmäßig cremigen Masse zerkleinern. Die Suppe noch mal aufkochen lassen. Falls sie zu dickflüssig geworden ist, wieder etwas von der abgegossenen Flüssigkeit hinzugeben.
<file_sep>---
title: Sojabohnen rot gelb grün
date: 2014-03-02
tags:
- lowcarb
- vegan
aliases:
- ../../hauptgerichte/sojabohnen-rot-gelb-grün
---
## Zutaten

- 1 Tasse Sojabohnen
- Olivenöl
- 2 kleine Zwiebel(n), gewürfelt
- 2 Lorbeerblatt
- Paprikapulver, rosenscharf
- 6 Paprikaschote(n), rot, gewürfelt
- 1 Tasse Maiskörner
- 1 Tasse Erbsen
- Salz
- 1 Handvoll Kräuter, frische (z. B. Basilikum, Petersilie, Schnittlauch)
- Rosmarin, getrocknet
- Koriander
- Kümmel
- Thymian, getrocknet
- Oregano, getrocknet
- Majoran, getrocknet
- Basilikum, getrocknet
## Zubereitung
Die Sojabohnen mit der dreifachen Menge Wasser über Nacht (8 Stunden) quellen lassen. Bohnen und Wasser in einem hohen Kochtopf zwei Stunden bei geringer Hitze kochen.
Zwiebel, Lorbeerblatt und Gewürze kurz anbraten, Paprika hinzufügen, Mais und Erbsen erst nach 3 bis 5 Minuten beigeben. Die abgetropften Sojabohnen unterrühren. Salzen, nachwürzen und mit den frischen Kräutern und einem Spritzer Zitronensaft abschmecken.
<file_sep>---
title: Gemüseauflauf mit Feta und Schmand
date: 2015-04-25
tags:
- veggie
- lowcarb
aliases:
- ../../hauptgerichte/gemüseauflauf-mit-feta-und-schmand
---
## Zutaten
- 1 Zwiebel
- 2 Tomaten
- 1 große Karotte
- 1 kleine Zucchini
- 1 Paprikaschote
- Salz & Pfeffer
- Oregano
- Basilikum
- 2 EL Tomatenmark
- 300 g Feta-Käse
- 210 g Schmand
- etwas Öl für die Form
## Zubereitung
Die Zwiebel schälen und möglichst klein schneiden. Tomaten, Karotte, Zucchini, Paprika waschen bzw. putzen und in kleine Würfel schneiden. Alles in eine Schüssel geben und gut miteinander mischen. Mit Salz, Pfeffer und den anderen Gewürzen abschmecken. Eventuell entstehende Flüssigkeit abschütten. Tomatenmark zugeben und nochmals gut durchmischen.
Eine Auflaufform mit etwas Öl einreiben und das Gemüse hinein geben. Den Feta-Käse in kleine Würfel schneiden und gut mit Schmand vermischen. Über das Gemüse geben, so dass ein gleichmäßiger Belag entsteht
Im vorgeheizten Backofen bei 200°C ca. 30 Min. backen – der Käse sollte leicht goldbraun werden. Heiß servieren.
<file_sep>---
title: Harzer Käse Snack
date: 2017-12-18
tags:
- lowcarb
aliases:
- ../../snacks-und-shakes/harzer-käse-snack
---
## Zutaten
- 50g Schinken
- 200g (1 Rolle) <NAME>se ohne Kümmel
- 2 Eier
- 50g Tomatensauce
- Salz, Pfeffer, Paprika, Knoblauch, Zwiebeln nach Belieben
## Zubereitung
Schinken und <NAME>se in Würfel schneiden.
Schinken und evtl. die Zwiebeln in einer Pfanne anbraten und den Harzer, das Ei, die Tomatensauce und die Gewürze in einer Schüssel verrühren.
Die restlichen Zutaten zu dem Schinken in die Pfanne geben und kurz durchschwenken.
Das sieht nicht wirklich gut aus, aber schnell gemacht und für den kleinen Hunger.
## Nährwerte pro Portion
- kcal: 430
- KH: 3g
- Fett: 12g
- EW: 88g
<file_sep>---
title: Hackfleisch Brokkoli Auflauf
date: 2019-11-13
tags:
- lowcarb
aliases:
- ../../hauptgerichte/hackfleisch-brokkoli-auflauf
---
## Zutaten für 4 Portionen
- 500 g Hackfleisch
- 1000 g Brokkoli
- 1 Becher Sahne
- 1 Becher Schmand
- 2 Eier
- 250 g Käse, geriebenen
- Salz und Pfeffer
## Zubereitung
Das Hackfleisch anbraten. Den Brokkoli in Röschen teilen und in Salzwasser kurz kochen lassen (er sollte noch Biss haben).
In eine gefettete Auflaufform das Hackfleisch und den Brokkoli einschichten.
Die Sahne mit Schmand, den Eiern, dem Käse, Salz und Pfeffer verrühren und eventuell noch Kräuter oder Schinkenwürfel hinzufügen. Diese Soße dann über das Hackfleisch und den Brokkoli gießen.
Bei 180°C Umluft 30 Minuten überbacken. Für die ersten 20 Minuten den Auflauf mit Alufolie abdecken!
<file_sep>---
title: Quinoa mit Tomaten Spinat Paprika Pfanne
date: 2020-12-19
tags:
- lowcarb
- simple
aliases:
- ../../hauptgerichte/quinoa-mit-tomaten-spinat-paprika-pfanne
---
## Zutaten für 2 Portionen
- 1 Tasse Quinoa
- 1 Zehe Knoblauch
- 1 kleine Zwiebel
- 1 TL Kreuzkümmel
- ½ TL Paprikapulver, rosenscharf
- etwas Chilipulver
- 1 rote Paprikaschote
- 8 Datteltomaten
- 300 g Blattspinat
- 2 EL Sesampaste (Tahin)
- Salz & Pfeffer
- Öl für die Pfanne
## Zubereitung
1. Die Quinoa nach Packungsanweisung zubereiten.
1. Den Knoblauch und die Zwiebel fein hacken, und bei mittlerer Hitze in einer Pfanne mit Öl anbraten.
1. Kreuzkümmel, Paprikapulver und Chilipulver hinzugeben.
1. Paprika waschen, entkernen, in Würfel schneiden und mit in die Pfanne geben. Ca. 3 Minuten mitbraten.
1. Den Spinat waschen, die Tomaten waschen und vierteln und ebenfalls in die Pfanne geben.
1. So lange braten, bis der Saft der Tomaten alles zu einer leicht sämigen Masse werden lässt.
1. Dann die Temperatur senken, nochmals mit Salz und Pfeffer abschmecken.
1. Zusammen mit dem Quinoa anrichten.
<file_sep>---
title: Gebratenes Fischfilet mit Stangensellerie
date: 2017-02-14
lastmod: 2023-05-23 16:43:31
tags:
- lowcarb
aliases:
- ../../hauptgerichte/gebratenes-fischfilet-mit-stangensellerie
---
Das hier ist ein einfaches Gericht für Fischfiletes mit Strangensellerie (Pad Plah Keun Chai) - dazu passt [Blumenkohlreis]({{< relref "Blumenkohlreis" >}}) sehr gut.

## Zutaten für 2 Portionen
- 2 Stängel Sellerie
- 3 EL Öl, (Erdnuss- oder Sojaöl)
- 250 g Fischfilets: Rotbarsch, Wels, Kabeljau oder Seelachs
- 1 Knoblauchzehe
- 2 EL Austernsauce
- 2 EL Fischsauce
- 2 EL Wasser
- 1 TL Kokosblütenzucker
- 2 Stängel Frühlingszwiebeln
- 1 rote Chilischote oder getrocknete Chilisamen
- etwas Pfeffer
## Zubereitung
1. Den Sellerie abwaschen, die Blätter abzupfen, grob hacken und beiseite stellen, die Stangen in Ringe schneiden.
1. Die Chilischote und Frühlingszwiebeln in Ringe schneiden und zu den Sellerieblättern geben.
1. Das Öl in einem Wok erhitzen und den Fisch in breitere Streifen schneiden.
1. Den Fisch von beiden Seiten im Wok ca. 5 Min. bei mittlerer Hitze braten. Dabei immer mal wieder den Wok leicht schwenken und den Fisch einmal vorsichtig wenden. Dann die Fischstücke herausnehmen und schon mal auf Tellern anrichten.
1. Inzwischen Austernsauce, Fischsauce, Kokosblütenzucker und Wasser vermischen.
1. Die Knoblauchzehe pellen, kleinhacken, und bei großer Hitze den Knoblauch in dem restlichen Öl frittieren.
1. Den Sellerie hinzugeben und ca. 30 Sekunden im Wok schwenken. Dann mit der Sauce ablöschen und über dem Fisch verteilen.
1. Die grob gehackten Sellerieblätter, Chili und Frühlingszwiebeln auf den Tellern verteilen und eventuell mit Pfeffer nachwürzen.
<file_sep>---
title: Gefüllte Paprika mit Hackfleisch und Gemüse
date: 2015-03-15
tags:
- lowcarb
aliases:
- ../../hauptgerichte/gefüllte-paprika-mit-hackfleisch-und-gemüse
---
## Zutaten für 4 Portionen
- 2 große Zwiebeln
- 4 große Paprikaschoten, rote oder gelbe
- 260 g Karotten
- 1 Stange Lauch (Poree)
- 1 Stange Staudensellerie
- 450 g Brokkoli
- 500 g Hackfleisch, gemischt
- 200 g Käse, Gouda gerieben
- 300 ml Gemüsebrühe
- 2 EL Butter
- 1 TL Paprikapulver
- Salz und Pfeffer
## Zubereitung
Zwiebeln schälen und eine würfeln, die andere in Scheiben schneiden.
Karotten schälen, Lauch und Sellerie putzen und alles in dünne Scheiben schneiden. Den Brokkoli in Röschen teilen und waschen.
Butter in einem Topf erhitzen und die Zwiebeln darin glasig dünsten. Karotten, Lauch und den Sellerie dazugeben, das Ganze 3 Minuten mit dünsten.
Anschließend den Brokkoli und 2/3 der Brühe zufügen und weitere 3 Minuten ziehen lassen. Gemüse mit Salz, Pfeffer und Zucker abschmecken!
Ofen auf 175°C vorheizen und Aufflaufform fetten.
Paprika aufschneiden, Kerne entfernen und waschen, trocken tupfen und salzen und pfeffern.
Das Hackfleisch in heißem Öl krümelig Braten und mit mit Salz, Pfeffer und Paprika würzen.
Mit dem Käse wird das Hackfleisch nun vermischt und in die Paprika gefüllt. Die gefüllten Paprika werden auf das Gemüsebett in die Auflaufform gelegt und mit der restlichen Brühe angegossen
Das Ganze nun bei 175°C ca 25-30 Minuten schmoren lassen.
Der Paprika ist noch schön fest und die Füllung sehr lecker!
<file_sep>---
title: Bullet Proof Coffee Extended
date: 2015-05-21
tags:
- lowcarb
- highfat
aliases:
- ../../snacks-und-shakes/bullet-proof-coffee-extended
---
## Zutaten
- 250 ml Kaffee
- 1 Ei
- 1 TL Kokosöl
- 1 TL Butter
- ½ TL gemahlener Zimt
- 1 Msp. Vanillepulver
- evtl. etwas Kokosblütenzucker
## Zubereitung
Eine Tasse (250 ml) Kaffee auf die restlichen Zutaten gießen und mit einem Pürierstab mixen bis ein cremiges Getränk entsteht.
In einem Glas servieren.
<file_sep>---
title: Kartoffel Wedges
date: 2019-03-19
tags:
- veggie
aliases:
- ../../beilagen/kartoffel-wedges
---
## Zutaten
für ein Ofenblech Kartoffeln:
- ~ 1,5 kg Kartoffeln
für die Gewürzmischung:
- 4 TL Öliven- oder Rapsöl
- 1 TL Pizzagewürz
- 1 TL <NAME>
- 1 TL Senf
- Pfeffer
- Salz
- Oregano
- Koriander
- Knoblauchsalz
## Zubereitung
Kartoffeln waschen und in Rechtecke oder Spalten schneiden. Schale natürlich dranlassen (enthält die meisten Vitamine). Gewürzmischung anrühren und soviel Öl dazugeben, das sie die Viskosität von Pesto hat, vielleicht etwas flüssiger. Schön gleichmäßig über die Kartoffelspalten verteilen. Zu Schluß etwas Salz über die rohen Kartoffeln streuen und im Ofen bei 200 °C (Umluft 180 ℃ ) ca. 20-25 Minuten bis sie schön knusprig sind.
<file_sep>---
title: Gemischter Gemüsesalat mit Hähnchenbruststreifen
date: 2015-09-23
tags:
- lowcarb
aliases:
- ../../salate/gemischter-gemüsesalat-mit-hähnchenbruststreifen
---
## Zutaten für 2 Portionen
- 90 g Tomaten
- 300 g Eisbergsalat
- ½ Gurke
- 90 g weiße Champignons
- 3 Eier
- 250 g Hähnchenfleisch (am besten TK, das ist schon mariniert)
- 100 g Feta-Käse
- Olivenöl
- Kräuter, (z. B. Kräuterlinge)
- Currypulver
- Paprikapulver, edelsüß
- Chiliflocken
- Sonnenblumenkerne
- Salz und Pfeffer
## Zubereitung
Das Hähnchenfleisch auftauen und in kleine Würfel schneiden.
Olivenöl in einer beschichteten Pfanne erhitzen, das Fleisch darin braten und mit Salz, Pfeffer, edelsüßem Paprika, Curry und Chiliflocken würzen. Die Eier hart kochen.
Währenddessen das Gemüse, die Champignons und den Feta in mundgerechte Stücke schneiden und in einer Schüssel leicht mit Kräutern würzen. Ich nehme dazu immer Knorr Kräuterling "Italienische Kräuter" zum Streuen. Die Eier abschrecken, in Würfel schneiden und zum Salat geben. Das gebratene Hähnchenfleisch heiß mit dem Bratfett (super Geschmack und erspart das Dressing!) zum Salat geben, dann wird der Salat leicht lauwarm. Mit Salz und Pfeffer abschmecken und mit Sonnenblumenkernen bestreut servieren.
## Nährwerte pro Portion
- kcal: 750
- KH: 14 g
- Fett: 40 g
- EW: 88 g
<file_sep>---
title: Rote Linsen Salat mit Tomaten
date: 2014-02-23
tags:
- veggie
- vegan
aliases:
- ../../salate/rote-linsen-salat-mit-tomaten
---
## Zutaten

- 150 g Linsen, rote
- 500 ml Gemüsebrühe
- 100 g Feldsalat
- 1 Knoblauchzehe
- 6 EL Olivenöl
- 2 EL Essig
- 1 kleine Zwiebel(n)
- 10 kleine Cherrytomaten
- n. B. Kräuter, Petersilie
- Salz und Pfeffer
## Zubereitung
Die Linsen über nacht einweichen lassen und dann in der Gemüsebrühe nur ca. 10 Minuten kochen, damit sie noch Biss haben.
Währenddessen die Zwiebel fein würfeln, den Feldsalat waschen, die Tomaten in Stücke schneiden und den Knoblauch schälen und klein hacken. Knoblauch, Olivenöl, Essig, Salz und Pfeffer zu einem Dressing verrühren.
Die Linsen abgießen (nicht unbedingt abspülen) und mit den Zwiebeln, Feldsalat, Tomaten vermengen und das Dressing darüber geben.
<file_sep>---
title: Teufelseier mit Thunfischfüllung
date: 2015-04-29
tags:
- lowcarb
- highfat
- simple
aliases:
- ../../snacks-und-shakes/teufelseier-mit-thunfischfüllung
---
Ideal als Partysnack oder Fingerfood, kann man auch [/snacks-und-shakes/Teufelseier-mit-Avocado] zubereiten.
## Zutaten für 3 Portionen
- 6 hart gekochte Eier
- 6 EL Thunfisch in eigenem Saft
- 3 EL Mayonnaise
- Salz & Pfeffer
## Zubereitung
1. Eier schälen und halbieren, dass Eigelb in eine separate Schüssel geben
2. Die Mayonnaise und den Thunfisch mit in die Schüssel geben, vermengen.
3. Mit Salz und Pfeffer abschmecken. Es können auch noch Kräuter untergemischt werden.
4. Dann die Masse wieder in die Eihälften als Füllung geben.
<file_sep>---
title: Thunfisch griechische Art
date: 2016-01-12
tags:
- lowcarb
aliases:
- ../../hauptgerichte/thunfisch-griechische-art
---
## Zutaten
- 1 Dose Thunfisch in Wasser
- 2 EL Olivenöl
- Thymian
## Zubereitung
Den Saft vom Thunfisch abgießen. Das Öl in einer Pfanne leicht erhitzen und den Thunfisch dazugeben. Ordentlich mit Thymian würzen. Nur So lange erhitzen, bis das Öl leicht anfängt zu köcheln, dann sofort aus der Pfanne nehmen.
Dazu passt natürlich [griechischer Salat]({{< relref "Griechischer-Salat" >}}) sehr gut.
<file_sep>---
title: Zimtbrötchen
date: 2018-03-08
tags:
- lowcarb
- highfat
aliases:
- ../../beilagen/zimtbrötchen
---
## Zutaten für 14 Brötchen
- 8 Eier
- 2 EL Kokosblütenzucker
- 100g Butter
- 200g Sahne
- 100g Kokosraspel
- 6 EL Flohsamenschalen
- 2 TL Zimt
- 1 TL Kardamom
- 4 TL Backpulver
- 1 Ei zum Bestreichen
## Zubereitung
Die Butter schmelzen und zusammen mit der Sahne und den Eiern mit dem Kokosblütenzucker verrühren. Anschließend die trockenen Zutaten hinzufügen und alles gut verrühren, damit sich keine Klumpen bilden. Den Teig ca. 10 Minuten ruhen lassen.
Den Backofen auf 175 ℃ vorheizen. Ein Backblech mit Backpapier auslegen. Den Teig mit leicht angefeuchteten Händen vorsichtig zu Kugeln formen. Die Brötchen mit Ei bestreichen und für 20 Minuten im Backofen backen.
<file_sep>---
title: Zucchinigratin
date: 2018-08-16
tags:
- veggie
aliases:
- ../../hauptgerichte/zucchinigratin
---
## Zutaten
- 800 g Zucchini
- 1 Ei
- 2 EL Milch
- 500 g Quark (Sahnequark)
- 4 EL Tomatenmark
- 130 g Käse, gerieben
- 1 Bund Basilikum
- 1 Knoblauch, zerdrückt
- 3 EL Kürbiskerne, gehackt
- Salz & Pfeffer
- Muskat
## Zubereitung
Zucchini waschen, in dünne Scheiben schneiden. In Salzwasser ca. 1 Min. blanchieren, abtropfen und abkühlen lassen. Ei mit Milch, Quark und Tomatenmark verrühren, die Hälfte des Käses zugeben. Mit geschnittenen Basilikum, Pfeffer, Muskat und Knoblauch abschmecken. Die Hälfte der Zucchinischeiben schuppenartig in eine ausgefettete flache Backform schichten. Mit der Quark-Ei-Masse begießen und den Vorgang wiederholen. Mit restlichem Käse und grob gehackten Kürbiskernen bestreuen. Im vorgeheizten Backofen (E-Herd: 180°) 35 Min. überbacken.
<file_sep>---
title: Low Carb Snack
date: 2015-04-28
tags:
- lowcarb
aliases:
- ../../snacks-und-shakes/low-carb-snack
---
## Zutaten

- 3 EL Mandel(n), gemahlen
- 1 Eier
- 1 EL Butter, weich
- 1 TL Backpulver
- 1 Prise Salz
## Zubereitung
Alles zu einem Teig vermengen, die Masse auf einem kleinen Teller verteilen und für 2 Minuten in die Mikrowelle geben. Bei Bedarf mehr Mandeln verwenden oder auch andere gemahlene Nüsse verwenden, da die Masse relativ flüssig ist. Kann als Brotersatz bei Low Carb-Ernährung verwendet werden oder einfach als Snack zwischendurch. Ergibt eine gute, sattmachende Portion.
<file_sep>---
title: Indisches Curry
date: 2017-05-30
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/indisches-curry
---

## Zutaten für 4 Portionen
- 600g Lamm- oder Rinderhack
- 1 TL Ingwer
- 1 Knoblauchzehe
- 1 Zwiebel
- 1 EL Tomatenmark
- 1 EL Koriander
- 2 EL Zimt
- 2 TL Kardamom
- 2 TL Kurkuma
- 1½ TL Gewürznelken
- 2 TL Kreuzkümmel
- 200g Crème Fraîche
- Salz & Pfeffer
- Kokosöl zum Braten
- evtl. Kokosraspeln, geröstete Sonnenblumenkerne oder Erdnüsse als Topping
## Zubereitung
Den Ingwer kleinreiben oder ganz fein hacken, Zwiebel und Knoblauch schälen und kleinhacken.
Das Kokosöl in einem Topf erhitzen und das Hackfleisch darin anbraten. Ingwer, Zwiebel und Knoblauch unterrühren. Dann das Tomatenmark und alle Gewürze dazugeben.
Mit Crème Fraîche und 150 ml Wasser ablöschen und 20-30 Minuten bei mittlerer Hitze köcheln lassen. Mit Salz & Pfeffer abschmecken.
Dazu passt [Raita]({{< relref "Raita" >}}) und Naan-Brot sehr gut.
<file_sep>---
title: Low Carb Knäckebrot
date: 2016-02-21
tags:
- lowcarb
- highfat
- veggie
aliases:
- ../../beilagen/low-carb-knäckebrot
---

## Zutaten für 1 Blech
- 160g Leinsamen
- 120g Kürbiskerne
- 80g Sesam
- 80g Sonnenblumenkerne
- 2 Eier
- 2 TL Salz
## Zubereitung
Körner und Samen in eine Schüssel geben und vermischen. Die Eier in einer zweiten Schüssel verquirlen und mit den Körnern und Samen sowie Salz und 150ml kaltem Wasser verquirlen.
Alles gut umrühren und den Teig eine Stunde ruhen lassen. Der Teig wirkt zunächst noch sehr feucht, aber die Leinsamen saugen die Feutigkeit auf.
Den Backofen auf 125 ℃ vorheizen. Ein Backblech mit Backpapier auslegen. Anschließend den Teig gleichmäßig auf das Backpapier gießen und im Backofen 90 Minuten backen.
Das ergibt eine große, feste Platte, die man nach belieben in kleinere Stücke brechen kann.
## Nährwerte für 1 Blech
- kcal: 2635
- KH: 22g
- Fett: 215g
- EW: 133g
<file_sep>---
title: Rote Linsen Salat mit Radieschen
date: 2015-02-03
aliases:
- ../../salate/rote-linsen-salat-mit-radieschen
---
## Zutaten
- 90 g Linsen, rote
- 300 ml Gemüsebrühe
- 1 Bund Radieschen
- 1 Paprikaschote(n), rot
- 1 cm Ingwer
- Pfeffer, schwarzer aus der Mühle
- 2 Prisen Salz
- 1 Bund Schnittlauch
- 1 Orange(n)
- 1 TL Olivenöl
- evtl. Anis
## Zubereitung
Die roten Linsen zugedeckt in der Gemüsebrühe 10 - 12 Minuten köcheln lassen, abgießen und erkalten lassen. Paprika und Radieschen waschen, putzen und klein schneiden. Ingwer schälen und fein reiben.
Die Zutaten zu den Linsen geben und unterrühren. Den Schnittlauch in feine Röllchen schneiden und zum Salat geben. Die Orange auspressen und den Saft mit dem Öl über den Salat geben. Mit Salz und Pfeffer abschmecken. Wer mag, kann den Salat noch mit Anis abschmecken. Der Salat lässt sich gut vorbereiten.
<file_sep>---
title: Low Carb Cheesecake
date: 2020-09-21
tags:
- lowcarb
- protein
aliases:
- ../../desserts/low-carb-cheesecake
---

## Zutaten
- 1000g Quark
- 6 Eier
- 1 Prise Salz
- 20 ml flüssige Butter
- 100g Erythrit mit Stevia oder Xylit / Birkenzucker
- 4 EL Proteinpulver
- Mark einer Vanilleschote
- Abrieb von 1 Zitronenschale
## Zubereitung
1. Die Eier trennen, aus dem Eiweiß einen festen Schnee schlagen.
2. Die restlichen Zutaten in eine große Rührschüssel geben und gut verrühren
3. Danach den Ei-Schnee unterheben, in eine Springform geben und bei 160 Grad ca. eine Stunde im Backrohr backen.
4. Nun im Backofen auskühlen lassen – so fällt er nicht so sehr zusammen.
Den Kuchen am Besten warm servieren und mit aufgetauten TK-Waldbeeren garnieren
<file_sep>---
title: Thunfischsalat mit Tomate
date: 2016-12-31
tags:
- lowcarb
aliases:
- ../../salate/thunfischsalat-mit-tomate
---
## Zutaten
- 200 g körniger Frischkäse (Cottage Cheese)
- 3-4 Tomaten
- 150 g Thunfisch in eigenem Saft (eine Dose)
- etwas Olivenöl
- etwas Balsamico Essig
## Zubereitung
Alles in einer Schale vermischen.
## Nährwerte
- EW: 55g
- KH: 23g
- Fett: 11g
<file_sep>---
title: Salate
layout: index
order: date
reverse: true
---
<file_sep>---
title: Schellfisch mit Curry
date: 2016-02-24
aliases:
- ../../hauptgerichte/schellfisch-mit-curry
---

## Zutaten für 4 Portionen
- 600g Schellfisch
- 1 Zwiebel
- ½ Apfel
- 1 EL Currypulver
- 300g Sahne
- Salz & Pfeffer
- Butter oder Kokosöl zum Braten
## Zubereitung
Backofen auf 200 ℃ vorheizen und eine ofenfeste Form mit Backpapier auslegen. Die Fischfilets mit Wasser abspülen, trocken tupfen und mit Salz & Pfeffer würzen. In die Form legen und 20 Minuten im Backofen backen.
Für die Sauce die Zwiebel schälen und zusammen mit dem Apfel in kleine Würfel schneiden. Kokosöl in einem Topf zerlassen, und die Zwiebelwürfel, den Apfel und das Currypulver hinzugeben. Etwas anschwitzen lassen und dann die Sahne hinzufügen. Kurz aufkochen und dann köcheln lassen, bis die Sauce dicker geworden ist. Mit Salz & Pfeffer abschmecken und ab und zu umrühren.
Dazu passt [Blumenkohlreis]({{< relref "Blumenkohlreis" >}})
## Nährwerte pro Portion
- kcal: 455
- KH: 35g
- Fett: 30g
- EW: 26g
<file_sep>---
title: Proteinkekse
date: 2015-06-05
tags:
- lowcarb
- simple
- protein
aliases:
- ../../desserts/proteinkekse
---
## Zutaten
- 3 Eiklar
- 40 g Proteinpulver
- 250 g Speisequark 20% Fett
- etwas Süßstoff
## Zubereitung
Backofen auf 170 Grad vorheizen und ein Blech mit Backpapier auslegen. Alle Zutaten zusammenmischen, gut verrühren in 9 Klecksen auf dem Backpapier verteilen.
Das ganze dann für ca. 20 Minuten im Ofen backen lassen.
<file_sep>---
title: Apfel Quark Kuchen
date: 2020-06-20
tags:
- lowcarb
- veggie
aliases:
- ../../desserts/apfel-quark-kuchen
---


## Zutaten
- 200 g Magerquark
- 3 Äpfel
- 80 g Butter weich
- 100 g gemahlene Mandeln
- 3 Eier
- 1-3 EL Xylit / Birkenzucker
- 1 TL Backpulver
- 2 TL Zimt
- 0,5 Päckchen Vanillepuddingpulver
- gehobelte Mandeln für das Topping
## Zubereitung
1. Butter, Mehl, gemahlene Mandeln, Eier, Xylit, Backpulver und Zimt in eine Rührschüssel geben und zu einem cremigen Teig verrühren
1. den Teig in eine gefettete Springform geben
1. den Backofen auf 180°C vorheizen
1. inzwischen Äpfel waschen und entkernen, in einem Mixer zerkleinern, Magerquark und Puddingpulver hinzugeben und verrühren
1. anschließend die Apfel-Quark-Masse auf dem Teig verteilen, die gehobelten Mandeln darauf verteilen und für etwa 60 Minuten in den Ofen geben
<file_sep>---
title: Arabischer Kichererbsen Salat
date: 2021-05-26
tags:
- lowcarb
- schnell
- simple
- veggie
aliases:
- ../../salate/arabischer-kichererbsen-salat
---

## Zutaten für 2 Portionen
- 1 Dose Kichererbsen (400 g)
- 1 Gurke
- 2 Tomaten
- 1 rote Paprika
- 1 kleine rote Zwiebel
- 1 Bund glatte Petersilie
- 1/2 Bund Koriander
- 1 Bio-Zitrone
- 1 Zehe Knoblauch
- 1 TL Zucker oder Xylit / Birkenzucker
- Olivenöl
- Salz & Pfeffer
Optional:
- Schafskäse
- Griechischer Joghurt
## Zubereitung
1. Gurken, Tomaten und Paprika in ca. 2 cm große Stücke schneiden.
2. Die Zwiebel und die Kräuter fein hacken und alles zusammen in einer großen Schüssel mischen.
3. Von der Zitrone die Schale abreiben, dann auspressen.
4. 50ml Olivenöl mit Zitronenschale und 3 EL Zitronensaft und 1 TL Zucker mischen. Dann mit Salz und Pfeffer abschmecken.
5. Die Knoblauchzehe dazu pressen und alles gut vermischen und anschließend unter den Salat heben.
6. 2-3 EL Olivenöl in einer Pfanne heiß werden lassen.
7. Die Kichererbsen abtropfen lassen, salzen. Dann 2 – 3 Minuten im heißen Öl braten bis sie „springen“ und gleichmäßig gebräunt sind und anschließend unter den Salat heben.
E<NAME> auf den Kichererbsen dazu ist sehr lecker und auch Schafskäse im Salat ist der Hammer.
<file_sep>---
title: <NAME> mit Joghurt Dip
date: 2020-10-28
tags:
- simple
- veggie
aliases:
- ../../hauptgerichte/linsen-curry-mit-joghurt-dip
---
## Zutaten für 4 Portionen
- 250 g rote Linsen
- 1 Knoblauchzehe
- 1 Zwiebel
- 2 rote Paprika
- 2 Karotten
- 1 TL Paprikapulver
- 1 TL Kurkuma
- ½ TL Kreuzkümmel
- 1 Msp. Chilipulver
- 2 EL Rapsöl
- 600 ml Gemüsebrühe
- Salz
- 1 Prise Zimt
- 2 TL Zitronensaft
- 100 g Sahnejoghurt
- 4 EL Korianderblättchen
## Zubereitung
1. Linsen in einem Sieb abbrausen und abtropfen lassen.
1. Knoblauch schälen und fein hacken. Zwiebel schälen und klein würfeln. Paprika waschen, halbieren, putzen und würfeln. Karotten schälen und in dünne Scheiben schneiden.
1. Knoblauch und Zwiebeln im heißen Öl glasig braten, dann Paprika und Karotten zugeben.
1. Paprikapulver, Kurkuma, Kreuzkümmel und Chili mischen und mit in die Pfanne geben, unter Rühren 2–3 Minuten braten.
1. Brühe und Linsen zugeben und alles ca. 10 Minuten köcheln lassen. Mit Salz, Zimt und Zitronensaft abschmecken.
1. Mit Joghurt und Koriandergrün servieren.
<file_sep>---
title: Hackbraten mit Magerquark und Sellerie
date: 2016-01-13
tags:
- lowcarb
- highfat
- paleo
aliases:
- ../../hauptgerichte/hackbraten-mit-magerquark-und-sellerie
---

## Zutaten für 2 Portionen
- 500 g Staudensellerie
- 2 EL Öl
- 400 g Hackfleisch
- 125 g Magerquark
- 2 Eier
- 1 Knoblauchzehe
- 1 Zwiebel
- 200 g körniger Frischkäse
- Butter oder Kokosöl für die Form
- Salz & Pfeffer
## Zubereitung
Sellerie putzen und in Ringe schneiden. In heißem Öl 10 Minuten dünsten.
Inzwischen die Zwiebel abziehen und in kleine Würfel schneiden. Das Hackfleisch mit Quark, Eiern, zerdrückter Knoblauchzehe und Zwiebelwürfeln verkneten. Mit Salz und Pfeffer würzen. Eine Auflaufform mit Butter oder Kokosöl einfetten. Den Hackteig zu einem länglichen Laib formen, in die Auflaufform legen und den Frischkäse darübergeben, leicht andrücken. Den Sellerie rundherum verteilen.
In den kalten Backofen schieben und bei 225 ℃/Gas Stufe 4 etwa 25 Minuten backen.
## Nährwerte pro Portion
- kcal: 871
- KH: 14g
- Fett: 59g
- Ew: 69g
<file_sep>---
title: Grüner Ballaststoff Smoothie
date: 2015-04-18
tags:
- lowcarb
- highfat
aliases:
- ../../snacks-und-shakes/grüner-ballaststoff-smoothie
---
## Zutaten

- 50.00 g, Brokkoli (Roh)
- 50.00 g, Grünkohl
- 0.50 Avocado
- 10.00 g, Petersilie
- 1.00 mittelgroß (150g), <NAME> (Mittelgroß)
- 40.00 g, Staudensellerie
- 10.00 g, Ingwer
- 80.00 g, Apfelsine/orange
- 100.00 g, Zucchini
## Zubereitung
Zuerst Brokkoli, Grünkohl, Avocado und Petersilie mit einem Pürierstab zerkleinern. Den Apfel entkernen, den Ingwer und die Zucchini schälen. Die Apfelsine auspressen und den Saft zusammen mit den anderen Zutaten in pürieren, bis eine konsistente Masse entsteht. Eventuell noch etwas Wasser nachkippen.
<file_sep>---
title: Low Carb Nutella
date: 2015-05-07
tags:
- lowcarb
- highfat
aliases:
- ../../desserts/low-carb-nutella
---
## Zutaten
- 2 reife Avocados
- Abrieb und Saft von 1 Orange oder Orangenaroma zum Backen
- 200 g dunkle Schokolade (min. 80% Kakaoanteil)
- 1 TL Vanillepulver
- 1 TL Kokosöl (am besten sehr dünnflüssiges, also kein Kokosfett)
- 3 EL Stevia oder anderes Süßungsmittel in Pulverform
## Zubereitung
Avocados halbieren und entkernen, Fruchtfleisch herauslösen. Mit dem Orangensaft/-abrieb/-Aroma mit einem Pürierstab oder Mixer pürieren. Darauf achten, dass eine gleichmäßige Masse ohne Stücken entsteht.
Die Schokolade im Wasserbad schmelzen und das Kokosöl und Vanillepulver hinzufügen.
Die geschmolzene Schokoladenmasse und das Süßungsmittel unter die Avocadomasse rühren. Die noch flüssige Nutella in ein Einmachglas füllen und in den Kühlschrank stellen.
<file_sep>---
title: Avocado Schoko Pudding
date: 2018-07-05
tags:
- lowcarb
- veggie
aliases:
- ../../snacks-und-shakes/avocado-schoko-pudding
---


## Zutaten
- 1 Avocado
- 30 g Mandelmus
- 30 g Kakaopulver
- 1 TL Kokosblütenzucker
## Zubereitung
Alles mit einer Gabel in einer Schüssel verkneten.
<file_sep>---
title: Geflügelsalat
date: 2018-03-05
tags:
- lowcarb
- highfat
aliases:
- ../../salate/geflügelsalat
---

## Zutaten für 2 Portionen
- 100g Bacon / Frühstücksspeck
- 3-4 Stangen (150g) grüner Spargel
- 300 g Geflügelfleisch
- 6 Cherrytomaten
- 5 EL (125g) Estragon-Mayonanaise
- 5 Blätter Romanasalat
## Zubereitung
Den Bacon auf einem mit Backpapier ausgelegtem Blech im Ofen knusprig braten. Den Spargel in mundgerechte Stücke schneiden und kurz in kochendem Salzwasser blanchieren. Unter kaltem Wasser abschrecken.
Das Geflügel in Würfel schneiden und in einer Pfanne durchbraten, die Tomaten halbieren und alles mit der Estragon-Mayonanaise vermischen.
Den Salat in einzelne Blätter teilen, waschen und abtropen lassen. Den Geflügelsalat auf den Blättern verteilen und mit dem Spargel und Bacon servieren.
## Nährwerte pro Portion
- kcal: 623
- KH: 7g
- Fett: 40g
- EW: 57g
<file_sep>---
title: Wraps mit Walnussfarce
date: 2015-06-30
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/wraps-mit-walnussfarce
---
## Zutaten für 2 Portionen
- 4 große Kohlblätter
- [Walnussfarce]({{< relref "Walnussfarce" >}})
## Zubereitung
Die Walnussfarce mittig auf die Kohlblätter geben, die Seiten einklappen, einrollen und in der Mitte durchschneiden.
<file_sep>---
title: Sauerkraut Rote Beete Salat
date: 2016-12-07
tags:
- lowcarb
- veggie
- vegan
aliases:
- ../../salate/sauerkraut-rote-beete-salat
---
## Zutaten für 4 Portionen
- 500 g Sauerkraut
- 3 Kugel/n Rote Bete, gekochte (Rote Rüben)
- 2 Zwiebel(n)
- ½ Bund Schnittlauch
- etwas Muskat
- 3 EL Öl
- etwas Zucker
- evtl. Kümmel
- Salz & Pfeffer
## Zubereitung
Sauerkraut abtropfen lassen und klein schneiden. Rote Bete grob reiben. Zwiebel in Würfel schneiden. Schnittlauch fein schneiden.
Alle Zutaten vermengen und mit Salz, Pfeffer, Muskatnuss, Zucker, Schnittlauch und 2-3 EL Öl abschmecken.
Eventuell auch etwas Kümmel dazu geben.
<file_sep>---
title: Low Carb Nutella alternative
date: 2015-05-17
tags:
- lowcarb
aliases:
- ../../desserts/low-carb-nutella-alternative
---
## Zutaten
- 60 g Butter
- 150 ml Schlagsahne
- 2 EL Kakaopulver
- 50 g gemahlene Mandeln
- etwas Süßstoff
## Zubereitung
Die Butter schmelzen und mit der flüssigen Sahne, dem Kakao und den gemahlenen Mandeln mischen. Nach Belieben etwas Süßstoff hinzugeben. In eine kleine Schüssel gießen und in den Kühlschrank stellen und ca. 1 Std. fest werden lassen.
Wer die Creme gern etwas fester möchte, nimmt etwas weniger Sahne, dafür mehr Butter. Passt gut zu [/hauptgerichte/Eiweissreiche-Brunch-Pfannkuchen].
<file_sep>---
title: Gefüllte Zucchini
date: 2019-05-10
tags:
- lowcarb
aliases:
- ../../hauptgerichte/gefüllte-zucchini
---

## Zutaten für 3 Portionen
- 3 Zucchinis mittelgroß
- 1 Dose gehackte Tomaten
- 10 Cherrytomaten
- 200g Schinken (in Würfel geschnitten)
- 200g geriebener Gouda Käse
## Zubereitung
Die Zucchini längs in zwei Teile schneiden und mit einem Löffel aushöhlen. Das Cherrytomaten klein schneiden und mit den Dosentomaten und Schinkenwürfeln vermischen. Das Ganze nach belieben würzen und in die Aushöhlung geben. Den Käse darauf verteilen und für mind. 30 Minuten bei 180° im Ofen backen bis sich der Käse goldgelb färbt.
<file_sep>---
title: Fisch Gemüsepfanne mit Kokosmilch
date: 2017-02-27
tags:
- lowcarb
aliases:
- ../../hauptgerichte/fisch-gemüsepfanne-mit-kokosmilch
---
##Zutaten

- 500 g Fischfilet (z. B. Pangasius, Seelachs)
- 1 Zucchini
- 1 gelbe Paprikaschote
- 1 rote Paprikaschote
- 1 mittelgroße Zwiebel
- 100 g Brokkoli
- 2 Frühlingszwiebeln
- 500 ml Kokosmilch
- 1 EL Rapsöl
- 1 EL Sesamöl
- Salz & Pfeffer
- Dill
- 1 cm Ingwer
- 1 Knoblauchzehe
##Zubereitung
Fisch auftauen, falls TK-Fisch verwendet wird. Abspülen, trocken tupfen und in mundgerechte Stücke schneiden. Salzen und pfeffern und beiseitestellen.
Zucchini halbieren und in dünne Halbmonde schneiden. Zwiebel grob hacken, Paprikaschoten grob würfeln, Brokkoli in Röschen teilenm Frühlingszwiebeln - auch das Grün - in Ringe schneiden. Bis auf den Brokkoli alles zusammen mite dem Öl in einer großen Pfanne oder Wok gut anbraten und mit Salz, Pfeffer und Dill nicht zu zaghaft würzen.
Wenn das Gemüse scharf angebraten ist, die Kokosmilch dazugießen und das Ganze einmal aufkochen lassen und dann die Hitze reduzieren. Den Ingwer und Knoblauch schälen, kleinhacken und ebenfalls dazugeben.
10 Minuten auf kleiner Flamme ohne Deckel köcheln lassen. Dann den Brokkoli und Fisch dazugeben und weitere 10 Minuten auf dem Herd lassen. Öfter mal umrühren.
Dazu passt jeder [Salat]({{< relref "salate" >}})
<file_sep>---
title: Rezepte
layout: index
order: date
reverse: true
---
In diesen Sektionen findest du alle Rezepte von herzhaften Hauptgerichten bis zu süßen Versuchungen. Lass dich inspirieren und entdecke neue kulinarische Genüsse!
<file_sep>#!/usr/bin/env python3
# python3 -m pip install pathlib python-frontmatter
import sys
from pathlib import Path
import frontmatter
if not len(sys.argv) == 2:
print("please give filename as only parameter")
sys.exit(1)
path = Path(sys.argv[1])
if not path.exists():
print("{} does not exist".format(path))
sys.exit(1)
print(path)
info = frontmatter.load(path)
if "title" not in info:
title = path.stem
chars = "-_"
for c in chars:
if c in title:
title = title.replace(c, " ")
info["title"] = title
if "aliases" not in info:
old_path = "../../{}/{}".format(path.parent.name, path.stem.lower())
info["aliases"] = [old_path]
path.write_text(frontmatter.dumps(info, sort_keys=False) + "\n")
<file_sep>---
title: Spinat Blumenkohl Curry
date: 2020-02-12
lastmod: 2023-02-28
cookTime: PT30M
tags:
- veggie
- vegan
- schnell
- einfach
- curry
aliases:
- ../../hauptgerichte/spinat-blumenkohl-curry
---
Probier dieses einfache und gesunde Spinat-Blumenkohl Curry aus! Mit wenigen Zutaten zauberst du ein leckeres Mittagessen oder Abendessen. Perfekt für eine gesunde Ernährung.

## Zutaten für 4 Portionen
- 2 Zwiebeln
- 2 Knoblauchzehen
- 4 EL Olivenöl
- 1 Blumenkohl (ca. 600g)
- 8 TL Curry(paste)
- 450 g Spinat
- 150 ml Gemüsebrühe
- Salz & Pfeffer
- etwas Zitronensaft zum Abschmecken
## Zubereitung
1. Zwiebeln und Knoblauchzehen schälen und klein hacken. Öl in einem Topf erhitzen und Zwiebeln und Knoblauch darin anschwitzen.
2. Unterdessen den Blumenkohl waschen und in kleine Röschen teilen.
3. Dann das Curry dazugeben und etwas mitdünsten lassen.
4. Den Spinat, den Blumenkohl und die Gemüsebrühe zugeben.
5. Bei mäßiger Hitze etwa 15 Minuten köcheln bis der Blumenkohl weich ist.
6. Mit Pfeffer, Salz und dem Zitronensaft abschmecken.
<file_sep>---
title: Käse Pizzen
date: 2017-08-27
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/käse-pizzen
---



## Zutaten für 4 kleine Pizzen
- 400g Reibekäse
- 3 Eier
- 2 EL Flohsamenschalen
## Beispiele für das Topping
- Tomaten
- frische Spinatblätter
- Walnüsse
- Kürbiskerne
- Speckwürfel
## Zubereitung
Backofen auf ~ 220 ℃ Umluft vorheizen und ein Blech mit Backpapier auslegen.
Käse, Eier und Flohsamenschalen in einer Schüssel verrühren und diesen "Teig" in 4 Kreisen auf dem Backblech verteilen. Im Ofen für ca. 10 Minuten backen, bis die Pizzen einen goldgelben Rand bekommen.
Inzwischen die Zutaten für das Topping vorbereiten. Die fertigen Pizzen aus dem Ofen nehmen und das Topping darauf verteilen.
Das Ganze weitere 5 Minuten backen.
Alternativ lassen sich die Pizzen auch als Pfannkuchen bei mittlerer Hitze in einer Pfanne braten.
<file_sep>---
title: Artischoken Hähnchen Pfanne
date: 2016-03-14
tags:
- lowcarb
- paleo
aliases:
- ../../hauptgerichte/artischoken-hähnchen-pfanne
---


## Zutaten
- 500g eingelegte Artischocken
- 400g Hähnchenfleisch
- 1 kleine Zwiebel
- 2 Chilischoten
- 2 Knoblauchzehen
- evtl. Sojasauce
- Schnittlauch
- etwas Kokosöl zum Braten
## Zubereitung
1. Artischocken abgießen und klein schneiden
1. Zwiebel klein schneiden und mit den Artischocken vermischen
1. Beides zusammen etwas ziehen lassen, damit sich die Aromen entfalten
1. Fleisch grillen (sofern Kontaktgrill vorhanden) oder in der Pfanne anbraten
1. Wenn das Fleisch halbwegs durch ist geben wir die Artischocken dazu
1. Das Ganze mit dem Knoblauch, Chili und eventuell Sojasauce würzen
1. Alles zusammen nochmal durchbraten und zum Schluss noch mit etwas Schnittlauch garnieren
Als Beilage bietet sich z.b. [Blumenkohlreis]({{< relref "Blumenkohlreis" >}}) an.
## Nährwerte
- kcal: 741
- KH: 15g
- Fett: 30g
- EW: 95g
<file_sep>---
title: Low Carb Marzipan Pralinen
date: 2015-10-09
tags:
- lowcarb
aliases:
- ../../desserts/low-carb-marzipan-pralinen
---


## Zutaten
- 100 g Mandelmehl
- 2 EL, gehäuft Mandelmus (~ 45g)
- 1 EL, gehäuft Süßstoff (Erythrit oder Stevia)
- 3 EL Wasser
## Zubereitung
Das Mandelmehl mit dem Süßstoff mischen, das Wasser und Mandelmus dazugeben und alles gut miteinander verrühren. Mit angefeuchteten Händen aus der Masse Kugeln formen. Ergibt ~ 10-12 Stück. Evtl. noch 5 min. bei 200 C Umluft im Ofen noch kurz anbacken.
Im Kühlschrank aufbewahren.
## Nährwerte pro Praline
- kcal: 75
- KH: 1g
- EW: 3g
- Fett: 6g
<file_sep>---
title: Thunfischsalat mit Brokkoli
date: 2016-06-28
tags:
- lowcarb
aliases:
- ../../salate/thunfischsalat-mit-brokkoli
---

## Zutaten
- 350g Brokkoli
- 1 <NAME> ohne Öl
- 1 kleiner Becher Joghurt
- Salz, Pfeffer
## Zubereitung
Wasser zum Kochen bringen und Salzen.
Den Brokkoli bissfest kochen, also nicht zu lang.
Joghurt, Salz und Pfeffer je nach Geschmack, vermengen.
Thunfisch Naturell abtropfen lassen und mit dem Jogurt vermischen.
Sauce über den Brokkoli geben - fertig.
## Nährwerte
- kcal: 340
- KH: 16g
- Fett: 4g
- EW: 58g
<file_sep>#!/usr/bin/make
HUGO_VERSION=0.110.0
.PHONY: all
all: serve
.PHONY: serve
serve: bin/hugo themes/congo/theme.toml
bin/hugo server --disableFastRender
.PHONY: test
test: bin/hugo bin/htmltest
rm -fr public/
bin/hugo --minify
bin/htmltest
.PHONY: publish
publish: clean test
sed -i "s/hugo-version:.*$$/hugo-version: $(HUGO_VERSION)/" .github/workflows/gh-pages.yml
git add -u
.PHONY: clean
clean:
find . -name '*~' -o -name '*.bak' -delete
bin/htmltest:
curl https://htmltest.wjdp.uk | bash
bin/hugo: /tmp/hugo.tar.gz
tar xf /tmp/hugo.tar.gz -C bin/ hugo && touch bin/hugo
/tmp/hugo.tar.gz:
wget https://github.com/gohugoio/hugo/releases/download/v$(HUGO_VERSION)/hugo_extended_$(HUGO_VERSION)_Linux-64bit.tar.gz -O /tmp/hugo.tar.gz
themes/congo/theme.toml:
git submodule update --remote --init
static/img/%.webp: assets/%.jpg
exiftran -ai $<
cwebp -alpha_cleanup on -quiet -q 85 $< -o $@
<file_sep>---
title: <NAME>
date: 2019-03-22
lastmod: 2022-06-19
tags:
- lowcarb
- protein
aliases:
- ../../hauptgerichte/tartar-muffins
---
Diese Muffins sind eine einfache Alternative zu Frikadellen aus der Pfanne, dafür sollte auf jeden Fall Tartar bzw. Rinderhack genommen werden, Schweinehack verliert zuviel Flüssigkeit, was im Ofen eine Sauerei gibt. Zur Sicherheit am besten ein tiefes Backblech auf die unterste Schiene mit in den Ofen geben.

## Zutaten
- 350g Rinderhackfleisch / Tartar
- 1 große Zwiebel
- 150g Karotten
- 2 Eiklar
- 200g Kräuterquark oder Magerquark
- Paprikapulver
- Salz & Pfeffer
## Zubereitung
1. Backofen auf 170 Grad vorheizen.
1. Zwiebel und Karotten schälen und in sehr kleine Würfel hacken (evtl. in der Küchenmaschine)
1. Alle Zutaten in eine Schüssel geben, gut durchkneten und gleichmäßig auf eine 6er Muffinform verteilen, welche vorher bestenfalls eingefettet wird.
1. Im Ofen ca. 20 Minuten backen.
<file_sep>---
title: Erdnuss Sellerie Suppe
date: 2021-11-17
lastmod: 2023-07-12
tags:
- lowcarb
- highfat
- soup
aliases:
- ../../hauptgerichte/erdnuss-sellerie-suppe
---

## Zutaten für 4 Portionen
- 1 rote Zwiebel (ca. 120 g)
- 4 EL Butter ungesalzen (ca. 40 g)
- 440 g Staudensellerie
- 680 ml Hühnerbrühe (2 Gläser)
- 150g Erdnussmus
- 1 Chili
- Salz
- Limetten- oder Zitronensaft
## Zubereitung
1. Die Zwiebel pellen und in dünne Viertelringe schneiden. Die Butter in einem großen Topf zerlassen und die Zwiebeln darin etwas anschwitzen.
1. Währenddessen den Sellerie waschen und in dünne Scheiben schneiden.
1. Nach einigen Minuten die Selleriescheiben dazugeben und beides einige Minuten bei mittlerer Hitze anschwitzen lassen.
1. Dann die Hühnerbrühe dazugeben und das Erdnussmus darunter rühren.
1. Die Suppe unter Rühren bei schwacher Hitze ca. 10 Minuten köcheln lassen und etwas reduzieren, damit sie cremig wird.
1. Die Suppe mit Salz, der kleingehackten Chili und Limetten- oder Zitronensaft abschmecken.
## Nährwerte pro Portion
- kcal 419
- KH 14g
- Fett 31g
- EW 20g
<file_sep>---
title: Ofengemüse
date: 2020-06-24
tags:
- veggie
aliases:
- ../../hauptgerichte/ofengemüse
---

## Zutaten
So ziemlich alle möglichen Gemüsesorten eignen sich. Obligatorisch sind neben dem Gemüse eigentlich nur Öl, Salz & Pfeffer.
## Zubereitung
1. Ofen auf 200℃ Umluft vorheizen
2. Gemüse putzen und in mundgerechte Stücke schneiden
3. Gemüse in eine Schüssel geben, in Öl und Gewürzen schwenken
4. ein flaches Blech mit Backpapier auslegen und Gemüse darauf geben
5. nach folgenden Garzeiten in den Ofen geben:
- 30 Minuten:
- Romanesco
- Kartoffel
- Süßkartoffel
- Rote Bete
- Karotten
- Kürbis
- 20 Minuten:
- Fenchel
- Zwiebel
- Aubergine
- 15 Minuten:
- Zucchini
- Brokkoli
- Paprika
- Tomaten
- Radieschen
Als Extra kann 200 g Feta abgegossen, trockengetupft und über das Blech gebröselt werden.
Ofengemüse kann zu Fleisch- oder Geflügel serviert werden oder zusammen mit einem frischen Salat aus einer halben Gurke, einer halben Avocado, einer handvoll Tomaten, Zitronensaft oder Balsamico und etwas Basilikum oder Petersilie als Hauptgericht gereicht werden.
<file_sep>---
title: Chili Con Carne Spezial
date: 2019-03-17
lastmod: 2023-03-15
tags:
- slowcarb
- einfach
- fleisch
aliases:
- ../../hauptgerichte/chili-con-carne-spezial
---
Das "Spezial" an dieser Chili Con Carne Variante ist das Kakaopulver bzw. die Herrenschokolade. Das scheint erst mal seltsam zu sein und nicht zu einem Fleischgericht zu passen, aber die Schoko-Note verbreitert zusammen mit dem Rotwein das Geschmacksspektrum.
## Zutaten für 6 Portionen

- 2 mittelgroße Zwiebeln
- 600 g Hackfleisch
- 3 EL Öl zum Braten
- 3 Dosen Kidneybohnen a 255 gramm
- 1 Dose Kichererbsen a 265 gramm
- 2 Knoblauchzehen
- 4 EL Tomatenmark
- 1 Dose geschälte Tomaten a 400 gramm
- 1 Pkg passierte Tomaten a 500 gramm
- 2-3 Chilischoten gehackt
- 150 ml Rotwein trocken
- 2 EL Kakaopulver oder Herrenschokolade
- 1 TL Salz
- 1 TL Pfeffer aus der Mühle
- ½ TL Kreuzkümmel gemahlen
- ½ TL Paprika rosenscharf
- 1 Prise Oregano
## Zubereitung
1. Die Zwiebeln abziehen und würfeln.
2. Zwiebeln zusammen mit dem Hack in einem großen Topf anbraten.
3. Die Bohnen und Kichererbsen durch ein Sieb abtropfen lassen und mit in den Topf geben.
4. Nach und nach die anderen Zutaten unterrühren.
5. Das Ganze jetzt noch mindestens 30 Minuten auf kleiner Flamme köcheln lassen, damit alles schön duchziehen kann.
<file_sep>---
title: Low Carb Bounty
date: 2020-02-27
tags:
- lowcarb
- highfat
aliases:
- ../../desserts/low-carb-bounty
---

## Zutaten
- 1 Dose Kokosmilch (400 ml)
- 3 EL Kokosöl
- 2 EL Kokosblütenzucker
- 150 g Kokosraspel
- 200 g dunkle Schokolade (> 80% Kakaoanteil)
## Zubereitung
Die Kokosmilch einige Stunden im Kühlschrank lagern, damit sich die Creme vom Kokoswasser absetzt. Das Kokoswasser weggießen oder für etwas anderes verwenden.
Die Kokoscreme mit 2 EL Kokosöl in einem Topf schmelzen, dann den Kokosblütenzucker und die Kokosraspel hinzufügen und alles zu einer gleichmäßigen Masse verrühren.
Eine Kastenform mit Frischhaltefolie auslegen und die Kokosmasse hineinfüllen und gut andrücken. Etwa 3 Stunden in den Kühlschrank stellen, bis die Masse vollständig geworden ist.
Danach vorsichtig aus der Kastenform nehmen und mit einem scharfen Messer in Riegel schneiden.
Die Schokolade mit dem verbliebenen EL Kokosöl im Wasserbad schmelzen und die Kokosriegel mithilfe von zwei Gabeln vorsichtig in die geschmolzene Schokolade tauchen und auf einen großen Teller mit Backpapier legen und anschließend im Kühlschrank abkühlen lassen.
<file_sep>---
title: Rindfleisch Spiess mit gebratenem Thai Gemüse
date: 2015-10-08
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/rindfleisch-spiess-mit-gebratenem-thai-gemüse
---
## Zutaten für 4 Portionen
- 600 g Rindfleisch
- ~ 10 Holzspieße
- 3 <NAME>
- 1 Paprikaschote
- 1 Limette
- 1 EL Sesamöl
- 4 EL Tamari (glutenfreie Sojasoße)
- 1 TL rote Currypaste
- 3 Knoblauchzehen
- 1 EL Ingwer
- 2 <NAME> (Porree)
- 400g grüner Spargel
- 1 <NAME>
- ½ <NAME>
- 100g Erdnüsse
- Kokosöl zum Braten
## Zubereitung
Das Fleisch abspülen, trocken tupfen und in Würfel schneiden. Die Knoblauchzehen abziehen und kleinhacken, die Limette entsaften, den Ingwer klein reiben. In einer Schüssel oder einem tiefen Teller das Sesamöl, 2 EL von dem Tamari, die Currypaste, den Ingwer und ⅓ von dem kleingehackten Knoblauch zusammen mit dem Limettensaft zu einer Marinade zusammenrühren. Das Fleisch in der Marinade wenden und gut damit bedecken, das Ganze einige Stunden ziehen lassen. Die Holzspiesse in kaltem Wasser einweichen.
Den Backofen auf 220 ℃ vorheizen. Ein Grillrost mit Backpapier belegen, die Paprikaschote abwaschen, entkernen und in Stücke scheiden. Zwei von den roten Zwiebeln abziehen und achteln. Das Fleisch auf die Holzspieße ziehen, etwa 4 Stück auf jeden Spiess, dazwischen Zwiebeln und Paprika, und auf das Backpapier legen. Im Backofen auf der oberen Schiene etwa 15 Minuten backen, öfter wenden.
Den Lauch waschen, putzen und klein schneiden. Vom Spargel die holzigen Enden entfernen und in kleine Stücke schneiden. Die letzte rote Zwiebel pellen und kleinhacken. Die Chilischote ebenfalls kleinhacken. Das Kokosöl in einer tiefen Pfanne oder einem Wok erhitzen und zuerst den restlichen Knoblauch und Chili anbraten und danach das restliche Gemüse dazugeben. Alles mit Tamari kurz braten, bis es weich ist. Mit Erdnüssen und frischen Koriander garnieren.
## Nährwerte pro Portion
- kcal: 609
- KH: 16 g
- EW: 46 g
- Fett: 36 g
<file_sep>---
title: Teutonenpfanne
date: 2018-06-02
lastmod: 2023-05-23 16:45:47
cookTime: PT17M
tags:
- lowcarb
- eier
- simple
aliases:
- ../../hauptgerichte/teutonenpfanne
---

## Zutaten
- 1-2 Paprikaschoten
- 1 Zwiebel
- 250 g Rinderhack
- 100 g passierte Tomaten
- 50 g Harzer Käse oder Fetakäse
- 2 Eier
- Gewürze nach Belieben (Salz, Pfeffer, Basilikum ...)
## Zubereitung
1. Zwiebel abziehen, würfeln und zusammen mit dem Hackfleisch in einer großen Pfanne abraten.
2. Paprika entkernen, in Stücke oder Streifen schneiden und mit in die Pfanne geben.
3. Käse mit in die Pfanne geben, leicht anschmelzen lassen und dann mit den passierten Tomaten ablöschen. Nach belieben würzen.
4. Die Eier in die Pfanne Schlagen und unterrühren.
5. Hitze reduzieren und das Ganze noch ein paar Minuten köcheln lassen.
Dazu passt [Blumenkohlreis]({{< relref "Blumenkohlreis" >}})
<file_sep>---
title: Italienische Fleischbällchen in Tomatensauce mit Rosmarin
date: 2019-04-01
tags:
- lowcarb
aliases:
- ../../hauptgerichte/italienische-fleischbällchen-in-tomatensauce-mit-rosmarin
---

## Zutaten für 4 Portionen
- 600 g Rinderhack
- 2 TL Paprikapulver
- 4 Zwiebeln
- 4 Knoblauchzehen
- 3 EL fein gehackte Rosmarin
- 1 EL fein gehackte Thymian
- 3 Dosen gehackte Tomaten а 400 g
- 80 g getrocknete Tomaten
- 150 g schwarze Oliven
- 1 EL Kokoszucker
- Salz & Pfeffer
- Öl zum Braten
## Zubereitung
Zwiebeln und Knoblauch abziehen, fein hacken und die Hälfte davon mit dem Fleisch in einer Schüssel verkneten. Paprikapulver sowie 1 EL Rosmarin untermengen und den Fleischteig etwa 10 Minuten ruhen lassen.
Das Öl in einem Topf erhitzen und den Rest von den Zwiebeln und dem Knoblauch anschwitzen, bis sie glasig sind. Die übrigen Zutaten zugeben und alles 30 bis 40 Minuten zugedeckt köcheln lassen.
Den Backofen auf 200 Grad Celsius vorheizen. Ein Backblech mit Backpapier auslegen.
Dann mit einem Löffel kleine Fleischbällchen formen und diese auf Backpapier legen. Im Backofen 15 bis 20 Minuten braten. Dann herausnehmen aber den Backofen nicht ausschalten.
Die gebraten Fleischbällchen in eine feuerfeste Form legen und die Tomatensoße darüber gießen. Die Form für 5 bis 10 Minuten in den Backofen stellen. Man kann die Fleischbällchen auch in den Topf mit der Tomatensoße legen und bis zum Schluß mitkochen, das erfordert allerdings einen großen Topf.
Dazu geriebenen Käse und einen grünen Salat reichen.
<file_sep>---
title: Garnelen in Petersiliensauce
date: 2019-05-26
tags:
- lowcarb
aliases:
- ../../hauptgerichte/garnelen-in-petersiliensauce
---

## Zutaten für 1 Portion
- 225g Garnelen Natur oder Provence
- 3 Bund glatte Petersilie
- 1 El Butter
- 1 El Öl
- 2-3 Knoblauchzehen
- Salz
- Cayennepfeffer
- 1/8 l Schlagsahne oder Saure Sahne
## Zubereitung
Wenn nötig, die Garnelen waschen, schälen und entdarmen. Schwanzflossen dranlassen!
Butter und Öl zusammen in einer großen Pfanne erhitzen. Knoblauch pellen und dazupressen. Garnelen in die Pfanne geben und von jeder Seite etwa 1 bis 1 1/2 Minuten braten. Mit Salz und Cayenne würzen.
Petersilie fein hacken und zusammen mit der Sahne in die Pfanne geben. 7-10 Minuten cremig einkochen lassen.
<file_sep>---
title: Guacamole
date: 2015-05-03
tags:
- lowcarb
- highfat
- veggie
- vegan
aliases:
- ../../beilagen/guacamole
---
## Zutaten für 4 Portionen
- 3-4 Avocados
- 1 Limette
- 1 mittelgroße Zwiebel
- 2 Knoblauchzehen
- 2 Tomaten
- 2 EL Kreuzkümmel
- 2 TL Koriander
- 1 TL Cayennepfeffer oder Chilipulver
- etwas Tabasco
- Salz & Pfeffer
## Zubereitung
Die Limette entsaften. Die Avocados entkernen und den Inhalt mit einem Löffel in eine Schüssel geben und mit einer Gabel zerdrücken. Sofort den Saft der Limette zugeben, damit die Avocados nicht braun werden. Die Zwiebel schälen, grob zerkleinern und ebenfalls zugeben. Den Knoblauch schälen und hineinpressen. Die Tomaten waschen, feinhacken und den Saft auspressen, die Tomatenstücke unterrühren. Die übrigen Gewürze hinzugeben. Mit Salz, Pfeffer und Tabasco nach Belieben würzen. Das Ganze mit dem Pürierstab zu einer Creme zerkleinern. Zwischendurch den Saft der zweiten Limette so zugeben, dass weder die Schärfe des Pfeffers, die Zwiebel oder die Limette vorschmeckt. Zwischendurch abschmecken.
Die Avocados sollten so reif sein, dass sie beim Drücken leicht nachgeben. Wenn die Avocados zu reif sind, wird die Guacamole matschig. Als Notersatz für die Limetten kann man auch eine Zitrone verwenden.
Wenn man die Creme vorbereiten möchte, sollten man einen der Kerne in die Guacamole stecken und das Ganze unter Klarsichtfolie im Kühlschrank aufbewahren. Vor dem Servieren den Kern wieder entfernen. Die Guacamole bleibt so länger grün.
<file_sep>---
title: Thunfischsalat mit Apfel
date: 2015-09-26
draft: false
tags:
- lowcarb
- salat
aliases:
- ../../salate/thunfischsalat-mit-apfel
---
## Zutaten

- 1 <NAME>
- 100 g körniger Frischkäse (Cottage Cheese)
- 28 g Zwiebel (~ 1 kleine Zwiebel)
- 45 g Apfel (~ ½ kleiner Apfel)
- 25 g Majonnaise (~ 1 EL)
- Salz
## Zubereitung
Zwiebel pellen und in kleine Würfel schneiden, den Apfel entkernen und in kleine Stifte schneiden, Thunfisch abtropen lassen. Dann alle Zutaten in einer Schüssel miteinander vermischen und mit Salz abschmecken.
## Nährwerte
- Kcal: 350
- EW: 40 g
- KH: 8 g
- Fett: 18 g
<file_sep>---
title: Putenpfanne mit Zucchini und Pilzen
date: 2015-02-07
lastmod: 2023-04-07
tags:
- lowcarb
- pfanne
- geflügel
- pilze
aliases:
- ../../hauptgerichte/putenpfanne-mit-zucchini-und-pilzen
---


## Zutaten
- 500g Putenbrustfilet
- 1 große Zwiebel
- Olivenöl
- 250g Zucchini
- 400g Champignons
- 2 Chilischote
- 100 ml Hühnerbrühe
- 150 g Schmand / saure Sahne
- Kräuter nach belieben
## Zubereitung
1. Putenfilet in Streifen schneiden, Zwiebel abziehen und würfeln, beides zusammen im Öl in einer großen Pfanne anbraten.
1. Inzwischen Champignons und Zucchini putzen und kleinschneiden. Chilischote klein hacken.
1. Puten und Zwiebeln aus der Pfanne nehmen und Zucchini, Champignons und Chili anbraten.
1. Das Geflügel und die Zwiebeln wieder dazugeben, mit der Hühnerbrühe ablöschen und den Schmand unterrühren, die Kräuter dazugeben.
1. Vielleicht noch 5-10 Minuten, köcheln lassen.
<file_sep>---
title: Pak Choi mit Cashewkernen
date: 2020-05-31
tags:
- lowcarb
aliases:
- ../../hauptgerichte/pak-choi-mit-cashewkernen
---

## Zutaten für 2 Portionen
- 400g Pak Choi
- 1 Zwiebel
- 1 EL Sesamöl
- 250ml Wasser
- 3 EL Sojasauce
- 1 EL Pilzsauce
- 100 g Cashewkerne, ungesalzen
- ½Bund frischer Koriander
- 1 EL Sesam
## Zubereitung
Den Pak Choi waschen und das untere, helle Stück in kleine Stücke schneiden, die Blätter teilen. Die Zwiebel in kleine Würfel schneiden.
Zwiebelwürfel und helle Pak Choi Anteiel mit etwas Öl bei mittlerer Hitze im Wok anbraten. Nach wenigen Minuten die Pak Choi Blätter hinzugeben. Nach ca. 10 Minuten mit Wasser, Sojasauce und Pilzsauße ablöschen und weitere 10 Minuten bei geringer Hitze köcheln lassen.
Inzwischen die Cashewkerne in einer Pfanne ohne Fett kurz rösten und dann alles zusammen mit dem gehackten Koriander und Sesam servieren.
Dazu passt [/beilagen/blumenkohlreis] sehr gut.
<file_sep>---
title: Rührei Variationen
date: 2015-05-03
lastmod: 2022-08-13
tags:
- simple
- lowcarb
aliases:
- ../../hauptgerichte/rührei-variationen
---
Rührei ist so simpel, wie nur irgend ein Rezept sein kann. Trotzdem ist es super kombinierbar und kann beliebig variiert werden.
Eine klassische Kombination sind Rühreier und Pilze: Champignons, Steinpilze, Pfifferlinge, Austernpilze, Maronen, Shitake oder Kräuterseitlinge.
Weitere Kombinationen: Tomaten, Paprika, Zucchini, Speck, Schinken, Avocado, Spinat, Parmesan, Feta.
Kräuter und Gewürze: Schnittlauch, Petersilie, Basilikum.


## Zutaten
- 3-4 Eier
- Salz & Pfeffer
- ½ TL Cayennepfeffer oder Paprika rosenscharf
- ½ Zwiebel
- 100 g Gemüse oder Pilze (optional)
- 75 g Speck (optional)
- Butter, Ghee oder Öl für die Pfanne
## Zubereitung
1. Eier zu beliebigen Anteilen von Eigelb und Eiweiß in eine Schüssel schlagen, mit Salz, Pfeffer und dem Champignons oder Paprika würzen.
2. Die Zwiebel schälen und in Würfel schneiden.
3. Optional Pilze, Gemüse oder Speck ebenfalls in Würfel schneiden. Beides mit dem Fett (am besten Butter oder Ghee) in einer Pfanne bei mittlerer Temperatur anbraten.
4. Dann die Eier in die Pfanne geben, den Herd ausmachen und weiter rühren, bis es die gewünschte Konsistenz erreicht hat. Aus der Pfanne nehmen, bevor es zu trocken ist.
<file_sep>---
title: Schokoladenmousse
date: 2018-05-26
tags:
- lowcarb
- highfat
aliases:
- ../../desserts/schokoladenmousse
---

## Zutaten für 6 kleine Gläser
- 150g dunkle Schokolade (> 80% Kakaoanteil)
- 150g Sahne
- 2 Eier
- 1 EL Kokosblütenzucker
- ½ TL Vanillepulver
- 1 Orange, ungewachst
## Zubereitung
Die Schokolade im Wasserbad schmelzen lassen. Die Eier trennen und das Eiweiß steif schlagen.
Die Sahne fast steif schlagen. Die Orangenschale abreiben und zusammen mit dem Eigelb, Kokosblütenzucker und Vanillepulver vermischen und zu der geschmolzenen Schokolade geben.
Dann die Schokoladenmasse vorsichtig unter die Sahne heben und alles zu einer gleichmäßigen Masse verrühren. Anschließend das Eiweiß vorsichtig unterheben. Die Mousse in 6 kleine Gläser füllen und in den Kühlschrank stellen.
<file_sep>---
title: Sonnenblumenfisch
date: 2015-09-05
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/sonnenblumenfisch
---

## Zutaten für 4 Portionen
- 650 g Pollak oder Schellfisch
- 100 g Parmesan
- 100 g Sonnenblumenkerne
- 150 g Mischsalat
- 200 g Creme fraiche
- 2 unbehandelte Limetten
- 1 große reife Avocado
- 1 EL Sahne
- 1 Knoblauchzehe
- 1 Handvoll gemischte Kräuter
- Salz & Pfeffer
- Kokosöl zum einfetten der Form
## Zubereitung
Den Backofen auf 225 ℃ vorheizen. Eine feuerfeste Form mit etwas Öl einfetten.
Die Pollak Filets abspülen, trockentupfen, mit Salz und Pfeffer würzen und in die Form legen. Den Parmesan fein reiben und mit der Limettenschale mischen. Die Mischung auf dem Fisch verteilen und zuletzt eine Schicht Sonnenblumenkerne darauf geben. Den Fisch auf der oberen Schiene im Backofen etwa 20 Minuten backen.
Den Salat waschen, trocken schleudern und klein schneiden. Die Avocado längs halbieren, den Kern entfernen das Fruchtfleisch aus der Schale lösen und in dünne Scheiben schneiden. Für das Dressing Creme Fraiche, Sahne, Knoblauch und Kräuter verquirlen und mit Salz und Pfeffer abschmecken.
Den Salat und die Avocado auf dem Teller neben dem Fisch anrichten oder in einer Schüssel servieren und mit dem Dressing beträufeln.
<file_sep>---
title: Ballaststoffreiche Karottenbrötchen
date: 2015-10-21
tags:
- lowcarb
- highfat
aliases:
- ../../beilagen/ballaststoffreiche-karottenbrötchen
---
## Zutaten für 6 Stück
- 5 Eier
- 100 g Crème Fraîche
- 80 g Sesam
- 80 g Sonnenblumenkerne
- 60 g Mandelmehl
- 2 EL Flohsamenschalen
- 1 EL Sukrin
- 2 TL Backpulver
- 2 TL Salz
- 1 Karotte
## Zubereitung
Die Karotte wachen und grob reiben. Einige von den Sonnenblumenkernen beiseite legen.
Den Backofen auf 200 ℃ vorheizen und ein Blech mit Backpapier auslegen.
Eier und Crème Fraîche verrühren und anschließend alle weiteren Zutaten dazugeben. Den Teig etwa 10 Minuten ruhen lassen.
Mit angefeuchteten Händen den Teig zu kleinen Kugeln formen und auf das Backpapier legen und mit den übrigen Sonnenblumenkernen bestreuen und 15 Minuten backen.
## Nährwerte pro Portion
- kcal: 351
- KH: 6g
- Fett: 29g
- EW: 15g
<file_sep>---
title: Chili Con Tuna
date: 2016-10-26
tags:
- slowcarb
aliases:
- ../../hauptgerichte/chili-con-tuna
---
## Zutaten für 2 Portionen

- 2 Dosen Thunfisch in eigenem Saft a 150g
- 1 mittelgroße Zwiebel gewürfelt
- 1 Knoblauchzehe gehackt
- 2 EL Tomatenmark
- 1 Pkg passierte Tomaten a 500 gramm
- 2 Dosen Kidneybohnen a 255 gramm
- ½ Dose Kichererbsen a 265 gramm oder Mais a 150 gramm
- 2 Chilischoten gehackt
- <NAME>
- Salz & Pfeffer
- Kreuzkümmel gemahlen
- Oregano
- 2 EL Öl zum Braten
## Zubereitung
1. Zwiebel abziehen, grob würfeln
1. Zwiebelwürfel mit dem Tomatenmark in einem Topf mit Öl leicht anbraten
1. Thunfisch dazugeben und kurz mitschmoren lassen
1. währendessen die Chilis und den Knoblauch kleinhacken
1. mit den Tomaten ablöschen
1. Kidneybohnen und alle Gewürze dazugeben
1. die Hitze reduzieren und das Ganze noch 30-45 Minuten köcheln lassen
<file_sep>---
title: Gefüllte Pfannkuchen
date: 2017-03-01
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/gefüllte-pfannkuchen
---
## Zutaten für 4 Portionen
- 2 Eier
- 2 Eiweiß
- 75g griechischer Jogurt
- ½ TL Salz
- 25 g Sahne
- 4 TL Flohsamenschalen
- 250g Schweinefleisch
- 2 Karotten
- 4 Brokkoliröschen
- 6 Champignons
- 1 Knoblauchzehe
- 2 cm Ingwer
- Kokosöl zum Braten
- Salz & Pfeffer
## Zubereitung
Alle Zutaten von den Eiern bis Flohsamenschalen verrühren, Kokosöl in einer beschichteten Pfanne zerlassen und 4 Pfannkuchen braten.
Das Schweinefleisch in dünne Streifen schneiden, die Karotten schälen und ebenfalls in dünne Streifen schneiden, Brokkoli und Champignons kleinschneiden, den Ingwer und Knoblauch schälen und reiben oder kleinhacken.
Wieder etwas Kokosöl in einer Pfanne erhitzen und das Schweinefleisch 5-7 Minuten abraten, dann das Gemüse dazugeben. Evtl. etwas Sojasoße darüberträufeln und ca. 5 Minuten weiterbraten. Mit Salz & Pfeffer abschmecken.
Die Mischung auf die Pfannkuchen geben und zusammenrollen.
<file_sep>---
title: Zucchini Gemüsepfanne mit Hackfleisch
date: 2014-09-19
lastmod: 2022-06-22
tags:
- lowcarb
- simple
aliases:
- ../../hauptgerichte/zucchini-gemüsepfanne-mit-hackfleisch
---

## Zutaten für 2 Portionen
- 1 Zwiebel
- 2 Zehen Knoblauch
- 1 EL Olivenöl
- 500 g Hackfleisch, gemischt
- 1 Zucchini
- 3 Tomaten
- 1 EL Tomatenmark
- Salz und Pfeffer
- Paprikapulver
- 75g Schafskäse
## Zubereitung
1. Zwiebel und Knoblauch abziehen, Zwiebel würfeln, Knoblauch zerdrücken.
1. Olivenöl in einer Pfanne erhitzen und das Hackfleisch zusammen mit Zwiebel und Knoblauch darin anbraten.
1. Zucchini waschen, würfeln. Tomaten waschen, den Stielansatz entfernen und ebenfalls würfeln. 1. Gemüse zum Hack geben, Hitze reduzieren und ca. 10 Minuten mitdünsten lassen.
1. Tomatenmark hinzugeben und nach Geschmack würzen.
1. Zum Schluss den zerbröselten Schafskäse hinzugeben.
<file_sep>---
title: Erdbeer Cheesecake
date: 2016-01-08
lastmod: 2022-05-21
tags:
- lowcarb
- highfat
- veggie
aliases:
- ../../desserts/erdbeer-cheesecake
---

## Zutaten für eine Torte
- 300 g Erdbeeren
- 1 TL Vanillepulver
- 5 EL Kokosblütenzucker
- ½ ungewachste Zitrone
- 150 g Pekanüsse oder Paranüsse
- 150 g Mandeln oder Mandelmehl
- 130 g weiche entsteinte Datteln
- 2 EL Kokosöl
- 250 g Mascarpone
- 250 g griechischer Jogurt
- Zitronenmelisse
- Butter
## Zubereitung
1. Die Schale von der Zitrone abreiben und den Saft auspressen.
1. Ein paar Erdbeeren für die Deko beiseite legen. Die Erdbeeren, Vanillepulver, Kokosblütenzucker und Zitronensaft und -abrieb aufkochen und dann wieder vollständig abkühlen lassen. Das Ganze mit dem Pürierstab zu einer homogenen Masser verrühren.
1. Die Nüsse und Mandeln zu Mehl verarbeiten, dann Datteln und Kokosöl mit dem Pürierstab einarbeiten, bis ein dicker Nussteig entstanden ist. Den Teig in eine gefettete Springform (~ 22 cm) geben und gut mit einem Löffel andrücken. Den Boden in den Gefrierschrank stellen.
1. Mascarpone mit Jogurt vermischen und die abgekühlten Erdbeeren mit einem Schneebesen untermischen. Diese Masse auf dem Tortenboden verteilen und glattstreichen.
1. Die Torte mindestens 8 Stunden in den Gefrierschrank stellen, dann mit den verbliebenen Erdbeeren und der Zitronenmelisse dekorieren.
## Nährwerte pro Torte
- kcal: 4035
- KH: 168 g
- Fett: 315 g
- EW: 90 g
<file_sep>---
title: Hey, schön dass Du da bist!
---

Ich habe diese Sammlung von einfachen, gesunden und leckeren Rezepten zusammengestellt, um eine abwechslungsreiche Ernährung ohne viel Aufwand zu ermöglichen. Diese Rezepte sind unkompliziert, mit wenigen Zutaten und in kurzer Zeit zubereitet.
Die Rezepte sind entsprechend kategorisiert, wenn sie bestimmten Ernährungsweisen wie z.B. ["lowcarb"](tags/lowcarb/), ["highfat"](tags/highfat/), ["paleo"](tags/paleo/) entsprechen oder ["simple"](tags/simple/), wenn sie relativ schnell und einfach zubereitet sind. Alle Kategorien findest du [hier](tags/).
<file_sep>---
title: Waffeln mit Zitrone und Mohn
date: 2018-05-20
tags:
- lowcarb
- highfat
aliases:
- ../../desserts/waffeln-mit-zitrone-und-mohn
---

## Zutaten für 8 Waffeln
- 4 Eier
- 3 EL Kokosblütenzucker
- 300 g <NAME>
- 1 TL Vanillepulver
- 60 g Mandelmehl
- 2 EL Flohsamenschalen
- 2 TL Backpulver
- 2 EL Blaumohn
- 1 Zitrone
## Zubereitung
Die Schale der (möglichst unbehandelten) Zitrone mit einer Küchenreibe abreiben.
Die Eier schaumig schlagen, Kokosblütenzucker und <NAME>iche unterrühren bis ein glatter Teig entsteht. Die restlichen Zutaten unterrühren.
Den Teig etwas ruhen lassen und inswischen das Waffeleisen aufwärmen lassen. Nacheinander 8 Waffeln aus dem Teig backen.
Aus dem Teig können problemlos auch Pfannkuchen gebacken werden.
<file_sep>---
title: Crispy Coconut Chicken
date: 2020-07-08
tags:
- lowcarb
- paleo
aliases:
- ../../hauptgerichte/crispy-coconut-chicken
---

## Zutaten
- 500g Hähnchenbrust
- 2 Eier
- ½ Tasse Kokosraspeln
- ½ Esslöffel Paprika
- ¼ TL Cayennepfeffer
- ¼ Teelöffel Muskatnuss
- Salz & Pfeffer nach Geschmack
## Zubereitung
1. Zuerst den Backofen vorheizen. Umluft 200 Grad / oder Ober- und Unterhitze 220 Grad.
2. Die Hähnchenbrust in Nuggets schneiden.
3. Die beiden Eier in einer mittelgroßen Schüssel aufschlagen.
4. In einer zweiten Schüssel die Kokosraspeln zusammen mit den Gewürzen, mit Hilfe einer Gabel, gut durchmischen.
5. Danach die Nuggets zuerst durch das Ei ziehen und dann in die Kokosraspel-Mischung geben. Dabei darauf achten, dass die Nuggets rundum ummantelt sind.
6. Die Nuggets auf ein mit Backpapier ausgelegtes Backblech legen und darauf achten, dass sie sich nicht berühren. Nun die Nuggets ca. 15-20 Minuten auf einer Seite goldbraun backen. Anschließend die Hähnchenstücke wenden und knusprig fertig backen.
<file_sep>---
title: Gurkensalat
date: 2019-05-28
tags:
- lowcarb
- veggie
aliases:
- ../../salate/gurkensalat
---

## Zutaten für 2 Portionen
- 1 Salatgurke
- 2 Chilischoten
- 1 handvoll Koriander
- ½ Limette
- 1 handvoll Cherrytomaten
- 1 EL Austern- oder Fischsauce
## Zubereitung
Die Gurke klein schneiden, die Chilischoten und den Koriander kleinhacken und vermischen. Die Cherrytomaten halbieren und dazugeben. Den Limettensaft, Austern- oder Fischsauce über den Gurkensalat gießen und das ganze ca. 1 Stunde ziehen lassen.
<file_sep>---
title: Protein Pudding
date: '2022-01-29'
cookTime: PT5M
servings: 1
tags:
- simple
- protein
aliases:
- ../../desserts/protein-pudding
---
## Zutaten
- 50 g Beeren
- 1 Eiklar
- 20 g Proteinpulver
- 200 g Magerquark
- some Flavor Drops (optional)
- 5 g Speisestärke (optional)
## Zubehör
- mikrowellenfeste Schüssel
- Mikrowelle
- Teller
## Zubereitung
1. Magerquark, Proteinpulver, Eiklar, Speisestärke (optional), Flavor Drops (optional) in eine mikrowellenfeste Schüsselgeben, dann Beeren untermischen und für 5 Minuten bei 700Watt in die Mikrowelle stellen.
[Beeren: 50 g; Eiklar: 1; Flavor Drops (optional): some; Magerquark: 200 g; Proteinpulver: 20 g; Speisestärke (optional): 5 g]
2. Immer wieder schauen, dass es nicht zu hoch geht und über die Schüssel läuft. Am besten in Intervallen arbeiten.
[–]
3. Auf einen Teller stürzen, abkühlen lassen und genießen.
[–]
<file_sep>---
title: Linsen Aglio, Olio e Peperoncino
date: 2014-06-15
lastmod: 2023-01-05
tags:
- lowcarb
aliases:
- ../../hauptgerichte/linsen-aglio-olio-e-peperoncino
---
Das hier ist eine Kohlehydrat-reduzierte Variante des italienischen Pasta-Klassikers, der nach Belieben mit einer Vielzahl von weiteren Zutaten wie Gambas, Pilzen, und Salsiccia variiert werden kann. Hier ist das puristische Grundrezept.
## Zutaten für 4 Portionen
- 4 Knoblauchzehen
- 2 Chilischoten
- 1 kleine Paprika
- 200g Linsen (Trockengewicht)
- 4 EL Olivenöl
- Salz & Pfeffer
- Petersilie
- optional: Zitronensaft
## Zubereitung
1. Wasser für die Linsen zum Kochen aufsetzen.
2. Während das Wasser erhitzt, Knoblauchzehen abziehen, in grobe Stücke schneiden, Paprikaschote putzen und ebenfalls kleinschneiden, die Chilischoten klein hacken.
3. Sobald das Wasser kocht, Linsen hineingeben.
4. Die Knoblauchzehen zusammen mit Paprika und Chili in einer Pfanne in Olivenöl bei ¾ Hitze anbraten. Vorsicht! Der Knoblauch darf nicht zu braun werden, sonst wird er bitter!
5. Die Linsen abtropfen und mit in die Pfanne geben und gut durchmengen. Mit Salz und Pfeffer abschmecken.
6. Die Linsen Aglio, Olio e Peperoncino mit Petersilie und nach Belieben mit Zitronensaft anrichten.
<file_sep>---
title: Fischfrikadellen
date: 2019-05-28
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/fischfrikadellen
---

## Zutaten für 2 Portionen
- 2 Dosen Thunfisch in eigenem Saft ODER
- 300g Fisch (Scholle, Kabeljau, Schellfisch, Lachs ...nur kein Pangasius)
- 1 Ei
- 1 TL Flohsamenschalen
- Salz & Peffer
- evtl. Öl zum Braten
- 1 TL Ingwer
- 5 TL gelbe Currypaste
- 200g Mayonnaise oder Sahne
## Zubereitung
Den Thunfisch gut auspressen oder die Fischfilets in einer Küchenmaschine zerkleinern dann das Ei und die Flosamenschalen untermengen, mit Salz & Pfeffer würzen.
Für Thai-Style Frikadellen etwas Ingwer schälen, kleinhacken und diesen zusammen mit 3 TL von der Currypaste in die Hackmasse untermengen.
Für den Dip die Sahne mit 2 TL Currypaste verrühren.
Dann Frikadellen aus der Masse formen und entweder 8 Minuten von jeder Seite in der Pfanne braten oder im Backofen bei 200 C ca. 20 Minuten backen.
Die Frikadellen eignen sich sehr gut als Beilage zu [/beilagen/Blumenkohlreis] und [/salate/gurkensalat].
<file_sep>---
title: Blumenkohlpizza
date: 2015-11-14
tags:
- lowcarb
aliases:
- ../../hauptgerichte/blumenkohlpizza
---

## Zutaten für 4 Portionen
- 400 g Blumenkohl
- 2 Eier
- 350 g geriebener Käse
- 1 EL getrockneter Oregano
- 2 EL Flohsamenschalen
- 6 EL passierte Tomaten
- 100 g Parma- oder Serranoschinken
- 6 sonnengetrocknete Tomaten
- etwas Thymian
- grobes Salz
## Zubereitung
Backofen auf 230 ℃ vorheizen und ein Backblech mit Backpapier auslegen. Blumenkohl waschen, abtropfen lassen und in der Küchenmaschine kleinhacken. Dann den Blumenkohl mit den Eiern, 150 g von dem Reibekäse, dem Oregano und den Flohsamenschalen zu einem Teig verrühren und diesen auf dem Backpapier ausbreiten. Den Teig dann ca. 12 Minuten im Ofen backen und wieder herausnehmen.
Den Boden dann mit den passierten Tomaten bestreichen und mit dem restlichen Reibekäse bestreuen. Dann kann die Pizza mit dem Schinken, den getrockneten Tomaten und Oliven belegt werden. Das Ganze kommt dann noch mal für 5 - 10 Minuten in den Ofen, bis der Käse geschmolzen ist. Dann mit dem Thymian und Salz bestreuen.
Vor dem Servieren etwas abkühlen lassen, damit die Pizza besser zusammenhält.
## Nährwerte pro Portion
- kcal: 391
- KH: 7g
- Fett: 23g
- EW: 38g
<file_sep>---
title: Spitzkohl-Apfel Salat
date: 2022-02-27
cookTime: PT10M
servings: 6
tags:
- schnell
- veggie
aliases:
- ../../salate/spitzkohl-apfel-salat-mit-karamellisierten-walnüssen
---
## Zutaten für 6 Portionen
- 1 EL Honig
- 1 TL Zucker
- 1 TL Salz
- 1 Prise Pfeffer
- 2 ELs Olivenöl
- 2 Äpfel
- 500 g Spitzkohl
- 4 ELs hellem Balsamico-Essig oder Weißweinessig
- 50 g Walnüsse
## Zubehör
- groben Raspel
- kleinen Pfanne
## Zubereitung
1. Die äußeren Blätter vom Spitzkohl entfernen, vierteln und den Strunk rausschneiden. Dann in dünne Streifen schneiden.
[Spitzkohl: 500 g]
2. Mit den Händen den Spitzkohl mit Salz und Zucker vermengen und gut durchkneten. Anschließend mit hellem Balsamico-Essig oder Weißweinessig und Olivenöl sowie Pfeffer würzen.
[Olivenöl: 2 ELs; Pfeffer: 1 Prise; Salz: 1 TL; Zucker: 1 TL; hellem Balsamico-Essig oder Weißweinessig: 4 ELs]
3. Äpfel waschen und mit einer groben Raspel in kleine Stücke raspeln. Anschließend mit dem Spitzkohlsalat vermischen.
[Äpfel: 2]
4. In einer kleinen Pfanne Walnüsse anrösten, den Honig hinzugen und kurz karamellisieren lassen. Dann vom Ofen nehmen, abkühlen lassen und über den Salat geben.
[Honig: 1 EL; Walnüsse: 50 g]
5. Salat mit Salz und Pfeffer abschmecken.
[–]
<file_sep>---
title: Griechischer Salat
date: 2015-05-18
tags:
- lowcarb
- highfat
aliases:
- ../../salate/griechischer-salat
---
## Zutaten

- 130 g Eisbergsalat (~ ½ Salatkopf)
- 130 g Tomaten
- 180 g Gurke
- 90 g Fenchel
- 75 g rote Zwiebel (~ 1 Zwiebel)
- 200 g Feta
- 75 g Oliven (~ 1 Hand voll)
- 4 EL Olivenöl
- Oregano
## Zubereitung
Salat, Fenchel, Tomaten und Gurke waschen und abtropfen lassen. Den Salat in kleine Streifen schneiden, die Tomaten achteln, die Gurke längs halbieren und in dicke Scheiben schneiden, den Fenchel und die Zwiebel in dünne Halbringe schneiden. Den Feta in kleine Würfel schneiden oder einfach zerkrümeln.
Alles zusammen mit den Oliven in eine Schüssel geben und das Olivenöl unterheben und Oregano darüberstreuen.
<file_sep>---
title: Eier im Hackfleischnest
date: 2015-09-27
tags:
- lowcarb
aliases:
- ../../hauptgerichte/eier-im-hackfleischnest
---
## Zutaten für 2 Portionen

- 400 g Hackfleisch
- 2 Ei(er)
- 1 Zwiebel(n), gewürfelt
- 1 Knoblauch (Zehen)
- ½ EL Tomatenmark
- ¼ TL Paprikapulver
- ¼ TL Pfeffer
- ½ EL Salz
## Zubereitung
Das Fleisch mit allen Zutaten außer Ei und Paprika mischen und gut durchkneten.
4 ovale Klößchen formen, in der Mitte eine Vertiefung eindrücken und jeweils ein rohes Ei hineingeben. Mit Paprikapulver bestreuen, in eine gefettete Auflaufform setzen und im Ofen bei 200 Grad ca. 30 min. backen.
Dazu passt Schmorgurke oder Brechbohnen.
<file_sep>---
title: Ketchup
date: 2015-11-16
tags:
- lowcarb
aliases:
- ../../beilagen/ketchup
---
## Zutaten
- 2 EL Olivenöl
- 1 Zwiebel
- 1 Knoblauchzehe
- 2 Dosen stückige Tomaten
- 100 g Tomatenmark
- ½ TL Cayennepfeffer
- 3 EL Weißweinessig
- 3 EL Rosinen
- 1 Apfel
- 3 EL Kokosblütenzucker
- Salz & Pfeffer
## Zubereitung
Die Zwiebel und die Knoblauchzehe abziehen und kleinhacken. Den Apfel entkernen und in kleine Stücke hacken.
Das Olivenöl in einem Topf erzhitzen und die Zwiebel und die Knoblauchzehe hinzugeben. Anschwitzen, bis die Zwiebelstücke glasig werden. Die restlichen Zutaten hinzugeben und alles ca. 30 Minuten köcheln lassen, bis die Konsistenz etwas dicker geworden ist.
Anschließend mit Salz, Pfeffer und Kokosblütenzucker abschmecken.
Abkühlen lassen und in ein Einmachglas abfüllen.
<file_sep>---
title: <NAME>
date: 2017-01-04
lastmod: 2022-08-30
tags:
- lowcarb
- simple
cookTime: PT28M
aliases:
- ../../hauptgerichte/cowboy-bohnen
---

## Zutaten für 2 Portionen
- 2 Knoblauchzehen
- 1 Zwiebel
- 1 Chilischote
- 2 EL Olivenöl
- 100g Speckwürfel oder Baconstreifen
- 1 Dose Kidneybohnen
- 1 Dose weiße Bohnen
- 1 Dose geschälte Tomaten
- Paprikapulver
- Salz & Pfeffer
## Zubereitung
1. Zwiebel und Knoblauchzehen abziehen, Zwiebel in Halbringe schneiden, Knoblauch zerdrücken.
2. Chilischote klein hacken und mit Zwiebeln, Knoblauch und dem Öl in einem Topf langsam erhitzen.
3. Speck oder Bacon hinzugeben und anbraten.
4. Auf mittlere Hitze reduzieren, Bohnen mit in den Topf geben und ebenfalls leicht anbraten.
5. Mit den Tomaten ablöschen und das Ganze nochmal für 10 Minuten köcheln lassen.
6. Mit Paprikapulver, Salz und Pfeffer abschmecken.
Vielleicht noch mit einem Spritzer Zitrone ergänzen und nach Belieben noch mit frischen Kräutern abrunden. Dazu passen natürlich hervorragend Eier!
<file_sep>---
title: "Über diese Seite"
layout: simple
---
## Motivation
Warum schon wieder eine weitere Rezeptsammlung? Es gibt bereits eine Bazillion Rezeptseiten und alle möglichen Online-Dienste und Apps, mit denen man seine Lieblingsrezepte verwalten kann.
Ich will Rezepte ohne Werbung, ohne Push-Benachrichtigungen, ohne Registrierung, ohne Newsletter-Anmelde-Pop-Ups und all das andere nervige Zeug.
Außerdem müssen die meisten beliebten Rezept-Blogs immer erst ihre ganze Lebensgeschichte erzählen, bevor sie endlich auf den Punkt kommen und ein "einfaches" Rezept präsentieren.
Ich will Rezepte als eine Sammlung von simplen Schritt-für-Schritt-Anleitungen in einfachem Markdown, die sich leicht durchsuchen und bearbeiten lassen, garniert mit ein paar Metadaten und einem Hauch von zusätzlichem Inhalt, der auf Besonderheiten und Variationen hinweist.
## Technischer Hintergrund
Ich bin überzeugt von der Idee von Open Source und der Verbreitung von Wissen für die Öffentlichkeit. Ich denke, dass Rezepte keine Ausnahme sind und für alle zugänglich sein sollten. Deswegen ist der Quelltext für diese Rezeptsammlung Open Source.
Ihr findet den Quelltext und die Installationsleitung auf [GitHub](https://github.com/skoenig/kochbuch).
Wenn ihr Fehler findet oder Verbesserungsvorschläge habt, reicht gerne ein [Issue](https://github.com/skoenig/kochbuch/issues/new) ein. Es gilt die [UNLICENSE](/LICENSE.txt).
<file_sep>---
title: Spargelauflauf
date: 2014-02-18
tags:
- lowcarb
aliases:
- ../../hauptgerichte/spargelauflauf
---
## Zutaten

- 300g Spargelstücke aus der Dose
- 100g Frischkäse 0,8% Fett
- 250g Putenbrust alternativ auch Lachs oder Schinken
- 2 x Eiweiß
- 2 x Eigelb
## Zubereitung
Spargel abtropfen lassen. Pute in Streifen schneiden. Eier trennen und Eiweiss steiff schlagen. Eigelb mit Frischkäse und Gewürzen verquirlen. Eiweiss unter die Masse unterheben Spargel und Putenstreifen in einer Auflaufform verteilen und Masse drübergiessen. Ofen 200°C vorheizen und ca 30 min. in den Ofen.
Passt auch gut zu Kartoffeln!
Ergibt 2 Portionen.
## Nährwerte
- EW: 80g
- KH: 15g
- Fett: 12g
<file_sep>---
title: Cremiges Kichererbsen Curry
date: 2021-04-03
lastmod: 2023-07-28
tags:
- lowcarb
- simple
- schnell
- curry
- vegan
- veggie
aliases:
- ../../hauptgerichte/cremiges-kichererbsen-curry
---

## Zutaten für 2 Portionen
- ½ Tasse (117 ml) gewürfelte rote Zwiebeln
- 1 Knoblauchzehe gehackt
- 2 cm Ingwer
- 2 EL Olivenöl
- 1 EL Currypulver
- 1 TL gemahlener Koriander
- ¼ TL gemahlener Kreuzkümmel
- ¼ TL Paprika
- ¼ TL Chilipulver
- 2 Dosen a 400g Kichererbsen, abgetropft und abgespült
- 1 Dose a 400g gehackte Tomaten
- 100 ml Kokosnussmilch aus der Dose
- 2 Handvoll frischer Babyspinat
- Salz & Pfeffer zum Abschmecken
- Garnierung: frischer Koriander
## Zubereitung
1. Zwiebeln abziehen und würfeln. Knoblauch abziehen, Ingwer schälen und beides klein hacken.
1. Olivenöl in einer großen Pfanne bei mittlerer bis hoher Hitze erhitzen. Zwiebeln darin 1 Minute anbraten.
1. Knoblauch und Ingwer dazugeben und eine weitere Minute anbraten.
1. Currypulver, Koriander, Kreuzkümmel, Paprika und Chilipulver hinzugeben. Umrühren und 30 Sekunden lang anbraten.
1. Die Kichererbsen, die gehackten Tomaten und die Kokosmilch hinzufügen, zum Kochen bringen und 5 Minuten kochen, dabei häufig umrühren.
1. Mit Salz und Pfeffer abschmecken und den Spinat unterheben. Umrühren und eine weitere Minute kochen.
1. Mit frischem Koriander garnieren.
Das Curry kann pur serviert werden, als auch mit gekochtem Quinoa oder Naturreis als Beilage.
<file_sep>---
title: Low Carb Snickers
date: 2015-07-31
tags:
- lowcarb
- highfat
aliases:
- ../../desserts/low-carb-snickers
---
## Zutaten

- 100 g gesalzene Erdnüsse
- 100 g ungesalzene Erdnüsse
- 200 g stückige Erdnussbutter ohne Zuckerzusatz
- 25 g Butter
- 2 EL Stevia oder ähnlicher Süßstoff in Pulverform
- 1 Msp. Vanillepulver
- 200 g dunkle Schokolade (min. 80% Kakaoanteil)
- 1 EL Kokosöl
## Zubereitung
Die Nüsse grob hacken. Erdnussbutter in einem Topf schmelzen, Butter, die gehackten Nüsse, den Süßstoff und die Vanille hinzufügen und gut vermischen.
Eine Kastenform mit Frischhaltefolie auslegen, die Masse hineinfüllen und im Gefrierschrank kalt stellen, bis sie schnittfest ist. Die Masse mit einem scharfen Messer in Riegel schneiden und auf einem Teller mit Backpapier ausbreiten.
Die Schokolade mit Kokosöl in einem Wasserbad schmelzen und die geschmolzene Schokolade mit einem Glasierpinsel auf die Riegel auftragen. Alternativ kann man die Riegel auch vorsichtig mit zwei Gabeln in die flüssige Schokolade tauchen.
Das ganze dann vor dem Servieren im Kühlschrank abkühlen lassen.
<file_sep>---
title: Gefüllte Paprika
date: 2019-05-31
tags:
- lowcarb
aliases:
- ../../hauptgerichte/gefüllte-paprika
---

## Zutaten für 2 Portionen
- 1 größere Paprika
- 2 Zwiebel
- 1-2 Karotten (je nach Größe)
- Tomatenmark
- 200g Tartar
- Salz & Pfeffer
- fettarmer Tzatziki (evtl. selbstgemacht aus Magerquark)
## Zubereitung
Gemüse putzen und schälen, die Paprika dabei in zwei Hälften schneiden, Kerne entfernen damit schön viel Platz ist.
Karotten und Ziebel in kleine Würfel schneiden und bei mittlerer Hitze anschwitzen. Bei fast glasigen Zwiebeln das Tartar hinzu und scharf anbraten. Abschliessend mit einem kräftigen Stoß Tomatenmark ablöschen. Nachträglich salzen und pfeffern.
Das Tartar dann in die Paprika-Hälften geben diese wieder in die Pfanne legen, Deckel drauf und bei geringer Hitze 5-10 Minuten garen, damit die Paprika etwas weicher wird.
Zum Servieren den Tzatziki darauf geben.
<file_sep>---
title: Schokopralinen mit Kokos
date: 2016-06-29
tags:
- lowcarb
- highfat
aliases:
- ../../desserts/schokopralinen-mit-kokos
---


## Zutaten für etwa 12 Stück
- 100 g dunkle Schokolade (> 80% Kakaoanteil)
- 50 g Sahne
- ½ TL Vanillepulver
- 2 TL Kokosblütenzucker
- 2 EL Kokosraspel
- etwas Salz
## Zubereitung
Die Schokolade im Wasserbad zum Schmelzen bringen und die Sahne mit Vanillepulver, Kokosblütenzucke, Salz und 1 EL Kokosraspeln verrühren.
Die geschmolze Schokolade unterheben und ordentlich durchmischen, die Masse sollte augenblicklich deutlich fester werden.
Noch etwas stehen lassen, damit sie fester wird und sich besser formen lässt.
Dann mit den Händen zu kleinen Kugeln formen, auf einen großen Teller mit Backpapier legen und nochmals in etwas Kokosblütenzucker rollen.
Dann wieder in den Kühlschrank stellen.
<file_sep>---
title: Pak Choi Paprika Pfanne
date: '2022-02-19'
servings: 2
tags: simple
cookTime: PT15M
aliases:
- ../../hauptgerichte/pak-choi-paprika-pfanne
---
## Zutaten
- some gehacketen Frühlingszwiebeln
- some Pak Choi
- 0.5 Blumenkohl
- some Chiliflocken
- 2 rote und gelbe Paprika
- 1 Knoblauchzehe
- etwas Öl
- some Sesamöl
- some Limettensaft
- some Salz
- 3 Eier
- some Sojasoße
- 1 Zwiebel
## Zubehör
- Pfanne
## Zubereitung
1. Die rote und gelbe Paprika putzen, waschen und in Streifen schneiden. Zwiebel schälen und in Streifen schneiden. Knoblauchzehe schälen und hacken. Alles in einer Pfanne mit Öl anbraten.
[Knoblauchzehe: 1; Zwiebel: 1; rote und gelbe Paprika: 2; Öl: etwas]
2. Inzwischen Blumenkohl zu [Blumenkohlreis]({{< relref "Blumenkohlreis" >}}) verarbeiten.
[Blumenkohl: 0.5]
3. Das Gemüse in der Pfanne mit Salz und Chiliflocken würzen und den Pak Choi hinzugeben und ein bisschen zusammenfallen lassen.
[Chiliflocken: some; Pak Choi: some; Salz: some]
4. Eier hineinschlagen und durchrühren, dann den Blumenkohlreis mit in die Pfanne geben.
[Eier: 3]
5. Mit Sojasoße, Sesamöl und Limettensaft abschmecken.
[Limettensaft: some; Sesamöl: some; Sojasoße: some]
6. In Schüsseln anrichten und mit ein gehacketen Frühlingszwiebeln garnieren.
[gehacketen Frühlingszwiebeln: some]
<file_sep>---
title: Puten Gyros mit Frischkäse
date: 2018-05-06
aliases:
- ../../hauptgerichte/puten-gyros-mit-frischkäse
---
## Zutaten für 1 Portion
- 200g Pute
- Salz & Pfeffer
- <NAME> nach Belieben
- Sojasoße
- 1 Zwiebel
- 2 EL Frischkäse
- Basilikum
- Thymian
- Sambal Olek
## Zubereitung
Putenfleisch in kleine dünne Streifen schneiden. Man gibt diese Streifen in eine Schüssel, salzt und pfeffert diese, evtl. noch etwas <NAME>ffer hinzufügen. Dann 2-3 Esslö<NAME> dazu und das ganze gut durchkneten. Mindestens 20 Minuten marinieren lassen.
Die Zwiebel in grob schneiden und zusammen mit der Pute in einer Pfanne anbraten. Dann das Sambal Olek unterrühren. Die Hitze reduzieren und den Frischkäse, Thymian und Basillikum mit in die Pfanne geben. Gut durchrühren und noch etwas reduzieren lassen.
Dazu passt [Blumenkohlreis]({{< relref "Blumenkohlreis" >}})
<file_sep>---
title: Ingwer Hühnchen Salat
date: 2020-10-31
tags:
- lowcarb
- simple
aliases:
- ../../salate/ingwer-hühnchen-salat
---

## Zutaten für 2 Personen
- 150g Blattsalat
- 1 gelbe Paprikaschote
- 1 Karotte
- 150 g Champignons
- 1 großer Apfel
- 400 g Hühnchenbrust
- 1 Knoblauchzehe
- 6cm Ingwer
- 7 EL Olivenöl
- 3 EL Sojasauce
- ½ TL Sambal Oelek
- 6 EL Hühnerbrühe
- Salz & Pfeffer
- 1 EL Essig
## Zubereitung
1. Salat zerpflücken, waschen, trockenschleudern und in mundgerechte Stücke zupfen
2. Paprikaschote entkernen und in feine Streifen schneiden
3. Karotte schälen und in dünne Scheiben schneiden
4. Salat, Paprika und Karottenscheiben auf Tellern anrichten
5. Champignons putzen und vierteln
7. Apfel waschen, vierteln, entkernen und in feine Spalten schneiden
6. Fleisch in dünne Scheiben schneiden
8. Knoblauch schälen und kleinhacken
9. Ingwer schälen und kleinhacken
10. 3 EL Öl in einer Pfanne erhitzen, Fleisch scharf anbraten
11. Apfel und Pilze hinzugeben, 3 Minuten braten
12. Ingwer und Knoblauch hinzugeben, Sojasauce, Sambal Oelek und Brühe unterrühren, mit Salz und Pfeffer abschmecken
13. bei mittlerer Hitze für 4 Minuten köcheln lassen
14. Essig und restliches Öl unterrühren und über den Salat geben
<file_sep>---
title: Gebackener Lachs
date: 2018-07-25
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/gebackener-lachs
---
## Zutaten für 4 Portionen
- 4 Lachsfilets
- 1 Zitrone (unbehandelt)
- Salz & Pfeffer
- Öl
## Zubereitung
Den Backofen auf 180 ℃ vorheizen. Eine Auflaufform mit etwas Öl einfetten. Die Lachsfilets abspülen und trockentupfen, in die Form legen und mit Salz & Pfeffer würzen. Für 25 Minuten backen. Die Schale der Zitrone mit einer Küchenreibe abreiben. Die Lachsfilets zusammen mit [Zucchini-Spaghetti]({{< relref "Zucchini-Spaghetti" >}}) und Petersilienpesto anrichten und mit dem Zitronenabrieb bestreuen.
<file_sep>---
title: Hähnchenpfanne mit Erbsen und Ajvar
date: 2017-03-25
lastmod: 2022-07-16
tags:
- lowcarb
- simple
aliases:
- ../../hauptgerichte/hähnchenpfanne-mit-erbsen-und-ajvar
---
Dieses Rezept ist nicht nur lecker, sondern auch super-simpel: es besteht nur aus einer handvoll Zutaten, die einfach nacheinander in die Pfanne gegeben werden. Statt Hähnchen kann hier auch Hackfleisch oder Schweinegeschnetzeltes verwendet werden.

## Zutaten für 2 Portionen
- 1 Zwiebel
- 400g Hähnchen
- Salz & Pfeffer
- 1 EL Ajvar, möglichst dickflüssig
- 1 Dose Erbsen (375g)
## Zubereitung
1. Die Zwiebeln abziehen und in kleine Würfel hacken.
1. Zusammen mit dem Fleisch in einer Pfanne in Öl anbraten.
1. Mit Salz und Pfeffer würzen und die Erbsen mit in die Pfanne geben.
1. Dann den Ajvar dazugeben, Herd ausmachen, Deckel drauf und 10 Minuten ziehen lassen.
<file_sep>---
title: Brokkolisalat
date: 2016-12-16
tags:
- lowcarb
- simple
aliases:
- ../../salate/brokkolisalat
---
## Zutaten

- Brokkoli
- Schinken oder Speckwürfel
- Frühlingszwiebeln
- Käse gerieben
- 1 Becher Joghurt
- 1 Becher <NAME>
- 1 EL Essig
- etwas Süßstoff
- evtl. Kräuter
- Salz & Pfeffer
## Zubereitung
Den Brokkoli in waschen, schniden und kurz in Salzwasser garen und abrtopfen lassen.
Jogurt, Sahne, Essig, Süßstoff und die Kräuter zu einer Marinade verrühren.
Schinken- oder Speckwürfel in einer Pfanne rösten. Frühlingszwiebeln waschen, in Ringe schneiden und dazugeben. Den Brokkoli untermischen und nach 1-2 Minuten vom Herd nehmen und etwas Käse drüber reiben.
Die gewünschte Menge Marinade über dem Brokkolisalat verteilen und servieren.
<file_sep>---
title: Beilagen
layout: index
order: date
reverse: true
---
<file_sep>---
title: Risotto mit Bacon und Pilzen
date: 2015-10-23
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/risotto-mit-bacon-und-pilzen
---

## Zutaten für 4 Portionen
- 300 g Bacon (Frühstücksspeck)
- 200 g Champignons
- 50 g Butter
- 1 Schalotte
- 1 Knoblauchzehe
- 1 <NAME>
- 500 g [Blumenkohlreis]({{< relref "Blumenkohlreis" >}})
- 400 g Schlagsahne
- 1 Eigelb
- 100 g Parmesan
- Petersilie
## Zubereitung
Den Bacon und die Champignons in kleinere Stücke schneiden. Den Bacon in einer Pfanne ohne Fett anbraten, bis er etwas Saft abgegeben hat, dann die Pilze hinzufügen und ca. 7 Minuten braten.
Die Schalotte und Knoblauchzehe pellen, kleinhacken und mit der Butter in einer weiteren Pfanne anschwitzen. Den Weißwein hinzufügen, aufkochen lassen und ca. 5 Minuten köcheln lassen. Den [Blumenkohlreis]({{< relref "Blumenkohlreis" >}}) und die Hälfte der Schlagsahne hinzugfügen und solange kochen, bis die Sahne zu einer dicken Sauce geworden ist.
Die restliche Sahne hinzufügen und die Sauce wieder einkochen lassen, bis sie eine dicke Konsistenz hat.
Die Pfanne vom Herd nehmen und das Eigelb mit dem Parmesan unterrühren. Den Bacon und die Champignons unter das fertige Risotto heben und zum Servieren die Petersilie darüberstreuen.
## Nährwerte pro Portion
- kcal: 821
- KH: 15g
- Fett: 68g
- EW: 28g
<file_sep>---
title: Blumenkohlreis
date: 2015-05-16
tags:
- lowcarb
- highfat
aliases:
- ../../beilagen/blumenkohlreis
---

## Zutaten
- Blumenkohl frisch (ca. 150 g für eine Portion)
## Zubereitung
Den Blumenkohl waschen, abtropfen lassen und durch eine Käsereibe in eine Schüssel reiben. Die Brösel mit kochendem Wasser übergießen und 2 Minuten ziehen lassen. Dann das Wasser durch ein Sieb abgießen.
<file_sep>---
title: Matcha Minz Erbsensuppe mit Garnelen
date: 2020-09-16
tags:
- lowcarb
aliases:
- ../../hauptgerichte/matcha-minz-erbsensuppe-mit-garnelen
---
## Zutaten für 2 Portionen
- 200 g Garnelen
- 400 g Bio Tiefkühlerbsen
- 300 ml Wasser
- 1 Zwiebel
- 1 TL gekörnte Gemüsebrühe
- 100 ml Sahne oder Kokosmilch
- 2 g Matcha Pulver
- ½ Teebeutel Pfefferminztee
- 1 EL Olivenöl
- Pfeffer & Salz
## Zubereitung
1. Die Bio Tiefkühlerbsen mit Wasser in einen Topf geben, aufkochen lassen und die Bio Gemüsebrühe einrühren. Auf mittlerer Flamme 10 bis 15 Minuten köcheln, bis die Bio Tiefkühlerbsen gar sind.
2. Nun mit Sahne aufgießen und mit einem Passierstab sämig pürieren. Aufkochen, dann die Hälfte des Matcha Pulvers und den halben Beutel Pfefferminztee einrühren. Mit etwas Pfeffer und - falls nicht würzig genug - etwas Salz abschmecken.
3. Die Zwiebel schälen und fein würfeln. Garnelen kalt waschen und trocknen. Olivenöl in einer Pfanne erhitzen, Zwiebeln und Garnelen darin braten, leicht salzen und pfeffern.
4. Die Matcha Minz-Erbsensuppe in Teller oder Schalen füllen, Garnelen dazugeben und mit dem restlichen Matcha bestäuben und genießen.
<file_sep>---
title: Falscher Kartoffelsalat
date: 2015-12-02
tags:
- lowcarb
aliases:
- ../../salate/falscher-kartoffelsalat
---
Ein Kartoffelsalat-Ersatz mit wenig Kohlenhydraten (knapp 4 %), lässt sich aus der Steckrübe zaubern. Er schmeckt zwar minimal süsser als die klassische Variante, ist ihr in der Konsistenz aber sehr ähnlich.

## Zutaten für 2 Portionen
- 1 Steckrübe (~ 550g)
- 3 g Gemüsebrühe
- 60 g Schinkenspeck
- 1 EL Apfelessig
- 1 EL Sonnenblumenöl
- 1 EL Petersilie (fein gehackt)
- 50 g Mayonnaise
- Pfeffer
- Muskatnuss
## Zubereitung
Die Steckrübe waschen, schälen, entsprechend schneiden, mit etwas Wasser und Gemüsebrühe in einen Topf geben, bei mittlerer bis hoher Hitze bis zur gewünschten Bissfeste garen (ca. 12 Minuten), abgießen und abkühlen lassen.
Den Schinkenspeck würfeln und in der Pfanne anbraten, bis er schön knusprig ist.
Die Steckrüben mit dem Schinkenspeck, dem Apfelessig, dem Öl, der Mayonnaise und der Petersilie gut vermischen. Mit einer Prise Muskatnuss und Pfeffer abschmecken und Servieren.
## Nährwerte
- kcal: 353
- KH: 12g
- Fett: 28g
- EW: 11g
<file_sep>---
title: Magerquark mit Mandeln
date: 2015-09-26
tags:
- lowcarb
- highfat
aliases:
- ../../snacks-und-shakes/magerquark-mit-mandeln
---
## Zutaten für 4 Portionen

- 500 g Magerquark
- 250 g Jogurt
- 250 g Sauerrahm (10 oder 15% Fett)
- 100 g Mandelsplitter
- 5 g Stevia
- zusätzlich n.B. Mandelmuß / Mandelmehl / Mandelaroma
## Zubereitung
Denkbar einfach: alles vermengen und kalt stellen.
## Nährwerte pro Portion
- kcal: 405
- KH: 10 g
- EW: 25 g
- Fett: 29 g
<file_sep>---
title: Eier en Cocotte
date: 2018-07-23
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/eier-en-cocotte
---

## Zutaten für 4 Stück
- 200g Frühstücksspeck
- 1 Zwiebel
- 100 g Parmesan, gerieben
- Salz & Pfeffer
- 4 Eier
- Schnittlauch
- Butter oder Kokosöl für die Förmchen
## Zubereitung
Backofen auf 200 Grad vorheizen. Währenddessen den Frühstücksspeck und die Zwiebel klein schneiden, beides bei mittlerer Temperatur in der Pfanne anbraten.
4 Förmchen mit dem Fett einfetten, den Speck und die Zwiebeln darin verteilen und den Parmesan, Salz und Pfeffer dazugeben.
In jedes Förmchen ein Ei schlagen, diese dann auf mittlerer Schiene in den Backofen geben, 15 Minuten backen.
Beim Servieren etwas Schnittlauch darüber geben.
Dazu passt Knäckebrot sehr gut.
<file_sep>---
title: Zigeuner Wurstpfanne
date: 2019-05-07
tags:
- simple
aliases:
- ../../hauptgerichte/zigeuner-wurstpfanne
---

## Zutaten für 2 Portionen
- 3 Paprika; z.B. rot, gelb und grün
- 1/2 Zwiebel
- 4 Würstchen
- 1 Dose gehackte Tomaten
- 1 EL Öl
- Paprikapulver, Kräuter nach Belieben, Salz & Pfeffer
## Zubereitung
Paprika in Streifen schneiden. Zwiebel fein würfeln. Würstchen in Scheiben schneiden. Öl in einer beschichteten Pfanne erhitzen. Wurst darin goldbraun braten. Zwiebel und Paprika zugeben, andünsten. Gehackte Tomaten dazugeben, alles aufkochen und ca. 5 Minuten köcheln lassen. Mit den Gewürzen abschmecken.
<file_sep>---
title: Gemüseauflauf mit Mozarella
date: 2017-03-15
tags:
- veggie
- lowcarb
aliases:
- ../../hauptgerichte/gemüseauflauf-mit-mozarella
---
## Zutaten für 3 Portionen
- 2 mittelgroße Karotten
- 1 große Zwiebel
- 1 Kohlrabi
- 1 rote Paprikaschote
- 2 Tomaten
- 1 Zucchini
- 1 Knoblauchzehe
- ein Bund Basilikum oder 2 EL getrockneter Basilikum
- 5 EL Öl, z.B. Rapsöl
- 2 Mozzarella
- etwas Fett für die Auflaufform
- Salz & Pfeffer
## Zubereitung
Die Karotten, den Kohlrabi und die Zwiebel schälen. Die Karotten und den Kohlrabi in sehr feine Scheiben hobeln, die Zwiebel halbieren und der Länge nach in Streifen schneiden. Karotten, Kohlrabi und Zwiebel in eine Schüssel geben, gut vermengen und vorerst zur Seite stellen.
Nun die Paprikaschote, die Tomaten und die Zucchini waschen. Paprika vierteln, dann die Viertel quer in ca. 0,5 cm breite Streifen schneiden. Tomaten und Zucchini in ca. 0,5 cm breite Scheiben schneiden und auch erst mal zur Seite stellen.
Das Öl in ein Glas oder eine Tasse geben, die Knoblauchzehe schälen und durch eine Knoblauchpresse in das Öl geben. Den Basilikum fein hacken, ebenfalls untermischen.
Eine Auflaufform gut einfetten und den Backofen auf 225°C vorheizen.

Nun das vorbereitete Gemüse in die Auflaufform geben. Den Boden mit der Mischung aus Karotten, Kohlrabi und Zwiebeln bedecken, kräftig mit Salz und frisch gemahlenem Pfeffer würzen und mit etwas Basilikum-Knoblauch-Öl beträufeln.

Dann Paprika, Zucchini und Tomaten gleichmäßig darüber verteilen, noch mal mit Pfeffer würzen und mit dem restlichen Basilikum-Knoblauch-Öl beträufeln.
Zum Schluss den in Scheiben geschnittenen Mozzarella auf dem Auflauf verteilen und alles für 30-35 Minuten auf der mittleren Schiene backen.

<file_sep>---
title: Rote Beete Walnuss Crumble
date: 2022-01-02
tags:
- veggie
aliases:
- ../../beilagen/rote-beete-walnuss-crumble
---
Dieses Crumble aus Walnüssen und Roter Beete passt super als Beilage zu Eiern, Salaten oder als Brotaufstrich.
## Zutaten
- 1 frische Rote Bete
- 120 g Walnüsse
- 50 g Sonnenblumenkerne oder Kürbiskerne
- 2 EL Olivenöl
- Salz & Pfeffer
## Zubereitung
1. Rote Beete grob würfeln
2. Dann mit den Walnüssen, Kernen, 1 TL Salz und Olivenöl in einen Mixer geben und so lange mixen, bis eine gleichmäßige aber leicht bröselige Masse entstanden ist
<file_sep>---
title: Kartoffel Erbsen Stampf
date: 2019-03-24
tags:
- veggie
aliases:
- ../../beilagen/kartoffel-erbsen-stampf
---
## Zutaten
- 400 g Kartoffeln oder Süßkartoffeln
- 150 g TK Erbsen
- 50 ml Milch
- Salz
## Zubereitung
Kartoffeln schälen und in Salzwasser 15 Minuten zugedeckt kochen. Dann die Erbsen zu den Kartoffeln geben und weitere 5 Minuten kochen.
Kartoffeln und Erbsen abgießen und mit einem Kartoffelstampfer zerdrücken, dabei die Milch unterheben.
Wenn man keinen Kartoffelstampfer hat, kann man stattdessen eine Konservendose, Wasserflasche, Kaffeebecher, die Olivenölflasche nehmen, also alles, was sich abwaschen lässt und einen glatten Boden hat. Oder man nimmt einfach eine Gabel.
Wer möchte, kann noch Kräuter wie Kresse oder Petersilie dazugeben.
<file_sep>---
title: Eiergratin mit Garnelen
date: 2020-12-20
tags:
- lowcarb
aliases:
- ../../hauptgerichte/eiergratin-mit-garnelen
---
## Zutaten für 2 Portionen
- 150g Garnelen
- 5 Eier
- 1 Schalotte oder ½ Zwiebel
- 1 TL Majoran
- 1 EL Butter
- 50g Schlagsahne
- geriebene Muskatnuss
- 100g Fetakäse
- Salz & Pfeffer
## Zubereitung
1. Die Garnelen auftauen, abspülen und ggf. schälen.
2. Backofen auf 250℃ vorheizen.
2. 4 Eier 10 Minuten hart kochen, pellen, in Scheiben schneiden und in zwei Schalen schichten.
3. Währenddessen die Zwiebel oder Schalotte putzen, kleinschneiden und mit dem Majoran in der Pfanne mit der Butter etwas andünsten.
4. Die Garnelen ebenfalls in die Pfanne geben und bei starker Hitze kurz anbraten, mit etwas Pfeffer und Salz würzen und dann zu den Eiern in die Schalen geben.
5. Das übrige Ei mit der Sahne verrühren, mit dem Muskat würzen und das Ganze dann über die Garnelen und Eier geben.
6. Den Feta würfeln und in den Schalen verteilen und im Backofen für ca. 7 Minuten backen, bis die Oberfläche leicht gebräunt ist.
<file_sep>---
title: Gebratener <NAME>is mit Schweinefleisch
date: 2015-11-30
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/gebratener-thai-blumenkohlreis-mit-schweinefleisch
---


## Zutaten für 2 Portionen
- 600 g Schweinefleisch
- 3 EL Hühnerbrühe
- 2 EL Fischsauce
- 3 EL Tamari (glutenfreie Sojasauce)
- 5 Knoblauchzehen
- 1 EL Limettensaft
- 1 TL Kokosblütenzucker
- 1 Chilischote
- 4 Frülingszwiebeln
- 1 Stange Staudensellerie
- 2 cm Ingwer
- 2 Eier
- 500 g [Blumenkohlreis]({{< relref "Blumenkohlreis" >}})
- Kokosöl zum Braten
## Zubereitung
Das Schweinefleisch in Würfel schneiden, den Knoblauch pellen und klein hacken. Die Hühnerbrühe, Fischsauce, 2 EL Tamari, ⅖ der Knoblauchzehen, den Limettensaft und den Kokosblütenzucker zu einer Marinate vermischen. Das Schweinefleisch darin wenden und ziehen lassen.
Die Chilischote fein hacken, die Frülingszwiebeln und den Staudensellerie wachen und kleinschneiden, den Ingwer kleinreiben. Kokosöl in einer Pfanne oder Wok erhitzen und den restlichen Knoblauch, Chili und Ingwer kurz anbraten. Das Schweinefleisch und die Marinade hinzufügen und ca. 10 Minuten braten. Dann die Frülingszwiebeln und Sellerie unterrühren, 1 EL Tamari hinzugeben und das Ganze einige Minuten köcheln lassen.
Kokosöl in einer weiteren Pfanne erhitzen, die Eier hineinschlagen, den [Blumenkohlreis]({{< relref "Blumenkohlreis" >}}) hinzugeben und alles gut umrühren. Dann den Blumenkohlreis zu dem Fleisch geben und alles noch mal durchmischen.
## Nährwerte pro Portion
- kcal: 1137
- KH: 19g
- Fett: 11g
- EW: 23g
<file_sep>---
title: Avocado Mousse
date: 2015-04-25
tags:
- lowcarb
- veggie
- vegan
aliases:
- ../../beilagen/avocado-mousse
---
## Zutaten
* 1 Avocado (reif, d.h. so dass man sie mit Schale schon gut eindrücken kann)
* 1/2 Zitrone
* 1/4 Zwiebel
* Salz
* Pfeffer
* Kräuter
## Zubereitung
Die Avocado aufschneiden, auslöffeln und das Fruchtfleisch in einer Schüssel pürieren. Danach wird die Zitrone darüber ausgepresst und unter die Masse gemischt (erst einmal sparsam verwenden, nicht alles auspressen). Dann die 1/4 Zwiebel in kleine Teilchen schneiden und zu dem Avocadobrei hinzugeben. Anschliessend gibt man die Kräuter (TK oder frisch) dazu und würzt das alles mit Salz und Pfeffer. Eventuell mit noch etwas mehr Zitrone abschmecken.
Schmeckt hervorragend zu:
* Rührei
* Harzer-Käse (kleingewürfelt im Muß)
* Thunfisch
<file_sep>---
title: Blumenkohlpüree
date: 2016-06-19
tags:
- lowcarb
- highfat
aliases:
- ../../beilagen/blumenkohlpüree
---
## Zutaten für 4 Portionen
- 1 Blumenkohl
- 100g Schlagsahne
- 100g Frischkäse
- 1 EL Butter
- 1 TL Muskatnuss
- Salz & Pfeffer
## Zubereitung
Wasser zum Kochen bringen und salzen. Den Blumenkohl waschen, in kleine Stücke schneiden und ca. 6-8 Minuten kochen. Das Kochwasser abgießen und beiseite stellen. Blumenkohl mit der Schlagsahne, dem Frischkäse und der Butter und evtl. etwas von dem Kochwasser mit dem Pürierstab zerkleinern. Mit Muskatnuss, Salz & Pfeffer abschmecken.
<file_sep>---
title: Quarkkuchen II
date: 2015-08-04
tags:
- lowcarb
- veggie
- protein
aliases:
- ../../desserts/quarkkuchen-ii
---
## Zutaten
- 100g Butter
- 4 Eier
- 100g Proteinpulver
- 250g Quark 40% Fett
- 250 ml Sahne
- 2 EL Süßstoff
- etwas Salz
- evtl dunkle Beeren (z.B. Himbeeren, Erdbeeren, Heidelbeeren)
- etwas Kokosöl für die Form
## Zubereitung
Alle Zutaten mit einem Rührgerät vermengen, bis eine glatte Masse entsteht und in eine gefettete Kastenform geben. Nach Belieben noch dunkle Beeren unterrühren. Die Form mit Alufolie abdecken und in den Ofen schieben.
Die Backzeit beträgt ca 45-50min bei 180°C.
<file_sep>---
title: Käse Tarte
date: 2016-09-16
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/käse-tarte
---

## Zutaten für 4 Portionen
- 2 EL Sesam
- 180g Mandelmehl
- 1 EL Flohsamenschalen
- 40 g Butter
- 4 Eier
- 1 TL Salz
- Butter oder Kokosöl zum Einfetten der Form
- 200g Sahne
- 1 TL Oregano
- 300g geriebener Käse
- 150g getrocknete Tomaten in Öl
## Zubereitung
Für den Teig Sesam in der Küchenmaschine oder mit dem Pürierstab zu Mehl mahlen und mit dem Mandelmehl, den Flohsamenschalen, der geschmolzenen Butter, einem Ei und den Salz verrühren. Eine Backform (ca. 20 cm Durchmesser) einfetten, den Teig in die Form drücken und mit einer Gabel ein paar Mal einstechen. 30 min. im Kühlschrank ruhen lassen. Backofen auf 180 ℃ vorheizen.
Den Boden dann 10 min. backen, dann herausnehmen und die Temperatur auf 200 ℃ erhöhen.
Die restlichen 3 Eier mit der Sahne und Oregano verrühren. Den geriebenen Käse auf dem Tarte-Boden verteilen und die Eier darübergeben. Die Tomaten darauf verteilen und die Tarte dann auf der unteren Schiene für weitere 25 min. backen.
Die Tarte mit einem der leichten [/Salate] anrichten und servieren.
<file_sep>---
title: Puten Erdnuss Wok
date: 2015-10-05
tags:
- lowcarb
aliases:
- ../../hauptgerichte/puten-erdnuss-wok
---
## Zutaten für 2 Portionen

- 400 g Putenbrust
- 2 Paprika
- ½ Zwiebel
- 200 ml Gemüsebrühe
- 1 TL <NAME>elek
- 2 EL Erdnussmuß (keine Erdnussbutter)
- Öl
- evtl. noch einige Erdnüsse
## Zubereitung
Das Öl im Wok erhitzen, Paprika kleinschneiden und im Wok anbraten, dann wieder herausnehmen. Pute in Stücke schneiden, Zwiebel in Ringe und die Erdnüsse kleinhacken. Die Pute im Wok anbraten, Zwiebelringe und kleingehackte Erdnüsse dazu. Wenn alles schon etwas angebraten ist - die Zwiebeln glasig sind, Sambal Oelek und Erdnussmuß dazugeben und kurz darauf das ganze mit der Gemüsebrühe ablöschen.
Die Paprika wieder dazugeben und evtl. bei mittlerer Hitze etwas reduzieren lassen.
<file_sep>---
title: Hähnchen Geschnetzeltes
date: 2017-10-10
tags:
- lowcarb
aliases:
- ../../hauptgerichte/hähnchen-geschnetzeltes
---

## Zutaten für 2 große Portionen
- Hühnerbrust 900g
- Sauerrahm 300g
- Schmelzkäse 200g
- Sonnnenblumenöl 50 ml
- Brokkoli 400g
- Knoblauch
- Salz
- Pfeffer
- Chili
## Zubereitung
Hühnerbrust kleinschneiden, mit Olivenöl und bisschen Knoblauch anbraten, mit Salz, Pfeffer und Chili würzen, Sauerrahm (Saure Sahne), Brokkoliröschen und Schmelzkäse dazu, alles rühren bis der Käse geschmolzen ist - fertig.
## Nährwerte pro Portion
- Kcal: 1232
- Fett: 75 g
- KH: 24 g
- EW: 115 g
<file_sep>---
title: Schichtkohl mit Blutwurst
date: 2020-08-30
lastmod: 2023-05-23 17:00:58
tags:
- lowcarb
- pfanne
- schnell
- simple
aliases:
- ../../hauptgerichte/schichtkohl-mit-blutwurst
---
Ein ähnlich einfaches und leckeres Rezept wie [Schichtkohl mit Hackfleisch]({{< relref schichtkohl-mit-hackfleisch >}}), allerdings wird hier Blutwurst verwendet.
## Zutaten für 4 Portionen
- 1 große Zwiebel
- Öl oder Fett
- 125 ml Gemüsebrühe
- 850 g (½ Kopf) Kohlsorte: Weißkohl, Wirsingkohl, Spitzkohl
- 250 g Kartoffeln
- 200 g Blutwurst
- Salz & Pfeffer
## Zubereitung
1. Die Zwiebel schälen, in kleine Würfel schneiden und in einem großen Topf mit Fett anbraten.
1. Inzwischen den Kohl vom Strunk befreien und in feine Streifen schneiden.
1. Die glasig gedünstete Zwiebel mit der Gemüsebrühe ablöschen und den Weißkohl hinzugeben.
1. Beides ca. 10 Minuten kochen, dann die klein gewürfelte Kartoffel untermischen.
1. Alles nochmal ca. 15 Minuten köcheln lassen, damit die Kartoffel und der Kohl weich wird.
1. Anschließend die klein geschnittene Blutwurst darunter mischen und nochmals kräftig erwärmen.
1. Mit Salz und Pfeffer abschmecken.
<file_sep>---
title: Himbeeromlett
date: 2016-06-11
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/himbeeromlett
---



## Zutaten für 1 Omlett
- 3 Eier
- 1 EL Kokosmilch
- 2 TL Kokoszucker
- ½ TL Vanillepulver
- 2 TL Flohsamenschalen
- 1 EL Kokosraspel
- 50 g Himbeeren oder andere dunkle Beeren
- Kokosfett zum Braten
## Zubereitung
Die Eier mit der Kokosmilch, dem Kokoszucker, und Vanillepulver schaumig schlagen. Die Flohsamenschalen und die Kokosraspel unterrühren.
Das Kokosfett in einer Pfanne bei mittlerer Hitze erwärmen. Die Eiermasse in die Pfanne geben. Während die Ränder des Omletts fest werden, vorsichtig vom Pfannenrand abheben. Die Beeren auf das Omlett geben und in die Eiermasse einsinken lassen. Das Omlett zusammenklappen und fertig braten.
Vor dem Servieren mit Kokosraspeln bestreuen.
<file_sep>---
title: Eiersalat
date: 2016-12-08
tags:
- lowcarb
aliases:
- ../../salate/eiersalat
---
## Zutaten für 3 Portionen

- 6 Eier
- 500 g Magerquark
- 100 g Zwiebeln
- 70 g Gewürzgurken
- 1 Knoblauchzehe
- 6 g Paprikapulver
- 10 g Senf
- Petersilie
- 2 g Salz
- 2 g Pfeffer, Schwarz
## Zubereitung
Die Eier hartkochen, inzwischen die Zwiebeln und die Gewürzgurken in sehr kleine Würfel schneiden. Den Magerquark mit Senf und den restlichen Gewürzen verrühren und abschmecken. Evtl. noch Chili hinzufügen.
Die Eier schälen und in dünne Scheiben schneiden, zusammen mit den Zwiebel- und Gewürzgurkenwürfel und dem Magerquark verrühren.
Bis zum Verzehr kühlstellen.
<file_sep>---
title: Zimtpfannkuchen mit Kokos
date: 2015-06-23
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/zimtpfannkuchen-mit-kokos
---
## Zutaten für 1 Portion
- 2-3 Eier
- 1-2 EL Sahne oder Kokosmilch
- 1 TL Kokosblütenzucker
- 2 TL Zimt
- 1 TL Kardamom
- 1 TL Flohsamenschalen
- 1 EL Kokosraspel oder Mandelmehl
- Butter oder Kokosöl zum Braten
## Zubereitung
Alle Zutaten bis auf das Fett verrühren, diese Masse in eine gefettete Pfanne gießen und zwei Pfannkuchen daraus braten.
<file_sep>---
title: Zucchini Spaghetti
date: 2015-05-16
tags:
- lowcarb
- highfat
aliases:
- ../../beilagen/zucchini-spaghetti
---
## Zutaten für eine Portion
- 1 Zucchini (ca. 800g)
- Salz
## Zubereitung
Die Zucchini waschen und mit einem Spiralschneider oder Kartoffelschäler schälen. Dabei sollten dünne Streifen aus der Zucchinischale abgeschält werden, damit sie eine Spaghetti-ähnliche Konsistenz haben. Die Streifen in ein Sieb geben und mit kochend heißem Wasser übergießen, abtropfen lassen.
<file_sep>---
title: Lachs mit Fetahaube
date: 2015-05-18
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/lachs-mit-fetahaube
---
## Zutaten
- 4 Lachsfilets a 125 g
- 180 g Feta
- 100 g Creme Fraiche
- 1 Knoblauchzehe, gepresst
- evtl. etwas Sahne
- 20 Minzeblätter (~ 1 Hand voll)
- Kokosöl zum einfetten der Form
- Salz & Pfeffer
## Zubereitung
Den Backofen auf 180 Grad vorheizen. Eine Auflaufform mit dem Öl einfetten. Die Lachsfilets abspülen, trockentupgen und in die Form legen, mit Salz und Pfeffer bestreuen.
Den Feta in einer Schale zerdrücken, Creme Fraiche und den Knoblauch hinzufügen und alles gut verrühren. Bei Bedarf mit etwas Sahne verdünnen. Die Minzeblätter waschen und abtropfen lassen, feinhacken und in den Fetamus rühren. Mit Salz und Pfeffer abschmecken.
Das Fetamus auf den Lachsfilets verteilen und auf mittlerer Schiene im Backofen ca. 25 Minuten backen.
Vor dem Servieren mit ein paar weiteren Minzeblätter garnieren.
Dazu passt [Griechischer Salat]({{< relref "Griechischer-Salat" >}})
<file_sep>---
title: <NAME>
date: 2019-03-28
tags:
- lowcarb
- veggie
aliases:
- ../../desserts/mandel-kakao-muffins
---
## Zutaten für 8 Muffins

- 3 Eier
- 130 g Magerquark
- 100 g Mandelmehl
- 10 g Backkakao, ungesüßt
- 1 Pck. Backpulver
- 1 Prise Salz
- Süßstoff nach Geschmack
## Zubereitung
Die Eier trennen, und das Eiweiß mit einer Prise (wirklich nur eine Prise!) Salz steif schlagen.
Eigelb, Mandelmehl, Magerquark, Backpulver, Kakao und den Süßstoff mit dem Mixer verrühren. Den Eischnee unterheben.
Die Masse in 8 Förmchen füllen und bei 150°C ca. 15 Min. backen. Wer keine Papierförmchen benutzt, sollte die Backform noch einfetten.
<file_sep>---
title: Chicoree Pasta
date: 2016-04-09
tags:
- paleo
aliases:
- ../../hauptgerichte/chicoree-pasta
---

## Zutaten für 4 Portionen
- 2 Chicorée
- 1 Birne
- 1 Orange
- 100 g Speck
- 1 Knoblauchzehe
- 1 Schalotte
- 50 g Olivenöl
- 50 g weißer Balsamico
- 50 g Agavensirup
- 200 g Spaghetti
- 2 Zweige Thymian
- 1 Zweig Rosmarin
- Salz und Pfeffer
- Butter, Olivenöl, <NAME>
## Zubereitung
Knoblauch und Schalotte schälen. Knoblauch in feine Blättchen schneiden. Die Schalotte ebenso in feine Würfel schneiden. Birne schälen und vom Kerngehäuse befreien und anschließend in feine Würfel schneiden.
Orange: heiß waschen und die Schale abreiben, schälen, filetieren und den Rest auspressen. Die Filets fein schneiden.
Speck: fein würfeln
Chicorée: Strunk dünn abschneiden, einen Chicorée vierteln und in feine Streifen schneiden; einen weiteren Chicorée vierteln und in 0,5 cm große Blättchen schneiden.
1. in einer tiefen Pfanne Butter und Olivenöl aufschäumen lassen
- die Speckwürfel darin auslassen
- die Knoblauchblättchen dazu geben und mit anbraten, bis sie goldbraun sind
- Schalotten-Stücke dazu geben und glasig anschwitzen
- den fein geschnittenen Chicorée dazugeben und ebenfalls anschwitzen
- Agavensirup dazu und leicht einkochen lassen
- mit weißem Balsamico ablöschen und kurz aufkochen
- Birnenwürfel, Orangenschale und Filets dazugeben
- mit <NAME> abschmecken
- die Spaghetti kochen und nach dem Abgießen sofort in die Chicorée-Pfanne geben und durchschwenken
- zum Schluss die Chicorée-Blättchen, Thymian und Rosmarin dazu geben. Kurz durchschwenken und anrichten
<file_sep>---
title: Gemüse Fladenbrot
date: 2015-11-16
lastmod: 2022-06-02
tags:
- lowcarb
- highfat
aliases:
- ../../beilagen/gemüse-fladenbrot
---

## Zutaten für 8 Stück
- 80 g Haselnüsse oder Walnüsse
- 50 g Sonnenblumenkerne
- ½ Blumenkohl
- 1 Karotte
- 1½ EL Flohsamenschalen
- 2 EL Petersilie
- 60 g geriebener Käse
- 1 TL Thymian
- ½ TL Cayennepfeffer
- 1 TL Salz
## Zubereitung
1. Den Backofen auf 200 ℃ vorheizen und ein Blech mit Backpapier auslegen.
1. Die Nüsse und Sonnenblumenkerne in einer Küchenmaschine zu Mehl verarbeiten.
1. Blumenkohl und Karotte waschen und abtropfen lassen, beides in kleine Stücke schneiden und Portionsweise in der Küchenmaschine kleinhacken.
1. Nach und nach die restlichen Zutaten in die Küchenmaschine geben, und alles zu einem Teig verarbeiten und daraus 8 kleine, dicke Fladenbrote formen.
1. Die Teigbatzen auf das Backpapier legen und im Ofen ca. 20 Minuten backen.
<file_sep>---
title: Beerensmoothie
date: 2015-06-22
tags:
- lowcarb
- highfat
- simple
aliases:
- ../../snacks-und-shakes/beerensmoothie
---
## Zutaten
- 75 g gefrorene Erdbeeren
- 75 g gefrorene Himbeeren
- 150 ml Kokosmilch oder Sahne
- 1 Ei
- 1 TL Kokosblütenzucker
- ¼ TL Vanillepulver
- ½ Zitrone
- Minze, Petersilie oder Basilikum ~ 10 Blätter
## Zubereitung
Die Zitronenschale abreiben, die Kräuterblätter waschen und trockenschütteln. Alles mit einem Pürierstab oder in einem Mixer pürieren. Zum Servieren in ein Glas gießen.
<file_sep>---
title: Low Carbonara
date: 2015-05-16
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/low-carbonara
---
## Zutaten für 4 Portionen

- 3 Karotten
- 1 Zucchini
- 300g Bacon (Frühstücksspeck)
- 300g [Blumenkohlreis]({{< relref "Blumenkohlreis" >}})
- 2 Eigelb
- 300g Schlagsahne
- 150g geriebener Parmesan
- Salz & Pfeffer
- Basilikumblätter
## Zubereitung
Karotten und Zucchini waschen und mit dem Spiralschneider oder Kartoffelschäler in gleichmäßige Streifen schneiden (siehe [Zucchini-Spaghetti]({{< relref "Zucchini-Spaghetti" >}})).
Den Frühstücksspeck in kleine Stücke schneiden und in einer Pfanne ohne Fett knusprig braten, evtl. austretendes Wasser abgießen. Die Zwiebel fein hacken und dazugeben und anbraten.
Den Blumenkohlreis und die Gemüsespiralen dazugeben. Das Eigelb mit der Sahne und dem geriebenen Parmesan verquirlen. Die Mischung in die Pfanne geben und alles kurz aufkochen lassen.
Vor dem Servieren mit wenig Salz und Pfeffer abschmecken, da der Frühstücksspeck bereits sehr salzig ist. Mit Basilikumblättern garnieren.
<file_sep>---
title: Reispfanne Italien Express
tags: simple
date: '2022-05-05'
servings: 2
aliases:
- ../../hauptgerichte/reispfanne-italien-express
---
## Zutaten
- 0.25 Bunds Petersilie
- some Salz und Pfeffer
- 75g Tomaten
- 1,5 ELs Tomatenmark
- 0.25 TLs Gemüsebrühe
- 1 rote Zwiebel
- 2 kg Putenbrust
- 1,5 ELs Öl
- 50 g Feta
- 1 Packung Express Reis
- 200 ml Wasser
- 0.5 rote und gelbe Paprika
## Zubehör
- Pfanne
## Zubereitung
1. Die rote und gelbe Paprika putzen, waschen und in Streifen schneiden. Tomaten waschen und halbieren. Die rote Zwiebel schälen und grob würfeln. Putenbrust waschen, trocken tupfen und grob würfeln.
[Putenbrust: 2 kg; Tomaten: 75g; rote Zwiebel: 1; rote und gelbe Paprika: 0.5]
2. Öl in einer großen Pfanne erhitzen und Putenbrust darin rundherum kräftig anbraten. Mit Salz und Pfeffer würzen, herausnehmen.
[Salz und Pfeffer: some; Öl: 1,5 ELs]
3. Paprika und Zwiebeln im heißen Bratfett ca. 2 Minuten braten. Tomatenmark zugeben, kurz anschwitzen und Wasser angießen. Gemüsebrühe, Express Reis und Pute unterrühren. Aufkochen und zugedeckt ca. 5 minutes köcheln.
[Express Reis: 1 Packung; Gemüsebrühe: 0.25 TLs; Tomatenmark: 1,5 ELs; Wasser: 200 ml]
4. Inzwischen Feta zerbröckeln. Petersilie waschen, trocken schütteln, Blätter abzupfen und grob hacken. Reispfanne abschmecken. Tomaten, Feta und Petersilie darauf verteilen.
[Feta: 50 g; Petersilie: 0.25 Bunds]
<file_sep>---
title: Blumenkohlsalat mit Ei
date: 2015-09-22
tags:
- veggie
aliases:
- ../../salate/blumenkohlsalat-mit-ei
---
## Zutaten für 2 Portionen
- 800 g Blumenkohl
- 1 Zitrone
- 150 g <NAME>
- frisch gemahlener Pfeffer
- 20 g Petersilie (fein gehackt)
- 4 Eier
## Zubereitung
Das Wasser für den Blumenkohl und für die Eier zum Kochen aufsetzen. Die Zitrone entsaften und eine Hälfte vom Saft in das Wasser für den Blumenkohl geben, die andere Hälfte beiseite stellen.
Den Blumenkohl putzen, waschen, in kleine Röschen teilen. Die Röschen in das kochende Zitronenwasser geben und 10 Minuten garen, aus dem Kochwasser herausnehmen und abkühlen lassen. Die Eier 7 Minuten hartkochen.
Aus der sauren Sahne, der Petersilie und dem restlichen Zitronensaft ein Dressing herstellen. Mit frisch gemahlenem Pfeffer abschmecken.
Die Hühnereier in feine Würfel schneiden, über den Blumenkohl geben und das Ganze mit dem Dressing übergießen.
## Nährwerte für 1 Portion
- kcal: 384
- KH: 27g
- Fett: 22g
- EW: 28g
<file_sep>---
title: Blumenkohlpüree mit Hackfleisch Topping
date: '2022-04-03'
lastmod: '2023-01-18'
servings: 4
calories: 1920
fat: 128
carbohydrate: 56
protein: 116
cookTime: PT30M
aliases:
- ../../hauptgerichte/blumenkohlpueree-mit-hackfleisch-topping
---

## Zutaten
- 2 Blumenkohl
- 2 Öl
- 1 Zwiebel
- 400 g Hackfleisch
- 1 Bund Suppengrün
- Paprika Edelsüß
- 1 Prise Zucker
- 2 EL Tomatenmark
- 250 ml Gemüsebrühe
- 100 g Crème fraîche
- 5 Stengel Petersilie
- optional: Muskat
## Zubereitung
1. Salzwasser in einem großen Topf aufkochen. Blumenkohl putzen, waschen und vierteln. In kochendes Salzwasser geben, zugedeckt aufkochen und 20 Minuten garen.
2. Inzwischen Zwiebel schälen, würfeln. Suppengrün putzen, waschen und je nach Gemüse würfeln oder in feine Ringe schneiden.
3. Öl in einer Pfanne erhitzen, Hackfleisch hineinbröseln und kräftig unter wenden anbraten. Zwiebeln und Gemüse zufügen, kurz mit anbraten. Mit Salz, Pfeffer, Paprika und Zucker würzen.
4. Tomatenmark unterrühren, anschwitzen, mit Brühe ablöschen und zugedeckt 6 Minuten köcheln lassen.
5. Inzwischen Petersilie waschen, trocken schütteln und fein hacken.
6. Blumenkohl abgießen, kurz in dem Topf abdämpfen lassen. Crème fraîche zufügen, und mit einem Kartoffelstampfer oder Pürierstab zu einem Püree verarbeiten. Mit Salz und Muskat abschmecken.
7. Blumenkohlstampf und Hackfleisch auf Tellern anrichten. Mit Petersilie bestreuen.
<file_sep>---
title: Spiegelei mit Käse und Tomatensalsa
date: 2019-03-23
tags:
- lowcarb
- simple
aliases:
- ../../hauptgerichte/spiegelei-mit-käse-und-tomatensalsa
---
## Zutaten
- 2 Eier
- 2 Scheiben Käse
- [Tomatensalsa]({{< relref "Tomatensalsa" >}})
## Zubereitung
Etwas Fett in einer Pfanne bei mittlerer Hitze zum Schmelzen bringen, die Eier darin zerschlagen und etwas stocken lassen. Den Käse auf die Spiegeleier legen bzw. streuen und schmelzen lassen.
Die Eier zusammen mit der [Tomatensalsa]({{< relref "Tomatensalsa" >}}) servieren.
<file_sep>---
title: Schokopralinen
date: 2014-08-31
tags:
- lowcarb
- highfat
aliases:
- ../../desserts/schokopralinen
---
## Zutaten
- 200 g gemahlene Mandel(n)
- 2 EL Mandelmus
- 2 TL gestr. Kakaopulver
- etwas Aroma (Orangenaroma)
- etwas Zitronensaft, frisch gepresst
- <NAME>
- <NAME>
## Zubereitung
Die frisch gemahlenen Mandeln in eine Schüssel geben. Mandelmus, Kakao, Orangenaroma, Zitronensaft und Süßstoff nach Belieben dazugeben. Alles miteinander verrühren und so viel Wasser dazugeben, bis es eine formbare Masse gibt. Sollte es zu feucht sein, können noch geriebene Mandeln dazugegeben werden, bis die Masse passt. Aus der Mischung Kugeln formen. Im Kühlschrank aufbewahren.
<file_sep>---
title: Karibische Linsensuppe mit Chinakohl
date: 2020-03-17
tags:
- veggie
aliases:
- ../../hauptgerichte/karibische-linsensuppe-mit-chinakohl
---
## Zutaten für 4 Portionen
- 150 g rote Linsen
- 1l Gemüsebrühe
- 400 g Chinakohl
- 1 EL Currypulver
- 2 Bananen
- etwas Cayennepfeffer
- 1 Prise Zimtpulver
- 1 TL Honig
- 2 EL Zitronensaft
- 150 g saure Sahne
- 2 EL Cashewnüsse (optional)
- etwas Öl
- etwas Salz
## Zubereitung
Den Chinakohl halbieren und die Blätter in Streifen schneiden. Diese im Suppentopf in wenig heißem Erdnuss- oder Sonnenblumenöl anschwitzen und das Currypulver darüberstreuen.
Gemüsebrühe, klein gewürfelte Banane und Linsen dazugeben. Das Ganze mindestens 5-10 Minuten köcheln lassen.
Mit Cayennepfeffer, Zimt, Salz, Honig und Zitronensaft abschmecken. Zum Schluss die saure Sahne vorsichtig unterrühren. Bei Belieben mit Cashewnüssen bestreuen und servieren.
<file_sep>---
title: Schweinehack mit gebratenem Reis
date: 2020-05-20
tags: []
aliases:
- ../../hauptgerichte/schweinehack-mit-gebratenem-reis
---
## Zutaten für 3 Portionen
- 3 große Eier, geschlagen
- 1 Bund Frühlingszwiebeln, in feine Scheiben geschnitten, hell- und dunkelgrüne Teile geteilt
- 3 Knoblauchzehen, gehackt
- 2 EL fein gehackter frischer Ingwer
- 500g Schweinehack
- 4 Tassen gekochter weißer Reis (von 1-1/3 Tassen ungekochter Reis)
- 1/2 Tasse tiefgefrorene Erbsen, aufgetaut
- 1½ Tassen gekochte Brokkoliröschen (siehe Anmerkung)
- 3 EL Fischsauce
- 2 EL Austernsauce
- 2 TL Zucker
- ¼ TK zerstoßene Chiliflocken
- 3 EL frisch gehackter Koriander
## Zubereitung
In einer großen Bratpfanne 1 Esslöffel des Öls bei mittlerer bis hoher Hitze erhitzen. Die geschlagenen Eier mit einer großzügigen Prise Salz würzen, in die Pfanne geben und unter häufigem Rühren braten, bis sie stocken. Die Eier auf einen Teller geben und beiseite stellen.
In derselben Pfanne (es ist nicht nötig, sie zu waschen) das restliche Esslöffel Öl bei mittlerer Hitze erhitzen. Die hellgrünen Frühlingszwiebeln, Knoblauch und Ingwer hinzufügen und unter häufigem Rühren etwa 1 Minute anbraten. Das Schweinefleisch hinzugeben und weiterbraten, das Fleisch mit einem Holzlöffel auseinanderteilen, bis es nicht mehr rosa ist (ca. 3 Minuten).
Den gekochten Reis, das Gemüse, die Fischsauce, die Austernsauce, den Zucker und die Paprikaflocken hinzugeben. Unter gleichmäßigem Rühren kochen, bis der Reis und das Gemüse heiß sind. Das dunkle Schalottengrün, Koriander und Rührei unterrühren. Abschmecken und ggf. die Gewürze anpassen. Falls gewünscht, mit Sriracha servieren.
<file_sep>---
title: Omlett mit Tomaten
date: 2015-04-25
lastmod: 2023-01-25
tags:
- eier
- highfat
- lowcarb
- pfanne
- simple
- schnell
cookTime: PT15M
recipeYield: 1
aliases:
- ../../hauptgerichte/omlett-mit-tomaten
---



## Zutaten
- 3 Eier
- 100g würziger Hartkäse
- handvoll Tomaten
- optional: Schnittlauch oder Basilikum
## Zubereitung
1. Tomaten in Scheiben schneiden und in einer Pfanne mit Öl bei hoher Hitze anbraten.
1. Die Eier in einer Schale verquirlen, nach belieben würzen.
1. Den Käse klein würfeln und unter die Eier geben.
1. Tomaten aus der Pfanne nehmen und beiseite Stellen.
1. Auf mittlere Hitze reduzieren, ggf. Öl nachgießen und die Eiermasse hineingeben.
1. Die Ränder des Omletts hin und wieder mit einem Bratenwender vom Pfannenrand lösen.
1. Wenn die Mitte des Omletts anfängt sich zuverfestigen, die Tomaten auf eine Hälfte geben und das Omlett zusammenklappen. Dann von beiden Seiten fertig braten.
<file_sep>---
title: Auberginen alla Parmagiana
date: 2017-03-24
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/auberginen-alla-parmagiana
---
## Zutaten für 4 Portionen
- 3 große Auberginen
- 3 Eier
- 250 g Parmesan gerieben
- 5 EL Olivenöl
- 1 Knoblauchzehe
- 800 g gehackte Tomaten
- 20 Basilikumblätter
- 600 g grüne Bohnen
- 2-3 EL Olivenöl oder Butter
- Salz & Pfeffer
- etwas Kokoszucker
- Butter oder Kokosöl
## Zubereitung
Die Auberginen waschen und längs in Scheiben schneiden, mit reichlich Salz bestreuen und mindestens 30 Minuten auf einem großen Teller ziehen lassen. Dann die Auberginen schreiben in kaltem Wasser abspülen und trockentupfen. Die Eier in einem tiefen Teller verquirlen uns die Auberginenscheiben darin finden. In einer Pfanne Butter oder Kokosöl zerlassen und die Auberginen goldgelb braten auf einem Stück Küchenpapier abtropfen lassen und zur Seite stellen.
Inzwischen für die Tomatensoße 5 El Öl in einem Topf erhitzen, die Knoblauchzehe fein hacken und anschwitzen. Tomaten, Basilikum und Kokos Suppe hinzufügen. Die Soße 30 bis 40 Minuten köcheln lassen und mit Salz und Pfeffer abschmecken.
Die gefrorenen Bohnen in einer Pfanne in zerlassener Butter oder Öl wenden. Dann auf ein mit Backpapier ausgelegtes Backblech verteilen und mit Salz bestreuen. Im Backofen auf der unteren Schiene etwa 30 Minuten backen.
Auf den Boden einer eingefetteten Auflaufform etwas Tomatensoße gießen. Eine erste Schicht aus leicht überlappenden Auberginenscheiben hinein legen und mit Parmesan bestreuen. Mit Basilikum bestreuen und weitere Tomatensoße einfüllen. Die Vorgänge solange wiederholen, bis alle Zutaten aufgebraucht sind, dabei mit Tomatensoße abschließen. Im Ofen zusammen mit den Bohnen 30 Minuten backen.
<file_sep>---
title: Grüner Eistee
date: 2015-04-15
aliases:
- ../../snacks-und-shakes/grüner-eistee
---
## Zutaten
- Grüner Tee
- Süßstoff
- Zitronensaft(konzentrat)
## Zubereitung
Grünen Tee aufgießen, nicht kochendes Wasser, 3 min. ziehen lassen.
Abkühlen lassen, mit Zitrone und Süßstoff abschmecken.
<file_sep>---
title: Shakshuka
date: 2020-08-04
tags:
- lowcarb
- schnell
- simple
- veggie
aliases:
- ../../hauptgerichte/shakshuka
---
Ein klassisches und einfaches Eiergericht mit vielen Variationsmöglichkeiten.
## Zutaten für 2 Portionen
- 1 Zwiebel
- 2 Knoblauchzehen
- 1 EL Öl für die Pfanne
- 1 EL Tomatenmark
- 1 rote Paprika
- 4 Tomaten
- 400 ml gestückelte Tomaten
- 1 TL Paprikapulver
- Salz & Pfeffer
- 1 Prise Chili
- 4 Eier
- 1 Handvoll Petersilie
## Zubereitung
1. Paprika und Tomaten waschen und in kleine Würfel schneiden.
1. Zwiebel und Knoblauch abziehen und hacken und in der Pfanne mit Öl anschwitzen. Tomatenmark hinzugeben.
1. Paprika und Tomaten hinzugeben und 5 Minuten köcheln lassen.
1. Gestückelte Tomaten hinzugeben. Mit Paprikapulver, Chilipulver, Salz und Pfeffer würzen.
1. Weitere 10 Minuten einköcheln lassen.
1. Mit einem Löffel 4 Mulden in die Tomatenmasse formen. In jede Mulde ein Ei schlagen. Deckel auf die Pfanne setzen und Eier 6-8 Minuten stocken lassen, so dass das Eiweiß geronnen ist aber das Eigelb noch flüssig ist.
1. Mit frischer Petersilie bestreuen und servieren.
<file_sep>---
title: Mayonnaise Varianten
date: 2015-11-19
tags:
- lowcarb
- highfat
aliases:
- ../../beilagen/mayonnaise-varianten
---
Hier sind einige Mayonnaise-Varianten vorgestellt, die Grundzutat ist immer 250 g Mayonnaise.
## Chili-Mayonnaise
- 2 EL Chili-Flocken
- 1 Knoblauchzehe
- ½ EL Zimt
- 70 g Tomatenmark
- 150 ml Oliven- oder Leinöl
- Salz & Pfeffer
Die Knoblauchzehe pellen und kleinhacken. Die Chiliflocken und 100 ml Wasser in einen Kochtopf geben und aufkochen. Zwischedurch eventuell etwas Wasser dazugeben, bis eine dickflüssige Masse entsteht.
Knoblauch, Zimt und Tomatenmark unterrühren und erneut aufkochen. Mit Salz & Pfeffer abschmecken und abkühlen lassen. Das Öl nach und nach unterühren.
Dadurch erhält man eine leckere Chili-Sauce von der man nun 2 EL unter 250 g Mayonnaise gibt.
## Kräutercreme
- 1 handvoll frische, gemischte Kräuter
Die Kräuter abspülen, fein hacken und unter die Mayonnaise geben.
## Estragon-Mayonnaise
- 1 Schalotte
- 1 EL frischer Estragon
- 1 TL Dijon-Senf
Die Schalotte abziehen und genau wie den Estragon kleinhacken und zusammen mit dem Senf unter die Mayonnaise rühren.
## Aioli
- 3 Knoblauchzehen
Die Knoblauchzehen pellen und in die Mayonnaise auspressen.
<file_sep>---
title: Putenauflauf
date: 2017-07-31
tags:
- lowcarb
aliases:
- ../../hauptgerichte/putenauflauf
---
## Zutaten
- 4 Putenschnitzel (ca. 650 g)
- etwas Öl zum Anbraten
- 2 Paprika, am besten gelbe, rote oder orange, da sie etwas milder schmecken
- 400 g Blumenkohl
- 200 g saure Sahne (10% Fett)
- 100 g Frischkäse
- 200 g geriebener Käse
- Meersalz, Pfeffer, Knoblauchpulver und gemischte Kräuter
## Zubereitung
Die Putenschnitzel in einer Pfanne mit dem Öl kurz von beiden Seiten anbraten und dann in eine Auflaufform geben und von beiden Seiten würzen.
Den Blumenkohl waschen in kleine Röschen zerteilen und im zugedeckten Topf kurz garen (er sollte noch nicht weich sein).
Inzwischen die Paprika waschen, kerne entfernen und in dünne Streifen schneiden. Dann zusammen mit dem Blumenkohl über die Putenschnitzel in die Auflaufform geben.
Sahne, Frischkäse, Gewürzen und Kräutern vermischen und über dem Fleisch verteilen. Anschließend den geriebenen Käse darüber geben und bei 200 Grad im vorgeheizten Backofen ca. 30 Minuten backen. Wenn der Käse goldbraun aussieht ist der Auflauf fertig.
<file_sep>---
title: Weißkohl Kartoffel Eintopf
date: 2022-01-30
lastmod: 2022-09-06
tags:
- simple
aliases:
- ../../hauptgerichte/weißkohl-kartoffel-eintopf
---
## Zutaten für 4 Portionen
- 1 kg Weißkohl
- 1 l Gemüsebrühe (Instant)
- Salz & Pfeffer
- 500 g Kartoffeln
- 2 mittelgroße Zwiebeln
- 1-2 EL Öl
- 500 g Rinderhackfleisch
## Zubereitung
1. Kohl waschen, putzen und vierteln. Den harten Strunk herausschneiden und in Streifen schneiden.
2. Brühe in einem großen Topf aufkochen, mit Salz und Pfeffer würzen.
3. Weißkohlstreifen zufügen und bei mittlerer Hitze kochen.
4. Kartoffeln schälen, waschen und in grobe Würfel schneiden. Kartoffeln nach ca. 10 Minuten Garzeit zum Eintopf geben.
5. Zwiebeln schälen und würfeln. Öl in einer großen beschichteten Pfanne erhitzen und die Zwiebelwürfel darin andünsten.
6. Hackfleisch zufügen und anbraten und in den Eintopf rühren.
7. Insgesamt 30 Minuten kochen. Eventuell nochmal mit Salz und Pfeffer abschmecken.
<file_sep>---
title: Auberginen a la Napoli
date: 2021-02-10
lastmod: 2022-07-21
tags:
- lowcarb
aliases:
- ../../hauptgerichte/auberginen-a-la-napoli
---

## Zutaten für 2 Portionen
- 600 g Aubergine (2 Stück)
- 1 Zwiebel
- 4 EL Olivenöl
- 400 g gehackte Tomate (1 Dose)
- 2 EL Tomatenmark
- 250 g Mozzarella (2 Stück)
- 80 g Parmesan
- 50 g Schinkenwürfel
- Basilikum
- Salz und Pfeffer
- Fett für die Form
## Zubereitung
1. Die Auberginen putzen und in ca. 1 cm-dicke Scheiben schneiden, von beiden Seiten salzen und ruhen lassen.
2. Inzwischen die Zwiebeln in grobe Würfel schneiden und in einem weiten Topf in Öl andünsten.
3. Die Tomaten und das Tomatenmark dazugeben, mit Basilikum, Salz und Pfeffer abschmecken, alles ca. 15 Minuten durchkochen, dann beiseite Stellen.
4. Die Auberginenscheiben abtrocknen und von beiden Seiten kurz in einer Pfanne anbräunen.
5. Eine Auflaufform einfetten und Auberginen, Tomatensoße und Mozzarella hineinschichten, Schinkenwürfel hinzugeben und mit Parmesankäse bestreuen. Mit Alufolie abdecken und bei 250°C ca. 20 Minuten backen.
6. Anschließen die Alufolie abnehmen und nochmals ca. 10 Minuten gratinieren lassen.
<file_sep>---
title: Bacon Cheeseburger
date: 2015-11-16
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/bacon-cheeseburger
---
## Zutaten für 4 Burger
- 8 Stück [Gemüse-Fladenbrot]({{< relref "Gemüse-Fladenbrot" >}})
- 3 EL selbstgemachter [Ketchup]({{< relref "Ketchup" >}})
- 250 g Mayonnaise
- 3 Knoblauchzehen
- 150g Bacon
- 600 g Rinderhackfleisch
- 1 Ei
- 50 g geriebener Käse
- 4 Schieben Käse (z.B. Havarti)
- 1 Zwiebel
- 2 Tomaten
- Kopfsalat
- Kokosöl zum Braten
- Salz & Pfeffer
## Zubereitung
Zuerst das Gemüse-Fladenbrot und den Ketchup zubereiten.
Die Knoblauchzehen schälen, auspressen und mit der Mayonnaise verrühren.
Den Backofen auf 190 C vorheizen und ein Backbleck mit Backpapier auslegen.
Die Speckstücke auf das Backpapier legen und im Backofen ca. 10 Minuten knusprig braten. Auf Küchenpapier abtropfen lassen.
Das Rinderhack mit Ei, Ketchup, geriebenem Käse und Salz & Pfeffer vermischen und daraus 4 flache Patties formen. In einer Pfanne Kokosöl zerlassen und die Patties darin braten. Wenn sie schon fast fertig sind, die Käsescheiben darauflegen und schmelzen lassen.
Die Zwiebel schälen und genauso wie die Tomaten in dünne Ringe schneiden.
Aus allen Zutatten 4 leckere Burger zusammenstellen.
## Nährwerte pro Burger mit allen Zutaten
- kcal: 917
- KH: 11g
- Fett: 71g
- EW: 59g
<file_sep>---
title: Deftige Pilzpfanne
date: 2017-07-10
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/deftige-pilzpfanne
---
<!--

-->
## Zutaten
- 1 mittelgroße Ziebel (70g)
- 250g Pilze - Pfifferlinge, Champignongs oder Austernpilze
- 125g Speckwürfel oder -streifen
- 1 EL Butter
- 10g Petersilie
- etwas Kümmel
- 100g Sahne
- Salz & Pfeffer
- Kokosöl zum Braten
## Zubereitung
Die Zwiebel fein hacken. Die Pilze waschen und vierteln.
Pfanne mit etwas Öl erhitzen. Die Zwiebel und den Speck darin glasig anbraten, dann die Pilze hinzufügen und etwa 10 min braten. Die Butter in die Pfanne geben, schmelzen lassen und die Petersilie und den Kümmel hinzufügen. Mit Pfeffer und Salz abschmecken. Zum Schluss die Flüssigkeit in der Pfanne mit etwas Sahne abbinden.
## Nährwerte
- kcal: 761
- KH: 10g
- Fett: 68g
- EW: 27g
<file_sep>---
title: Spinat mit Bohnen und Ei
date: 2015-05-02
tags:
- lowcarb
- simple
aliases:
- ../../hauptgerichte/spinat-mit-bohnen-und-ei
---
## Zutaten

- 2 Eiklar, 1 Vollei
- 2 Handvoll TK-Spinat
- 1 Dose schwarze Bohnen
- Salz & Pfeffer
## Zubereitung
Den Spinat in der Mikrowelle erhitzen, die Bohnen in einer Pfanne anbraten, währenddessen die Eier trennen. Die Eier mit Salz und Pfeffer würzen und zu den Bohnen in die Pfanne geben. Mittlerweile sollte der Spinat fertig sein, das Ganze auf einem Teller anrichten.
<file_sep>---
title: Hauptgerichte
layout: index
order: date
reverse: true
---
<file_sep>---
title: Avocado Brownies
date: 2018-02-28
tags:
- veggie
aliases:
- ../../desserts/avocado-brownies
---

## Zutaten
- 200 g Zartbitter-Schokolade
- 2 mittelgroße reife Avocados (à 200–250 g)
- 4 Eier
- 1 Päckchen Vanillin-Zucker
- 100 g Kokosblütenzucker
- 100 g <NAME>
- 60 g Kakaopulver
- ½ TL Backpulver
## Zubereitung
Backofen auf 175 °C bzw. Umluft: 150 °C vorheizen.
Schokolade grob hacken und in einer Schüssel über einem warmen Wasserbad schmelzen. Avocados halbieren, Stein entfernen und das Fruchtfleisch aus der Schale lösen. Fruchtfleisch, Eier, Vanillin-Zucker und Zucker pürieren.
Geschmolzene Schokolade unterrühren. Mandeln, Kakao und Backpulver mischen und unterrühren.
Boden einer Springform mit Backpapier auslegen. Teig einfüllen und glatt streichen.
Kuchen im vorgeheizten Backofen 20 - 25 Minuten backen. Herausnehmen und auskühlen lassen. Kuchen aus der Form lösen, und auf Brownie-Größe zurechtschneiden.
## Nährwerte
- kcal: 3160
- KH: 158g
- Fett: 241g
- EW: 91g
<file_sep>---
title: Kokos Porridge
date: 2020-05-02
tags:
- simple
aliases:
- ../../hauptgerichte/kokos-porridge
---
## Zutaten
- 30g (1 handvoll) Nüsse
- 200 ml Kokosmilch
- 100 g zarte Haferflocken
- 2 EL Leinsamen
- 1 EL Kakaopulver
- 2 EL Kokosflocken
- 1 handvoll Himbeeren
## Zubereitung
Für das Kokos-Porridge röstest du zunächst die Nüsse bei mittlerer Temparatur in einem kleinen Topf etwas an. Danach fügst du nach und nach die anderen Zutaten hinzu. Nach belieben kann das Porridge mit Kardamom oder Vanillepulver abgeschmeckt werden.
<file_sep>---
title: Sündhaft gute Brownies
date: 2015-10-11
tags:
- lowcarb
- highfat
- veggie
aliases:
- ../../desserts/sündhaft-gute-brownies
---

## Zutaten für 10 Brownies
- 175g weiche, gesalzene Butter (oder eben ungesalzene Butter mit 2 TL Salz)
- 80g Kokosblütenzucker
- 2 EL Steviapulver
- 200g dunkle Schokolade (~80% Kakaoanteil)
- 6 Eier
- 150g Walnüsse oder Paranüsse
- 1 TL gemahlener Zimt
- 25g gemahlener Kaffee
## Zubereitung
Die Schokolade im Wasserbad oder in einem kleinen Topf bei niedriger Hitze zum Schmelzen bringen.
Währenddessen Butter, Kokoszucker und Steviapulver in einer Schüssel mit einem Rührgerät mischen. Sollte die Butter zu hart sein, einfach für ~30 Sekunden auf niedriger Stufe in der Mikrowelle erhitzen. Dann die geschmolzene Schokolade hinzugeben.
Die Eier trennen und das Eigelb zusammen mit dem Zimt und dem Kaffee in den "Teig" einrühren.
Jetzt kann schon mal der Backofen auf 180 ℃ vorgeheizt werden und eine Springform oder eine andere ofenfeste Form mit Backpapier ausgelegt oder eingefettet werden.
Die Quirle des Rührgerätes abspülen, so dass sie fettfrei sind, damit das Eiweiss steif schlagen und vorsichtig dem Teig unterheben.
Zum Schluss die Nüsse grob hacken und ebenfalls in den Teig unterrühren.
Das ganze kommt dann für 20 min. in den Backofen.
## Nährwerte pro Brownie
- kcal: 411
- KH: 14g
- EW: 9g
- Fett: 36g
<file_sep>---
title: Humus
date: 2014-02-23
tags:
- lowcarb
aliases:
- ../../beilagen/humus
---
# Zutaten

- 250 g Kichererbsen, getrocknete oder aus dem Glas
- 2 Zehen Knoblauch oder Knoblauchpaste
- 1 Prise Kreuzkümmel
- 1 TL Paprikapulver, süß
- 1 Bund Petersilie
- 4 EL Olivenöl
- 4 EL Sesampaste (Tahin)
- 1/2 Zitrone
- Salz & Pfeffer
## Zubereitung
1. Die Kichererbsen 12 Stunden einweichen - kann man sich bei den Kichererbsen aus dem Glas sparen. Etwa 1 Stunde weich kochen, Wasser abgießen und beiseite stellen.
2. Alle Zutaten von Kichererbsen bis Olivenöl im Mixer pürieren oder mit dem Pürierstab zerkleinern. Es muss eine geschmeidige Paste entstehen.
3. Falls die Masse zu trocken ist, etwas vom Kochwasser hinzufügen.
4. Am Schluss Tahin und Zitronensaft unterrühren, mit Salz und Pfeffer abschmecken.
<file_sep>---
title: Dessertpizza
date: 2015-10-14
tags:
- lowcarb
- highfat
- veggie
aliases:
- ../../desserts/dessertpizza
---

## Zutaten
- 3 Eier
- 100 ml Kokosmilch oder Sahne
- 50 g Kokosraspel
- 1 TL Backpulver
- 1 TL Kardamom
- 3 TL Flohsamenschalen
- 150 g Ricotta
- 4 TL Kokosblütenzucker
- 2 TL gemahlener Zimt
- 1 Apfel
- 15 g Butter
- 50 g Mandeln
## Zubereitung
Die Eier zusammen mit Kokosmilch, Kokosraspel, Backpulver, Kardamom und den Flohsamenschalen zu einem Teig verrühren und diesen 10 min. ruhen lassen.
Inzwischen schon mal den Backofen auf 200℃ vorheizen und ein Blech mit Backpapier auslegen. Den Ricotta mit 1 TL Kokosblütenzucker und ½ TL Zimt verrühren, den Apfel waschen, entkernen und in dünne Scheiben schneiden.
Den Teig jetzt pizzaartig auf dem Backpapier verteilen, 10 min. vorbacken und dann wieder aus dem Ofen nehmen.
Die Butter zusammen mit 2 TL Kokosblütenzucker und 1 TL Zimt in einer Pfanne zerlassen und die Apfelscheiben darin kandieren.
Den Ricotta auf dem Pizzaboden streichen und die Apfelscheiben darauf verteilen. Die Mandeln grob hacken mit dem restlichen Kokosblütenzucker (1 TL), Zimt (½ TL) und 1 EL Wasser in der Pfanne kandieren und dann über die Pizza streuen.
Der Pizzakuchen wird dann noch mal 8 min. im Backofen fertig gebacken.
## Nährwerte pro Pizza
- kcal: 1,532
- KH: 60 g
- Fett: 119 g
- EW: 50 g
<file_sep>---
title: Avocadosalat mit Bacon und Walnüssen
date: 2017-01-11
tags:
- lowcarb
- highfat
- simple
aliases:
- ../../salate/avocadosalat-mit-bacon-und-walnüssen
---
## Zutaten für 2 Portionen

- 200 g Bacon
- 50 g Rucola
- 2 Tomaten
- 1 rote Zwiebel
- 1 Avocado
- 60 g Walnüsse
- 2 EL Zitronensaft
## Zubereitung
Den Bacon auf einem mit Backpapier ausgelegtem Blech ausbreiten und für 10 Minuten bei 190 Grad in den Ofen schieben.
Währenddessen den Rucola und die Tomaten waschen und die Tomaten achteln. Die Zwiebel häuten und in kleine Würfel schneiden. Die Avocado aufschneiden und entkernen, das Fruchtfleich in längliche Streifen schneiden. Die Walnusskerne zerdrücken oder kleinhacken und zusammen mit dem Bacon unter die restlichen Zutaten mischen.
Den Zitronensaft darüber geben und servieren.
<file_sep>---
title: Gebackene Aubergine
date: 2017-07-08
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/gebackene-aubergine
---

## Zutaten für 2 Portionen
- 1 Aubergine
- 250g Halloumi, Feta oder Ziegenkäse
- 1 Zucchini
- 1 rote Paprika
- 1 gelbe Paprika
- 1 rote Zwiebel
- 2 Knoblauchzehen
- 1 handvoll Rucola
- Olivenöl
- Salz & Pfeffer
## Zubereitung
Backofen auf 250 ℃ vorheizen und ein Blech mit Backpapier auslegen.
Die Aubergine in Scheiben schneiden und auf das Backblech legen. Mit ein wenig Olivenöl bestreichen und mit Salz bestreuen. Das ganze 10 Minuten backen.
Den Käse in Scheiben schneiden, auf die Auberginen legen und für ca. 5 Minuten mitbacken.
Die Paprika waschen und aufschneiden und ausnehmen, Zucchini waschen, Zwiebel schälen und alles in grobe Stücke schneiden. Die Knoblauchzehen fein hacken. Öl in der Pfanne erhitzen und das Gemüse bissfest braten. Mit Salz & Pfeffer abschmecken.
Rucola waschen, trockenschütteln und auf den Tellern verteilen, das gebratene Gemüse und die Auberginenscheiben darauf verteilen.
<file_sep>---
title: Teufelseier mit Avocado
date: 2017-08-16
tags:
- lowcarb
- highfat
- simple
- veggie
aliases:
- ../../snacks-und-shakes/teufelseier-mit-avocado
---
Ideal als Partysnack oder Fingerfood, kann man auch [/snacks-und-shakes/Teufelseier-mit-Thunfischfüllung] zubereiten.


## Zutaten für 3 Portionen
- 6 hart gekochte Eier
- 2 mittelgroße Avocados
- Prise Paprika
- 1 EL Salz
## Zubereitung
1. Eier schälen und halbieren, dass Eigelb in eine separate Schüssel geben
2. Avocado schälen und zum Eigelb in der Schüssel geben, mit einer Gabel alles zerdrücken
3. Salz hinzufügen, alles gut vermischen
4. mit einem Löffel das Avocado-Eigelb wieder in die Eier füllen
5. mit Paprika bestreuen
## Nährwerte pro Portion
- kcal: 330
- EW: 17g
- Fett: 32g
- KH: 8g
<file_sep>---
title: Marinierter Lachs
date: 2017-12-24
tags:
- lowcarb
- highfat
aliases:
- ../../beilagen/marinierter-lachs
---
## Zutaten für 2 Portionen
- 250g TK Lachs
- 6 Limetten
- 1 <NAME>
- 3 EL Kapern
## Zubereitung
Den noch leicht gefrorenen Lachs in dünne Scheiben schneiden und auf einen Teller legen. Die Limetten entsaften und den Saft über den Lachs geben. Einige Stunden marinieren lassen.
Die Zwiebel fein hacken und zusammen mit den Kapern über den Lachs geben.
Dazu passt gut ein grüner Salat mit Creme-Fraiche-Knoblauch Dressing.
<file_sep>---
title: Walnussfarce
date: 2015-06-30
tags:
- lowcarb
- highfat
aliases:
- ../../beilagen/walnussfarce
---
## Zutaten
- 150g Walnüsse
- 80g sonnengetrocknete Tomaten
- 100g braune Champignongs
- 2 EL Olivenöl
- 1 EL Tamari (glutenfreie Sojasauce)
- 1 EL Kokoszucker
- 2 TL TK-Petersilie
- 2 TL geriebener Oregano
- etwas Cayennepfeffer
## Zubereitung
Alle Zutaten in der Küchenmaschine oder mit dem Pürierstab zerkleinern.
<file_sep>---
title: Rotkohl mit Speck
date: 2014-02-19
tags:
- lowcarb
aliases:
- ../../beilagen/rotkohl-mit-speck
---
## Zutaten

- 1 Kopf Rotkohl oder 1 Glas fertigen Rotkohl (550g)
- 200 g Schinkenspeck
- 200 ml Wasser
- n. B. <NAME>
- n. B. Schnittlauch, fein geschnitten
- n. B. Öl (Sonnenblumenöl)
- Salz & Pfeffer
## Zubereitung
Den Rotkohl fein schneiden. Den Schinkenspeck in Würfel schneiden, in der Pfanne auslassen, bis er knusprig ist. Den Rotkohl in die Pfanne geben und kurz anschwitzen, salzen und pfeffern. Bei Mit dem Wasser ablöschen und bei mittlerer Hitze bissfest garen (kann bei fertigem Rotkohl aus dem Glas natürlich weggelassen werden).
Die Pfanne vom Herd nehmen, etwas abkühlen lassen, nochmals salzen und pfeffern. Schnittlauch, einen Schuss Sonnenblumenöl und Aceto Balsamico zugeben.
<file_sep>---
title: Lachsröllchen mit Frischkäse
date: 2019-04-16
tags:
- lowcarb
- highfat
aliases:
- ../../beilagen/lachsröllchen-mit-frischkäse
---
## Zutaten für 2 Portion
- 100g Frischkäse
- 2 EL Sahne
- 1 Handvoll Kräuter z.B. Petersilie, Basilikum, Koriander
- 200g Räucherlachs in Scheiben
- Salz & Pfeffer
## Zubereitung
Die Kräuter kleinhacken und mit dem Frischkäse und der Sahne verrühren. Mit Salz und Pfeffer abschmecken. Einen Löffel dieser Frischkäsemischung auf auf je eine Lachsscheibe geben und zusammenrollen.
<file_sep>---
title: Himbeer Mohn Muffins
date: 2020-05-06
tags:
- lowcarb
- veggie
- protein
aliases:
- ../../desserts/himbeer-mohn-muffins
---
## Zutaten für 6 Muffins
- 2 Eier
- 250 g Quark 20% Fett
- 60 g Kokosmehl
- 50 g Proteinpulver Vanille
- 35 g Blaumohn
- 65 g Erythrit oder 50 g Xylit / Birkenzucker
- 1 TL Backpulver
- 1 TL Guarkernmehl / Reismehl / Johannisbrotkernmehl
- 150 g Himbeeren (frisch oder gefroren)
## Zubereitung
Backofen auf 175 ℃ vorheizen.
Dann alle Bestandteile außer den Himbeeren in einer Rührschüssel mit der Küchenmaschine oder dem Rührgerät durchmischen. Zum Schluss die Himbeeren ganz vorsichtig unterheben.
Sechs Vertiefungen einer Muffin-Backform mit Papierförmchen auslegen und die Masse darin verteilen.
Für 30 Minuten backen und auskühlen lassen.
<file_sep>---
title: Putenschnitzel mit Salami überbacken
date: 2016-06-30
tags:
- lowcarb
aliases:
- ../../hauptgerichte/putenschnitzel-mit-salami-überbacken
---


## Zutaten
- 2 Putenschnitzel
- 1 Zwiebel
- 2 Scheiben Käse
- 6 kleine Salamischeiben
## Zubereitung
Zwiebel in halbe Ringe schneiden und in der Pfanne mit Margarine anschwitzen, nach einiger Zeit (sobald die ersten Ringe braun werden) Putenschnitzel dazugeben und Hitze reduzieren, Schnitzel fertig braten.
Danach die Salami je nach Geschmack auf die Schnitzel verteilen. Sobald Salami rot glänzt zuerst die Zwiebeln und dann den Käse darauf verteilen, Hitze leicht erhöhen und Deckel drauf. Wenn der Käse zerläuft ist das ganze servierfertig.
## Nährwerte
- kcal: 779
- Fett: 41,6 g
- KH: 9,8 g
- EW: 93,8 g
<file_sep>---
title: Bananenbrot
date: 2016-12-08
tags:
- lowcarb
- highfat
- veggie
aliases:
- ../../desserts/bananenbrot
---

## Zutaten
- 100 g Walnüsse
- 50 g dunkle Schokolade
- 2 Bananen
- 100 ml Kokosmilch
- 4 Eier
- 120 g Kokosblütenzucker
- 100 g Butter
- 1 EL gemahlener Zimt
- 1 TL gemahlener Kardamom
- 1 TL Vanillepulver
- 6 TL Flohsamenschalen
- 100 g Kokosraspel
- 1 TL Backpulver
## Zubereitung
1. Butter bei niedriger Temperatur in einem Topf zum Schmelzen bringen.
1. Bananen, Kokosmilch, Eier und Kokosblütenzucker in der Küchenmaschine oder mit dem Pürierstab mixen und in eine Schüssel geben.
1. Die geschmolzene Butter, den Zimt, Kardamom, Vanillepulver, Flohsamenschalen, Kokosraspel und Backpulver hinzufügen und gut verrühren.
1. Die Walnüsse und die Schokolade grob hacken und unterheben.
1. Den Teig für 10 Minuten ruhen lassen.
1. Inzwischen den Backofen auf 200 ℃ vorheizen und eine Kastenform mit Backpapier auslegen.
1. Den Teig dann in die Kastenform füllen und 30 Minuten backen.
<file_sep>---
title: Tomatensalsa
date: 2017-03-21
tags:
- lowcarb
- veggie
aliases:
- ../../beilagen/tomatensalsa
---

## Zutaten für 4 Portionen
- 500 g Tomaten
- 1 <NAME>
- 1 Knoblauchzehe
- 1 Chilischote
- 1 <NAME>
- 2 EL Olivenöl
- ½ Limette
- Salz & Pfeffer
## Zubereitung
Die Tomaten waschen und in Würfel schneiden. Zwiebel und Knoblauchzehe schälen und zusammen mit der Chilischote fein hacken. Den Koriander waschen und grob hacken. Das Ganze mit dem Olivenöl und Limettensaft in einer Schüssel verrühren.
Mit Salz & Pfeffer abschmecken und ca. 1 Stunde ziehen lassen.
<file_sep>---
title: Apfelkuchen
date: 2021-01-04
tags:
- lowcarb
- simple
- veggie
aliases:
- ../../desserts/apfelkuchen
---
## Zutaten
- 6 Eier
- 150 g weiche Butter
- 130 g Erythrit
- 6 Einheiten Stevia
- 250 g Mandelmehl
- 2 TL Guarkernmehl
- 2 TL Backpulver
- 1/2 TL Bourbon-Vanille
- 300 g säuerlicher Apfel
- 50 g Mandelblättchen
## Zubereitung
1. Den Backofen auf 175 Grad Umluft vorheizen.
1. Butter und Eier in einer Rührschüssel gut vermengen.
1. Nach und nach die trockenen Zutaten untermischen.
1. Die Springform fetten, den Boden mit Backpapier bedecken und dann Teig hineingeben.
1. Äpfel schälen, entkernen und in feine Scheiben schneiden.
1. Äpfel gleichmäßig verteilt leicht in den Teig drücken.
1. Die Mandelblättchen darüber streuen.
1. Für 45 Minuten in den Backofen. Wenn der Apfelkuchen zu dunkel wird, dann nach 30 Minuten mit etwas Alufolie schützen.
Alternativ kann der Kuchen statt mit Äpfeln auch mit Brombeeren oder Himbeeren zubereitet werden.
<file_sep>---
title: Putenpfanne Indische Art
date: 2020-03-07
tags:
- lowcarb
aliases:
- ../../hauptgerichte/putenpfanne-indische-art
---

## Zutaten für 2 Portionen
- 500g Putenbrust
- 1 Zwiebel
- 2 TL Currypaste
- 125 g Magerquark
- 2 Knoblauchzehen
- Pfeffer
- Gemüsebrühe
- Öl für die Pfanne
## Zubereitung
Das Geflügel in kleine, dünne Stücke schneiden. Die Zwiebel pellen und kleinschneiden nge schneiden. Die Zwiebelwürfel zusammen mit dem Geflügel in einer Pfanne im Öl anbraten.
Währenddessen Knoblauchzehen klein hacken und zusammen mit dem Magerquark, Curry, Pfeffer und den Brühwürfel zu einer Soße verarbeiten.
Wenn das Geflügel durchgebraten ist, Herdplatte ausmachen und die Soße in die Pfanne geben und alles nochmal durchschwenken.
Dazu passt ein [/salate/gurkensalat] sehr gut.
<file_sep>---
title: Focaccia Brot
date: 2017-10-16
tags:
- lowcarb
- veggie
aliases:
- ../../beilagen/focaccia-brot
---

## Zutaten
- 300 g Hüttenkäse 4% Fett
- 6 Eier
- 40 g Butter
- 160 g Mandeln
- 80 g geschälte Sonnenblumenkerne
- 2 EL Flohsamenschalen
- 1 TL Salz
- 2 TL Backpulver
- 100 g sonnengetrocknete Tomaten
- etwas grobes Salz
## Zubereitung
Den Backofen auf 200 ℃ vorheizen und 2 kleine Backformen (ca. 15x25 cm) mit Backpapier auslegen.
Mandeln und die (sehr wichtig) geschälten Sonnenblumenkerne in einer Küchenmaschine zu Mehl mahlen. Die Butter schmelzen und zusammen mit den Eiern unterrühren.
Den Hüttenkäse dazugeben und durchmischen, bis er keine Krümel mehr hat. Das Ganze mit den Flohsamenschalen, Salz und Backpulver vermengen.
Den Teig teilen und in die beiden Backformen füllen. Die Brote im Backofen 10-15 min. backen und dann wieder herausnehmen.
Die sonnengetrockneten Tomaten kleinhacken und in den Teig drücken und mit grobem Salz bestreuen.
Die Brote dann weitere 15-20 min. backen.
<file_sep>---
title: Schokomousse mit Orange
date: 2015-08-15
tags:
- veggie
- lowcarb
- highfat
aliases:
- ../../desserts/schokomousse-mit-orange
---

## Zutaten für 6 kleine Gläser
- 150g dunkle Schokolade (~ 85% Kakaoanteil)
- 150g Sahne
- 2 Eier
- 1 EL Kokoszucker
- ½ TL Vanillepulver
- 1 unbehandelte Orange
## Zubereitung
Die Schokolade in einem Topf oder Wasserbad schmelzen lassen. Inzwischen die Schale der Orange mit einer feinen Küchenreibe abreiben. Die Sahne schlagen, bis sie ein bisschen fest, aber noch nicht ganz steif ist.
Die Eier trennen und das Eiweiß steif schlagen. Eigelb mit dem Kokoszucker und Vanillepulver verrühren. Anschließend zu der geschmolzennen Schokolade geben und das meiste von der Orangenschale dazugeben.
Die Schokolade vorsichtig unter die geschlagene Sahne heben und alles verrühren bis eine gleichmäßige Masse entstanden ist. Dann noch das Eiweiß vorsichtig unterheben. Die Mousse jetzt in kleine Gläser füllen und in den Kühlschrank stellen.
Zum Servieren noch die beiseite gestellte restliche Orangenschale dazugeben.
<file_sep>---
title: Fischfilet mit Sesam und roten Beeten
date: 2021-02-28
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/fischfilet-mit-sesam-und-roten-beeten
---
## Zutaten für 4 Portionen
- Eine Zwiebel
- 500 g [/beilagen/blumenkohlreis]
- 100 g Reibekäse
- 1 EL Flohsamenschalen
- 4 Eier
- 650 g Schollenfilets
- 150 g Sesam
- Salz und Pfeffer
- Fett oder zum Braten
- 100 g Haselnusskerne
- 400 g rote Beete (vorgekocht)
- 50 ml Balsamico
- glattblättrige Petersilie

## Zubereitung
1. Backofen auf 200 Grad vorheizen und ein Backblech mit Backpapier auslegen
1. Die Zwiebel abziehen und fein würfeln
1. Den Blumenkohlreis mit den Zwiebelwürfeln, 2 Eiern, geriebenen Käse und Flohsamenschalen verrühren
1. Diesen Teig verkneten und in kleinen Portionen auf dem Backpapier zu Fladen pressen
1. Im Backofen 20 Minuten backen, bis sie goldbraun sind
1. Für die Fischfilets die 2 verbliebenen Eier in einem tiefen Teller schlagen und verquirlen, den Sesam auf einem zweiten Teller geben
1. Die Schollenfilets abspülen, trocken tupfen und mit Salz und Pfeffer würzen
1. Filets in den Eiern und dann in Sesam wälzen. Die panierten Schollen beiseite legen
1. In einer Pfanne reichlich Butter oder Öl erhitzen und die Schollen bei mittlerer Temperatur von beiden Seiten braten
1. Dabei häufig kontrollieren, damit der Sesam nicht verbrennt
1. Die Haselnüsse grob hacken und in einer Pfanne ohne Fett rösten und Beiseite stellen
1. Die Roten Beete klein würfeln und in einer Pfanne mit Butter und dem Balsamico etwa 10 Minuten köcheln lassen, bis der Essig eingekocht ist und die roten Beete bissfest sind
1. Die gerösteten Haselnüsse über die roten Beete streuen und mit Petersilie garnieren
1. Die Schollenfilets und die Blumenkohl-Rösti dazu servieren
<file_sep>---
title: Low Carb Muffins
servings: 6
cookTime: PT35M
date: '2022-02-18'
aliases:
- ../../desserts/low-carb-muffins
---
## Zutaten
- 55 g Xylit
- 40 g Kokosmehl
- 0.5 TLs Backpulver
- 0.5 Prises Salz
- 3 Eier
- 40 g Butter
- 40 g Mandelmehl
## Zubehör
- Muffin-Förmchen
## Zubereitung
1. Backofen auf 175 Grad Ober- und Unterhitze vorheizen. Die weiche Butter mit dem Xylit schaumig schlagen, nach und nach die Eier einzeln sehr gut unterrühren.
[Butter: 40 g; Eier: 3; Xylit: 55 g]
2. Kokosmehl, Mandelmehl, Salz und Backpulver mischen; kurz unter die Butter-Eier-Masse rühren. Teig sofort in Muffin-Förmchen füllen.
[Backpulver: 0.5 TLs; Kokosmehl: 40 g; Mandelmehl: 40 g; Salz: 0.5 Prises]
3. Muffins 18 Minuten backen. Eventuell gegen Ende abdecken, damit sie nicht zu braun werden.
[–]
<file_sep>---
title: Protein Pfannkuchen
date: 2015-09-19
tags:
- lowcarb
aliases:
- ../../hauptgerichte/protein-pfannkuchen
---
## Zutaten für 2 Pfannkuchen
- 1 Ei
- 5g Backpulver
- 3g Salz
- 1,5 TL Stevia (~ 0,75g)
- 50 ml Milch
- 40 g Proteinpulver
- 10 g Flohsamenschalen
- 8 g Kokosöl
## Zubereitung
Alle Zutaten mit einem Schneebesen oder einem Rührgerät vermischen, bis eine homogene Masse entstanden ist. Wasser nach Bedarf zugeben, sodass der Teig schön cremig aber nicht zu dünnflüssig ist. Das Kokosöl in einer beschichteten Pfanne zerlassen und die Pfannkuchen bei mittelerer Hitze braten.
## Nährwerte
- kcal: 343
- KH: 6g
- Fett: 17g
- Protein: 44g
<file_sep>---
title: Quarkkuchen I
date: 2015-05-20
tags:
- lowcarb
- highfat
aliases:
- ../../desserts/quarkkuchen-i
---
## Zutaten für 4 Portionen
- 500 g Magerquark
- 250 g cremiger Frischkäse
- 8-10 TL Flohsamenschalen (1 TL ~ 2g)
- 4 TL Kokosblütenzucker (1 TL ~ 3,8g)
- 1 TL Vanillepulver
- 1 Packung Backpulver
- Saft einer halben Zitrone
- 2 EL Erdnuss- oder Walnussöl
- 250g TK Waldbeeren
- etwas Kokosöl oder Butter zum Einfetten der Form
## Zubereitung
Die Tiefkühl Waldbeeren in einem Sieb mit warmen Wasser übergiessen, damit sie etwas auftauen.
Inzwischen alle Zutaten von Magerquark bis zum Öl mit einem Rührgerät verquirlen bis eine einheiliche Masse entsteht.
Eine Kastenform einfetten und die Masse hineingiessen und bei ca. 170 Grad für 30 Minuten in den Backofen. Am besten gleich am Anfang mit Alufolie abdecken, sonst wird die Oberfläche zu dunkel.
Währenddessen die eine Hälfte der Waldbeeren pürieren, bis ein Sorbeet entsteht, dann wieder mit den unpürierten Beeren vermengen.
Den Quarkkuchen portionsweise aus der Form spachteln, er wird ziemlich flüssig werden, eher wie ein Pudding. Mit den kalten Waldbeeren übergiessen und servieren.
<file_sep>---
title: Fischauflauf mit Spinat
date: 2016-03-16
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/fischauflauf-mit-spinat
---

## Zutaten
- 500 g Fisch (nach Wahl Tipp: Seelachs oder Rotbarsch)
- 1 große Zwiebel
- 2 Eier Größe
- 400 g Spinat tiefgekühlt
- 100 g Gouda 45% Fett gerieben
- für die Würze: Muskat, Meersalz, schwarzer Pfeffer und Zitronensaft
- Fett für die Auflaufform
## Zubereitung
Den Fisch mit kalten Wasser abspülen und trocken tupfen - dann von beiden Seiten mit Meersalz, frisch gemahlenen Pfeffer und ein wenig Zitronensaft würzen und in eine gefettete Auflaufform legen.
Den aufgetauten Spinat und die fein gewürfelten Zwiebeln vermengen, dann die Eier unterrühren und mit Meersalz, Pfeffer und Muskat nach Geschmack würzen.
Die Spinat Masse gleichmäßig über den Fisch in der Auflaufform verteilen. Den geriebenen Käse darüber verteilen. Auflaufform im vorgeheizten Backofen bei ca. 190 Grad mindestens 30 Minuten backen.
## Nährwerte
- kcal: 1072
- KH: 9g
- Fett: 53g
- EW: 137g
<file_sep>---
title: <NAME>
date: 2016-12-19
tags:
- lowcarb
aliases:
- ../../hauptgerichte/puten-curry
---

## Zutaten für 2 Portionen
- 500g Pute oder Hühnchen
- 1 Zwiebel
- 50ml Gemüse oder Geflügelbrühe
- 150ml Sahne
- 3-4 TL Curry
- evtl. Kurkuma oder Chili (Geschmackssache)
- Fett für fie Pfanne
- Pfeffer & Salz
## Zubereitung
Pute klein schneiden und mit dem Fett in der Pfanne anbraten. Zwiebelringe dazu geben, bis sie leicht gebräunt sind. Mit der Brühe ablöschen, kurz aufkochen lassen. Sahne und Gewürze dazugeben, Hitze reduzieren und das ganze bis zur gewünschten Konsistenz eindicken lassen. Fertig.
<file_sep>---
title: Rote Linsen Salat mit Senf
date: 2019-04-22
tags:
- slowcarb
- veggie
aliases:
- ../../salate/rote-linsen-salat-mit-senf
---

## Zutaten
- 100 g rote Linsen
- ½ kleine Zwiebel
- 1 EL Senf
- 2 EL Öl
- ½ EL Sojasauce
- Paprikapulver
- n. B. gehackte Petersilie
- n. B. Essig
- n. B. Zitronensaft
- Salz & Pfeffer
## Zubereitung
Zuerst die roten Linsen ca. 15 Min. weich kochen.
Die Zwiebel abziehen und würfeln. Die restlichen Zutaten zu einer Marinade verarbeiten und die Zwiebelwürfel zugeben. Nun die roten Linsen zugeben und untermengen.
Bis zum Verzehr evtl. noch etwas durchziehen lassen, dann schmeckt es noch besser.
<file_sep>---
title: Schnelle Linsensuppe
cookTime: PT25M
date: '2022-02-15'
carbohydrate: 204
calories: 2640
fat: 132
protein: 140
servings: 4
aliases:
- ../../hauptgerichte/schnelle-linsensuppe
---
## Zutaten
- 4 Würstchen
- 2 Butter
- 2 Möhren
- 1.2 l Wasser
- 1 Porree
- 1 Zwiebel
- 1 Prise Zucker
- 300 g Linsen
## Zubereitung
1. Porree putzen, waschen und in Ringe schneiden. Möhren schälen, waschen, der Länge nach halbieren und in Scheiben schneiden. Zwiebel schälen und fein würfeln.
[Möhren: 2; Porree: 1; Zwiebel: 1]
2. Butter in einem großen Topf erhitzen. Gemüse darin 5 Minuten andünsten.
[Butter: 2]
3. Wasser und Linsen zum Gemüse geben. Aufkochen, Brühe einrühren, 8 Minuten köcheln.
[Linsen: 300 g; Wasser: 1.2 l]
4. Die Würstchen in Scheiben schneiden, in die Suppe geben, für 5 Minuten weiterkochen.
[Würstchen: 4]
5. Mit Salz, Pfeffer, Zucker und Essig abschmecken.
[Zucker: 1 Prise]
<file_sep>---
title: Schoko Kokos Muffins
date: 2020-09-30
tags:
- lowcarb
- simple
- veggie
- protein
aliases:
- ../../desserts/schoko-kokos-muffins
---
## Zutaten für 6 Muffins
- 1 Ei
- 250 g Schmand, 20% Fett
- 25 g Kokosmehl
- 35 g Proteinpulver
- 30 g Erythrit
- 1 EL Kakaopulver
- 1/2 TL Backpulver
- 50 g Schokodrops / Kokaonibs
## Zubereitung
1. Backofen auf 175°C Umluft vorheizen
1. Alle Zutaten auf einen Schlag in eine Rührschüssel geben und gut verrühren.
1. Die cremige Masse auf 6 Portionen in einer Muffinform verteilen.
1. 25 Minuten backen und abkühlen lassen.
Wer keine Papierförmchen benutzt, sollte die Backform noch einfetten.
<file_sep>---
title: Chia Leinsamen Pudding
date: 2016-02-11
tags:
- lowcarb
- highfat
- paleo
- veggie
aliases:
- ../../snacks-und-shakes/chia-leinsamen-pudding
---



## Zutaten
- 3 EL Leinsamen (~ 30 g)
- 3 EL Chiasamen, (~ 30 g)
- 250 ml Mandel- oder Kokosmilch
- 1 EL Ghee oder Kokosfett (~ 11 g)
- evtl. etwas Stevia oder Kokosblütenzucker zum Süßen
als Topping:
- Himbeeren (oder andere Waldbeeren)
- Walnuss-, Paranuss- oder Chashewkerne
## Zubereitung
Die Lein- und Chiasamen zusammen mit dem Großteil (9/10) Mandel- oder Kokosmilch vermischen, damit sie schon mal ein bisschen aufquellen können.
Das Kokosfett bsw. Ghee bei mittlerer Hitze in einer beschichteten Pfanne zerlassen und die Flüssigkeit hineingeben. Mit einem Spatel 3 Minuten lang rühren, bis eine puddingartige Masse entstanden ist.
Vom Herd nehmen und in eine Schüssel gießen, den Rest der Mandel- oder Kokosmilch nach Belieben mit Stevia süßen und die Beeren sowie die grob gehackten Paranusskerne darübergeben.
<file_sep>---
title: Garnelen mit Frischkäse
date: 2015-03-14
tags:
- lowcarb
aliases:
- ../../hauptgerichte/garnelen-mit-frischkäse
---
## Zutaten
- 225g Garnelen Natur oder Provence
- Kokosfett
- 3 Chilis
- 200g Frischkäse
- 1 EL Olivenöl
## Zubereitung
Garnelen auftauen, abspülen, trocknen und im Kokosfett anbraten, wer mag kann noch Zwiebeln mit dazu geben. Die Chilis kleinhacken, mit dem Frischkäse und dem Öl mischen und auf die Garnelen geben, kurz warm werden lassen.
Mit Nudeln muss es göttlich schmecken.
<file_sep>---
title: Hähnchen in cremiger Erdnusssauce
date: 2019-04-04
tags:
- lowcarb
- highfat
aliases:
- ../../hauptgerichte/hähnchen-in-cremiger-erdnusssauce
---

## Zutaten für 4 Portionen
- 600 g Hähnchenbrustfilet
- 1-2 TL Currypaste
- 200 ml Kokosmilch
- 200 g Schlagsahne
- ½ Limette
- 2 EL Tamari (glutenfreie Sojasauce)
- 4 EL Erdnussbutter, cremig
- 1 handvoll Erdnüsse
- 1 <NAME>
- 2 Frühlingszwiebeln
- ½ Apfel
- Salz & Pfeffer
- Butter oder Kokosöl zum Braten
## Zubereitung
Die Hähnchenbrustfilets abspülen, abtrocknen und in Würfel schneiden. In einer Pfanne oder einem Topf in Butter oder Kokosöl gar braten.
Für die Sauce etwas Kokosöl in einer Pfanne erhitzen und die Currypaste hinzufügen, etwas anrösten. Die Limette entsaften und die Schale abreiben. Kokosmilch, Sahne, Limettensaft, Tamari und Erdnussbutter hinzufügen und umrühren, bis die Sauce eine gleichmäßige und cremige Konsistenz hat.
Die Hähnchenwürfel hinzufügen und alles etwas köcheln lassen. Mit Salz & Pfeffer abschmecken.
Den Koriander und die Frühlingszwiebeln feinhacken, den Apfel in feine Scheiben schneiden und alles zusammen mit dem Limettenabrieb und den Erdnüssen vermischen und beim Anrichten über das Gericht streuen.
Dazu passt [Blumenkohlreis]({{< relref "Blumenkohlreis" >}}) sehr gut.
<file_sep>---
title: Protein Pfannkuchen mit Frischkäse
date: 2018-02-19
tags:
- lowcarb
- highfat
- protein
aliases:
- ../../hauptgerichte/protein-pfannkuchen-mit-frischkäse
---
## Zutaten
- 100g Sahnefrischkäse
- 3 Eiklar
- 30g Proteinpulver
- Süßstoff nach Bedarf
- Kokosöl zum Braten
## Zubereitung
Kokosöl in einer beschichteten Pfanne zerlassen. Die restlichen Zutaten gut durchmischen und bei mittlerer Hitze in der Pfanne braten. Das ergibt ca. 4 kleine Pfannkuchen. Bei diesem Rezept wird die Textur und Konsistenz sehr gut, vor allem durch den Frischkäse und dem Eiklar. Allerdings schmeckt man das Ei (wie bei allen low carb Back- oder Pfannkuchenrezepten mit Ei) sehr deutlich durch.
## Nährwerte
- kcal: 513
- KH: 6 g
- Fett: 35 g
- EW: 43 g
| f698aa36458fb6f08126bdcd8544738a2c7e59f5 | [
"Markdown",
"Python",
"Makefile"
]
| 188 | Markdown | skoenig/kochbuch | b0a710f9841b9d27ddaf2299773071ddf8f1f034 | 32b406ccdb04e295c8e007acfaf9238d8f61005f |
refs/heads/develop-1.8 | <file_sep>local UI = require('opus.ui')
local Krist = require('swshop.krist')
local colors = _G.colors
local device = _G.device
local os = _G.os
--[[ Configuration Page ]]--
local wizardPage = UI.WizardPage {
title = 'Store Front',
index = 2,
form = UI.Form {
x = 2, ex = -2, y = 1, ey = -2,
manualControls = true,
[1] = UI.TextEntry {
formLabel = 'Domain', formKey = 'domain',
help = 'Krist wallet domain (minus .kst)',
limit = 64,
shadowText = 'example',
required = true,
},
[2] = UI.TextEntry {
formLabel = 'Header', formKey = 'header',
help = 'Text to show in header',
limit = 64,
shadowText = "xxxx's shop",
required = false,
},
[3] = UI.Checkbox {
formLabel = 'Single shop', formKey = 'refundInvalid',
help = 'Only this shop uses this domain',
},
[4] = UI.Checkbox {
formLabel = 'Show out of stock', formKey = 'showOutOfStock',
help = 'Show out of stock items in red',
},
[5] = UI.Chooser {
formLabel = 'RS Signal', formKey = 'rsSide', formIndex = 6,
width = 10,
choices = {
{name = 'Bottom', value = 'bottom'},
{name = 'Top', value = 'top'},
{name = 'Back', value = 'back'},
{name = 'Front', value = 'front'},
{name = 'Right', value = 'right'},
{name = 'Left', value = 'left'},
},
required = true,
},
[6] = UI.Chooser {
width = 9,
formIndex = 7,
formLabel = 'Font Size', formKey = 'textScale',
nochoice = 'Small',
choices = {
{ name = 'Small', value = .5 },
{ name = 'Large', value = 1 },
},
help = 'Adjust text scaling',
},
},
}
function wizardPage:setNode(node)
self.form:setValues(node)
end
function wizardPage:validate()
return self.form:save()
end
function wizardPage:saveNode(node)
os.queueEvent('shop_restart', node)
end
function wizardPage:isValidType(node)
local m = device[node.name]
return m and m.type == 'monitor' and {
name = 'Store Front',
value = 'shop',
category = 'display',
help = 'Add a store front display'
}
end
function wizardPage:isValidFor(node)
return node.mtype == 'shop'
end
-- [[Password View]] --
local passwordPage = UI.WizardPage {
title = 'Krist Settings',
index = 3,
form = UI.Form {
x = 2, ex = -2, y = 1, ey = -2,
manualControls = true,
passEntry = UI.TextEntry {
formIndex = 1,
formLabel = 'Password', formKey = 'password',
shadowText = 'Password',
help = 'Krist wallet password',
limit = 256,
required = true,
pass = true,
},
pkeyCheck = UI.Checkbox {
formIndex = 2,
formLabel = 'Is private key', formKey = 'isPrivateKey',
help = 'Password is in private key format',
ispkey = true,
},
preview = UI.TextEntry {
formIndex = 4,
formLabel = 'Using address', formKey = 'address',
backgroundColor = 'primary',
textColor = colors.yellow,
inactive = true,
},
},
}
local function makeAddress(text, isPrivateKey)
local privKey = text or ''
if not isPrivateKey then
privKey = Krist.toKristWalletFormat(privKey)
end
return Krist.makev2address(privKey)
end
function passwordPage.form:eventHandler(event)
if (event.type == 'text_change' and event.element.pass) or
(event.type == 'checkbox_change' and event.element.ispkey) then
self.passEntry.shadowText = self.pkeyCheck.value and 'Private key' or 'Password'
self.preview.value = makeAddress(self.passEntry.value, self.pkeyCheck.value)
self:draw()
end
return UI.Form.eventHandler(self, event)
end
function passwordPage:setNode(node)
node.address = node.password and makeAddress(node.password, node.isPrivateKey) or ''
self.form:setValues(node)
end
function passwordPage:validate()
return self.form:save()
end
function passwordPage:isValidFor(node)
return node.mtype == 'shop'
end
UI:getPage('nodeWizard').wizard:add({ storeFronta = wizardPage, storeFrontb = passwordPage })
<file_sep># opus-apps
Applications for Opus OS
| d209cc6d18ae489cf1b1b1b77b08d739fdabed46 | [
"Markdown",
"Lua"
]
| 2 | Lua | coolstar/opus-apps | c85bb530626767b80eaaedbbc0b554bc7d8c6228 | e48ec262615033f75997bdbec929f27d843a4e02 |
refs/heads/main | <repo_name>shuto1441/atcoder_archive<file_sep>/atcoder.jp/abc091/abc091_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >>N;
vector<string>s(110);
for(int i=0;i<N;i++)
cin>>s[i];
int M;
cin>>M;
vector<string>t(110);
for(int i=0;i<M;i++)
cin>>t[i];
int maxi=max(N,M);
int ans=0;
for(int i=0;i<N;i++){
int cnt=0;
for(int j=0;j<maxi;j++){
if(s[i]==s[j])
cnt++;
if(s[i]==t[j])
cnt--;
}
ans=max(ans,cnt);
}
cout<<ans<<endl;
}
<file_sep>/atcoder.jp/abc111/abc111_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string a;
cin >> a;
for(int i=0;i<3;i++)
if(a.at(i)=='1')
a.at(i)='9';
else
a.at(i)='1';
cout<<a<<endl;
}
<file_sep>/atcoder.jp/abc051/abc051_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int K,S;
int ans=0;
cin>>K>>S;
for(int i=0;i<K+1;i++){
for(int j=0;j<K+1;j++){
if(S-i-j<=K&&S-i-j>=0)
ans++;
}
}
cout << ans << endl;
}
<file_sep>/atcoder.jp/abc121/abc121_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N,M,C;
cin>>N>>M>>C;
// int型の2次元配列(3×4要素の)の宣言
vector<int>B(M);
vector<vector<int>> A(N, vector<int>(M));
for(int i=0;i<M;i++){
cin>>B.at(i);
}
// 入力 (2重ループを用いる)
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
cin >> A.at(i).at(j);
}
}
int ans=0;
int cnt;
for (int i = 0; i < N; i++) {
cnt =C;
for (int j = 0; j < M; j++) {
cnt+=A.at(i).at(j)*B.at(j);
}
if(cnt>0){
ans++;
}
}
cout << ans << endl;
}<file_sep>/atcoder.jp/abc119/abc119_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin>>N;
vector<double>a(N);
vector<string>b(N);
for(int i=0;i<N;i++)
cin>>a.at(i)>>b.at(i);
double sum=0;
for(int i=0;i<N;i++){
if(b.at(i)=="JPY")
sum+=a.at(i);
else
sum+=a.at(i)*380000;
}
cout<<sum<<endl;
}
<file_sep>/atcoder.jp/abc126/abc126_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int s;
cin>>s;
int a=s/100;
int b=s-a*100;
if(a>=1&&a<=12&&b<=12&&b>=1)
cout<<"AMBIGUOUS"<<endl;
else if(a>=1&&a<=12&&(b>12||b==0))
cout<<"MMYY"<<endl;
else if(b>=1&&b<=12&&(a>12||a==0))
cout<<"YYMM"<<endl;
else
cout<<"NA"<<endl;
}
<file_sep>/atcoder.jp/abc055/abc055_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a;
cin>>a;
cout<<a*800-a/15*200<<endl;
}
<file_sep>/atcoder.jp/abc033/abc033_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
if(s.at(0)==s.at(1)&&s.at(1)==s.at(2)&&s.at(2)==s.at(3))
cout<<"SAME"<<endl;
else
cout<<"DIFFERENT"<<endl;
}
<file_sep>/atcoder.jp/abc028/abc028_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
if(n<60)
cout<<"Bad"<<endl;
else if(n<90)
cout<<"Good"<<endl;
else if(n<100)
cout<<"Great"<<endl;
else
cout<<"Perfect"<<endl;
}
<file_sep>/atcoder.jp/abc093/abc093_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string a;
cin >> a;
if(a.at(0)!=a.at(1)&&a.at(1)!=a.at(2)&&a.at(0)!=a.at(2))
cout << "Yes" << endl;
else
cout<<"No"<<endl;
}
<file_sep>/atcoder.jp/abc102/abc102_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin>>N;
vector<int>A(N);
for(int i=0;i<N;i++)
cin>>A[i];
int max1=0;
for(int i=0;i<N-1;i++){
for(int j=i+1;j<N;j++)
max1=max(max1,abs(A[i]-A[j]));
}
cout<<max1<<endl;
}
<file_sep>/atcoder.jp/abc071/abc071_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int s,a,b;
cin >>s>> a>>b;
if(abs(s-a)>abs(s-b))
cout<<'B'<<endl;
else
cout<<'A'<<endl;
}<file_sep>/atcoder.jp/abc108/abc108_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a;
cin >> a;
cout<<(a/2)*((a+1)/2)<<endl;
}
<file_sep>/atcoder.jp/abc124/abc124_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b;
cin >> a>>b;
int ans;
if(a-1>=b)
ans = 2*a-1;
else if(a==b)
ans = a+b;
else
ans = 2*b-1;
cout << ans << endl;
}<file_sep>/atcoder.jp/abc073/abc073_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a;
cin >> a;
if(a%10==9||a/10==9)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}<file_sep>/atcoder.jp/m-solutions2019/m_solutions2019_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
int cnt=0;
for(int i=0;i<s.size();i++){
if(s.at(i)=='o')
cnt++;
}
if(cnt+15-s.size()>=8)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}<file_sep>/atcoder.jp/abc047/abc047_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int W,H,N;
cin >> W>>H>>N;
vector<vector<int>> data(N, vector<int>(3));
// 入力 (2重ループを用いる)
for (int i = 0; i < N; i++) {
for (int j = 0; j < 3; j++) {
cin >> data.at(i).at(j);
}
}
int lx=0,hx=W,ly=0,hy=H;
for(int i=0;i<N;i++){
if(data[i][2]==1)
lx=max(lx,data[i][0]);
if(data[i][2]==2)
hx=min(hx,data[i][0]);
if(data[i][2]==3)
ly=max(ly,data[i][1]);
if(data[i][2]==4)
hy=min(hy,data[i][1]);
}
if(hx-lx>=0&&hy-ly>=0)
cout<<(hx-lx)*(hy-ly)<<endl;
else
cout<<0<<endl;
}
<file_sep>/atcoder.jp/abc049/arc065_a/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define repr(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define VECV(a,n,m) vector<vector<int>> a(n, vector<int>(m));
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const ll mod = 1000000007;
bool f(string s){
bool ans=true;
rep(i,s.size()/2){
if(s[i]!=s[s.size()/2+i]){
ans=false;
break;
}
}
return ans;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
string s;
cin>>s;
string divide[4] = {"dream", "dreamer", "erase", "eraser"};
reverse(s.begin(),s.end());
rep(i,4) reverse(divide[i].begin(),divide[i].end());
bool f,f2;
f2=true;
for(int i=0;i<s.size();){
f=false;
rep(j,4){
if(s.substr(i,divide[j].size())==divide[j]){
i+=divide[j].size();
f=true;
}
}
if(!f){
f2=false;
break;
}
}
if(f2) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}<file_sep>/atcoder.jp/abc129/abc129_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int S,T,U;
cin>>S>>T>>U;
cout<<min(S+T,min(S+U,T+U))<<endl;
}<file_sep>/atcoder.jp/arc004/arc004_1/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin>>N;
vector<double>x(N);
vector<double>y(N);
for(int i=0;i<N;i++)
cin>>x[i]>>y[i];
double ans=0;
for(int i=0;i<N-1;i++){
for(int j=i+1;j<N;j++){
ans = max(ans,sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])));
}
}
cout << ans << endl;
}
<file_sep>/atcoder.jp/dp/dp_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,k;
cin>>n>>k;
int h[n];
int dp[n];
for(int i=0;i<n;i++){
cin>>h[i];
}
for(int i=0;i<n;i++){
dp[i]=INT_MAX;
}
dp[0]=0;
for(int i=0;i<n;i++){
for(int j=1;j<=k;j++){
if(i+j<n){
dp[i+j]=min(dp[i+j],dp[i]+abs(h[i]-h[i+j]));
}
}
}
cout<<dp[n-1]<<endl;
}
<file_sep>/atcoder.jp/abc018/abc018_1/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int>A(3);
vector<int>B(3);
for(int i=0;i<3;i++){
cin>>A[i];
B[i]=A[i];
}
sort(A.begin(),A.end());
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(B[i]==A[j])
cout<<3-j<<endl;
}
}
}
<file_sep>/atcoder.jp/abc054/abc054_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
if(a==1&&b!=1)
cout<<"Alice"<<endl;
else if(a!=1&&b==1)
cout<<"Bob"<<endl;
else if(a==b)
cout<<"Draw"<<endl;
else if(a>b)
cout<<"Alice"<<endl;
else
cout<<"Bob"<<endl;
}
<file_sep>/atcoder.jp/abc105/abc105_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin>>N;
string ans="No";
for(int i=0;i<N/4+1;i++){
if((N-4*i)%7==0){
ans="Yes";
break;
}
}
cout << ans << endl;
}
<file_sep>/atcoder.jp/abc015/abc015_1/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
string a,b;
cin >> a>>b;
if(a.size()>b.size())
cout << a<<endl;
else
cout <<b<<endl;
}
<file_sep>/atcoder.jp/abc004/abc004_1/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a;
cin>>a;
cout<<2*a<<endl;
}
<file_sep>/atcoder.jp/abc128/abc128_b/Main.cpp
#include <bits/stdc++.h>
#include<algorithm>
#include<complex>
#include<ctype.h>
#include<iomanip>
#include<iostream>
#include<map>
#include<math.h>
#include<numeric>
#include<queue>
#include<set>
#include<stack>
#include<stdio.h>
#include<string>
#include<string>
#include<vector>
using namespace std;
bool compare_by_b(pair<string, int> a, pair<string, int> b) {
if(a.first == b.first){
return a.second > b.second;
}else{
return a.first < b.first;
}
}
int main(){
int N;
cin>>N;
vector<pair<string, int> > pairs(N);
vector<pair<string, int> > copy(N);
for(int i=0;i<N;i++){
string a;
int b;
cin >> a >> b;
pairs[i] = make_pair(a, b);
copy[i] = make_pair(a,b);
}
sort(pairs.begin(),pairs.end(), compare_by_b);
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if(pairs[i]==copy[j]){
cout<<j+1<<endl;
break;
}
}
}
}
<file_sep>/atcoder.jp/abc019/abc019_1/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int>A(3);
for(int i=0;i<3;i++){
cin>>A[i];
}
sort(A.begin(),A.end());
cout<<A[1]<<endl;
}
<file_sep>/atcoder.jp/abc053/abc053_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string str;
cin >> str;
int count1,count2 = 0;
for (int i = 0; i < str.size(); i++) {
if (str.at(i) == 'A') {
count1=i+1;
break;
}
}
for(int i=str.size()-1;i>0;i--){
if(str.at(i)=='Z'){
count2=i+1;
break;
}
}
cout<<count2-count1+1<<endl;
}
<file_sep>/atcoder.jp/abc049/abc049_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
char a;
cin >> a;
if(a=='a'||a=='u'||a=='i'||a=='o'||a=='e')
cout << "vowel" << endl;
else
cout << "consonant" << endl;
}<file_sep>/atcoder.jp/abc104/abc104_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string N;
cin>>N;
int count=0;
int ans=0;
if(N.at(0)!='A')
ans=1;
for(int i=2;i<N.size()-1;i++){
if(isupper(N.at(i))){
if(N.at(i)=='C')
count++;
else
ans=1;
}
if(ans==1)
break;
}
if(count!=1)
ans=1;
if(isupper(N.at(N.size()-1))||isupper(N.at(1)))
ans=1;
if(ans==0)
cout<<"AC"<<endl;
else
cout<<"WA"<<endl;
}
<file_sep>/atcoder.jp/abc081/abc081_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int cnt=0;
for(int i=0;i<3;i++){
if(s.at(i)=='1')
cnt++;
}
cout<<cnt<<endl;
}
<file_sep>/atcoder.jp/abc098/abc098_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b;
cin >> a>>b;
int max1 = max(max(a+b,a-b),max(a-b,a*b));
cout<<max1<<endl;
}
<file_sep>/atcoder.jp/abc115/abc115_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int s;
cin>>s;
vector<int>vec(s);
for(int i=0;i<s;i++){
cin>>vec[i];
}
sort(vec.begin(),vec.end());
int sum=0;
for(int i=0;i<s;i++){
sum+=vec[i];
}
cout<<sum-vec[s-1]/2<<endl;
}
<file_sep>/atcoder.jp/abc112/abc112_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int N,T;
cin>>N>>T;
vector<pair<int, int> > pairs(N);
for(int i=0;i<N;i++){
int a;
int b;
cin >> a >> b;
pairs[i] = make_pair(b, a);
}
sort(pairs.begin(),pairs.end());
int ans=1000000000;
for(int i=0;i<N;i++){
if(pairs[i].first<=T)
ans=min(ans,pairs[i].second);
else
break;
}
if(ans==1000000000)
cout<<"TLE"<<endl;
else
cout<<ans<<endl;
}
<file_sep>/atcoder.jp/abc037/abc037_b/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define repr(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const ll mod = 1000000007;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int N,Q;
cin>>N>>Q;
int L[Q],R[Q];
ll T[Q];
rep(i,Q){
cin>>L[i]>>R[i]>>T[i];
}
ll A[N];
rep(i,N)
A[i]=0;
rep(i,Q){
FOR(j,L[i]-1,R[i]){
A[j]=T[i];
}
}
rep(i,N){
cout<<A[i]<<endl;
}
}
<file_sep>/atcoder.jp/abc043/abc043_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int N;
cin>>N;
int sum=0;
for(int i=1;i<N+1;i++)
sum+=i;
cout<<sum<<endl;
}
<file_sep>/atcoder.jp/abc100/abc100_b/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define repr(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const ll mod = 1000000007;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int D,N;
cin>>D>>N;
if(N==100){
if(D==0){
cout<<101<<endl;
return 0;
}
if(D==1){
cout<<101*100<<endl;
return 0;
}
if(D==2){
cout<<101*10000<<endl;
return 0;
}
}
if(D==0){
cout<<N<<endl;
return 0;
}
else if(D==1){
cout<<N*100<<endl;
return 0;
}
else if(D==2){
cout<<N*10000<<endl;
return 0;
}
}
<file_sep>/atcoder.jp/abc125/abc125_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,t;
cin>>a>>b>>t;
cout<<t/a*b<<endl;
}
<file_sep>/atcoder.jp/abc166/abc166_d/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define repr(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define VECV(a,n,m) vector<vector<int>> a(n, vector<int>(m));
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const ll mod = 1000000007;
bool f(string s){
bool ans=true;
rep(i,s.size()/2){
if(s[i]!=s[s.size()/2+i]){
ans=false;
break;
}
}
return ans;
}
vector<ll> calc(ll n){
ll a = 2;
cout<<"ok";
vector<ll> v;
while (n >= a) {
if (n % a == 0) {
cout<<a;
n /= a;
if(v.back()!=a)v.push_back(a);
}
else a+=1;
}
return v;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
ll X;
cin>>X;
for(int i=-1000;i<1001;i++){
for(int j=-1000;j<1001;j++){
if(pow(i,5)-pow(j,5)==X){
cout<<i<<" "<<j<<endl;
return 0;
}
}
}
}
<file_sep>/atcoder.jp/abc089/abc089_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
string s;
int cnt = 0;
cin >> n;
for(int i = 0; i < n; i++){
cin >> s;
if(s == "Y"){
cnt++;
}
}
if(cnt > 0)
cout << "Four" << endl;
else
cout << "Three" << endl;
}
<file_sep>/atcoder.jp/abc031/abc031_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
cout<<max((a+1)*b,a*(b+1))<<endl;
}
<file_sep>/atcoder.jp/abc009/abc009_1/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a;
cin>>a;
cout<<(a+1)/2<<endl;
}
<file_sep>/atcoder.jp/abc048/abc048_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
string a,b,c;
cin >> a >> b >>c;
char s = b.at(0);
cout << "A"<<s<<"C"<<endl;
}
<file_sep>/atcoder.jp/APG4b/APG4b_ci/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int A, B, C;
cin >> A >> B >> C;
int max1 = max(A,B);
int max2 = max(B,C);
int max3 = max(max1,max2);
int min1 = min(A,B);
int min2 = min(C,B);
int min3 = min(min1,min2);
cout << max3 - min3 <<endl;
}
<file_sep>/atcoder.jp/abc042/abc042_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N,L;
cin >> N>>L;
vector<string>vec(N);
for (int i = 0;i < N;++i)
cin>>vec[i];
sort(vec.begin(),vec.end());
for (int i = 0;i < N;++i)
cout<<vec[i];
cout<<endl;
}
<file_sep>/atcoder.jp/tenka1-2019-beginner/tenka1_2019_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int x,y,z;
cin>>x>>y>>z;
if(min(x,y)<z&&max(x,y)>z)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
<file_sep>/atcoder.jp/abc114/abc114_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
vector<int>ans(s.size()-2);
int sum;
for(int i=0;i<s.size()-2;i++){
sum=(s.at(i)-'0')*100+(s.at(i+1)-'0')*10+(s.at(i+2)-'0');
ans[i]=abs(sum-753);
}
sort(ans.begin(),ans.end());
cout<<ans[0]<<endl;
}
<file_sep>/atcoder.jp/abc076/abc076_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int n,k;
cin >> n >>k;
int cnt = 1;
for(int i = 0; i < n; i++){
if(cnt > k)
cnt += k;
else
cnt *= 2;
}
cout << cnt << endl;
}
<file_sep>/atcoder.jp/abc061/abc061_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int x,y,z;
cin>>x>>y>>z;
bool f=false;
if(z>=x&&z<=y)
f=true;
if(f)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
<file_sep>/atcoder.jp/abc118/abc118_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b;
cin >> a>>b;
int ans;
if(b%a==0)
ans = a+b;
else
ans = b-a;
cout << ans<<endl;
}
<file_sep>/atcoder.jp/abc072/abc072_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b;
cin >> a>>b;
if(a>=b)
cout<<a-b<<endl;
else
cout<<0<<endl;
}<file_sep>/atcoder.jp/abc127/abc127_d/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define repr(i, n) for(int i = n-1; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const ll mod = 1000000007;
bool f(string s){
bool ans=true;
rep(i,s.size()/2){
if(s[i]!=s[s.size()/2+i]){
ans=false;
break;
}
}
return ans;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int N,M;
cin>>N>>M;
vector<l_l> pairs(M);
vector<ll>A(N);
rep(i,N) cin>>A[i];
sort all(A);
rep(i,M){
ll a;
ll b;
cin >> a >> b;
pairs[i] = make_pair(b, a);
}
sort all(pairs);
vector<ll>D(N);
int cnt=0;
repr(i,M){
rep(j,pairs[i].second){
if(cnt==N)
break;
else{
D.push_back(pairs[i].first);
cnt++;
}
}
if(cnt==N)
break;
}
ll ans=0;
sort all(D);
reverse all(D);
rep(i,N){
ans+=max(A[i],D[i]);
}
cout<<ans<<endl;
}
<file_sep>/atcoder.jp/abc081/abc081_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int n,a;
cin >> n;
int min = 10000;
for(int i = 0; i < n; i++){
cin >> a;
int cnt = 0;
while(a%2==0){
a /=2;
cnt ++;
}
if(cnt < min)
min =cnt;
}
cout << min << endl;
}
<file_sep>/atcoder.jp/abc090/abc090_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int a,b;
cin >> a >> b;
int cnt = 0;
int n =a;
for(int i = a; i < b+1; i++){
if((n/10000==n%10)&&(n/1000%10)==(n/10%10))
cnt ++;
n++;
}
cout << cnt << endl;
}
<file_sep>/atcoder.jp/abc128/abc128_d/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define repr(i, n) for(int i = n-1; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const ll mod = 1000000007;
bool f(string s){
bool ans=true;
rep(i,s.size()/2){
if(s[i]!=s[s.size()/2+i]){
ans=false;
break;
}
}
return ans;
}
ll a[55],n,k;
ll dfs(ll l,ll r){
ll s;
vector<ll> vec;
for(int i=0;i<=l;i++) vec.push_back(a[i]);
for(int i=r;i<n;i++) vec.push_back(a[i]);
sort(vec.begin(),vec.end());
ll maxs;
maxs=k-vec.size();
if(maxs<0) return 0;
s=0;
for(int i=0;i<vec.size();i++){
if(vec[i]<0&&maxs>0){
maxs--;
}
else{
s+=vec[i];
}
}
return s;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>k;
rep(i,n){
cin>>a[i];
}
ll ans=0;
for(int i=-1;i<n;i++){
for(int j=i+1;j<=n;j++){
ans=max(ans,dfs(i,j));
}
}
cout<<ans<<endl;
return 0;
}
<file_sep>/atcoder.jp/abc090/abc090_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string a,b,c;
cin >> a>>b>>c;
cout << a.at(0)<<b.at(1)<<c.at(2) << endl;
}
<file_sep>/archive.sh
#!/bin/bash
procon-gardener archive
cd /home/ishii/github/atcoder_archive
git push origin HEAD<file_sep>/atcoder.jp/abc026/abc026_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a;
cin>>a;
if(a%2==0)
cout<<a*a/4<<endl;
else
cout<<a/2*(a/2+1)<<endl;
}
<file_sep>/atcoder.jp/abc065/abc065_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int X,A,B;
cin>>X>>A>>B;
if(A-B>=0)
cout<<"delicious"<<endl;
else if(B-A<=X)
cout<<"safe"<<endl;
else
cout<<"dangerous"<<endl;
}
<file_sep>/atcoder.jp/abc102/abc102_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a;
cin >> a;
if(a%2==0)
cout<<a<<endl;
else
cout<<a*2<<endl;
}
<file_sep>/atcoder.jp/abc133/abc133_e/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define repr(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const int mod=1000000007,MAX=100001;
vector<int> S[MAX];
vector<ll> dis(MAX);
ll ans,K;
ll BFS(){
queue<int> Q;
ll ans=1;
Q.push(0);
dis[0]=0;
ans*=K;
while(!Q.empty()){
int a=Q.front();
Q.pop();
int cnt=0;
for(int i=0;i<S[a].size();i++){
int b=S[a][i];
if(dis[b]==-1){
if(dis[a]==0){
ans*=(K-1-cnt);
ans=ans%mod;
cnt++;
dis[b]=1;
}else{
ans*=(K-2-cnt);
ans=ans%mod;
cnt++;
dis[b]=dis[a]+1;
}
Q.push(b);
}
}
}
return ans;
}
int main(){
int N;cin>>N>>K;
for(int i=0;i<N-1;i++){
int a,b;cin>>a>>b;
a--;b--;
S[a].push_back(b);
S[b].push_back(a);
}
for(int i=0;i<N;i++){
dis[i]=-1;
}
cout<<BFS()<<endl;
}
<file_sep>/atcoder.jp/abc078/abc078_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int ans(char x){
int ans;
if(x=='A')
ans=10;
else if(x=='B')
ans=11;
else if(x=='C')
ans=12;
else if(x=='D')
ans=13;
else if(x=='E')
ans=14;
else
ans=15;
return ans;
}
int main() {
char a,b;
cin >> a>>b;
int x,y;
x=ans(a);
y=ans(b);
if(x>y)
cout<<'>'<<endl;
else if(x<y)
cout<<'<'<<endl;
else
cout<<'='<<endl;
}
<file_sep>/atcoder.jp/abc106/abc106_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b;
cin >> a>>b;
cout<<a*b-a-b+1<<endl;
}
<file_sep>/atcoder.jp/abc101/abc101_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin>>N;
int sum=0;
int tmp=N;
int tmp1;
while(tmp!=0){
tmp1=tmp;
sum+=tmp%10;
tmp=tmp1/10;
}
if(N%sum==0)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
<file_sep>/atcoder.jp/abc119/abc119_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
if((s.at(5)=='0'&&s.at(6)=='4')||(s.at(5)=='0'&&s.at(6)=='3')||(s.at(5)=='0'&&s.at(6)=='2')||(s.at(5)=='0'&&s.at(6)=='1'))
cout << "Heisei" << endl;
else
cout<<"TBD"<<endl;
}
<file_sep>/atcoder.jp/abc061/abc061_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
//入力部
int N,M;
cin>>N>>M;
vector<int>a(M);
vector<int>b(M);
vector<int>c(N);
for(int i = 0;i < M; i++){
cin>>a.at(i)>>b.at(i);
}
//上下の文字列
for(int i = 0;i < N; i++){
for(int j=0;j < M; j++){
if (i + 1== a[j]|| i+1==b[j])
c[i]++;
}
}
for(int i =0;i<N;i++)
cout<<c.at(i)<<endl;
}
<file_sep>/atcoder.jp/abc095/abc095_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N,X;
cin>>N>>X;
vector<int>m(N);
int sum=0;
for(int i=0;i<N;i++){
cin>>m[i];
sum+=m[i];
}
sort(m.begin(),m.end());
cout<<(X-sum)/m[0]+N<<endl;
}
<file_sep>/atcoder.jp/abc067/abc067_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
// 各桁の和を計算する関数
int main() {
int N,K;
cin >> N>>K;
vector<int>vec(N);
for (int i = 0; i < N; ++i)
cin>>vec[i];
sort(vec.begin(),vec.end());
reverse(vec.begin(),vec.end());
int sum=0;
for(int i=0;i<K;i++)
sum+=vec[i];
cout << sum << endl;
}
<file_sep>/atcoder.jp/dp/dp_c/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e9)
#define PI (acos(-1))
const ll mod = 1000000007;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int N;
cin>>N;
int a[N],b[N],c[N];
rep(i,N){
cin>>a[i]>>b[i]>>c[i];
}
int dp[N][3];
rep(i,N){
rep(j,3){
dp[i][j]=0;
}
}
dp[0][0]=a[0];
dp[0][1]=b[0];
dp[0][2]=c[0];
rep(i,N-1){
dp[i+1][0]=max(dp[i][1]+a[i+1],dp[i][2]+a[i+1]);
dp[i+1][1]=max(dp[i][0]+b[i+1],dp[i][2]+b[i+1]);
dp[i+1][2]=max(dp[i][1]+c[i+1],dp[i][0]+c[i+1]);
}
cout<<max(dp[N-1][0],max(dp[N-1][1],dp[N-1][2]))<<endl;;
}
<file_sep>/atcoder.jp/abc109/abc109_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin>>N;
// 100要素の配列で初期化
vector<string> x(N);
int ans=0;
for(int i=0;i<N;i++)
cin>>x.at(i);
for(int i=0;i<N;i++){
for(int j=i+1;j<N;j++){
if(x.at(i)==x.at(j)){
ans=1;
break;
}
if(ans==1)
break;
}
}
string tmp=x[0];
for(int i=1;i<N;i++){
if(x[i].at(0)!=tmp.at(tmp.size()-1)){
ans=1;
break;
}
tmp=x.at(i);
}
if(ans==1)
cout<<"No"<<endl;
else
cout<<"Yes"<<endl;
}
<file_sep>/atcoder.jp/abc059/abc059_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
string a,b,c;
cin>>a>>b>>c;
transform (a.begin (), a.end (), a.begin (), ::toupper);
transform (b.begin (), b.end (), b.begin (), ::toupper);
transform (c.begin (), c.end (), c.begin (), ::toupper);
cout<<a.at(0)<<b.at(0)<<c.at(0)<<endl;
}
<file_sep>/atcoder.jp/abc105/abc105_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b;
int ans;
cin >> a>>b;
if(a%b==0)
ans = 0;
else
ans =1;
cout<<ans<<endl;
}
<file_sep>/atcoder.jp/abc085/abc085_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string a;
cin >> a;
a.at(3)='8';
cout << a << endl;
}
<file_sep>/atcoder.jp/abc024/abc024_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,c,d,s,t;
cin>>a>>b>>c>>d>>s>>t;
if(s+t>=d)
cout<<a*s+b*t-(s+t)*c<<endl;
else
cout<<a*s+b*t<<endl;
}
<file_sep>/atcoder.jp/abc053/abc053_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a;
cin>>a;
if(a<1200)
cout<<"ABC"<<endl;
else
cout<<"ARC"<<endl;
}
<file_sep>/atcoder.jp/abc112/abc112_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a;
int b,c;
cin >> a>>b>>c;
if(a==1)
cout<<"Hello World"<<endl;
else
cout<<b+c<<endl;
}
<file_sep>/atcoder.jp/abc127/abc127_c/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N,M;
cin>>N>>M;
vector<int> a(M);
vector<int> b(M);
for (int i = 0; i < M; i++) {
cin >> a.at(i)>>b.at(i);
}
sort(a.begin(), a.end());
sort(b.begin(), b.end());
if(b[0]>=a[M-1])
cout<<b[0]-a[M-1]+1<<endl;
else
cout<<0<<endl;
}
<file_sep>/atcoder.jp/abc165/abc165_b/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define repr(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define VECV(a,n,m) vector<vector<int>> a(n, vector<int>(m));
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const ll mod = 1000000007;
bool f(string s){
bool ans=true;
rep(i,s.size()/2){
if(s[i]!=s[s.size()/2+i]){
ans=false;
break;
}
}
return ans;
}
int gcd(int a, int b) {
int v0 = a, v1 = b, v2 = a % b;
while (v2 != 0) {
v0 = v1;
v1 = v2;
v2 = v0 % v1;
};
return v1;
}
int gcd3(int a, int b,int c){
return gcd(gcd(a,b),c);
}
int mid(int a, int b, int c){
if(max(max(a,b),c)==a && min(min(a,b),c)==b)
return c;
if(max(max(a,b),c)==a && min(min(a,b),c)==c)
return b;
if(max(max(a,b),c)==b && min(min(a,b),c)==a)
return c;
if(max(max(a,b),c)==b && min(min(a,b),c)==c)
return a;
if(max(max(a,b),c)==c && min(min(a,b),c)==a)
return b;
if(max(max(a,b),c)==c && min(min(a,b),c)==b)
return a;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
ll X;
cin>>X;
int i=0;
ll ans=100;
while (ans < X) {
ans*=1.01;
i+=1;
}
cout<<i<<endl;
}
<file_sep>/atcoder.jp/dp/dp_e/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const ll mod = 1000000007;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
ll N,W;
cin>>N>>W;
ll w[N],v[N];
rep(i,N){
cin>>w[i]>>v[i];
}
ll dp[N][100001];
rep(i,N){
rep(j,100001){
dp[i][j]=INF;
}
}
dp[0][0]=0;
dp[0][v[0]]=w[0];
rep(i,N-1){
rep(j,100001){
dp[i+1][j]=min(dp[i][j],dp[i+1][j]);
if(dp[i][j]+w[i+1]<=W&&j+v[i+1]<=100000)
dp[i+1][j+v[i+1]]=min(dp[i+1][j+v[i+1]],dp[i][j]+w[i+1]);
}
}
ll ans=INF;
rep(i,100001){
if(dp[N-1][i]!=INF&&dp[N-1][i]!=0)
ans=i;
}
cout<<ans<<endl;
}
<file_sep>/atcoder.jp/abc036/abc036_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,x;
cin>>n>>x;
cout<<(x+n-1)/n<<endl;
}
<file_sep>/atcoder.jp/tenka1-2019-beginner/tenka1_2019_b/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int N,K;
string S;
cin>>N>>S>>K;
for(int i=0;i<N;i++){
if(S.at(K-1)!=S.at(i))
S.at(i)='*';
}
cout<<S<<endl;
}
<file_sep>/atcoder.jp/abc123/abc123_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int ordinary(int x){
return (x+9)/10*10;
}
int last(int x){
return x;
}
int main() {
int a,b,c,d,e;
cin >> a>>b>>c>>d>>e;
vector<int>vec={a,b,c,d,e};
int min1=9999;
int sum=0;
for(int i=0;i<5;i++)
sum+=ordinary(vec[i]);
for(int i=0;i<5;i++){
if(min1>=sum-ordinary(vec[i])+last(vec[i]))
min1=sum-ordinary(vec[i])+last(vec[i]);
}
cout<<min1<<endl;
}
<file_sep>/atcoder.jp/APG4b/APG4b_ck/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string S;
cin >> S;
int a=0,b=0;
for(int i=0; i < S.size(); i++){
if(S.at(i)=='+')
a++;
if(S.at(i)=='-')
b++;
}
cout << 1+a-b << endl;
}
<file_sep>/atcoder.jp/abc046/abc046_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,c;
cin>>a>>b>>c;
int cnt=1;
if(a!=b)
cnt++;
if(a!=c&&b!=c)
cnt++;
cout<<cnt<<endl;
}
<file_sep>/atcoder.jp/abc127/abc127_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int r,D,x;
cin >> r>>D>>x;
int tmp1=x;
int tmp;
for(int i=1;i<11;i++){
tmp=tmp1;
cout<<r*tmp-D<<endl;
tmp1=r*tmp-D;
}
}<file_sep>/atcoder.jp/abc085/abc085_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
int ans;
cin >> N;
vector<int> vec(N);
for(int i = 0;i < N;i++)
cin >> vec[i];
sort(vec.begin(), vec.end());
int tmp = vec[0];
for(int i = 0;i < N-1;i++){
if(tmp != vec[i+1])
ans++;
tmp=vec[i+1];
}
cout << ans+1 << endl;
}
<file_sep>/atcoder.jp/abc088/abc088_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
int sum = 0;
cin >> N;
vector<int> vec(N);
for(int i = 0;i < N;i++)
cin >> vec[i];
sort(vec.begin(), vec.end());
reverse(vec.begin(), vec.end());
for(int i = 0;i < N;i++){
if(i%2==1)
sum -= vec[i];
else if(i==0)
sum += vec[i];
else
sum += vec[i];
}
cout << sum << endl;
}
<file_sep>/atcoder.jp/abc100/abc100_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b;
cin >> a>>b;
if(a>8||b>8)
cout<<":("<<endl;
else
cout<<"Yay!"<<endl;
}
<file_sep>/atcoder.jp/abc035/abc035_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int gcd(int a,int b){
if(b==0)
return a;
return gcd(b,a%b);
}
int main(){
int n,x;
cin>>n>>x;
cout<<n/gcd(n,x)<<':'<<x/gcd(n,x)<<endl;
}
<file_sep>/atcoder.jp/abc077/abc077_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string a,b;
cin >> a>>b;
if(a.at(0)==b.at(2)&&a.at(1)==b.at(1)&&a.at(2)==b.at(0))
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
<file_sep>/atcoder.jp/abc115/abc115_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a;
cin >> a;
if(a==22)
cout << "Christmas Eve Eve Eve"<<endl;
else if(a==23)
cout << "Christmas Eve Eve"<<endl;
else if(a==24)
cout << "Christmas Eve"<<endl;
else
cout << "Christmas"<<endl;
}
<file_sep>/atcoder.jp/dp/dp_d/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e9)
#define PI (acos(-1))
const ll mod = 1000000007;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
ll N,W;
cin>>N>>W;
ll w[N],v[N];
rep(i,N){
cin>>w[i]>>v[i];
}
ll dp[N][W+1];
rep(i,N){
rep(j,W+1){
dp[i][j]=-INF;
}
}
dp[0][0]=0;
dp[0][w[0]]=v[0];
rep(i,N-1){
rep(j,W+1){
dp[i+1][j]=max(dp[i][j],dp[i+1][j]);
if(j+w[i+1]<=W)
dp[i+1][j+w[i+1]]=max(dp[i+1][j+w[i+1]],dp[i][j]+v[i+1]);
}
}
ll ans=-INF;
rep(i,W+1){
ans=max(dp[N-1][i],ans);
}
cout<<ans<<endl;
}
<file_sep>/atcoder.jp/abc108/abc108_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
int x3=x2+y1-y2;
int y3=y2+x2-x1;
int x4=x1+y1-y2;
int y4=x2-x1+y1;
cout<<x3<<' '<<y3<<' '<<x4<<' '<<y4<<endl;
}
<file_sep>/atcoder.jp/abc044/abc044_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int N,K,X,Y;
cin>>N>>K>>X>>Y;
if(N<=K)
cout<<N*X<<endl;
else
cout<<K*X+(N-K)*Y<<endl;
}
<file_sep>/atcoder.jp/abc017/abc017_1/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int>A(3);
vector<int>B(3);
for(int i=0;i<3;i++){
cin>>A[i]>>B[i];
}
int ans=0;
for(int i=0;i<3;i++){
ans+=A[i]*B[i]/10;
}
cout<<ans<<endl;
}
<file_sep>/atcoder.jp/abc096/abc096_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b;
cin >> a>>b;
if(a<=b)
cout<<a<<endl;
else
cout<<a-1<<endl;
}
<file_sep>/atcoder.jp/abc068/abc068_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a;
cin >>a;
int tmp,tmp1,cnt,ans1;
int ans=0;
for(int i=1;i<a+1;i++){
tmp=i;
cnt=0;
while(tmp%2==0){
tmp1=tmp;
tmp=tmp/2;
cnt++;
}
if(cnt>ans){
ans=cnt;
ans1=i;
}
}
if(a==1)
ans1=1;
cout<<ans1<<endl;
}
<file_sep>/atcoder.jp/abc084/abc084_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int A,B;
string s;
cin>>A>>B>>s;
bool f=false;
if(s.at(A)!='-')
f = true;
for(int i=0;i<A;i++){
if(s.at(i)=='-'){
f=true;
break;
}
}
for(int i=A+1;i<s.size();i++){
if(s.at(i)=='-'){
f=true;
break;
}
}
if(f)
cout<<"No"<<endl;
else
cout<<"Yes"<<endl;
}
<file_sep>/atcoder.jp/abc131/abc131_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string N;
cin>>N;
if(N[0]==N[1]||N[1]==N[2]||N[2]==N[3])
cout<<"Bad"<<endl;
else
cout<<"Good"<<endl;
}
<file_sep>/atcoder.jp/abc120/abc120_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b,c;
cin>>a>>b>>c;
int cnt=0;
for(int i=min(a,b);i>0;i--){
if(a%i==0&&b%i==0)
cnt++;
if(cnt==c){
cout<<i<<endl;
break;
}
}
}
<file_sep>/atcoder.jp/abc122/abc122_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
char a,b;
cin >> a;
if(a=='A')
b = 'T';
else if(a=='T')
b = 'A';
else if(a=='G')
b = 'C';
else
b ='G';
cout << b << endl;
}<file_sep>/atcoder.jp/abc072/abc072_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string str;
cin >> str;
for (int i = 0; i < str.size(); i+=2)
cout << str.at(i);
cout<<endl;
}
<file_sep>/atcoder.jp/abc110/abc110_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b,c;
cin >> a>>b>>c;
int ans;
int max1=max(max(a,b),max(b,c));
if(max1==a)
ans=10*a+b+c;
else if(max1==b)
ans=10*b+a+c;
else
ans=10*c+a+b;
cout<<ans<<endl;
}
<file_sep>/atcoder.jp/dp/dp_a/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e9)
#define PI (acos(-1))
const ll mod = 1000000007;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int N;
cin>>N;
int h[N];
rep(i,N){
cin>>h[i];
}
int dp[N];
rep(i,N){
dp[i]=INF;
}
dp[0]=0;
dp[1]=abs(h[1]-h[0]);
rep(i,N-2){
dp[i+2]=min(dp[i+1]+abs(h[i+2]-h[i+1]),dp[i]+abs(h[i+2]-h[i]));
}
cout<<dp[N-1]<<endl;;
}
<file_sep>/atcoder.jp/abc129/abc129_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin>>N;
vector<int>S(N);
for (int i=0;i<N;i++){
cin>>S[i];
}
int sum=0;
for (int i=0;i<N;i++){
sum+=S[i];
}
int ans=0;
int tmp;
for (int i=0;i<N;i++){
ans+=S[i];
if(ans >=sum/2){
tmp=i;
break;
}
}
cout<<min(abs(sum-ans-ans),abs(sum-ans+S[tmp]-ans+S[tmp]))<<endl;
}<file_sep>/atcoder.jp/APG4b/APG4b_cj/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
int sum =0;
vector<int> vec(N);
for(int i = 0; i < N; i++){
cin >> vec.at(i);
}
for(int i = 0; i < N; i++){
sum += vec.at(i);
}
int avg = sum/N;
for(int i = 0; i < N; i++){
if(vec[i]>avg)
cout<<vec[i]-avg<<endl;
else
cout<<avg-vec[i]<<endl;
}
}
<file_sep>/atcoder.jp/abc117/abc117_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
double a,b;
cin >> a>>b;
cout << a/b<<endl;
}
<file_sep>/atcoder.jp/abs/arc065_a/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define repr(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define VECV(a,n,m) vector<vector<int>> a(n, vector<int>(m));
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
#define SET(value) set<int>value
#define SORT_G(a,N) sort(a,a+N,greater<int>())
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const ll mod = 1000000007;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
string S;
cin>>S;
string divide[4] = {"dream", "dreamer", "erase", "eraser"};
reverse(S.begin(),S.end());
rep(i,4) reverse(divide[i].begin(),divide[i].end());
bool can = true;
rep(i,S.size()){
bool can2 = false;
rep(j,4){
if(S.substr(i,divide[j].size())==divide[j]){
can2=true;
i+=divide[j].size()-1;
}
}
if(!can2){
can=false;
break;
}
}
if(can) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
return 0;
}
<file_sep>/README.md
# atcoder_archive
# Reference
[procon-gardener](https://github.com/togatoga/procon-gardener)<file_sep>/atcoder.jp/abc025/abc025_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
int n;
cin>>s>>n;
cout<<s.at((n-1)/5)<<s.at((n-1)%5)<<endl;
}
<file_sep>/atcoder.jp/abc103/abc103_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b,c,d,e,f;
cin >> a>>b>>c;
if(a-b>=0)
d=a-b;
else
d=b-a;
if(a-c>=0)
e=a-c;
else
e=c-a;
if(b-c>=0)
f=b-c;
else
f=c-b;
int max1=max(max(d,e),max(e,f));
cout<<d+e+f-max1<<endl;
}
<file_sep>/atcoder.jp/abc104/abc104_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a;
cin >> a;
if(a<1200)
cout<<"ABC"<<endl;
else if(a>=2800)
cout<<"AGC"<<endl;
else
cout<<"ARC"<<endl;
}
<file_sep>/atcoder.jp/abc042/abc042_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,c;
cin>>a>>b>>c;
if(a==5&&b==5&&c==7||a==7&&b==5&&c==5||a==5&&b==7&&c==5)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
<file_sep>/atcoder.jp/abc032/abc032_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int gcd(int a,int b){
if(b==0)
return a;
return gcd(b,a%b);
}
int main(){
int a,b,n;
cin>>a>>b>>n;
int lms=a*b/gcd(a,b);
cout<<(n+lms-1)/lms*lms<<endl;
}
<file_sep>/atcoder.jp/abc110/abc110_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N,M,X,Y;
cin>>N>>M>>X>>Y;
// 100要素の配列で初期化
vector<int> x(N);
vector<int>y(M);
for(int i=0;i<N;i++)
cin>>x.at(i);
for(int i=0;i<M;i++)
cin>>y.at(i);
sort(x.begin(),x.end());
sort(y.begin(),y.end());
int ans=0;
int tmp=X+1;
for(int i=X;i<Y;i++){
if(x.at(N-1)<tmp&&y.at(0)>=tmp){
cout<<"No War"<<endl;
ans=1;
break;
}
tmp++;
}
if(ans==0)
cout<<"War"<<endl;
}
<file_sep>/atcoder.jp/abc071/abc071_b/Main.cpp
// std::set を用いた解
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin>>s;
for(char i='a';i<='z';i++){
bool f=false;
for(int j=0;j<s.size();j++){
if(i==s[j]){
f=true;
}
}
if(!f){
cout<<i<<endl;
return 0;
}
}
cout<<"None"<<endl;
}
<file_sep>/atcoder.jp/agc025/agc025_a/Main.cpp
#include <iostream>
using namespace std;
// 各桁の和を計算する関数
int findSumOfDigits(int n) {
int sum = 0;
while (n > 0) { // n が 0 になるまで
sum += n % 10;
n /= 10;
}
return sum;
}
int main() {
int N;
cin >> N;
int ans = 99999;
for (int i = 1; i <= N-1; ++i) {
int sum = findSumOfDigits(i)+findSumOfDigits(N-i); // i の各桁の和
ans=min(ans,sum);
}
cout << ans << endl;
}
<file_sep>/atcoder.jp/abc122/abc122_b/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
int cnt =0;
int ans=0;
for(int i=0;i<s.size();i++){
if(s.at(i)=='A'||s.at(i)=='C'||s.at(i)=='G'||s.at(i)=='T')
cnt++;
else
cnt=0;
if(cnt>ans)
ans=cnt;
}
cout<<ans<<endl;
}
<file_sep>/atcoder.jp/abc097/abc097_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b,c,d;
cin >> a>>b>>c>>d;
if(abs(a-c)<=d||(abs(a-b)<=d&&abs(b-c)<=d))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
<file_sep>/atcoder.jp/abc124/abc124_c/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
// int型の2次元配列(3×4要素の)の宣言
string s;
cin>>s;
int count1=0;
int count2=0;
// 入力 (2重ループを用いる)
for (int i = 0; i < s.size(); i++) {
if(i%2==0){
if(s.at(i)=='0')
count1++;
else
count2++;
}
else{
if(s.at(i)=='0')
count2++;
else
count1++;
}
}
cout<<min(count1,count2)<<endl;
}<file_sep>/atcoder.jp/abc064/abc064_b/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define repr(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const ll mod = 1000000007;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int N;
cin>>N;
VEC(A,N);
rep(i,N)
cin>>A[i];
sort all(A);
cout<<A[N-1]-A[0]<<endl;
}
<file_sep>/atcoder.jp/abc051/abc051_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
s.at(5)=' ';
s.at(13)=' ';
cout<<s<<endl;
}
<file_sep>/atcoder.jp/abc074/abc074_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int n,k,a;
cin >> n >>k;
int cnt = 0;
for(int i = 0; i < n; i++){
cin >> a;
if(a < k -a )
cnt += 2*a;
else
cnt += 2*(k-a);
}
cout << cnt << endl;
}
<file_sep>/atcoder.jp/abc062/abc062_b/Main.cpp
#include<iostream>
#include<vector>
#include<cstdlib>
#include<string>
using namespace std;
int main(){
//入力部
int H,W;
cin>>H>>W;
vector<string>a(H);
for(int i = 0;i < H; i++){
cin>>a.at(i);
}
//上下の文字列
vector<string>b(W+2,"#");
for(int i = 0;i < W+2; i++){
cout<<b.at(i);
}
cout<<endl;
//n行目の処理
for(int i = 0;i < H; i++){
cout<<"#"<<a.at(i)<<"#"<<endl;
}
for(int i = 0;i < W+2; i++){
cout<<b.at(i);
}
cout<<endl;
return 0;
}
<file_sep>/atcoder.jp/abc125/abc125_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
vector<int>a(n);
vector<int>b(n);
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<n;i++)
cin>>b[i];
vector<int>c(n);
int sum =0;
for(int i=0;i<n;i++)
c[i]=a[i]-b[i];
sort(c.begin(),c.end());
reverse(c.begin(),c.end());
for(int i=0;i<n;i++){
if(c[i]>0)
sum+=c[i];
else
break;
}
cout<<sum<<endl;
}
<file_sep>/atcoder.jp/abc129/abc129_d/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define repr(i, n) for(int i = n-1; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const ll mod = 1000000007;
bool f(string s){
bool ans=true;
rep(i,s.size()/2){
if(s[i]!=s[s.size()/2+i]){
ans=false;
break;
}
}
return ans;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int H,W;
cin>>H>>W;
vector<string>S(H);
rep(i,H){
cin>>S[i];
}
vector<vector<ll>> L(H, vector<ll>(W));
vector<vector<ll>> R(H, vector<ll>(W));
vector<vector<ll>> D(H, vector<ll>(W));
vector<vector<ll>> U(H, vector<ll>(W));
vector<vector<ll>> dp(H, vector<ll>(W));
rep(i,H){
rep(j,W){
if(S[i][j]=='#')
L[i][j]=0;
else if(j==0)
L[i][j]=1;
else
L[i][j]=L[i][j-1]+1;
}
}
repr(i,H){
repr(j,W){
if(S[i][j]=='#')
R[i][j]=0;
else if(j==W-1)
R[i][j]=1;
else
R[i][j]=R[i][j+1]+1;
}
}
rep(i,H){
rep(j,W){
if(S[i][j]=='#')
U[i][j]=0;
else if(i==0)
U[i][j]=1;
else
U[i][j]=U[i-1][j]+1;
}
}
repr(i,H){
rep(j,W){
if(S[i][j]=='#')
D[i][j]=0;
else if(i==H-1)
D[i][j]=1;
else
D[i][j]=D[i+1][j]+1;
}
}
ll ans=0;
rep(i,H){
rep(j,W){
dp[i][j]=L[i][j]+R[i][j]+U[i][j]+D[i][j]-3;
ans=max(dp[i][j],ans);
}
}
cout<<ans<<endl;
}
<file_sep>/atcoder.jp/abc132/abc132_b/Main.c
#include<stdio.h>
int main(void){
int i,n,count=0;
scanf("%d",&n);
int p[n];
for(i=0;i<n;i++){
scanf("%d",&p[i]);
}
for(i=0;i<n-2;i++){
if((p[i]<p[i+1])&&(p[i+1]<p[i+2])){
count+=1;
}
else if((p[i]>p[i+1])&&(p[i+1]>p[i+2])){
count+=1;
}
}
printf("%d\n",count);
return 0;
}<file_sep>/atcoder.jp/abc045/abc045_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,h;
cin>>a>>b>>h;
cout<<(a+b)*h/2<<endl;
}
<file_sep>/atcoder.jp/abc029/abc029_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
string a;
cin >> a;
cout << a<<'s'<<endl;
}
<file_sep>/atcoder.jp/abc013/abc013_1/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
char a;
cin>>a;
if(a=='A')
cout<<1<<endl;
if(a=='B')
cout<<2<<endl;
if(a=='C')
cout<<3<<endl;
if(a=='D')
cout<<4<<endl;
if(a=='E')
cout<<5<<endl;
}
<file_sep>/atcoder.jp/abc133/abc133_d/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define repr(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const ll mod = 2019;
bool f(string s){
bool ans=true;
rep(i,s.size()/2){
if(s[i]!=s[s.size()/2+i]){
ans=false;
break;
}
}
return ans;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int N;
cin>>N;
vector<ll>A(N);
vector<ll>M(N);
rep(i,N){
cin>>A[i];
}
M[0]=0;
for(int i=0;i<N-2;i+=2){
M[i+2]=M[i]+(A[i+1]-A[i])*2;
}
M[1]=M[N-1]+(A[0]-A[N-1])*2;
for(int i=1;i<N-2;i+=2){
M[i+2]=M[i]+(A[i+1]-A[i])*2;
}
ll Msum=0,Asum=0;
for(int i=0;i<N;i++){
Msum+=M[i];
Asum+=A[i];
}
ll ans =(Asum-Msum)/N;
for(int i=0;i<N;i++){
cout<<M[i]+ans<<" ";
}
cout<<endl;
}<file_sep>/atcoder.jp/abc111/abc111_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
for(int i=1;i<10;i++){
if(n<=i*111){
cout<<i*111<<endl;
break;
}
}
}<file_sep>/atcoder.jp/abc069/abc069_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >>s;
cout<<s.at(0)<<s.size()-2<<s.at(s.size()-1)<<endl;
}
<file_sep>/atcoder.jp/abc080/abc080_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int b =0;
for(int i = n; i > 0; i/=10)
b += i%10;
if(n%b==0)
cout << "Yes" << endl;
else
cout << "No" <<endl;
}
<file_sep>/atcoder.jp/abc040/abc040_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,x;
cin>>n>>x;
cout<<min(n-x,x-1)<<endl;
}
<file_sep>/atcoder.jp/abc133/abc133_b/Main.cpp
using namespace std;
#include <bits/stdc++.h>
#define rep(i, s) for (int i = 0; i < s; ++i)
#define repr(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define all(v) (v.begin(), v.end())
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define EPS (1e-7)
#define INF (1e10)
#define PI (acos(-1))
const ll mod = 1000000007;
bool f(string s){
bool ans=true;
rep(i,s.size()/2){
if(s[i]!=s[s.size()/2+i]){
ans=false;
break;
}
}
return ans;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int N,D;
cin>>N>>D;
vector<vector<int>> data(N, vector<int>(D));
// 入力 (2重ループを用いる)
for (int i = 0; i < N; i++) {
for (int j = 0; j < D; j++) {
cin >> data.at(i).at(j);
}
}
int cnt=0;
rep(i,N){
FOR(j,i+1,N){
int ans=0;
rep(k,D){
ans+=(data[i][k]-data[j][k])*(data[i][k]-data[j][k]);
}
int ans2=sqrt(ans);
if(ans2*ans2==ans)
cnt++;
}
}
cout<<cnt<<endl;
}<file_sep>/atcoder.jp/abc022/abc022_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,s,t;
cin>>n>>s>>t;
int ans=0;
vector<int>vec(n);
for(int i=0;i<n;i++){
cin>>vec[i];
}
int cnt=0;
for(int i=0;i<n;i++){
ans+=vec[i];
if(ans>=s&&ans<=t)
cnt++;
}
cout<<cnt<<endl;
}
<file_sep>/atcoder.jp/abc106/abc106_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin>>N;
int ans=0;
int count;
for(int i=1;i<N+1;i+=2){
count=0;
for(int j=1;j<i+1;j++){
if(i%j==0)
count++;
}
if(count==8)
ans++;
}
cout<<ans<<endl;
}
<file_sep>/atcoder.jp/abc116/abc116_b/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int s;
cin>>s;
vector<int>vec(10000);
int tmp=s;
vec.at(0)=s;
for(int i=0;i<9999;i++){
if(vec.at(i)==4||vec.at(i)==2||vec.at(i)==1){
cout<<i+4<<endl;
break;
}
tmp=vec.at(i);
if(tmp%2==0)
vec.at(i+1)=tmp/2;
else
vec.at(i+1)=3*tmp+1;
}
}
<file_sep>/atcoder.jp/abc130/abc130_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int X,A;
cin>>X>>A;
if(X<A)
cout<<0<<endl;
else
cout<<10<<endl;
}
<file_sep>/atcoder.jp/abc095/abc095_a/Main.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string a;
cin >> a;
int ans = 0;
for(int i=0;i<3;i++){
if(a.at(i)=='o')
ans++;
}
cout << ans*100+700 << endl;
}
<file_sep>/atcoder.jp/abc062/abc062_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int x,y;
cin>>x>>y;
vector<int>A={1,3,5,7,8,10,12};
vector<int>B={4,6,9,11};
bool f=false;
for(int i=0;i<5;i++){
for(int j=i+1;j<6;j++){
if(A[i]==x&&A[j]==y)
f=true;
}
}
for(int i=0;i<3;i++){
for(int j=i+1;j<4;j++){
if(B[i]==x&&B[j]==y)
f=true;
}
}
if(f)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
<file_sep>/atcoder.jp/abc113/abc113_b/Main.cpp
#include <bits/stdc++.h>
#include<cmath>
using namespace std;
int main() {
int N,T,A;
cin>>N>>T>>A;
vector<int>H(N);
for(int i=0;i<N;i++){
cin>>H[i];
}
int ans=999999999;
int ans1;
for(int i=0;i<N;i++){
if(ans>abs((T*1000-H[i]*6)-A*1000)){
ans=abs((T*1000-H[i]*6)-A*1000);
ans1=i+1;
}
}
cout<<ans1<<endl;
}
<file_sep>/atcoder.jp/abc063/abc063_a/Main.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int A,B;
cin>>A>>B;
if(A+B<10)
cout<<A+B<<endl;
else
cout<<"error"<<endl;
} | 15cec5616a1c10924ebfd7d1db2134dbcc4e5598 | [
"Markdown",
"C",
"C++",
"Shell"
]
| 145 | C++ | shuto1441/atcoder_archive | 8c3cc31ebe39746e26f8fdef4f6ac289d34f91a0 | 2c474a379b6b3df8783504335cc678b3e45fc0e8 |
refs/heads/master | <repo_name>ka7eh/clowder-extractor-pytorch<file_sep>/clowder-pytorch-extractor-example/example-extractor/example_extractor.py
#!/usr/bin/env python
import logging
from pyclowder.extractors import Extractor
import pyclowder.files
import pyclowder.utils
import torch
import torchvision
class ExampleExtractor(Extractor):
def __init__(self):
super(ExampleExtractor, self). __init__()
# parse command line and load default logging configuration
self.setup()
# setup logging for the extractor
logging.getLogger('pyclowder').setLevel(logging.DEBUG)
logging.getLogger('__main__').setLevel(logging.DEBUG)
def process_message(self, connector, host, secret_key, resource, parameters):
# Process the file and upload the results
input_file = resource["local_paths"][0]
file_id = resource['id']
metadata = {
"@context": {
"@vocab": "http://www.w3.org/2003/12/exif/ns"
},
"file_id": file_id,
"content": {
"test_tag": "success"
},
"agent": {
"@type": "cat:extractor",
"extractor_id": host + "/api/extractors/ncsa.image.metadata"
}
}
pyclowder.files.upload_metadata(connector, host, secret_key, file_id, metadata)
if __name__ == "__main__":
extractor = ExampleExtractor()
extractor.start()
<file_sep>/Dockerfile
FROM clowder/pyclowder:onbuild
RUN apt update && apt upgrade -y
RUN pip install future torch torchvision
<file_sep>/README.md
## A Clowder Extractor Docker Image with PyTorch and torchvision

See the latest published image on [Docker Hub](https://hub.docker.com/repository/docker/kavehk/clowder-extractor-pytorch).
### Example usage
Run `docker-compose up` in `clowder-pytorch-extractor-example` to start a Clowder instance with `example-extractor`,
which has `pytorch` and `torchvision` installed.
| 72dabd7cb2c03edaa6106e314cba6ecbabae417a | [
"Markdown",
"Python",
"Dockerfile"
]
| 3 | Python | ka7eh/clowder-extractor-pytorch | e59fda28b7d54125f5607cb25921770179d3a2f8 | f99b1f4991ac800133cd9ecbd20132f1fd5ad8c4 |
refs/heads/master | <repo_name>ValkyrieUK/Rails-Chat<file_sep>/app/controllers/messages_controller.rb
class MessagesController < ApplicationController
def index
if current_user.present?
@messages = Message.all
else
redirect_to root_url, notice: "Please log in to continue"
end
end
def create
@message = Message.create!(params[:message])
PrivatePub.publish_to("/messages/new", message: @message)
@message.user_username = current_user.username
flash[:error] = "something went wrong" unless @message.save
end
end
<file_sep>/db/migrate/20131205134149_salt_and_hash.rb
class SaltAndHash < ActiveRecord::Migration
def removing_password
remove_column :user, :password
remove_column :user, :password_confirmation
add_column :user, :password_hash
add_column :user, :password_salt
end
end
<file_sep>/README.rdoc
== Rails-Chat
A chat room application
== Launching
run rails s
and in a new tab in the same dir
run rackup private_pub.ru -s thin -E production
<file_sep>/db/migrate/20131205135208_drop_table.rb
class DropTable < ActiveRecord::Migration
def drop_table
end
end
<file_sep>/db/migrate/20131219104715_add_username_to_messages.rb
class AddUsernameToMessages < ActiveRecord::Migration
def change
add_column :messages, :user_username, :string
remove_column :messages, :user_id
end
end
| 3697564edc81fcb68bb6c327157f181a78227e91 | [
"RDoc",
"Ruby"
]
| 5 | Ruby | ValkyrieUK/Rails-Chat | 666632847365937c5763c78febb52bd31a37ffdd | 12ee1ddbef8e7513290da90cf9dbfaadc19c5f34 |
refs/heads/master | <file_sep>package Sept_8_20;
public class UTSspet2020 {
public static void main (String[] args) {
String huruf = "ABCDEFGHIJKLMNOPQRSTUVWXYZ-";
char fn [] = {huruf.charAt(5),huruf.charAt(0),huruf.charAt(17),huruf.charAt(7),huruf.charAt(0),huruf.charAt(13),huruf.charAt(26)};
char pa [] = {huruf.charAt(15),huruf.charAt(4),huruf.charAt(17),huruf.charAt(12),huruf.charAt(0),huruf.charAt(13),huruf.charAt(0)};
String fn = new String(fn);
String pa = new String(pa);
System.out.println(fn+pa);
}
}
| ad8062d93e2e2327598ca09329a657cdecc721cc | [
"Java"
]
| 1 | Java | Muhamad-ux/UTS | d80b3582442b2a16f14f2ea179326d50a4ec39c9 | f62ea498752b464ca0b61e8ca72c38d036e6ac8e |
refs/heads/master | <file_sep>package com.fzy.xiaoshuo.controller;
import cn.hutool.core.map.MapUtil;
import com.fzy.xiaoshuo.common.Result;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@RestController
public class AuthController extends BaseController {
@Autowired
private Producer producer;
//
// /**
// * 图片验证码
// */
@GetMapping("/captcha")
public Result captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 生成随机五位数验证码
String code = producer.createText();
// 生成key 存到redis
String key = UUID.randomUUID().toString();
// 生成图片
BufferedImage image = producer.createImage(code);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", outputStream);
BASE64Encoder encoder = new BASE64Encoder();
String str = "data:image/jpeg;base64,";
String base64Img = str + encoder.encode(outputStream.toByteArray());
// 存储到redis中
redisUtils.set(key,code,120L);
log.info("验证码 -- {} - {}", key, code);
return Result.success(MapUtil.builder().put("token", key).put("base64Img", base64Img).build());
}
}
<file_sep>package com.fzy.xiaoshuo.common;
import lombok.Data;
// 消息封装类
@Data
public class Result {
private int code;
private String msg;
private Object data;
public static final Result success(int code,String msg,Object data){
Result r = new Result();
r.setCode(code);
r.setMsg(msg);
r.setData(data);
return r;
}
public static final Result success(Object data){
return success(200,"操作成功",data);
}
public static final Result error(int code,String msg,Object data){
Result r = new Result();
r.setCode(code);
r.setMsg(msg);
r.setData(data);
return r;
}
public static final Result error(String msg,Object data){
return error(400,msg,data);
}
public static final Result error(String msg){
return error(400,msg,null);
}
}
<file_sep>package com.fzy.xiaoshuo.controller;
import com.fzy.xiaoshuo.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BaseController {
@Autowired
HttpServletResponse resp;
@Autowired
HttpServletRequest req;
@Autowired
RedisUtils redisUtils;
}
<file_sep>package com.fzy.xiaoshuo.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.fzy.xiaoshuo.dao")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
/**
* 乐观锁配置
* 当要更新一条记录的时候,希望这条记录没有被别人更新
* 乐观锁实现方式:
* 取出记录时,获取当前version
* 更新时,带上这个version
* 执行更新时, set version = newVersion where version = oldVersion
* 如果version不对,就更新失败
*/
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
// 添加分页插件
PaginationInnerInterceptor pageInterceptor = new PaginationInnerInterceptor();
// 设置请求的页面大于最大页后操作,true调回到首页,false继续请求。默认false
// pageInterceptor.setOverflow(false);
// 单页分页条数限制,默认无限制
// pageInterceptor.setMaxLimit(500L);
// 设置数据库类型
pageInterceptor.setDbType(DbType.MYSQL);
interceptor.addInnerInterceptor(pageInterceptor);
return interceptor;
}
} | 48c93a59651714f856f84c7d38e8a42c6d15728e | [
"Java"
]
| 4 | Java | mayadebi/springboot | 2e70b88d0a7260f917e5b7e685e770e5a8649831 | fb9a4a61dba9df4a4bf7ff5851d2bb00b0165669 |
refs/heads/master | <file_sep>CONFIG_LIBAV="\
--disable-bzlib \
--disable-muxers \
--disable-bsfs \
--disable-avdevice \
--disable-devices \
--disable-filters \
--disable-encoders \
--enable-muxer=spdif \
--enable-protocols \
--enable-demuxers \
--enable-parsers \
--enable-decoders \
--enable-libdav1d"
| fd3b6f5e30c9bb890fa81776cfcb3847282abaf4 | [
"Shell"
]
| 1 | Shell | cyb3rpunk452/aos-ffmpeg-android-builder | 2f7c4b4ec973a9a03824e232922227a433ae693b | 929b8f445fcc40a859d017505e850d6b6f0e19b4 |
refs/heads/master | <file_sep>// TODO: Rename the file to something actually useful
/**
* IIFE --> Immediately Invoked Function Expression
* Function that is executed as soon at it is defined.
* Avoid the anti pattern that is 'global scope'
*/
(function() {
// Forcing the browser to evaluate JS in a stricter way
// by converting code mistakes to syntax error among other things
'use strict'
// Create a data structure representing our tasks
var tasks = [];
// Query the DOM for ul elements and assign the result to a variable.
var ul = document.querySelector('ul');
// Get the form element
var form_el = document.getElementById('task');
// Get the input text box
var input_text_box = document.getElementById('input_text')
/**
* Get stored tasks from the browsers local storage
*/
function getStoredTasks(){
var locStorage = localStorage.getItem('nerdschool-todo-tasks')
return JSON.parse(locStorage);
}
/**
* Function that runs when the page loads
*/
window.onload = function() {
var storedData = getStoredTasks();
console.log(storedData);
for(var i = 0; i < storedData.length; i++){
tasks.push(storedData[i]);
}
renderTasks();
}
/**
* Store all tasks from array 'tasks' to browser local storage
*/
function storeAllTasks(){
var arr_len = tasks.length;
if(arr_len = 0){
return;
} else {
var stringify = JSON.stringify(tasks);
localStorage.setItem('nerdschool-todo-tasks', stringify);
}
}
/**
* Adds all tasks in array 'tasks' to the page's local 'ul' element
*/
function renderTasks(){
// Remove all 'li' elements from 'ul'
while(ul.firstChild) {
ul.removeChild(ul.firstChild);
}
for(var i = 0; i < tasks.length; i++){
ul.appendChild(createTaskElement(tasks[i].name));
}
storeAllTasks();
}
/**
* Add tasks to array 'tasks'
* @param {*} description
*/
function addTasks(description){
var newTask = {
name: description
};
tasks.push(newTask);
}
/**
* Create list element based on form input
* I.e. the text written in the input box
* @param {*} description
*/
function createTaskElement(description){
// Create a new list element
var listItem = document.createElement('li');
// Create a input element of type checkbox
var checkbox = document.createElement('input');
checkbox.type='checkbox';
// Create a new label element (text for checkbox)
var label = document.createElement('label');
// The label must have a child node with text = description
var label_description = document.createTextNode(description);
label.appendChild(label_description);
listItem.appendChild(checkbox);
listItem.appendChild(label);
return listItem;
}
/**
* Handling of the submitted form
* @param {*} event
*/
function submitFormHandler(event){
// Extracting the value of the submitted text-field
var input_text = event.target.querySelector('input').value;
input_text.value = '';
addTasks(input_text);
var listItem = createTaskElement(input_text)
ul.appendChild(listItem);
renderTasks();
event.preventDefault();
}
// Register submitFormHandler as an event listenre on the form element
// listening for 'submit' events
form_el.addEventListener('submit', submitFormHandler);
})();<file_sep># Project from a Nerdschool Bergen gathering
------------
├── README.md <- The top-level README for developers using this project.
│
├── classes <-.css files:
│ screen - main .css file
│
├── scripts <- .js files
│ script - main .js file
│
├── TODO.html <- .html page displaying the TODO-list
------------
<file_sep># various-js
Various javascript 'tutorial' projects
| 602c277547e8890647885f2b07dd6189df25b3c1 | [
"JavaScript",
"Markdown"
]
| 3 | JavaScript | Sindreedelange/various-js | b59a3394043407a1160653b1dbb2ab85e5947548 | b9af6af5368250a826d2225d47000476d8b0cfbb |
refs/heads/master | <repo_name>rohitchhabra95/MQTT-publisher_subscriber-<file_sep>/final_publisher_rohit.py
import paho.mqtt.client as mqtt
# This is the Publisher
def on_publish(client,userdata,result): #create function for callback
print("data published \n")
pass
client = mqtt.Client("sdfaaaghjaacvbnvbn")
client.on_publish= on_publish
client.connect("www.ioturtle.com",1883,60)
client.publish("topic/test", "This is my server move back bitches !!")
#client.disconnect();
<file_sep>/README.md
# MQTT-publisher_subscriber-
This contains a connection between publisher and subscriber when you are using MQTT.
<file_sep>/final_subscriber_rohit.py
import paho.mqtt.client as mqtt
# This is the Subscriber
def on_connect(client, userdata, flags, rc):
print("Connected with rohit server "+str(rc))
client.subscribe("topic/test")
def on_message(client, userdata, message):
print ("Message received: " + message.payload.decode())
#print("Yes!")
#client.disconnect()
client = mqtt.Client("sdfghjertycvbn")
client.connect("www.ioturtle.com",1883,60)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever() | 926bca5c235ec1542efc80c741cecdde0eb6d50c | [
"Markdown",
"Python"
]
| 3 | Python | rohitchhabra95/MQTT-publisher_subscriber- | 8782e5ce57ae439fe1660e19980af77c19664226 | 3684cb32b1c25b57337c66d883ae8cb37026cefc |
refs/heads/master | <file_sep># hacking-taoe
Repo for the source code of exercises included in <NAME>'s Hacking: The Art of Exploitation
<file_sep>#include <stdio.h>
#include <stdlib.h>
int global_var;
int global_initialized_var = 5;
void function()
{
int stack_var;
printf("The function's stack_var is at address %p\n", &stack_var);
}
int main()
{
int stack_var;
static int static_initialized_var = 5;
static int static_var;
int *heap_var_ptr;
heap_var_ptr = (int *) malloc(4);
//Data segment
printf("global_initialized_var is at address %p\n", &global_initialized_var);
printf("static_initialized_var is at address %p\n\n", &static_initialized_var);
//BSS segment
printf("static_var is at address %p\n", &static_var);
printf("global_var is at address %p\n\n", &global_var);
//Heap segment
printf("heap_var is at address %p\n\n", heap_var_ptr);
//Stack segment
printf("stack_var is at address %p\n", &stack_var);
function();
return 0;
}<file_sep>PROGRAM=$1
CPROGRAM="$PROGRAM.c"
# if [ gcc -g $CPROGRAM -o $PROGRAM ]; then
# echo "ERROR!!!"
# exit
# fi
gcc -g $CPROGRAM -o $PROGRAM
sudo chown root:root $PROGRAM
sudo chmod u+s $PROGRAM
echo " "
echo "STARTING PROGRAM"
echo " "
./$PROGRAM
<file_sep>#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "hacking.h"
#define FILENAME "/var/notes"
int main()
{
int fd = open(FILENAME, O_RDONLY);
char byte;
printf("Testing read()\n");
while (read(fd, &byte, 1))
{
printf("%c", byte);
}
return 0;
}<file_sep>#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
int main(int argc, char const *argv[])
{
int fd = open("/tmp/lseek_test", O_RDONLY);
char burn;
read(fd, &burn, 1);
while(burn != 'y')
read(fd, &burn, 1);
printf("%c", burn);
lseek(fd, -3, SEEK_CUR);
read(fd, &burn, 1);
read(fd, &burn, 1);
read(fd, &burn, 1);
printf("%c\n", burn);
close(fd);
return 0;
}<file_sep>#include <stdio.h>
#include <string.h>
int sum(int a, int b)
{
return a + b;
}
int main()
{
char str_a[20];
strcpy(str_a, "Hello, world!\n");
printf(str_a);
printf("%d", sum(1,2));
return 0;
}<file_sep>#include <stdio.h>
int main()
{
// printf("%u \t %u", sizeof(unsigned int), sizeof(int*));
int i;
char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
int int_array[5] = {1, 2, 3, 4, 5};
long unsigned int hack_nonpointer;
hack_nonpointer = (long unsigned int) char_array;
for (i = 0; i < 5; i++)
{
printf("[integer pointer] points to %p, which contains the char %c\n", hack_nonpointer, *((char *) hack_nonpointer));
hack_nonpointer = hack_nonpointer + sizeof(char);
}
hack_nonpointer = (long unsigned int) int_array;
for (i = 0; i < 5; i++)
{
printf("[char pointer] points to %p, which contains the int %d\n", hack_nonpointer, *((int *) hack_nonpointer));
hack_nonpointer = hack_nonpointer + sizeof(int);
}
return 0;
} | f6f02f24d5e61c7f254d44a33532703752e754b4 | [
"Markdown",
"C",
"Shell"
]
| 7 | Markdown | Loptt/hacking-taoe | bcde6c421372f7f3ba143f994c2ccd9df1c3966c | 072db07e777a9b5929f7f5fe8eb701f196f1b0ed |
refs/heads/master | <repo_name>ownelin/linux_class<file_sep>/b.py
print("git")
| 9014e27d3c874e3628bb76e504d7c3f94e0e1d2f | [
"Python"
]
| 1 | Python | ownelin/linux_class | 6bedfcccf1fa32ec08d52d1e1578e7d6ef3af27c | b5095355f0db24c04008344a5430ff42505f7aaa |
refs/heads/master | <file_sep>class DoNothingYet < ActiveRecord::Migration
def self.up
# instructions for changing the db to a new state
end
def self.down
# instructions for changing the db back to the previous state
end
end
<file_sep># PositionMover is a module to manage the :position
# attribute of a model.
# Put in the "/lib" folder and include it in any class
# (with a :position column) using "include PositionMover".
# NB: Plug-ins such as "acts_as_list" offer additional
# functionality and better performance.
module PositionMover
# <tt>move_to_position</tt> is an instance method that
# will move a list item to a new position, but also
# increment/decrement the positions of the other list items
# as necessary.
#
# Send nil as the value for new_position to remove
# the item from the list.
def move_to_position(new_position)
max_position = self.class.where(position_scope).count
# ensure new_position is an integer in 1..max_position
unless new_position.nil?
new_position = [[1, new_position.to_i].max, max_position].min
end
if position == new_position # do nothing
return true
elsif position.nil? # not in list yet
increment_items(new_position, 1000000)
elsif new_position.nil? # remove from list
decrement_items(position+1, 1000000)
elsif new_position < position # shift lower items up
increment_items(new_position, position-1)
elsif new_position > position # shift higher items down
decrement_items(position+1, new_position)
end
return update_attribute(:position, new_position)
end
private
# <tt>position_scope</tt> defines an SQL fragment used for
# narrowing the scope of queries related to position.
#
# Often it is not desirable to manage positions for all items
# in a class, but instead to narrow the scope based on a
# parent class. For example, if subject1 has 3 pages and
# subject2 has 4 pages, you would want to narrow the scope of
# position so that when working with subject1's pages only
# positions 1-3 under that subject are reordered. The positions
# of subject2's pages should be unchanged. And each subject
# should be able to have a page at position 1.
#
# To narrow the scope, override this method in your model
# with the SQL that should be used to narrow the scope.
# (NB: Must come after "include PositionMover".)
#
# Example:
# class Page < ActiveRecord::Base
# include PositionMover
# def position_scope
# "pages.subject_id = #{subject_id.to_i}"
# end
# end
def position_scope
# default is always true
# won't affect SQL conditions or narrow scope
"1=1"
end
def increment_items(first, last)
items = self.class.where(["position >= ? AND position <= ? AND #{position_scope}", first, last])
items.each {|i| i.update_attribute(:position, i.position + 1) }
end
def decrement_items(first, last)
items = self.class.where(["position >= ? AND position <= ? AND #{position_scope}", first, last])
items.each {|i| i.update_attribute(:position, i.position - 1) }
end
end
<file_sep>DROP TABLE IF EXISTS `admin_users`;
CREATE TABLE `admin_users` (
`id` int(11) NOT NULL,
`first_name` varchar(25) DEFAULT NULL,
`last_name` varchar(50) DEFAULT NULL,
`email` varchar(100) NOT NULL DEFAULT '',
`hashed_password` varchar(40) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`username` varchar(25) DEFAULT NULL,
`salt` varchar(40) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `index_admin_users_on_username` (`username`)
);
INSERT INTO `admin_users` VALUES (1,'Kevin','Skoglund','<EMAIL>','0<PASSWORD>','2010-09-26 13:56:25','2010-10-04 16:50:59','kskoglund','347dbace3a94ce62d9e8d1bfc5168bec9feeecb8');
DROP TABLE IF EXISTS `admin_users_pages`;
CREATE TABLE `admin_users_pages` (
`admin_user_id` int(11) DEFAULT NULL,
`page_id` int(11) DEFAULT NULL,
KEY `index_admin_users_pages_on_admin_user_id_and_page_id` (`admin_user_id`,`page_id`)
);
INSERT INTO `admin_users_pages` VALUES (1,2);
DROP TABLE IF EXISTS `pages`;
CREATE TABLE `pages` (
`id` int(11) NOT NULL,
`subject_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`permalink` varchar(255) DEFAULT NULL,
`position` int(11) DEFAULT NULL,
`visible` tinyint(1) DEFAULT '0',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `index_pages_on_subject_id` (`subject_id`),
KEY `index_pages_on_permalink` (`permalink`)
);
INSERT INTO `pages` VALUES (2,1,'First Page','first',1,1,'2010-10-06 18:25:08','2010-10-04 21:18:05'),(3,NULL,'Second Page','second',2,0,'2010-10-06 18:26:09','2010-10-02 17:16:18'),(5,2,'Revised First Page','rfirst',1,1,'2010-10-04 19:29:53','2010-10-04 19:29:53'),(6,1,'Second page','second_page',2,1,'2010-10-04 20:05:53','2010-10-04 20:06:05');
DROP TABLE IF EXISTS `schema_migrations`;
CREATE TABLE `schema_migrations` (
`version` varchar(255) NOT NULL,
UNIQUE KEY `unique_schema_migrations` (`version`)
);
INSERT INTO `schema_migrations` VALUES ('20100423211100'),('20100423211421'),('20100423214919'),('20100423232138'),('20100423232147'),('20100423232154'),('20100426135018'),('20100426145232');
DROP TABLE IF EXISTS `section_edits`;
CREATE TABLE `section_edits` (
`id` int(11) NOT NULL,
`admin_user_id` int(11) DEFAULT NULL,
`section_id` int(11) DEFAULT NULL,
`summary` varchar(255) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `index_section_edits_on_admin_user_id_and_section_id` (`admin_user_id`,`section_id`)
);
INSERT INTO `section_edits` VALUES (1,1,1,'Test edit','2010-09-26 14:58:42','2010-09-26 14:59:09'),(2,1,1,'Ch-ch-ch-changes','2010-09-26 15:01:31','2010-09-26 15:01:31');
DROP TABLE IF EXISTS `sections`;
CREATE TABLE `sections` (
`id` int(11) NOT NULL,
`page_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`position` int(11) DEFAULT NULL,
`visible` tinyint(1) DEFAULT '0',
`content_type` varchar(255) DEFAULT NULL,
`content` text,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `index_sections_on_page_id` (`page_id`)
);
INSERT INTO `sections` VALUES (1,2,'Section One',1,1,'text','This is sample content.','2010-09-26 14:57:35','2010-10-02 17:16:36'),(2,2,'Section Two',2,1,'text','Another section of text.','2010-10-04 20:07:15','2010-10-04 20:07:15');
DROP TABLE IF EXISTS `subjects`;
CREATE TABLE `subjects` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`position` int(11) DEFAULT NULL,
`visible` tinyint(1) DEFAULT '0',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `subjects` VALUES (1,'Initial Subject',2,1,'2010-09-29 20:51:00','2010-10-04 19:59:09'),(2,'Revised Subject',1,1,'2010-09-29 20:54:16','2010-10-04 19:59:09'),(4,'Third Subject',3,0,'2010-09-30 14:31:00','2010-10-04 19:05:54');
| 7b3785136b004afc83b1dcf1573549ab3289fd50 | [
"SQL",
"Ruby"
]
| 3 | Ruby | supersudh/authcms | b43094401b4fe367d4b5bfdd439d935cc013dc46 | 5da0b0269416bad45d81d08bf243fdb83c26ebac |
refs/heads/master | <file_sep>This is a universal circuit breaker for microservice request protecting
<file_sep>import axios, { AxiosRequestConfig } from 'axios'
import crypto from 'crypto'
import fs from 'fs'
import path from 'path'
import { when, gt, lte, ifElse, both } from 'ramda'
import url from 'url'
const cachePath = path.join(
path.dirname(process.mainModule?.filename || '.'),
'_cache'
)
interface IdState {
failures: number,
coldPeriod: number,
status: string,
nextTry: number
}
interface OPTIONS {
url: string,
method: string,
responseType: string,
timeout?: number
}
enum STATUS {
CLOSED = 'CLOSED',
OPEN = 'OPEN',
HALF = 'HALF'
}
interface State {
[key: string]: IdState
}
interface Cache {
[key: string]: any
}
class CirCuitBreaker {
state: State = {}
cache: Cache = {}
constructor(
public failerThreshold: number = 5,
public coldPeriod: number = 10,
public requestTimeout = 60,
) { }
private mkDir = (dirPath: string): void => {
if (fs.existsSync(dirPath)) return
this.mkDir(path.dirname(dirPath))
fs.mkdirSync(dirPath)
}
private mkFile = (filePath: string): void => {
if (fs.existsSync(filePath)) return
this.mkDir(path.dirname(filePath))
fs.closeSync(fs.openSync(filePath, 'w'))
}
private resetState = (id: string): CirCuitBreaker => {
this.state[id] = {
failures: 0,
coldPeriod: this.coldPeriod,
status: STATUS.CLOSED,
nextTry: 0
}
return this
}
private onSuccess = this.resetState
private get second(): number {
return +new Date() / 1000
}
private onFailure = (id: string): void => {
const state = this.state[id]
state.failures += 1
const overflow = gt(this.failerThreshold)
const whenOverflow = when(
overflow,
() => {
Object.assign(state, {
status: STATUS.OPEN,
nextTry: this.second + this.coldPeriod
})
})
whenOverflow(state.failures)
}
private canRequest = (id: string): boolean => {
const state = this.state[id]
if (!state) this.resetState(id)
const { status, nextTry } = state
if (status === STATUS.CLOSED) return true
const coldPeriodPassed = lte(this.second)
return ifElse(
coldPeriodPassed,
() => {
state.status = STATUS.HALF
return true
},
() => false
)(nextTry)
}
public fetch = async (options: OPTIONS): Promise<any> => {
const { method, url: URL, responseType, timeout } = options
const id = `${method}${URL}`
if (!this.canRequest(id)) return Promise.resolve(null)
options.timeout = (timeout || this.requestTimeout) * 1000
const cacheId = crypto.createHash('md5')
.update(`${method}${url.parse(URL).path}`)
.digest('hex')
try {
const { data } = await axios(options as AxiosRequestConfig)
this.onSuccess(id)
ifElse(
both(
() => responseType === 'stream',
() => !!data.pipe
),
() => {
this.mkDir(cachePath)
data.pipe(
fs.createWriteStream(
path.join(cachePath, cacheId)
)
)
},
() => this.cache[cacheId] = data
)(null)
return Promise.resolve(data)
} catch {
this.onFailure(id)
const filePath = path.join(cachePath, cacheId)
return ifElse(
fs.existsSync,
() => Promise.resolve(fs.createReadStream(filePath)),
() => Promise.resolve(this.cache[cacheId] || null)
)(filePath)
}
}
}
| 7134be250e7eb9a0d626a11d7207599973dbac1e | [
"Markdown",
"TypeScript"
]
| 2 | Markdown | nfwyst/circuitBreaker | 91d8c30cf1278a4db93d9159526dda75a06c2b36 | 138766e4557390db2b023e820ff31d3eee05d494 |
refs/heads/master | <repo_name>fibjs/fib-swagger<file_sep>/README.md
# Swagger to fibjs Codegen
This package generates a fibjs class from a [swagger specification file](https://github.com/wordnik/swagger-spec). The code is generated using [mustache templates](https://github.com/mtennoe/swagger-js-codegen/tree/master/templates) and is quality checked by [jshint](https://github.com/jshint/jshint/) and beautified by [js-beautify](https://github.com/beautify-web/js-beautify).
The generator is based on [superagent](https://github.com/visionmedia/superagent) and can be used for fibjs.
This fork was made to simplify some parts, add some more features, and tailor it more to specific use cases.
## Installation
```bash
fibjs --install fib-swagger
```
## cli
```bash
fibjs node_modules/fib-swagger/lib/cli -c Test gen test.json test.js
```
## Example Code
```javascript
var fs = require("fs");
var CodeGen = require("fib-swagger").CodeGen;
var file = "swagger/spec.json";
var swagger = JSON.parse(fs.readFileSync(file, "UTF-8"));
var tsSourceCode = CodeGen.getFibjsCode({
className: "Test",
swagger: swagger
});
console.log(tsSourceCode);
```
<file_sep>/lib/cli.js
'use strict';
const fs = require('fs');
const pkg = require('../package.json');
const cli = require('commander');
const yaml = require('js-yaml').safeLoad;
const CodeGen = require('./index.js').CodeGen;
cli
.version(pkg.version)
.command('gen <file> <out>')
.description('Generate from Swagger file')
.option('-c, --class <class>', 'Class name [Test]', 'Test')
.option('-l, --lint', 'Whether or not to run jslint on the generated code [false]')
.option('-b, --beautify', 'Whether or not to beautify the generated code [false]')
.action((file, out, options) => {
const fn = CodeGen.getFibjsCode;
options.lint = options.lint || false;
options.beautify = options.beautify || false;
const content = fs.readFileSync(file, 'utf-8');
var swagger;
try {
swagger = JSON.parse(content);
} catch (e) {
swagger = yaml(content);
}
const result = fn({
moduleName: options.module,
className: options.class,
swagger: swagger,
lint: options.lint,
beautify: options.beautify
});
fs.writeFileSync(out, result);
});
cli.parse(process.argv);
if (!cli.args.length) {
cli.help();
}
| aa4267f23356759d8d98136c929e2f38dfb58a89 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | fibjs/fib-swagger | 27e84879d9ffb4d871157939a54a2162fa8b20c4 | 6c94397c911206e8a46729066c2b42c5c3721ba0 |
refs/heads/master | <repo_name>jwrench/fcc_twitchy<file_sep>/src/App.js
import React, { Component } from 'react';
import './App.css';
class Streamer extends Component {
render() {
let streamer = this.props.streamer;
return (
<tr className="streamer">
<td><img src={streamer.logo} alt={streamer.username}/></td>
<td><a href={streamer.url} target="_blank">{streamer.username}</a></td>
<td>{(streamer.streaming !== null)?streamer.streaming:'Offline'}</td>
</tr>
);
}
}
class Streamers extends Component {
render() {
let rows = [];
let filter = this.props.filterBy;
let filteredList = this.props.streamers.slice();
filteredList.filter(streamer => {
if (filter === 'all') return true;
if (filter === 'online' && streamer.streaming !== null) return true;
if (filter === 'offline' && streamer.streaming === null) return true;
return false;
})
.forEach((streamer, i) => {
rows.push(<Streamer streamer={streamer} key={'streamer_'+i}/>);
});
return (
<div>
<table className="table table-hover table-responsive">
<tbody>{rows}</tbody>
</table>
</div>
);
}
}
class Filter extends Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
this.handleFilterSelectionChange = this.handleFilterSelectionChange.bind(this);
}
onClick(e) {
let value = document.querySelector('input[name="filter"]:checked').value;
this.handleFilterSelectionChange(value);
}
handleFilterSelectionChange(filterValue) {
this.props.onFilterSelected(filterValue);
}
render() {
return (
<div className="filter">
<div className="radio-inline">
<label>
<input onClick={this.onClick} type="radio" name="filter" id="all" value="all"/>
all
</label>
</div>
<div className="radio-inline">
<label>
<input onClick={this.onClick} type="radio" name="filter" id="online" value="online" />
online
</label>
</div>
<div className="radio-inline">
<label>
<input onClick={this.onClick} type="radio" name="filter" id="offline" value="offline" />
offline
</label>
</div>
</div>
);
}
}
class TwitchyHeader extends Component {
render() {
return (
<div className="text-center">
<h1>twitchy</h1>
<Filter filterBy={this.props.filterBy} onFilterSelected={this.props.onFilterSelected}/>
</div>
);
}
}
class AppContainer extends Component {
constructor(props) {
super(props);
this.state = {
streamers: []
};
this.createStreamer = this.createStreamer.bind(this);
}
createStreamer(user, response) {
let data = JSON.parse(response);
if (data.status === 404)
return {
username: user,
logo: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQSYT9tC8ETP1-a_0DXNkhFnL2aSlNwJTV5-MTxei_o10iSZHxBkQ',
streaming: 'This user does not yet exist',
url: 'https://www.twitch.tv/'
};
else
return {
username: data.display_name,
logo: data.logo,
streaming: data.status,
url: data.url
};
}
componentDidMount() {
const USERS = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp",
"storbeck", "habathcx", "RobotCaleb", "noobs2ninjas",
"comster404"];
const BASE_URL = "https://wind-bow.glitch.me/twitch-api/channels/";
USERS.forEach(user => {
let url = BASE_URL + user;
let request = new XMLHttpRequest();
request.onload = () => {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
let streamers = this.state.streamers.slice();
streamers.push(this.createStreamer(user, request.responseText));
this.setState({streamers: streamers});
} else {
console.log('request is not ok status: ' + request.status);
}
} else {
console.log('there was a problem with the request...');
}
};
request.open('GET', url);
request.send();
});
}
render() {
return <App streamers={this.state.streamers}/>
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
filterBy: 'all'
};
this.handleFilterSelection = this.handleFilterSelection.bind(this);
}
handleFilterSelection(filter) {
this.setState({
filterBy: filter
});
}
render() {
return (
<div>
<TwitchyHeader filterBy={this.state.filterBy} onFilterSelected={this.handleFilterSelection}/>
<Streamers streamers={this.props.streamers} filterBy={this.state.filterBy}/>
</div>
);
}
}
export default AppContainer;
| f15905cc210c5eacd827633429ab1f41a1d389de | [
"JavaScript"
]
| 1 | JavaScript | jwrench/fcc_twitchy | ec273fd7256c020203ead21c4d6d185bf8274f4d | ac1970a7fd480e3c145c60aface0d57a80d71a09 |
refs/heads/master | <repo_name>dwaynedwards/new-game-plus<file_sep>/src/modules/Game/pages/GamePage/index.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Grid } from 'semantic-ui-react';
import axios from 'axios';
import GameFull from '../../components/GameFull';
export default class GamePage extends Component {
static propTypes = {
match: PropTypes.object.isRequired
};
state = {
game: {}
};
platform = '';
slug = '';
componentDidMount = () => {
this.getData();
};
getData = () => {
const { match } = this.props;
this.platform = match.params.platform;
this.slug = match.params.slug;
axios
.get(`/api/games/${this.platform || ''}/${this.slug || ''}`)
.then(res => {
this.setState({ game: res.data });
})
.catch(console.error);
};
render() {
return (
<Grid container>
{this.state.game && <GameFull game={this.state.game} />}
</Grid>
);
}
}
<file_sep>/readme.md
# New Game+
A MERN stack application that retrieves Xbox One and Playstation 4 game information from a database and displays it to the user.
## Todo
* Style application
* Game search
* Filter games by platform, genre, price, etc...
* Redux
* Server-side rendering
* GraphQL (_Maybe_)
<file_sep>/api/models/game.js
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const gameSchema = new Schema({
slug: {
type: String,
required: true
},
pictureUrl: {
type: String,
required: true
},
name: {
type: String,
trim: true,
required: true
},
description: {
type: String,
trim: true,
required: true
},
genre: {
type: [String],
enum: [
'Shooter',
'RPG',
'Adventure',
'Racing',
'Sport',
'Fighting',
'Action',
'Survival'
],
required: true
},
platform: {
type: String,
enum: ['Xbox One', 'Playstation 4'],
required: true
},
price: {
type: Number,
required: true
},
releaseDate: {
type: Date,
required: true
}
});
export default mongoose.model('Game', gameSchema);
<file_sep>/routes/index.js
import express from 'express';
const router = express.Router();
router.get('/', (req, res) => {
res.redirect('/games');
});
router.get(
['/games', '/games/:platform/:slug', '/games/:platform/'],
(req, res) => {
res.render('index', { title: 'New Game+' });
}
);
export default router;
<file_sep>/src/modules/App/index.js
import React, { Component } from 'react';
import { Switch, Route } from 'react-router-dom';
import Header from './components/Header';
import Footer from './components/Footer';
import GamesPage from '../Game/pages/GamesPage';
import GamePage from '../Game/pages/GamePage';
import './App.scss';
export default class App extends Component {
render() {
return (
<div>
<Header />
<div>
<Switch>
<Route exact path="/games/:platform?" component={GamesPage} />
<Route exact path="/games/:platform/:slug" component={GamePage} />
</Switch>
</div>
<Footer />
</div>
);
}
}
<file_sep>/src/modules/Game/components/GameShort.js
import React from 'react';
import PropTypes from 'prop-types';
import { Card, Image, Label, Grid } from 'semantic-ui-react';
const GameShort = ({ game }) => {
const platform = game.platform.split(' ')[0].toLowerCase();
const url = `/games/${platform}/${game.slug}`;
return (
<Grid.Column computer={4}>
<Card href={url}>
<Card.Content>
<Image src={game.pictureUrl} />
</Card.Content>
<Card.Content>
<Card.Header>{game.name}</Card.Header>
<Card.Meta>{game.platform}</Card.Meta>
</Card.Content>
<Card.Content extra>
<Label horizontal="right">${game.price}</Label>
</Card.Content>
</Card>
</Grid.Column>
);
};
GameShort.propTypes = {
game: PropTypes.object.isRequired
};
export default GameShort;
<file_sep>/server.js
const [major, minor] = process.versions.node.split('.').map(parseFloat);
if (major < 7 || (major === 7 && minor <= 5)) {
console.error(
'You\'re on an older version of node that doesn\'t support Async + Await! Please go to nodejs.org and download version 7.6 or greater.\n'
);
process.exit();
}
import dotenv from 'dotenv';
dotenv.config({ path: 'variables.env' });
import mongoose from 'mongoose';
mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise;
mongoose.connection.on('error', err => {
console.error(`Error connecting to database: ${err.message}`);
});
import './api/models/Game';
//import './api/data/load-game-data';
import { join } from 'path';
import express from 'express';
import bodyParser from 'body-parser';
import routes from './routes';
import apiRoutes from './api/routes';
import { notFound } from './api/utils/errorHandlers';
const server = express();
server.set('port', process.env.PORT || 8888);
server.set('views', join(__dirname, 'views'));
server.set('view engine', 'pug');
server.use(express.static(join(__dirname, 'public')));
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
server.use('/', routes);
server.use('/api', apiRoutes);
server.use(notFound);
const port = server.get('port');
server.listen(port, () => {
console.info(`Server running on port: ${port}`);
});
<file_sep>/webpack.config.babel.js
import { resolve } from 'path';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import autoprefixer from 'autoprefixer';
const postcss = {
loader: 'postcss-loader',
options: {
plugins() {
return [autoprefixer({ browsers: 'last 3 versions' })];
}
}
};
const styles = {
test: /\.(scss)$/,
exclude: /(node_modules|public\/)/,
use: ExtractTextPlugin.extract([
'css-loader?sourceMap',
postcss,
'sass-loader?sourceMap'
])
};
const javascript = {
test: /\.(js)$/,
exclude: /(node_modules|public\/)/,
use: [{ loader: 'babel-loader' }]
};
const extractCSS = new ExtractTextPlugin('../css/[name].bundle.css');
const config = {
entry: { app: './src/index.js' },
output: {
path: resolve(__dirname, 'public', 'js'),
filename: '[name].bundle.js'
},
module: { rules: [styles, javascript] },
plugins: [extractCSS],
devtool: 'source-map'
};
export default config;
<file_sep>/src/modules/Game/pages/GamesPage/index.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Grid } from 'semantic-ui-react';
import axios from 'axios';
import GameShort from '../../components/GameShort';
export default class GamesPage extends Component {
static propTypes = {
match: PropTypes.object.isRequired
};
state = {
games: []
};
originalGames = [];
platform = '';
componentDidMount = () => {
this.getData();
};
componentDidUpdate = prevProps => {
const { match: curr } = this.props;
const { match: prev } = prevProps;
if (curr.params.platform === prev.params.platform) {
return;
}
this.getData();
};
getData = () => {
const { match } = this.props;
this.platform = match.params.platform;
axios
.get(`/api/games/${this.platform || ''}`)
.then(res => {
this.originalGames = res.data;
this.setState({ games: this.originalGames });
})
.catch(console.error);
};
render() {
return (
<Grid container>
{this.state.games.map(game => {
return <GameShort key={game._id} game={game} />;
})}
</Grid>
);
}
}
<file_sep>/src/modules/Game/components/GameFull.js
import React from 'react';
import PropTypes from 'prop-types';
import { Item, Label } from 'semantic-ui-react';
const GameFull = ({ game }) => {
return (
<Item.Group relaxed="very">
<Item>
<Item.Image size="large" src={game.pictureUrl} />
<Item.Content verticalAlign="middle">
<Item.Header>{game.name}</Item.Header>
<Item.Meta>{game.platform}</Item.Meta>
<Item.Description>{game.description}</Item.Description>
<Item.Extra>
<Label>${game.price}</Label>
</Item.Extra>
</Item.Content>
</Item>
</Item.Group>
);
};
GameFull.propTypes = {
game: PropTypes.object.isRequired
};
export default GameFull;
<file_sep>/api/controllers/gameController.js
const mongoose = require('mongoose');
const Game = mongoose.model('Game');
export const getGames = async (req, res) => {
const games = await Game.find();
res.json(games.sort(sortNameAsc));
};
export const getGamesByPlatform = async (req, res) => {
const { platform } = req.params;
const games = await Game.find({
platform: { $regex: new RegExp('^' + platform, 'i') }
});
if (games) {
res.json(games.sort(sortNameAsc));
} else {
res.redirect('/api/games');
}
};
export const getGame = async (req, res) => {
const { slug, platform } = req.params;
const game = await Game.findOne({
slug: slug,
platform: { $regex: new RegExp('^' + platform, 'i') }
});
if (game) {
res.json(game);
} else {
res.redirect('/api/games');
}
};
const sortNameAsc = (a, b) => {
const a2 = a.name.toLowerCase();
const b2 = b.name.toLowerCase();
return a2 === b2 ? 0 : a2 > b2 ? 1 : -1;
};
<file_sep>/src/modules/App/components/Header.js
import React from 'react';
import { Link } from 'react-router-dom';
import { Menu, Grid } from 'semantic-ui-react';
const Header = () => {
return (
<Grid container>
<Grid.Column>
<Menu>
<Menu.Item as={Link} to="/games">
Home
</Menu.Item>
<Menu.Item as={Link} to="/games/xbox">
Xbox One
</Menu.Item>
<Menu.Item as={Link} to="/games/playstation">
Playstation 4
</Menu.Item>
</Menu>
</Grid.Column>
</Grid>
);
};
export default Header;
| ab98fb3b7c4293c0fd0487be72a072e088da80a8 | [
"JavaScript",
"Markdown"
]
| 12 | JavaScript | dwaynedwards/new-game-plus | dcf0139d53717ea8675dd33bea357237980f5a34 | 64e02dddb9597428cbd05d828d3aa83f8ed810f4 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
/*Assigment 3
* <NAME>
* Programm keeps track of the vehicle in txt file
* 9/22/2020
*
*/
namespace A3_Hinojoza
{
public partial class Assignment3 : Form
{
//create a list to remember the cars in stock
private List<vehicle> vehicleLog = new List<vehicle>();
public Assignment3()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)//reading the file correctly and making vehicle elements
{
//read in file
//the file provides strings, year, mileage, make, model
using (StreamReader fileIn = File.OpenText("vehicles.txt"))
{
String line = fileIn.ReadLine(); //define line to break apart
while (line != null)
{
if (line != "")
{
String[] lineArray = line.Split(' ');
//parse and set parameter values
double year = double.Parse(lineArray[0]);
double mileage = double.Parse(lineArray[1]);
String makeAndmodel = lineArray[2] + " " + lineArray[3];
vehicleLog.Add(new vehicle(year, mileage, makeAndmodel));
}
line = fileIn.ReadLine();
}
}
CreateMakeandModelLabel();
CreateYearLabel();
CreateMileageTxt();
}
private void CreateMileageTxt()
{
int txtBoxTop = 97;
foreach (vehicle item in vehicleLog)
{
//Console.WriteLine(item.getMakeAndModel() + " " + item.getYear() + " " + item.getMileage());
TextBox txtMileage = new TextBox();
txtMileage.Location = new System.Drawing.Point(204, txtBoxTop);
txtMileage.Name = "textBox1";
txtMileage.Size = new System.Drawing.Size(100, 20);
txtMileage.TabIndex = 8;
txtMileage.Text = item.getMileage().ToString();
this.Controls.Add(txtMileage);
item.setTxtMileage(txtMileage);
txtBoxTop += 20;
}
}
private void CreateMakeandModelLabel()
{
int lblTop = 100;
foreach (vehicle item in vehicleLog)
{
//Console.WriteLine(item.getMakeAndModel() + " " + item.getYear() + " " + item.getMileage());
Label lblMakeModel = new Label();
lblMakeModel.AutoSize = true;
lblMakeModel.Location = new System.Drawing.Point(12, lblTop);
lblMakeModel.Name = "lblVehicle";
lblMakeModel.Size = new System.Drawing.Size(87, 13);
lblMakeModel.TabIndex = 2;
lblMakeModel.Text = "";
lblMakeModel.Text += item.getMakeAndModel();
if (item.getMileage() > 100000)
{
lblMakeModel.BackColor = System.Drawing.Color.Yellow;
}
this.Controls.Add(lblMakeModel);
lblTop += 20;
}
}
private void CreateYearLabel()
{
int lblTop = 100;
foreach (vehicle item in vehicleLog)
{
Label lblYear = new Label();
lblYear.AutoSize = true;
lblYear.Location = new System.Drawing.Point(138, lblTop);
lblYear.Name = "lblVehicle";
lblYear.Size = new System.Drawing.Size(87, 13);
lblYear.TabIndex = 2;
lblYear.Text = "";
lblYear.Text += item.getYear();
if (item.getMileage() > 100000)
{
lblYear.BackColor = System.Drawing.Color.Yellow;
}
this.Controls.Add(lblYear);
lblTop += 20;
}
}
private void btnLowestMileage_Click(object sender, EventArgs e)
{
double lowMileage = Double.MaxValue;
String lowMileageCar = "";
foreach (vehicle item in vehicleLog)
{
if(lowMileage > double.Parse(item.gettxtMileage().Text))
{
lowMileage = double.Parse(item.gettxtMileage().Text);
lowMileageCar = "The car with the lowest miles is a " + item.getMakeAndModel() + " " + item.getYear() + " with " + item.gettxtMileage().Text + " miles.";
}
}
MessageBox.Show(lowMileageCar);
}
private void btnAvgFordMileage_Click(object sender, EventArgs e)
{
double i = 0;
double mileageSum = 0;
foreach (vehicle item in vehicleLog)
{
if(item.getMakeAndModel().StartsWith("Ford"))
{
mileageSum += double.Parse(item.gettxtMileage().Text);
i++;
}
}
double avgFordMileage = (mileageSum / i);
MessageBox.Show("The average Ford mileage is " + avgFordMileage + " miles (" + i + " cars total).");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Instrumentation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace A3_Hinojoza
{
class vehicle
{
private String makeAndmodel;
private double mileage, year;
private TextBox txtMileage;
//create constructor based on parameters
public vehicle(double year, double mileage, String makeAndmodel)
{
this.year = year;
this.mileage = mileage;
this.makeAndmodel = makeAndmodel;
}
//set getters
public double getMileage()
{
return mileage;
}
public double getYear()
{
return year;
}
public String getMakeAndModel()
{
return makeAndmodel;
}
public TextBox gettxtMileage()
{
return txtMileage;
}
//set setters
public void setMileage(double newMileage)
{
mileage = newMileage;
}
public void setYear(double newYear)
{
year = newYear;
}
public void setMake(string newMakeAndModel)
{
makeAndmodel = newMakeAndModel;
}
public void setTxtMileage(TextBox newtxtMileage)
{
txtMileage = newtxtMileage;
}
}
}
| 6e25bf8a9a6738fe2841220ec636c73163355d24 | [
"C#"
]
| 2 | C# | JoseHinojoza-byte/VehicleRentedLog-Mock-Program | 0db7d343dd9810ac968210a7c0db07acf7d17493 | 8c2c285aa4b0fa01fe8d588ccbb6b8a369737bf2 |
refs/heads/master | <repo_name>hensoko/go-netbox<file_sep>/tools.go
package tools
import (
_ "github.com/go-swagger/go-swagger"
)
| 5de9155b33efa4ee69c060e1f53d67494011cb95 | [
"Go"
]
| 1 | Go | hensoko/go-netbox | 8b28441bb9f6b7d002746495872fe5207779d387 | 68d31e621ea3a874aac020a9543d8ad50ba2e66e |
refs/heads/master | <repo_name>Claytongirl/DailySmartyUI<file_sep>/src/actions/types.js
export const SET_RECENT_POSTS = "SET_RECENT_POSTS";
export const SET_RESULTS_POSTS = "SET_RESULTS_POSTS"; | 222815599b1e16c893e3625d4b78811f74b7a9a3 | [
"JavaScript"
]
| 1 | JavaScript | Claytongirl/DailySmartyUI | 2f2723164dc72cb295703945d7cd064addc1be47 | c6e8787f8245a0e8d858ce03109b3d5f48373d65 |
refs/heads/master | <repo_name>liyilun2019/homework6<file_sep>/app/src/main/java/com/byted/camp/todolist/MainActivity.java
package com.byted.camp.todolist;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import com.byted.camp.todolist.beans.Note;
import com.byted.camp.todolist.beans.State;
import com.byted.camp.todolist.db.TodoContract;
import com.byted.camp.todolist.db.TodoDbHelper;
import com.byted.camp.todolist.debug.DebugActivity;
import com.byted.camp.todolist.ui.NoteListAdapter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CODE_ADD = 1002;
public static final int REQUEST_CODE_MODIFY=1003;
private RecyclerView recyclerView;
private NoteListAdapter notesAdapter;
private TodoDbHelper helper;
private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
helper = new TodoDbHelper(this);
db = helper.getWritableDatabase();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivityForResult(
new Intent(MainActivity.this, NoteActivity.class),
REQUEST_CODE_ADD);
}
});
recyclerView = findViewById(R.id.list_todo);
recyclerView.setLayoutManager(new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false));
recyclerView.addItemDecoration(
new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
notesAdapter = new NoteListAdapter(new NoteOperator() {
@Override
public void deleteNote(Note note) {
MainActivity.this.deleteNote(note);
notesAdapter.refresh(loadNotesFromDatabase());
}
@Override
public void updateNote(Note note) {
MainActivity.this.updateNode(note);
notesAdapter.notifyDataSetChanged();
}
});
recyclerView.setAdapter(notesAdapter);
notesAdapter.refresh(loadNotesFromDatabase());
}
@Override
protected void onDestroy() {
helper.close();
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
return true;
case R.id.action_debug:
startActivity(new Intent(this, DebugActivity.class));
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_ADD
&& resultCode == Activity.RESULT_OK) {
notesAdapter.refresh(loadNotesFromDatabase());
}else if(requestCode==REQUEST_CODE_MODIFY&&resultCode==Activity.RESULT_OK){
notesAdapter.refresh(loadNotesFromDatabase());
}
}
private List<Note> loadNotesFromDatabase() {
// endTODO 从数据库中查询数据,并转换成 JavaBeans
// SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+ TodoContract.TodoTable.TABLE_NAME,
null);
ArrayList<Note> ret = new ArrayList<>();
while(cursor.moveToNext()){
Note tmp = new Note(
cursor.getLong(
cursor.getColumnIndexOrThrow(
TodoContract.TodoTable.COLUMN_NAME_ID)));
tmp.setContent(cursor.getString(cursor.getColumnIndexOrThrow(
TodoContract.TodoTable.COLUMN_NAME_CONTENT)));
tmp.setDate(new Date(cursor.getString(cursor.getColumnIndexOrThrow(
TodoContract.TodoTable.COLUMN_NAME_DATE))));
tmp.setState(State.from(cursor.getInt(cursor.getColumnIndexOrThrow(
TodoContract.TodoTable.COLUMN_NAME_STATE
))));
try{
tmp.setPriority(cursor.getInt(cursor.getColumnIndexOrThrow(
TodoContract.TodoTable.COLUMN_NAME_PRI)));
}catch (Exception e){
tmp.setPriority(0);
}
ret.add(tmp);
// Log.d("SQL", "loadNotesFromDatabase: add "+tmp.id);
}
ret.sort(new Comparator<Note>() {
@Override
public int compare(Note o1, Note o2) {
//Log.d("SQL", "compare: "+o1.getPriority()+" "+o2.getPriority());
int diff = o2.getPriority()-o1.getPriority();
if(diff==0){
diff = o2.getDate().compareTo(o1.getDate());
}
return diff;
}
});
return ret;
}
private void deleteNote(Note note) {
// TODO 删除数据
int deleteRows = db.delete(TodoContract.TodoTable.TABLE_NAME ,
TodoContract.TodoTable.COLUMN_NAME_ID + " LIKE ?",
new String[]{""+note.id});
}
private void updateNode(Note note) {
// TODO 更新数据
ContentValues values = new ContentValues();
values.put(TodoContract.TodoTable.COLUMN_NAME_CONTENT,note.getContent());
// values.put(TodoContract.TodoTable.COLUMN_NAME_DATE, note.getDate().toString());
values.put(TodoContract.TodoTable.COLUMN_NAME_STATE,note.getState().intValue);
values.put(TodoContract.TodoTable.COLUMN_NAME_PRI,note.getPriority());
int count = db.update(TodoContract.TodoTable.TABLE_NAME,
values,
TodoContract.TodoTable.COLUMN_NAME_ID+" LIKE ?",
new String[]{""+note.id});
}
}
<file_sep>/app/src/main/java/com/byted/camp/todolist/db/TodoDbHelper.java
package com.byted.camp.todolist.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import static android.content.ContentValues.TAG;
/**
* Created on 2019/1/22.
*
* @author <EMAIL> (<NAME>)
*/
public class TodoDbHelper extends SQLiteOpenHelper {
// TODO 定义数据库名、版本;创建数据库
public static final String DATABASE_NAME = "database.db";
public static final int DATABASE_VERSION = 2;
public static final String TAG = "SQL";
public TodoDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "onCreate: ");
db.execSQL(TodoContract.SQL_CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for(int i = oldVersion;i<newVersion;i++){
switch (i){
case 1:
try {
db.execSQL("ALTER TABLE " + TodoContract.TodoTable.TABLE_NAME
+ " ADD " + TodoContract.TodoTable.COLUMN_NAME_PRI
+ " INTEGER ");
} catch (Exception e){
Log.d(TAG, "onUpgrade: "+e.getClass().getName() + " "+e.getMessage());
}
}
}
}
}
<file_sep>/readme.md
# todoList app:
#### 这次用SQLite完成了一个todoList,带有优先级,基本功能如下:
<img src = "./gif1.gif" width=50%>
#### 除了增加之外,还可以修改状态为完成,然后还支持删除
<img src="gif2.gif" width=50%>
#### 除此之外还能够对表中的内容和优先级进行修改
<img src="gif3.gif" width=50%>
#### 注意,这里只有打勾的时候会在内存里先改好再放到数据库里,插入和该内容、优先级都是先改完数据库再重新拉下来的,说不定下次可以用id查一个再拉数据,或者用Intent data传输返回数据然后在内存中更改note | 09dd486991a135f9724d1ba2d3fa69d079127df4 | [
"Markdown",
"Java"
]
| 3 | Java | liyilun2019/homework6 | e4651fc5d7ce0c77eab402157e071c53a6bf0f78 | bbc73347b8fe1b4a739bc6b7f4de1bb0d55cacfa |
refs/heads/master | <repo_name>samafshari/RedCorners.Wpf<file_sep>/RedCorners.Wpf/BoolToVisibilityConverter.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Windows;
using System.Windows.Data;
namespace RedCorners.Wpf
{
public class BoolToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool b)
{
if (b) return Visibility.Visible;
return Visibility.Collapsed;
}
if (value == null)
throw new ArgumentNullException("BoolToVisibilityConverter -> needs a bool. null passed instead.");
throw new ArgumentException($"BoolToVisibilityConverter -> needs a bool. {value.GetType().Name} passed instead.");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is Visibility v)
{
if (v == Visibility.Visible) return true;
return false;
}
if (value == null)
throw new ArgumentNullException("BoolToVisibilityConverter <- needs a Visibility. null passed instead.");
throw new ArgumentException($"BoolToVisibilityConverter <- needs a Visibility. {value.GetType().Name} passed instead.");
}
}
}
<file_sep>/RedCorners.Wpf/ViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Linq;
using System.Windows.Input;
using System.Reflection;
namespace RedCorners.Wpf
{
public class Command : System.Windows.Input.ICommand
{
private readonly Action _action;
private readonly bool _canExecute;
public Command(Action action, bool canExecute = true)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action();
}
}
[AttributeUsage(AttributeTargets.All)]
public class NoUpdate : Attribute
{
}
[AttributeUsage(AttributeTargets.All)]
public class Updates : Attribute
{
}
[AttributeUsage(AttributeTargets.All)]
public class ManualUpdate : Attribute
{
public ManualUpdate() { }
public ManualUpdate(bool updateIfForced)
{
UpdateIfForced = updateIfForced;
}
public bool UpdateIfForced { get; set; } = true;
}
public partial class ViewModel : INotifyPropertyChanged
{
public static Action<Action> DefaultDispatchAction = a => System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(a);
public static bool DispatchOnSetProperty = true;
public event PropertyChangedEventHandler PropertyChanged;
PropertyInfo[] propertyInfos;
public virtual void Dispatch(Action a)
{
DefaultDispatchAction?.Invoke(a);
}
public void RaisePropertyChanged([CallerMemberName] string m = null, bool? dispatch = null)
{
if (dispatch ?? DispatchOnSetProperty)
{
Dispatch(() =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(m)));
}
else
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(m));
}
}
public ViewModel() { }
protected virtual void SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null, bool? dispatch = null)
{
storage = value;
if (dispatch ?? DispatchOnSetProperty)
{
Dispatch(() => RaisePropertyChanged(propertyName));
}
else
{
RaisePropertyChanged(propertyName);
}
}
public void UpdateProperties(bool forceAll = false)
{
Dispatch(() =>
{
if (propertyInfos == null)
propertyInfos = GetType().GetProperties();
foreach (var item in propertyInfos)
{
if (item.GetCustomAttributes(typeof(NoUpdate), true).Any())
continue;
if (item.GetCustomAttributes(typeof(ManualUpdate), true).Any() && !forceAll)
continue;
if (item.PropertyType.IsAssignableFrom(typeof(ICommand)) && !item.GetCustomAttributes(typeof(Updates), true).Any())
continue;
RaisePropertyChanged(item.Name, dispatch: false);
}
});
}
public void UpdateProperties(IEnumerable<string> names)
{
Dispatch(() =>
{
foreach (var item in names)
RaisePropertyChanged(item, dispatch: false);
});
}
}
}
| 5a883019876465145e541263f11450ae43cdc8e3 | [
"C#"
]
| 2 | C# | samafshari/RedCorners.Wpf | c09d598e12e1889a2f325b79b464709fafe88011 | dbe0bad0c9d9389f11e4d332ab034ea4c0f3b048 |
refs/heads/master | <file_sep>0.0.3 / 2014-06-18
==================
* If command fails, just log the error instead of calling done(err);
0.0.2 / 2014-03-23
==================
* Updated underscore version
0.0.1 / 2013-09-09
==================
* Initial version<file_sep>grunt-git-ref-changed-files
===========================
> Detects which files have changed between two git refs.
## Getting Started
_If you haven't used [grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](https://github.com/cowboy/grunt/blob/master/docs/getting_started.md) guide._
From the same directory as your project's Gruntfile and package.json, install this plugin with the following command:
```bash
npm install grunt-git-ref-changed-files
```
Once that's done, add this line to your project's Gruntfile:
```js
grunt.loadNpmTasks('grunt-git-ref-changed-files');
```
## Overview
Inside your `Gruntfile.js` file add a section named `refChangedFiles`. This section specifies the
options to detect which files have changed between two refs (from/to) and a regular expression to filter them.
## How it works
It will query which files have changed since the specified from/to parameter using git by running:
```bash
git log {ref}..{ref} --name-only --pretty=format:
```
Finally it will filter the changed files by applying the **regexp** option to every item. The result of the filtered
files changed will be stored in a grunt config item called *refChangedFiles*.
## Config Example
Example to detect if static files where modified since *v.100* tag:
```javascript
refChangedFiles: {
dist: {
options: {
from: 'v.100', // optional: default is HEAD^
to: 'HEAD', // optional: default is HEAD
regexp: /public\/lib\/js/, // optional: default is /.*/
},
src: 'repoFolder'
}
}
```
Then you can access to the filtered changed files using:
```javascript
grunt.config.get('refChangedFiles');
```
License
-------
Copyright (c) 2013 <NAME>
Licensed under the MIT license.
<file_sep>/*
* grunt-git-ref-changed-files
* https://github.com/Ideame/grunt-git-ref-changed-files
*
* Copyright (c) 2013 Ideame
*/
module.exports = function (grunt) {
var _ = require('underscore')
, util = require('util');
grunt.registerMultiTask("refChangedFiles", "Detects which files have changed between two git refs.", function () {
var done = this.async();
var options = this.options({
from: 'HEAD^',
to: 'HEAD',
regexp: /.*/
});
var src = this.filesSrc[0];
if (!src) {
grunt.fail.warn('The src folder provided does not exists.');
}
grunt.util.spawn({
cmd: 'git',
args: [ 'log', util.format('%s..%s', options.from, options.to), '--name-only', '--pretty=format:' ],
opts: { cwd: src }
}, function (err, result){
grunt.log.writeln('Checking if provided regular expression matches with file changes in the last commit.');
if (err) {
grunt.log.error(err);
return done();
}
var refsChangedFiles = _.compact(String(result).split(grunt.util.linefeed));
grunt.verbose.write(refsChangedFiles);
var changedFiles = _.filter(refsChangedFiles, function (f) {
return new RegExp(options.regexp).test(f);
});
grunt.config.set('refChangedFiles', changedFiles);
done();
});
});
};
| 448c1d3fa5869cb1347cd385f653e11a246fe00b | [
"Markdown",
"JavaScript"
]
| 3 | Markdown | isabella232/grunt-git-ref-changed-files | 89f1486bfd620403e5a3272ffc3be6d9c8fd4132 | 7ffbeae70078b4ef6498edbf9572703dab0fbf3e |
refs/heads/master | <file_sep>package model;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.jupiter.api.Test;
class ClientTest {
private RestaurantsManager restaurantsManager = new RestaurantsManager();
public void setupScenary1() throws IOException {
restaurantsManager.addClient("Andrea", "Corrales", "2154531341", 1, "31254867624", "Cali");
restaurantsManager.addClient("Camilo", "Ramirez", "1548225645", 4, "3124865794", "Cali");
}
@Test
public void testClientSortedAdded_1() throws IOException {
setupScenary1();
//The first one added is now the second one (position 1) by add client sorted by name
assertEquals("Fail test client", "2154531341",restaurantsManager.getClients().get(1).getIdNum());
}
@Test
public void testClientFullName_2() throws IOException {
setupScenary1();
assertEquals("Fail test client full name", "<NAME>",restaurantsManager.getClients().get(0).getFullName());
}
}
<file_sep>package model;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.jupiter.api.Test;
class RestaurantTest {
private RestaurantsManager restaurantsManager = new RestaurantsManager();
public void setupScenary1() throws IOException {
restaurantsManager.addRestaurant("Las delicias de Gallo", "12345", "Gallo");
restaurantsManager.addRestaurant("Las delicias de Colombia", "12345", "Camilo");
}
@Test
public void testSameRestaurantsNit_1() throws IOException {
setupScenary1();
assertEquals("Fail test restaurants duplicate", 1, restaurantsManager.getRestaurants().size());
}
@Test
public void testSameRestaurantsNit_2() throws IOException {
setupScenary1();
assertEquals("Fail test restaurants duplicate", "Las delicias de Gallo", restaurantsManager.getRestaurants().get(0).getName());
}
}
<file_sep>package model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import exceptions.NullCodeException;
import exceptions.WrongIdException;
import exceptions.WrongNitException;
import java.lang.Comparable;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.File;
public class RestaurantsManager implements Comparable<Client> {
//Initialization and constants declaration
public final static String SAVE_PATH_FILE_RESTAURANTS = "data/restaurants.ap2";
public final static String SAVE_PATH_FILE_CLIENTS = "data/clients.ap2";
public final static String SAVE_PATH_FILE_PRODUCTS = "data/products.ap2";
public final static String SAVE_PATH_FILE_ORDERS = "data/orders.ap2";
public List<Restaurant> restaurants;
public List<Product> products;
public List<Client> clients;
public List<Order> orders;
private final static String SEPARATOR = ",";
/**
* This method is the constructor of RestaurantsManager
* <b><pre>:<br><br>
*
* <b>post:</b>ArrayList are created<br>
*/
public RestaurantsManager() {
restaurants = new ArrayList<Restaurant>();
products = new ArrayList<Product>();
clients = new ArrayList<Client>();
orders = new ArrayList<Order>();
}
/**
* This method gets the restaurants list
* <b><pre>:<br><br>
*
* @return restaurants
*
* <b>post:</b><br>
*/
public List<Restaurant> getRestaurants(){
return restaurants;
}
/**
* This method gets the products list
* <b><pre>:<br><br>
*
* @return products
*
* <b>post:</b><br>
*/
public List<Product> getProducts(){
return products;
}
/**
* This method gets the clients list
* <b><pre>:<br><br>
*
* @return clients
*
* <b>post:</b><br>
*/
public List<Client> getClients(){
return clients;
}
/**
* This method gets the orders list
* <b><pre>:<br><br>
*
* @return orders
*
* <b>post:</b><br>
*/
public List<Order> getOrders(){
return orders;
}
/**
* This method serialize the program data
* <b><pre>:<br><br>
*
* @param type String of the object type to serialize
* @throws IOException
*
* <b>post:</b>Serialize the data requested for each path file<br>
*/
public void saveData(String type) throws IOException{
if(type.equalsIgnoreCase("rest")) {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SAVE_PATH_FILE_RESTAURANTS));
oos.writeObject(restaurants);
oos.close();
}
if(type.equalsIgnoreCase("client")) {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SAVE_PATH_FILE_CLIENTS));
oos.writeObject(clients);
oos.close();
}
if(type.equalsIgnoreCase("products")) {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SAVE_PATH_FILE_PRODUCTS));
oos.writeObject(products);
oos.close();
}
if(type.equalsIgnoreCase("orders")) {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SAVE_PATH_FILE_ORDERS));
oos.writeObject(orders);
oos.close();
}
}
/**
* This method deserialize the program data
* <b><pre>:<br>Serialized files must be created to be deserialize<br>
*
* @param type String of the object type to deserialize
*
* @return loaded boolean that notify if was added or not
*
* @throws IOException
* @throws ClassNotFoundException
*
* <b>post:</b>Deserialize the data requested for each path file<br>
*/
@SuppressWarnings("unchecked")
public boolean loadData(String type) throws IOException, ClassNotFoundException{
File r = new File(SAVE_PATH_FILE_RESTAURANTS);
File c = new File(SAVE_PATH_FILE_CLIENTS);
File p = new File(SAVE_PATH_FILE_PRODUCTS);
File o = new File(SAVE_PATH_FILE_ORDERS);
boolean loaded = false;
if(r.exists()){
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(r));
if(type.equalsIgnoreCase("rest")) {
restaurants = (List<Restaurant>)ois.readObject();
loaded = true;
}
ois.close();
}
if(c.exists()){
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(c));
if(type.equalsIgnoreCase("client")) {
clients = (List<Client>)ois.readObject();
loaded = true;
}
ois.close();
}
if(p.exists()){
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(p));
if(type.equalsIgnoreCase("products")) {
products = (List<Product>)ois.readObject();
loaded = true;
}
ois.close();
}
if(o.exists()){
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(o));
if(type.equalsIgnoreCase("orders")) {
orders = (List<Order>)ois.readUnshared();
loaded = true;
}
ois.close();
}
else {
loaded = false;
}
return loaded;
}
// Exporting & importing data...
/**
* This method import the restaurants information
* <b><pre>:<br>The file must be exist and with information to load<br>
*
* @param fileName String of the file path to import
*
* @throws IOException
*
* <b>post:</b>Restaurants information was imported<br>
*/
public void importRestaurants(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
br.readLine();
String line = br.readLine();
while(line!=null) {
String[] parts = line.split(SEPARATOR);
String name = parts[0];
String nit = parts[1];
String manager = parts[2];
addRestaurant(name,nit,manager);
line = br.readLine();
}
br.close();
}
/**
* This method import the clients information
* <b><pre>:<br>The file must be exist and with information to load<br>
*
* @param fileName String of the file path to import
*
* @throws IOException
*
* <b>post:</b>Clients information was imported<br>
*/
public void importClients(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
br.readLine();
String line = br.readLine();
while(line!=null) {
String[] parts = line.split(SEPARATOR);
String name = parts[0];
String lastName = parts[1];
String idNum = parts[2];
int idType = Integer.parseInt(parts[3]);
String telephone = parts[4];
String address= parts[5];
addClient(name, lastName, idNum, idType, telephone, address);
line = br.readLine();
}
br.close();
}
/**
* This method import the products information
* <b><pre>:<br>The file must be exist and with information to load<br>
*
* @param fileName String of the file path to import
*
* @throws IOException
*
* <b>post:</b>Products information was imported<br>
*/
public void importProducts(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
br.readLine();
String line = br.readLine();
while(line!=null) {
String[] parts = line.split(SEPARATOR);
String name = parts[0];
String code = parts[1];
String info = parts[2];
double cost = Double.parseDouble(parts[3]);
String restNit = parts[4];
addProduct(name, code, info, cost, restNit);
line = br.readLine();
}
br.close();
}
/**
* This method export the orders information
* <b><pre>:<br>An order as minimum must be added<br>
*
* @param separator String of the separator to use between columns
* @throws FileNotFoundException
*
* <b>post:</b>Orders was exported in a .csv file<br>
*/
public void exportOrder(String separator) throws FileNotFoundException {
sortOrder();
PrintWriter pw = new PrintWriter("data/orders.csv");
pw.println("Code"+separator+"Date"+separator+"Client ID"+separator+"Status"+separator+"Restaurant Nit"+separator+"Product code"+separator+"Product quantity");
for (int i = 0; i < orders.size(); i++) {
if (orders.get(i).getOrdersProductList().size()==1)
pw.println(orders.get(i).getCode()+separator+orders.get(i).getDate()+separator+orders.get(i).getClientIdNum()+separator+orders.get(i).getOrderStat()+separator+orders.get(i).getRestaurantNit()+separator+orders.get(i).getOrdersProductList().get(0).getInfoToExport(separator));
if(orders.get(i).getOrdersProductList().size()>1) {
for (int j = 0; j < orders.get(i).getOrdersProductList().size(); j++) {
pw.println(orders.get(i).getCode()+separator+orders.get(i).getDate()+separator+orders.get(i).getClientIdNum()+separator+orders.get(i).getOrderStat()+separator+orders.get(i).getRestaurantNit()+separator+orders.get(i).getOrdersProductList().get(j).getInfoToExport(separator));
}
}
}
pw.close();
}
//*****************************************************************************************************//
//Sorting methods
/**
* This method sort the clients by their full names descending
* <b><pre>:<br>Multiple clients must be added<br>
*
* <b>post:</b>Clients are sorted by full name order descending<br>
*/
public void sortClientsCorrect() {
Comparator<Client> ca = new Comparator<Client>() {
public int compare(Client c1, Client c2) {
int comp;
String nom1 = c1.getFullName();
String nom2 = c2.getFullName();
comp = nom2.compareToIgnoreCase(nom1);
return comp;
}
};
Collections.sort(clients,ca);
}
/**
* This method sort the order requested to export
* <b><pre>:<br>Multiple orders must be added<br>
*
* <b>post:</b>Orders was sorted by bubble way<br>
*/
public void sortOrder() {
class SortOrder implements Comparator<Order>{
@Override
public int compare(Order o1, Order o2) {
int value1 = 0, value2 = 0;
value1 = o1.getRestaurantNit().compareTo(o2.getRestaurantNit());
if(value1 == 0) {
value2 = o2.getClientIdNum().compareTo(o1.getClientIdNum());
if(value2 == 0) {
return o1.getDate().compareTo(o2.getDate());
}
else {
return value2;
}
}
return value1;
}
}
Collections.sort(orders, new SortOrder());
}
//Insertion
/**
* This method sort the restaurants names by insertion way
* <b><pre>:<br>A restaurant as minimum must be added<br>
*
* <b>post:</b>Restaurants was sorted by insertion way<br>
*/
public void sortByRestaurantNameBubble() {
Restaurant temp;
boolean sorted = false;
while (!sorted) {
sorted = true;
for (int i = 0; i < restaurants.size()-1; i++) {
if (restaurants.get(i).getName().compareTo(restaurants.get(i + 1).getName()) > 0) {
temp = restaurants.get(i);
restaurants.set(i, restaurants.get(i + 1));
restaurants.set(i + 1, temp);
sorted = false;
}
}
}
}
//Bubble
/**
* This method sort the clients telephones by bubble way
* <b><pre>:<br>A client as minimum must be added<br>
*
* <b>post:</b>Clients was sorted by bubble way<br>
*/
public void SortbyClientTelephoneInsertion() {
for (int i = 1; i < clients.size(); i++) {
Client c1 = clients.get(i);
int j = i;
Client c2 = clients.get(j-1);
while(j>0 && c2.getTelephone().compareTo(c1.getTelephone())<0) {
clients.set(j,c2);
j--;
if(j>0) c2 = clients.get(j-1);
}
clients.set(j,c1);
}
}
//******************************************************************************************************//
//Updating & searching
/**
* This method search a restaurant by his nit
* <b><pre>:<br>A restaurant must be added<br>
*
* @param nit String of the restaurant NIT
*
* @throws WrongNitException
*
* @return position
*
* <b>post:</b>Returns the position in the array<br>
*/
public int searchRestaurantNit(String nit) throws WrongNitException{
int position = 0;
boolean found = !false;
for(int i=0; i<restaurants.size() && found; i++){
if(restaurants.get(i).getNit().equalsIgnoreCase(nit)){
found = true;
position = i;
}
} if(found == false) {
throw new WrongNitException();
}
return position;
}
/**
* This method search a product by his code and returns the position
* <b><pre>:<br>A product must be added<br>
*
* @param code String of the product code
*
* @throws NullCodeException
*
* @return position
*
* <b>post:</b>Returns the position in the array<br>
*/
public int searchProductByCode(String code) throws NullCodeException{
int position = 0;
boolean found = !false;
for(int i=0; i<products.size() && found; i++){
if(products.get(i).getCode().equalsIgnoreCase(code)){
found = true;
position = i;
}
} if(found == false) {
throw new NullCodeException();
}
return position;
}
/**
* This method search a client by ID number and returns the position
* <b><pre>:<br>A client must be added<br>
*
* @param idNum String of the client ID number
*
* @throws WrongIdException
*
* @return position
*
* <b>post:</b>Returns the position in the array<br>
*/
public int searchClientId(String idNum) throws WrongIdException{
int position = 0;
boolean found = !false;
for(int i=0; i<clients.size() && found; i++){
if(clients.get(i).getIdNum().equalsIgnoreCase(idNum)){
found = true;
position = i;
}
}
if(found = false) {
throw new WrongIdException();
}
return position;
}
/**
* This method search a client by his name and last name executing a binary search
* <b><pre>:<br>A client must be added<br>
*
* @param name String of client name
* @param lastName String od client last name
*
* @return found
*
* <b>post:</b>Returns the search condition<br>
*/
public boolean searchClientName(String name, String lastName) {
String fullName = "";
fullName = name+" "+lastName;
boolean found = false;
int start = 0;
int end = clients.size()-1;
while (start <= end && !found) {
int middle = (start + end)/2;
if (clients.get(middle).getFullName().equalsIgnoreCase(fullName)) {
found = true;
} else if(clients.get(middle).getFullName().compareToIgnoreCase(fullName) < 1){
end = middle -1;
} else {
start = middle +1;
}
}
return found;
}
/**
* This method search an order by his code and returns the position
* <b><pre>:<br>An order must be added<br>
*
* @param orderCode String of order code
*
* @throws NullCodeException
*
* @return position
*
* <b>post:</b>Returns the position in the array<br>
*/
public int searchOrder(String orderCode) throws NullCodeException{
int position = 0;
boolean found = !false;
for(int i=0; i<orders.size() && found; i++){
if(orders.get(i).getCode().equalsIgnoreCase(orderCode)){
found = true;
position = i;
}
} if(found == false) {
throw new NullCodeException();
}
return position;
}
/**
* This method search the products of a requested restaurant and returns their information
* <b><pre>:<br>The restaurant to search products must have products added<br>
*
* @param nit String of restaurant NIT
*
* @return info
*
* <b>post:</b>Returns the products information linked with the restaurant requested<br>
*/
public String searchProductByRestaurant(String nit) {
String info = "";
for (int i = 0; i < products.size(); i++) {
if(products.get(i).getRestaurantNit().equalsIgnoreCase(nit)) {
info += products.get(i).getAllInfo();
}
}
return info;
}
/**
* This method update the restuarant NIT linked to their products
* <b><pre>:<br>A product must be added and linked with a restaurant<br>
*
* @param OldNit String of the restaurant old NIT
* @param NewNit String of the restaurant new NIT
*
*
* <b>post:</b>New NIT is setted for each restaurant<br>
*/
public void updateNitProducts(String OldNit, String NewNit) {
for (int i = 0; i < products.size(); i++) {
if(products.get(i).getRestaurantNit().equalsIgnoreCase(OldNit)) {
products.get(i).setRestaurantNit(NewNit);
}
}
}
/**
* This method update the restuarant NIT linked to their orders
* <b><pre>:<br>An order must be added and linked with a restaurant<br>
*
* @param OldNit String of the restaurant old NIT
* @param NewNit String of the restaurant new NIT
*
*
* <b>post:</b>New NIT is setted for each orders<br>
*/
public void updateNitOrders(String OldNit, String NewNit) {
for (int i = 0; i < orders.size(); i++) {
if(orders.get(i).getRestaurantNit().equalsIgnoreCase(OldNit)) {
orders.get(i).setRestaurantNit(NewNit);
}
}
}
/**
* This method update the client ID number linked to their orders
* <b><pre>:<br>An order must be added and linked with a client<br>
*
* @param OldId String of the client old ID number
* @param NewId String of the client new ID number
*
* <b>post:</b>New ID number is setted for each orders<br>
*/
public void updateClientIdOrders(String OldId, String NewId) {
for (int i = 0; i < orders.size(); i++) {
if(orders.get(i).getClientIdNum().equalsIgnoreCase(OldId)) {
orders.get(i).setClientIdNum(NewId);
}
}
}
/**
* This method update the product code linked to their orders
* <b><pre>:<br>An order must be added and linked with a product<br>
*
* @param OldCode String of the product old code
* @param NewCode String of the product new code
*
* <b>post:</b>New product code is setted for each orders<br>
*/
public void updateProductOrderCodeFromProduct(String oldCode, String newCode) {
for (int i = 0; i < orders.size(); i++) {
orders.get(i).updateProductsCode(oldCode, newCode);
}
}
//***************************************************************************************************//
//Methods of restaurants
/**
* This method add a restaurant, then serialize and returns an information about the adding process
* <b><pre>:<br>The restaurant to add must have a unique NIT<br>
*
* @param name String of restaurant name
* @param nit String nit of restaurant NIT
* @param manager String manager of restaurant manager
*
* @throws IOException
*
* @return info
*
* <b>post:</b>Returns information of adding process<br>
*/
public String addRestaurant(String name, String nit, String manager) throws IOException {
Restaurant R = new Restaurant(name, nit, manager);
String info = "";
boolean added = false;
if(restaurants.isEmpty()) {
restaurants.add(R);
added = true;
info += "\n**Added!**\n";
saveData("rest");
}
else if(!added){
boolean unique = uniqueRestaurantNit(R.getNit());
if(unique) {
restaurants.add(R);
info += "\n**Added!**\n";
saveData("rest");
}
else
info += "**\nRestaurant alredy exists\n**";
}
return info;
}
/**
* This method search if a restaurant NIT is unique and returns a boolean
* <b><pre>:<br>A restaurant as minimum must be added<br>
*
* @param nit String nit of restaurant NIT to search
*
* @return unique
*
* <b>post:</b>Returns a boolean notifying if Nit is unique or no<br>
*/
public boolean uniqueRestaurantNit(String nit){
boolean unique = true;
for(int i=0; i<restaurants.size() && unique; i++){
if(restaurants.get(i).getNit().equalsIgnoreCase(nit)){
unique = false;
}
}
return unique;
}
/**
* This method deploy the restaurants and sort it by his names
* <b><pre>:<br>A restaurant as minimum must be added<br>
*
* @return info
*
* <b>post:</b>Restaurants list is deployed<br>
*/
public String showRestaurants() {
String info = "";
if (restaurants.isEmpty()) {
info = "**\nThere no restaurants in list***\n";
}
else {
sortByRestaurantNameBubble();
info += getRestaurants()+"\n";
}
return info;
}
//************************************************************************************************//
//Methods of clients
/**
* This method add a client, then serialize and returns an information about the adding process
* <b><pre>:<br>The restaurant to add must have a unique NIT<br>
*
* @param name String of client name
* @param lastName String of client last name
* @param idNum String of client ID number
* @param choice Integer of the choice of ID type (CC, PP, CE or TI)
* @param tel String of client telephone
* @param address String of client address
*
* @throws IOException
*
* @return info
*
* <b>post:</b>Returns information of adding process<br>
*/
public String addClient(String name, String lastName, String idNum, int choice, String tel, String address) throws IOException {
String info = "";
String idType = "";
switch (choice) {
case 1:
idType = "CC";
break;
case 2:
idType = "PP";
break;
case 3:
idType = "CE";
break;
case 4:
idType = "TI";
break;
default:
info += "Choice not valid";
break;
}
Client c = new Client(name, lastName, idNum, idType, tel, address);
boolean unique = uniqueClientId(c.getIdNum());
if(clients.isEmpty()) {
clients.add(c);
info += "**Added!**";
saveData("client");
} else if(!unique) {
info += "**Client alredy exists **";
} else {
//method sorting called
clients.add(compareTo(c),c);
info += "**Added!**";
saveData("client");
}
return info;
}
/**
* This method sort the clients by his names and last name to add clients sorted and returns the position to add the new client
* <b><pre>:<br><br>
*
* @param c Client Object
*
* @return r
*
* <b>post:</b>Returns position to set in array<br>
*/
@Override
public int compareTo(Client c) {
int r = 0;
boolean added = false;
for (int i = 0; i < clients.size() && !added; i++) {
int S = c.getFullName().compareToIgnoreCase(clients.get(i).getFullName());
if (S > 0) {
r = i;
added = true;
} else if(!added && i == clients.size()-1) {
i++;
r = i;
added = true;
}
}
return r;
}
/**
* This method search if a client ID number is unique and returns a boolean
* <b><pre>:<br>A client as minimum must be added<br>
*
* @param idNum String ID number of client to search
*
* @return unique
*
* <b>post:</b>Returns a boolean notifying if ID number is unique or no<br>
*/
public boolean uniqueClientId(String idNum){
boolean unique = true;
for(int i=0; i<clients.size() && unique; i++){
if(clients.get(i).getIdNum().equalsIgnoreCase(idNum)){
unique = false;
}
}
return unique;
}
/**
* This method deploy the clients
* <b><pre>:<br>A client as minimum must be added<br>
*
* @return info
*
* <b>post:</b>Clients list is deployed<br>
*/
public String showClients() {
String info = "";
if (clients.isEmpty()) {
info = "There no clients in list\n";
}
else {
for (int i = 0; i < clients.size(); i++) {
info += clients.get(i).getInfo()+"\n";
info += i+"\n";
}
}
return info;
}
//***********************************************************************************************//
//Methods of products
/**
* This method add a product, then serialize and returns an information about the adding process
* <b><pre>:<br>The product to add must have a unique product code<br>
*
* @param name String of product name
* @param code String of product code
* @param infoP String of product information
* @param cost Double of product cost
* @param restNit String of restaurant NIT
*
* @throws IOException
*
* @return info
*
* <b>post:</b>Returns information of adding process<br>
*/
public String addProduct(String name, String code,String infoP, double cost, String restNit) throws IOException {
String info = "";
if(!uniqueRestaurantNit(restNit)) {
Product p = new Product(name, code, infoP, cost, restNit);
boolean unique = uniqueProductCode(p.getCode());
if(unique) {
products.add(p);
info += "Added!";
saveData("products");
}
else
info += "** Product alredy exists **";
} else {
info += "** Restaurant NIT doesnīt exists, product canīt be added! **";
}
return info;
}
/**
* This method search if a product code is unique and returns a boolean
* <b><pre>:<br>A product as minimum must be added<br>
*
* @param code String of product code
*
* @return unique
*
* <b>post:</b>Returns a boolean notifying if code is unique or no<br>
*/
public boolean uniqueProductCode(String code){
boolean unique = true;
for(int i=0; i<products.size() && unique; i++){
if(products.get(i).getCode().equalsIgnoreCase(code)){
unique = false;
}
}
return unique;
}
/**
* This method deploy the products
* <b><pre>:<br>A product as minimum must be added<br>
*
* @return info
*
* <b>post:</b>Products list is deployed<br>
*/
public String showProducts() {
String info = "";
if (products.isEmpty()) {
info = "There no products in list\n";
}
else {
for (int i = 0; i < products.size(); i++) {
info += products.get(i).getAllInfo()+"\n";
}
}
return info;
}
//***********************************************************************************************//
//Methods of orders
/**
* This method add an order, then serialize and returns an information about the adding process
* <b><pre>:<br>A restaurant must be added as minimum<br>
* <b><pre>:<br>A client must be added as minimum<br>
* <b><pre>:<br>A product must be added as minimum linked to a restaurant<br>
*
* @param code String of order code
* @param idNum String of client ID number
* @param Nit String of restaurant NIT
*
* @throws IOException
*
* @return info
*
* <b>post:</b>Returns information of adding process<br>
*/
public String addOrder(String code, String idNum, String Nit) throws IOException {
String info = "";
Order order = new Order(code, idNum, Nit);
boolean unique = uniqueOrderCode(order.getCode());
if(unique) {
orders.add(order);
saveData("orders");
info += "Added!";
}
else
info += "** Order alredy exists **";
return info;
}
/**
* This method search if an order is unique and returns a boolean
* <b><pre>:<br>An order as minimum must be added<br>
*
* @param code String order code
*
* @return unique
*
* <b>post:</b>Returns a boolean notifying if order code is unique or no<br>
*/
public boolean uniqueOrderCode(String code){
boolean unique = true;
for(int i=0; i<orders.size() && unique; i++){
if(orders.get(i).getCode().equalsIgnoreCase(code)){
unique = false;
}
}
return unique;
}
/**
* This method deploy the orders
* <b><pre>:<br>An order as minimum must be added<br>
*
* @return info
*
* <b>post:</b>Orders list is deployed<br>
*/
public String showOrders() {
String info = "";
if (orders.isEmpty()) {
info = "There no orders in list\n";
}
else {
for (int i = 0; i < orders.size(); i++) {
info += orders.get(i).getInfo()+"\n";
}
}
return info;
}
}<file_sep>package model;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
import org.junit.jupiter.api.Test;
class OrderTest {
Random random = new Random();
private RestaurantsManager restaurantsManager = new RestaurantsManager();
public void setupScenary1() throws IOException{
restaurantsManager.addRestaurant("Las delicias de Gallo", "12345", "Gallo");
restaurantsManager.addRestaurant("Las delicias de Colombia", "1234", "Camilo");
restaurantsManager.addProduct("Pollo", "4673", "Pollo por libra", 12000, "1234");
restaurantsManager.addProduct("Carne de res", "4675", "Carne de res por libra", 8500, "1234");
restaurantsManager.addClient("Andrea", "Corrales", "2154531341", 1, "31254867624", "Cali");
restaurantsManager.addOrder((String)new BigInteger(50, random).toString(32), "2154531341", "12345");
restaurantsManager.getOrders().get(0).addProductInOrderList("4673", 2);
restaurantsManager.addOrder((String)new BigInteger(50, random).toString(32), "2154531341", "12345");
restaurantsManager.getOrders().get(1).addProductInOrderList("2153", 2);
restaurantsManager.getOrders().get(1).addProductInOrderList("4673", 3);
}
@Test
public void testOrderAdded_1() throws IOException {
setupScenary1();
assertEquals("Fail test in order added", 2, restaurantsManager.getOrders().size());
}
@Test
public void testOrderSearchProductCode_1() throws IOException {
setupScenary1();
assertEquals("Fail test in order to search", 1, restaurantsManager.getOrders().get(1).searchProductInList("4673"));
}
}
| 3eaa49911162c65841b3599073601cd041820c2f | [
"Java"
]
| 4 | Java | CH1GU1/restaurantsManager | 2c224c2f8d4ab52963c08fb0c0bec63c2ee8ab54 | 7112cbe9181c989ade46207279e1943f37414900 |
refs/heads/master | <repo_name>mooneyow/wow-report<file_sep>/stuff.lua
sendSync("V", ("%d\t%s\t%s\t%s\t%s"):format(DBM.Revision, tostring(DBM.ReleaseRevision), DBM.DisplayVersion, GetLocale(), tostring(not DBM.Options.DontSetIcons)))
displayVersion
local function sendSync(prefix, msg)
msg = msg or ""
if IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and IsInInstance() and not C_Garrison:IsOnGarrisonMap() then--For BGs, LFR and LFG (we also check IsInInstance() so if you're in queue but fighting something outside like a world boss, it'll sync in "RAID" instead)
SendAddonMessage("D4", prefix .. "\t" .. msg, "INSTANCE_CHAT")
else
if IsInRaid() then
SendAddonMessage("D4", prefix .. "\t" .. msg, "RAID")
elseif IsInGroup(LE_PARTY_CATEGORY_HOME) then
SendAddonMessage("D4", prefix .. "\t" .. msg, "PARTY")
else--for solo raid
SendAddonMessage("D4", prefix .. "\t" .. msg, "WHISPER", playerName)
end
end
end
SendAddonMessage("D4", "V" .. "\t" .. ("%d\t%s\t%s\t%s\t%s"):format(DBM.Revision, tostring(DBM.ReleaseRevision), DBM.DisplayVersion, GetLocale(), tostring(not DBM.Options.DontSetIcons)), "WHISPER", "ocd")
Revision = tonumber(("$Revision: 15307 $"):sub(12, -3)),
DisplayVersion = "7.0.11", -- the string that is shown as version
ReleaseRevision = 15307 -- the revision of the latest stable version that is available
function AceComm:SendCommMessage(prefix, text, distribution, target, prio, callbackFn, callbackArg)
prio = prio or "NORMAL" -- pasta's reference implementation had different prio for singlepart and multipart, but that's a very bad idea since that can easily lead to out-of-sequence delivery!
if not( type(prefix)=="string" and
type(text)=="string" and
type(distribution)=="string" and
(target==nil or type(target)=="string") and
(prio=="BULK" or prio=="NORMAL" or prio=="ALERT")
) then
error('Usage: SendCommMessage(addon, "prefix", "text", "distribution"[, "target"[, "prio"[, callbackFn, callbackarg]]])', 2)
end
local textlen = #text
local maxtextlen = 255 -- Yes, the max is 255 even if the dev post said 256. I tested. Char 256+ get silently truncated. /Mikk, 20110327
local queueName = prefix..distribution..(target or "")
local ctlCallback = nil
if callbackFn then
ctlCallback = function(sent)
return callbackFn(callbackArg, sent, textlen)
end
end
local forceMultipart
if match(text, "^[\001-\009]") then -- 4.1+: see if the first character is a control character
-- we need to escape the first character with a \004
if textlen+1 > maxtextlen then -- would we go over the size limit?
forceMultipart = true -- just make it multipart, no escape problems then
else
text = "\004" .. text
end
end
if not forceMultipart and textlen <= maxtextlen then
-- fits all in one message
CTL:SendAddonMessage(prio, prefix, text, distribution, target, queueName, ctlCallback, textlen)
else
maxtextlen = maxtextlen - 1 -- 1 extra byte for part indicator in prefix(4.0)/start of message(4.1)
-- first part
local chunk = strsub(text, 1, maxtextlen)
CTL:SendAddonMessage(prio, prefix, MSG_MULTI_FIRST..chunk, distribution, target, queueName, ctlCallback, maxtextlen)
-- continuation
local pos = 1+maxtextlen
while pos+maxtextlen <= textlen do
chunk = strsub(text, pos, pos+maxtextlen-1)
CTL:SendAddonMessage(prio, prefix, MSG_MULTI_NEXT..chunk, distribution, target, queueName, ctlCallback, pos+maxtextlen-1)
pos = pos + maxtextlen
end
-- final part
chunk = strsub(text, pos)
CTL:SendAddonMessage(prio, prefix, MSG_MULTI_LAST..chunk, distribution, target, queueName, ctlCallback, textlen)
end
end
Recount:SendCommMessage("RECOUNT", Recount:Serialize("VQ", Recount.PlayerName, Recount.Version), "PARTY")
elseif cmd == "PS" then -- Player data set (when first meeting up)
--Recount:DPrint(cmd .." "..owner.." "..name.." "..(syncin["Damage"] or "nil").." "..(syncin["DamageTaken"] or "nil").." "..(syncin["Healing"] or "nil").." "..(syncin["OverHealing"] or "nil").." "..(syncin["HealingTaken"] or "nil").." "..(syncin["ActiveTime"] or "nil"))
if type(name) ~= "number" and (not Recount.VerNum[owner] or Recount.VerNum[owner] >= MinimumV) then
local combatant = dbCombatants[name]
if not combatant then
local nameFlags
local petowner = name:match("<(.-)>")
if owner == name or not petowner then
nameFlags = PARTY_GUARDIAN_OWNER_FLAGS
else
nameFlags = PARTY_PET_FLAGS
end
--Recount:DPrint("Creating combatant from PS: "..name.." "..(petowner or "nil"))
Recount:AddCombatant(name, petowner and owner, nil, nameFlags, nil) -- This could be bad.
combatant = dbCombatants[name]
end
syncHandlers["NS"] = function(sender, modid, modvar, text, abilityName)
local msg = modid.."\t"..modvar.."\t"..syncText.."\t"..abilityName
SendAddonMessage("D4", "NS\t" .. msg, "RAID")
local msg = modid.."\t".."modvar".."\t".."".."\t".."|22"
SendAddonMessage("D4", "NS\t" .. msg, "WHISPER", "ocd")
-- automatically sends an addon message to the appropriate channel (INSTANCE_CHAT, RAID or PARTY)
local function sendSync(prefix, msg)
--In group kill
local msg = "sdfs".."\t".."sdfs".."\t".."sdf".."\t".."|22";
SendAddonMessage("D4", "NS\t" .. msg, "PARTY")<file_sep>/README.md
## Exploiting World of Warcraft
##### Date: 2016-11-2 22:05
World of Warcraft is a fun game that I like to play in my spare time. Because it's cool it supports user interface modifications through addons. These addons are written in lua and their functionality as you can imagine is pretty restricted to prevent scamming etc.
Addons are not allowed to communicate with the internet or process' outside of the game. They can however communicate with each other through "addon message channels". These channels are not seen by the player (unless explicitly printed by the addon).
One day my guild asked everyone to install the addon NKeystone. It allows guild members to see each others keystones. Keystones are an item in-game used to unlock timed dungeons for a chance at better loot. So, it was pretty handy to have.
Me being a programmer I thought wouldn't it be cool to send something back other than my keystone? A silly item perhaps? Thunderfury, Blessed Blade of the Windseeker was the obvious choice.
The addon works by sending a request to the player asking for their keystone. Their addon then sends the itemLink in reply.
```
function SendKeystoneInfo(target)
local bagID, slotID = GetBagAndSlotIDForKeystone();
local itemLink = GetItemLinkFromBagAndSlotID(bagID, slotID);
if itemLink ~= nil then
dist = target and "WHISPER" or "GUILD";
SendAddonMessage(nkt.AddonPrefix, itemLink, dist, target);
end
end
```
This seemed like an easy thing to do, lookup the itemLink and change the function a little. The problem being when I looked up item links at http://wowwiki.wikia.com/wiki/ItemLink they used the "|" divied as opposed to "\" which the game actually uses.
I attempted to print the item link to test that it was valid and bam, game immediately freezes up. No crash, but spamming the mouse results in Windows telling me that "World of Warcraft is not responding".
That's weird. I fixed the problem by replacing the itemLink with the correctly formatted version.
About ten minutes later I had a much better idea. Why not send the dodgy itemLink to other players on purpose and see if it will lock up their game client. What could go wrong? :P
NKeystone will just print messages it receives if they are correctly formatted, expecting itemLinks, what else could it be?
This should do the trick:
```
SendAddonMessage(NKEYSTONE, "|124cffff8000|124Hitem:137225::::::::110:::::|124h[Thunderfury, Blessed Blade of the Windseeker]|124h|124r", "WHISPER", targetName);
```
(Addon messages can be to various different channels like your guild or the current raid group. Whisper sends it to one specific player.)
I had a helpful friend of mine install the addon to test it. And of course it worked and locked up his game.
Now at this point I could have stopped. I've found a way to crash a print function in the game and I can make other players addons call the function with my dodgy string. But meh, lets find more.
https://mods.curse.com/addons/wow/rclootcouncil was my next attempt. It has 500k+ monthly downloads and sends a lot of addon messages.
Because addons in the game cannot communicate with the internet it is difficult to tell when they are out of date. They accomplish this by instead sending other players their version numbers. When a version number is received that is higher than the one installed they prompt the user to update...by printing to their chat.
Like this:

Bingo. We now have a delivery mechanism common to many addons.
With some magic CTRL+F the version sending function of RCLootCouncil is found and a delivery method written:
```
addon:SendCommand(targetName, "verTest", "|124cffff8000|124Hitem:19019::::::::::0\124h[Did Someone Say?]\124h\124r", self.playerName);
```
Their game locks up instantly, nothing is printed, they don't know what caused it. And because the game does not propery crash I don't believe that it logs it (I could be totally wrong here but I couldn't find crash logs where they normally go).
It also happens to be used by all the hardcore progress raiders and most Twitch streamers. Fun could be had, but I'm a responsible adult.
There's two addons, lets try more. How about the most popular addon in the game with 5 million monthly downloads https://mods.curse.com/addons/wow/deadly-boss-mods?
Now, this addon checks what channel the addon message was sent to, most of the time.
Version numbers are only printed if received by two group members. Oh well.
If in a group you can also send an invalid note and it will print an error to chat. I can't get anyone, but hey, I can still crash some people.
So I couldn't find a way to get it to print messages from random players, I did however find a way to send anyone a countdown that pops up on their screen and verbally counts down like this: https://youtu.be/bQs_-drb6z0?t=26
That's something I guess. There was some other trickery you could do as well but it was patched after I notified the developer.
I tried getting some other addons but most of them very sensibly cast version numbers to numbers.
There are definately more that print error messages with strings from other players, but I'm in college and do not have time to read tons of code in a language I don't write...
Blizzard don't have a bug bounty program so it's a little difficult to get in-touch. Here's the timeline of how it went:
**2016-10-7** Submitted report to Blizzard via customer support
**2016-10-7** Warned NKeystone developer (I thought the bug was specific to this addon at this point, I handn't really thought about try others)
**2016-10-8** Received reply frm customer support, I was much too vague
**2016-10-8** Re-submitted report with much more detail
**2016-10-9** Was asked to submit to a different email for hacking reports and exploits in general. They don't reply to things submitted here unfortunately.
**2016-10-9** Submit to this different email
**2016-10-9** Receive reply from NKeystone developer, they patch NKeystone to validate itemLinks making it invulnerable to the crash. They also work at Blizzard and very kindly passed it on to the right people.
**2016-10-11** Received confirmation that the WoW team is working on the bug.
**2016-10-25** Bug is fixed in game client with patch 7.1!
| df5a8c03deb1568faf81b8cc449e34009152192c | [
"Markdown",
"Lua"
]
| 2 | Lua | mooneyow/wow-report | 81f28dc1b4083d9597c3d4252e6132361e2a4918 | e50f94d299785babd0a5c076ef6a42b897829f9d |
refs/heads/main | <repo_name>vernusotku/BotSecure<file_sep>/Bot/DB/DataBase.py
import mysql.connector
from mysql.connector import Error
class Database:
def __init__(self):
self.cursor = None
self.connection = None
self.host_name = None
self.db = None
self.host_user = None
self.host_password = None
def create_connection(self,host_name,db,host_user,host_password):
self.host_user = host_user
self.host_name = host_name
self.db = db
self.host_password = <PASSWORD>
try:
self.connection = mysql.connector.connect(
host = host_name,
user = host_user,
passwd = <PASSWORD>,
database = db
)
self.cursor = self.connection.cursor(buffered=True)
print('MySQL connect')
return True
except Error as e:
print(f'Error: {e}')
def create_database(self, query):
if not self.connection.is_connected():
self.create_connection(self.host_name,self.db,self.host_user,self.host_password)
self.close_cursor()
try:
self.cursor.execute(query)
except Error as e:
print(f'Error: {e}')
return True
def close_cursor(self):
self.cursor.close()
self.connection.commit()
def close_connection(self):
self.connection.close()
def connection_exist(self):
if self.connection:
return True
return False<file_sep>/bot.py
import threading
from configReader import TOKEN_BOT
import telebot
from VideoAi import start_stream
print('bot starting')
bot = telebot.TeleBot(TOKEN_BOT)
@bot.message_handler(commands='start')
def starting(message):
threading.Thread(start_stream(bot, message))
if __name__ == '__main__':
bot.polling(none_stop=True)
<file_sep>/configReader.py
import json
import os
if os.path.exists(os.getcwd()+'/config.json'):
with open('config.json') as json_file:
data = json.load(json_file)
TOKEN_BOT = data['TOKEN_BOT']<file_sep>/README.md
"# ImageAI"
<file_sep>/Bot/user.py
class User:
def __init__(self, id, ip, login, password, channel):
self.id = id
self.ip = ip
self.login = login
self.password = <PASSWORD>
self.channel = channel
def get_site(self):
return f'rtsp://{self.ip}:554/user={self.login}_password={self.password}_channel={self.channel}_stream=0.sdp?real_stream'
| 43a5335c3b5aa7a850602ea4adab667ce1f18552 | [
"Markdown",
"Python"
]
| 5 | Python | vernusotku/BotSecure | 926296df2fcd2a42ec4a52690ebf4b2a9d1534a4 | 0c7f44093d28bb27e5c54554e7e0c953cbf3a1b1 |
refs/heads/master | <file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe04_example05.dir/recipe04.cpp.o"
"recipe04_example05"
"recipe04_example05.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe04_example05.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep># - Config file for the hayai package
#
# HAYAI_INCLUDE_DIRS - include directories for hayai
# HAYAI_LIBRARIES - libraries to link against
# Compute paths.
get_filename_component(HAYAI_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
set(HAYAI_INCLUDE_DIRS "${HAYAI_CMAKE_DIR}/../../../include")
# Library dependencies (contains definitions for IMPORTED targets.)
include("${HAYAI_CMAKE_DIR}/hayai-targets.cmake")
# These are IMPORTED targets created by hayai-targets.cmake.
set(HAYAI_LIBRARIES hayai_main rt)
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe04_example03.dir/recipe04.cpp.o"
"recipe04_example03"
"recipe04_example03.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe04_example03.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe05_example03.dir/recipe05.cpp.o"
"recipe05_example03"
"recipe05_example03.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe05_example03.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h> /* for fprintf */
int main() {
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int sum = 0;
for (int i = 0; i < 10; i++) {
sum = sum + a[i];
}
printf("The sum is %i.\n", sum);
sum = 0;
//for (int *p = a; p != (int*)(&(a[10])); p++){
for (int *p = a; p != (int*) (a[10]); p++){
sum = sum + *p;
}
printf("The sum is %i.\n", sum);
}
<file_sep>/** a program to demo what happens if we (don't) run out of stack space
*/
#include <stdio.h>
#include <stdbool.h> // for bool
void f();
void main() {
int i;
while (true) {
f();
i++;
printf("iteration %i \n", i);
}
}
void f(){
int x[300];
x[0]=0;
for( int i=1; i<300; i++){
x[i] = x[i-1]+i;
}
}
<file_sep>#----------------------------------------------------------------
# Generated CMake target import file.
#----------------------------------------------------------------
# Commands may need to know the format version.
set(CMAKE_IMPORT_FILE_VERSION 1)
# Import target "hayai_main" for configuration ""
set_property(TARGET hayai_main APPEND PROPERTY IMPORTED_CONFIGURATIONS NOCONFIG)
set_target_properties(hayai_main PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES_NOCONFIG "CXX"
IMPORTED_LOCATION_NOCONFIG "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/libhayai_main.a"
)
list(APPEND _IMPORT_CHECK_TARGETS hayai_main )
list(APPEND _IMPORT_CHECK_FILES_FOR_hayai_main "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/libhayai_main.a" )
# Commands beyond this point should not need to know the version.
set(CMAKE_IMPORT_FILE_VERSION)
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/hayai"
"CMakeFiles/hayai-complete"
"hayai-prefix/src/hayai-stamp/hayai-build"
"hayai-prefix/src/hayai-stamp/hayai-configure"
"hayai-prefix/src/hayai-stamp/hayai-download"
"hayai-prefix/src/hayai-stamp/hayai-install"
"hayai-prefix/src/hayai-stamp/hayai-mkdir"
"hayai-prefix/src/hayai-stamp/hayai-patch"
"hayai-prefix/src/hayai-stamp/hayai-update"
)
# Per-language clean rules from dependency scanning.
foreach(lang )
include(CMakeFiles/hayai.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep># Install script for directory: /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai
# Set the install prefix
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
set(CMAKE_INSTALL_PREFIX "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external")
endif()
string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")
# Set the install configuration name.
if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
if(BUILD_TYPE)
string(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
else()
set(CMAKE_INSTALL_CONFIG_NAME "")
endif()
message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
endif()
# Set the component getting installed.
if(NOT CMAKE_INSTALL_COMPONENT)
if(COMPONENT)
message(STATUS "Install component: \"${COMPONENT}\"")
set(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
else()
set(CMAKE_INSTALL_COMPONENT)
endif()
endif()
# Install shared libraries without execute permission?
if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)
set(CMAKE_INSTALL_SO_NO_EXE "1")
endif()
# Is this installation the result of a crosscompile?
if(NOT DEFINED CMAKE_CROSSCOMPILING)
set(CMAKE_CROSSCOMPILING "FALSE")
endif()
if("x${CMAKE_INSTALL_COMPONENT}x" STREQUAL "xdevx" OR NOT CMAKE_INSTALL_COMPONENT)
list(APPEND CMAKE_ABSOLUTE_DESTINATION_FILES
"/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/CMake/hayai/hayai-config.cmake")
if(CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
message(WARNING "ABSOLUTE path INSTALL DESTINATION : ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
endif()
if(CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
message(FATAL_ERROR "ABSOLUTE path INSTALL DESTINATION forbidden (by caller): ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
endif()
file(INSTALL DESTINATION "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/CMake/hayai" TYPE FILE FILES "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/CMakeFiles/hayai-config.cmake")
endif()
if("x${CMAKE_INSTALL_COMPONENT}x" STREQUAL "xdevx" OR NOT CMAKE_INSTALL_COMPONENT)
if(EXISTS "$ENV{DESTDIR}/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/CMake/hayai/hayai-targets.cmake")
file(DIFFERENT EXPORT_FILE_CHANGED FILES
"$ENV{DESTDIR}/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/CMake/hayai/hayai-targets.cmake"
"/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/CMakeFiles/Export/_root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/CMake/hayai/hayai-targets.cmake")
if(EXPORT_FILE_CHANGED)
file(GLOB OLD_CONFIG_FILES "$ENV{DESTDIR}/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/CMake/hayai/hayai-targets-*.cmake")
if(OLD_CONFIG_FILES)
message(STATUS "Old export file \"$ENV{DESTDIR}/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/CMake/hayai/hayai-targets.cmake\" will be replaced. Removing files [${OLD_CONFIG_FILES}].")
file(REMOVE ${OLD_CONFIG_FILES})
endif()
endif()
endif()
list(APPEND CMAKE_ABSOLUTE_DESTINATION_FILES
"/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/CMake/hayai/hayai-targets.cmake")
if(CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
message(WARNING "ABSOLUTE path INSTALL DESTINATION : ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
endif()
if(CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
message(FATAL_ERROR "ABSOLUTE path INSTALL DESTINATION forbidden (by caller): ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
endif()
file(INSTALL DESTINATION "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/CMake/hayai" TYPE FILE FILES "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/CMakeFiles/Export/_root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/CMake/hayai/hayai-targets.cmake")
if("${CMAKE_INSTALL_CONFIG_NAME}" MATCHES "^()$")
list(APPEND CMAKE_ABSOLUTE_DESTINATION_FILES
"/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/CMake/hayai/hayai-targets-noconfig.cmake")
if(CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
message(WARNING "ABSOLUTE path INSTALL DESTINATION : ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
endif()
if(CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
message(FATAL_ERROR "ABSOLUTE path INSTALL DESTINATION forbidden (by caller): ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
endif()
file(INSTALL DESTINATION "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/CMake/hayai" TYPE FILE FILES "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/CMakeFiles/Export/_root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/external/lib/CMake/hayai/hayai-targets-noconfig.cmake")
endif()
endif()
if(NOT CMAKE_INSTALL_LOCAL_ONLY)
# Include the install script for each subdirectory.
include("/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/src/cmake_install.cmake")
include("/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/sample/cmake_install.cmake")
include("/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/vendor/gtest/cmake_install.cmake")
include("/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/tests/cmake_install.cmake")
endif()
if(CMAKE_INSTALL_COMPONENT)
set(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt")
else()
set(CMAKE_INSTALL_MANIFEST "install_manifest.txt")
endif()
string(REPLACE ";" "\n" CMAKE_INSTALL_MANIFEST_CONTENT
"${CMAKE_INSTALL_MANIFEST_FILES}")
file(WRITE "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/${CMAKE_INSTALL_MANIFEST}"
"${CMAKE_INSTALL_MANIFEST_CONTENT}")
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe01_example07.dir/recipe01.cpp.o"
"recipe01_example07"
"recipe01_example07.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe01_example07.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe03_example03.dir/recipe03.cpp.o"
"recipe03_example03"
"recipe03_example03.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe03_example03.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep># - Config file for the hayai package
#
# HAYAI_INCLUDE_DIRS - include directories for hayai
# HAYAI_LIBRARIES - libraries to link against
# Compute paths.
get_filename_component(HAYAI_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
set(HAYAI_INCLUDE_DIRS "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai/src;/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build")
# Library dependencies (contains definitions for IMPORTED targets.)
include("${HAYAI_CMAKE_DIR}/hayai-targets.cmake")
# These are IMPORTED targets created by hayai-targets.cmake.
set(HAYAI_LIBRARIES hayai_main rt)
<file_sep>#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAXWORD 100
#define NKEYS 10;
int getword(char *, int);
int binsearch(char *, struct key *, int);
typedef struct {
char *word;
int count;
}Key;
Key keytab[] ={
"auto", 0,
"break", 0,
"case", 0,
"char", 0,
"const", 0,
"continue", 0,
"default", 0,
"unsigned", 0,
"void", 0,
"volatile", 0,
"while", 0 };
main()
{
int n;
char word[MAXWORD];
while (getword(word, MAXWORD) != EOF)
if (isalpha(word[0]))
if ((n = binsearch(word, keytab, NKEYS)) >= 0)
keytab[n].count++;
for (n = 0; n < NKEYS; n++)
if (keytab[n].count > 0)
printf("%4d %s\n",
keytab[n].count, keytab[n].word);
return 0;
}
<file_sep>#include <stdio.h>
#include <string.h>
void vulnerable(char *s){
char a[10] = "Hallo ";
char buffer[10] = {'N','a','m','e','\0'};
char b[10] = ", welkom!\n";
strcpy(buffer, s); // copy s into buffer
printf("%s%s%s\n", a,buffer,b);
printf(" buffer is %s \n", buffer);
printf(" a is %s \n", a);
printf(" b is %s \n", b);
}
void main( int argc, char** argv) {
vulnerable(argv[1]);
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe07_example02.dir/recipe07.cpp.o"
"CMakeFiles/recipe07_example02.dir/recipe07_helper.cpp.o"
"recipe07_example02"
"recipe07_example02.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe07_example02.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h>
void do_print(char* string)
{
printf(string);
}
int main (int argc, char** argv){
long bla = 0xDEADC0DECAFEF00D;
do_print(argv[1]);
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/snippet_c04.dir/scratchpad.c.o"
"snippet_c04"
"snippet_c04.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/snippet_c04.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/snippet_c01.dir/scratchpad.c.o"
"snippet_c01"
"snippet_c01.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/snippet_c01.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/snippet_cpp03.dir/scratchpad.cpp.o"
"snippet_cpp03"
"snippet_cpp03.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/snippet_cpp03.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>echo "$(perl -e 'print "a" x118; print "\n"')" > badfile
<file_sep>#include <stdio.h> /* for fprintf */
#include <stdint.h> /* for intptr_t */
#include <inttypes.h> /* for printing intptr_t */
#include <stdbool.h> /* for bool */
/* Will the compiler complain about conversions that loose precision?
*
* gcc will give more warnings with command line options, for example
* -Wall
* -Wconversion
*/
int main() {
long l = 1234567812345678;
int i = l;
char c = i;
printf("As a long, 1234567812345678 is %li \n", l); // printing long integer
printf("As an int, 1234567812345678 is %i \n" , i);
printf("As a char, 1234567812345678 is %c \n" , c);
// now in hex
printf("As a long, 1234567812345678 printed in hex is %lx \n", l); // printing long hex
printf("As an int, 1234567812345678 printed in hex is %x \n" , i);
printf("As a char, 1234567812345678 printed in hex is %x \n" , c);
}
<file_sep>#include <stdio.h>
int main(){
char *shell = (char *)getenv("MYSHELL");
if(shell){
printf(" Value: %s\n", shell);
printf(" Address: %x\n", (unsigned int)shell);
printf(" Paddress: %p\n", shell);
}
return 1;
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/snippet_cpp06.dir/scratchpad.cpp.o"
"snippet_cpp06"
"snippet_cpp06.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/snippet_cpp06.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h>
#include "funs.h"
//The unary operator & gives the address of an objest,
//so the statement p = &c;
//assigns the address of c to the variable p
//p is said "point to c"
//
//The & operator only applies to objects in memory: variables and array ele//ments. It cannot be applied to expressions, constants, or register varaib//les.
//
//
//The unary operator * is the indirection or dereferencing operator; when a//pplied to a pointer it access the object the pointer points to. Suppose //that x and y are integers and ip is a pointer to int.
//
void testpointers(){
testpointerloc();
printf("This is poitner testing\n\n");
int x = 3;
int* p1 = &x;
int** p2 = &p1;
int z = **p2 +1;
printf("result of z: %d\n", z);
}
extern void testpointerloc(){
char x; int i; short s; char y;
printf("x is located at %p \n", &x);
printf("i is located at %p \n", &i);
printf("s is located at %p \n", &s);
printf("y is located at %p \n", &y);
}
extern void testarrayoverrun(){
int y = 7;
int a[2];
int x = 6;
printf("oops array over run %i \n", a[2]);
}
extern void pointerillustrate1(){
int y = 7;
int* p = &y; //assign the address of y to p;
printf ("\n\n"
"int y = 7;\n"
"int* p = &y; //assign the address of y to p;\n");
printf ("y = %i \n", y);
printf ("*p = %i \n", *p);
}
extern void pointerillustrate2(){
int y = 7;
int* p = &y; //assign the address of y to p;
int z = *p; //give z the value of what p points to
printf ("\n \n "
"int y = 7 \n "
"int* p = &y; //assign the address of y to p \n "
"int z = *p; //give z the value of what p points to \n ");
printf ("y = %i \n", y);
printf ("*p = %i \n", *p);
printf ("z = %i \n", z);
}
<file_sep>// File name: ExtremeC_exampels_chapter1_15.c
// Description: Example 1.15
#include <stdio.h>
int* create_an_integer(int default_value) {
int var = default_value;//assign value in a stack memory
return &var;//at the time this pointer is out of scope it lost its value.
}
int main() {
int* ptr = NULL;
ptr = create_an_integer(10);//the returned &var is now pointing at nothing. ptr is now a danggling pointer.
printf("%d\n", *ptr);
return 0;
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe04_example06.dir/recipe04.cpp.o"
"recipe04_example06"
"recipe04_example06.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe04_example06.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>"$(perl -e 'print "\x90" x31 . "\xcc" . "\x90" x 40 . "\xfa\xdd\xff\xff\xff\x7f"')"
<file_sep>#include <stdio.h> /* for fprintf */
int main() {
int y = 7;
int a[2];
int x = 6;
printf("Oops, accessing a[2] returns %i \n", a[2]);
printf("y is allocated at %p \n", &y);
printf("a is allocated at %p \n", &a);
printf("x is allocated at %p \n", &x);
printf("a[2] is allocated at %p \n", &(a[2]));
printf("a[3] is allocated at %p \n", &(a[3]));
printf("a[4] is allocated at %p \n", &(a[4]));
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/catch"
"CMakeFiles/catch-complete"
"catch-prefix/src/catch-stamp/catch-build"
"catch-prefix/src/catch-stamp/catch-configure"
"catch-prefix/src/catch-stamp/catch-download"
"catch-prefix/src/catch-stamp/catch-install"
"catch-prefix/src/catch-stamp/catch-mkdir"
"catch-prefix/src/catch-stamp/catch-patch"
"catch-prefix/src/catch-stamp/catch-update"
)
# Per-language clean rules from dependency scanning.
foreach(lang )
include(CMakeFiles/catch.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h>
#include "funs.h"
void test3(){
printf("this is test 3! \n");
}
<file_sep>CC=/usr/bin/gcc
CFLAGS= -Wall -Wextra -g -O3
all: main
main: main.c test.c test1.c test2.c test3.c testFuncPtr.c funs.h
$(CC) $(CFLAGS) -o main main.c test.c testFuncPtr.c
clean:
rm -f main
<file_sep>#include <stdio.h>
#include "funs.h"
void test1(){
printf("this is test 1! \n");
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe03_example02.dir/recipe03.cpp.o"
"recipe03_example02"
"recipe03_example02.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe03_example02.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h>
void printd(int n)
{
if(n<0){
putchar('-');
n=-n;
}
if(n/10)
printd(n/10);
putchar(n % 10 + '0');
}
int number =261701;
void recurint(){
number--;
printf("number is %d \n",number);
recurint();
}
void main(int narg, char* argv[]){
char* a = argv[1];
int ia;
sscanf(argv[1],"%d",&ia);
printd(ia);
printf("\n\n%s\n%d\n", argv[1], ia);
recurint();
}
<file_sep>// File name: ExtremeC_exampels_chapter1_16.c
// Description: Example 1.16
#include <stdio.h>
#include <stdlib.h>
int* create_an_integer(int default_value) {
int* var_ptr = (int*)malloc(sizeof(int));//assign a chunk of memory in heap memory, so it can pass
//value in the pointer even when the scope is end(lifetime not limited to the declating function.).
//its life ends with free() fcuntion.
*var_ptr = default_value;
return var_ptr;
}
int main() {
int* ptr = NULL;
ptr = create_an_integer(10);
printf("%d\n", *ptr);
free(ptr);
return 0;
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe06_example03.dir/recipe06.cpp.o"
"recipe06_example03"
"recipe06_example03.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe06_example03.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/** a program to demo what happens if we run out of heap space
*/
#include <stdio.h> // for printf
#include <stdbool.h> // for bool
#include <stdlib.h> // for malloc
void f();
void main() {
int i = 0;
while (true) {
f();
i++;
//printf("iteration %i \n", i);
}
}
void f(){
int *x = (int*) malloc(300*sizeof(int));
x[0] = 0;
for( int i=1; i<300; i++){
x[i] = x[i-1]+i;
}
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe06_example02.dir/recipe06.cpp.o"
"recipe06_example02"
"recipe06_example02.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe06_example02.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep># CMake generated Testfile for
# Source directory: /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai/tests
# Build directory: /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/tests
#
# This file includes the relevant testing commands required for
# testing this directory and lists subdirectories to be tested as well.
add_test(HayaiTests "tests")
set_tests_properties(HayaiTests PROPERTIES _BACKTRACE_TRIPLES "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai/tests/CMakeLists.txt;24;add_test;/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai/tests/CMakeLists.txt;0;")
<file_sep>#include <stdio.h>
#include "funs.h"
#define ALLOCSIZE 10000
int main()
{
//test1();
//test2();
testFuncPtr();
testpointers();
testarrayoverrun();
pointerillustrate1();
pointerillustrate2();
static char allocbuf[ALLOCSIZE];
static char *allocp = allocbuf;
printf("allocp, %p \n", allocp);
static char *allocp2 = &allocbuf[0];
printf("allocp2, %p \n", allocp2);
// static char allocp3 = &allocbuf[0];
// printf("allocp3, %p", allocp3);
printf("Length of string : %d \n",checklen("Hola!"));
}
extern int checklen(char *s)
{
char *p = s;
while (*p != '\0')
p++;
return p - s;
}
<file_sep># CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.16
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake
# The command to remove a file.
RM = /usr/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /root/Desktop/c/c++/Hands-On-System-Programming-with-CPP/Chapter02
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /root/Desktop/c/c++/Hands-On-System-Programming-with-CPP/Chapter02/build
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
/usr/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available.
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/usr/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start /root/Desktop/c/c++/Hands-On-System-Programming-with-CPP/Chapter02/build/CMakeFiles /root/Desktop/c/c++/Hands-On-System-Programming-with-CPP/Chapter02/build/CMakeFiles/progress.marks
$(MAKE) -f CMakeFiles/Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start /root/Desktop/c/c++/Hands-On-System-Programming-with-CPP/Chapter02/build/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named snippet_cpp06
# Build rule for target.
snippet_cpp06: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 snippet_cpp06
.PHONY : snippet_cpp06
# fast build rule for target.
snippet_cpp06/fast:
$(MAKE) -f CMakeFiles/snippet_cpp06.dir/build.make CMakeFiles/snippet_cpp06.dir/build
.PHONY : snippet_cpp06/fast
#=============================================================================
# Target rules for targets named snippet_cpp05
# Build rule for target.
snippet_cpp05: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 snippet_cpp05
.PHONY : snippet_cpp05
# fast build rule for target.
snippet_cpp05/fast:
$(MAKE) -f CMakeFiles/snippet_cpp05.dir/build.make CMakeFiles/snippet_cpp05.dir/build
.PHONY : snippet_cpp05/fast
#=============================================================================
# Target rules for targets named snippet_c01
# Build rule for target.
snippet_c01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 snippet_c01
.PHONY : snippet_c01
# fast build rule for target.
snippet_c01/fast:
$(MAKE) -f CMakeFiles/snippet_c01.dir/build.make CMakeFiles/snippet_c01.dir/build
.PHONY : snippet_c01/fast
#=============================================================================
# Target rules for targets named snippet_c05
# Build rule for target.
snippet_c05: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 snippet_c05
.PHONY : snippet_c05
# fast build rule for target.
snippet_c05/fast:
$(MAKE) -f CMakeFiles/snippet_c05.dir/build.make CMakeFiles/snippet_c05.dir/build
.PHONY : snippet_c05/fast
#=============================================================================
# Target rules for targets named snippet_c04
# Build rule for target.
snippet_c04: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 snippet_c04
.PHONY : snippet_c04
# fast build rule for target.
snippet_c04/fast:
$(MAKE) -f CMakeFiles/snippet_c04.dir/build.make CMakeFiles/snippet_c04.dir/build
.PHONY : snippet_c04/fast
#=============================================================================
# Target rules for targets named snippet_c03
# Build rule for target.
snippet_c03: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 snippet_c03
.PHONY : snippet_c03
# fast build rule for target.
snippet_c03/fast:
$(MAKE) -f CMakeFiles/snippet_c03.dir/build.make CMakeFiles/snippet_c03.dir/build
.PHONY : snippet_c03/fast
#=============================================================================
# Target rules for targets named snippet_c02
# Build rule for target.
snippet_c02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 snippet_c02
.PHONY : snippet_c02
# fast build rule for target.
snippet_c02/fast:
$(MAKE) -f CMakeFiles/snippet_c02.dir/build.make CMakeFiles/snippet_c02.dir/build
.PHONY : snippet_c02/fast
#=============================================================================
# Target rules for targets named snippet_cpp03
# Build rule for target.
snippet_cpp03: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 snippet_cpp03
.PHONY : snippet_cpp03
# fast build rule for target.
snippet_cpp03/fast:
$(MAKE) -f CMakeFiles/snippet_cpp03.dir/build.make CMakeFiles/snippet_cpp03.dir/build
.PHONY : snippet_cpp03/fast
#=============================================================================
# Target rules for targets named snippet_c06
# Build rule for target.
snippet_c06: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 snippet_c06
.PHONY : snippet_c06
# fast build rule for target.
snippet_c06/fast:
$(MAKE) -f CMakeFiles/snippet_c06.dir/build.make CMakeFiles/snippet_c06.dir/build
.PHONY : snippet_c06/fast
#=============================================================================
# Target rules for targets named snippet_cpp04
# Build rule for target.
snippet_cpp04: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 snippet_cpp04
.PHONY : snippet_cpp04
# fast build rule for target.
snippet_cpp04/fast:
$(MAKE) -f CMakeFiles/snippet_cpp04.dir/build.make CMakeFiles/snippet_cpp04.dir/build
.PHONY : snippet_cpp04/fast
#=============================================================================
# Target rules for targets named snippet_c07
# Build rule for target.
snippet_c07: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 snippet_c07
.PHONY : snippet_c07
# fast build rule for target.
snippet_c07/fast:
$(MAKE) -f CMakeFiles/snippet_c07.dir/build.make CMakeFiles/snippet_c07.dir/build
.PHONY : snippet_c07/fast
#=============================================================================
# Target rules for targets named snippet_cpp01
# Build rule for target.
snippet_cpp01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 snippet_cpp01
.PHONY : snippet_cpp01
# fast build rule for target.
snippet_cpp01/fast:
$(MAKE) -f CMakeFiles/snippet_cpp01.dir/build.make CMakeFiles/snippet_cpp01.dir/build
.PHONY : snippet_cpp01/fast
#=============================================================================
# Target rules for targets named snippet_cpp02
# Build rule for target.
snippet_cpp02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 snippet_cpp02
.PHONY : snippet_cpp02
# fast build rule for target.
snippet_cpp02/fast:
$(MAKE) -f CMakeFiles/snippet_cpp02.dir/build.make CMakeFiles/snippet_cpp02.dir/build
.PHONY : snippet_cpp02/fast
scratchpad.o: scratchpad.c.o
.PHONY : scratchpad.o
# target to build an object file
scratchpad.c.o:
$(MAKE) -f CMakeFiles/snippet_c01.dir/build.make CMakeFiles/snippet_c01.dir/scratchpad.c.o
$(MAKE) -f CMakeFiles/snippet_c05.dir/build.make CMakeFiles/snippet_c05.dir/scratchpad.c.o
$(MAKE) -f CMakeFiles/snippet_c04.dir/build.make CMakeFiles/snippet_c04.dir/scratchpad.c.o
$(MAKE) -f CMakeFiles/snippet_c03.dir/build.make CMakeFiles/snippet_c03.dir/scratchpad.c.o
$(MAKE) -f CMakeFiles/snippet_c02.dir/build.make CMakeFiles/snippet_c02.dir/scratchpad.c.o
$(MAKE) -f CMakeFiles/snippet_c06.dir/build.make CMakeFiles/snippet_c06.dir/scratchpad.c.o
$(MAKE) -f CMakeFiles/snippet_c07.dir/build.make CMakeFiles/snippet_c07.dir/scratchpad.c.o
.PHONY : scratchpad.c.o
scratchpad.i: scratchpad.c.i
.PHONY : scratchpad.i
# target to preprocess a source file
scratchpad.c.i:
$(MAKE) -f CMakeFiles/snippet_c01.dir/build.make CMakeFiles/snippet_c01.dir/scratchpad.c.i
$(MAKE) -f CMakeFiles/snippet_c05.dir/build.make CMakeFiles/snippet_c05.dir/scratchpad.c.i
$(MAKE) -f CMakeFiles/snippet_c04.dir/build.make CMakeFiles/snippet_c04.dir/scratchpad.c.i
$(MAKE) -f CMakeFiles/snippet_c03.dir/build.make CMakeFiles/snippet_c03.dir/scratchpad.c.i
$(MAKE) -f CMakeFiles/snippet_c02.dir/build.make CMakeFiles/snippet_c02.dir/scratchpad.c.i
$(MAKE) -f CMakeFiles/snippet_c06.dir/build.make CMakeFiles/snippet_c06.dir/scratchpad.c.i
$(MAKE) -f CMakeFiles/snippet_c07.dir/build.make CMakeFiles/snippet_c07.dir/scratchpad.c.i
.PHONY : scratchpad.c.i
scratchpad.s: scratchpad.c.s
.PHONY : scratchpad.s
# target to generate assembly for a file
scratchpad.c.s:
$(MAKE) -f CMakeFiles/snippet_c01.dir/build.make CMakeFiles/snippet_c01.dir/scratchpad.c.s
$(MAKE) -f CMakeFiles/snippet_c05.dir/build.make CMakeFiles/snippet_c05.dir/scratchpad.c.s
$(MAKE) -f CMakeFiles/snippet_c04.dir/build.make CMakeFiles/snippet_c04.dir/scratchpad.c.s
$(MAKE) -f CMakeFiles/snippet_c03.dir/build.make CMakeFiles/snippet_c03.dir/scratchpad.c.s
$(MAKE) -f CMakeFiles/snippet_c02.dir/build.make CMakeFiles/snippet_c02.dir/scratchpad.c.s
$(MAKE) -f CMakeFiles/snippet_c06.dir/build.make CMakeFiles/snippet_c06.dir/scratchpad.c.s
$(MAKE) -f CMakeFiles/snippet_c07.dir/build.make CMakeFiles/snippet_c07.dir/scratchpad.c.s
.PHONY : scratchpad.c.s
scratchpad.o: scratchpad.cpp.o
.PHONY : scratchpad.o
# target to build an object file
scratchpad.cpp.o:
$(MAKE) -f CMakeFiles/snippet_cpp06.dir/build.make CMakeFiles/snippet_cpp06.dir/scratchpad.cpp.o
$(MAKE) -f CMakeFiles/snippet_cpp05.dir/build.make CMakeFiles/snippet_cpp05.dir/scratchpad.cpp.o
$(MAKE) -f CMakeFiles/snippet_cpp03.dir/build.make CMakeFiles/snippet_cpp03.dir/scratchpad.cpp.o
$(MAKE) -f CMakeFiles/snippet_cpp04.dir/build.make CMakeFiles/snippet_cpp04.dir/scratchpad.cpp.o
$(MAKE) -f CMakeFiles/snippet_cpp01.dir/build.make CMakeFiles/snippet_cpp01.dir/scratchpad.cpp.o
$(MAKE) -f CMakeFiles/snippet_cpp02.dir/build.make CMakeFiles/snippet_cpp02.dir/scratchpad.cpp.o
.PHONY : scratchpad.cpp.o
scratchpad.i: scratchpad.cpp.i
.PHONY : scratchpad.i
# target to preprocess a source file
scratchpad.cpp.i:
$(MAKE) -f CMakeFiles/snippet_cpp06.dir/build.make CMakeFiles/snippet_cpp06.dir/scratchpad.cpp.i
$(MAKE) -f CMakeFiles/snippet_cpp05.dir/build.make CMakeFiles/snippet_cpp05.dir/scratchpad.cpp.i
$(MAKE) -f CMakeFiles/snippet_cpp03.dir/build.make CMakeFiles/snippet_cpp03.dir/scratchpad.cpp.i
$(MAKE) -f CMakeFiles/snippet_cpp04.dir/build.make CMakeFiles/snippet_cpp04.dir/scratchpad.cpp.i
$(MAKE) -f CMakeFiles/snippet_cpp01.dir/build.make CMakeFiles/snippet_cpp01.dir/scratchpad.cpp.i
$(MAKE) -f CMakeFiles/snippet_cpp02.dir/build.make CMakeFiles/snippet_cpp02.dir/scratchpad.cpp.i
.PHONY : scratchpad.cpp.i
scratchpad.s: scratchpad.cpp.s
.PHONY : scratchpad.s
# target to generate assembly for a file
scratchpad.cpp.s:
$(MAKE) -f CMakeFiles/snippet_cpp06.dir/build.make CMakeFiles/snippet_cpp06.dir/scratchpad.cpp.s
$(MAKE) -f CMakeFiles/snippet_cpp05.dir/build.make CMakeFiles/snippet_cpp05.dir/scratchpad.cpp.s
$(MAKE) -f CMakeFiles/snippet_cpp03.dir/build.make CMakeFiles/snippet_cpp03.dir/scratchpad.cpp.s
$(MAKE) -f CMakeFiles/snippet_cpp04.dir/build.make CMakeFiles/snippet_cpp04.dir/scratchpad.cpp.s
$(MAKE) -f CMakeFiles/snippet_cpp01.dir/build.make CMakeFiles/snippet_cpp01.dir/scratchpad.cpp.s
$(MAKE) -f CMakeFiles/snippet_cpp02.dir/build.make CMakeFiles/snippet_cpp02.dir/scratchpad.cpp.s
.PHONY : scratchpad.cpp.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... snippet_cpp06"
@echo "... edit_cache"
@echo "... snippet_cpp05"
@echo "... snippet_c01"
@echo "... snippet_c05"
@echo "... snippet_c04"
@echo "... snippet_c03"
@echo "... snippet_c02"
@echo "... snippet_cpp03"
@echo "... snippet_c06"
@echo "... snippet_cpp04"
@echo "... snippet_c07"
@echo "... snippet_cpp01"
@echo "... rebuild_cache"
@echo "... snippet_cpp02"
@echo "... scratchpad.o"
@echo "... scratchpad.i"
@echo "... scratchpad.s"
@echo "... scratchpad.o"
@echo "... scratchpad.i"
@echo "... scratchpad.s"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe07_example01.dir/recipe07.cpp.o"
"recipe07_example01"
"recipe07_example01.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe07_example01.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h>
#include "addvector.h"
int main(void)
{
int a[10], b[10], r[10];
unsigned int i;
for(i=0;i<10;i++)
{
a[i] = b[i] = i;
}
addvector(r, a, b, 10);
for(i=0;i<10;i++)
{
printf("%d %d %d\n", a[i], b[i], r[i]);
}
return 0;
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe01_example01.dir/recipe01.cpp.o"
"recipe01_example01"
"recipe01_example01.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe01_example01.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/hayai_main.dir/hayai_posix_main.o"
"libhayai_main.a"
"libhayai_main.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/hayai_main.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe06_example01.dir/recipe06.cpp.o"
"recipe06_example01"
"recipe06_example01.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe06_example01.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>
void addvector(int *r, const int *a, const int *b, unsigned int len);
<file_sep>void func(char* string)
{char buf[20];
for (int i = 0; i < 20; i++)
buf[i] ='A'+ i;
printf(buf);// our debugger
}
int main(int argc, char* argv[])
{
func(argv[1]);
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/snippet_cpp01.dir/scratchpad.cpp.o"
"snippet_cpp01"
"snippet_cpp01.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/snippet_cpp01.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h>
#include <string.h>
int f(){
char p[20];
int j;
gets(p); // NEVER USE gets!!
return 1;
}
int main(int argc, char** archv i){
char *msg ="hello";
f();
printf("%i", i);
}
<file_sep>#include <stdio.h>
#include "funs.h"
#define abc 5;
void main()
{
test1();
test2();
test3();
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe03_example04.dir/recipe03.cpp.o"
"recipe03_example04"
"recipe03_example04.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe03_example04.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe01_example02.dir/recipe01.cpp.o"
"recipe01_example02"
"recipe01_example02.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe01_example02.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe02_example06.dir/recipe02.cpp.o"
"recipe02_example06"
"recipe02_example06.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe02_example06.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>
#include <stdio.h> // for printf
#include <stdbool.h> // for bool
#include <stdlib.h> // for malloc
int *table_of(int num, int len) {
int i;
int table[len+1];
for (i=0; i <= len; i++) {
table[i] = i*num;
}
return table; /* an int[] can be treated as an int* */
}
int main(){
int *table3 = table_of(3,10);
printf("5 times 3 is %i\n", *(table3+5));
int *table4 = table_of(4,10);
printf("5 times 4 is %i\n", *(table4+5));
printf("5 times 3 is %i\n", *(table3+5));
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe04_example04.dir/recipe04.cpp.o"
"recipe04_example04"
"recipe04_example04.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe04_example04.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h>
void func(){
char *result;
char buf[100];
printf("Enter your name");
result = gets(buf);
printf(result);
}
int main (int argc, char* argv[])
{
func();
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe03_example08.dir/recipe03.cpp.o"
"recipe03_example08"
"recipe03_example08.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe03_example08.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h>
/* This demoes what may happen if we read uninitialised memory
*
*/
int counter;
/* declarations of f, g, h so we can use them in main */
void f();
void g();
void h();
int main(){
f(); // prints a value of i that it happens to find on the stack
g();
f(); // probably prints a different value for i
// because the call to g() will have changed the stack
h();
f(); // probably prints a different value for i
// because the call to h() will have changed the stack
}
void f(){
int i;
printf("i has value %i \n", i);
// because i is not initialised, this will print whatever
// value happens to be on the stack
}
void g(){
int j = 0xFFFFFFFF;
printf("j has value %i \n", j);
}
void h(){
int k = 0xCFFFFFFF;
printf("k has value %i \n", k);
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe03_example01.dir/recipe03.cpp.o"
"recipe03_example01"
"recipe03_example01.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe03_example01.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/snippet_cpp05.dir/scratchpad.cpp.o"
"snippet_cpp05"
"snippet_cpp05.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/snippet_cpp05.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>// File name: ExtremeC_exampels_chapter1_23.c
// Description: Example 1.23
#include<stdio.h>
typedef struct {
int x;
int y;
} point_t;
typedef struct {
point_t center;
int radius;
} circle_t;
typedef struct {
point_t start;
point_t end;
} line_t;
//3 differenet pointers addressing the same cell of memory
int main(int argc, char** argv){
circle_t c;
circle_t* p1 = &c;
point_t* p2 = (point_t*)&c;
int* p3 = (int*)&c;
printf("p1: %p\n",(void*)p1);
printf("p2: %p\n",(void*)p2);
printf("p3: %p\n",(void*)p3);
}
<file_sep>
# CFLAGS = -ggdb -fno-stack-protector -Wall -std=c99
CFLAGS = -ggdb -fno-stack-protector -std=c99
SRC=$(wildcard *.c)
OBJS := $(patsubst %.c, %.o, $(SRC))
BINS := $(patsubst %.c, %, $(SRC))
all: $(BINS)
%.o: %.c
gcc $(CFLAGS) -c $< -o $@
%: %.c
gcc $(CFLAGS) -o $@ $<
# With the -fsplit-stack option, the stack size can be increased
# at runtime (aka dynamically). So the compiled code will include
# a check for impending stack overflow, and code to allocate
# additional stack space.
#
# This is called "split-stack" because it means the stack is no
# longer one continguous piece of memory.
#
# The compiled code can also decide to decrease the stack space.
splitstack:
gcc -ggdb -fsplit-stack -o stack_overflow_splitstack stack_overflow.c
# GCC can spot tail-recursion in programs, and then optimise this
# away, so that the compiled code is no longer recursive. The
# binaries created by the lines below illustrate this: if we
# turn up the optimisation level, the code no longer causes a
# stack overflow.
without_optimisations:
gcc -ggdb -O0 -o stack_overflow_not_optimised stack_overflow_tailrecursion.c
with_optimisations:
gcc -ggdb -O2 -o stack_overflow_optimised stack_overflow_tailrecursion.c
clean:
rm *.o a.out
<file_sep>#include <stdio.h>
#include <stdint.h>
int main (int argc, char** argv){
long pincode2 = 0xffeeddac;
printf(argv[1]);
printf("\n");
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe05_example01.dir/recipe05.cpp.o"
"recipe05_example01"
"recipe05_example01.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe05_example01.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>
// C++ program to print DFS traversal from
// a given vertex in a given graph
//#include<bits/stdc++.h>
#include"stdc++.h"
#include<algorithm>
using namespace std;
// Graph class represents a directed graph
// using adjacency list representation
class Graph
{
int V; // No. of vertices
bool Directional;
// Pointer to an array containing
// adjacency lists
list<int> *adj;
vector<int> *ancestors;
// A recursive function used by DFS
void DFSUtil(int v, bool visited[]);
bool isCyclicUtil(int v, bool visited[], int parent);
public:
Graph(int V); // Constructor
Graph(int V, bool Directional);
// function to add an edge to graph
void addEdge(int v, int w);
bool isCyclic(); // returns true if there is a cycle
// DFS traversal of the vertices
// reachable from v
void DFS(int v);
void BFS(int v);
};
Graph::Graph(int V)
{
this->Directional = true;
this->V = V;
adj = new list<int>[V];
ancestors = new vector<int>[V];
}
Graph::Graph(int V, bool Directional)
{
this->Directional = Directional;
this->V = V;
if (this->Directional){
adj = new list<int>[V];
ancestors = new vector<int>[V];}
else{
adj = new list<int>[2*V];
ancestors = new vector<int>[V];
}
}
void Graph::addEdge(int v, int w)
{
if (this->Directional)
adj[v].push_back(w); // Add w to v’s list.
else{
adj[v].push_back(w); // Add w to v’s list.
adj[w].push_back(v); // Add w to v’s list.
}
}
bool Graph::isCyclicUtil(int v, bool visited[], int parent)
{
// Mark the current node as visited
visited[v] = true;
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
{
// If an adjacent is not visited, then recur for that adjacent
if (!visited[*i])
{
if (isCyclicUtil(*i, visited, v)){
cout << " - " << v;
return true; }
}
// If an adjacent is visited and not parent of current vertex,
// then there is a cycle.
else if (*i != parent) {
cout << "circle connects in " << *i << " - " << v;
return true; }
}
return false;
}
bool Graph::isCyclic()
{
// Mark all the vertices as not visited and not part of recursion
// stack
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
// Call the recursive helper function to detect cycle in different
// DFS trees
for (int u = 0; u < V; u++)
if (!visited[u]) // Don't recur for u if it is already visited
if (isCyclicUtil(u, visited, -1))
{ // cout << "and " << u;
return true;
}
return false;
}
void Graph::DFSUtil(int v, bool visited[])
{
// Mark the current node as visited and
// print it
visited[v] = true;
cout << v << " ";
// Recur for all the vertices adjacent
// to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i]){
/*********************looking for cercle********************
ancestors[*i].push_back(v);
if(!ancestors[v].empty()){
//copy(ancestors[v].begin(), ancestors[v].end(), back_inserter(ancestors[*i]));
if(std::find(ancestors[v].begin(), ancestors[v].end(), *i) != ancestors[v].end()){
cout << "circle exists in " << *i << "\n";
}
ancestors[*i].insert(ancestors[*i].end(), ancestors[v].begin(), ancestors[v].end());
}
std::cout <<"bgin";
for (std::vector<int>::const_iterator k = ancestors[*i].begin(); k != ancestors[*i].end(); ++k)
std::cout <<' ' << *k << ' ';
std::cout <<"end";
********************looking for cercle*********************/
DFSUtil(*i, visited);}
}
// DFS traversal of the vertices reachable from v.
// It uses recursive DFSUtil()
void Graph::DFS(int v)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
// ancestors[v].push_back(999);
// Call the recursive helper function
// to print DFS traversal
DFSUtil(v, visited);
}
void Graph::BFS(int s)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
// 'i' will be used to get all adjacent
// vertices of a vertex
list<int>::iterator i;
while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();
// Get all adjacent vertices of the dequeued
// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
// Driver code
int main(int argc, char *argv[])
{
// Create a graph given in the above diagram
Graph g(11,false);
g.addEdge(0, 1);
//g.addEdge(1, 0);
g.addEdge(1, 2);
//g.addEdge(2, 1);
g.addEdge(2, 3);
//g.addEdge(3, 2);
g.addEdge(0, 4);
//g.addEdge(4, 0);
g.addEdge(4, 5);
//g.addEdge(5, 4);
g.addEdge(5, 6);
//g.addEdge(6, 5);
g.addEdge(4, 7);
//g.addEdge(7, 1);
g.addEdge(0, 8);
//g.addEdge(8, 0);
g.addEdge(8, 9);
//g.addEdge(6, 0);
g.addEdge(6, 0);
//g.addEdge(3, 3);
cout << " DFS";
g.DFS(0);
g.isCyclic()? cout << "Graph contains cycle\n":
cout << "Graph doesn't contain cycle\n";
cout << "\n";
cout << " BFS";
g.BFS(4);
cout << "\n";
return 0;
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe02_example05.dir/recipe02.cpp.o"
"recipe02_example05"
"recipe02_example05.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe02_example05.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>CC=/usr/bin/gcc
CFLAGS=-Wall -Wextra -g -O3
all: main hello
main: main.c addvector.c addvector.h
$(CC) $(CFLAGS) -o main main.c addvector.c
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe03_example05.dir/recipe03.cpp.o"
"recipe03_example05"
"recipe03_example05.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe03_example05.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe01_example05.dir/recipe01.cpp.o"
"recipe01_example05"
"recipe01_example05.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe01_example05.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h> // for fprintf
#include <stdint.h> // for intptr_t
#include <inttypes.h> // for printing intptr_t
/* Using the operation & we can find out where a variable is
* located. The result of &x is called the ADDRESS of X or
* a POINTER to x;
*
* By compiling with the -O2 option, gcc will align variables
* differently.
*/
int main() {
char x;
int i;
short s;
char y;
printf("x is allocated at %p \n", &x);
printf("i is allocated at %p \n", &i);
printf("s is allocated at %p \n", &s);
printf("y is allocated at %p \n", &y);
}
<file_sep>#include <stdio.h>
#include "funs.h"
void test2(){
printf("this is test 2! \n");
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/snippet_c06.dir/scratchpad.c.o"
"snippet_c06"
"snippet_c06.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/snippet_c06.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>c++ -I ./boost_1_73_0 boosttest.cpp -o test
<file_sep>// File name: ExtremeC_exampels_chapter1_20.c
// Description: Example 1.20
#include <stdio.h>
//typedef: define an alias for an already defined type.
//define bool_t as an alias for int type
typedef int bool_t;
//define less_than_func_t as an alias for function pointer type boolt(*)(int,int)
typedef bool_t (*less_than_func_t)(int, int);
//in C, name of a new type usually end with _t by convention.
bool_t less_than(int a, int b) {
return a < b ? 1 : 0;
}
bool_t less_than_modular(int a, int b) {
return (a % 5) < (b % 5) ? 1 : 0;
}
int main(int argc, char** argv) {
less_than_func_t func_ptr = NULL;
func_ptr = &less_than;
bool_t result = func_ptr(3, 7);
printf("%d\n", result);
func_ptr = &less_than_modular;
result = func_ptr(3, 7);
printf("%d\n", result);
return 0;
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe01_example08.dir/recipe01.cpp.o"
"recipe01_example08"
"recipe01_example08.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe01_example08.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>//
// Copyright (C) 2019 <NAME> <<EMAIL>>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// -----------------------------------------------------------------------------
#ifdef EXAMPLE01
#include <mutex>
#include <stack>
#include <iostream>
#include <thread>
template<typename T>
class my_stack
{
std::stack<T> m_stack;
mutable std::mutex m{};
public:
int counter = 0;
int sum = 0;
template<typename ARG>
void push(ARG &&arg)
{
//std::lock_guard lock(m);
sum += std::forward<ARG>(arg);
std::cout << std::forward<ARG>(arg) << "\n" << static_cast<void*>(this) << "\n";
counter++;
m_stack.push(std::forward<ARG>(arg));
}
void pushint(int i){
push(i);
}
void pop()
{
std::lock_guard lock(m);
std::cout << "cout top " << m_stack.top() << "\n";
m_stack.pop();
}
auto empty() const
{
std::lock_guard lock(m);
return m_stack.empty();
}
};
int main(void)
{
my_stack<int> s;
int a = 4;
//stackoverflow.com/questions/21617860
std::thread t1([&]{ s.push(4); });
std::thread t2([&]{ s.push(5); });
std::thread t3([&]{ s.push(6); });
std::thread t4([&]{ s.push(7); });
std::thread t5([&]{ s.push(8); });
std::thread t6([&]{ s.push(9); });
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
t6.join();
while(!s.empty()) {
s.pop();
}
std::cout << s.counter << "\n" << s.sum << "\n";
return 0;
}
#endif
// -----------------------------------------------------------------------------
#ifdef EXAMPLE02
#include <mutex>
#include <stack>
#include <iostream>
#include <thread>
template<typename T>
class my_stack
{
std::stack<T> m_stack;
mutable std::mutex m{};
public:
int counter = 0;
int sum = 0;
template<typename ARG>
void push(ARG &&arg)
{
//std::lock_guard lock(m);
sum += std::forward<ARG>(arg);
std::cout << std::forward<ARG>(arg) << "\n" << static_cast<void*>(this) << "\n";
counter++;
m_stack.push(std::forward<ARG>(arg));
}
void pushint(int i){
push(i);
}
void pop()
{
std::lock_guard lock(m);
std::cout << "cout top " << m_stack.top() << "\n";
m_stack.pop();
}
auto empty() const
{
std::lock_guard lock(m);
return m_stack.empty();
}
};
int main(void)
{
my_stack<int> s;
// std::thread t1(&my_stack<int>::pushint, &s, 4);
//std::thread t2(&my_stack<int>::pushint, &s, 8);
//std::thread t3(&my_stack<int>::pushint, &s, 15);
//std::thread t4(&my_stack<int>::pushint, &s, 16);
//std::thread t5(&my_stack<int>::pushint, &s, 23);
//std::thread t6(&my_stack<int>::pushint, &s, 42);
s.push(4);
s.push(8);
s.push(15);
s.push(16);
s.push(23);
s.push(42);
//t1.join();
//t2.join();
//t3.join();
//t4.join();
//t5.join();
//t6.join();
while(!s.empty()) {
s.pop();
}
std::cout << s.counter << "\n" << s.sum << "\n";
return 0;
}
#endif
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe01_example06.dir/recipe01.cpp.o"
"recipe01_example06"
"recipe01_example06.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe01_example06.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h>
#include "funs.h"
int (*functionPtr)(int,int);
int (*functionPtr3)(int, int, int);
int addInt(int n, int m){
return n+m;
}
int add3Int(int a, int b, int c){
return a+b+c;
}
void testFuncPtr(){
printf("this is FuncPtr! \n");
functionPtr = &addInt;
// the standard says that a function name in this context is converted to the address // of the function
functionPtr3 = add3Int;
int sum = (*functionPtr)(2, 3);
int sum3= (*functionPtr3)(2,3,4);
printf("result from function ptr %d \n", sum);
printf("result from function ptr 3 %d \n", sum3);
}
<file_sep>
# CFLAGS = -ggdb -fno-stack-protector -std=c99 -Wconversion
# CFLAGS = -ggdb -fno-stack-protector -Wall -std=c99
CFLAGS = -ggdb -std=c99 -Wall
SRC=$(wildcard *.c)
OBJS := $(patsubst %.c, %.o, $(SRC))
BINS := $(patsubst %.c, %, $(SRC))
all: $(BINS)
%.o: %.c
gcc $(CFLAGS) -c $< -o $@
%: %.c
gcc $(CFLAGS) -o $@ $<
align:
gcc -ggdb -O2 -o where_is_data_allocated where_is_data_allocated.c
notopt:
gcc -ggdb -o stack_overflow_printing stack_overflow_printing.c
opt:
gcc -ggdb -O2 -o stack_overflow_optimisable stack_overflow_optimisable.c
clean:
rm *.o a.out
<file_sep>#include <stdio.h>
#include <string.h>
int main( int argc, char** argv) {
char buffer[10];
printf("What is your name?\n");
gets(buffer);
printf("Hello %s, welcome to our website!\n", buffer);
return 0;
}
<file_sep>// File name: ExtremeC_exampels_chapter1_9.c
// Description: Example 1.9
int main(int argc, char** argv) {
int var = 100;
int* ptr = 0; //assigning a null pointer
ptr = &var;
printf("%x \n",ptr);
*ptr = 200;
printf("%x \n",ptr);
return 0;
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe01_example04.dir/recipe01.cpp.o"
"recipe01_example04"
"recipe01_example04.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe01_example04.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe03_example07.dir/recipe03.cpp.o"
"recipe03_example07"
"recipe03_example07.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe03_example07.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep># CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.16
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake
# The command to remove a file.
RM = /usr/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter02
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter02/build
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/usr/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
/usr/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available.
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter02/build/CMakeFiles /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter02/build/CMakeFiles/progress.marks
$(MAKE) -f CMakeFiles/Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter02/build/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named recipe05_example03
# Build rule for target.
recipe05_example03: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe05_example03
.PHONY : recipe05_example03
# fast build rule for target.
recipe05_example03/fast:
$(MAKE) -f CMakeFiles/recipe05_example03.dir/build.make CMakeFiles/recipe05_example03.dir/build
.PHONY : recipe05_example03/fast
#=============================================================================
# Target rules for targets named recipe05_example01
# Build rule for target.
recipe05_example01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe05_example01
.PHONY : recipe05_example01
# fast build rule for target.
recipe05_example01/fast:
$(MAKE) -f CMakeFiles/recipe05_example01.dir/build.make CMakeFiles/recipe05_example01.dir/build
.PHONY : recipe05_example01/fast
#=============================================================================
# Target rules for targets named recipe01_example01
# Build rule for target.
recipe01_example01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe01_example01
.PHONY : recipe01_example01
# fast build rule for target.
recipe01_example01/fast:
$(MAKE) -f CMakeFiles/recipe01_example01.dir/build.make CMakeFiles/recipe01_example01.dir/build
.PHONY : recipe01_example01/fast
#=============================================================================
# Target rules for targets named recipe02_example03
# Build rule for target.
recipe02_example03: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe02_example03
.PHONY : recipe02_example03
# fast build rule for target.
recipe02_example03/fast:
$(MAKE) -f CMakeFiles/recipe02_example03.dir/build.make CMakeFiles/recipe02_example03.dir/build
.PHONY : recipe02_example03/fast
#=============================================================================
# Target rules for targets named recipe03_example01
# Build rule for target.
recipe03_example01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe03_example01
.PHONY : recipe03_example01
# fast build rule for target.
recipe03_example01/fast:
$(MAKE) -f CMakeFiles/recipe03_example01.dir/build.make CMakeFiles/recipe03_example01.dir/build
.PHONY : recipe03_example01/fast
#=============================================================================
# Target rules for targets named recipe02_example02
# Build rule for target.
recipe02_example02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe02_example02
.PHONY : recipe02_example02
# fast build rule for target.
recipe02_example02/fast:
$(MAKE) -f CMakeFiles/recipe02_example02.dir/build.make CMakeFiles/recipe02_example02.dir/build
.PHONY : recipe02_example02/fast
#=============================================================================
# Target rules for targets named recipe01_example03
# Build rule for target.
recipe01_example03: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe01_example03
.PHONY : recipe01_example03
# fast build rule for target.
recipe01_example03/fast:
$(MAKE) -f CMakeFiles/recipe01_example03.dir/build.make CMakeFiles/recipe01_example03.dir/build
.PHONY : recipe01_example03/fast
#=============================================================================
# Target rules for targets named recipe01_example05
# Build rule for target.
recipe01_example05: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe01_example05
.PHONY : recipe01_example05
# fast build rule for target.
recipe01_example05/fast:
$(MAKE) -f CMakeFiles/recipe01_example05.dir/build.make CMakeFiles/recipe01_example05.dir/build
.PHONY : recipe01_example05/fast
#=============================================================================
# Target rules for targets named recipe02_example01
# Build rule for target.
recipe02_example01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe02_example01
.PHONY : recipe02_example01
# fast build rule for target.
recipe02_example01/fast:
$(MAKE) -f CMakeFiles/recipe02_example01.dir/build.make CMakeFiles/recipe02_example01.dir/build
.PHONY : recipe02_example01/fast
#=============================================================================
# Target rules for targets named recipe02_example04
# Build rule for target.
recipe02_example04: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe02_example04
.PHONY : recipe02_example04
# fast build rule for target.
recipe02_example04/fast:
$(MAKE) -f CMakeFiles/recipe02_example04.dir/build.make CMakeFiles/recipe02_example04.dir/build
.PHONY : recipe02_example04/fast
#=============================================================================
# Target rules for targets named recipe01_example02
# Build rule for target.
recipe01_example02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe01_example02
.PHONY : recipe01_example02
# fast build rule for target.
recipe01_example02/fast:
$(MAKE) -f CMakeFiles/recipe01_example02.dir/build.make CMakeFiles/recipe01_example02.dir/build
.PHONY : recipe01_example02/fast
#=============================================================================
# Target rules for targets named recipe03_example03
# Build rule for target.
recipe03_example03: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe03_example03
.PHONY : recipe03_example03
# fast build rule for target.
recipe03_example03/fast:
$(MAKE) -f CMakeFiles/recipe03_example03.dir/build.make CMakeFiles/recipe03_example03.dir/build
.PHONY : recipe03_example03/fast
#=============================================================================
# Target rules for targets named recipe02_example05
# Build rule for target.
recipe02_example05: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe02_example05
.PHONY : recipe02_example05
# fast build rule for target.
recipe02_example05/fast:
$(MAKE) -f CMakeFiles/recipe02_example05.dir/build.make CMakeFiles/recipe02_example05.dir/build
.PHONY : recipe02_example05/fast
#=============================================================================
# Target rules for targets named recipe04_example04
# Build rule for target.
recipe04_example04: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe04_example04
.PHONY : recipe04_example04
# fast build rule for target.
recipe04_example04/fast:
$(MAKE) -f CMakeFiles/recipe04_example04.dir/build.make CMakeFiles/recipe04_example04.dir/build
.PHONY : recipe04_example04/fast
#=============================================================================
# Target rules for targets named recipe02_example06
# Build rule for target.
recipe02_example06: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe02_example06
.PHONY : recipe02_example06
# fast build rule for target.
recipe02_example06/fast:
$(MAKE) -f CMakeFiles/recipe02_example06.dir/build.make CMakeFiles/recipe02_example06.dir/build
.PHONY : recipe02_example06/fast
#=============================================================================
# Target rules for targets named recipe04_example03
# Build rule for target.
recipe04_example03: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe04_example03
.PHONY : recipe04_example03
# fast build rule for target.
recipe04_example03/fast:
$(MAKE) -f CMakeFiles/recipe04_example03.dir/build.make CMakeFiles/recipe04_example03.dir/build
.PHONY : recipe04_example03/fast
#=============================================================================
# Target rules for targets named recipe03_examples
# Build rule for target.
recipe03_examples: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe03_examples
.PHONY : recipe03_examples
# fast build rule for target.
recipe03_examples/fast:
$(MAKE) -f CMakeFiles/recipe03_examples.dir/build.make CMakeFiles/recipe03_examples.dir/build
.PHONY : recipe03_examples/fast
#=============================================================================
# Target rules for targets named recipe02_examples
# Build rule for target.
recipe02_examples: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe02_examples
.PHONY : recipe02_examples
# fast build rule for target.
recipe02_examples/fast:
$(MAKE) -f CMakeFiles/recipe02_examples.dir/build.make CMakeFiles/recipe02_examples.dir/build
.PHONY : recipe02_examples/fast
#=============================================================================
# Target rules for targets named recipe01_examples
# Build rule for target.
recipe01_examples: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe01_examples
.PHONY : recipe01_examples
# fast build rule for target.
recipe01_examples/fast:
$(MAKE) -f CMakeFiles/recipe01_examples.dir/build.make CMakeFiles/recipe01_examples.dir/build
.PHONY : recipe01_examples/fast
#=============================================================================
# Target rules for targets named recipe04_examples
# Build rule for target.
recipe04_examples: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe04_examples
.PHONY : recipe04_examples
# fast build rule for target.
recipe04_examples/fast:
$(MAKE) -f CMakeFiles/recipe04_examples.dir/build.make CMakeFiles/recipe04_examples.dir/build
.PHONY : recipe04_examples/fast
#=============================================================================
# Target rules for targets named recipe03_example02
# Build rule for target.
recipe03_example02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe03_example02
.PHONY : recipe03_example02
# fast build rule for target.
recipe03_example02/fast:
$(MAKE) -f CMakeFiles/recipe03_example02.dir/build.make CMakeFiles/recipe03_example02.dir/build
.PHONY : recipe03_example02/fast
#=============================================================================
# Target rules for targets named recipe05_example02
# Build rule for target.
recipe05_example02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe05_example02
.PHONY : recipe05_example02
# fast build rule for target.
recipe05_example02/fast:
$(MAKE) -f CMakeFiles/recipe05_example02.dir/build.make CMakeFiles/recipe05_example02.dir/build
.PHONY : recipe05_example02/fast
#=============================================================================
# Target rules for targets named recipe01_example04
# Build rule for target.
recipe01_example04: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe01_example04
.PHONY : recipe01_example04
# fast build rule for target.
recipe01_example04/fast:
$(MAKE) -f CMakeFiles/recipe01_example04.dir/build.make CMakeFiles/recipe01_example04.dir/build
.PHONY : recipe01_example04/fast
#=============================================================================
# Target rules for targets named recipe03_example04
# Build rule for target.
recipe03_example04: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe03_example04
.PHONY : recipe03_example04
# fast build rule for target.
recipe03_example04/fast:
$(MAKE) -f CMakeFiles/recipe03_example04.dir/build.make CMakeFiles/recipe03_example04.dir/build
.PHONY : recipe03_example04/fast
#=============================================================================
# Target rules for targets named recipe03_example05
# Build rule for target.
recipe03_example05: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe03_example05
.PHONY : recipe03_example05
# fast build rule for target.
recipe03_example05/fast:
$(MAKE) -f CMakeFiles/recipe03_example05.dir/build.make CMakeFiles/recipe03_example05.dir/build
.PHONY : recipe03_example05/fast
#=============================================================================
# Target rules for targets named recipe05_examples
# Build rule for target.
recipe05_examples: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe05_examples
.PHONY : recipe05_examples
# fast build rule for target.
recipe05_examples/fast:
$(MAKE) -f CMakeFiles/recipe05_examples.dir/build.make CMakeFiles/recipe05_examples.dir/build
.PHONY : recipe05_examples/fast
#=============================================================================
# Target rules for targets named recipe04_example01
# Build rule for target.
recipe04_example01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe04_example01
.PHONY : recipe04_example01
# fast build rule for target.
recipe04_example01/fast:
$(MAKE) -f CMakeFiles/recipe04_example01.dir/build.make CMakeFiles/recipe04_example01.dir/build
.PHONY : recipe04_example01/fast
#=============================================================================
# Target rules for targets named recipe04_example02
# Build rule for target.
recipe04_example02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe04_example02
.PHONY : recipe04_example02
# fast build rule for target.
recipe04_example02/fast:
$(MAKE) -f CMakeFiles/recipe04_example02.dir/build.make CMakeFiles/recipe04_example02.dir/build
.PHONY : recipe04_example02/fast
recipe01.o: recipe01.cpp.o
.PHONY : recipe01.o
# target to build an object file
recipe01.cpp.o:
$(MAKE) -f CMakeFiles/recipe01_example01.dir/build.make CMakeFiles/recipe01_example01.dir/recipe01.cpp.o
$(MAKE) -f CMakeFiles/recipe01_example03.dir/build.make CMakeFiles/recipe01_example03.dir/recipe01.cpp.o
$(MAKE) -f CMakeFiles/recipe01_example05.dir/build.make CMakeFiles/recipe01_example05.dir/recipe01.cpp.o
$(MAKE) -f CMakeFiles/recipe01_example02.dir/build.make CMakeFiles/recipe01_example02.dir/recipe01.cpp.o
$(MAKE) -f CMakeFiles/recipe01_example04.dir/build.make CMakeFiles/recipe01_example04.dir/recipe01.cpp.o
.PHONY : recipe01.cpp.o
recipe01.i: recipe01.cpp.i
.PHONY : recipe01.i
# target to preprocess a source file
recipe01.cpp.i:
$(MAKE) -f CMakeFiles/recipe01_example01.dir/build.make CMakeFiles/recipe01_example01.dir/recipe01.cpp.i
$(MAKE) -f CMakeFiles/recipe01_example03.dir/build.make CMakeFiles/recipe01_example03.dir/recipe01.cpp.i
$(MAKE) -f CMakeFiles/recipe01_example05.dir/build.make CMakeFiles/recipe01_example05.dir/recipe01.cpp.i
$(MAKE) -f CMakeFiles/recipe01_example02.dir/build.make CMakeFiles/recipe01_example02.dir/recipe01.cpp.i
$(MAKE) -f CMakeFiles/recipe01_example04.dir/build.make CMakeFiles/recipe01_example04.dir/recipe01.cpp.i
.PHONY : recipe01.cpp.i
recipe01.s: recipe01.cpp.s
.PHONY : recipe01.s
# target to generate assembly for a file
recipe01.cpp.s:
$(MAKE) -f CMakeFiles/recipe01_example01.dir/build.make CMakeFiles/recipe01_example01.dir/recipe01.cpp.s
$(MAKE) -f CMakeFiles/recipe01_example03.dir/build.make CMakeFiles/recipe01_example03.dir/recipe01.cpp.s
$(MAKE) -f CMakeFiles/recipe01_example05.dir/build.make CMakeFiles/recipe01_example05.dir/recipe01.cpp.s
$(MAKE) -f CMakeFiles/recipe01_example02.dir/build.make CMakeFiles/recipe01_example02.dir/recipe01.cpp.s
$(MAKE) -f CMakeFiles/recipe01_example04.dir/build.make CMakeFiles/recipe01_example04.dir/recipe01.cpp.s
.PHONY : recipe01.cpp.s
recipe02.o: recipe02.cpp.o
.PHONY : recipe02.o
# target to build an object file
recipe02.cpp.o:
$(MAKE) -f CMakeFiles/recipe02_example03.dir/build.make CMakeFiles/recipe02_example03.dir/recipe02.cpp.o
$(MAKE) -f CMakeFiles/recipe02_example02.dir/build.make CMakeFiles/recipe02_example02.dir/recipe02.cpp.o
$(MAKE) -f CMakeFiles/recipe02_example01.dir/build.make CMakeFiles/recipe02_example01.dir/recipe02.cpp.o
$(MAKE) -f CMakeFiles/recipe02_example04.dir/build.make CMakeFiles/recipe02_example04.dir/recipe02.cpp.o
$(MAKE) -f CMakeFiles/recipe02_example05.dir/build.make CMakeFiles/recipe02_example05.dir/recipe02.cpp.o
$(MAKE) -f CMakeFiles/recipe02_example06.dir/build.make CMakeFiles/recipe02_example06.dir/recipe02.cpp.o
.PHONY : recipe02.cpp.o
recipe02.i: recipe02.cpp.i
.PHONY : recipe02.i
# target to preprocess a source file
recipe02.cpp.i:
$(MAKE) -f CMakeFiles/recipe02_example03.dir/build.make CMakeFiles/recipe02_example03.dir/recipe02.cpp.i
$(MAKE) -f CMakeFiles/recipe02_example02.dir/build.make CMakeFiles/recipe02_example02.dir/recipe02.cpp.i
$(MAKE) -f CMakeFiles/recipe02_example01.dir/build.make CMakeFiles/recipe02_example01.dir/recipe02.cpp.i
$(MAKE) -f CMakeFiles/recipe02_example04.dir/build.make CMakeFiles/recipe02_example04.dir/recipe02.cpp.i
$(MAKE) -f CMakeFiles/recipe02_example05.dir/build.make CMakeFiles/recipe02_example05.dir/recipe02.cpp.i
$(MAKE) -f CMakeFiles/recipe02_example06.dir/build.make CMakeFiles/recipe02_example06.dir/recipe02.cpp.i
.PHONY : recipe02.cpp.i
recipe02.s: recipe02.cpp.s
.PHONY : recipe02.s
# target to generate assembly for a file
recipe02.cpp.s:
$(MAKE) -f CMakeFiles/recipe02_example03.dir/build.make CMakeFiles/recipe02_example03.dir/recipe02.cpp.s
$(MAKE) -f CMakeFiles/recipe02_example02.dir/build.make CMakeFiles/recipe02_example02.dir/recipe02.cpp.s
$(MAKE) -f CMakeFiles/recipe02_example01.dir/build.make CMakeFiles/recipe02_example01.dir/recipe02.cpp.s
$(MAKE) -f CMakeFiles/recipe02_example04.dir/build.make CMakeFiles/recipe02_example04.dir/recipe02.cpp.s
$(MAKE) -f CMakeFiles/recipe02_example05.dir/build.make CMakeFiles/recipe02_example05.dir/recipe02.cpp.s
$(MAKE) -f CMakeFiles/recipe02_example06.dir/build.make CMakeFiles/recipe02_example06.dir/recipe02.cpp.s
.PHONY : recipe02.cpp.s
recipe03.o: recipe03.cpp.o
.PHONY : recipe03.o
# target to build an object file
recipe03.cpp.o:
$(MAKE) -f CMakeFiles/recipe03_example01.dir/build.make CMakeFiles/recipe03_example01.dir/recipe03.cpp.o
$(MAKE) -f CMakeFiles/recipe03_example03.dir/build.make CMakeFiles/recipe03_example03.dir/recipe03.cpp.o
$(MAKE) -f CMakeFiles/recipe03_example02.dir/build.make CMakeFiles/recipe03_example02.dir/recipe03.cpp.o
$(MAKE) -f CMakeFiles/recipe03_example04.dir/build.make CMakeFiles/recipe03_example04.dir/recipe03.cpp.o
$(MAKE) -f CMakeFiles/recipe03_example05.dir/build.make CMakeFiles/recipe03_example05.dir/recipe03.cpp.o
.PHONY : recipe03.cpp.o
recipe03.i: recipe03.cpp.i
.PHONY : recipe03.i
# target to preprocess a source file
recipe03.cpp.i:
$(MAKE) -f CMakeFiles/recipe03_example01.dir/build.make CMakeFiles/recipe03_example01.dir/recipe03.cpp.i
$(MAKE) -f CMakeFiles/recipe03_example03.dir/build.make CMakeFiles/recipe03_example03.dir/recipe03.cpp.i
$(MAKE) -f CMakeFiles/recipe03_example02.dir/build.make CMakeFiles/recipe03_example02.dir/recipe03.cpp.i
$(MAKE) -f CMakeFiles/recipe03_example04.dir/build.make CMakeFiles/recipe03_example04.dir/recipe03.cpp.i
$(MAKE) -f CMakeFiles/recipe03_example05.dir/build.make CMakeFiles/recipe03_example05.dir/recipe03.cpp.i
.PHONY : recipe03.cpp.i
recipe03.s: recipe03.cpp.s
.PHONY : recipe03.s
# target to generate assembly for a file
recipe03.cpp.s:
$(MAKE) -f CMakeFiles/recipe03_example01.dir/build.make CMakeFiles/recipe03_example01.dir/recipe03.cpp.s
$(MAKE) -f CMakeFiles/recipe03_example03.dir/build.make CMakeFiles/recipe03_example03.dir/recipe03.cpp.s
$(MAKE) -f CMakeFiles/recipe03_example02.dir/build.make CMakeFiles/recipe03_example02.dir/recipe03.cpp.s
$(MAKE) -f CMakeFiles/recipe03_example04.dir/build.make CMakeFiles/recipe03_example04.dir/recipe03.cpp.s
$(MAKE) -f CMakeFiles/recipe03_example05.dir/build.make CMakeFiles/recipe03_example05.dir/recipe03.cpp.s
.PHONY : recipe03.cpp.s
recipe04.o: recipe04.cpp.o
.PHONY : recipe04.o
# target to build an object file
recipe04.cpp.o:
$(MAKE) -f CMakeFiles/recipe04_example04.dir/build.make CMakeFiles/recipe04_example04.dir/recipe04.cpp.o
$(MAKE) -f CMakeFiles/recipe04_example03.dir/build.make CMakeFiles/recipe04_example03.dir/recipe04.cpp.o
$(MAKE) -f CMakeFiles/recipe04_example01.dir/build.make CMakeFiles/recipe04_example01.dir/recipe04.cpp.o
$(MAKE) -f CMakeFiles/recipe04_example02.dir/build.make CMakeFiles/recipe04_example02.dir/recipe04.cpp.o
.PHONY : recipe04.cpp.o
recipe04.i: recipe04.cpp.i
.PHONY : recipe04.i
# target to preprocess a source file
recipe04.cpp.i:
$(MAKE) -f CMakeFiles/recipe04_example04.dir/build.make CMakeFiles/recipe04_example04.dir/recipe04.cpp.i
$(MAKE) -f CMakeFiles/recipe04_example03.dir/build.make CMakeFiles/recipe04_example03.dir/recipe04.cpp.i
$(MAKE) -f CMakeFiles/recipe04_example01.dir/build.make CMakeFiles/recipe04_example01.dir/recipe04.cpp.i
$(MAKE) -f CMakeFiles/recipe04_example02.dir/build.make CMakeFiles/recipe04_example02.dir/recipe04.cpp.i
.PHONY : recipe04.cpp.i
recipe04.s: recipe04.cpp.s
.PHONY : recipe04.s
# target to generate assembly for a file
recipe04.cpp.s:
$(MAKE) -f CMakeFiles/recipe04_example04.dir/build.make CMakeFiles/recipe04_example04.dir/recipe04.cpp.s
$(MAKE) -f CMakeFiles/recipe04_example03.dir/build.make CMakeFiles/recipe04_example03.dir/recipe04.cpp.s
$(MAKE) -f CMakeFiles/recipe04_example01.dir/build.make CMakeFiles/recipe04_example01.dir/recipe04.cpp.s
$(MAKE) -f CMakeFiles/recipe04_example02.dir/build.make CMakeFiles/recipe04_example02.dir/recipe04.cpp.s
.PHONY : recipe04.cpp.s
recipe05.o: recipe05.cpp.o
.PHONY : recipe05.o
# target to build an object file
recipe05.cpp.o:
$(MAKE) -f CMakeFiles/recipe05_example03.dir/build.make CMakeFiles/recipe05_example03.dir/recipe05.cpp.o
$(MAKE) -f CMakeFiles/recipe05_example01.dir/build.make CMakeFiles/recipe05_example01.dir/recipe05.cpp.o
$(MAKE) -f CMakeFiles/recipe05_example02.dir/build.make CMakeFiles/recipe05_example02.dir/recipe05.cpp.o
.PHONY : recipe05.cpp.o
recipe05.i: recipe05.cpp.i
.PHONY : recipe05.i
# target to preprocess a source file
recipe05.cpp.i:
$(MAKE) -f CMakeFiles/recipe05_example03.dir/build.make CMakeFiles/recipe05_example03.dir/recipe05.cpp.i
$(MAKE) -f CMakeFiles/recipe05_example01.dir/build.make CMakeFiles/recipe05_example01.dir/recipe05.cpp.i
$(MAKE) -f CMakeFiles/recipe05_example02.dir/build.make CMakeFiles/recipe05_example02.dir/recipe05.cpp.i
.PHONY : recipe05.cpp.i
recipe05.s: recipe05.cpp.s
.PHONY : recipe05.s
# target to generate assembly for a file
recipe05.cpp.s:
$(MAKE) -f CMakeFiles/recipe05_example03.dir/build.make CMakeFiles/recipe05_example03.dir/recipe05.cpp.s
$(MAKE) -f CMakeFiles/recipe05_example01.dir/build.make CMakeFiles/recipe05_example01.dir/recipe05.cpp.s
$(MAKE) -f CMakeFiles/recipe05_example02.dir/build.make CMakeFiles/recipe05_example02.dir/recipe05.cpp.s
.PHONY : recipe05.cpp.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... rebuild_cache"
@echo "... edit_cache"
@echo "... recipe05_example03"
@echo "... recipe05_example01"
@echo "... recipe01_example01"
@echo "... recipe02_example03"
@echo "... recipe03_example01"
@echo "... recipe02_example02"
@echo "... recipe01_example03"
@echo "... recipe01_example05"
@echo "... recipe02_example01"
@echo "... recipe02_example04"
@echo "... recipe01_example02"
@echo "... recipe03_example03"
@echo "... recipe02_example05"
@echo "... recipe04_example04"
@echo "... recipe02_example06"
@echo "... recipe04_example03"
@echo "... recipe03_examples"
@echo "... recipe02_examples"
@echo "... recipe01_examples"
@echo "... recipe04_examples"
@echo "... recipe03_example02"
@echo "... recipe05_example02"
@echo "... recipe01_example04"
@echo "... recipe03_example04"
@echo "... recipe03_example05"
@echo "... recipe05_examples"
@echo "... recipe04_example01"
@echo "... recipe04_example02"
@echo "... recipe01.o"
@echo "... recipe01.i"
@echo "... recipe01.s"
@echo "... recipe02.o"
@echo "... recipe02.i"
@echo "... recipe02.s"
@echo "... recipe03.o"
@echo "... recipe03.i"
@echo "... recipe03.s"
@echo "... recipe04.o"
@echo "... recipe04.i"
@echo "... recipe04.s"
@echo "... recipe05.o"
@echo "... recipe05.i"
@echo "... recipe05.s"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe02_example02.dir/recipe02.cpp.o"
"recipe02_example02"
"recipe02_example02.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe02_example02.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>
int main(){
int number = 255;
printf ("number = %d \n", number);
//set off
number &= ~(1UL << 2);
printf ("number after off 2nd bit= %d \n", number);
number |= 1UL << 2;
printf ("number after set 2nd bit= %d \n", number);
number ^= 1UL << 2;
printf ("number after toggle 2nd bit= %d \n", number);
}
<file_sep>CC=/usr/bin/gcc
CFLAGS= -Wall -Wextra -g -O3
all: main
main: main.c test1.c test2.c test3.c funs.h
$(CC) $(CFLAGS) -o main main.c test1.c test2.c test3.c
<file_sep>#include <stdio.h>
/* An example to show the effect of a stack overflow.
*
* Note:
*
* - comparing this code with stack_overflow_printing.c shows that
* printing is very slow!
*
* - making the string longer means we run out of memory faster.
*
* - using the -fstack-split option of gcc will change the
* behaviour, because then the stack size can be adjusted when
* the program runs.
*/
int counter = 261701;
int main(){
char* string = "let's use up some memory";
counter--;
main();
}
<file_sep># CMake generated Testfile for
# Source directory: /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai
# Build directory: /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build
#
# This file includes the relevant testing commands required for
# testing this directory and lists subdirectories to be tested as well.
subdirs("src")
subdirs("sample")
subdirs("vendor/gtest")
subdirs("tests")
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe03_example06.dir/recipe03.cpp.o"
"recipe03_example06"
"recipe03_example06.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe03_example06.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep># The set of languages for which implicit dependencies are needed:
set(CMAKE_DEPENDS_LANGUAGES
"CXX"
)
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
"/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai/sample/delivery_man_benchmark.cpp" "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/sample/CMakeFiles/sample.dir/delivery_man_benchmark.o"
"/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai/sample/delivery_man_benchmark_parameterized.cpp" "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/sample/CMakeFiles/sample.dir/delivery_man_benchmark_parameterized.o"
"/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai/sample/delivery_man_benchmark_parameterized_with_fixture.cpp" "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/sample/CMakeFiles/sample.dir/delivery_man_benchmark_parameterized_with_fixture.o"
"/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai/sample/delivery_man_benchmark_with_fixture.cpp" "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/sample/CMakeFiles/sample.dir/delivery_man_benchmark_with_fixture.o"
"/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai/sample/delivery_man_sleep.cpp" "/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/sample/CMakeFiles/sample.dir/delivery_man_sleep.o"
)
set(CMAKE_CXX_COMPILER_ID "GNU")
# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
"/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai/src"
)
# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
"/root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter06/build/hayai-prefix/src/hayai-build/src/CMakeFiles/hayai_main.dir/DependInfo.cmake"
)
# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")
<file_sep>#include <stdio.h>
/* Printing an integer n different formats */
int main( ) {
int j = 15;
printf("The value of j is %i \n", j);
printf("In octal notation: %o \n", j);
printf("In hexadecimal notation: %x \n", j);
printf("Idem with capitals: %X \n", j);
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe02_example04.dir/recipe02.cpp.o"
"recipe02_example04"
"recipe02_example04.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe02_example04.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep># CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.16
# The generator used is:
set(CMAKE_DEPENDS_GENERATOR "Unix Makefiles")
# The top level Makefile was generated from the following files:
set(CMAKE_MAKEFILE_DEPENDS
"CMakeCache.txt"
"../CMakeLists.txt"
"CMakeFiles/3.16.3/CMakeCCompiler.cmake"
"CMakeFiles/3.16.3/CMakeCXXCompiler.cmake"
"CMakeFiles/3.16.3/CMakeSystem.cmake"
"/usr/share/cmake-3.16/Modules/CMakeCInformation.cmake"
"/usr/share/cmake-3.16/Modules/CMakeCXXInformation.cmake"
"/usr/share/cmake-3.16/Modules/CMakeCheckCompilerFlagCommonPatterns.cmake"
"/usr/share/cmake-3.16/Modules/CMakeCommonLanguageInclude.cmake"
"/usr/share/cmake-3.16/Modules/CMakeGenericSystem.cmake"
"/usr/share/cmake-3.16/Modules/CMakeInitializeConfigs.cmake"
"/usr/share/cmake-3.16/Modules/CMakeLanguageInformation.cmake"
"/usr/share/cmake-3.16/Modules/CMakeSystemSpecificInformation.cmake"
"/usr/share/cmake-3.16/Modules/CMakeSystemSpecificInitialize.cmake"
"/usr/share/cmake-3.16/Modules/Compiler/CMakeCommonCompilerMacros.cmake"
"/usr/share/cmake-3.16/Modules/Compiler/GNU-C.cmake"
"/usr/share/cmake-3.16/Modules/Compiler/GNU-CXX.cmake"
"/usr/share/cmake-3.16/Modules/Compiler/GNU.cmake"
"/usr/share/cmake-3.16/Modules/Internal/CMakeCheckCompilerFlag.cmake"
"/usr/share/cmake-3.16/Modules/Platform/Linux-GNU-C.cmake"
"/usr/share/cmake-3.16/Modules/Platform/Linux-GNU-CXX.cmake"
"/usr/share/cmake-3.16/Modules/Platform/Linux-GNU.cmake"
"/usr/share/cmake-3.16/Modules/Platform/Linux.cmake"
"/usr/share/cmake-3.16/Modules/Platform/UnixPaths.cmake"
)
# The corresponding makefile is:
set(CMAKE_MAKEFILE_OUTPUTS
"Makefile"
"CMakeFiles/cmake.check_cache"
)
# Byproducts of CMake generate step:
set(CMAKE_MAKEFILE_PRODUCTS
"CMakeFiles/CMakeDirectoryInformation.cmake"
)
# Dependency information for all targets:
set(CMAKE_DEPEND_INFO_FILES
"CMakeFiles/recipe05_example01.dir/DependInfo.cmake"
"CMakeFiles/recipe01_example01.dir/DependInfo.cmake"
"CMakeFiles/recipe01_example08.dir/DependInfo.cmake"
"CMakeFiles/recipe03_examples.dir/DependInfo.cmake"
"CMakeFiles/recipe01_example07.dir/DependInfo.cmake"
"CMakeFiles/recipe02_examples.dir/DependInfo.cmake"
"CMakeFiles/recipe03_example02.dir/DependInfo.cmake"
"CMakeFiles/recipe01_examples.dir/DependInfo.cmake"
"CMakeFiles/recipe04_examples.dir/DependInfo.cmake"
"CMakeFiles/recipe01_example06.dir/DependInfo.cmake"
"CMakeFiles/recipe01_example09.dir/DependInfo.cmake"
"CMakeFiles/recipe01_example03.dir/DependInfo.cmake"
"CMakeFiles/recipe01_example02.dir/DependInfo.cmake"
"CMakeFiles/recipe03_example03.dir/DependInfo.cmake"
"CMakeFiles/recipe01_example05.dir/DependInfo.cmake"
"CMakeFiles/recipe02_example01.dir/DependInfo.cmake"
"CMakeFiles/recipe02_example02.dir/DependInfo.cmake"
"CMakeFiles/recipe03_example01.dir/DependInfo.cmake"
"CMakeFiles/recipe05_example02.dir/DependInfo.cmake"
"CMakeFiles/recipe01_example04.dir/DependInfo.cmake"
"CMakeFiles/recipe03_example04.dir/DependInfo.cmake"
"CMakeFiles/recipe03_example07.dir/DependInfo.cmake"
"CMakeFiles/recipe03_example05.dir/DependInfo.cmake"
"CMakeFiles/recipe05_examples.dir/DependInfo.cmake"
"CMakeFiles/recipe04_example01.dir/DependInfo.cmake"
"CMakeFiles/recipe03_example06.dir/DependInfo.cmake"
)
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe01_example03.dir/recipe01.cpp.o"
"recipe01_example03"
"recipe01_example03.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe01_example03.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>
CFLAGS_WARNINGS = -ggdb -fno-stack-protector -Wformat-security -std=c99
CFLAGS = -ggdb -fno-stack-protector -std=c99 -Wno-format-security
# With the flags
# -Wformat-security
# -Wno-format-security
# gcc will/will not warn for format string problems
# With
# -Wall
# all warnings are turned on.
SRC=$(wildcard *.c)
OBJS := $(patsubst %.c, %.o, $(SRC))
BINS := $(patsubst %.c, %, $(SRC))
all: $(BINS)
%.o: %.c
gcc $(CFLAGS) -c $< -o $@
safe:
gcc $(CFLAGS_WARNINGS) format_string_attack.c
%: %.c
gcc $(CFLAGS) -o $@ $<
clean:
rm *.o a.out
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe02_example01.dir/recipe02.cpp.o"
"recipe02_example01"
"recipe02_example01.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe02_example01.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h>
main(int argc, char *argv[])
{
FILE *fp;
void filecopy(FILE *, FILE *);
char *prog = argv[0];
if(argc ==1 )
filecopy(stdin, stdout);
else
while(--argc > 0)
if((fp = fopen(*++argv, "r")) == NULL)
{
fprintf(stderr, "cat: cannot open %s\n, *argv");
return 1;
}
else
{
filecopy(fp,stdout);
fclose(fp);
}
if (ferror(stdout)){
fprintf(stderr, "%s: error writing stdout \n", prog);
exit(2);
}
exit(0);
//return 0;
}
void filecopy (FILE *ifp, FILE *ofp)
{
int c;
while ((c=getc(ifp)) != EOF)
putc(c,ofp);
}
<file_sep>#include <stdio.h>
/* Another example to show the effect of a stack overflow.
*
* Note:
*
* - comparing this code with stack_overflow.c shows that
* printing is very slow!
*
* - making the string longer means we run out of memory faster.
*
*/
int counter = 261701;
int main(){
char* test = "testing testing!";
char* test1 = "testing testing!";
char* test2 = "testing testing!";
char* test3 = "testing testing!";
counter--;
printf("Counter now has value %i \n",counter);
main();
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/snippet_c03.dir/scratchpad.c.o"
"snippet_c03"
"snippet_c03.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/snippet_c03.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/snippet_c05.dir/scratchpad.c.o"
"snippet_c05"
"snippet_c05.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/snippet_c05.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>file(REMOVE_RECURSE
"libhayai_main.a"
)
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe04_example01.dir/recipe04.cpp.o"
"recipe04_example01"
"recipe04_example01.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe04_example01.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h>
void test1();
void test2();
void test3();
void testpointers();
void testarrayoverrun();
void pointerillustrate1();
void pointerillustrate2();
void testFuncPtr();
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe02_example03.dir/recipe02.cpp.o"
"recipe02_example03"
"recipe02_example03.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe02_example03.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include <stdio.h>
/* An example to show how gcc optimisations can avoid stack overflow.
*
* This code will segfault, but not when we compile with
* gcc -O2
* as gcc then optimises away the tail recursion
*
*/
int i;
void do_something()
{
i++;
char* string = "let's use up some memory";
// printf("Counter now has value %i \n",i);
}
int main()
{
do_something();
main();
}
<file_sep>// File name: ExtremeC_exampels_chapter1_18.c
// Description: Example 1.18
#include <stdio.h>
void func(int* a) {//it's usually recommanded to use pointers as arguments, 8 bytes(x64 machine, 4 bytes in x86 machine) of a pointer argument is much more efficient than copoying hundreds of bytes of an object.
int b = 9;
*a = 5;// changeing pointer (parameter) 's value is allowed by dereferencing the pointer.
a = &b;//but the pointer's location is never changed, this line of code affects nothing.
}
int main(int argc, char** argv) {
int x = 3;
int* xptr = &x;
printf("Value before call: %d\n", x);
printf("Pointer before function call: %p\n", (void*)xptr);
func(xptr);
printf("Value after call: %d\n", x);
printf("Pointer after function call: %p\n", (void*)xptr);
return 0;
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/recipe04_example02.dir/recipe04.cpp.o"
"recipe04_example02"
"recipe04_example02.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/recipe04_example02.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep># CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.16
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake
# The command to remove a file.
RM = /usr/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter04
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter04/build
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/usr/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
/usr/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available.
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter04/build/CMakeFiles /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter04/build/CMakeFiles/progress.marks
$(MAKE) -f CMakeFiles/Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start /root/Desktop/c/c++/Advanced-CPP-Programming-CookBook/Chapter04/build/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named recipe03_example02
# Build rule for target.
recipe03_example02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe03_example02
.PHONY : recipe03_example02
# fast build rule for target.
recipe03_example02/fast:
$(MAKE) -f CMakeFiles/recipe03_example02.dir/build.make CMakeFiles/recipe03_example02.dir/build
.PHONY : recipe03_example02/fast
#=============================================================================
# Target rules for targets named recipe02_examples
# Build rule for target.
recipe02_examples: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe02_examples
.PHONY : recipe02_examples
# fast build rule for target.
recipe02_examples/fast:
$(MAKE) -f CMakeFiles/recipe02_examples.dir/build.make CMakeFiles/recipe02_examples.dir/build
.PHONY : recipe02_examples/fast
#=============================================================================
# Target rules for targets named recipe05_example01
# Build rule for target.
recipe05_example01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe05_example01
.PHONY : recipe05_example01
# fast build rule for target.
recipe05_example01/fast:
$(MAKE) -f CMakeFiles/recipe05_example01.dir/build.make CMakeFiles/recipe05_example01.dir/build
.PHONY : recipe05_example01/fast
#=============================================================================
# Target rules for targets named recipe01_example05
# Build rule for target.
recipe01_example05: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe01_example05
.PHONY : recipe01_example05
# fast build rule for target.
recipe01_example05/fast:
$(MAKE) -f CMakeFiles/recipe01_example05.dir/build.make CMakeFiles/recipe01_example05.dir/build
.PHONY : recipe01_example05/fast
#=============================================================================
# Target rules for targets named recipe02_example03
# Build rule for target.
recipe02_example03: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe02_example03
.PHONY : recipe02_example03
# fast build rule for target.
recipe02_example03/fast:
$(MAKE) -f CMakeFiles/recipe02_example03.dir/build.make CMakeFiles/recipe02_example03.dir/build
.PHONY : recipe02_example03/fast
#=============================================================================
# Target rules for targets named recipe01_example04
# Build rule for target.
recipe01_example04: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe01_example04
.PHONY : recipe01_example04
# fast build rule for target.
recipe01_example04/fast:
$(MAKE) -f CMakeFiles/recipe01_example04.dir/build.make CMakeFiles/recipe01_example04.dir/build
.PHONY : recipe01_example04/fast
#=============================================================================
# Target rules for targets named recipe02_example02
# Build rule for target.
recipe02_example02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe02_example02
.PHONY : recipe02_example02
# fast build rule for target.
recipe02_example02/fast:
$(MAKE) -f CMakeFiles/recipe02_example02.dir/build.make CMakeFiles/recipe02_example02.dir/build
.PHONY : recipe02_example02/fast
#=============================================================================
# Target rules for targets named recipe06_example01
# Build rule for target.
recipe06_example01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe06_example01
.PHONY : recipe06_example01
# fast build rule for target.
recipe06_example01/fast:
$(MAKE) -f CMakeFiles/recipe06_example01.dir/build.make CMakeFiles/recipe06_example01.dir/build
.PHONY : recipe06_example01/fast
#=============================================================================
# Target rules for targets named recipe01_example03
# Build rule for target.
recipe01_example03: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe01_example03
.PHONY : recipe01_example03
# fast build rule for target.
recipe01_example03/fast:
$(MAKE) -f CMakeFiles/recipe01_example03.dir/build.make CMakeFiles/recipe01_example03.dir/build
.PHONY : recipe01_example03/fast
#=============================================================================
# Target rules for targets named recipe01_example02
# Build rule for target.
recipe01_example02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe01_example02
.PHONY : recipe01_example02
# fast build rule for target.
recipe01_example02/fast:
$(MAKE) -f CMakeFiles/recipe01_example02.dir/build.make CMakeFiles/recipe01_example02.dir/build
.PHONY : recipe01_example02/fast
#=============================================================================
# Target rules for targets named recipe03_example01
# Build rule for target.
recipe03_example01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe03_example01
.PHONY : recipe03_example01
# fast build rule for target.
recipe03_example01/fast:
$(MAKE) -f CMakeFiles/recipe03_example01.dir/build.make CMakeFiles/recipe03_example01.dir/build
.PHONY : recipe03_example01/fast
#=============================================================================
# Target rules for targets named recipe05_example02
# Build rule for target.
recipe05_example02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe05_example02
.PHONY : recipe05_example02
# fast build rule for target.
recipe05_example02/fast:
$(MAKE) -f CMakeFiles/recipe05_example02.dir/build.make CMakeFiles/recipe05_example02.dir/build
.PHONY : recipe05_example02/fast
#=============================================================================
# Target rules for targets named recipe01_example01
# Build rule for target.
recipe01_example01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe01_example01
.PHONY : recipe01_example01
# fast build rule for target.
recipe01_example01/fast:
$(MAKE) -f CMakeFiles/recipe01_example01.dir/build.make CMakeFiles/recipe01_example01.dir/build
.PHONY : recipe01_example01/fast
#=============================================================================
# Target rules for targets named recipe01_examples
# Build rule for target.
recipe01_examples: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe01_examples
.PHONY : recipe01_examples
# fast build rule for target.
recipe01_examples/fast:
$(MAKE) -f CMakeFiles/recipe01_examples.dir/build.make CMakeFiles/recipe01_examples.dir/build
.PHONY : recipe01_examples/fast
#=============================================================================
# Target rules for targets named recipe04_example04
# Build rule for target.
recipe04_example04: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe04_example04
.PHONY : recipe04_example04
# fast build rule for target.
recipe04_example04/fast:
$(MAKE) -f CMakeFiles/recipe04_example04.dir/build.make CMakeFiles/recipe04_example04.dir/build
.PHONY : recipe04_example04/fast
#=============================================================================
# Target rules for targets named recipe06_example03
# Build rule for target.
recipe06_example03: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe06_example03
.PHONY : recipe06_example03
# fast build rule for target.
recipe06_example03/fast:
$(MAKE) -f CMakeFiles/recipe06_example03.dir/build.make CMakeFiles/recipe06_example03.dir/build
.PHONY : recipe06_example03/fast
#=============================================================================
# Target rules for targets named recipe07_example01
# Build rule for target.
recipe07_example01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe07_example01
.PHONY : recipe07_example01
# fast build rule for target.
recipe07_example01/fast:
$(MAKE) -f CMakeFiles/recipe07_example01.dir/build.make CMakeFiles/recipe07_example01.dir/build
.PHONY : recipe07_example01/fast
#=============================================================================
# Target rules for targets named recipe02_example01
# Build rule for target.
recipe02_example01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe02_example01
.PHONY : recipe02_example01
# fast build rule for target.
recipe02_example01/fast:
$(MAKE) -f CMakeFiles/recipe02_example01.dir/build.make CMakeFiles/recipe02_example01.dir/build
.PHONY : recipe02_example01/fast
#=============================================================================
# Target rules for targets named recipe04_examples
# Build rule for target.
recipe04_examples: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe04_examples
.PHONY : recipe04_examples
# fast build rule for target.
recipe04_examples/fast:
$(MAKE) -f CMakeFiles/recipe04_examples.dir/build.make CMakeFiles/recipe04_examples.dir/build
.PHONY : recipe04_examples/fast
#=============================================================================
# Target rules for targets named recipe04_example01
# Build rule for target.
recipe04_example01: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe04_example01
.PHONY : recipe04_example01
# fast build rule for target.
recipe04_example01/fast:
$(MAKE) -f CMakeFiles/recipe04_example01.dir/build.make CMakeFiles/recipe04_example01.dir/build
.PHONY : recipe04_example01/fast
#=============================================================================
# Target rules for targets named recipe04_example02
# Build rule for target.
recipe04_example02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe04_example02
.PHONY : recipe04_example02
# fast build rule for target.
recipe04_example02/fast:
$(MAKE) -f CMakeFiles/recipe04_example02.dir/build.make CMakeFiles/recipe04_example02.dir/build
.PHONY : recipe04_example02/fast
#=============================================================================
# Target rules for targets named recipe04_example05
# Build rule for target.
recipe04_example05: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe04_example05
.PHONY : recipe04_example05
# fast build rule for target.
recipe04_example05/fast:
$(MAKE) -f CMakeFiles/recipe04_example05.dir/build.make CMakeFiles/recipe04_example05.dir/build
.PHONY : recipe04_example05/fast
#=============================================================================
# Target rules for targets named recipe04_example03
# Build rule for target.
recipe04_example03: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe04_example03
.PHONY : recipe04_example03
# fast build rule for target.
recipe04_example03/fast:
$(MAKE) -f CMakeFiles/recipe04_example03.dir/build.make CMakeFiles/recipe04_example03.dir/build
.PHONY : recipe04_example03/fast
#=============================================================================
# Target rules for targets named recipe05_examples
# Build rule for target.
recipe05_examples: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe05_examples
.PHONY : recipe05_examples
# fast build rule for target.
recipe05_examples/fast:
$(MAKE) -f CMakeFiles/recipe05_examples.dir/build.make CMakeFiles/recipe05_examples.dir/build
.PHONY : recipe05_examples/fast
#=============================================================================
# Target rules for targets named recipe06_examples
# Build rule for target.
recipe06_examples: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe06_examples
.PHONY : recipe06_examples
# fast build rule for target.
recipe06_examples/fast:
$(MAKE) -f CMakeFiles/recipe06_examples.dir/build.make CMakeFiles/recipe06_examples.dir/build
.PHONY : recipe06_examples/fast
#=============================================================================
# Target rules for targets named recipe06_example02
# Build rule for target.
recipe06_example02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe06_example02
.PHONY : recipe06_example02
# fast build rule for target.
recipe06_example02/fast:
$(MAKE) -f CMakeFiles/recipe06_example02.dir/build.make CMakeFiles/recipe06_example02.dir/build
.PHONY : recipe06_example02/fast
#=============================================================================
# Target rules for targets named recipe07_examples
# Build rule for target.
recipe07_examples: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe07_examples
.PHONY : recipe07_examples
# fast build rule for target.
recipe07_examples/fast:
$(MAKE) -f CMakeFiles/recipe07_examples.dir/build.make CMakeFiles/recipe07_examples.dir/build
.PHONY : recipe07_examples/fast
#=============================================================================
# Target rules for targets named recipe03_examples
# Build rule for target.
recipe03_examples: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe03_examples
.PHONY : recipe03_examples
# fast build rule for target.
recipe03_examples/fast:
$(MAKE) -f CMakeFiles/recipe03_examples.dir/build.make CMakeFiles/recipe03_examples.dir/build
.PHONY : recipe03_examples/fast
#=============================================================================
# Target rules for targets named recipe07_example02
# Build rule for target.
recipe07_example02: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 recipe07_example02
.PHONY : recipe07_example02
# fast build rule for target.
recipe07_example02/fast:
$(MAKE) -f CMakeFiles/recipe07_example02.dir/build.make CMakeFiles/recipe07_example02.dir/build
.PHONY : recipe07_example02/fast
recipe01.o: recipe01.cpp.o
.PHONY : recipe01.o
# target to build an object file
recipe01.cpp.o:
$(MAKE) -f CMakeFiles/recipe01_example05.dir/build.make CMakeFiles/recipe01_example05.dir/recipe01.cpp.o
$(MAKE) -f CMakeFiles/recipe01_example04.dir/build.make CMakeFiles/recipe01_example04.dir/recipe01.cpp.o
$(MAKE) -f CMakeFiles/recipe01_example03.dir/build.make CMakeFiles/recipe01_example03.dir/recipe01.cpp.o
$(MAKE) -f CMakeFiles/recipe01_example02.dir/build.make CMakeFiles/recipe01_example02.dir/recipe01.cpp.o
$(MAKE) -f CMakeFiles/recipe01_example01.dir/build.make CMakeFiles/recipe01_example01.dir/recipe01.cpp.o
.PHONY : recipe01.cpp.o
recipe01.i: recipe01.cpp.i
.PHONY : recipe01.i
# target to preprocess a source file
recipe01.cpp.i:
$(MAKE) -f CMakeFiles/recipe01_example05.dir/build.make CMakeFiles/recipe01_example05.dir/recipe01.cpp.i
$(MAKE) -f CMakeFiles/recipe01_example04.dir/build.make CMakeFiles/recipe01_example04.dir/recipe01.cpp.i
$(MAKE) -f CMakeFiles/recipe01_example03.dir/build.make CMakeFiles/recipe01_example03.dir/recipe01.cpp.i
$(MAKE) -f CMakeFiles/recipe01_example02.dir/build.make CMakeFiles/recipe01_example02.dir/recipe01.cpp.i
$(MAKE) -f CMakeFiles/recipe01_example01.dir/build.make CMakeFiles/recipe01_example01.dir/recipe01.cpp.i
.PHONY : recipe01.cpp.i
recipe01.s: recipe01.cpp.s
.PHONY : recipe01.s
# target to generate assembly for a file
recipe01.cpp.s:
$(MAKE) -f CMakeFiles/recipe01_example05.dir/build.make CMakeFiles/recipe01_example05.dir/recipe01.cpp.s
$(MAKE) -f CMakeFiles/recipe01_example04.dir/build.make CMakeFiles/recipe01_example04.dir/recipe01.cpp.s
$(MAKE) -f CMakeFiles/recipe01_example03.dir/build.make CMakeFiles/recipe01_example03.dir/recipe01.cpp.s
$(MAKE) -f CMakeFiles/recipe01_example02.dir/build.make CMakeFiles/recipe01_example02.dir/recipe01.cpp.s
$(MAKE) -f CMakeFiles/recipe01_example01.dir/build.make CMakeFiles/recipe01_example01.dir/recipe01.cpp.s
.PHONY : recipe01.cpp.s
recipe02.o: recipe02.cpp.o
.PHONY : recipe02.o
# target to build an object file
recipe02.cpp.o:
$(MAKE) -f CMakeFiles/recipe02_example03.dir/build.make CMakeFiles/recipe02_example03.dir/recipe02.cpp.o
$(MAKE) -f CMakeFiles/recipe02_example02.dir/build.make CMakeFiles/recipe02_example02.dir/recipe02.cpp.o
$(MAKE) -f CMakeFiles/recipe02_example01.dir/build.make CMakeFiles/recipe02_example01.dir/recipe02.cpp.o
.PHONY : recipe02.cpp.o
recipe02.i: recipe02.cpp.i
.PHONY : recipe02.i
# target to preprocess a source file
recipe02.cpp.i:
$(MAKE) -f CMakeFiles/recipe02_example03.dir/build.make CMakeFiles/recipe02_example03.dir/recipe02.cpp.i
$(MAKE) -f CMakeFiles/recipe02_example02.dir/build.make CMakeFiles/recipe02_example02.dir/recipe02.cpp.i
$(MAKE) -f CMakeFiles/recipe02_example01.dir/build.make CMakeFiles/recipe02_example01.dir/recipe02.cpp.i
.PHONY : recipe02.cpp.i
recipe02.s: recipe02.cpp.s
.PHONY : recipe02.s
# target to generate assembly for a file
recipe02.cpp.s:
$(MAKE) -f CMakeFiles/recipe02_example03.dir/build.make CMakeFiles/recipe02_example03.dir/recipe02.cpp.s
$(MAKE) -f CMakeFiles/recipe02_example02.dir/build.make CMakeFiles/recipe02_example02.dir/recipe02.cpp.s
$(MAKE) -f CMakeFiles/recipe02_example01.dir/build.make CMakeFiles/recipe02_example01.dir/recipe02.cpp.s
.PHONY : recipe02.cpp.s
recipe03.o: recipe03.cpp.o
.PHONY : recipe03.o
# target to build an object file
recipe03.cpp.o:
$(MAKE) -f CMakeFiles/recipe03_example02.dir/build.make CMakeFiles/recipe03_example02.dir/recipe03.cpp.o
$(MAKE) -f CMakeFiles/recipe03_example01.dir/build.make CMakeFiles/recipe03_example01.dir/recipe03.cpp.o
.PHONY : recipe03.cpp.o
recipe03.i: recipe03.cpp.i
.PHONY : recipe03.i
# target to preprocess a source file
recipe03.cpp.i:
$(MAKE) -f CMakeFiles/recipe03_example02.dir/build.make CMakeFiles/recipe03_example02.dir/recipe03.cpp.i
$(MAKE) -f CMakeFiles/recipe03_example01.dir/build.make CMakeFiles/recipe03_example01.dir/recipe03.cpp.i
.PHONY : recipe03.cpp.i
recipe03.s: recipe03.cpp.s
.PHONY : recipe03.s
# target to generate assembly for a file
recipe03.cpp.s:
$(MAKE) -f CMakeFiles/recipe03_example02.dir/build.make CMakeFiles/recipe03_example02.dir/recipe03.cpp.s
$(MAKE) -f CMakeFiles/recipe03_example01.dir/build.make CMakeFiles/recipe03_example01.dir/recipe03.cpp.s
.PHONY : recipe03.cpp.s
recipe04.o: recipe04.cpp.o
.PHONY : recipe04.o
# target to build an object file
recipe04.cpp.o:
$(MAKE) -f CMakeFiles/recipe04_example04.dir/build.make CMakeFiles/recipe04_example04.dir/recipe04.cpp.o
$(MAKE) -f CMakeFiles/recipe04_example01.dir/build.make CMakeFiles/recipe04_example01.dir/recipe04.cpp.o
$(MAKE) -f CMakeFiles/recipe04_example02.dir/build.make CMakeFiles/recipe04_example02.dir/recipe04.cpp.o
$(MAKE) -f CMakeFiles/recipe04_example05.dir/build.make CMakeFiles/recipe04_example05.dir/recipe04.cpp.o
$(MAKE) -f CMakeFiles/recipe04_example03.dir/build.make CMakeFiles/recipe04_example03.dir/recipe04.cpp.o
.PHONY : recipe04.cpp.o
recipe04.i: recipe04.cpp.i
.PHONY : recipe04.i
# target to preprocess a source file
recipe04.cpp.i:
$(MAKE) -f CMakeFiles/recipe04_example04.dir/build.make CMakeFiles/recipe04_example04.dir/recipe04.cpp.i
$(MAKE) -f CMakeFiles/recipe04_example01.dir/build.make CMakeFiles/recipe04_example01.dir/recipe04.cpp.i
$(MAKE) -f CMakeFiles/recipe04_example02.dir/build.make CMakeFiles/recipe04_example02.dir/recipe04.cpp.i
$(MAKE) -f CMakeFiles/recipe04_example05.dir/build.make CMakeFiles/recipe04_example05.dir/recipe04.cpp.i
$(MAKE) -f CMakeFiles/recipe04_example03.dir/build.make CMakeFiles/recipe04_example03.dir/recipe04.cpp.i
.PHONY : recipe04.cpp.i
recipe04.s: recipe04.cpp.s
.PHONY : recipe04.s
# target to generate assembly for a file
recipe04.cpp.s:
$(MAKE) -f CMakeFiles/recipe04_example04.dir/build.make CMakeFiles/recipe04_example04.dir/recipe04.cpp.s
$(MAKE) -f CMakeFiles/recipe04_example01.dir/build.make CMakeFiles/recipe04_example01.dir/recipe04.cpp.s
$(MAKE) -f CMakeFiles/recipe04_example02.dir/build.make CMakeFiles/recipe04_example02.dir/recipe04.cpp.s
$(MAKE) -f CMakeFiles/recipe04_example05.dir/build.make CMakeFiles/recipe04_example05.dir/recipe04.cpp.s
$(MAKE) -f CMakeFiles/recipe04_example03.dir/build.make CMakeFiles/recipe04_example03.dir/recipe04.cpp.s
.PHONY : recipe04.cpp.s
recipe05.o: recipe05.cpp.o
.PHONY : recipe05.o
# target to build an object file
recipe05.cpp.o:
$(MAKE) -f CMakeFiles/recipe05_example01.dir/build.make CMakeFiles/recipe05_example01.dir/recipe05.cpp.o
$(MAKE) -f CMakeFiles/recipe05_example02.dir/build.make CMakeFiles/recipe05_example02.dir/recipe05.cpp.o
.PHONY : recipe05.cpp.o
recipe05.i: recipe05.cpp.i
.PHONY : recipe05.i
# target to preprocess a source file
recipe05.cpp.i:
$(MAKE) -f CMakeFiles/recipe05_example01.dir/build.make CMakeFiles/recipe05_example01.dir/recipe05.cpp.i
$(MAKE) -f CMakeFiles/recipe05_example02.dir/build.make CMakeFiles/recipe05_example02.dir/recipe05.cpp.i
.PHONY : recipe05.cpp.i
recipe05.s: recipe05.cpp.s
.PHONY : recipe05.s
# target to generate assembly for a file
recipe05.cpp.s:
$(MAKE) -f CMakeFiles/recipe05_example01.dir/build.make CMakeFiles/recipe05_example01.dir/recipe05.cpp.s
$(MAKE) -f CMakeFiles/recipe05_example02.dir/build.make CMakeFiles/recipe05_example02.dir/recipe05.cpp.s
.PHONY : recipe05.cpp.s
recipe06.o: recipe06.cpp.o
.PHONY : recipe06.o
# target to build an object file
recipe06.cpp.o:
$(MAKE) -f CMakeFiles/recipe06_example01.dir/build.make CMakeFiles/recipe06_example01.dir/recipe06.cpp.o
$(MAKE) -f CMakeFiles/recipe06_example03.dir/build.make CMakeFiles/recipe06_example03.dir/recipe06.cpp.o
$(MAKE) -f CMakeFiles/recipe06_example02.dir/build.make CMakeFiles/recipe06_example02.dir/recipe06.cpp.o
.PHONY : recipe06.cpp.o
recipe06.i: recipe06.cpp.i
.PHONY : recipe06.i
# target to preprocess a source file
recipe06.cpp.i:
$(MAKE) -f CMakeFiles/recipe06_example01.dir/build.make CMakeFiles/recipe06_example01.dir/recipe06.cpp.i
$(MAKE) -f CMakeFiles/recipe06_example03.dir/build.make CMakeFiles/recipe06_example03.dir/recipe06.cpp.i
$(MAKE) -f CMakeFiles/recipe06_example02.dir/build.make CMakeFiles/recipe06_example02.dir/recipe06.cpp.i
.PHONY : recipe06.cpp.i
recipe06.s: recipe06.cpp.s
.PHONY : recipe06.s
# target to generate assembly for a file
recipe06.cpp.s:
$(MAKE) -f CMakeFiles/recipe06_example01.dir/build.make CMakeFiles/recipe06_example01.dir/recipe06.cpp.s
$(MAKE) -f CMakeFiles/recipe06_example03.dir/build.make CMakeFiles/recipe06_example03.dir/recipe06.cpp.s
$(MAKE) -f CMakeFiles/recipe06_example02.dir/build.make CMakeFiles/recipe06_example02.dir/recipe06.cpp.s
.PHONY : recipe06.cpp.s
recipe07.o: recipe07.cpp.o
.PHONY : recipe07.o
# target to build an object file
recipe07.cpp.o:
$(MAKE) -f CMakeFiles/recipe07_example01.dir/build.make CMakeFiles/recipe07_example01.dir/recipe07.cpp.o
$(MAKE) -f CMakeFiles/recipe07_example02.dir/build.make CMakeFiles/recipe07_example02.dir/recipe07.cpp.o
.PHONY : recipe07.cpp.o
recipe07.i: recipe07.cpp.i
.PHONY : recipe07.i
# target to preprocess a source file
recipe07.cpp.i:
$(MAKE) -f CMakeFiles/recipe07_example01.dir/build.make CMakeFiles/recipe07_example01.dir/recipe07.cpp.i
$(MAKE) -f CMakeFiles/recipe07_example02.dir/build.make CMakeFiles/recipe07_example02.dir/recipe07.cpp.i
.PHONY : recipe07.cpp.i
recipe07.s: recipe07.cpp.s
.PHONY : recipe07.s
# target to generate assembly for a file
recipe07.cpp.s:
$(MAKE) -f CMakeFiles/recipe07_example01.dir/build.make CMakeFiles/recipe07_example01.dir/recipe07.cpp.s
$(MAKE) -f CMakeFiles/recipe07_example02.dir/build.make CMakeFiles/recipe07_example02.dir/recipe07.cpp.s
.PHONY : recipe07.cpp.s
recipe07_helper.o: recipe07_helper.cpp.o
.PHONY : recipe07_helper.o
# target to build an object file
recipe07_helper.cpp.o:
$(MAKE) -f CMakeFiles/recipe07_example02.dir/build.make CMakeFiles/recipe07_example02.dir/recipe07_helper.cpp.o
.PHONY : recipe07_helper.cpp.o
recipe07_helper.i: recipe07_helper.cpp.i
.PHONY : recipe07_helper.i
# target to preprocess a source file
recipe07_helper.cpp.i:
$(MAKE) -f CMakeFiles/recipe07_example02.dir/build.make CMakeFiles/recipe07_example02.dir/recipe07_helper.cpp.i
.PHONY : recipe07_helper.cpp.i
recipe07_helper.s: recipe07_helper.cpp.s
.PHONY : recipe07_helper.s
# target to generate assembly for a file
recipe07_helper.cpp.s:
$(MAKE) -f CMakeFiles/recipe07_example02.dir/build.make CMakeFiles/recipe07_example02.dir/recipe07_helper.cpp.s
.PHONY : recipe07_helper.cpp.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... rebuild_cache"
@echo "... edit_cache"
@echo "... recipe03_example02"
@echo "... recipe02_examples"
@echo "... recipe05_example01"
@echo "... recipe01_example05"
@echo "... recipe02_example03"
@echo "... recipe01_example04"
@echo "... recipe02_example02"
@echo "... recipe06_example01"
@echo "... recipe01_example03"
@echo "... recipe01_example02"
@echo "... recipe03_example01"
@echo "... recipe05_example02"
@echo "... recipe01_example01"
@echo "... recipe01_examples"
@echo "... recipe04_example04"
@echo "... recipe06_example03"
@echo "... recipe07_example01"
@echo "... recipe02_example01"
@echo "... recipe04_examples"
@echo "... recipe04_example01"
@echo "... recipe04_example02"
@echo "... recipe04_example05"
@echo "... recipe04_example03"
@echo "... recipe05_examples"
@echo "... recipe06_examples"
@echo "... recipe06_example02"
@echo "... recipe07_examples"
@echo "... recipe03_examples"
@echo "... recipe07_example02"
@echo "... recipe01.o"
@echo "... recipe01.i"
@echo "... recipe01.s"
@echo "... recipe02.o"
@echo "... recipe02.i"
@echo "... recipe02.s"
@echo "... recipe03.o"
@echo "... recipe03.i"
@echo "... recipe03.s"
@echo "... recipe04.o"
@echo "... recipe04.i"
@echo "... recipe04.s"
@echo "... recipe05.o"
@echo "... recipe05.i"
@echo "... recipe05.s"
@echo "... recipe06.o"
@echo "... recipe06.i"
@echo "... recipe06.s"
@echo "... recipe07.o"
@echo "... recipe07.i"
@echo "... recipe07.s"
@echo "... recipe07_helper.o"
@echo "... recipe07_helper.i"
@echo "... recipe07_helper.s"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
| f4cc687353e543c5fe302d48e4521ebe86a9ae6c | [
"CMake",
"Makefile",
"C",
"C++",
"Shell"
]
| 110 | CMake | YanyangChen/C_practice | e9b4a19e35738110bc6bc44aac5063839fdae200 | f6ac2439a03556edc558a4cc3e6cd1abc6bda1a2 |
refs/heads/master | <repo_name>huguesto/rails-stupid-coaching<file_sep>/app/controllers/questions_controller_controller.rb
class QuestionsControllerController < ApplicationController
def answer
@response = params[:response]
if @response == "fuck"
@answer = "parles moi mieux."
else
@answer = "Silly question son..."
end
end
def ask
end
end
| c788e097cc0d95a9b4d955516360d3dc704a81e3 | [
"Ruby"
]
| 1 | Ruby | huguesto/rails-stupid-coaching | ed61b6905bc560d34700e08119f4df8be9cd7226 | 9b41821aade000c3cdc330798da4aa87f06bdd31 |
refs/heads/master | <file_sep>import axios from 'axios'
const api = axios.create({
baseURL: 'http://127.0.0.1:5000',
//baseURL: 'http://earthr.herokuapp.com:33507',
})
export const getAllFoods = () => api.get(`/foods`)
export default getAllFoods;
<file_sep># earthr
https://earthr.herokuapp.com/
### What is Earthr?
We are an innovative lifestyle oriented technology provider that aims to raise awareness about the inherent sustainability issues within the food production process.
### Our Stack:
* Backend: Flask
* Frontend: NodeJS, React
* DB: MongoDB Atlas
* Deployment: Heroku
<file_sep>import React,{Component} from 'react';
import logo from './logo.svg';
import './App.css';
import getAllFoods from './api/api.js'
import Autocomplete from './Autocomplete'
import { BrowserRouter as Router, Switch,Route} from 'react-router-dom'
import FoodResult from './FoodResult'
class Home extends Component {
constructor(props) {
super(props)
this.state = {
foods:{
data:[]
}
}
}
componentDidMount = async () => {
getAllFoods().then(foods => {
this.setState({
foods: foods.data,
})
console.log("hi")
console.log(this.state.foods)
})
}
render (){
return(
<div>
<Autocomplete
options={this.state.foods.data}
/>
</div>
)
}
}
export default Home;
<file_sep>import React, { Component } from 'react'
class FoodResult extends Component {
render() {
const {data} = this.props.location.state
return (
<div>
<p>this food {data['product_name']}, also known as {data['generic_name']}, is served in the quantity of {data['serving_size']} per serving.
the quantiy of this food comes in {data['quantity']} per packaging and the consumption of this product outputs a total carbon-footprint,
including everything from production to distribution of the product, is {data['carbon-footprint_100g']} </p>
</div>
)
}
}
export default FoodResult
| 57e51fcbfed4bdacc352877eaddc2b28a7f1d890 | [
"JavaScript",
"Markdown"
]
| 4 | JavaScript | atykwonderland/earthr | c4c1bfb790b661bbca49f3bc8c75f86feb07931a | 14533d6bf94c13e62249d52909ee4f0535089ee5 |
refs/heads/master | <file_sep># Netology-ajs-15-hm4_3Mocking
[](https://ci.appveyor.com/project/Ekaterina-Bogdanova/netology-ajs-15-hm4-3mocking)
<file_sep>import getLevel from '../app';
import fetchData from '../http';
jest.mock('../http');
// Обнуляем mock' перед каждым вызовом ф-ии, тогда тесты не будут зависеть друг от друга
beforeEach(() => {
jest.resetAllMocks();
});
test('test getLevel 1', () => {
fetchData.mockReturnValue({ status: 'ok', level: 10 });
getLevel(54);
expect(fetchData).toBeCalledTimes(1); // проверяет, что функция была вызвана 1 раз
expect(fetchData).toBeCalledWith('https://server/user/54'); // проверяет, верно ли используется переданный аргумент
});
test('test getLevel 2', () => {
fetchData.mockReturnValue({ status: 'badly', level: 0 });
getLevel(20);
expect(fetchData).toBeCalledTimes(1); // проверяет, что функция была вызвана 1 раз
expect(fetchData).toBeCalledWith('https://server/user/20'); // проверяет, верно ли используется переданный аргумент
});
| 3f20f56371f0dc183fa50a4ccc04567b75c89d9a | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | Ekaterina-Bogdanova/Netology-ajs-15-hm4_3Mocking | 905f1e945ec909b3e639799d5ffedc1bcdde4d8d | e75c8f61ca0247a4d89076daa8b3556df898c9dc |
refs/heads/master | <repo_name>DiamondSheep/JetsonGPIO<file_sep>/build/makefile
# Copyright (c) 2012-2017 <NAME> <EMAIL>.
# Copyright (c) 2019, NVIDIA CORPORATION.
# Copyright (c) 2019 <NAME>(pjueon) <EMAIL>.
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
AR = ar
RANLIB = ranlib
LIB_NAME = JetsonGPIO
LIB_FULL_NAME = lib$(LIB_NAME).a
SRC_DIR = ../src
INCLUDE_DIR = ../include
LIB_SRCS = JetsonGPIO.cpp PythonFunctions.cpp gpio_pin_data.cpp gpio_event.cpp
LIB_HEADERS = $(INCLUDE_DIR)/$(LIB_NAME).h $(INCLUDE_DIR)/private/PythonFunctions.h $(INCLUDE_DIR)/private/gpio_pin_data.h $(INCLUDE_DIR)/private/gpio_event.h
LIB_OBJS = $(LIB_NAME).o PythonFunctions.o gpio_pin_data.o gpio_event.o
TEST_SRC = test.cpp
INCLUDE_FLAG = -I$(INCLUDE_DIR)
LIBS_FLAG = -l$(LIB_NAME)
ifeq ($(PREFIX),)
PREFIX := /usr/local
endif
all : $(LIB_OBJS)
$(AR) rcv $(LIB_FULL_NAME) $(LIB_OBJS)
$(RANLIB) $(LIB_FULL_NAME)
$(LIB_NAME).o : $(SRC_DIR)/$(LIB_NAME).cpp $(LIB_HEADERS)
g++ $(INCLUDE_FLAG) -c -o $@ $(SRC_DIR)/$(LIB_NAME).cpp
PythonFunctions.o : $(SRC_DIR)/PythonFunctions.cpp $(INCLUDE_DIR)/private/PythonFunctions.h
g++ $(INCLUDE_FLAG) -c -o $@ $(SRC_DIR)/PythonFunctions.cpp
gpio_pin_data.o : $(SRC_DIR)/gpio_pin_data.cpp $(LIB_HEADERS)
g++ $(INCLUDE_FLAG) -c -o $@ $(SRC_DIR)/gpio_pin_data.cpp
gpio_event.o : $(SRC_DIR)/gpio_event.cpp $(LIB_HEADERS)
g++ $(INCLUDE_FLAG) -I -lpthread -c -o $@ $(SRC_DIR)/gpio_event.cpp
install : $(LIB_FULL_NAME)
install -m 644 $(LIB_FULL_NAME) $(PREFIX)/lib/
install -m 644 $(INCLUDE_DIR)/$(LIB_NAME).h $(PREFIX)/include/
uninstall :
rm -rf $(PREFIX)/lib/$(LIB_FULL_NAME)
rm -rf $(PREFIX)/include/$(LIB_NAME).h
test : $(SRC_DIR)/$(TEST_SRC)
g++ -o $@ $(SRC_DIR)/$(TEST_SRC) $(LIBS_FLAG) -lpthread
clean :
rm -rf *.o
rm -rf *.a
<file_sep>/include/private/gpio_pin_data.h
/*
Copyright (c) 2012-2017 <NAME> <EMAIL>.
Copyright (c) 2019, NVIDIA CORPORATION.
Copyright (c) 2019 <NAME>(pjueon) <EMAIL>.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#pragma once
#ifndef GPIO_PIN_DATA_H
#define GPIO_PIN_DATA_H
#include <string>
#include <map>
#include <vector>
#include "JetsonGPIO.h"
#include "private/Model.h"
struct PinDefinition
{
const int LinuxPin; // Linux GPIO pin number
const std::string SysfsDir; // GPIO chip sysfs directory
const std::string BoardPin; // Pin number (BOARD mode)
const std::string BCMPin; // Pin number (BCM mode)
const std::string CVMPin; // Pin name (CVM mode)
const std::string TEGRAPin; // Pin name (TEGRA_SOC mode)
const std::string PWMSysfsDir; // PWM chip sysfs directory
const int PWMID; // PWM ID within PWM chip
std::string PinName(GPIO::NumberingModes key) const
{
if (key == GPIO::BOARD)
return BoardPin;
else if (key == GPIO::BCM)
return BCMPin;
else if (key == GPIO::CVM)
return CVMPin;
else // TEGRA_SOC
return TEGRAPin;
}
};
struct PinInfo
{
const int P1_REVISION;
const std::string RAM;
const std::string REVISION;
const std::string TYPE;
const std::string MANUFACTURER;
const std::string PROCESSOR;
};
struct ChannelInfo
{
const std::string channel;
const std::string gpio_chip_dir;
const int chip_gpio;
const int gpio;
const std::string pwm_chip_dir;
const int pwm_id;
ChannelInfo(const std::string &channel, const std::string &gpio_chip_dir,
int chip_gpio, int gpio, const std::string &pwm_chip_dir,
int pwm_id)
: channel(channel),
gpio_chip_dir(gpio_chip_dir),
chip_gpio(chip_gpio),
gpio(gpio),
pwm_chip_dir(pwm_chip_dir),
pwm_id(pwm_id)
{}
};
struct PinData
{
Model model;
PinInfo pin_info;
std::map<GPIO::NumberingModes, std::map<std::string, ChannelInfo>> channel_data;
};
PinData get_data();
#endif // GPIO_PIN_DATA_H
<file_sep>/src/JetsonGPIO.cpp
/*
Copyright (c) 2012-2017 <NAME> <EMAIL>.
Copyright (c) 2019, NVIDIA CORPORATION.
Copyright (c) 2019 <NAME>(pjueon) <EMAIL>.
Copyright (c) 2021 <NAME> <EMAIL>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <dirent.h>
#include <unistd.h>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include "JetsonGPIO.h"
#include "private/Model.h"
#include "private/PythonFunctions.h"
#include "private/gpio_event.h"
#include "private/gpio_pin_data.h"
using namespace GPIO;
using namespace std;
// The user CAN'T use GPIO::UNKNOW, GPIO::HARD_PWM
// These are only for implementation
constexpr Directions UNKNOWN = Directions::UNKNOWN;
constexpr Directions HARD_PWM = Directions::HARD_PWM;
//================================================================================
// All global variables are wrapped in a singleton class except for public APIs,
// in order to avoid initialization order problem among global variables in
// different compilation units.
class GlobalVariableWrapper
{
public:
// -----Global Variables----
// NOTE: DON'T change the declaration order of fields.
// declaration order == initialization order
PinData _pinData;
const Model _model;
const PinInfo _JETSON_INFO;
const map<GPIO::NumberingModes, map<string, ChannelInfo>> _channel_data_by_mode;
// A map used as lookup tables for pin to linux gpio mapping
map<string, ChannelInfo> _channel_data;
bool _gpio_warnings;
NumberingModes _gpio_mode;
map<string, Directions> _channel_configuration;
GlobalVariableWrapper(const GlobalVariableWrapper&) = delete;
GlobalVariableWrapper& operator=(const GlobalVariableWrapper&) = delete;
static GlobalVariableWrapper& get_instance()
{
static GlobalVariableWrapper singleton{};
return singleton;
}
static string get_model()
{
auto& instance = get_instance();
auto ret = ModelToString(instance._model);
if (is_None(ret))
throw runtime_error("get_model error");
return ret;
}
static string get_JETSON_INFO()
{
auto& instance = GlobalVariableWrapper::get_instance();
stringstream ss{};
ss << "[JETSON_INFO]\n";
ss << "P1_REVISION: " << instance._JETSON_INFO.P1_REVISION << endl;
ss << "RAM: " << instance._JETSON_INFO.RAM << endl;
ss << "REVISION: " << instance._JETSON_INFO.REVISION << endl;
ss << "TYPE: " << instance._JETSON_INFO.TYPE << endl;
ss << "MANUFACTURER: " << instance._JETSON_INFO.MANUFACTURER << endl;
ss << "PROCESSOR: " << instance._JETSON_INFO.PROCESSOR << endl;
return ss.str();
}
private:
GlobalVariableWrapper()
: _pinData(get_data()), // Get GPIO pin data
_model(_pinData.model),
_JETSON_INFO(_pinData.pin_info),
_channel_data_by_mode(_pinData.channel_data),
_gpio_warnings(true),
_gpio_mode(NumberingModes::None)
{
_CheckPermission();
}
void _CheckPermission()
{
string path1 = _SYSFS_ROOT + "/export"s;
string path2 = _SYSFS_ROOT + "/unexport"s;
if (!os_access(path1, W_OK) || !os_access(path2, W_OK)) {
cerr << "[ERROR] The current user does not have permissions set to access the library functionalites. "
"Please configure permissions or use the root user to run this."
<< endl;
throw runtime_error("Permission Denied.");
}
}
};
//================================================================================
auto& global = GlobalVariableWrapper::get_instance();
//================================================================================
void _validate_mode_set()
{
if (global._gpio_mode == NumberingModes::None)
throw runtime_error("Please set pin numbering mode using "
"GPIO::setmode(GPIO::BOARD), GPIO::setmode(GPIO::BCM), GPIO::setmode(GPIO::TEGRA_SOC) or "
"GPIO::setmode(GPIO::CVM)");
}
ChannelInfo _channel_to_info_lookup(const string& channel, bool need_gpio, bool need_pwm)
{
if (!is_in(channel, global._channel_data))
throw runtime_error("Channel " + channel + " is invalid");
ChannelInfo ch_info = global._channel_data.at(channel);
if (need_gpio && is_None(ch_info.gpio_chip_dir))
throw runtime_error("Channel " + channel + " is not a GPIO");
if (need_pwm && is_None(ch_info.pwm_chip_dir))
throw runtime_error("Channel " + channel + " is not a PWM");
return ch_info;
}
ChannelInfo _channel_to_info(const string& channel, bool need_gpio = false, bool need_pwm = false)
{
_validate_mode_set();
return _channel_to_info_lookup(channel, need_gpio, need_pwm);
}
vector<ChannelInfo> _channels_to_infos(const vector<string>& channels, bool need_gpio = false, bool need_pwm = false)
{
_validate_mode_set();
vector<ChannelInfo> ch_infos{};
for (const auto& c : channels) {
ch_infos.push_back(_channel_to_info_lookup(c, need_gpio, need_pwm));
}
return ch_infos;
}
/* Return the current configuration of a channel as reported by sysfs.
Any of IN, OUT, HARD_PWM, or UNKNOWN may be returned. */
Directions _sysfs_channel_configuration(const ChannelInfo& ch_info)
{
if (!is_None(ch_info.pwm_chip_dir)) {
string pwm_dir = ch_info.pwm_chip_dir + "/pwm" + to_string(ch_info.pwm_id);
if (os_path_exists(pwm_dir))
return HARD_PWM;
}
string gpio_dir = _SYSFS_ROOT + "/gpio"s + to_string(ch_info.gpio);
if (!os_path_exists(gpio_dir))
return UNKNOWN; // Originally returns None in NVIDIA's GPIO Python Library
string gpio_direction;
{ // scope for f
ifstream f_direction(gpio_dir + "/direction");
stringstream buffer{};
buffer << f_direction.rdbuf();
gpio_direction = buffer.str();
gpio_direction = strip(gpio_direction);
// lower()
transform(gpio_direction.begin(), gpio_direction.end(), gpio_direction.begin(),
[](unsigned char c) { return tolower(c); });
} // scope ends
if (gpio_direction == "in")
return IN;
else if (gpio_direction == "out")
return OUT;
else
return UNKNOWN; // Originally returns None in NVIDIA's GPIO Python Library
}
/* Return the current configuration of a channel as requested by this
module in this process. Any of IN, OUT, or UNKNOWN may be returned. */
Directions _app_channel_configuration(const ChannelInfo& ch_info)
{
if (!is_in(ch_info.channel, global._channel_configuration))
return UNKNOWN; // Originally returns None in NVIDIA's GPIO Python Library
return global._channel_configuration[ch_info.channel];
}
void _export_gpio(const int gpio)
{
if (os_path_exists(_SYSFS_ROOT + "/gpio"s + to_string(gpio)))
return;
{ // scope for f_export
ofstream f_export(_SYSFS_ROOT + "/export"s);
f_export << gpio;
} // scope ends
string value_path = _SYSFS_ROOT + "/gpio"s + to_string(gpio) + "/value"s;
int time_count = 0;
while (!os_access(value_path, R_OK | W_OK)) {
this_thread::sleep_for(chrono::milliseconds(10));
if (time_count++ > 100)
throw runtime_error("Permission denied: path: " + value_path +
"\n Please configure permissions or use the root user to run this.");
}
}
void _unexport_gpio(const int gpio)
{
if (!os_path_exists(_SYSFS_ROOT + "/gpio"s + to_string(gpio)))
return;
ofstream f_unexport(_SYSFS_ROOT + "/unexport"s);
f_unexport << gpio;
}
void _output_one(const string gpio, const int value)
{
ofstream value_file(_SYSFS_ROOT + "/gpio"s + gpio + "/value"s);
value_file << int(bool(value));
}
void _output_one(const int gpio, const int value) { _output_one(to_string(gpio), value); }
void _setup_single_out(const ChannelInfo& ch_info, int initial = -1)
{
_export_gpio(ch_info.gpio);
string gpio_dir_path = _SYSFS_ROOT + "/gpio"s + to_string(ch_info.gpio) + "/direction"s;
{ // scope for direction_file
ofstream direction_file(gpio_dir_path);
direction_file << "out";
} // scope ends
if (initial != -1)
_output_one(ch_info.gpio, initial);
global._channel_configuration[ch_info.channel] = OUT;
}
void _setup_single_in(const ChannelInfo& ch_info)
{
_export_gpio(ch_info.gpio);
string gpio_dir_path = _SYSFS_ROOT + "/gpio"s + to_string(ch_info.gpio) + "/direction"s;
{ // scope for direction_file
ofstream direction_file(gpio_dir_path);
direction_file << "in";
} // scope ends
global._channel_configuration[ch_info.channel] = IN;
}
string _pwm_path(const ChannelInfo& ch_info) { return ch_info.pwm_chip_dir + "/pwm" + to_string(ch_info.pwm_id); }
string _pwm_export_path(const ChannelInfo& ch_info) { return ch_info.pwm_chip_dir + "/export"; }
string _pwm_unexport_path(const ChannelInfo& ch_info) { return ch_info.pwm_chip_dir + "/unexport"; }
string _pwm_period_path(const ChannelInfo& ch_info) { return _pwm_path(ch_info) + "/period"; }
string _pwm_duty_cycle_path(const ChannelInfo& ch_info) { return _pwm_path(ch_info) + "/duty_cycle"; }
string _pwm_enable_path(const ChannelInfo& ch_info) { return _pwm_path(ch_info) + "/enable"; }
void _export_pwm(const ChannelInfo& ch_info)
{
if (os_path_exists(_pwm_path(ch_info)))
return;
{ // scope for f
string path = _pwm_export_path(ch_info);
ofstream f(path);
if (!f.is_open())
throw runtime_error("Can't open " + path);
f << ch_info.pwm_id;
} // scope ends
string enable_path = _pwm_enable_path(ch_info);
int time_count = 0;
while (!os_access(enable_path, R_OK | W_OK)) {
this_thread::sleep_for(chrono::milliseconds(10));
if (time_count++ > 100)
throw runtime_error("Permission denied: path: " + enable_path +
"\n Please configure permissions or use the root user to run this.");
}
}
void _unexport_pwm(const ChannelInfo& ch_info)
{
ofstream f(_pwm_unexport_path(ch_info));
f << ch_info.pwm_id;
}
void _set_pwm_period(const ChannelInfo& ch_info, const int period_ns)
{
ofstream f(_pwm_period_path(ch_info));
f << period_ns;
}
void _set_pwm_duty_cycle(const ChannelInfo& ch_info, const int duty_cycle_ns)
{
// On boot, both period and duty cycle are both 0. In this state, the period
// must be set first; any configuration change made while period==0 is
// rejected. This is fine if we actually want a duty cycle of 0. Later, once
// any period has been set, we will always be able to set a duty cycle of 0.
// The code could be written to always read the current value, and only
// write the value if the desired value is different. However, we enable
// this check only for the 0 duty cycle case, to avoid having to read the
// current value every time the duty cycle is set.
if (duty_cycle_ns == 0) {
ifstream f(_pwm_duty_cycle_path(ch_info));
stringstream buffer;
buffer << f.rdbuf();
auto cur = buffer.str();
cur = strip(cur);
if (cur == "0")
return;
}
ofstream f(_pwm_duty_cycle_path(ch_info));
f << duty_cycle_ns;
}
void _enable_pwm(const ChannelInfo& ch_info)
{
ofstream f(_pwm_enable_path(ch_info));
f << 1;
}
void _disable_pwm(const ChannelInfo& ch_info)
{
ofstream f(_pwm_enable_path(ch_info));
f << 0;
}
void _cleanup_one(const ChannelInfo& ch_info)
{
Directions app_cfg = global._channel_configuration[ch_info.channel];
if (app_cfg == HARD_PWM) {
_disable_pwm(ch_info);
_unexport_pwm(ch_info);
} else {
_event_cleanup(ch_info.gpio);
_unexport_gpio(ch_info.gpio);
}
global._channel_configuration.erase(ch_info.channel);
}
void _cleanup_all()
{
auto copied = global._channel_configuration;
for (const auto& _pair : copied) {
const auto& channel = _pair.first;
ChannelInfo ch_info = _channel_to_info(channel);
_cleanup_one(ch_info);
}
global._gpio_mode = NumberingModes::None;
}
//==================================================================================
// APIs
// The reason that model and JETSON_INFO are not wrapped by
// GlobalVariableWrapper is because they belong to API
// GlobalVariableWrapper singleton object must be initialized before
// model and JETSON_INFO.
extern const string GPIO::model = GlobalVariableWrapper::get_model();
extern const string GPIO::JETSON_INFO = GlobalVariableWrapper::get_JETSON_INFO();
/* Function used to enable/disable warnings during setup and cleanup. */
void GPIO::setwarnings(bool state) { global._gpio_warnings = state; }
// Function used to set the pin mumbering mode.
// Possible mode values are BOARD, BCM, TEGRA_SOC and CVM
void GPIO::setmode(NumberingModes mode)
{
try {
// check if mode is valid
if (mode == NumberingModes::None)
throw runtime_error("Pin numbering mode must be GPIO::BOARD, GPIO::BCM, GPIO::TEGRA_SOC or GPIO::CVM");
// check if a different mode has been set
if (global._gpio_mode != NumberingModes::None && mode != global._gpio_mode)
throw runtime_error("A different mode has already been set!");
global._channel_data = global._channel_data_by_mode.at(mode);
global._gpio_mode = mode;
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: setmode())" << endl;
terminate();
}
}
// Function used to get the currently set pin numbering mode
NumberingModes GPIO::getmode() { return global._gpio_mode; }
/* Function used to setup individual pins or lists/tuples of pins as
Input or Output. direction must be IN or OUT, initial must be
HIGH or LOW and is only valid when direction is OUT */
void GPIO::setup(const string& channel, Directions direction, int initial)
{
try {
ChannelInfo ch_info = _channel_to_info(channel, true);
if (global._gpio_warnings) {
Directions sysfs_cfg = _sysfs_channel_configuration(ch_info);
Directions app_cfg = _app_channel_configuration(ch_info);
if (app_cfg == UNKNOWN && sysfs_cfg != UNKNOWN) {
cerr << "[WARNING] This channel is already in use, continuing anyway. Use GPIO::setwarnings(false) to "
"disable warnings.\n";
}
}
if (direction == OUT) {
_setup_single_out(ch_info, initial);
} else if (direction == IN) {
if (initial != -1)
throw runtime_error("initial parameter is not valid for inputs");
_setup_single_in(ch_info);
} else
throw runtime_error("GPIO direction must be GPIO::IN or GPIO::OUT");
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: setup())" << endl;
terminate();
}
}
void GPIO::setup(int channel, Directions direction, int initial) { setup(to_string(channel), direction, initial); }
/* Function used to cleanup channels at the end of the program.
If no channel is provided, all channels are cleaned */
void GPIO::cleanup(const string& channel)
{
try {
// warn if no channel is setup
if (global._gpio_mode == NumberingModes::None && global._gpio_warnings) {
cerr << "[WARNING] No channels have been set up yet - nothing to clean up! "
"Try cleaning up at the end of your program instead!";
return;
}
// clean all channels if no channel param provided
if (is_None(channel)) {
_cleanup_all();
return;
}
ChannelInfo ch_info = _channel_to_info(channel);
if (is_in(ch_info.channel, global._channel_configuration)) {
_cleanup_one(ch_info);
}
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: cleanup())" << endl;
terminate();
}
}
void GPIO::cleanup(int channel)
{
string str_channel = to_string(channel);
cleanup(str_channel);
}
/* Function used to return the current value of the specified channel.
Function returns either HIGH or LOW */
int GPIO::input(const string& channel)
{
try {
ChannelInfo ch_info = _channel_to_info(channel, true);
Directions app_cfg = _app_channel_configuration(ch_info);
if (app_cfg != IN && app_cfg != OUT)
throw runtime_error("You must setup() the GPIO channel first");
{ // scope for value
ifstream value(_SYSFS_ROOT + "/gpio"s + to_string(ch_info.gpio) + "/value"s);
int value_read;
value >> value_read;
return value_read;
} // scope ends
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: input())" << endl;
terminate();
}
}
int GPIO::input(int channel) { return input(to_string(channel)); }
/* Function used to set a value to a channel.
Values must be either HIGH or LOW */
void GPIO::output(const string& channel, int value)
{
try {
ChannelInfo ch_info = _channel_to_info(channel, true);
// check that the channel has been set as output
if (_app_channel_configuration(ch_info) != OUT)
throw runtime_error("The GPIO channel has not been set up as an OUTPUT");
_output_one(ch_info.gpio, value);
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: output())" << endl;
terminate();
}
}
void GPIO::output(int channel, int value) { output(to_string(channel), value); }
/* Function used to check the currently set function of the channel specified.
*/
Directions GPIO::gpio_function(const string& channel)
{
try {
ChannelInfo ch_info = _channel_to_info(channel);
return _sysfs_channel_configuration(ch_info);
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: gpio_function())" << endl;
terminate();
}
}
Directions GPIO::gpio_function(int channel) { gpio_function(to_string(channel)); }
//=============================== Events =================================
bool GPIO::event_detected(const std::string& channel)
{
ChannelInfo ch_info = _channel_to_info(channel, true);
try {
// channel must be setup as input
Directions app_cfg = _app_channel_configuration(ch_info);
if (app_cfg != Directions::IN)
throw runtime_error("You must setup() the GPIO channel as an input first");
return _edge_event_detected(ch_info.gpio);
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: GPIO::event_detected())" << endl;
_cleanup_all();
terminate();
}
}
bool GPIO::event_detected(int channel) { return event_detected(std::to_string(channel)); }
void GPIO::add_event_callback(const std::string& channel, void (*callback)(int))
{
try {
// Argument Check
if (callback == nullptr) {
throw invalid_argument("callback cannot be null");
}
ChannelInfo ch_info = _channel_to_info(channel, true);
// channel must be setup as input
Directions app_cfg = _app_channel_configuration(ch_info);
if (app_cfg != Directions::IN) {
throw runtime_error("You must setup() the GPIO channel as an input first");
}
// edge event must already exist
if (_edge_event_exists(ch_info.gpio))
throw runtime_error("The edge event must have been set via add_event_detect()");
// Execute
EventResultCode result = (EventResultCode)_add_edge_callback(ch_info.gpio, callback);
switch (result) {
case EventResultCode::None:
break;
default: {
const char* error_msg = event_error_code_to_message[result];
throw runtime_error(error_msg ? error_msg : "Unknown Error");
}
}
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: GPIO::add_event_callback())" << endl;
_cleanup_all();
terminate();
}
}
void GPIO::add_event_callback(int channel, void (*callback)(int))
{
add_event_callback(std::to_string(channel), callback);
}
void GPIO::remove_event_callback(const std::string& channel, void (*callback)(int channel))
{
ChannelInfo ch_info = _channel_to_info(channel, true);
_remove_edge_callback(ch_info.gpio, callback);
}
void GPIO::remove_event_callback(int channel, void (*callback)(int channel))
{
remove_event_callback(std::to_string(channel), callback);
}
void GPIO::add_event_detect(const std::string& channel, Edge edge, void (*callback)(int), unsigned long bounce_time)
{
add_event_detect(std::atoi(channel.data()), edge, callback, bounce_time);
}
void GPIO::add_event_detect(int channel, Edge edge, void (*callback)(int), unsigned long bounce_time)
{
try {
ChannelInfo ch_info = _channel_to_info(std::to_string(channel), true);
// channel must be setup as input
Directions app_cfg = _app_channel_configuration(ch_info);
if (app_cfg != Directions::IN) {
throw runtime_error("You must setup() the GPIO channel as an input first");
}
// edge provided must be rising, falling or both
if (edge != Edge::RISING && edge != Edge::FALLING && edge != Edge::BOTH)
throw invalid_argument("argument 'edge' must be set to RISING, FALLING or BOTH");
// Execute
EventResultCode result = (EventResultCode)_add_edge_detect(ch_info.gpio, channel, edge, bounce_time);
switch (result) {
case EventResultCode::None:
break;
default: {
const char* error_msg = event_error_code_to_message[result];
throw runtime_error(error_msg ? error_msg : "Unknown Error");
}
}
if (callback != nullptr) {
if (_add_edge_callback(ch_info.gpio, callback))
// Shouldn't happen (--it was just added successfully)
throw runtime_error("Couldn't add callback due to unknown error with just added event");
}
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: GPIO::add_event_detect())" << endl;
_cleanup_all();
terminate();
}
}
void GPIO::remove_event_detect(const std::string& channel)
{
ChannelInfo ch_info = _channel_to_info(channel, true);
_remove_edge_detect(ch_info.gpio);
}
void GPIO::remove_event_detect(int channel) { remove_event_detect(std::to_string(channel)); }
int GPIO::wait_for_edge(const std::string& channel, Edge edge, uint64_t bounce_time, uint64_t timeout)
{
return wait_for_edge(std::atoi(channel.data()), edge, bounce_time, timeout);
}
int GPIO::wait_for_edge(int channel, Edge edge, uint64_t bounce_time, uint64_t timeout)
{
try {
ChannelInfo ch_info = _channel_to_info(std::to_string(channel), true);
// channel must be setup as input
Directions app_cfg = _app_channel_configuration(ch_info);
if (app_cfg != Directions::IN) {
throw runtime_error("You must setup() the GPIO channel as an input first");
}
// edge provided must be rising, falling or both
if (edge != Edge::RISING && edge != Edge::FALLING && edge != Edge::BOTH)
throw invalid_argument("argument 'edge' must be set to RISING, FALLING or BOTH");
// Execute
EventResultCode result =
(EventResultCode)_blocking_wait_for_edge(ch_info.gpio, channel, edge, bounce_time, timeout);
switch (result) {
case EventResultCode::None:
// Timeout
return 0;
case EventResultCode::EdgeDetected:
// Event Detected
return channel;
default: {
const char* error_msg = event_error_code_to_message[result];
throw runtime_error(error_msg ? error_msg : "Unknown Error");
}
}
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: GPIO::wait_for_edge())" << endl;
_cleanup_all();
terminate();
}
}
// PWM class ==========================================================
struct GPIO::PWM::Impl {
ChannelInfo _ch_info;
bool _started;
int _frequency_hz;
int _period_ns;
double _duty_cycle_percent;
int _duty_cycle_ns;
~Impl() = default;
void _reconfigure(int frequency_hz, double duty_cycle_percent, bool start = false);
};
void GPIO::PWM::Impl::_reconfigure(int frequency_hz, double duty_cycle_percent, bool start)
{
if (duty_cycle_percent < 0.0 || duty_cycle_percent > 100.0)
throw runtime_error("invalid duty_cycle_percent");
bool restart = start || _started;
if (_started) {
_started = false;
_disable_pwm(_ch_info);
}
_frequency_hz = frequency_hz;
_period_ns = int(1000000000.0 / frequency_hz);
_set_pwm_period(_ch_info, _period_ns);
_duty_cycle_percent = duty_cycle_percent;
_duty_cycle_ns = int(_period_ns * (duty_cycle_percent / 100.0));
_set_pwm_duty_cycle(_ch_info, _duty_cycle_ns);
if (restart) {
_enable_pwm(_ch_info);
_started = true;
}
}
GPIO::PWM::PWM(int channel, int frequency_hz)
: pImpl(make_unique<Impl>(
Impl{_channel_to_info(to_string(channel), false, true), false, 0, 0, 0.0, 0})) // temporary values
{
try {
Directions app_cfg = _app_channel_configuration(pImpl->_ch_info);
if (app_cfg == HARD_PWM)
throw runtime_error("Can't create duplicate PWM objects");
/*
Apps typically set up channels as GPIO before making them be PWM,
because RPi.GPIO does soft-PWM. We must undo the GPIO export to
allow HW PWM to run on the pin.
*/
if (app_cfg == IN || app_cfg == OUT) {
cleanup(channel);
}
if (global._gpio_warnings) {
auto sysfs_cfg = _sysfs_channel_configuration(pImpl->_ch_info);
app_cfg = _app_channel_configuration(pImpl->_ch_info);
// warn if channel has been setup external to current program
if (app_cfg == UNKNOWN && sysfs_cfg != UNKNOWN) {
cerr << "[WARNING] This channel is already in use, continuing "
"anyway. "
"Use GPIO::setwarnings(false) to disable warnings"
<< endl;
}
}
_export_pwm(pImpl->_ch_info);
_set_pwm_duty_cycle(pImpl->_ch_info, 0);
pImpl->_reconfigure(frequency_hz, 0.0);
global._channel_configuration[to_string(channel)] = HARD_PWM;
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: PWM::PWM())" << endl;
_cleanup_all();
terminate();
}
}
GPIO::PWM::~PWM()
{
if (!is_in(pImpl->_ch_info.channel, global._channel_configuration) ||
global._channel_configuration.at(pImpl->_ch_info.channel) != HARD_PWM) {
/* The user probably ran cleanup() on the channel already, so avoid
attempts to repeat the cleanup operations. */
return;
}
try {
stop();
_unexport_pwm(pImpl->_ch_info);
global._channel_configuration.erase(pImpl->_ch_info.channel);
} catch (...) {
cerr << "[Exception] ~PWM Exception! shut down the program." << endl;
_cleanup_all();
terminate();
}
}
// move construct
GPIO::PWM::PWM(GPIO::PWM&& other) = default;
// move assign
GPIO::PWM& GPIO::PWM::operator=(GPIO::PWM&& other)
{
if (this == &other)
return *this;
pImpl = std::move(other.pImpl);
return *this;
}
void GPIO::PWM::start(double duty_cycle_percent)
{
try {
pImpl->_reconfigure(pImpl->_frequency_hz, duty_cycle_percent, true);
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: PWM::start())" << endl;
_cleanup_all();
terminate();
}
}
void GPIO::PWM::ChangeFrequency(int frequency_hz)
{
try {
pImpl->_reconfigure(frequency_hz, pImpl->_duty_cycle_percent);
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: PWM::ChangeFrequency())" << endl;
terminate();
}
}
void GPIO::PWM::ChangeDutyCycle(double duty_cycle_percent)
{
try {
pImpl->_reconfigure(pImpl->_frequency_hz, duty_cycle_percent);
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: PWM::ChangeDutyCycle())" << endl;
terminate();
}
}
void GPIO::PWM::stop()
{
try {
if (!pImpl->_started)
return;
_disable_pwm(pImpl->_ch_info);
} catch (exception& e) {
cerr << "[Exception] " << e.what() << " (catched from: PWM::stop())" << endl;
throw runtime_error("Exeception from GPIO::PWM::stop");
}
}
//=========================== Originally added ===========================
struct _cleaner {
private:
_cleaner() = default;
public:
_cleaner(const _cleaner&) = delete;
_cleaner& operator=(const _cleaner&) = delete;
static _cleaner& get_instance()
{
static _cleaner singleton;
return singleton;
}
~_cleaner()
{
try {
// When the user forgot to call cleanup() at the end of the program,
// _cleaner object will call it.
_cleanup_all();
} catch (exception& e) {
cerr << "Exception: " << e.what() << endl;
cerr << "Exception from destructor of _cleaner class." << endl;
}
}
};
// AutoCleaner will be destructed at the end of the program, and call
// _cleanup_all(). It COULD cause a problem because at the end of the program,
// global._channel_configuration and global._gpio_mode MUST NOT be destructed
// before AutoCleaner. But the static objects are destructed in the reverse
// order of construction, and objects defined in the same compilation unit will
// be constructed in the order of definition. So it's supposed to work properly.
_cleaner& AutoCleaner = _cleaner::get_instance();
//=========================================================================
<file_sep>/README.md
# JetsonGPIO(C++)
JetsonGPIO(C++) is an C++ port of the **NVIDIA's Jetson.GPIO Python library**(https://github.com/NVIDIA/jetson-gpio).
Jetson TX1, TX2, AGX Xavier, and Nano development boards contain a 40 pin GPIO header, similar to the 40 pin header in the Raspberry Pi. These GPIOs can be controlled for digital input and output using this library. The library provides almost same APIs as the Jetson.GPIO Python library.
# Installation
Clone this repository, build it, and install it.
```
git clone https://github.com/pjueon/JetsonGPIO
cd JetsonGPIO/build
make all
sudo make install
```
# Setting User Permissions
In order to use the Jetson GPIO Library, the correct user permissions/groups must
be set first. Or you have to run your program with root permission.
Create a new gpio user group. Then add your user to the newly created group.
```
sudo groupadd -f -r gpio
sudo usermod -a -G gpio your_user_name
```
Install custom udev rules by copying the 99-gpio.rules file into the rules.d
directory. The 99-gpio.rules file was copied from NVIDIA's official repository.
```
sudo cp JetsonGPIO/99-gpio.rules /etc/udev/rules.d/
```
For the new rule to take place, you either need to reboot or reload the udev
rules by running:
```
sudo udevadm control --reload-rules && sudo udevadm trigger
```
# Library API
The library provides almost same APIs as the the NVIDIA's Jetson GPIO Python library.
The following discusses the use of each API:
#### 1. Include the libary
To include the JetsonGPIO use:
```cpp
#include <JetsonGPIO>
```
All public APIs are declared in namespace "GPIO". If you want to make your code shorter, you can use:
```cpp
using namespace GPIO; // optional
```
To compile your program use:
```
g++ -o your_program_name your_source_code.cpp -lpthread -lJetsonGPIO
```
#### 2. Pin numbering
The Jetson GPIO library provides four ways of numbering the I/O pins. The first
two correspond to the modes provided by the RPi.GPIO library, i.e BOARD and BCM
which refer to the pin number of the 40 pin GPIO header and the Broadcom SoC
GPIO numbers respectively. The remaining two modes, CVM and TEGRA_SOC use
strings instead of numbers which correspond to signal names on the CVM/CVB
connector and the Tegra SoC respectively.
To specify which mode you are using (mandatory), use the following function
call:
```cpp
GPIO::setmode(GPIO::BOARD);
// or
GPIO::setmode(GPIO::BCM);
// or
GPIO::setmode(GPIO::CVM);
// or
GPIO::setmode(GPIO::TEGRA_SOC);
```
To check which mode has be set, you can call:
```cpp
GPIO::NumberingModes mode = GPIO::getmode();
```
This function returns an instance of enum class GPIO::NumberingModes. The mode must be one of GPIO::BOARD(GPIO::NumberingModes::BOARD), GPIO::BCM(GPIO::NumberingModes::BCM), GPIO::CVM(GPIO::NumberingModes::CVM), GPIO::TEGRA_SOC(GPIO::NumberingModes::TEGRA_SOC) or GPIO::NumberingModes::None.
#### 3. Warnings
It is possible that the GPIO you are trying to use is already being used
external to the current application. In such a condition, the Jetson GPIO
library will warn you if the GPIO being used is configured to anything but the
default direction (input). It will also warn you if you try cleaning up before
setting up the mode and channels. To disable warnings, call:
```cpp
GPIO::setwarnings(false);
```
#### 4. Set up a channel
The GPIO channel must be set up before use as input or output. To configure
the channel as input, call:
```cpp
// (where channel is based on the pin numbering mode discussed above)
GPIO::setup(channel, GPIO::IN); // channel must be int or std::string
```
To set up a channel as output, call:
```cpp
GPIO::setup(channel, GPIO::OUT);
```
It is also possible to specify an initial value for the output channel:
```cpp
GPIO::setup(channel, GPIO::OUT, GPIO::HIGH);
```
#### 5. Input
To read the value of a channel, use:
```cpp
int value = GPIO::input(channel);
```
This will return either GPIO::LOW(== 0) or GPIO::HIGH(== 1).
#### 6. Output
To set the value of a pin configured as output, use:
```cpp
GPIO::output(channel, state);
```
where state can be GPIO::LOW(== 0) or GPIO::HIGH(== 1).
#### 7. Clean up
At the end of the program, it is good to clean up the channels so that all pins
are set in their default state. To clean up all channels used, call:
```cpp
GPIO::cleanup();
```
If you don't want to clean all channels, it is also possible to clean up
individual channels:
```cpp
GPIO::cleanup(chan1); // cleanup only chan1
```
#### 8. Jetson Board Information and library version
To get information about the Jetson module, use/read:
```cpp
std::string info = GPIO::JETSON_INFO;
```
To get the model name of your Jetson device, use/read:
```cpp
std::string model = GPIO::model;
```
To get information about the library version, use/read:
```cpp
std::string version = GPIO::VERSION;
```
This provides a string with the X.Y.Z version format.
#### 9. Interrupts
Aside from busy-polling, the library provides three additional ways of monitoring an input event:
__The wait_for_edge() function__
This function blocks the calling thread until the provided edge(s) is detected. The function can be called as follows:
```cpp
GPIO::wait_for_edge(channel, GPIO::RISING);
```
The second parameter specifies the edge to be detected and can be GPIO::RISING, GPIO::FALLING or GPIO::BOTH. If you only want to limit the wait to a specified amount of time, a timeout can be optionally set:
```cpp
// timeout is in milliseconds__
// debounce_time set to 10ms
GPIO::wait_for_edge(channel, GPIO::RISING, 10, 500);
```
The function returns the channel for which the edge was detected or 0 if a timeout occurred.
__The event_detected() function__
This function can be used to periodically check if an event occurred since the last call. The function can be set up and called as follows:
```cpp
// set rising edge detection on the channel
GPIO::add_event_detect(channel, GPIO::RISING);
run_other_code();
if(GPIO::event_detected(channel))
do_something();
```
As before, you can detect events for GPIO::RISING, GPIO::FALLING or GPIO::BOTH.
__A callback function run when an edge is detected__
This feature can be used to run a second thread for callback functions. Hence, the callback function can be run concurrent to your main program in response to an edge. This feature can be used as follows:
```cpp
// define callback function
void callback_fn(int channel) {
std::cout << "Callback called from channel " << channel << std::endl;
}
// add rising edge detection
GPIO::add_event_detect(channel, GPIO::RISING, callback_fn);
```
More than one callback can also be added if required as follows:
```cpp
void callback_one(int channel) {
std::cout << "First Callback" << std::endl;
}
void callback_two(int channel) {
std::cout << "Second Callback" << std::endl;
}
GPIO::add_event_detect(channel, GPIO::RISING);
GPIO::add_event_callback(channel, callback_one);
GPIO::add_event_callback(channel, callback_two);
```
The two callbacks in this case are run sequentially, not concurrently since there is only one event thread running all callback functions.
In order to prevent multiple calls to the callback functions by collapsing multiple events in to a single one, a debounce time can be optionally set:
```cpp
// bouncetime set in milliseconds
GPIO::add_event_detect(channel, GPIO::RISING, callback_fn, 200);
```
If one of the callbacks are no longer required it may then be removed:
```cpp
GPIO::remove_event_callback(channel, callback_two);
```
Similarly, if the edge detection is no longer required it can be removed as follows:
```cpp
GPIO::remove_event_detect(channel);
```
#### 10. Check function of GPIO channels
This feature allows you to check the function of the provided GPIO channel:
```cpp
GPIO::Directions direction = GPIO::gpio_function(channel);
```
The function returns either GPIO::IN(GPIO::Directions::IN) or GPIO::OUT(GPIO::Directions::OUT) which are the instances of enum class GPIO::Directions.
#### 11. PWM
See `samples/simple_pwm.cpp` for details on how to use PWM channels.
The JetsonGPIO library supports PWM only on pins with attached hardware PWM
controllers. Unlike the RPi.GPIO library, the JetsonGPIO library does not
implement Software emulated PWM. Jetson Nano supports 2 PWM channels, and
Jetson AGX Xavier supports 3 PWM channels. Jetson TX1 and TX2 do not support
any PWM channels.
The system pinmux must be configured to connect the hardware PWM controlller(s)
to the relevant pins. If the pinmux is not configured, PWM signals will not
reach the pins! The JetsonGPIO library does not dynamically modify the pinmux
configuration to achieve this. Read the L4T documentation for details on how to
configure the pinmux.
<file_sep>/include/JetsonGPIO.h
/*
Copyright (c) 2012-2017 <NAME> <EMAIL>.
Copyright (c) 2019, NVIDIA CORPORATION.
Copyright (c) 2019 <NAME>(pjueon) <EMAIL>.
Copyright (c) 2021 <NAME> <EMAIL>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#pragma once
#ifndef JETSON_GPIO_H
#define JETSON_GPIO_H
#include <memory> // for pImpl
#include <string>
namespace GPIO
{
constexpr auto VERSION = "1.0.0";
constexpr auto _SYSFS_ROOT = "/sys/class/gpio";
extern const std::string JETSON_INFO;
extern const std::string model;
// Pin Numbering Modes
enum class NumberingModes { BOARD, BCM, TEGRA_SOC, CVM, None };
// GPIO::BOARD, GPIO::BCM, GPIO::TEGRA_SOC, GPIO::CVM
constexpr NumberingModes BOARD = NumberingModes::BOARD;
constexpr NumberingModes BCM = NumberingModes::BCM;
constexpr NumberingModes TEGRA_SOC = NumberingModes::TEGRA_SOC;
constexpr NumberingModes CVM = NumberingModes::CVM;
// Pull up/down options are removed because they are unused in NVIDIA's original python libarary.
// check: https://github.com/NVIDIA/jetson-gpio/issues/5
constexpr int HIGH = 1;
constexpr int LOW = 0;
// GPIO directions.
// UNKNOWN constant is for gpios that are not yet setup
// If the user uses UNKNOWN or HARD_PWM as a parameter to GPIO::setmode function,
// An exception will occur
enum class Directions { UNKNOWN, OUT, IN, HARD_PWM };
// GPIO::IN, GPIO::OUT
constexpr Directions IN = Directions::IN;
constexpr Directions OUT = Directions::OUT;
// GPIO Event Types
enum class Edge { UNKNOWN, NONE, RISING, FALLING, BOTH };
constexpr Edge NO_EDGE = Edge::NONE;
constexpr Edge RISING = Edge::RISING;
constexpr Edge FALLING = Edge::FALLING;
constexpr Edge BOTH = Edge::BOTH;
// Function used to enable/disable warnings during setup and cleanup.
void setwarnings(bool state);
// Function used to set the pin mumbering mode.
// Possible mode values are BOARD, BCM, TEGRA_SOC and CVM
void setmode(NumberingModes mode);
// Function used to get the currently set pin numbering mode
NumberingModes getmode();
/* Function used to setup individual pins as Input or Output.
direction must be IN or OUT, initial must be
HIGH or LOW and is only valid when direction is OUT */
void setup(const std::string& channel, Directions direction, int initial = -1);
void setup(int channel, Directions direction, int initial = -1);
/* Function used to cleanup channels at the end of the program.
If no channel is provided, all channels are cleaned */
void cleanup(const std::string& channel = "None");
void cleanup(int channel);
/* Function used to return the current value of the specified channel.
Function returns either HIGH or LOW */
int input(const std::string& channel);
int input(int channel);
/* Function used to set a value to a channel.
Values must be either HIGH or LOW */
void output(const std::string& channel, int value);
void output(int channel, int value);
/* Function used to check the currently set function of the channel specified. */
Directions gpio_function(const std::string& channel);
Directions gpio_function(int channel);
//----------------------------------
/* Function used to check if an event occurred on the specified channel.
Param channel must be an integer.
This function return True or False */
bool event_detected(const std::string& channel);
bool event_detected(int channel);
/* Function used to add a callback function to channel, after it has been
registered for events using add_event_detect() */
void add_event_callback(const std::string& channel, void (*callback)(int channel));
void add_event_callback(int channel, void (*callback)(int channel));
/* Function used to remove a callback function previously added to detect a channel event */
void remove_event_callback(const std::string& channel, void (*callback)(int channel));
void remove_event_callback(int channel, void (*callback)(int channel));
/* Function used to add threaded event detection for a specified gpio channel.
@gpio must be an integer specifying the channel
@edge must be a member of GPIO::Edge
@callback (optional) may be a callback function to be called when the event is detected (or nullptr)
@bouncetime (optional) a button-bounce signal ignore time (in milliseconds, default=none) */
void add_event_detect(const std::string& channel, Edge edge, void (*callback)(int channel) = nullptr,
unsigned long bounce_time = 0);
void add_event_detect(int channel, Edge edge, void (*callback)(int channel) = nullptr, unsigned long bounce_time = 0);
/* Function used to remove event detection for channel */
void remove_event_detect(const std::string& channel);
void remove_event_detect(int channel);
/* Function used to perform a blocking wait until the specified edge event is detected within the specified
timeout period. Returns the channel if an event is detected or 0 if a timeout has occurred.
@channel is an integer specifying the channel
@edge must be a member of GPIO::Edge
@bouncetime in milliseconds (optional)
@timeout in milliseconds (optional)
@returns channel for an event, 0 for a timeout */
int wait_for_edge(const std::string& channel, Edge edge, unsigned long bounce_time = 0, unsigned long timeout = 0);
int wait_for_edge(int channel, Edge edge, unsigned long bounce_time = 0, unsigned long timeout = 0);
//----------------------------------
class PWM
{
public:
PWM(int channel, int frequency_hz);
PWM(PWM&& other);
PWM& operator=(PWM&& other);
PWM(const PWM&) = delete; // Can't create duplicate PWM objects
PWM& operator=(const PWM&) = delete; // Can't create duplicate PWM objects
~PWM();
void start(double duty_cycle_percent);
void stop();
void ChangeFrequency(int frequency_hz);
void ChangeDutyCycle(double duty_cycle_percent);
private:
struct Impl;
std::unique_ptr<Impl> pImpl;
};
} // namespace GPIO
#endif // JETSON_GPIO_H
<file_sep>/src/gpio_pin_data.cpp
/*
Copyright (c) 2012-2017 <NAME> <EMAIL>.
Copyright (c) 2019, NVIDIA CORPORATION.
Copyright (c) 2019 <NAME>(pjueon) <EMAIL>.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <string>
#include <stdexcept>
#include <vector>
#include <map>
#include <set>
#include <fstream>
#include <sstream>
#include <cctype>
#include <algorithm>
#include <iterator>
#include "JetsonGPIO.h"
#include "private/gpio_pin_data.h"
#include "private/PythonFunctions.h"
using namespace GPIO;
using namespace std;
using namespace std::string_literals; // enables s-suffix for std::string literals
// ========================================= Begin of "gpio_pin_data.py" =========================================
// Global variables are wrapped in singleton pattern in order to avoid
// initialization order of global variables in different compilation units problem
class EntirePinData
{
private:
EntirePinData();
public:
/* These vectors contain all the relevant GPIO data for each Jetson Platform.
The values are use to generate dictionaries that map the corresponding pin
mode numbers to the Linux GPIO pin number and GPIO chip directory */
const vector<PinDefinition> CLARA_AGX_XAVIER_PIN_DEFS;
const vector<string> compats_clara_agx_xavier;
const vector<PinDefinition> JETSON_NX_PIN_DEFS;
const vector<string> compats_nx;
const vector<PinDefinition> JETSON_XAVIER_PIN_DEFS;
const vector<string> compats_xavier;
const vector<PinDefinition> JETSON_TX2_PIN_DEFS;
const vector<string> compats_tx2;
const vector<PinDefinition> JETSON_TX1_PIN_DEFS;
const vector<string> compats_tx1;
const vector<PinDefinition> JETSON_NANO_PIN_DEFS;
const vector<string> compats_nano;
const map<Model, vector<PinDefinition>> PIN_DEFS_MAP;
const map<Model, PinInfo> JETSON_INFO_MAP;
EntirePinData(const EntirePinData &) = delete;
EntirePinData &operator=(const EntirePinData &) = delete;
~EntirePinData() = default;
static EntirePinData &get_instance()
{
static EntirePinData singleton{};
return singleton;
}
};
EntirePinData::EntirePinData()
:
CLARA_AGX_XAVIER_PIN_DEFS
{
{ 134, "2200000.gpio", "7", "4", "MCLK05", "SOC_GPIO42", "None", -1 },
{ 140, "2200000.gpio", "11", "17", "UART1_RTS", "UART1_RTS", "None", -1 },
{ 63, "2200000.gpio", "12", "18", "I2S2_CLK", "DAP2_SCLK", "None", -1 },
{ 124, "2200000.gpio", "13", "27", "GPIO32", "SOC_GPIO04", "None", -1 },
// Older versions of L4T don"t enable this PWM controller in DT, so this PWM
// channel may not be available.
{ 105, "2200000.gpio", "15", "22", "GPIO27", "SOC_GPIO54", "3280000.pwm", 0 },
{ 8, "c2f0000.gpio", "16", "23", "GPIO8", "CAN1_STB", "None", -1 },
{ 56, "2200000.gpio", "18", "24", "GPIO35", "SOC_GPIO12", "32c0000.pwm", 0 },
{ 205, "2200000.gpio", "19", "10", "SPI1_MOSI", "SPI1_MOSI", "None", -1 },
{ 204, "2200000.gpio", "21", "9", "SPI1_MISO", "SPI1_MISO", "None", -1 },
{ 129, "2200000.gpio", "22", "25", "GPIO17", "SOC_GPIO21", "None", -1 },
{ 203, "2200000.gpio", "23", "11", "SPI1_CLK", "SPI1_SCK", "None", -1 },
{ 206, "2200000.gpio", "24", "8", "SPI1_CS0_N", "SPI1_CS0_N", "None", -1 },
{ 207, "2200000.gpio", "26", "7", "SPI1_CS1_N", "SPI1_CS1_N", "None", -1 },
{ 3, "c2f0000.gpio", "29", "5", "CAN0_DIN", "CAN0_DIN", "None", -1 },
{ 2, "c2f0000.gpio", "31", "6", "CAN0_DOUT", "CAN0_DOUT", "None", -1 },
{ 9, "c2f0000.gpio", "32", "12", "GPIO9", "CAN1_EN", "None", -1 },
{ 0, "c2f0000.gpio", "33", "13", "CAN1_DOUT", "CAN1_DOUT", "None", -1 },
{ 66, "2200000.gpio", "35", "19", "I2S2_FS", "DAP2_FS", "None", -1 },
// Input-only (due to base board)
{ 141, "2200000.gpio", "36", "16", "UART1_CTS", "UART1_CTS", "None", -1 },
{ 1, "c2f0000.gpio", "37", "26", "CAN1_DIN", "CAN1_DIN", "None", -1 },
{ 65, "2200000.gpio", "38", "20", "I2S2_DIN", "DAP2_DIN", "None", -1 },
{ 64, "2200000.gpio", "40", "21", "I2S2_DOUT", "DAP2_DOUT", "None", -1 }
},
compats_clara_agx_xavier
{
"nvidia,e3900-0000+p2888-0004"
},
JETSON_NX_PIN_DEFS
{
{ 148, "2200000.gpio", "7", "4", "GPIO09", "AUD_MCLK", "None", -1 },
{ 140, "2200000.gpio", "11", "17", "UART1_RTS", "UART1_RTS", "None", -1 },
{ 157, "2200000.gpio", "12", "18", "I2S0_SCLK", "DAP5_SCLK", "None", -1 },
{ 192, "2200000.gpio", "13", "27", "SPI1_SCK", "SPI3_SCK", "None", -1 },
{ 20, "c2f0000.gpio", "15", "22", "GPIO12", "TOUCH_CLK", "None", -1 },
{ 196, "2200000.gpio", "16", "23", "SPI1_CS1", "SPI3_CS1_N", "None", -1 },
{ 195, "2200000.gpio", "18", "24", "SPI1_CS0", "SPI3_CS0_N", "None", -1 },
{ 205, "2200000.gpio", "19", "10", "SPI0_MOSI", "SPI1_MOSI", "None", -1 },
{ 204, "2200000.gpio", "21", "9", "SPI0_MISO", "SPI1_MISO", "None", -1 },
{ 193, "2200000.gpio", "22", "25", "SPI1_MISO", "SPI3_MISO", "None", -1 },
{ 203, "2200000.gpio", "23", "11", "SPI0_SCK", "SPI1_SCK", "None", -1 },
{ 206, "2200000.gpio", "24", "8", "SPI0_CS0", "SPI1_CS0_N", "None", -1 },
{ 207, "2200000.gpio", "26", "7", "SPI0_CS1", "SPI1_CS1_N", "None", -1 },
{ 133, "2200000.gpio", "29", "5", "GPIO01", "SOC_GPIO41", "None", -1 },
{ 134, "2200000.gpio", "31", "6", "GPIO11", "SOC_GPIO42", "None", -1 },
{ 136, "2200000.gpio", "32", "12", "GPIO07", "SOC_GPIO44", "32f0000.pwm", 0 },
{ 105, "2200000.gpio", "33", "13", "GPIO13", "SOC_GPIO54", "3280000.pwm", 0 },
{ 160, "2200000.gpio", "35", "19", "I2S0_FS", "DAP5_FS", "None", -1 },
{ 141, "2200000.gpio", "36", "16", "UART1_CTS", "UART1_CTS", "None", -1 },
{ 194, "2200000.gpio", "37", "26", "SPI1_MOSI", "SPI3_MOSI", "None", -1 },
{ 159, "2200000.gpio", "38", "20", "I2S0_DIN", "DAP5_DIN", "None", -1 },
{ 158, "2200000.gpio", "40", "21", "I2S0_DOUT", "DAP5_DOUT", "None", -1 }
},
compats_nx
{
"nvidia,p3509-0000+p3668-0000",
"nvidia,p3509-0000+p3668-0001",
"nvidia,p3449-0000+p3668-0000",
"nvidia,p3449-0000+p3668-0001"
},
JETSON_XAVIER_PIN_DEFS
{
{ 134, "2200000.gpio", "7", "4", "MCLK05", "SOC_GPIO42", "None", -1 },
{ 140, "2200000.gpio", "11", "17", "UART1_RTS", "UART1_RTS", "None", -1 },
{ 63, "2200000.gpio", "12", "18", "I2S2_CLK", "DAP2_SCLK", "None", -1 },
{ 136, "2200000.gpio", "13", "27", "PWM01", "SOC_GPIO44", "32f0000.pwm", 0 },
// Older versions of L4T don"t enable this PWM controller in DT, so this PWM
// channel may not be available.
{ 105, "2200000.gpio", "15", "22", "GPIO27", "SOC_GPIO54", "3280000.pwm", 0 },
{ 8, "c2f0000.gpio", "16", "23", "GPIO8", "CAN1_STB", "None", -1 },
{ 56, "2200000.gpio", "18", "24", "GPIO35", "SOC_GPIO12", "32c0000.pwm", 0 },
{ 205, "2200000.gpio", "19", "10", "SPI1_MOSI", "SPI1_MOSI", "None", -1 },
{ 204, "2200000.gpio", "21", "9", "SPI1_MISO", "SPI1_MISO", "None", -1 },
{ 129, "2200000.gpio", "22", "25", "GPIO17", "SOC_GPIO21", "None", -1 },
{ 203, "2200000.gpio", "23", "11", "SPI1_CLK", "SPI1_SCK", "None", -1 },
{ 206, "2200000.gpio", "24", "8", "SPI1_CS0_N", "SPI1_CS0_N", "None", -1},
{ 207, "2200000.gpio", "26", "7", "SPI1_CS1_N", "SPI1_CS1_N", "None", -1},
{ 3, "c2f0000.gpio", "29", "5", "CAN0_DIN", "CAN0_DIN", "None", -1 },
{ 2, "c2f0000.gpio", "31", "6", "CAN0_DOUT", "CAN0_DOUT", "None", -1 },
{ 9, "c2f0000.gpio", "32", "12", "GPIO9", "CAN1_EN", "None", -1 },
{ 0, "c2f0000.gpio", "33", "13", "CAN1_DOUT", "CAN1_DOUT", "None", -1 },
{ 66, "2200000.gpio", "35", "19", "I2S2_FS", "DAP2_FS", "None", -1 },
// Input-only (due to base board)
{ 141, "2200000.gpio", "36", "16", "UART1_CTS", "UART1_CTS", "None", -1 },
{ 1, "c2f0000.gpio", "37", "26", "CAN1_DIN", "CAN1_DIN", "None", -1 },
{ 65, "2200000.gpio", "38", "20", "I2S2_DIN", "DAP2_DIN", "None", -1 },
{ 64, "2200000.gpio", "40", "21", "I2S2_DOUT", "DAP2_DOUT", "None", -1 }
},
compats_xavier
{
"nvidia,p2972-0000",
"nvidia,p2972-0006",
"nvidia,jetson-xavier"
},
JETSON_TX2_PIN_DEFS
{
{ 76, "2200000.gpio", "7", "4", "AUDIO_MCLK", "AUD_MCLK", "None", -1 },
// Output-only (due to base board)
{ 146, "2200000.gpio", "11", "17", "UART0_RTS", "UART1_RTS", "None", -1 },
{ 72, "2200000.gpio", "12", "18", "I2S0_CLK", "DAP1_SCLK", "None", -1 },
{ 77, "2200000.gpio", "13", "27", "GPIO20_AUD_INT", "GPIO_AUD0", "None", -1 },
{ 15, "3160000.i2c/i2c-0/0-0074", "15", "22", "GPIO_EXP_P17", "GPIO_EXP_P17", "None", -1 },
// Input-only (due to module):
{ 40, "c2f0000.gpio", "16", "23", "AO_DMIC_IN_DAT", "CAN_GPIO0", "None", -1 },
{ 161, "2200000.gpio", "18", "24", "GPIO16_MDM_WAKE_AP", "GPIO_MDM2", "None", -1 },
{ 109, "2200000.gpio", "19", "10", "SPI1_MOSI", "GPIO_CAM6", "None", -1 },
{ 108, "2200000.gpio", "21", "9", "SPI1_MISO", "GPIO_CAM5", "None", -1 },
{ 14, "3160000.i2c/i2c-0/0-0074", "22", "25", "GPIO_EXP_P16", "GPIO_EXP_P16", "None", -1 },
{ 107, "2200000.gpio", "23", "11", "SPI1_CLK", "GPIO_CAM4", "None", -1 },
{ 110, "2200000.gpio", "24", "8", "SPI1_CS0", "GPIO_CAM7", "None", -1 },
{ -1, "None", "26", "7", "SPI1_CS1", "None", "None", -1 },
{ 78, "2200000.gpio", "29", "5", "GPIO19_AUD_RST", "GPIO_AUD1", "None", -1 },
{ 42, "c2f0000.gpio", "31", "6", "GPIO9_MOTION_INT", "CAN_GPIO2", "None", -1 },
// Output-only (due to module):
{ 41, "c2f0000.gpio", "32", "12", "AO_DMIC_IN_CLK", "CAN_GPIO1", "None", -1 },
{ 69, "2200000.gpio", "33", "13", "GPIO11_AP_WAKE_BT", "GPIO_PQ5", "None", -1 },
{ 75, "2200000.gpio", "35", "19", "I2S0_LRCLK", "DAP1_FS", "None", -1 },
// Input-only (due to base board) IF NVIDIA debug card NOT plugged in
// Output-only (due to base board) IF NVIDIA debug card plugged in
{ 147, "2200000.gpio", "36", "16", "UART0_CTS", "UART1_CTS", "None", -1 },
{ 68, "2200000.gpio", "37", "26", "GPIO8_ALS_PROX_INT", "GPIO_PQ4", "None", -1 },
{ 74, "2200000.gpio", "38", "20", "I2S0_SDIN", "DAP1_DIN", "None", -1 },
{ 73, "2200000.gpio", "40", "21", "I2S0_SDOUT", "DAP1_DOUT", "None", -1}
},
compats_tx2
{
"nvidia,p2771-0000",
"nvidia,p2771-0888",
"nvidia,p3489-0000",
"nvidia,lightning",
"nvidia,quill",
"nvidia,storm"
},
JETSON_TX1_PIN_DEFS
{
{ 216, "6000d000.gpio", "7", "4", "AUDIO_MCLK", "AUD_MCLK", "None", -1 },
// Output-only (due to base board)
{ 162, "6000d000.gpio", "11", "17", "UART0_RTS", "UART1_RTS", "None", -1 },
{ 11, "6000d000.gpio", "12", "18", "I2S0_CLK", "DAP1_SCLK", "None", -1 },
{ 38, "6000d000.gpio", "13", "27", "GPIO20_AUD_INT", "GPIO_PE6", "None", -1 },
{ 15, "7000c400.i2c/i2c-1/1-0074", "15", "22", "GPIO_EXP_P17", "GPIO_EXP_P17", "None", -1 },
{ 37, "6000d000.gpio", "16", "23", "AO_DMIC_IN_DAT", "DMIC3_DAT", "None", -1 },
{ 184, "6000d000.gpio", "18", "24", "GPIO16_MDM_WAKE_AP", "MODEM_WAKE_AP", "None", -1 },
{ 16, "6000d000.gpio", "19", "10", "SPI1_MOSI", "SPI1_MOSI", "None", -1 },
{ 17, "6000d000.gpio", "21", "9", "SPI1_MISO", "SPI1_MISO", "None", -1 },
{ 14, "7000c400.i2c/i2c-1/1-0074", "22", "25", "GPIO_EXP_P16", "GPIO_EXP_P16", "None", -1 },
{ 18, "6000d000.gpio", "23", "11", "SPI1_CLK", "SPI1_SCK", "None", -1 },
{ 19, "6000d000.gpio", "24", "8", "SPI1_CS0", "SPI1_CS0", "None", -1 },
{ 20, "6000d000.gpio", "26", "7", "SPI1_CS1", "SPI1_CS1", "None", -1 },
{ 219, "6000d000.gpio", "29", "5", "GPIO19_AUD_RST", "GPIO_X1_AUD", "None", -1 },
{ 186, "6000d000.gpio", "31", "6", "GPIO9_MOTION_INT", "MOTION_INT", "None", -1 },
{ 36, "6000d000.gpio", "32", "12", "AO_DMIC_IN_CLK", "DMIC3_CLK", "None", -1 },
{ 63, "6000d000.gpio", "33", "13", "GPIO11_AP_WAKE_BT", "AP_WAKE_NFC", "None", -1 },
{ 8, "6000d000.gpio", "35", "19", "I2S0_LRCLK", "DAP1_FS", "None", -1 },
// Input-only (due to base board) IF NVIDIA debug card NOT plugged in
// Input-only (due to base board) (always reads fixed value) IF NVIDIA debug card plugged in
{ 163, "6000d000.gpio", "36", "16", "UART0_CTS", "UART1_CTS", "None", -1 },
{ 187, "6000d000.gpio", "37", "26", "GPIO8_ALS_PROX_INT", "ALS_PROX_INT", "None", -1 },
{ 9, "6000d000.gpio", "38", "20", "I2S0_SDIN", "DAP1_DIN", "None", -1 },
{ 10, "6000d000.gpio", "40", "21", "I2S0_SDOUT", "DAP1_DOUT", "None", -1 }
},
compats_tx1
{
"nvidia,p2371-2180",
"nvidia,jetson-cv"
},
JETSON_NANO_PIN_DEFS
{
{ 216, "6000d000.gpio", "7", "4", "GPIO9", "AUD_MCLK", "None", -1 },
{ 50, "6000d000.gpio", "11", "17", "UART1_RTS", "UART2_RTS", "None", -1 },
{ 79, "6000d000.gpio", "12", "18", "I2S0_SCLK", "DAP4_SCLK", "None", -1 },
{ 14, "6000d000.gpio", "13", "27", "SPI1_SCK", "SPI2_SCK", "None", -1 },
{ 194, "6000d000.gpio", "15", "22", "GPIO12", "LCD_TE", "None", -1 },
{ 232, "6000d000.gpio", "16", "23", "SPI1_CS1", "SPI2_CS1", "None", -1 },
{ 15, "6000d000.gpio", "18", "24", "SPI1_CS0", "SPI2_CS0", "None", -1 },
{ 16, "6000d000.gpio", "19", "10", "SPI0_MOSI", "SPI1_MOSI", "None", -1 },
{ 17, "6000d000.gpio", "21", "9", "SPI0_MISO", "SPI1_MISO", "None", -1 },
{ 13, "6000d000.gpio", "22", "25", "SPI1_MISO", "SPI2_MISO", "None", -1 },
{ 18, "6000d000.gpio", "23", "11", "SPI0_SCK", "SPI1_SCK", "None", -1 },
{ 19, "6000d000.gpio", "24", "8", "SPI0_CS0", "SPI1_CS0", "None", -1 },
{ 20, "6000d000.gpio", "26", "7", "SPI0_CS1", "SPI1_CS1", "None", -1 },
{ 149, "6000d000.gpio", "29", "5", "GPIO01", "CAM_AF_EN", "None", -1 },
{ 200, "6000d000.gpio", "31", "6", "GPIO11", "GPIO_PZ0", "None", -1 },
// Older versions of L4T have a DT bug which instantiates a bogus device
// which prevents this library from using this PWM channel.
{ 168, "6000d000.gpio", "32", "12", "GPIO07", "LCD_BL_PW", "7000a000.pwm", 0 },
{ 38, "6000d000.gpio", "33", "13", "GPIO13", "GPIO_PE6", "7000a000.pwm", 2 },
{ 76, "6000d000.gpio", "35", "19", "I2S0_FS", "DAP4_FS", "None", -1 },
{ 51, "6000d000.gpio", "36", "16", "UART1_CTS", "UART2_CTS", "None", -1 },
{ 12, "6000d000.gpio", "37", "26", "SPI1_MOSI", "SPI2_MOSI", "None", -1 },
{ 77, "6000d000.gpio", "38", "20", "I2S0_DIN", "DAP4_DIN", "None", -1 },
{ 78, "6000d000.gpio", "40", "21", "I2S0_DOUT", "DAP4_DOUT", "None", -1 }
},
compats_nano
{
"nvidia,p3450-0000",
"nvidia,p3450-0002",
"nvidia,jetson-nano"
},
PIN_DEFS_MAP
{
{ CLARA_AGX_XAVIER, CLARA_AGX_XAVIER_PIN_DEFS },
{ JETSON_NX, JETSON_NX_PIN_DEFS },
{ JETSON_XAVIER, JETSON_XAVIER_PIN_DEFS },
{ JETSON_TX2, JETSON_TX2_PIN_DEFS },
{ JETSON_TX1, JETSON_TX1_PIN_DEFS },
{ JETSON_NANO, JETSON_NANO_PIN_DEFS }
},
JETSON_INFO_MAP
{
{ CLARA_AGX_XAVIER, {1, "16384M", "Unknown", "CLARA_AGX_XAVIER", "NVIDIA", "ARM Carmel"} },
{ JETSON_NX, {1, "16384M", "Unknown", "Jetson NX", "NVIDIA", "ARM Carmel"} },
{ JETSON_XAVIER, {1, "16384M", "Unknown", "Jetson Xavier", "NVIDIA", "ARM Carmel"} },
{ JETSON_TX2, {1, "8192M", "Unknown", "Jetson TX2", "NVIDIA", "ARM A57 + Denver"} },
{ JETSON_TX1, {1, "4096M", "Unknown", "Jetson TX1", "NVIDIA", "ARM A57"} },
{ JETSON_NANO, {1, "4096M", "Unknown", "Jetson nano", "NVIDIA", "ARM A57"} }
}
{};
static bool ids_warned = false;
PinData get_data()
{
try
{
EntirePinData& _DATA = EntirePinData::get_instance();
const string compatible_path = "/proc/device-tree/compatible";
const string ids_path = "/proc/device-tree/chosen/plugin-manager/ids";
set<string> compatibles{};
{ // scope for f:
ifstream f(compatible_path);
stringstream buffer{};
buffer << f.rdbuf();
string tmp_str = buffer.str();
vector<string> _vec_compatibles(split(tmp_str, '\x00'));
// convert to std::set
copy(_vec_compatibles.begin(), _vec_compatibles.end(), inserter(compatibles, compatibles.end()));
} // scope ends
auto matches = [&compatibles](const vector<string>& vals)
{
for(const auto& v : vals)
{
if(is_in(v, compatibles))
return true;
}
return false;
};
auto find_pmgr_board = [&](const string& prefix) -> string
{
if (!os_path_exists(ids_path))
{
if (ids_warned == false)
{
ids_warned = true;
string msg = "WARNING: Plugin manager information missing from device tree.\n"
"WARNING: Cannot determine whether the expected Jetson board is present.";
cerr << msg;
}
return "None";
}
for (const auto& file : os_listdir(ids_path))
{
if (startswith(file, prefix))
return file;
}
return "None";
};
auto warn_if_not_carrier_board = [&find_pmgr_board](const vector<string>& carrier_boards)
{
auto found = false;
for (auto&& b : carrier_boards)
{
found = !is_None(find_pmgr_board(b + "-"s));
if (found)
break;
}
if (found == false)
{
string msg = "WARNING: Carrier board is not from a Jetson Developer Kit.\n"
"WARNNIG: Jetson.GPIO library has not been verified with this carrier board,\n"
"WARNING: and in fact is unlikely to work correctly.";
cerr << msg << endl;
}
};
Model model{};
if (matches(_DATA.compats_tx1))
{
model = JETSON_TX1;
warn_if_not_carrier_board({"2597"s});
}
else if (matches(_DATA.compats_tx2))
{
model = JETSON_TX2;
warn_if_not_carrier_board({"2597"s});
}
else if (matches(_DATA.compats_clara_agx_xavier))
{
model = CLARA_AGX_XAVIER;
warn_if_not_carrier_board({"3900"s});
}
else if (matches(_DATA.compats_xavier))
{
model = JETSON_XAVIER;
warn_if_not_carrier_board({"2822"s});
}
else if (matches(_DATA.compats_nano))
{
model = JETSON_NANO;
string module_id = find_pmgr_board("3448");
if (is_None(module_id))
throw runtime_error("Could not determine Jetson Nano module revision");
string revision = split(module_id, '-').back();
// Revision is an ordered string, not a decimal integer
if (revision < "200")
throw runtime_error("Jetson Nano module revision must be A02 or later");
warn_if_not_carrier_board({"3449"s, "3542"s});
}
else if (matches(_DATA.compats_nx))
{
model = JETSON_NX;
warn_if_not_carrier_board({"3509"s, "3449"s});
}
else
{
throw runtime_error("Could not determine Jetson model");
}
vector<PinDefinition> pin_defs = _DATA.PIN_DEFS_MAP.at(model);
PinInfo jetson_info = _DATA.JETSON_INFO_MAP.at(model);
map<string, string> gpio_chip_dirs{};
map<string, int> gpio_chip_base{};
map<string, string> pwm_dirs{};
vector<string> sysfs_prefixes = { "/sys/devices/", "/sys/devices/platform/" };
// Get the gpiochip offsets
set<string> gpio_chip_names{};
for (const auto& pin_def : pin_defs)
{
if(!is_None(pin_def.SysfsDir))
gpio_chip_names.insert(pin_def.SysfsDir);
}
for (const auto& gpio_chip_name : gpio_chip_names)
{
string gpio_chip_dir = "None";
for (const auto& prefix : sysfs_prefixes)
{
auto d = prefix + gpio_chip_name;
if(os_path_isdir(d))
{
gpio_chip_dir = d;
break;
}
}
if (is_None(gpio_chip_dir))
throw runtime_error("Cannot find GPIO chip " + gpio_chip_name);
gpio_chip_dirs[gpio_chip_name] = gpio_chip_dir;
string gpio_chip_gpio_dir = gpio_chip_dir + "/gpio";
auto files = os_listdir(gpio_chip_gpio_dir);
for (const auto& fn : files)
{
if (!startswith(fn, "gpiochip"))
continue;
string gpiochip_fn = gpio_chip_gpio_dir + "/" + fn + "/base";
{ // scope for f
ifstream f(gpiochip_fn);
stringstream buffer;
buffer << f.rdbuf();
gpio_chip_base[gpio_chip_name] = stoi(strip(buffer.str()));
break;
} // scope ends
}
}
auto global_gpio_id = [&gpio_chip_base](string gpio_chip_name, int chip_relative_id) -> int
{
if (is_None(gpio_chip_name) ||
!is_in(gpio_chip_name, gpio_chip_base) ||
chip_relative_id == -1)
return -1;
return gpio_chip_base[gpio_chip_name] + chip_relative_id;
};
set<string> pwm_chip_names{};
for(const auto& x : pin_defs)
{
if(!is_None(x.PWMSysfsDir))
pwm_chip_names.insert(x.PWMSysfsDir);
}
for(const auto& pwm_chip_name : pwm_chip_names)
{
string pwm_chip_dir = "None";
for (const auto& prefix : sysfs_prefixes)
{
auto d = prefix + pwm_chip_name;
if(os_path_isdir(d))
{
pwm_chip_dir = d;
break;
}
}
/* Some PWM controllers aren't enabled in all versions of the DT. In
this case, just hide the PWM function on this pin, but let all other
aspects of the library continue to work. */
if (is_None(pwm_chip_dir))
continue;
auto chip_pwm_dir = pwm_chip_dir + "/pwm";
if (!os_path_exists(chip_pwm_dir))
continue;
for (const auto& fn : os_listdir(chip_pwm_dir))
{
if (!startswith(fn, "pwmchip"))
continue;
string chip_pwm_pwmchip_dir = chip_pwm_dir + "/" + fn;
pwm_dirs[pwm_chip_name] = chip_pwm_pwmchip_dir;
break;
}
}
auto model_data = [&global_gpio_id, &pwm_dirs, &gpio_chip_dirs]
(NumberingModes key, const auto& pin_defs)
{
auto get_or = [](const auto& dictionary, const string& x, const string& defaultValue) -> string
{
return is_in(x, dictionary) ? dictionary.at(x) : defaultValue;
};
map<string, ChannelInfo> ret{};
for (const auto& x : pin_defs)
{
string pinName = x.PinName(key);
if(!is_in(x.SysfsDir, gpio_chip_dirs))
throw std::runtime_error("[model_data]"s + x.SysfsDir + " is not in gpio_chip_dirs"s);
ret.insert(
{
pinName,
ChannelInfo
{
pinName,
gpio_chip_dirs.at(x.SysfsDir),
x.LinuxPin,
global_gpio_id(x.SysfsDir, x.LinuxPin),
get_or(pwm_dirs, x.PWMSysfsDir, "None"),
x.PWMID
}
}
);
}
return ret;
};
map<NumberingModes, map<string, ChannelInfo>> channel_data =
{
{ BOARD, model_data(BOARD, pin_defs) },
{ BCM, model_data(BCM, pin_defs) },
{ CVM, model_data(CVM, pin_defs) },
{ TEGRA_SOC, model_data(TEGRA_SOC, pin_defs) }
};
return {model, jetson_info, channel_data};
}
catch(exception& e)
{
cerr << "[Exception] " << e.what() << " (catched from: get_data())" << endl;
throw false;
}
}
| 6dc2a05f6da30cdf5c8fdad74d32c30b94f4358e | [
"Markdown",
"Makefile",
"C++"
]
| 6 | Makefile | DiamondSheep/JetsonGPIO | ea6815cd2af9454a7c4927843882cd65ce821dc1 | 8d9f484446d99b9c86a18197c732a537bee6db1c |
refs/heads/master | <file_sep>import re
# 打开文件并读取内容
with open(r'C:\Users\lenovo-pc\Desktop\婷婷的Twitter 1-72.txt', 'r', encoding='UTF-8') as file:
content = file.read()
# 使用正则表达式去除多余的换行符和空格
content = re.sub(r'\n+', '\n', content)
content = re.sub(r' +', ' ', content)
# 将文本按照段落划分
paragraphs = content.split('\n\n')
# 对每个段落进行处理
for i in range(len(paragraphs)):
# 去除段落中的多余空格和换行符
paragraphs[i] = paragraphs[i].strip()
# 将段落中的多余空格替换为一个空格
paragraphs[i] = re.sub(r' +', ' ', paragraphs[i])
# 将处理后的文本写入新文件
with open('output.txt', 'w') as file:
file.write('\n\n'.join(paragraphs))
<file_sep>import os
import chardet
import zhconv
def detect_file_encoding(file_path):
"""
判断文件的编码格式
UTF-8-SIG
UTF-8
GB2313
"""
file = open(file_path, 'rb')
# 根据二进制信息判断编码{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}
result = chardet.detect(file.read())['encoding']
# chardet 默认为GB2313,实则不然,需要手工改为GBK,保证文档内容不发生篡改,已遇到'肏' '吋'等变为乱码
if result == 'GB2312':
result = 'GBK'
return result
def process_content(content):
lines = content.split('\n')
# print(lines)
new_lines = []
for line in lines:
# print(line)
line = line.strip() # 去除行末换行符
if line: # 如果该行非空
# zh - cn
# 大陆简体
# zh - sg
# 马新简体(马来西亚和新加坡使用的简体汉字)
# zh - tw
# 台灣正體(台湾正体)
# zh - hk
# 香港繁體(香港繁体)
# zh - hans 简体
# line = zhconv.convert(line, 'zh-cn')
# print(line)
new_lines.append(line + '\n\n') # 写入该行并加上换行符
# last_line_empty = False # 标记上一行不为空行
# elif not last_line_empty: # 如果该行为空行且上一行不为空行
# new_lines.append('\n') # 写入一个空行
# last_line_empty = True # 标记上一行为空行
# 去除每行行首空格并添加四个空格
new_lines = [' ' * 4 + line.lstrip() if line.strip() else line for line in new_lines]
return ''.join(new_lines)
# 定义需要处理的文件夹路径
folder_path = r'D:\PYcode\wwww\test'
# 遍历文件夹下所有txt文件并处理
for file_name in os.listdir(folder_path):
if file_name.endswith('.txt'):
# 定义需要处理的文件路径
file_path = os.path.join(folder_path, file_name)
# 获取文件编码格式
file_encoding = detect_file_encoding(file_path)
print(file_name + ":")
print(file_encoding)
# 定义要写入的临时文件路径
temp_path = os.path.join(folder_path, 'temp.txt')
# 打开文件并按行读取内容
# with open(file_path, 'r', encoding='UTF-8-SIG', errors='ignore') as f1, open(temp_path, 'w', encoding='utf-8') as f2:
with open(file_path, 'r', encoding=file_encoding, errors='ignore') as f1, open(temp_path, 'w', encoding='utf-8') as f2:
content = f1.read()
output_content = process_content(content)
output_content = output_content.replace('[各种丝袜美腿,呦呦少妇,SM重口味,空姐嫩模,直播做爱,一有尽有]', '')
output_content = output_content.replace('– 黑沼泽俱乐部', '')
output_content = output_content.replace('– 蔷薇后花园', '')
output_content = output_content.replace('@@', '')
f2.write(output_content)
# 删除原文件
os.remove(file_path)
# 将临时文件重命名为原文件
os.rename(temp_path, file_path)
<file_sep>import time
import threading
from queue import Queue
time_start = time.time()
queue1 = Queue()
for i in range(20000):
queue1.put(i)
# print(queue1.queue)
def print_num(num: Queue) -> None:
while num.qsize() > 0:
print("现在输出" + str(num.get()))
def start() -> None:
thread1 = threading.Thread(name='t1', target= print_num, args=(queue1, ))
# thread2 = threading.Thread(name='t2', target= print_num, args=(queue1, ))
# thread3 = threading.Thread(name='t3', target= print_num, args=(queue1, ))
# 启动线程1
thread1.start()
# thread2.start()
# thread3.start()
start()
time_end = time.time()
time_sum = time_end - time_start
print(time_sum)
<file_sep>import os
import chardet
def detect_file_encoding(file_path):
"""
判断文件的编码格式
UTF-8-SIG
UTF-8
GB2313
"""
file = open(file_path, 'rb')
# 根据二进制信息判断编码{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}
result = chardet.detect(file.read())['encoding']
# chardet 默认为GB2313,实则不然,需要手工改为GBK,保证文档内容不发生篡改,已遇到'肏' '吋'等变为乱码
if result == 'GB2312':
result = 'GBK'
return result
folder_path = r'C:\Users\lenovo-pc\Desktop\处理1'
target_path = r'C:\Users\lenovo-pc\Desktop\处理2'
for file_name in os.listdir(folder_path):
if file_name.endswith('.txt'):
# 定义需要处理的文件路径
file_path = os.path.join(folder_path, file_name)
target_file = os.path.join(target_path, file_name)
# 获取文件编码格式
file_encoding = detect_file_encoding(file_path)
with open(file_path, 'r', encoding=file_encoding, errors='ignore') as f1, open(target_file, 'w', encoding='utf-8') as f2:
lines = f1.read().split('\n')
# print(lines)
nextline = lines[0]
for line in lines[1:]:
# print(line)
if line and not line.startswith('\u3000'):
f2.write(''.join(nextline.rsplit()))
nextline = line.lstrip()
else:
f2.write(''.join(nextline) + "\n\n")
nextline = line.lstrip()
f2.close()
print("任务结束! ✿✿ヽ(°▽°)ノ✿")<file_sep>import glob
from os import path
from aip import AipOcr
# def get_Same_Image(image):
# # size = (489, 113)
# return image.convert('RGB')
#
#
# def store_pic(img, name):
# img.save(name)
#
#
#
# def difference(list1, list2):
# sum1 = 0
# for i in range(len(list1)):
# if list1[i] == list2[i]:
# sum1 += 1
# else:
# # 照公式可获得
# sum1 += 1-(abs(list1[i] - list2[i]) / max(list1[i], list2[i]))
# return sum1 / len(list1)
#
#
# def Get_Similarity(image1, image2):
# # 统一格式
# img1 = get_Same_Image(image1)
# img2 = get_Same_Image(image2)
# # 获得直方图
# list1 = img1.histogram()
# list2 = img2.histogram()
# return difference(list1, list2)
#
#
# t = (383, 138, 470, 165)
# pyautogui.click(x=1277, y=11)
# time.sleep(1)
# n = 5
# pyautogui.click(x=670, y=280)
# while n < 10:
# time.sleep(1)
# img = ImageGrab.grab(t)
# img.save('D:\PYcode\old_pic\\' + str(n) +'.jpg')
# pyautogui.click(x=600, y=690)
# n = n + 1
# pyautogui.click(x=920, y=300)
#
# a = Image.open("D:\\PYcode\\old_pic\\2.jpg")
# b = Image.open("D:\\PYcode\\old_pic\\0.jpg")
# c = Image.open("D:\\PYcode\\old_pic\\3.jpg")
# d = Image.open("D:\\PYcode\\old_pic\\zijin.jpg")
# # print((Get_Similarity(a, d)))
# # print((Get_Similarity(d, c)))
# # print((Get_Similarity(b, d)))
#
# # string = pytesseract.image_to_string(a, lang='chi_sim')
# # print(string)
# # string = pytesseract.image_to_string(c, lang='chi_sim')
# # print(string)
# # string = pytesseract.image_to_string(d, lang='chi_sim')
# # print(string)
#
#
#
# def matchImg(imgsrc, imgobj, value):#imgsrc=原始图像,imgobj=待查找的图片
# imsrc = ac.imread(imgsrc)
# imobj = ac.imread(imgobj)
#
# match_result = ac.find_template(imsrc, imobj,value) # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
# if match_result is not None:
# match_result['shape']=(imsrc.shape[1], imsrc.shape[0]) # 0为高,1为宽
#
# return match_result
# # 图像识别启动模拟器
# weituo_old = Image.open("D:\\PYcode\\old_pic\\moniqi.png")
# quanping = (0, 0, 1365, 726)
# quanping_img = ImageGrab.grab(quanping)
# t = time.strftime('%Y%m%d_%H%M%S', time.localtime())
# name = 'D:\\PYcode\\new_pic\\' + 'zhuomian_' + t +'.jpg'
# quanping_img.save(name)
# position = matchImg(name, "D:\\PYcode\\old_pic\\moniqi.png", 0.01)
# print (position)
# if position != None:
# x, y = position['result']
# print(x, y)
# pyautogui.click(x=x, y=y, clicks=2, interval=0.1)
def baiduOCR(outfile):
"""利用百度api识别文本,并保存提取的文字
picfile: 图片文件名
outfile: 输出文件
"""
filename = path.basename(picfile)
APP_ID = '25680730'
API_KEY = 'oEyoYzFPwlUMFiibBcGDBv3l'
SECRET_KEY = '<KEY>'
client = AipOcr(APP_ID, API_KEY,SECRET_KEY)
i = open(picfile, 'rb')
img = i.read()
print("正在识别图片:\t" + filename)
# message = client.basicGeneral(img) # 通用文字识别,每天 50 000 次免费
message = client.basicAccurate(img) # 通用文字高精度识别,每天 500 次免费
print("识别成功!")
i.close()
with open(outfile, 'a+',encoding='utf-8') as fo:
fo.writelines("+" * 60 + '\n')
fo.writelines("识别图片:\t" + filename + "\n" * 2)
fo.writelines("文本内容:\n")
# 输出文本内容
for text in message.get('words_result'):
fo.writelines(text.get('words') + '\n')
fo.writelines('\n' * 2)
print("文本导出成功!")
print()
if __name__ == "__main__":
open('result.txt', 'a+',encoding='utf-8').close()
outfile = 'result.txt'
for picfile in glob.glob("C:\\Users\\lenovo-pc\\Desktop\\微信图片_20220406164116.jpg"):
baiduOCR(outfile)
print('图片文本提取结束!文本输出结果位于 %s 文件中。' % outfile)
# # Hash值对比
#
# def cmpHash(hash1, hash2, shape=(10, 10)):
# n = 0
# # hash长度不同则返回-1代表传参出错
# if len(hash1) != len(hash2):
# return -1
# # 遍历判断
# for i in range(len(hash1)):
# # 相等则n计数+1,n最终为相似度
# if hash1[i] == hash2[i]:
# n = n + 1
# return n/(shape[0]*shape[1])
#
#
# # 均值哈希算法
# def aHash(img, shape=(10, 10)):
# # 缩放为10*10
# img = cv2.resize(img, shape)
# # 转换为灰度图
# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# # s为像素和初值为0,hash_str为hash值初值为''
# s = 0
# hash_str = ''
# # 遍历累加求像素和
# for i in range(shape[0]):
# for j in range(shape[1]):
# s = s + gray[i, j]
# # 求平均灰度
# avg = s / 100
# # 灰度大于平均值为1相反为0生成图片的hash值
# for i in range(shape[0]):
# for j in range(shape[1]):
# if gray[i, j] > avg:
# hash_str = hash_str + '1'
# else:
# hash_str = hash_str + '0'
# return hash_str
#
#
# def main():
# # t = (383, 138, 470, 165)
# # n = 3
# # img = "D:\\PYcode\\old_pic\\" + str(n) + ".jpg"
# img1 = cv2.imread("D:\\PYcode\\new_pic\\keyan_20220318_125123.png")
# img2 = cv2.imread("D:\\PYcode\\para_pic\\keyanxiangmu_20220318_121033.png")
# img3 = cv2.imread("D:\\PYcode\\old_pic\\zhanshuqianwang.png")
# img_zijin = cv2.imread("D:\\PYcode\\old_pic\\zijin.jpg")
# # img_test = cv2.imread("D:\\PYcode\\new_pic\\keyan_20220316_190832.png")
# # img4 = cv2.imread("D:\\PYcode\\para_pic\\zhanshujiaocheng_20220316_190218.png")
# # 使用两个变量,1记录五个科研任务 2 保存图片的数量 break跳出while循环
# hash1 = aHash(img1)
# hash2 = aHash(img2)
# hash3 = aHash(img3)
# # hash4 = aHash(img4)
# hash_zijin = aHash(img_zijin)
# # hash_test = aHash(img_test)
# n1 = cmpHash(hash1, hash2)
# n2 = cmpHash(hash1, hash3)
# n3 = cmpHash(hash2, hash3)
# # n_test = cmpHash(hash4, hash_test)
# print('均值哈希算法相似度:', n1)
# # print('均值哈希算法相似度:', n2)
# # print('均值哈希算法相似度:', n3)
# # 前往按钮相似度最大为0.76 暂定为0.78
# # 科研类型 0.9
# if __name__=="__main__":
# main()
#
# def get_Same_Image(image):
# # size = (489, 113)
# return image.convert('RGB')
#
#
# def difference(list1, list2):
# sum1 = 0
# for i in range(len(list1)):
# if list1[i] == list2[i]:
# sum1 += 1
# else:
# # 照公式可获得
# sum1 += 1-(abs(list1[i] - list2[i]) / max(list1[i], list2[i]))
# return sum1 / len(list1)
#
#
# def Get_Similarity(image1, image2):
# # 统一格式
# img1 = get_Same_Image(image1)
# img2 = get_Same_Image(image2)
# # 获得直方图
# list1 = img1.histogram()
# list2 = img2.histogram()
# return difference(list1, list2)
# os.makedirs("D:\\PYcode\\old_pic2")
# os.rmdir("D:\\PYcode\\old_pic2")
# def zdy(a):
# m = a + 3
# n = 4
# if m < n:
# print("wwwww")
# return
# else:
# print("wh")
# print("wwwwwxxxxx")
# print("zdydsb")
#
# zdy(0)
# zdy(4)
<file_sep>import os
import re
# def count_num(a: list) -> int:
# return len(a)
#
# def test_count():
# assert count_num([1, 2, 3]) != 3
# os.system("taskkill /F /IM NemuPlayer.exe")
# python 字符串类型转换
# a = 1234656
# c = str(a)
# for i in c:
# print(i + " ")
#
# b = "000001"
# # 输出 1
# print(int(b))
# python字符串分割
# s = "Hello, world! 你 好:世:界!"
# result = re.split(r'[ \u3000::]+', s)
# print(result)
import time
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
driver = webdriver.Chrome()
max_retry = 10
for i in range(max_retry):
try:
driver.get('https://alhs.xyz/index.php/archives/2023/02/53057/')
except WebDriverException as e:
print(f"第{i+1}次访问网页出错,错误信息:{e}")
time.sleep(5) # 设置重试间隔时间为5秒
continue
else:
break
# 这里进行页面操作
driver.quit()<file_sep># import chardet
#
# with open('艾拉系列外传 强制改造学院上篇.txt', 'rb') as f:
# content = f.read()
# result = chardet.detect(content)
# encoding = result['encoding']
# print(encoding)
# with open('艾拉系列外传 强制改造学院上篇.txt', 'r', encoding='utf-8') as f:
# content = f.read()
# # 将 UTF-8 编码的字符串转换成 GBK 编码的字符串
# gbk_content = content.encode('gbk')
#
# with open('example.txt', 'w', encoding='gbk') as f:
# f.write(gbk_content.decode('gbk'))
# print('鍝'.encode('GBK').decode('utf-8'))
# b = '哦'.encode('utf-8').decode('ISO-8859-1')
# print(b.encode('utf-8'))
# a = '鍝'.encode('GBK').decode('ISO-8859-1')
# print(a.encode('utf-8'))
# import ftfy
# import os
# import codecs
# # 打开GBK编码的文件
# with codecs.open('D:\\PYcode\\wwww\\【转载】穿越SP异世界.txt', 'r', encoding='utf-8', errors='ignore') as f1:
# # 读取文件内容
# content = f1.read()
# # 使用ftfy修复编码问题
# fixed_data = ftfy.fix_encoding(content)
# # 以UTF-8编码格式打开文件,写入修改后的内容
# with codecs.open('D:\\PYcode\\wwww\\example_utf8.txt', 'w', encoding='utf-8') as f2:
# f2.write(fixed_data)
# print('https://alhs.xyz/index.php/archives/2022/10/46233/'.rsplit('/', 8)[-2])
# 网址分割排序
# links = [
# 'https://alhs.xyz/index.php/archives/2022/12/46457/',
# 'https://alhs.xyz/index.php/archives/2022/10/46467/',
# 'https://alhs.xyz/index.php/archives/2022/10/46304/',
# 'https://alhs.xyz/index.php/archives/2022/10/46305/',
# 'https://alhs.xyz/index.php/archives/2022/10/46315/',
# 'https://alhs.xyz/index.php/archives/2022/10/46271/',
# 'https://alhs.xyz/index.php/archives/2022/10/46244/',
# 'https://alhs.xyz/index.php/archives/2022/10/46233/'
# ]
#
# # 按照最后两个/之间的数字大小排序
# sorted_links = sorted(links, key=lambda x: int(x.rsplit('/', 8)[-2]))
#
# # 打印排序结果
# print(sorted_links)
# 一行TXT长度计算
str_line = "2222222222222222222222222222222222222222222222222222222222222222222222 "
# 长度 70
str2 = " “是啊,都快过年了,冬天都要结束了,超冷的呢”身旁躺着的一位黑色长发的少女回答着她的话"
print(len(str2))
sis_line = " 其实,要不是这个系统的操纵者,那些背后的神绝对的禁止他就这样自我催 "
print(len(sis_line)) # 36 大于37即可<file_sep>import multiprocessing
import time
from multiprocessing import Queue
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
import re
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
options = webdriver.ChromeOptions()
# options.binary_location = r"E:\工具\翻墙\Chrome109_AllNew_2023.2.13\App\chrome.exe" # 这里是360安全浏览器的路径
# options.add_argument(r'--lang=zh-CN') # 这里添加一些启动的参数
options.add_argument('--ignore -ssl-errors')
options.add_argument('--ignore-certificate-errors')
options.add_argument('--disable-gpu') # 禁用GPU加速
options.add_argument('--disable-dev-shm-usage') # 禁用/dev/shm使用
options.add_argument('--disable-extensions') # 禁用扩展
# options.add_argument('--headless') # 不开启网页
options.add_argument('--disable-javascript') # 禁用JavaScript
options.add_argument('--blink-settings=imagesEnabled=false') # 禁用加载图片
# browser = webdriver.Chrome(options=options, executable_path="E:\工具\翻墙\chromedriver109")
browser = webdriver.Chrome(options=options)
class MultProcess(multiprocessing.Process):
def __init__(self, que: Queue):
multiprocessing.Process.__init__(self)
self.que = que
@staticmethod
def downloadFirstPage(page_url):
retry(page_url)
try:
# 查找id为"example"的元素
element = browser.find_element(By.CLASS_NAME, "post-series-title")
# print("222" + str(element))
except NoSuchElementException:
# 如果找不到该元素,则执行此处的代码
# print("元素不存在")
pagename = browser.find_element(By.CLASS_NAME, "post-title").text
print("开始下载url:" + page_url)
print("文章标题:" + pagename)
filename = FileName(pagename) + '.txt'
# pages = browser.find_elements(By.XPATH, '/html/body/div[6]/div[5]/main/article/div[1]/p')
pages = browser.find_elements(By.XPATH, '//*[@id="post_content"]/p ')
# | //*[@id="post_content"]/div[1]/div 用于早期文档
# print("123456" + str(pages))
with open(filename, mode='w', encoding='utf-8') as ft:
ft.write(pagename + "\n\n\n")
for i in pages:
str_2 = i.get_attribute('innerText')
ft.write("\n\n")
ft.write(" " + str_2)
ft.close()
else:
# 如果找到了该元素,则执行此处的代码
# print("元素存在")
pagename = element.text.split(':', 1)[1]
print("开始下载url:" + page_url)
print("文章标题:" + pagename)
filename = FileName(pagename) + '.txt'
seriesHrefPages = browser.find_elements(By.XPATH, '//*[@id="post_content"]/section/ul/li[*]/span/a')
# print(seriesHrefPages)
hrefList = [browser.current_url]
for i in seriesHrefPages:
# print(i.get_attribute('href'))
hrefList.append(i.get_attribute('href'))
# hrefList.sort()
sorted_links = sorted(hrefList, key=lambda x: int(x.rsplit('/', 8)[-2]))
# print(sorted_links)
retry(sorted_links[0])
pages = browser.find_elements(By.XPATH, '//*[@id="post_content"]/p')
# menu = browser.find_element(By.CLASS_NAME, 'post-series-list')
with open(filename, mode='w', encoding='utf-8') as ft:
ft.write(pagename + "\n\n\n")
ft.write(" " + "目录\n\n")
menuList = browser.find_elements(By.XPATH, '//*[@id="post_content"]/section/ul/li[*]/span')
for t in menuList:
ft.write(" " + t.get_attribute('innerText') + "\n\n")
ft.write("\n\n\n")
ft.write("----------------------------------------------------------------\n")
title = browser.find_element(By.CLASS_NAME, "post-title").text
ft.write(" " + title)
for i in pages:
str_2 = i.get_attribute('innerText')
ft.write("\n\n")
ft.write(" " + str_2)
ft.close()
for hrefs in sorted_links[1:]:
retry(hrefs)
print("开始下载url:" + hrefs)
pages = browser.find_elements(By.XPATH, '//*[@id="post_content"]/p')
with open(filename, mode='a+', encoding='utf-8') as ft:
title = browser.find_element(By.CLASS_NAME, "post-title").text
ft.write("\n\n\n" + " " + title)
for i in pages:
str_2 = i.get_attribute('innerText')
ft.write("\n\n")
ft.write(" " + str_2)
ft.close()
def run(self):
while not self.que.empty():
# print(self.Que.get(), os.getpid())
MultProcess.downloadFirstPage(self.que.get())
# browser.quit()
def retry(target_url):
max_retry = 120
for i in range(max_retry):
try:
browser.get(target_url)
except WebDriverException as e:
# print(f"第{i + 1}次访问网页出错,错误信息:{e}")
time.sleep(8) # 设置重试间隔时间为x秒
continue
else:
break
def FileName(name):
for i, j in ("//", "\\\", "??", "|︱", "\""", "**", "<<", ">>"):
name = name.replace(i, j)
return name
if __name__ == '__main__':
# 正则表达式判断一个字符串以http或https开头,有且只有一个http或https
pattern = r'^(https?)(?:://)(?!.*?\1.*?:).*?$'
queue1 = Queue()
list2 = []
with open("D:\\PYcode\\wwww\\alhs_url.txt", mode = 'r', encoding='utf-8') as f:
for line in f:
line = line.replace("\n", "")
if re.match(pattern, line):
queue1.put(line)
# print(line)
else:
list2.append(line)
# print("2:" + line)
f.close()
p = MultProcess(queue1)
w = MultProcess(queue1)
e = MultProcess(queue1)
p.start()
w.start()
e.start()
p.join()
w.join()
e.join()
if len(list2) != 0:
print(list2)
# browser.quit()
print("工作完成!✿✿ヽ(°▽°)ノ✿")<file_sep>from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import os
def login():
browser.get("https://houhuayuan.vip")
try:
browser.find_element(By.ID, "user_login").send_keys("<PASSWORD>")
except Exception:
print('输入用户名失败')
else:
print('输入用户名成功')
try:
browser.find_element(By.ID, "user_pass").send_keys("<PASSWORD>")
except Exception:
print('输入密码失败')
else:
print('输入密码成功')
browser.find_element(By.NAME, "wp-submit").click()
def main():
login()
url_base = "https://houhuayuan.vip/wp-admin/edit.php?post_status=publish&post_type=post&paged="
n = 2
with open("D:\\PYcode\\wwww\\zhaoze_url.txt",mode = 'a+',encoding='utf-8') as f:
while(n < 114):
url = url_base + str(n)
browser.get(url)
for i in range(1, 21):
name_xpath = "/html/body/div/div[2]/div[2]/div[1]/div[3]/form[1]/table/tbody/tr["+str(i)+"]/td[1]/strong/span"
href_xpath = "/html/body/div/div[2]/div[2]/div[1]/div[3]/form[1]/table/tbody/tr["+str(i)+"]/td[1]/div/span/a"
name = browser.find_element(By.XPATH, name_xpath)
href = browser.find_element(By.XPATH, href_xpath)
f.write(name.get_attribute('innerText') + ":")
f.write("\n")
f.write(href.get_attribute('href'))
f.write("\n")
n = n +1
f.close()
if __name__ == "__main__":
options = webdriver.ChromeOptions()
options.add_argument('-ignore-certificate-errors')
# options.add_argument('-ignore -ssl-errors')
# options.add_argument('-disable-software-rasterizer')
browser = webdriver.Chrome(options=options)
main()
browser.quit()
<file_sep>import os
# if len(sys.argv) != 1:
# num = 100
# else:
# num = int(sys.argv[1])
num = 100
for i in range(0, num):
command = 'adb shell input tap 540 1080' # 点击屏幕上录音按钮处
os.system(command)
# time.sleep(0.02)
i = i + 1
<file_sep># coding = utf-8
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
def qiandao(name, password):
print('启动自动签到')
browser = webdriver.Chrome()
try:
time.sleep(1)
browser.get("https://www.s70m.com/index.php")
except Exception:
print('启动浏览器插件失败')
else:
print('启动浏览器插件成功')
try:
browser.find_element(By.NAME, "pwuser").send_keys(name)
except Exception:
print('输入用户名失败')
else:
print('输入用户名成功')
try:
browser.find_element(By.NAME, "pwpwd").send_keys(password)
except Exception:
print('输入密码失败')
else:
print('输入密码成功')
try:
time.sleep(1)
browser.find_element(By.NAME, "cktime").click()
except Exception:
print('启动记住密码失败')
else:
print('启动记住密码成功')
try:
time.sleep(1)
browser.find_element(By.NAME, "head_login").click()
except Exception:
print('登录失败')
else:
print('登录成功')
try:
time.sleep(3)
browser.refresh()
except Exception:
print('刷新失败')
else:
print('刷新成功')
try:
time.sleep(1)
browser.find_element(By.ID, "td_userinfomore").click()
except Exception:
print('进入个人信息失败')
else:
print('进入个人信息成功')
try:
time.sleep(1)
browser.find_element(By.ID, "punch").click()
except Exception:
print('签到失败')
else:
print('签到成功')
print('自动签到结束')
browser.quit()
return
def main():
qiandao("w1g2f3", "w@123456")
return
if __name__ == '__main__':
main()
<file_sep>import multiprocessing
import time
from multiprocessing import Queue
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
options = webdriver.ChromeOptions()
options.add_argument('-ignore-certificate-errors')
browser = webdriver.Chrome(options=options)
class MultProcess(multiprocessing.Process):
def __init__(self, Que: Queue):
multiprocessing.Process.__init__(self)
self.Que = Que
def run(self):
while not self.Que.empty():
# print(self.Que.get(), os.getpid())
browser.get(self.Que.get())
if __name__ == '__main__':
time_start = time.time()
queue1 = Queue()
# for i in range(2000):
# queue1.put(i)
queue1.put("https://www.baidu.com/")
queue1.put("http://www.cctv.com/")
queue1.put("http://www.people.com.cn/")
queue1.put("https://xiaoyouxi.360.cn/?src=youxi")
queue1.put("https://www.ctrip.com/?allianceid=1328&sid=1643")
queue1.put("https://p4psearch.1688.com/")
queue1.put("https://www.tmall.com/")
queue1.put("https://nj.58.com//")
queue1.put("https://zonghe.hao.360.cn/#cid=youlike?")
p = MultProcess(queue1)
w = MultProcess(queue1)
e = MultProcess(queue1)
p.start()
w.start()
e.start()
# p.join()
# w.join()
# e.join()
time_end = time.time()
print(time_end - time_start)
<file_sep>import os
import shutil
import sys
import time
import aircv as ac
import cv2
import pyautogui
from PIL import ImageGrab
time.sleep(2)
# 最小化编译器
# pyautogui.click(x=1277, y=11)
# 桌面最小化
# pyautogui.click(x=1359, y=755, clicks=2, interval=0.5)
if len(sys.argv) == 1:
num = 10
else:
num = int(sys.argv[1])
# junshiweituo = (76, 247, 567, 363)
junshiweituo = (270, 247, 420, 363)
zhanshujiaocheng = (78, 380, 567, 493)
keyanxiangmu = (270, 516, 420, 629)
weituo_last = (243, 538, 1225, 687)
keyanleixing = (383, 138, 470, 165)
quanping = (0, 0, 1365, 726)
weituo_quanping = (0, 0, 567, 363)
richang = (0, 0, 200, 767)
keyan_small = (0, 516, 567, 629)
weituo_small = (0, 247, 567, 363)
moniqi_guanggao = (70, 40, 1300, 725)
path_new = "D:\\PYcode\\new_pic\\"
path_pre = "D:\\PYcode\\para_pic\\"
img_zijin = cv2.imread("D:\\PYcode\\old_pic\\zijin.jpg")
img_dingxiang = cv2.imread("D:\\PYcode\\old_pic\\dingxiang.jpg")
img_jianzhuangjiexi = cv2.imread("D:\\PYcode\\old_pic\\jianzhuangjiexi.jpg")
img_jichuyanjiu = cv2.imread("D:\\PYcode\\old_pic\\jichuyanjiu.jpg")
img_mofang = cv2.imread("D:\\PYcode\\old_pic\\mofang.jpg")
img_shiyanpin = cv2.imread("D:\\PYcode\\old_pic\\shiyanpin.jpg")
img_yanjiuweituo = cv2.imread("D:\\PYcode\\old_pic\\yanjiuweituo.jpg")
# global name_weituo
# global name_zhanshu
# global name_keyan
# name_weituo = "D:\\PYcode\\para_pic\\weituo_20220316_190209.png"
# name_keyan = "D:\\PYcode\\para_pic\\zhanshujiaocheng_20220316_190218.png"
def restart():
exit_mnq()
time.sleep(60)
main()
def check():
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " " + "开始检查")
num1 = prepare_hash("D:\\PYcode\\old_pic\\weituo_check.png", name_weituo)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 相似度:" + str(num1))
if num1 < 0.55:
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " " + "重新启动程序")
restart()
# 模拟器最大化情况下效果最好
def day_mask():
time.sleep(1)
# if :
difference_pic(quanping, 'D:\\PYcode\\weituo\\', 'richang_', 'D:\\PYcode\\old_pic\\queding.png', 0.95,
"重新连接", "不需要重新连接,请忽略", 1, 0.1, 0, 10)
difference_pic(quanping, 'D:\\PYcode\\weituo\\', 'richang_', 'D:\\PYcode\\old_pic\\richang.png', 0.55,
"打开日常栏", "未找到日常栏,请检查。", 1, 0.1, 0, 1)
def exit_mnq():
# difference_pic(quanping, 'D:\\PYcode\\start_game\\', 'exit_', 'D:\\PYcode\\old_pic\\guanbi_mnq.png', 0.65,
# "点击模拟器关闭", "未找到模拟器关闭键,请检查。", 1, 0.1, 0, 1)
time.sleep(1)
# difference_pic(quanping, 'D:\\PYcode\\start_game\\', 'exit_', 'D:\\PYcode\\old_pic\\tuichu_mnq.png', 0.65,
# "点击模拟器关闭 确定", "未找到模拟器关闭-确定键,请检查。", 1, 0.1, 0, 1)
os.system("taskkill /F /IM NemuPlayer.exe")
def zuotuichu():
time.sleep(1)
difference_pic(quanping, 'D:\\PYcode\\start_game\\', 'zuotuichu_', 'D:\\PYcode\\old_pic\\zuotuichu.png', 0.65,
"点击左返回", "未找到左返回键,请检查。", 1, 0.1, 0, 1)
def youfanhui():
difference_pic(quanping, 'D:\\PYcode\\start_game\\', 'youfanhui_', 'D:\\PYcode\\old_pic\\youfanhui.png', 0.65,
"点击右退出", "未找到右退出键,请检查。", 1, 0.1, 0, 2)
time.sleep(1)
# day_mask()
def start_keyan():
difference_pic(quanping, 'D:\\PYcode\\keyan\\', 'keyan_', 'D:\\PYcode\\old_pic\\kaishiyanfa.png', 0.75,
"点击 开始研发", "未找到 开始研发 按钮,请检查。", 1, 0.2, 0, 1)
difference_pic(quanping, 'D:\\PYcode\\keyan\\', 'queding_', 'D:\\PYcode\\old_pic\\queding.png', 0.75,
"点击 确定按钮", "未找到 确定按钮,请检查。", 1, 0.2, 0, 1)
youfanhui()
day_mask()
def matchImg(imgsrc, imgobj, value): # imgsrc=原始图像,imgobj=待查找的图片
imsrc = ac.imread(imgsrc)
imobj = ac.imread(imgobj)
match_result = ac.find_template(imsrc, imobj, value) # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
if match_result is not None:
match_result['shape'] = (imsrc.shape[1], imsrc.shape[0]) # 0为高,1为宽
return match_result
def rebulid_path(rootdir):
filelist = os.listdir(rootdir)
for f in filelist:
filepath = os.path.join(rootdir, f)
if os.path.isfile(filepath):
os.remove(filepath)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) +" "+filepath+" removed!")
elif os.path.isdir(filepath):
shutil.rmtree(filepath, True)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + "dir"+" "+filepath+" removed!")
# 比较函数,入参依次为 截图区域,保存路径,截图类型,对比图像路径,对比相似度,成功相似输出语句,失败相似输出语句,点击次数,点击间隔,
# 是否退出程序(1退出), 延时时间
def difference_pic(area, path, typ, prepare_pic, value, successful_word, failed_word, cli, inl, code, sleep_tim):
quanping_img = ImageGrab.grab(area)
t = time.strftime('%Y%m%d_%H%M%S', time.localtime())
name = str(path) + str(typ) + t + '.png'
quanping_img.save(name)
position = matchImg(name, prepare_pic, value)
# print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + position)
if position is not None:
x, y = position['result']
# print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + x, y)
pyautogui.click(x=x, y=y, clicks=cli, interval=inl)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " " + successful_word)
time.sleep(sleep_tim)
else:
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " " + failed_word)
if position is None and code == 1:
exit()
# 680 360 66 + 55
def refresh(x, y):
pyautogui.click(x=x, y=y, clicks=1, button = 'right')
time.sleep(2)
pyautogui.click(x=x + 80, y=y + 60, clicks=1)
# 启动网易mumu模拟器,启动时快捷方式图标不可处于被选中状态
def start_moniqi():
# 桌面最小化
time.sleep(1)
pyautogui.hotkey('winleft', 'd')
# pyautogui.click(x=1359, y=755, clicks=2, interval=0.5)
time.sleep(1)
refresh(400, 200)
time.sleep(3)
# difference_pic(quanping, 'D:\\PYcode\\new_pic\\', 'zhuomian_', 'D:\\PYcode\\old_pic\\moniqi.png', 0.65,
# "启动模拟器,时间较长请等待", "错误码 101:没有发现模拟器快捷方式,退出程序。", 2, 0.1, 1, 95)
# 直接调用exe可执行程序
os.startfile(r"D:\z\emulator\nemu\EmulatorShell\NemuLauncher.exe")
time.sleep(105)
def start_game():
# 最大化模拟器
# pyautogui.click(x=15, y=15, clicks=2, interval=0.05)
zuidahua_img = ImageGrab.grab(quanping)
name_zuidahua = 'D:\\PYcode\\start_game\\' + 'qidong_zuidahua_' + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '.png'
zuidahua_img.save(name_zuidahua)
time.sleep(2)
position_zuidahua = matchImg(name_zuidahua, "D:\\PYcode\\old_pic\\zuidahua.png", 0.65)
if position_zuidahua is not None:
x, y = position_zuidahua['result']
# print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + x, y)
pyautogui.click(x=x, y= y, clicks=1)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 最大化模拟器。")
else:
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 最大化模拟器失败!")
exit()
# difference_pic(quanping, 'D:\\PYcode\\start_game\\', 'qidong_guangao_', 'D:\\PYcode\\old_pic\\moniqi_guanggao.png', 0.65,
# "关闭模拟器广告", "今天网易做人啦,没有广告!", 1, 0.1, 0, 5)
guanggao_img = ImageGrab.grab(moniqi_guanggao)
name_guanggao = 'D:\\PYcode\\start_game\\' + 'qidong_guangao_' + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '.png'
guanggao_img.save(name_guanggao)
position = matchImg(name_guanggao, "D:\\PYcode\\old_pic\\moniqi_guanggao.png", 0.65)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 广告关闭键 " + str(position))
if position is not None:
x, y = position['result']
# print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + x, y)
pyautogui.click(x=x + 70, y= y + 40, clicks=1)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 关闭模拟器广告。")
else:
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 今天网易做人啦,没有广告!")
time.sleep(2)
difference_pic(quanping, 'D:\\PYcode\\start_game\\', 'qidong_', 'D:\\PYcode\\old_pic\\bilanhangxian.png', 0.75,
"启动游戏,时间较长请等待", "错误码 102:没有发现游戏快捷方式,退出程序。", 1, 0.1, 1, 75)
pyautogui.click(x=666, y=353, clicks=2, interval=0.5)
time.sleep(15)
pyautogui.click(x=880, y=125)
time.sleep(4)
youfanhui()
time.sleep(6)
difference_pic(quanping, 'D:\\PYcode\\start_game\\', 'qidong_', 'D:\\PYcode\\old_pic\\chacha.png', 0.75,
"关闭每日公告", "非第一次登陆,无需关闭公告。", 1, 0.1, 0, 10)
def prepare():
global name_weituo
global name_zhanshu
global name_keyan
day_mask()
time.sleep(3)
weittuo = ImageGrab.grab(junshiweituo)
name_weituo = path_pre + 'weituo_' + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '.png'
weittuo.save(name_weituo)
time.sleep(2)
# 战术课堂,写不出来
# zhanshu = ImageGrab.grab(zhanshujiaocheng)
# name_zhanshu = path_pre + 'zhanshujiaocheng_' + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '.png'
# zhanshu.save(name_zhanshu)
# time.sleep(2)
# 科研流程,因游戏更新,不需要
# pyautogui.moveTo(x=300, y=450)
# time.sleep(2)
# pyautogui.dragTo(x=300, y=250, duration=0.2)
# time.sleep(2)
# keyan = ImageGrab.grab(keyanxiangmu)
# name_keyan = path_pre + 'keyanxiangmu_' + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '.png'
# keyan.save(name_keyan)
# time.sleep(2)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " " + "准备完成")
# Hash值对比
def cmpHash(hash1, hash2, shape=(10, 10)):
n = 0
# hash长度不同则返回-1代表传参出错
if len(hash1) != len(hash2):
return -1
# 遍历判断
for i in range(len(hash1)):
# 相等则n计数+1,n最终为相似度
if hash1[i] == hash2[i]:
n = n + 1
return n/(shape[0]*shape[1])
# 均值哈希算法
def aHash(img, shape=(10, 10)):
# 缩放为10*10
img = cv2.resize(img, shape)
# 转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# s为像素和初值为0,hash_str为hash值初值为''
s = 0
hash_str = ''
# 遍历累加求像素和
for i in range(shape[0]):
for j in range(shape[1]):
s = s + gray[i, j]
# 求平均灰度
avg = s / 100
# 灰度大于平均值为1相反为0生成图片的hash值
for i in range(shape[0]):
for j in range(shape[1]):
if gray[i, j] > avg:
hash_str = hash_str + '1'
else:
hash_str = hash_str + '0'
return hash_str
def prepare_hash(path1, path2):
img1 = cv2.imread(path1)
img2 = cv2.imread(path2)
hash1 = aHash(img1)
hash2 = aHash(img2)
return cmpHash(hash1, hash2)
def auto_richang_weituo():
pyautogui.click(x=730, y=400)
time.sleep(2)
day_mask()
time.sleep(1)
weittuo = ImageGrab.grab(junshiweituo)
name = path_new + 'weituo_' + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '.png'
weittuo.save(name)
weittuo2 = ImageGrab.grab(weituo_small)
name2 = path_new + 'weituo_small_' + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '.png'
weittuo2.save(name2)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " weittuo " + str(prepare_hash(name, name_weituo)))
position = matchImg(name2, "D:\\PYcode\\old_pic\\weituowancheng.png", 0.75)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " weittuo " + str(position))
# print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " weittuo " + str(position))
if position is not None:
x, y = position['result']
# print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + x, y)
pyautogui.click(x=x, y=y+247, clicks=1)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 完成 委托任务")
time.sleep(1)
pyautogui.click(x=800, y=120, clicks=10, interval=1)
youfanhui()
day_mask()
# else:
# print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 不需要点击完成 委托任务")
# print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " weituo " + str(prepare_hash(name, name_weituo)))
num = 0
while prepare_hash(name, name_weituo) < 0.91:
if num > 3:
# zuotuichu()
# youfanhui()
break
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 委托_循环 " + str(prepare_hash(name, name_weituo)))
difference_pic(weituo_quanping, 'D:\\PYcode\\new_pic\\', 'weituo_all_', 'D:\\PYcode\\old_pic\\weituoqianwang.png', 0.60,
"前往委托", "未找到前往键,请检查。", 1, 0.2, 0, 1)
pyautogui.moveTo(x=760, y=600)
time.sleep(1)
pyautogui.dragTo(x=760, y=300, duration=0.2)
# time.sleep(1)
# img = ImageGrab.grab(weituo_last)
# t = time.strftime('%Y%m%d_%H%M%S', time.localtime())
# img.save('D:\PYcode\history\\' + t + '.jpg')
time.sleep(1)
pyautogui.click(x=760, y=620)
time.sleep(1)
difference_pic(quanping, 'D:\\PYcode\\new_pic\\', 'weituo_', 'D:\\PYcode\\old_pic\\tuijian.png', 0.62,
"开始推荐", "未找到推荐键,请检查。", 1, 0.2, 0, 2)
difference_pic(quanping, 'D:\\PYcode\\new_pic\\', 'weituo_', 'D:\\PYcode\\old_pic\\kaishi.png', 0.62,
"开始委托", "未找到开始键,请检查。", 1, 0.2, 0, 1)
youfanhui()
day_mask()
time.sleep(2)
weittuo = ImageGrab.grab(junshiweituo)
name = path_new + 'weituo_' + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '.png'
weittuo.save(name)
num = num + 1
else:
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 暂无需要处理的任务委托")
weittuo2 = ImageGrab.grab(weituo_small)
name2 = path_new + 'weituo_small_' + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '01.png'
weittuo2.save(name2)
position = matchImg(name2, "D:\\PYcode\\old_pic\\weituoqianwang.png", 0.60)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 前往:" + str(position))
if position is None:
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 发生异常")
return 1
def auto_richang_keyan():
# 使用两个变量,1记录五个科研任务 2 保存图片的数量 break跳出while循环
n = 0
pyautogui.moveTo(x=300, y=450)
time.sleep(2)
pyautogui.dragTo(x=300, y=250, duration=0.2)
time.sleep(2)
keyan_daymask = ImageGrab.grab(keyanxiangmu)
name = path_new + 'keyan_' + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '.png'
keyan_daymask.save(name)
keyan_full = ImageGrab.grab(keyan_small)
name2 = path_new + 'keyan_small_' + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '.png'
keyan_full.save(name2)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " keyan " + str(prepare_hash(name, name_keyan)))
position = matchImg(name2, "D:\\PYcode\\old_pic\\keyanwancheng.png", 0.83)
if position is not None:
x, y = position['result']
# print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + x, y)
pyautogui.click(x=x, y=y+516, clicks=1)
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 完成科研任务")
time.sleep(5)
pyautogui.click(x=x, y=y+516, clicks=2, interval=2)
# elif prepare_hash(name, name_keyan) < 0.95:
# print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + "不需要点击完成科研任务")
# # difference_pic(quanping, 'D:\\PYcode\\new_pic\\', 'keyan_', 'D:\\PYcode\\old_pic\\keyanqianwang.png', 0.65,
# # "开始前往军部研究室", "未找到前往键,请检查。", 1, 0.2, 0, 1)
# pyautogui.click(x = 720, y = 360, clicks = 1)
# difference_pic(quanping, 'D:\\PYcode\\new_pic\\', 'keyan_mneu_', 'D:\\PYcode\\old_pic\\keyancaidan.png', 0.60,
# "开始前往科研菜单", "未找到科研键,请检查。", 1, 1, 0, 2)
# difference_pic(quanping, 'D:\\PYcode\\new_pic\\', 'keyan_mneu_', 'D:\\PYcode\\old_pic\\junbuyanjiushi.png', 0.65,
# "开始前往军部研究室", "未找到军部研究室 图标,请检查。", 1, 1, 0, 2)
# pyautogui.click(x=680, y=380)
# time.sleep(2)
else:
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 科研:本轮无需进行操作")
return
while n < 5:
img = ImageGrab.grab(keyanleixing)
name = 'D:\\PYcode\\new_pic\\xianmu_' + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '.png'
img.save(name)
img_type = cv2.imread(name)
hash_type = aHash(img_type)
# if函数
if cmpHash(hash_type, hash_shiyanpin) > 0.9 or cmpHash(hash_type, hash_jianzhuangjiexi) > 0.9 or cmpHash(hash_type, hash_jichuyanjiu) > 0.9:
start_keyan()
break
# elif cmpHash(hash_type, hash_zijin) > 0.9 or cmpHash(hash_type, hash_dingxiang) > 0.9:
# start_keyan()
# break
else:
pyautogui.click(x=600, y=690)
time.sleep(1)
pyautogui.click(x=920, y=300)
time.sleep(1)
if n == 4:
start_keyan()
time.sleep(1)
n = n + 1
hash_zijin = aHash(img_zijin)
hash_dingxiang = aHash(img_dingxiang)
hash_jianzhuangjiexi = aHash(img_jianzhuangjiexi)
hash_jichuyanjiu = aHash(img_jichuyanjiu)
hash_mofang = aHash(img_mofang)
hash_shiyanpin = aHash(img_shiyanpin)
hash_yanjiuweituo = aHash(img_yanjiuweituo)
def main():
# pyautogui.click(x=1277, y=11)
rebulid_path("D:\\PYcode\\new_pic")
rebulid_path("D:\\PYcode\\start_game")
rebulid_path("D:\\PYcode\\weituo")
rebulid_path("D:\\PYcode\\keyan")
rebulid_path("D:\\PYcode\\para_pic")
start_moniqi()
start_game()
prepare()
# auto_richang_weituo()
# auto_richang_keyan()
# check()
n = 0
tmp1 = 0
while n < num:
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 这是第" + str(n) + "次循环")
status = auto_richang_weituo()
if status == 1:
tmp1 = tmp1 + 1
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 当前异常次数为:" + str(tmp1))
else:
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 标志位重置0。")
tmp1 = 0
if tmp1 > 1:
print(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) + " 存在问题,重启脚本")
restart()
# 蛮啾出了科研队列,不需要自动科研了
# auto_richang_keyan()
n = n + 1
# time.sleep(1860)
time.sleep(570)
exit_mnq()
# 游戏港区默认背景会根据时间变化,影响功能,要么根据时间重新截图,要么使用一个字带背景且非L2D的秘书舰
# 问题已解决。
if __name__ == "__main__":
main()
# position = matchImg("D:\\PYcode\\new_pic\\weituo_20221130_133531.png", "D:\\PYcode\\old_pic\\moniqi_guanggao.png", 0.30)
# n = prepare_hash("D:\\PYcode\\new_pic\\weituo_20220718_040250.png", "D:\\PYcode\\new_pic\\weituo_20220718_041244.png")
# print(position)
# position2 = matchImg("D:\\PYcode\\new_pic\\weituo_small_20221203_13213501.png", "D:\\PYcode\\old_pic\\1670045393363(1).png", 0.30)
# print(position2)
# print(type(position2))
# print(n)
# position_zuidahua = matchImg("D:\\PYcode\\start_game\\123.png", "D:\\PYcode\\old_pic\\zuidahua.png", 0.65)
# print(position_zuidahua)
<file_sep>import requests
from bs4 import BeautifulSoup
# options = webdriver.ChromeOptions()
# options.add_argument('ignore-certificate-errors')
# wd = webdriver.Chrome(options=options)
#
# wd.get('https://154.84.6.38/bbs/viewthread.php?tid=11309743&extra=page%3D1%26amp%3Bfilter%3D0%26amp%3Borderby%3Ddateline%26amp%3Bascdesc%3DDESC')
# pages = wd.find_element(By.TAG_NAME, "em").text
# print(pages)
###################################
# print(1)
# wd.get('https://www.s80m.com/index.php')
# print(2)
# wd.get('https://www.baidu.com')
# print(3)
# 输出为1
# n = 1.9
# print(int(n))
#####################################################
# lang = ["Python", "C++", "Java", "PHP", "Ruby", "MATLAB"]
# del lang[-4: -1]
# del lang[-1]
# print(lang)
# ______________________________________________________#
# 可行,复杂度为n
# with open('textfile.txt') as f1:
# lines = f1.readlines()
#
# with open('textfile.txt', 'w') as f2:
# f2.writelines(lines[:-5])
#####################################################################
# 在文本文件中,若没有使用b模式选项打开的文件,只允许从文件头开始计算相对位置,从文件尾计算时就会引发异常
# file_old = open('D:/PYcode/wwww/遇到的二三事.txt', 'rb+')
# m = 250
#
# # 1.定位文件末尾的前m个字符的位置,大小可根据每一行的字符数量修改,为一估计值,但不能超过文件总字符数
# # 若要删除最后一行,要确保m比最后一行的字符数大
# # 若要删除后N行,要确保后N行的总字符数比m小
# # 若文件很小或无法大体估计每一行的字符数,可以删除这行代码
# file_old.seek(-m, os.SEEK_END)
#
# # 2.从步骤1定位的位置开始读取接下来的每一行数据,若步骤1的代码删除,则会从文件头部开始读取所有行
# lines = file_old.readlines()
#
# # 3.定位到最后一行的行首,若要删除后N行,将lines[-1]改为lines[-N:]即可。可你麻痹,根本不行
# i = -4
# n = 0
# while i < 0:
# n = n + len(lines[i])
# i = i+1
# file_old.seek(-n, os.SEEK_END)
#
# file_old.truncate() # 截断之后的数据
#
# file_old.close()
# 文本处理,留下偶数行
# with open("D:\\PYcode\\wwww\\zhaoze_url.txt", mode = 'r', encoding='utf-8') as f:
# with open("D:\\PYcode\\wwww\\c.txt", mode = 'a+', encoding='utf-8') as a:
# n = 1
# for line in f:
# if (n % 2) == 0:
# a.write(line)
# n = n + 1
# a.close()
# f.close()
# mainWin = tkinter.Tk() # 用构造方法Tk()创建主窗口容器。
# mainWin.title("碧蓝航线脚本") # 设置窗口标题
# mainWin.geometry("400x300") # 设置窗口尺寸
# label1 = tkinter.Label(mainWin, text="请输入循环次数: (默认100)") # 在主窗口中创建标签组件
# button1 = tkinter.Button(mainWin, text="按钮1") # 在主窗口中创建按钮组件
# button2 = tkinter.Button(mainWin, text="按钮2")
# label1.pack(padx=150, pady=0) # 标签组件以包裹方式添加进窗口
# button1.pack(side=tkinter.LEFT) # 按钮组件以包裹方式添加进窗口,设置为靠左。
# button2.pack(side=tkinter.RIGHT)
# mainWin.mainloop() # 执行消息循环,相当于while循环,则之后的代码不被执行
# python简单图形化代码
# mainWin = tk.Tk()
# # Entry文本框
# frame_1 = tk.Frame(mainWin)
# entry_1 = tk.Entry(frame_1, show="*") # 文本显示为“*”
# entry_2 = tk.Entry(frame_1, show="#") # 文本显示为“#”
# entry_3 = tk.Entry(frame_1,bg="red",fg="gray") # 设置背景色、前景色
# entry_4 = tk.Entry(frame_1,selectbackground="red", # 设置选中文本后的背景色、前景色
# selectforeground="gray")
# entry_1.pack()
# entry_2.pack()
# entry_3.pack()
# entry_4.pack()
# # text文本框
# frame_2 = tk.Frame(mainWin)
# label_name = tk.Label(frame_2,text="name:")
# label_tel = tk.Label(frame_2,text="tel:")
# label_email = tk.Label(frame_2,text="email:")
# text_name = tk.Text(frame_2,height="1",width=30)
# text_tel = tk.Text(frame_2,heigh="1",width=30)
# text_email = tk.Text(frame_2,heigh="1",width=30)
# btn_1 = tk.Button(frame_2,text="submit",width=7)
# btn_2 = tk.Button(frame_2,text="cancel",width=7)
# # 以网格方式添加到容器中
# label_name.grid(row=0,column=0)
# label_tel.grid(row=1,column=0)
# label_email.grid(row=2,column=0)
# text_name.grid(row=0,column=1)
# text_tel.grid(row=1,column=1)
# text_email.grid(row=2,column=1)
# btn_1.grid(row=3,column=0)
# btn_2.grid(row=3,column=1)
# # ------------------------
# frame_1.grid(row=0,column=0)
# frame_2.grid(row=1,column=0)
# mainWin.mainloop()
# python元组操作
# tuple1=(1, 2, 3, 4, 5, 6, 7, 9)
# print(tuple1[0], tuple1[2], tuple1[-1])
# 删除
# list = ['1', '2', '3', '4', '5']
# del(list[-1])
# print(list)
# 建立新空数组
# n = 10
#
# g = [[] for _ in range(n)]
# print(g)
# 删除网站名称
# str222 = "清纯女大入圈成为淫荡女M的心路历程 – 黑沼泽俱乐部"
# str222 = str222.replace(' – 黑沼泽俱乐部', ' ')
# print(str222)
# requests的用法
# 发送一个HTTP GET请求来获取页面内容
url = 'https://www.baidu.com'
response = requests.get(url)
# 使用BeautifulSoup解析网页内容,并提取文本
soup = BeautifulSoup(response.content.decode('utf-8', 'ignore'), 'html.parser')
text = soup.get_text()
# 打印文本
print(text)
<file_sep>import os
import time
from shutil import copyfile
import chardet
folder_path = r'D:\PYcode\wwww\test'
target_path = r'C:\Users\lenovo-pc\Desktop\处理1'
def detect_file_encoding(file_path):
"""
判断文件的编码格式
UTF-8-SIG
UTF-8
GB2313
"""
file = open(file_path, 'rb')
# 根据二进制信息判断编码{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}
result = chardet.detect(file.read())['encoding']
# chardet 默认为GB2313,实则不然,需要手工改为GBK,保证文档内容不发生篡改,已遇到'肏' '吋'等变为乱码
if result == 'GB2312':
result = 'GBK'
return result
for file_name in os.listdir(folder_path):
if file_name.endswith('.txt'):
# 定义需要处理的文件路径
file_path = os.path.join(folder_path, file_name)
target_file = os.path.join(target_path, file_name)
# 获取文件编码格式
file_encoding = detect_file_encoding(file_path)
# print(file_name + ":")
# print(file_encoding)
with open(file_path, 'r', encoding=file_encoding, errors='ignore') as f1:
content = f1.read()
flag = False
lines = content.split('\n')
for line in lines:
# str1 = ''.join(line)
# if '\u3000' in str1:
# print(str1)
# flag = True
# break
# # print(line + ":" + str(len(line)))
if len(line) > 46:
# print(len(line))
flag = True
if not flag:
copyfile(file_path, target_file)
print("任务结束! ✿✿ヽ(°▽°)ノ✿")<file_sep>import os
# 定义需要处理的文件夹路径
folder_path = r'D:\PYcode\wwww\test'
folder_temp_path = r'D:\PYcode\wwww\test2'
for file_name in os.listdir(folder_path):
if file_name.endswith('.txt'):
# 定义需要处理的文件路径
file_path = os.path.join(folder_path, file_name)
temp_path = os.path.join(folder_temp_path, file_name)
with open(file_path, 'r') as f1, open(temp_path, 'w', encoding='utf-8') as f2:
content = f1.read()
lines = content.split('\n')
# print(lines)
new_lines = []
for line in lines:
if line:
# 字符串前后删除空格
line = line.strip()
# 删除后10个字符
new_lines.append(line[:-10] + "\n\n")
# else:
# # new_lines.append(line + "\n\n")
f2.write(''.join(new_lines))
# os.remove(file_path)
# 将临时文件重命名为原文件
# os.rename(temp_path, file_path)
<file_sep>from selenium import webdriver
from selenium.webdriver.common.by import By
import time
def sleep(n):
time.sleep(n)
def clean_list(li):
res = []
for x in range(len(li)):
if x % 2 == 1:
res.append(li[x])
else:
pass
return res
def Download_Txt(filename):
class_names = browser.find_elements(By.CLASS_NAME, "t_msgfont")
# class_names = browser.find_element(By.XPATH, "/html/body/div[4]/div[1]/form/div[1]/table/tbody/tr[1]/td[2]/div[3]/div[3]/div").text
class_names = clean_list(class_names)
# print(class_names)
with open(filename, mode = 'a+', encoding='utf-8') as f:
for class_name in class_names:
text = class_name.get_attribute('innerText')
# print(text)
# print("-----------------------------------")
# f.write(text.replace('\n', ''))
f.write(text)
f.write("\n")
# print(class_name)
f.close()
def download(url):
print("开始下载url:" + url)
browser.get(url)
# sleep(10)
browser.find_element(By.LINK_TEXT, "只看该作者").click()
# text = browser.find_element(By.CLASS_NAME, "t_msgfont").get_attribute('innerText')
# a = browser.find_element(By.ID, "wrapper").get_attribute('innerText')
# element = browser.find_element(By.ID, "wrapper")
name = browser.find_element(By.CSS_SELECTOR, "h1").text
filename = name + '.txt'
pages = browser.find_element(By.TAG_NAME, "em").text
# 去空格
pages = pages.strip()
# print(type(pages)) # pages是字符型
# print('.....' + pages)
# print('.....' + '11')
# print(pages.isdigit())
with open(filename, mode = 'w', encoding='utf-8') as f:
f.write(name + "\n")
f.close()
Download_Txt(filename)
# 如果有pages 说明不只一页,本页页为$0,无法获取 ,取得值为 第二页 第三页。。。等, next页链接(第二页) 故删除列表最后一个元素
if pages.isdigit():
href_list = []
hrefs = browser.find_elements(By.XPATH, '/html/body/div[4]/div[1]/div[6]/div[2]/a')
for href in hrefs:
href_list.append(href.get_attribute('href'))
# href_list.sort() 排序后删除第一个元素,未排序删除最后一个
# print(href_list)
del(href_list[-1])
# print(href_list)
for i in href_list:
browser.get(i)
Download_Txt(filename)
def main():
with open("D:\\PYcode\\wwww\\url.txt", mode = 'r', encoding='utf-8') as f:
for line in f:
# print(type(line))
# if len(line) > 0:
download(line)
f.close()
if __name__ == "__main__":
options = webdriver.ChromeOptions()
options.add_argument('-ignore-certificate-errors')
options.add_argument('--disable-extensions') # 禁用扩展
options.add_argument('--headless') # 不开启网页
# options.add_argument('--disable-javascript') # 禁用JavaScript
options.add_argument('--blink-settings=imagesEnabled=false') # 禁用加载图片
# options.add_argument('-ignore -ssl-errors')
# options.add_argument('-disable-software-rasterizer')
browser = webdriver.Chrome(options=options)
main()
browser.quit()
# options = webdriver.ChromeOptions()
# options.add_argument('-ignore-certificate-errors')
# browser = webdriver.Chrome(options=options)
# browser.get('https://172.16.17.32/bbs/thread-11380876-1-1.html')
#
# pages = browser.find_element(By.CLASS_NAME, "pages")
# #pages = clean_list(pages)
# print(pages)
<file_sep>from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import os
def sleep(n):
time.sleep(n)
def login():
# browser.get("https://zhaoze.vip/")
browser.get("https://houhuayuan.vip/wp-login.php")
try:
# browser.find_element(By.ID, "user_login").send_keys("<PASSWORD>")
browser.find_element(By.ID, "user_login").send_keys("<PASSWORD>")
except Exception:
print('输入用户名失败')
else:
print('输入用户名成功')
try:
browser.find_element(By.ID, "user_pass").send_keys("<PASSWORD>")
except Exception:
print('输入密码失败')
else:
print('输入密码成功')
browser.find_element(By.NAME, "wp-submit").click()
def file_clean(filename):
file_old = open(filename, 'rb+')
m = 250
# 1.定位文件末尾的前m个字符的位置,大小可根据每一行的字符数量修改,为一估计值,但不能超过文件总字符数
# 若要删除最后一行,要确保m比最后一行的字符数大
# 若要删除后N行,要确保后N行的总字符数比m小
# 若文件很小或无法大体估计每一行的字符数,可以删除这行代码
file_old.seek(-m, os.SEEK_END)
# 2.从步骤1定位的位置开始读取接下来的每一行数据,若步骤1的代码删除,则会从文件头部开始读取所有行
lines = file_old.readlines()
# 3.定位到最后一行的行首,若要删除后N行,计算后N行字符长度,取负值定位
i = -4
n = 0
while i < 0:
n = n + len(lines[i])
i = i+1
file_old.seek(-n, os.SEEK_END)
file_old.truncate() # 截断之后的数据
file_old.close()
def Download_Txt(filename, url):
browser.get(url)
sleep(2)
# n1 = browser.find_elements(By.CLASS_NAME, "entry-content")
n1 = browser.find_elements(By.XPATH, '/html/body/div/div[2]/div/main/article/div[1]/h2 | '
'/html/body/div/div[2]/div/main/article/div[1]/p |'
'/html/body/div/div[2]/div/main/article/div[1]/blockquote/cite')
# print(len(n1))
# print(n1)
with open(filename, mode = 'a+', encoding='utf-8') as f:
for i in n1:
# print(i.get_attribute('innerText'))
str_2 = i.get_attribute('innerText')
str_2 = str_2.replace(' – 黑沼泽俱乐部', '')
str_2 = str_2.replace(' – 蔷薇后花园', '')
f.write(" " + str_2)
f.write("\n")
f.write("\n")
f.close()
# file_clean(filename)
def download(url):
print("开始下载url:" + url)
browser.get(url)
sleep(1)
name = browser.find_element(By.CLASS_NAME, "entry-title").text
name_head = name.split(' ')[0]
print("文章联想关键字为:" + str(name_head))
filename = name_head + '.txt'
# print(filename)
n1 = browser.find_elements(By.XPATH, '/html/body/div/div[2]/div/main/article/div[1]/h2 | '
'/html/body/div/div[2]/div/main/article/div[1]/p | '
'/html/body/div/div[2]/div/main/article/div[1]/div[1]/ul/li |'
'/html/body/div/div[2]/div/main/article/div[1]/div[1]/div/p |'
'/html/body/div/div[2]/div/main/article/div[1]/blockquote/cite')
with open(filename, mode = 'w', encoding='utf-8') as f:
f.write(name_head + "\n")
for i in n1:
# 字符型
# print(type(i.get_attribute('innerText')))
str_1 = i.get_attribute('innerText')
# print(str_1)
str_1 = str_1.replace(' – 黑沼泽俱乐部', '')
str_1 = str_1.replace(' – 蔷薇后花园', '')
f.write(" " + str_1)
f.write("\n")
f.write("\n")
f.close()
# i.get_attribute('innerText') 为string
# 链接需要从第一章搞起,Xpath适用正则表达式
elems = browser.find_elements(By.XPATH, '/html/body/div/div[2]/div/main/article/div[1]/div[1]/ul/li[*]/a')
# print(type(elems))
# print(len(elems))
href_list = []
for elem in elems:
href_list.append(elem.get_attribute('href'))
for ite in href_list:
Download_Txt(filename, ite)
def main():
# 蔷薇后花园需要登录,黑沼泽可注释
login()
with open("D:\\PYcode\\wwww\\zhaoze_url.txt", mode = 'r', encoding='utf-8') as f:
for line in f:
# print(type(line))
download(line)
f.close()
if __name__ == "__main__":
options = webdriver.ChromeOptions()
options.add_argument('-ignore-certificate-errors')
options.add_argument('--disable-extensions') # 禁用扩展
options.add_argument('--headless') # 不开启网页
options.add_argument('--disable-javascript') # 禁用JavaScript
options.add_argument('--blink-settings=imagesEnabled=false') # 禁用加载图片
# options.add_argument('-ignore -ssl-errors')
# options.add_argument('-disable-software-rasterizer')
browser = webdriver.Chrome(options=options)
main()
browser.quit()
| acb42ff046d33a6a3a148c480384b3ceaf1a03c8 | [
"Python"
]
| 18 | Python | w1g2f3/py | c957337bbbe08084e0b4beb11fc876c8e7902530 | dcaf95c804757bfe0d985631efe647fdfb04c1c9 |
refs/heads/master | <file_sep>var produce = new Vue ({
el:'#produce',
data:{
title:"",
classify_id:"",
classify_lists:[],
},
mounted:function(){
var ue = UE.getEditor('container');
this.select();
},
methods:{
getUeditorContent: function(){
return UE.getEditor('container').getContent()
},
issue:function(){
$.ajax({
url:'http://blog.com/api/blog/doAdd',
type:'post',
dataType:'json',
data:{
"user_id":localStorage.getItem("user_id"),
"title":this.title,
"content": this.getUeditorContent(),
"classify_id": this.classify_id,
},
success:function(res){
if (res.error_code == 0) {
alert("发布成功");
}
else{
alert(res.message);
}
}
})
},
select:function(){
var uId = window.location.search.split("=")[1];
var that = this;
$.ajax({
url:'http://blog.com/api/blog/add',
type:'get',
dataType:'json',
data:{
"user_id":localStorage.getItem("user_id"),
"blog_id":uId,
},
success:function(res){
that.classify_lists = res.data.classify_lists;
that.title=res.data.my_blog_info.title;
}
})
}
}
})<file_sep>var app = new Vue ({
el:'#homepage',
data:{
blog:[],
navLists:[],
banner:[],
isShow:false,
},
mounted:function(){
this.getData();
this.judge();
},
methods:{
getData:function(){
var that = this;
$.ajax({
url:'http://blog.com/api/index/index',
type:'get',
dataType:'json',
success:function(res){
that.blog = res.data.blog_lists;
that.navLists = res.data.classify_lists;
that.banner = res.data.banner;
that.swiperBanner();
}
})
},
swiperBanner:function(){
var mySwiper = new Swiper('.swiper-container',{
loop : true,
autoplay: {
delay: 2500,
disableOnInteraction: false,
},
pagination: {
el: '.swiper-pagination',
clickable: true,
},
observer:true,
observeParents:true,
});
},
judge:function(){
var user_id = localStorage.getItem("user_id")
if (user_id == "" || !user_id) {
this.isShow = false;
}
else{
this.isShow = true;
}
}
},
})<file_sep>var login = new Vue ({
el:'#login',
data:{
phone:"",
password:"",
},
mounted:function(){
// this.getData();
},
methods:{
login:function(){
if (this.phone == "") {
alert("用户名不能为空!");
return false;
};
if (this.password == "") {
alert("密码不能为空!");
return false;
};
$.ajax({
url:'http://blog.com/api/user/doLogin',
type:'post',
dataType:'json',
data:{
"phone":this.phone,
"password":<PASSWORD>,
},
success:function(res){
if (res.error_code == 0) {
localStorage.setItem("user_id",res.data.user.userid);
localStorage.setItem("user_img",res.data.user.userimg);
localStorage.setItem("user_name",res.data.user.username);
alert("登录成功!");
location.href = "./index.html";
}
else{
alert(res.message);
}
}
})
},
}
})<file_sep>var register = new Vue ({
el:'#register',
data:{
phone:null,
password:<PASSWORD>,
uname:null,
},
mounted:function(){
this.getData();
},
methods:{
getData:function(dataObj){
$.ajax({
url:'http://blog.com/api/user/doReg',
type:'post',
dataType:'json',
data:dataObj,
success:function(res){
console.log(res);
},
})
},
click:function(){
var that = this;
var phone = $(".phone-num").val();
var password = $(".pass-word").val();
var uname = $(".user-name").val();
var data = {
'phone' : phone,
'password' : <PASSWORD>,
'uname' : uname,
'format' : "json",
}
that.getData(data);
}
}
}) | f9322c6207e20e7cbef7a635b4971c6fe0991ccd | [
"JavaScript"
]
| 4 | JavaScript | UserLMmeNg/CSDN | b580a3d9700ba291aa0a663c987d56d2d8f857ee | 915ef67caea0afb23edbb403e1833292c2990eff |
refs/heads/master | <repo_name>ts90wb/lvgou<file_sep>/scripts/browser.js
var cWidth = document.documentElement.clientWidth;
console.log(cWidth);
if (cWidth < 768) {
window.location.href = 'register.html';
} | e427e6e2536876ff94564c44bd13995a6c5a906d | [
"JavaScript"
]
| 1 | JavaScript | ts90wb/lvgou | 7d5cb41096f3918cbb91bb5fa77e5d511530a447 | 82dd7fb51faa52a667aaff5672f40904ba4f2239 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from numpy.linalg import solve, norm, inv, LinAlgError
from numpy import dot, exp
from scipy.integrate import trapz
import scipy.stats as stats
import pandas as pd
from lifelines.plotting import plot_estimate, plot_regressions
from lifelines.utils import survival_table_from_events, inv_normal_cdf, \
epanechnikov_kernel, StatError, normalize, significance_code
from lifelines.utils import ridge_regression as lr
from lifelines.progress_bar import progress_bar
from lifelines.utils import concordance_index
class BaseFitter(object):
def __init__(self, alpha=0.95):
if not (0 < alpha <= 1.):
raise ValueError('alpha parameter must be between 0 and 1.')
self.alpha = alpha
def __repr__(self):
classname = self.__class__.__name__
try:
s = """<lifelines.%s: fitted with %d observations, %d censored>""" % (
classname, self.event_observed.shape[0], (1 - self.event_observed).sum())
except AttributeError:
s = """<lifelines.%s>""" % classname
return s
class WeibullFitter(BaseFitter):
"""
This class implements a Weibull model for univariate data. The model has parameterized
form:
S(t) = exp(-(lambda*t)**rho), lambda >0, rho > 0,
which implies the cumulative hazard rate is
H(t) = (lambda*t)**rho,
and the hazard rate is:
h(t) = rho*lambda(lambda*t)**rho
After calling the `.fit` method, you have access to properties like:
`cumulative_hazard_', 'survival_function_', 'lambda_' and 'rho_'.
"""
def fit(self, durations, event_observed=None, timeline=None, entry=None,
label='Weibull_estimate', alpha=None, ci_labels=None):
"""
Parameters:
duration: an array, or pd.Series, of length n -- duration subject was observed for
timeline: return the estimate at the values in timeline (postively increasing)
event_observed: an array, or pd.Series, of length n -- True if the the death was observed, False if the event
was lost (right-censored). Defaults all True if event_observed==None
entry: an array, or pd.Series, of length n -- relative time when a subject entered the study. This is
useful for left-truncated observations, i.e the birth event was not observed.
If None, defaults to all 0 (all birth events observed.)
label: a string to name the column of the estimate.
alpha: the alpha value in the confidence intervals. Overrides the initializing
alpha for this call to fit only.
ci_labels: add custom column names to the generated confidence intervals
as a length-2 list: [<lower-bound name>, <upper-bound name>]. Default: <label>_lower_<alpha>
Returns:
self, with new properties like `cumulative_hazard_', 'survival_function_', 'lambda_' and 'rho_'.
"""
self.durations = np.asarray(durations, dtype=float)
# check for negative or 0 durations - these are not allowed in a weibull model.
if np.any(self.durations <= 0):
raise ValueError('This model does not allow for non-positive durations. Suggestion: add a small positive value to zero elements.')
self.event_observed = np.asarray(event_observed, dtype=int) if event_observed is not None else np.ones_like(self.durations)
self.timeline = np.sort(np.asarray(timeline)) if timeline is not None else np.arange(int(self.durations.min()), int(self.durations.max()) + 1)
self._label = label
alpha = alpha if alpha is not None else self.alpha
# estimation
self.lambda_, self.rho_ = self._newton_rhaphson(self.durations, self.event_observed)
self.survival_function_ = pd.DataFrame(self.survival_function_at_times(self.timeline), columns=[self._label], index=self.timeline)
self.hazard_ = pd.DataFrame(self.hazard_at_times(self.timeline), columns=[self._label], index=self.timeline)
self.cumulative_hazard_ = pd.DataFrame(self.cumulative_hazard_at_times(self.timeline), columns=[self._label], index=self.timeline)
self.confidence_interval_ = self._bounds(alpha, ci_labels)
self.median_ = 1. / self.lambda_ * (np.log(2)) ** (1. / self.rho_)
# estimation functions - Cumulative hazard takes priority.
self.predict = _predict(self, "cumulative_hazard_", self._label)
self.subtract = _subtract(self, "cumulative_hazard_")
self.divide = _divide(self, "cumulative_hazard_")
# plotting - Cumulative hazard takes priority.
self.plot = plot_estimate(self, "cumulative_hazard_")
self.plot_cumulative_hazard = self.plot
return self
@property
def conditional_time_to_event_(self):
return _conditional_time_to_event_(self)
def hazard_at_times(self, times):
return self.lambda_ * self.rho_ * (self.lambda_ * times) ** (self.rho_ - 1)
def survival_function_at_times(self, times):
return np.exp(-self.cumulative_hazard_at_times(times))
def cumulative_hazard_at_times(self, times):
return (self.lambda_ * times) ** self.rho_
def _newton_rhaphson(self, T, E, precision=1e-5):
from lifelines.utils import _smart_search
from lifelines._univariate_weibull import _d_lambda_d_lambda_, _d_rho_d_lambda_,\
_d_rho_d_rho, _lambda_gradient, _rho_gradient, _negative_log_likelihood
def jacobian_function(parameters, T, E):
return np.array([
[_d_lambda_d_lambda_(parameters, T, E), _d_rho_d_lambda_(parameters, T, E)],
[_d_rho_d_lambda_(parameters, T, E), _d_rho_d_rho(parameters, T, E)]
])
def gradient_function(parameters, T, E):
return np.array([_lambda_gradient(parameters, T, E), _rho_gradient(parameters, T, E)])
# initialize the parameters. This shows dramatic improvements.
parameters = _smart_search(_negative_log_likelihood, 2, T, E)
iter = 1
step_size = 1.
converging = True
while converging and iter < 50:
# Do not override hessian and gradient in case of garbage
j, g = jacobian_function(parameters, T, E), gradient_function(parameters, T, E)
delta = solve(j, - step_size * g.T)
if np.any(np.isnan(delta)):
raise ValueError("delta contains nan value(s). Convergence halted.")
parameters += delta
# Save these as pending result
jacobian = j
if norm(delta) < precision:
converging = False
iter += 1
self._jacobian = jacobian
return parameters
def _bounds(self, alpha, ci_labels):
alpha2 = inv_normal_cdf((1. + alpha) / 2.)
df = pd.DataFrame(index=self.timeline)
var_lambda_, var_rho_ = inv(self._jacobian).diagonal()
def _dH_d_lambda(lambda_, rho, T):
return rho / lambda_ * (lambda_ * T) ** rho
def _dH_d_rho(lambda_, rho, T):
return np.log(lambda_ * T) * (lambda_ * T) ** rho
def sensitivity_analysis(lambda_, rho, var_lambda_, var_rho_, T):
return var_lambda_ * _dH_d_lambda(lambda_, rho, T) ** 2 + var_rho_ * _dH_d_rho(lambda_, rho, T) ** 2
std_cumulative_hazard = np.sqrt(sensitivity_analysis(self.lambda_, self.rho_, var_lambda_, var_rho_, self.timeline))
if ci_labels is None:
ci_labels = ["%s_upper_%.2f" % (self._label, alpha), "%s_lower_%.2f" % (self._label, alpha)]
assert len(ci_labels) == 2, "ci_labels should be a length 2 array."
df[ci_labels[0]] = self.cumulative_hazard_at_times(self.timeline) + alpha2 * std_cumulative_hazard
df[ci_labels[1]] = self.cumulative_hazard_at_times(self.timeline) - alpha2 * std_cumulative_hazard
return df
class ExponentialFitter(BaseFitter):
"""
This class implements an Exponential model for univariate data. The model has parameterized
form:
S(t) = exp(-(lambda*t)), lambda >0
which implies the cumulative hazard rate is
H(t) = lambda*t
and the hazard rate is:
h(t) = lambda
After calling the `.fit` method, you have access to properties like:
'survival_function_', 'lambda_'
"""
def fit(self, durations, event_observed=None, timeline=None, entry=None,
label='Exponential_estimate', alpha=None, ci_labels=None):
"""
Parameters:
duration: an array, or pd.Series, of length n -- duration subject was observed for
timeline: return the best estimate at the values in timelines (postively increasing)
event_observed: an array, or pd.Series, of length n -- True if the the death was observed, False if the event
was lost (right-censored). Defaults all True if event_observed==None
entry: an array, or pd.Series, of length n -- relative time when a subject entered the study. This is
useful for left-truncated observations, i.e the birth event was not observed.
If None, defaults to all 0 (all birth events observed.)
label: a string to name the column of the estimate.
alpha: the alpha value in the confidence intervals. Overrides the initializing
alpha for this call to fit only.
ci_labels: add custom column names to the generated confidence intervals
as a length-2 list: [<lower-bound name>, <upper-bound name>]. Default: <label>_lower_<alpha>
Returns:
self, with new properties like 'survival_function_' and 'lambda_'.
"""
self.durations = np.asarray(durations, dtype=float)
self.event_observed = np.asarray(event_observed, dtype=int) if event_observed is not None else np.ones_like(self.durations)
self.timeline = np.sort(np.asarray(timeline)) if timeline is not None else np.arange(int(self.durations.min()), int(self.durations.max()) + 1)
self._label = label
# estimation
D = self.event_observed.sum()
T = self.durations.sum()
self.lambda_ = D / T
self._lambda_variance_ = self.lambda_ / T
self.survival_function_ = pd.DataFrame(np.exp(-self.lambda_ * self.timeline), columns=[self._label], index=self.timeline)
self.confidence_interval_ = self._bounds(alpha if alpha else self.alpha, ci_labels)
self.median_ = 1. / self.lambda_ * (np.log(2))
# estimation functions
self.predict = _predict(self, "survival_function_", self._label)
self.subtract = _subtract(self, "survival_function_")
self.divide = _divide(self, "survival_function_")
# plotting
self.plot = plot_estimate(self, "survival_function_")
self.plot_survival_function_ = self.plot
return self
@property
def conditional_time_to_event_(self):
return _conditional_time_to_event_(self)
def _bounds(self, alpha, ci_labels):
alpha2 = inv_normal_cdf((1. + alpha) / 2.)
df = pd.DataFrame(index=self.timeline)
if ci_labels is None:
ci_labels = ["%s_upper_%.2f" % (self._label, alpha), "%s_lower_%.2f" % (self._label, alpha)]
assert len(ci_labels) == 2, "ci_labels should be a length 2 array."
std = np.sqrt(self._lambda_variance_)
sv = self.survival_function_
error = std * self.timeline[:, None] * sv
df[ci_labels[0]] = sv + alpha2 * error
df[ci_labels[1]] = sv - alpha2 * error
return df
class NelsonAalenFitter(BaseFitter):
"""
Class for fitting the Nelson-Aalen estimate for the cumulative hazard.
NelsonAalenFitter( alpha=0.95, nelson_aalen_smoothing=True)
alpha: The alpha value associated with the confidence intervals.
nelson_aalen_smoothing: If the event times are naturally discrete (like discrete years, minutes, etc.)
then it is advisable to turn this parameter to False. See [1], pg.84.
"""
def __init__(self, alpha=0.95, nelson_aalen_smoothing=True):
if not (0 < alpha <= 1.):
raise ValueError('alpha parameter must be between 0 and 1.')
self.alpha = alpha
self.nelson_aalen_smoothing = nelson_aalen_smoothing
if self.nelson_aalen_smoothing:
self._variance_f = self._variance_f_smooth
self._additive_f = self._additive_f_smooth
else:
self._variance_f = self._variance_f_discrete
self._additive_f = self._additive_f_discrete
def fit(self, durations, event_observed=None, timeline=None, entry=None,
label='NA_estimate', alpha=None, ci_labels=None):
"""
Parameters:
duration: an array, or pd.Series, of length n -- duration subject was observed for
timeline: return the best estimate at the values in timelines (postively increasing)
event_observed: an array, or pd.Series, of length n -- True if the the death was observed, False if the event
was lost (right-censored). Defaults all True if event_observed==None
entry: an array, or pd.Series, of length n -- relative time when a subject entered the study. This is
useful for left-truncated observations, i.e the birth event was not observed.
If None, defaults to all 0 (all birth events observed.)
label: a string to name the column of the estimate.
alpha: the alpha value in the confidence intervals. Overrides the initializing
alpha for this call to fit only.
ci_labels: add custom column names to the generated confidence intervals
as a length-2 list: [<lower-bound name>, <upper-bound name>]. Default: <label>_lower_<alpha>
Returns:
self, with new properties like 'cumulative_hazard_'.
"""
v = preprocess_inputs(durations, event_observed, timeline, entry)
self.durations, self.event_observed, self.timeline, self.entry, self.event_table = v
cumulative_hazard_, cumulative_sq_ = _additive_estimate(self.event_table, self.timeline,
self._additive_f, self._variance_f, False)
# esimates
self._label = label
self.cumulative_hazard_ = pd.DataFrame(cumulative_hazard_, columns=[self._label])
self.confidence_interval_ = self._bounds(cumulative_sq_[:, None], alpha if alpha else self.alpha, ci_labels)
self._cumulative_sq = cumulative_sq_
# estimation functions
self.predict = _predict(self, "cumulative_hazard_", self._label)
self.subtract = _subtract(self, "cumulative_hazard_")
self.divide = _divide(self, "cumulative_hazard_")
# plotting
self.plot = plot_estimate(self, "cumulative_hazard_")
self.plot_cumulative_hazard = self.plot
self.plot_hazard = plot_estimate(self, 'hazard_')
return self
def _bounds(self, cumulative_sq_, alpha, ci_labels):
alpha2 = inv_normal_cdf(1 - (1 - alpha) / 2)
df = pd.DataFrame(index=self.timeline)
if ci_labels is None:
ci_labels = ["%s_upper_%.2f" % (self._label, alpha), "%s_lower_%.2f" % (self._label, alpha)]
assert len(ci_labels) == 2, "ci_labels should be a length 2 array."
self.ci_labels = ci_labels
df[ci_labels[0]] = self.cumulative_hazard_.values * \
np.exp(alpha2 * np.sqrt(cumulative_sq_) / self.cumulative_hazard_.values)
df[ci_labels[1]] = self.cumulative_hazard_.values * \
np.exp(-alpha2 * np.sqrt(cumulative_sq_) / self.cumulative_hazard_.values)
return df
def _variance_f_smooth(self, population, deaths):
df = pd.DataFrame({'N': population, 'd': deaths})
return df.apply(lambda N_d: np.sum((1. / (N_d[0] - i) ** 2 for i in range(int(N_d[1])))), axis=1)
def _variance_f_discrete(self, population, deaths):
return 1. * (population - deaths) * deaths / population ** 3
def _additive_f_smooth(self, population, deaths):
df = pd.DataFrame({'N': population, 'd': deaths})
return df.apply(lambda N_d: np.sum((1. / (N_d[0] - i) for i in range(int(N_d[1])))), axis=1)
def _additive_f_discrete(self, population, deaths):
return (1. * deaths / population).replace([np.inf], 0)
def smoothed_hazard_(self, bandwidth):
"""
Parameters:
bandwidth: the bandwith used in the Epanechnikov kernel.
Returns:
a DataFrame of the smoothed hazard
"""
timeline = self.timeline
cumulative_hazard_name = self.cumulative_hazard_.columns[0]
hazard_name = "differenced-" + cumulative_hazard_name
hazard_ = self.cumulative_hazard_.diff().fillna(self.cumulative_hazard_.iloc[0])
C = (hazard_[cumulative_hazard_name] != 0.0).values
return pd.DataFrame(1. / (2 * bandwidth) * np.dot(epanechnikov_kernel(timeline[:, None], timeline[C][None, :], bandwidth), hazard_.values[C, :]),
columns=[hazard_name], index=timeline)
def smoothed_hazard_confidence_intervals_(self, bandwidth, hazard_=None):
"""
Parameter:
bandwidth: the bandwith to use in the Epanechnikov kernel.
hazard_: a computed (n,) numpy array of estimated hazard rates. If none, uses naf.smoothed_hazard_
"""
if hazard_ is None:
hazard_ = self.smoothed_hazard_(bandwidth).values[:, 0]
timeline = self.timeline
alpha2 = inv_normal_cdf(1 - (1 - self.alpha) / 2)
self._cumulative_sq.iloc[0] = 0
var_hazard_ = self._cumulative_sq.diff().fillna(self._cumulative_sq.iloc[0])
C = (var_hazard_.values != 0.0) # only consider the points with jumps
std_hazard_ = np.sqrt(1. / (2 * bandwidth ** 2) * np.dot(epanechnikov_kernel(timeline[:, None], timeline[C][None, :], bandwidth) ** 2, var_hazard_.values[C]))
values = {
self.ci_labels[0]: hazard_ * np.exp(alpha2 * std_hazard_ / hazard_),
self.ci_labels[1]: hazard_ * np.exp(-alpha2 * std_hazard_ / hazard_)
}
return pd.DataFrame(values, index=timeline)
class KaplanMeierFitter(BaseFitter):
"""
Class for fitting the Kaplan-Meier estimate for the survival function.
KaplanMeierFitter( alpha=0.95)
alpha: The alpha value associated with the confidence intervals.
"""
def fit(self, durations, event_observed=None, timeline=None, entry=None, label='KM_estimate',
alpha=None, left_censorship=False, ci_labels=None):
"""
Parameters:
duration: an array, or pd.Series, of length n -- duration subject was observed for
timeline: return the best estimate at the values in timelines (postively increasing)
event_observed: an array, or pd.Series, of length n -- True if the the death was observed, False if the event
was lost (right-censored). Defaults all True if event_observed==None
entry: an array, or pd.Series, of length n -- relative time when a subject entered the study. This is
useful for left-truncated (not left-censored) observations, i.e the birth event was not observed.
If None, defaults to all 0 (all birth events observed.).
See this twitter convo: https://twitter.com/Cmrn_DP/status/566403872361836544
label: a string to name the column of the estimate.
alpha: the alpha value in the confidence intervals. Overrides the initializing
alpha for this call to fit only.
left_censorship: True if durations and event_observed refer to left censorship events. Default False
ci_labels: add custom column names to the generated confidence intervals
as a length-2 list: [<lower-bound name>, <upper-bound name>]. Default: <label>_lower_<alpha>
Returns:
self, with new properties like 'survival_function_'.
"""
# if the user is interested in left-censorship, we return the cumulative_density_, no survival_function_,
estimate_name = 'survival_function_' if not left_censorship else 'cumulative_density_'
v = preprocess_inputs(durations, event_observed, timeline, entry)
self.durations, self.event_observed, self.timeline, self.entry, self.event_table = v
self._label = label
alpha = alpha if alpha else self.alpha
log_survival_function, cumulative_sq_ = _additive_estimate(self.event_table, self.timeline,
self._additive_f, self._additive_var,
left_censorship)
if entry is not None:
# a serious problem with KM is that when the sample size is small and there are too few early
# truncation times, it may happen that is the number of patients at risk and the number of deaths is the same.
# we adjust for this using the Breslow-Fleming-Harrington estimator
n = self.event_table.shape[0]
net_population = (self.event_table['entrance'] - self.event_table['removed']).cumsum()
if net_population.iloc[:int(n / 2)].min() == 0:
ix = net_population.iloc[:int(n / 2)].argmin()
raise StatError("""There are too few early truncation times and too many events. S(t)==0 for all t>%.1f. Recommend BreslowFlemingHarringtonFitter.""" % ix)
# estimation
setattr(self, estimate_name, pd.DataFrame(np.exp(log_survival_function), columns=[self._label]))
self.__estimate = getattr(self, estimate_name)
self.confidence_interval_ = self._bounds(cumulative_sq_[:, None], alpha, ci_labels)
self.median_ = median_survival_times(self.__estimate)
# estimation methods
self.predict = _predict(self, estimate_name, label)
self.subtract = _subtract(self, estimate_name)
self.divide = _divide(self, estimate_name)
# plotting functions
self.plot = plot_estimate(self, estimate_name)
setattr(self, "plot_" + estimate_name, self.plot)
return self
@property
def conditional_time_to_event_(self):
return _conditional_time_to_event_(self)
def _bounds(self, cumulative_sq_, alpha, ci_labels):
# See http://courses.nus.edu.sg/course/stacar/internet/st3242/handouts/notes2.pdf
alpha2 = inv_normal_cdf((1. + alpha) / 2.)
df = pd.DataFrame(index=self.timeline)
v = np.log(self.__estimate.values)
if ci_labels is None:
ci_labels = ["%s_upper_%.2f" % (self._label, alpha), "%s_lower_%.2f" % (self._label, alpha)]
assert len(ci_labels) == 2, "ci_labels should be a length 2 array."
df[ci_labels[0]] = np.exp(-np.exp(np.log(-v) + alpha2 * np.sqrt(cumulative_sq_) / v))
df[ci_labels[1]] = np.exp(-np.exp(np.log(-v) - alpha2 * np.sqrt(cumulative_sq_) / v))
return df
def _additive_f(self, population, deaths):
np.seterr(invalid='ignore')
return (np.log(population - deaths) - np.log(population))
def _additive_var(self, population, deaths):
np.seterr(divide='ignore')
return (1. * deaths / (population * (population - deaths))).replace([np.inf], 0)
class BreslowFlemingHarringtonFitter(BaseFitter):
"""
Class for fitting the Breslow-Fleming-Harrington estimate for the survival function. This estimator
is a biased estimator of the survival function but is more stable when the popualtion is small and
there are too few early truncation times, it may happen that is the number of patients at risk and
the number of deaths is the same.
Mathematically, the NAF estimator is the negative logarithm of the BFH estimator.
BreslowFlemingHarringtonFitter(alpha=0.95)
alpha: The alpha value associated with the confidence intervals.
"""
def fit(self, durations, event_observed=None, timeline=None, entry=None,
label='BFH_estimate', alpha=None, ci_labels=None):
"""
Parameters:
duration: an array, or pd.Series, of length n -- duration subject was observed for
timeline: return the best estimate at the values in timelines (postively increasing)
event_observed: an array, or pd.Series, of length n -- True if the the death was observed, False if the event
was lost (right-censored). Defaults all True if event_observed==None
entry: an array, or pd.Series, of length n -- relative time when a subject entered the study. This is
useful for left-truncated observations, i.e the birth event was not observed.
If None, defaults to all 0 (all birth events observed.)
label: a string to name the column of the estimate.
alpha: the alpha value in the confidence intervals. Overrides the initializing
alpha for this call to fit only.
ci_labels: add custom column names to the generated confidence intervals
as a length-2 list: [<lower-bound name>, <upper-bound name>]. Default: <label>_lower_<alpha>
Returns:
self, with new properties like 'survival_function_'.
"""
self._label = label
alpha = alpha if alpha is not None else self.alpha
naf = NelsonAalenFitter(alpha)
naf.fit(durations, event_observed=event_observed, timeline=timeline, label=label, entry=entry, ci_labels=ci_labels)
self.durations, self.event_observed, self.timeline, self.entry, self.event_table = \
naf.durations, naf.event_observed, naf.timeline, naf.entry, naf.event_table
# estimation
self.survival_function_ = np.exp(-naf.cumulative_hazard_)
self.confidence_interval_ = np.exp(-naf.confidence_interval_)
self.median_ = median_survival_times(self.survival_function_)
# estimation methods
self.predict = _predict(self, "survival_function_", label)
self.subtract = _subtract(self, "survival_function_")
self.divide = _divide(self, "survival_function_")
# plotting functions
self.plot = plot_estimate(self, "survival_function_")
self.plot_survival_function = self.plot
return self
@property
def conditional_time_to_event_(self):
return _conditional_time_to_event_(self)
class AalenAdditiveFitter(BaseFitter):
"""
This class fits the regression model:
hazard(t) = b_0(t) + b_t(t)*x_1 + ... + b_N(t)*x_N
that is, the hazard rate is a linear function of the covariates.
Parameters:
fit_intercept: If False, do not attach an intercept (column of ones) to the covariate matrix. The
intercept, b_0(t) acts as a baseline hazard.
alpha: the level in the confidence intervals.
coef_penalizer: Attach a L2 penalizer to the size of the coeffcients during regression. This improves
stability of the estimates and controls for high correlation between covariates.
For example, this shrinks the absolute value of c_{i,t}. Recommended, even if a small value.
smoothing_penalizer: Attach a L2 penalizer to difference between adjacent (over time) coefficents. For
example, this shrinks the absolute value of c_{i,t} - c_{i,t+1}.
"""
def __init__(self, fit_intercept=True, alpha=0.95, coef_penalizer=0.5, smoothing_penalizer=0.):
if not (0 < alpha <= 1.):
raise ValueError('alpha parameter must be between 0 and 1.')
if coef_penalizer < 0 or smoothing_penalizer < 0:
raise ValueError("penalizer parameter must be >= 0.")
self.fit_intercept = fit_intercept
self.alpha = alpha
self.coef_penalizer = coef_penalizer
self.smoothing_penalizer = smoothing_penalizer
def fit(self, dataframe, duration_col, event_col=None,
timeline=None, id_col=None, show_progress=True):
"""
Perform inference on the coefficients of the Aalen additive model.
Parameters:
dataframe: a pandas dataframe, with covariates and a duration_col and a event_col.
static covariates:
one row per individual. duration_col refers to how long the individual was
observed for. event_col is a boolean: 1 if individual 'died', 0 else. id_col
should be left as None.
time-varying covariates:
For time-varying covariates, an id_col is required to keep track of individuals'
changing covariates. individual should have a unique id. duration_col refers to how
long the individual has been observed to up to that point. event_col refers to if
the event (death) occured in that period. Censored individuals will not have a 1.
For example:
+----+---+---+------+------+
| id | T | E | var1 | var2 |
+----+---+---+------+------+
| 1 | 1 | 0 | 0 | 1 |
| 1 | 2 | 0 | 0 | 1 |
| 1 | 3 | 0 | 4 | 3 |
| 1 | 4 | 1 | 8 | 4 |
| 2 | 1 | 0 | 1 | 1 |
| 2 | 2 | 0 | 1 | 2 |
| 2 | 3 | 0 | 1 | 2 |
+----+---+---+------+------+
duration_col: specify what the duration column is called in the dataframe
event_col: specify what the event column is called in the dataframe.
If left as None, treat all individuals as non-censored.
timeline: reformat the estimates index to a new timeline.
id_col: (only for time-varying covariates) name of the id column in the dataframe
progress_bar: include a fancy progress bar =)
max_unique_durations: memory can be an issue if there are too many
unique durations. If the max is surpassed, max_unique_durations bins
will be used.
Returns:
self, with new methods like plot, smoothed_hazards_ and properties like cumulative_hazards_
"""
if id_col is None:
self._fit_static(dataframe, duration_col, event_col, timeline, show_progress)
else:
self._fit_varying(dataframe, duration_col, event_col, id_col, timeline, show_progress)
return self
def _fit_static(self, dataframe, duration_col, event_col=None,
timeline=None, show_progress=True):
"""
Perform inference on the coefficients of the Aalen additive model.
Parameters:
dataframe: a pandas dataframe, with covariates and a duration_col and a event_col.
one row per individual. duration_col refers to how long the individual was
observed for. event_col is a boolean: 1 if individual 'died', 0 else. id_col
should be left as None.
duration_col: specify what the duration column is called in the dataframe
event_col: specify what the event occurred column is called in the dataframe
timeline: reformat the estimates index to a new timeline.
progress_bar: include a fancy progress bar!
Returns:
self, with new methods like plot, smoothed_hazards_ and properties like cumulative_hazards_
"""
from_tuples = pd.MultiIndex.from_tuples
df = dataframe.copy()
# set unique ids for individuals
id_col = 'id'
ids = np.arange(df.shape[0])
df[id_col] = ids
# if the regression should fit an intercept
if self.fit_intercept:
df['baseline'] = 1.
# if no event_col is specified, assume all non-censorships
if event_col:
c = df[event_col].values
del df[event_col]
else:
c = np.ones_like(ids)
# each individual should have an ID of time of leaving study
C = pd.Series(c, dtype=bool, index=ids)
T = pd.Series(df[duration_col].values, index=ids)
df = df.set_index(id_col)
ix = T.argsort()
T, C = T.iloc[ix], C.iloc[ix]
del df[duration_col]
n, d = df.shape
columns = df.columns
# initialize dataframe to store estimates
non_censorsed_times = list(T[C].iteritems())
n_deaths = len(non_censorsed_times)
hazards_ = pd.DataFrame(np.zeros((n_deaths, d)), columns=columns,
index=from_tuples(non_censorsed_times)).swaplevel(1, 0)
variance_ = pd.DataFrame(np.zeros((n_deaths, d)), columns=columns,
index=from_tuples(non_censorsed_times)).swaplevel(1, 0)
# initialize loop variables.
previous_hazard = np.zeros((d,))
progress = progress_bar(n_deaths)
to_remove = []
t = T.iloc[0]
i = 0
for id, time in T.iteritems(): # should be sorted.
if t != time:
assert t < time
# remove the individuals from the previous loop.
df.iloc[to_remove] = 0.
to_remove = []
t = time
to_remove.append(id)
if C[id] == 0:
continue
relevant_individuals = (ids == id)
assert relevant_individuals.sum() == 1.
# perform linear regression step.
try:
v, V = lr(df.values, relevant_individuals, c1=self.coef_penalizer, c2=self.smoothing_penalizer, offset=previous_hazard)
except LinAlgError:
print("Linear regression error. Try increasing the penalizer term.")
hazards_.ix[time, id] = v.T
variance_.ix[time, id] = V[:, relevant_individuals][:, 0] ** 2
previous_hazard = v.T
# update progress bar
if show_progress:
i += 1
progress.update(i)
# print a new line so the console displays well
if show_progress:
print()
# not sure this is the correct thing to do.
self.hazards_ = hazards_.groupby(level=0).sum()
self.cumulative_hazards_ = self.hazards_.cumsum()
self.variance_ = variance_.groupby(level=0).sum()
if timeline is not None:
self.hazards_ = self.hazards_.reindex(timeline, method='ffill')
self.cumulative_hazards_ = self.cumulative_hazards_.reindex(timeline, method='ffill')
self.variance_ = self.variance_.reindex(timeline, method='ffill')
self.timeline = timeline
else:
self.timeline = self.hazards_.index.values.astype(float)
self.data = dataframe
self.durations = T
self.event_observed = C
self._compute_confidence_intervals()
self.plot = plot_regressions(self)
return
def _fit_varying(self, dataframe, duration_col="T", event_col="E",
id_col=None, timeline=None, show_progress=True):
from_tuples = pd.MultiIndex.from_tuples
df = dataframe.copy()
# if the regression should fit an intercept
if self.fit_intercept:
df['baseline'] = 1.
# each individual should have an ID of time of leaving study
df = df.set_index([duration_col, id_col])
# if no event_col is specified, assume all non-censorships
if event_col is None:
event_col = 'E'
df[event_col] = 1
C_panel = df[[event_col]].to_panel().transpose(2, 1, 0)
C = C_panel.minor_xs(event_col).sum().astype(bool)
T = (C_panel.minor_xs(event_col).notnull()).cumsum().idxmax()
del df[event_col]
n, d = df.shape
# so this is a problem line. bfill performs a recursion which is
# really not scalable. Plus even for modest datasets, this eats a lot of memory.
# Plus is bfill the correct thing to choose? It's forward looking...
wp = df.to_panel().bfill().fillna(0)
# initialize dataframe to store estimates
non_censorsed_times = list(T[C].iteritems())
columns = wp.items
hazards_ = pd.DataFrame(np.zeros((len(non_censorsed_times), d)),
columns=columns, index=from_tuples(non_censorsed_times))
variance_ = pd.DataFrame(np.zeros((len(non_censorsed_times), d)),
columns=columns, index=from_tuples(non_censorsed_times))
previous_hazard = np.zeros((d,))
ids = wp.minor_axis.values
progress = progress_bar(len(non_censorsed_times))
# this makes indexing times much faster
wp = wp.swapaxes(0, 1, copy=False).swapaxes(1, 2, copy=False)
for i, (id, time) in enumerate(non_censorsed_times):
relevant_individuals = (ids == id)
assert relevant_individuals.sum() == 1.
# perform linear regression step.
try:
v, V = lr(wp[time].values, relevant_individuals, c1=self.coef_penalizer, c2=self.smoothing_penalizer, offset=previous_hazard)
except LinAlgError:
print("Linear regression error. Try increasing the penalizer term.")
hazards_.ix[id, time] = v.T
variance_.ix[id, time] = V[:, relevant_individuals][:, 0] ** 2
previous_hazard = v.T
# update progress bar
if show_progress:
progress.update(i)
# print a new line so the console displays well
if show_progress:
print()
ordered_cols = df.columns # to_panel() mixes up my columns
self.hazards_ = hazards_.groupby(level=1).sum()[ordered_cols]
self.cumulative_hazards_ = self.hazards_.cumsum()[ordered_cols]
self.variance_ = variance_.groupby(level=1).sum()[ordered_cols]
if timeline is not None:
self.hazards_ = self.hazards_.reindex(timeline, method='ffill')
self.cumulative_hazards_ = self.cumulative_hazards_.reindex(timeline, method='ffill')
self.variance_ = self.variance_.reindex(timeline, method='ffill')
self.timeline = timeline
else:
self.timeline = self.hazards_.index.values.astype(float)
self.data = wp
self.durations = T
self.event_observed = C
self._compute_confidence_intervals()
self.plot = plot_regressions(self)
return
def smoothed_hazards_(self, bandwidth=1):
"""
Using the epanechnikov kernel to smooth the hazard function, with sigma/bandwidth
"""
return pd.DataFrame(np.dot(epanechnikov_kernel(self.timeline[:, None], self.timeline, bandwidth), self.hazards_.values),
columns=self.hazards_.columns, index=self.timeline)
def _compute_confidence_intervals(self):
alpha2 = inv_normal_cdf(1 - (1 - self.alpha) / 2)
n = self.timeline.shape[0]
d = self.cumulative_hazards_.shape[1]
index = [['upper'] * n + ['lower'] * n, np.concatenate([self.timeline, self.timeline])]
self.confidence_intervals_ = pd.DataFrame(np.zeros((2 * n, d)),
index=index,
columns=self.cumulative_hazards_.columns
)
self.confidence_intervals_.ix['upper'] = self.cumulative_hazards_.values + \
alpha2 * np.sqrt(self.variance_.cumsum().values)
self.confidence_intervals_.ix['lower'] = self.cumulative_hazards_.values - \
alpha2 * np.sqrt(self.variance_.cumsum().values)
return
def predict_cumulative_hazard(self, X, id_col=None):
"""
X: a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as the training data.
Returns the hazard rates for the individuals
"""
if id_col is not None:
# see https://github.com/CamDavidsonPilon/lifelines/issues/38
raise NotImplementedError
n, d = X.shape
cols = get_index(X)
if isinstance(X, pd.DataFrame):
order = self.cumulative_hazards_.columns
order = order.drop('baseline') if self.fit_intercept else order
X_ = X[order].values.copy()
else:
X_ = X.copy()
X_ = X_ if not self.fit_intercept else np.c_[X_, np.ones((n, 1))]
return pd.DataFrame(np.dot(self.cumulative_hazards_, X_.T), index=self.timeline, columns=cols)
def predict_survival_function(self, X):
"""
X: a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as the training data.
Returns the survival functions for the individuals
"""
return np.exp(-self.predict_cumulative_hazard(X))
def predict_percentile(self, X, p=0.5):
"""
X: a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as the training data.
Returns the median lifetimes for the individuals.
http://stats.stackexchange.com/questions/102986/percentile-loss-functions
"""
index = get_index(X)
return qth_survival_times(p, self.predict_survival_function(X)[index])
def predict_median(self, X):
"""
X: a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as the training data.
Returns the median lifetimes for the individuals
"""
return self.predict_percentile(X, 0.5)
def predict_expectation(self, X):
"""
Compute the expected lifetime, E[T], using covarites X.
X: a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as the training data.
Returns the expected lifetimes for the individuals
"""
index = get_index(X)
t = self.cumulative_hazards_.index
return pd.DataFrame(trapz(self.predict_survival_function(X)[index].values.T, t), index=index)
def predict(self, X):
return self.predict_median(X)
class CoxPHFitter(BaseFitter):
"""
This class implements fitting Cox's proportional hazard model:
h(t|x) = h_0(t)*exp(x'*beta)
Parameters:
alpha: the level in the confidence intervals.
tie_method: specify how the fitter should deal with ties. Currently only
'Efron' is available.
normalize: substract the mean and divide by standard deviation of each covariate
in the input data before performing any fitting.
penalizer: Attach a L2 penalizer to the size of the coeffcients during regression. This improves
stability of the estimates and controls for high correlation between covariates.
For example, this shrinks the absolute value of beta_i. Recommended, even if a small value.
The penalty is 1/2 * penalizer * ||beta||^2.
"""
def __init__(self, alpha=0.95, tie_method='Efron', normalize=True, penalizer=0.0):
if not (0 < alpha <= 1.):
raise ValueError('alpha parameter must be between 0 and 1.')
if penalizer < 0:
raise ValueError("penalizer parameter must be >= 0.")
if tie_method != 'Efron':
raise NotImplementedError("Only Efron is available atm.")
self.alpha = alpha
self.normalize = normalize
self.tie_method = tie_method
self.penalizer = penalizer
self.strata = None
def _get_efron_values(self, X, beta, T, E, include_likelihood=False):
"""
Calculates the first and second order vector differentials,
with respect to beta. If 'include_likelihood' is True, then
the log likelihood is also calculated. This is omitted by default
to speed up the fit.
Note that X, T, E are assumed to be sorted on T!
Parameters:
X: (n,d) numpy array of observations.
beta: (1, d) numpy array of coefficients.
T: (n) numpy array representing observed durations.
E: (n) numpy array representing death events.
Returns:
hessian: (d, d) numpy array,
gradient: (1, d) numpy array
log_likelihood: double, if include_likelihood=True
"""
n, d = X.shape
hessian = np.zeros((d, d))
gradient = np.zeros((1, d))
log_lik = 0
# Init risk and tie sums to zero
x_tie_sum = np.zeros((1, d))
risk_phi, tie_phi = 0, 0
risk_phi_x, tie_phi_x = np.zeros((1, d)), np.zeros((1, d))
risk_phi_x_x, tie_phi_x_x = np.zeros((d, d)), np.zeros((d, d))
# Init number of ties
tie_count = 0
# Iterate backwards to utilize recursive relationship
for i, (ti, ei) in reversed(list(enumerate(zip(T, E)))):
# Doing it like this to preserve shape
xi = X[i:i + 1]
# Calculate phi values
phi_i = exp(dot(xi, beta))
phi_x_i = dot(phi_i, xi)
phi_x_x_i = dot(xi.T, xi) * phi_i
# Calculate sums of Risk set
risk_phi += phi_i
risk_phi_x += phi_x_i
risk_phi_x_x += phi_x_x_i
# Calculate sums of Ties, if this is an event
if ei:
x_tie_sum += xi
tie_phi += phi_i
tie_phi_x += phi_x_i
tie_phi_x_x += phi_x_x_i
# Keep track of count
tie_count += 1
if i > 0 and T[i - 1] == ti:
# There are more ties/members of the risk set
continue
elif tie_count == 0:
# Only censored with current time, move on
continue
# There was atleast one event and no more ties remain. Time to sum.
partial_gradient = np.zeros((1, d))
for l in range(tie_count):
c = l / tie_count
denom = (risk_phi - c * tie_phi)
z = (risk_phi_x - c * tie_phi_x)
if denom == 0:
# Can't divide by zero
raise ValueError("Denominator was zero")
# Gradient
partial_gradient += z / denom
# Hessian
a1 = (risk_phi_x_x - c * tie_phi_x_x) / denom
# In case z and denom both are really small numbers,
# make sure to do division before multiplications
a2 = dot(z.T / denom, z / denom)
hessian -= (a1 - a2)
if include_likelihood:
log_lik -= np.log(denom).ravel()[0]
# Values outside tie sum
gradient += x_tie_sum - partial_gradient
if include_likelihood:
log_lik += dot(x_tie_sum, beta).ravel()[0]
# reset tie values
tie_count = 0
x_tie_sum = np.zeros((1, d))
tie_phi = 0
tie_phi_x = np.zeros((1, d))
tie_phi_x_x = np.zeros((d, d))
if include_likelihood:
return hessian, gradient, log_lik
else:
return hessian, gradient
def _newton_rhaphson(self, X, T, E, initial_beta=None, step_size=1.,
precision=10e-5, show_progress=True, include_likelihood=False):
"""
Newton Rhaphson algorithm for fitting CPH model.
Note that data is assumed to be sorted on T!
Parameters:
X: (n,d) Pandas DataFrame of observations.
T: (n) Pandas Series representing observed durations.
E: (n) Pandas Series representing death events.
initial_beta: (1,d) numpy array of initial starting point for
NR algorithm. Default 0.
step_size: float > 0.001 to determine a starting step size in NR algorithm.
precision: the convergence halts if the norm of delta between
successive positions is less than epsilon.
include_likelihood: saves the final log-likelihood to the CoxPHFitter under _log_likelihood.
Returns:
beta: (1,d) numpy array.
"""
assert precision <= 1., "precision must be less than or equal to 1."
n, d = X.shape
# Want as bools
E = E.astype(bool)
# make sure betas are correct size.
if initial_beta is not None:
assert initial_beta.shape == (d, 1)
beta = initial_beta
else:
beta = np.zeros((d, 1))
# Method of choice is just efron right now
if self.tie_method == 'Efron':
get_gradients = self._get_efron_values
else:
raise NotImplementedError("Only Efron is available.")
i = 1
converging = True
# 50 iterations steps with N-R is a lot.
# Expected convergence is ~10 steps
while converging and i < 50 and step_size > 0.001:
if self.strata is None:
output = get_gradients(X.values, beta, T.values, E.values, include_likelihood=include_likelihood)
h, g = output[:2]
else:
g = np.zeros_like(beta).T
h = np.zeros((beta.shape[0], beta.shape[0]))
ll = 0
for strata in np.unique(X.index):
stratified_X, stratified_T, stratified_E = X.loc[[strata]], T.loc[[strata]], E.loc[[strata]]
output = get_gradients(stratified_X.values, beta, stratified_T.values, stratified_E.values, include_likelihood=include_likelihood)
_h, _g = output[:2]
g += _g
h += _h
ll += output[2] if include_likelihood else 0
if self.penalizer > 0:
# add the gradient and hessian of the l2 term
g -= self.penalizer * beta.T
h.flat[::d + 1] -= self.penalizer
delta = solve(-h, step_size * g.T)
if np.any(np.isnan(delta)):
raise ValueError("delta contains nan value(s). Convergence halted.")
# Only allow small steps
if norm(delta) > 10:
step_size *= 0.5
continue
beta += delta
# Save these as pending result
hessian, gradient = h, g
if norm(delta) < precision:
converging = False
if ((i % 10) == 0) and show_progress:
print("Iteration %d: delta = %.5f" % (i, norm(delta)))
i += 1
self._hessian_ = hessian
self._score_ = gradient
if include_likelihood:
self._log_likelihood = output[-1] if self.strata is None else ll
if show_progress:
print("Convergence completed after %d iterations." % (i))
return beta
def fit(self, df, duration_col, event_col=None,
show_progress=False, initial_beta=None, include_likelihood=False,
strata=None):
"""
Fit the Cox Propertional Hazard model to a dataset. Tied survival times
are handled using Efron's tie-method.
Parameters:
df: a Pandas dataframe with necessary columns `duration_col` and
`event_col`, plus other covariates. `duration_col` refers to
the lifetimes of the subjects. `event_col` refers to whether
the 'death' events was observed: 1 if observed, 0 else (censored).
duration_col: the column in dataframe that contains the subjects'
lifetimes.
event_col: the column in dataframe that contains the subjects' death
observation. If left as None, assume all individuals are non-censored.
show_progress: since the fitter is iterative, show convergence
diagnostics.
initial_beta: initialize the starting point of the iterative
algorithm. Default is the zero vector.
include_likelihood: saves the final log-likelihood to the CoxPHFitter under
the property _log_likelihood.
strata: specify a list of columns to use in stratification. This is useful if a
catagorical covariate does not obey the proportional hazard assumption. This
is used similar to the `strata` expression in R.
See http://courses.washington.edu/b515/l17.pdf.
Returns:
self, with additional properties: hazards_
"""
df = df.copy()
# Sort on time
df.sort(duration_col, inplace=True)
# remove strata coefs
self.strata = strata
if strata is not None:
df = df.set_index(strata)
# Extract time and event
T = df[duration_col]
del df[duration_col]
if event_col is None:
E = pd.Series(np.ones(df.shape[0]), index=df.index)
else:
E = df[event_col]
del df[event_col]
# Store original non-normalized data
self.data = df if self.strata is None else df.reset_index()
if self.normalize:
# Need to normalize future inputs as well
self._norm_mean = df.mean(0)
self._norm_std = df.std(0)
df = normalize(df)
E = E.astype(bool)
self._check_values(df)
hazards_ = self._newton_rhaphson(df, T, E, initial_beta=initial_beta,
show_progress=show_progress,
include_likelihood=include_likelihood)
self.hazards_ = pd.DataFrame(hazards_.T, columns=df.columns,
index=['coef'])
self.confidence_intervals_ = self._compute_confidence_intervals()
self.durations = T
self.event_observed = E
self.baseline_hazard_ = self._compute_baseline_hazard()
self.baseline_cumulative_hazard_ = self.baseline_hazard_.cumsum()
self.baseline_survival_ = exp(-self.baseline_cumulative_hazard_)
return self
def _check_values(self, X):
low_var = (X.var(0) < 10e-5)
if low_var.any():
cols = str(list(X.columns[low_var]))
print("Warning: column(s) %s have very low variance.\
This may harm convergence." % cols)
def _compute_confidence_intervals(self):
alpha2 = inv_normal_cdf((1. + self.alpha) / 2.)
se = self._compute_standard_errors()
hazards = self.hazards_.values
return pd.DataFrame(np.r_[hazards - alpha2 * se,
hazards + alpha2 * se],
index=['lower-bound', 'upper-bound'],
columns=self.hazards_.columns)
def _compute_standard_errors(self):
se = np.sqrt(inv(-self._hessian_).diagonal())
return pd.DataFrame(se[None, :],
index=['se'], columns=self.hazards_.columns)
def _compute_z_values(self):
return (self.hazards_.ix['coef'] /
self._compute_standard_errors().ix['se'])
def _compute_p_values(self):
U = self._compute_z_values() ** 2
return stats.chi2.sf(U, 1)
@property
def summary(self):
"""Summary statistics describing the fit.
Set alpha property in the object before calling.
Returns
-------
df : pd.DataFrame
Contains columns coef, exp(coef), se(coef), z, p, lower, upper"""
df = pd.DataFrame(index=self.hazards_.columns)
df['coef'] = self.hazards_.ix['coef'].values
df['exp(coef)'] = exp(self.hazards_.ix['coef'].values)
df['se(coef)'] = self._compute_standard_errors().ix['se'].values
df['z'] = self._compute_z_values()
df['p'] = self._compute_p_values()
df['lower %.2f' % self.alpha] = self.confidence_intervals_.ix['lower-bound'].values
df['upper %.2f' % self.alpha] = self.confidence_intervals_.ix['upper-bound'].values
return df
def print_summary(self):
"""
Print summary statistics describing the fit.
"""
df = self.summary
# Significance codes last
df[''] = [significance_code(p) for p in df['p']]
# Print information about data first
print('n={}, number of events={}'.format(self.data.shape[0],
np.where(self.event_observed)[0].shape[0]),
end='\n\n')
print(df.to_string(float_format=lambda f: '{:.3e}'.format(f)))
# Significance code explanation
print('---')
print("Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ",
end='\n\n')
print("Concordance = {:.3f}"
.format(concordance_index(self.durations,
-self.predict_partial_hazard(self.data).values.ravel(),
self.event_observed)))
return
def predict_partial_hazard(self, X):
"""
X: a (n,d) covariate matrix
If covariates were normalized during fitting, they are normalized
in the same way here.
If X is a dataframe, the order of the columns do not matter. But
if X is an array, then the column ordering is assumed to be the
same as the training dataset.
Returns the partial hazard for the individuals, partial since the
baseline hazard is not included. Equal to \exp{\beta X}
"""
index = get_index(X)
if isinstance(X, pd.DataFrame):
order = self.hazards_.columns
X = X[order]
if self.normalize:
# Assuming correct ordering and number of columns
X = normalize(X, self._norm_mean.values, self._norm_std.values)
return pd.DataFrame(exp(np.dot(X, self.hazards_.T)), index=index)
def predict_cumulative_hazard(self, X):
"""
X: a (n,d) covariate matrix
Returns the cumulative hazard for the individuals.
"""
v = self.predict_partial_hazard(X)
s_0 = self.baseline_survival_
col = get_index(X)
return pd.DataFrame(-np.dot(np.log(s_0), v.T), index=self.baseline_survival_.index, columns=col)
def predict_survival_function(self, X):
"""
X: a (n,d) covariate matrix
Returns the survival functions for the individuals
"""
return exp(-self.predict_cumulative_hazard(X))
def predict_percentile(self, X, p=0.5):
"""
X: a (n,d) covariate matrix
Returns the median lifetimes for the individuals.
http://stats.stackexchange.com/questions/102986/percentile-loss-functions
"""
index = get_index(X)
return qth_survival_times(p, self.predict_survival_function(X)[index])
def predict_median(self, X):
"""
X: a (n,d) covariate matrix
Returns the median lifetimes for the individuals
"""
return self.predict_percentile(X, 0.5)
def predict_expectation(self, X):
"""
Compute the expected lifetime, E[T], using covarites X.
"""
index = get_index(X)
v = self.predict_survival_function(X)[index]
return pd.DataFrame(trapz(v.values.T, v.index), index=index)
def predict(self, X):
return self.predict_median(X)
def _compute_baseline_hazard(self):
# http://courses.nus.edu.sg/course/stacar/internet/st3242/handouts/notes3.pdf
ind_hazards = self.predict_partial_hazard(self.data).values
event_table = survival_table_from_events(self.durations.values,
self.event_observed.values)
baseline_hazard_ = pd.DataFrame(np.zeros((event_table.shape[0], 1)),
index=event_table.index,
columns=['baseline hazard'])
for t, s in event_table.iterrows():
less = np.array(self.durations >= t)
if ind_hazards[less].sum() == 0:
v = 0
else:
v = (s['observed'] / ind_hazards[less].sum())
baseline_hazard_.ix[t] = v
return baseline_hazard_
def get_index(X):
if isinstance(X, pd.DataFrame):
index = list(X.index)
else:
# If it's not a dataframe, order is up to user
index = list(range(X.shape[0]))
return index
def _conditional_time_to_event_(fitter):
"""
Return a DataFrame, with index equal to survival_function_, that estimates the median
duration remaining until the death event, given survival up until time t. For example, if an
individual exists until age 1, their expected life remaining *given they lived to time 1*
might be 9 years.
Returns:
conditional_time_to_: DataFrame, with index equal to survival_function_
"""
age = fitter.survival_function_.index.values[:, None]
columns = ['%s - Conditional time remaining to event' % fitter._label]
return pd.DataFrame(qth_survival_times(fitter.survival_function_[fitter._label] * 0.5, fitter.survival_function_).T.sort(ascending=False).values,
index=fitter.survival_function_.index,
columns=columns) - age
def _subtract(fitter, estimate):
class_name = fitter.__class__.__name__
doc_string = """
Subtract the %s of two %s objects.
Parameters:
other: an %s fitted instance.
""" % (estimate, class_name, class_name)
def subtract(other):
self_estimate = getattr(fitter, estimate)
other_estimate = getattr(other, estimate)
new_index = np.concatenate((other_estimate.index, self_estimate.index))
new_index = np.unique(new_index)
return self_estimate.reindex(new_index, method='ffill') - \
other_estimate.reindex(new_index, method='ffill')
subtract.__doc__ = doc_string
return subtract
def _divide(fitter, estimate):
class_name = fitter.__class__.__name__
doc_string = """
Divide the %s of two %s objects.
Parameters:
other: an %s fitted instance.
""" % (estimate, class_name, class_name)
def divide(other):
self_estimate = getattr(fitter, estimate)
other_estimate = getattr(other, estimate)
new_index = np.concatenate((other_estimate.index, self_estimate.index))
new_index = np.unique(new_index)
return self_estimate.reindex(new_index, method='ffill') / \
other_estimate.reindex(new_index, method='ffill')
divide.__doc__ = doc_string
return divide
def _predict(fitter, estimate, label):
class_name = fitter.__class__.__name__
doc_string = """
Predict the %s at certain point in time.
Parameters:
time: a scalar or an array of times to predict the value of %s at.
Returns:
predictions: a scalar if time is a scalar, a numpy array if time in an array.
""" % (class_name, class_name)
def predict(time):
predictor = lambda t: getattr(fitter, estimate).ix[:t].iloc[-1][label]
try:
return np.array([predictor(t) for t in time])
except TypeError:
return predictor(time)
predict.__doc__ = doc_string
return predict
def preprocess_inputs(durations, event_observed, timeline, entry):
n = len(durations)
durations = np.asarray(durations).reshape((n,))
# set to all observed if event_observed is none
if event_observed is None:
event_observed = np.ones(n, dtype=int)
else:
event_observed = np.asarray(event_observed).reshape((n,)).copy().astype(int)
if entry is not None:
entry = np.asarray(entry).reshape((n,))
event_table = survival_table_from_events(durations, event_observed, entry)
if timeline is None:
timeline = event_table.index.values
else:
timeline = np.asarray(timeline)
return durations, event_observed, timeline.astype(float), entry, event_table
def _additive_estimate(events, timeline, _additive_f, _additive_var, reverse):
"""
Called to compute the <NAME> and Nelson-Aalen estimates.
"""
if reverse:
events = events.sort_index(ascending=False)
population = events['entrance'].sum() - events['removed'].cumsum().shift(1).fillna(0)
deaths = events['observed'].shift(1).fillna(0)
estimate_ = np.cumsum(_additive_f(population, deaths)).ffill().sort_index()
var_ = np.cumsum(_additive_var(population, deaths)).ffill().sort_index()
else:
deaths = events['observed']
population = events['entrance'].cumsum() - events['removed'].cumsum().shift(1).fillna(0) # slowest line here.
estimate_ = np.cumsum(_additive_f(population, deaths))
var_ = np.cumsum(_additive_var(population, deaths))
timeline = sorted(timeline)
estimate_ = estimate_.reindex(timeline, method='pad').fillna(0)
var_ = var_.reindex(timeline, method='pad')
var_.index.name = 'timeline'
estimate_.index.name = 'timeline'
return estimate_, var_
def qth_survival_times(q, survival_functions):
"""
This can be done much better.
Parameters:
q: a float between 0 and 1.
survival_functions: a (n,d) dataframe or numpy array.
If dataframe, will return index values (actual times)
If numpy array, will return indices.
Returns:
v: if d==1, returns a float, np.inf if infinity.
if d > 1, an DataFrame containing the first times the value was crossed.
"""
q = pd.Series(q)
assert (q <= 1).all() and (0 <= q).all(), 'q must be between 0 and 1'
survival_functions = pd.DataFrame(survival_functions)
if survival_functions.shape[1] == 1 and q.shape == (1,):
return survival_functions.apply(lambda s: qth_survival_time(q[0], s)).ix[0]
else:
return pd.DataFrame({q_: survival_functions.apply(lambda s: qth_survival_time(q_, s)) for q_ in q})
def qth_survival_time(q, survival_function):
"""
Expects a Pandas series, returns the time when the qth probability is reached.
"""
if survival_function.iloc[-1] > q:
return np.inf
v = (survival_function <= q).idxmax(0)
return v
def median_survival_times(survival_functions):
return qth_survival_times(0.5, survival_functions)
"""
References:
[1] <NAME>., <NAME>., <NAME>., 2008. Survival and Event History Analysis
"""
<file_sep>from __future__ import division
import numpy as np
def _negative_log_likelihood(lambda_rho, T, E):
if np.any(lambda_rho < 0):
return np.inf
lambda_, rho = lambda_rho
return - np.log(rho * lambda_) * E.sum() - (rho - 1) * (E * np.log(lambda_ * T)).sum() + ((lambda_ * T) ** rho).sum()
def _lambda_gradient(lambda_rho, T, E):
lambda_, rho = lambda_rho
return - rho * (E / lambda_ - (lambda_ * T) ** rho / lambda_).sum()
def _rho_gradient(lambda_rho, T, E):
lambda_, rho = lambda_rho
return - E.sum() / rho - (np.log(lambda_ * T) * E).sum() + (np.log(lambda_ * T) * (lambda_ * T) ** rho).sum()
# - D/p - D Log[m t] + (m t)^p Log[m t]
def _d_rho_d_rho(lambda_rho, T, E):
lambda_, rho = lambda_rho
return (1. / rho ** 2 * E + (np.log(lambda_ * T) ** 2 * (lambda_ * T) ** rho)).sum()
# (D/p^2) + (m t)^p Log[m t]^2
def _d_lambda_d_lambda_(lambda_rho, T, E):
lambda_, rho = lambda_rho
return (rho / lambda_ ** 2) * (E + (rho - 1) * (lambda_ * T) ** rho).sum()
def _d_rho_d_lambda_(lambda_rho, T, E):
lambda_, rho = lambda_rho
return (-1. / lambda_) * (E - (lambda_ * T) ** rho - rho * (lambda_ * T) ** rho * np.log(lambda_ * T)).sum()
| 10d88777b738fec34a95d2e8ef2d3c1b60baae2d | [
"Python"
]
| 2 | Python | dhuynh/lifelines | ad69313fb4c51ec9f69395874a6e79900e580a4b | 8510e0a3b86290454c7c055c439a2caa6a11f0c3 |
refs/heads/master | <file_sep>from . import fauxtograph
from . import vaegan
VAE = fauxtograph.VAE
GAN = fauxtograph.GAN
VAEGAN = fauxtograph.VAEGAN
get_paths = fauxtograph.get_paths
image_resize = fauxtograph.image_resize
calc_fc_size = vaegan.calc_fc_size
calc_im_size = vaegan.calc_im_size
<file_sep>
# coding: utf-8
# # VAE+GAN
# githubにあがってたものを利用する
import sys, os
import numpy as np
import pandas as pd
import six
import math
from PIL import Image
from StringIO import StringIO
import matplotlib.pyplot as plt
import chainer
from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
from chainer.functions.loss.vae import gaussian_kl_divergence
import chainer.optimizers as O
import tqdm
import time
from IPython.display import display
import json
from vaegan import Encoder, Decoder, Discriminator, EncDec
from fauxtograph import VAEGAN, get_paths, image_resize
paths = get_paths('/home/tokita/projects/cinet/YouTubePriors_flv4/DividedImages/images_resize/sample_train/')
print len(paths)
# ########### モデルのインスタンス生成
vg = VAEGAN(img_width=96, img_height=96, flag_gpu=True)
# 画像ファイルのロード、正規化、transpose
x_all = vg.load_images(paths)
print 'image_data_shape = {}'.format(x_all.shape)
#vg.fit(x_all, n_epochs=10, mirroring=True)
m_path = '/home/tokita/workspace/projects/NTTD_CiNet/modelAutoEncoder/fauxtograph/out/model/'
im_path = '/home/tokita/workspace/projects/NTTD_CiNet/modelAutoEncoder/fauxtograph/out/images/'
vg.fit(x_all, save_freq=2, pic_freq=-1, n_epochs=4, model_path = m_path, img_path=im_path, mirroring=True)
# loss系列の保存
vg.loss_buf.to_csv('./out/loss_vaegan_faux.csv')
<file_sep>
# coding: utf-8
# # オートエンコーダー(一般画像)
# 学習済みのモデルファイルを入力して中間表現ベクトルと再構成画像を出力する
# * 中間層にKL正規化項を入れ、変分AEにしている
# * ネットワークはConvolution - Deconcolutionネットワークを使う
import sys, os
import numpy as np
import pandas as pd
from PIL import Image
from StringIO import StringIO
import math
import argparse
import six
import chainer
from chainer import Variable
import tables
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# AEモデルクラスのimport
from model_VAE import VAE, EncodeDecode
## 画像を描画して保存する関数
def draw_img_rgb(data, fig_path):
n = data.shape[0]
plt.figure(figsize=(n*2, 2))
plt.clf()
data /= data.max()
cnt = 1
for idx in np.arange(n):
plt.subplot(1, n, cnt)
tmp = data[idx,:,:,:].transpose(2,1,0)
plt.imshow(tmp)
plt.tick_params(labelbottom="off")
plt.tick_params(labelleft="off")
cnt+=1
plt.savefig(fig_path)
parser = argparse.ArgumentParser(description='option')
parser.add_argument('--img_file', '-img', default='../DataSet/Stimuli.mat', type=str)
parser.add_argument('--model_file', default='out/out_models_vae_stim01/model_VAE_00500.h5', type=str)
args = parser.parse_args()
# ## データのロード
# load images
print("loading image_files : {}".format(args.img_file))
## 刺激画像
fileStimuli = args.img_file
dataStimuli = tables.openFile(fileStimuli)
imgStimuli = dataStimuli.get_node('/st')[:]
imgStimuliVd = dataStimuli.get_node('/sv')[:]
print 'DataShape [Stimuli] : {}'.format(imgStimuli.shape)
print 'DataShape [Stimuli for varidation] : {}'.format(imgStimuliVd.shape)
## 15fpsで映像を見せているので、15枚ずつ間引く
x_train = imgStimuli[np.arange(0, imgStimuli.shape[0], 15)]
x_train = x_train.astype(np.float32)
### テストデータ
x_test = imgStimuliVd[np.arange(0, imgStimuliVd.shape[0], 15)]
x_test = x_test.astype(np.float32)
## データの正規化
x_train = x_train / 255
x_test = x_test / 255
print 'x_train.shape={}'.format(x_train.shape)
print 'x_test.shape={}'.format(x_test.shape)
N_train = x_train.shape[0]
N_test = x_test.shape[0]
print('N_train={}, N_test={}'.format(N_train, N_test))
## モデルのロード
print 'model_file : {}'.format(args.model_file)
ae = EncodeDecode(model_file=args.model_file)
## 中間表現ベクトルの取得
test_ind = np.random.permutation(N_test)[:10]
test = chainer.Variable(np.asarray(x_test[test_ind]), volatile='on')
z = ae.getLatentVector(test)
print 'latent_vector : {}'.format(z.data.shape)
## 再構成画像の取得
y = ae.getReconstructImage(z)
## 画像の出力
draw_img_rgb(test.data, "input_images.png")
draw_img_rgb(y.data, "reconstruct_images.png")
<file_sep>
# coding: utf-8
# # オートエンコーダー(一般画像)
# VAE+GAN
import sys, os
import numpy as np
import pandas as pd
from PIL import Image
from StringIO import StringIO
import math
import argparse
import six
import chainer
from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
from chainer.functions.loss.vae import gaussian_kl_divergence
from model_VAEGAN import Encoder, Decoder, Discriminator
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser(description='option')
parser.add_argument('--gpu', '-g', default=2, type=int)
parser.add_argument('--label', '-l', default='test', type=str)
parser.add_argument('--train_dir', default='/home/tokita/projects/cinet/YouTubePriors_flv4/DividedImages/images_resize/sample_train', type=str)
parser.add_argument('--test_dir', default='/home/tokita/projects/cinet/YouTubePriors_flv4/DividedImages/images_resize/sample_test', type=str)
parser.add_argument('--img_size', default=96, type=int)
parser.add_argument('--batch_size', default=100, type=int)
parser.add_argument('--epoch_num', default=10, type=int)
parser.add_argument('--latent_dimension', default=1000, type=int)
parser.add_argument('--max_convolution_size', default=512, type=int)
parser.add_argument('--adam_alpha', default=0.0001, type=float)
parser.add_argument('--adam_beta1', default=0.5, type=float)
parser.add_argument('--adam_beta2', default=0.999, type=float)
parser.add_argument('--kl_weight', default=1.0, type=float)
parser.add_argument('--gamma', default=1.0, type=float)
parser.add_argument('--out_interval', default=100, type=int)
args = parser.parse_args()
# ##### データのロード用のメソッド
def load_image(dir_name):
fs = os.listdir(dir_name)
data_set = []
for fn in fs:
f = open('%s/%s'%(dir_name, fn), 'rb')
img_bin = f.read()
img = np.asarray(Image.open(StringIO(img_bin)).convert('RGB')).astype(np.float32).transpose(2, 0, 1)
data_set.append(img)
f.close()
data_set = np.asarray(data_set)
# 正規化(0~1に)
data_set /= 255
return data_set
# ##### 画像を描画する関数
def draw_img_rgb(data, fig_path):
n = data.shape[0]
plt.figure(figsize=(n*2, 2))
plt.clf()
data /= data.max()
cnt = 1
for idx in np.arange(n):
plt.subplot(1, n, cnt)
tmp = data[idx,:,:,:].transpose(1,2,0)
plt.imshow(tmp)
plt.tick_params(labelbottom="off")
plt.tick_params(labelleft="off")
cnt+=1
plt.savefig(fig_path)
# ## GPU設定
gpu_flag = args.gpu
if gpu_flag >= 0:
cuda.check_cuda_available()
xp = cuda.cupy if gpu_flag >= 0 else np
print "##### start : chainer_VAEGAN.py"
# ## 学習パラメータの設定
batchsize = args.batch_size # ミニバッチのサイズ
n_epoch = args.epoch_num # epoch数
n_latent = args.latent_dimension # 潜在変数の次元(DCGANで言うところのプライヤーベクトルの次元)
conv_size = args.max_convolution_size # convolution層の最大チャネルサイズ
kl_weight = args.kl_weight # KL正則化項の重み
gamma = args.gamma # VAEとGANの重みを変えるためのパラメータ
# Optimizer(Adam)
al = args.adam_alpha
b1 = args.adam_beta1
b2 = args.adam_beta2
# 学習データセット
# img_size
size = args.img_size
# image path
#image_dir = args.img_dir
dir_train = args.train_dir
dir_test = args.test_dir
# モデルの出力インターバル
model_interval = args.out_interval
# モデルファイルの出力先
out_model_dir = './out/out_models_%s'%args.label
try:
os.mkdir(out_model_dir)
except:
pass
## 学習パラメータの設定ここまで
# ## パラメータの確認
print('epoch_num={}'.format(n_epoch))
print('latent_dimension={}'.format(n_latent))
print('KL_Weight={}'.format(kl_weight))
print('AdamParameter(alpha, b1, b2) = {}, {}, {}'.format(al, b1, b2))
print('output_directory={}'.format(out_model_dir))
# ## データのロード
x_train = load_image(dir_train)
x_test = load_image(dir_test)
print 'x_train.shape={}'.format(x_train.shape)
print 'x_test.shape={}'.format(x_test.shape)
N_train = x_train.shape[0]
N_test = x_test.shape[0]
print('N_train={}, N_test={}'.format(N_train, N_test))
sys.stdout.flush()
# ## モデルの定義
encode = Encoder(input_size=size, n_latent=n_latent, output_ch=conv_size)
decode = Decoder(input_size=size, n_latent=n_latent, output_ch=conv_size)
disc = Discriminator(input_size=size, n_latent=n_latent, output_ch=conv_size)
# GPU設定
if gpu_flag >= 0:
cuda.get_device(gpu_flag).use()
encode.to_gpu()
decode.to_gpu()
disc.to_gpu()
xp = np if gpu_flag < 0 else cuda.cupy
# Optimizerの設定
o_enc = optimizers.Adam(alpha=al, beta1=b1, beta2=b2)
o_dec = optimizers.Adam(alpha=al, beta1=b1, beta2=b2)
o_dis = optimizers.Adam(alpha=al, beta1=b1, beta2=b2)
o_enc.setup(encode)
o_dec.setup(decode)
o_dis.setup(disc)
# ## 訓練の実行
print 'epoch, loss_enc, loss_dec, loss_dis, gan_loss, like_loss, prior_loss'
df_col = ['epoch', 'enc_loss', 'dec_loss', 'dis_loss', 'GAN_loss', 'like_loss', 'prior_loss', 'L_base', 'L_rec', 'L_p']
loss_buf = pd.DataFrame(columns=df_col)
for epoch in six.moves.range(1, n_epoch + 1):
# training
## 訓練データのsampler
perm = np.random.permutation(N_train)
## lossのbuffer
sum_enc_loss = 0.
sum_dec_loss = 0.
sum_dis_loss = 0.
sum_gan_loss = 0.
sum_like_loss = 0.
sum_prior_loss = 0.
sum_L_base = 0.
sum_L_rec = 0.
sum_L_p = 0.
## バッチ学習
for i in six.moves.range(0, N_train, batchsize):
x = chainer.Variable(xp.asarray(x_train[perm[i:i + batchsize]])) # バッチ分のデータの抽出
##### ForwardとLossの計算
# KL距離
mu, ln_var = encode(x, test=False)
x_rec = decode(mu, sigmoid=True)
batchsize = len(mu.data)
kl_loss = gaussian_kl_divergence(mu, ln_var) / reduce(lambda x,y:x*y, mu.data.shape)
# ランダムzの生成とランダムzでのdecode ## zはN(0, 1)から生成
z_p = xp.random.standard_normal(mu.data.shape).astype('float32')
z_p = chainer.Variable(z_p)
x_p = decode(z_p)
# Discriminatorの出力を得る
d_x_rec, h_out_rec = disc(x_rec)
d_x_base, h_out_base = disc(x)
d_x_p, h_out_p = disc(x_p)
# Discriminatorのsoftmax_cross_entropy
L_rec = F.softmax_cross_entropy(d_x_rec, Variable(xp.zeros(batchsize, dtype=np.int32)))
L_base = F.softmax_cross_entropy(d_x_base, Variable(xp.ones(batchsize, dtype=np.int32)))
L_p = F.softmax_cross_entropy(d_x_p, Variable(xp.zeros(batchsize, dtype=np.int32)))
# Reconstruction Errorを得る(Discriminatorの中間出力の誤差)
rec_loss = (F.mean_squared_error(h_out_rec[0], h_out_base[0])
+ F.mean_squared_error(h_out_rec[1], h_out_base[1])
+ F.mean_squared_error(h_out_rec[2], h_out_base[2])
+ F.mean_squared_error(h_out_rec[3], h_out_base[3]) ) / 4.0
##### Loss計算ここまで
l_gan = (L_base + L_rec + L_p) / 3.0
l_like = rec_loss
l_prior = kl_loss
enc_loss = kl_weight * l_prior + l_like
dec_loss = gamma*l_like - l_gan
dis_loss = l_gan
##### パラメータの更新
# Encoder
o_enc.zero_grads()
enc_loss.backward()
o_enc.update()
# Decoder
o_dec.zero_grads()
dec_loss.backward()
o_dec.update()
#Discriminator
o_dis.zero_grads()
dis_loss.backward()
o_dis.update()
##### パラメータの更新ここまで
sum_enc_loss += enc_loss.data
sum_dec_loss += dec_loss.data
sum_dis_loss += dis_loss.data
sum_gan_loss += l_gan.data
sum_like_loss += l_like.data
sum_prior_loss += l_prior.data
sum_L_base += L_base.data
sum_L_rec += L_rec.data
sum_L_p += L_p.data
print '{}, {}, {}, {}, {}, {}, {}'.format(epoch, sum_enc_loss, sum_dec_loss, sum_dis_loss, sum_gan_loss, sum_like_loss, sum_prior_loss)
df_tmp = pd.DataFrame([[epoch, sum_enc_loss, sum_dec_loss, sum_dis_loss, sum_gan_loss, sum_like_loss, sum_prior_loss, sum_L_base, sum_L_rec, sum_L_p]], columns=df_col)
loss_buf = loss_buf.append(df_tmp, ignore_index=True)
# モデルの保存
if epoch%model_interval==0:
serializers.save_hdf5("%s/model_VAEGAN_Enc_%05d.h5"%(out_model_dir, epoch), encode)
serializers.save_hdf5("%s/model_VAEGAN_Dec_%05d.h5"%(out_model_dir, epoch), decode)
serializers.save_hdf5("%s/model_VAEGAN_Dis_%05d.h5"%(out_model_dir, epoch), disc)
sys.stdout.flush()
# モデルの保存(最終モデル)
if epoch%model_interval!=0:
serializers.save_hdf5("%s/model_VAEGAN_Enc_%05d.h5"%(out_model_dir, epoch), encode)
serializers.save_hdf5("%s/model_VAEGAN_Dec_%05d.h5"%(out_model_dir, epoch), decode)
serializers.save_hdf5("%s/model_VAEGAN_Dis_%05d.h5"%(out_model_dir, epoch), disc)
# lossの保存
loss_buf.to_csv("%s/loss_VAEGAN_%05d.csv"%(out_model_dir, epoch))
## 描画テスト (Closed test)
test_ind = np.random.permutation(N_train)[:10]
print "Reconstruct Test [Closed Test]"
print test_ind
x = chainer.Variable(xp.asarray(x_train[test_ind]), volatile='on')
mu, ln_var = encode(x, test=False)
x_rec = decode(mu, sigmoid=True)
draw_img_rgb(x_train[test_ind], ("%s/image_closed_input.png"%(out_model_dir)))
draw_img_rgb(x_rec.data.get(), ("%s/image_closed_reconstruct.png"%(out_model_dir)))
## 描画テスト (Open test)
test_ind = np.random.permutation(N_test)[:10]
print "Reconstruct Test [Open Test]"
print test_ind
x = chainer.Variable(xp.asarray(x_test[test_ind]), volatile='on')
mu, ln_var = encode(x, test=False)
x_rec = decode(mu, sigmoid=True)
draw_img_rgb(x_train[test_ind], ("%s/image_open_input.png"%(out_model_dir)))
draw_img_rgb(x_rec.data.get(), ("%s/image_open_reconstruct.png"%(out_model_dir)))
<file_sep># Chainer SAMPLES
## Rewuired
* Chainer 1.6 で動作確認。最新バージョンには随時更新予定
<file_sep># -*- coding: utf-8 -*-
import sys, os
import numpy as np
import pandas as pd
import math
import chainer
from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
from chainer.functions.loss.vae import gaussian_kl_divergence
import six
# Encoder
class Encoder(chainer.Chain):
def __init__(self, n_latent=1000, input_size=96, input_ch=3, output_ch=256):
self.input_ch = input_ch
self.output_ch = output_ch
self.input_size = input_size
self.out_size = input_size/(2**4)
super(Encoder, self).__init__(
ec0 = L.Convolution2D(self.input_ch, self.output_ch/8, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.input_ch)),
ec1 = L.Convolution2D(self.output_ch/8, self.output_ch/4, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/8)),
ec2 = L.Convolution2D(self.output_ch/4, self.output_ch/2, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/4)),
ec3 = L.Convolution2D(self.output_ch/2, self.output_ch, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/2)),
l4_mu = L.Linear(self.out_size*self.out_size*self.output_ch, n_latent, wscale=0.02*math.sqrt(self.out_size*self.out_size*self.output_ch)),
l4_var = L.Linear(self.out_size*self.out_size*self.output_ch, n_latent, wscale=0.02*math.sqrt(self.out_size*self.out_size*self.output_ch)),
bne0 = L.BatchNormalization(self.output_ch/8),
bne1 = L.BatchNormalization(self.output_ch/4),
bne2 = L.BatchNormalization(self.output_ch/2),
bne3 = L.BatchNormalization(self.output_ch),
)
def __call__(self, x, test=False):
h = F.relu(self.bne0(self.ec0(x), test=test))
h = F.relu(self.bne1(self.ec1(h), test=test))
h = F.relu(self.bne2(self.ec2(h), test=test))
h = F.relu(self.bne3(self.ec3(h), test=test))
mu = F.relu(self.l4_mu(h))
var = F.relu(self.l4_var(h))
return mu, var
# Decoder
class Decoder(chainer.Chain):
def __init__(self, n_latent=1000, input_size=96, input_ch=3, output_ch=256):
self.input_ch = input_ch
self.output_ch = output_ch
self.input_size = input_size
self.out_size = input_size/(2**4)
super(Decoder, self).__init__(
# decoder
l0z = L.Linear(n_latent, self.out_size*self.out_size*self.output_ch, wscale=0.02*math.sqrt(n_latent)),
dc1 = L.Deconvolution2D(self.output_ch, self.output_ch/2, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch)),
dc2 = L.Deconvolution2D(self.output_ch/2, self.output_ch/4, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/2)),
dc3 = L.Deconvolution2D(self.output_ch/4, self.output_ch/8, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/4)),
dc4 = L.Deconvolution2D(self.output_ch/8, self.input_ch, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/8)),
bnd0l = L.BatchNormalization(self.out_size*self.out_size*self.output_ch),
bnd0 = L.BatchNormalization(self.output_ch),
bnd1 = L.BatchNormalization(self.output_ch/2),
bnd2 = L.BatchNormalization(self.output_ch/4),
bnd3 = L.BatchNormalization(self.output_ch/8),
)
def __call__(self, z, sigmoid=True, test=False):
h = F.reshape(F.relu(self.bnd0l(self.l0z(z), test=test)), (z.data.shape[0], self.output_ch, self.out_size, self.out_size))
h = F.relu(self.bnd1(self.dc1(h), test=test))
h = F.relu(self.bnd2(self.dc2(h), test=test))
h = F.relu(self.bnd3(self.dc3(h), test=test))
x = (self.dc4(h))
if sigmoid:
return F.sigmoid(x)
else:
return x
# Discriminator
class Discriminator(chainer.Chain):
def __init__(self, n_latent=1000, input_size=96, input_ch=3, output_ch=256):
self.input_ch = input_ch
self.output_ch = output_ch
self.input_size = input_size
self.out_size = input_size/(2**4)
super(Discriminator, self).__init__(
# discriminator
gc0 = L.Convolution2D(self.input_ch, self.output_ch/8, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.input_ch)),
gc1 = L.Convolution2D(self.output_ch/8, self.output_ch/4, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/8)),
gc2 = L.Convolution2D(self.output_ch/4, self.output_ch/2, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/4)),
gc3 = L.Convolution2D(self.output_ch/2, self.output_ch, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/2)),
gl = L.Linear(self.out_size*self.out_size*self.output_ch, 2, wscale=0.02*math.sqrt(self.out_size*self.out_size*self.output_ch)),
gn0 = L.BatchNormalization(self.output_ch/8),
gn1 = L.BatchNormalization(self.output_ch/4),
gn2 = L.BatchNormalization(self.output_ch/2),
gn3 = L.BatchNormalization(self.output_ch),
)
def __call__(self, rec, test=False):
h0 = F.relu(self.gn0(self.gc0(rec), test=test))
h1 = F.relu(self.gn1(self.gc1(h0), test=test))
h2 = F.relu(self.gn2(self.gc2(h1), test=test))
h3 = F.relu(self.gn3(self.gc3(h2), test=test))
d = self.gl(h3)
hidden_out = [h0, h1, h2, h3]
return d, hidden_out
<file_sep># -*- coding: utf-8 -*-
import sys, os
import numpy as np
import pandas as pd
import math
import chainer
from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
from chainer.functions.loss.vae import gaussian_kl_divergence
import six
class EncodeDecode():
def __init__(self, model_file, n_latent=1000, input_size=96, input_ch=3, output_ch=512):
'''
Arguments:
model_file : 学習ずみモデルファイルのパス付きファイル名 [String]
n_latent : 中間表現ベクトルzの次元数 [Integer]
input_size : 入力画像のサイズ(正方形画像を想定) [Integer]
input_ch : 入力画像のカラーチャネル [Integer]
output_ch : Convolutionネットワークの最大チャネルサイズ [Integer]
'''
self.n_latent = n_latent
self.input_size = input_size
self.input_ch = input_ch
self.output_ch = output_ch
self.model_file = model_file
self.model = VAE(n_latent=n_latent, input_size=input_size, input_ch=input_ch, output_ch=output_ch)
serializers.load_hdf5(self.model_file, self.model)
def getLatentVector(self, images):
'''
中間表現ベクトルを取得する
arguments:
images : 画像データ.
サイズ : [N, ch, width, height]
N=画像枚数, ch=チャネル(カラーの場合3)
0~1に正規化されたデータ
型 : chainer.Variable()
return:
latent_vector : n_latent次元のベクトル
'''
mu, sig = self.model.encode(images)
self.mu = mu
self.sig = sig
return mu
def getReconstructImage(self, z):
y = self.model.decode(z)
return y
class VAE(chainer.Chain):
"""AutoEncoder"""
def __init__(self, n_latent=1000, input_size=128, input_ch=3, output_ch=512):
'''
Arguments:
n_latent : 中間表現ベクトルzの次元数 [Integer]
input_size : 入力画像のサイズ(正方形画像を想定) [Integer]
input_ch : 入力画像のカラーチャネル [Integer]
output_ch : Convolutionネットワークの最大チャネルサイズ [Integer]
'''
self.input_ch = input_ch
self.output_ch = output_ch
self.input_size = input_size
self.out_size = input_size/(2**4)
super(VAE, self).__init__(
## ネットワーク構造の定義
# encoder
c0 = L.Convolution2D(self.input_ch, self.output_ch/8, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.input_ch)),
c1 = L.Convolution2D(self.output_ch/8, self.output_ch/4, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/8)),
c2 = L.Convolution2D(self.output_ch/4, self.output_ch/2, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/4)),
c3 = L.Convolution2D(self.output_ch/2, self.output_ch, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/2)),
l4_mu = L.Linear(self.out_size*self.out_size*self.output_ch, n_latent, wscale=0.02*math.sqrt(self.out_size*self.out_size*self.output_ch)),
l4_var = L.Linear(self.out_size*self.out_size*self.output_ch, n_latent, wscale=0.02*math.sqrt(self.out_size*self.out_size*self.output_ch)),
bne0 = L.BatchNormalization(self.output_ch/8),
bne1 = L.BatchNormalization(self.output_ch/4),
bne2 = L.BatchNormalization(self.output_ch/2),
bne3 = L.BatchNormalization(self.output_ch),
# decoder
l0z = L.Linear(n_latent, self.out_size*self.out_size*self.output_ch, wscale=0.02*math.sqrt(n_latent)),
dc1 = L.Deconvolution2D(self.output_ch, self.output_ch/2, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch)),
dc2 = L.Deconvolution2D(self.output_ch/2, self.output_ch/4, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/2)),
dc3 = L.Deconvolution2D(self.output_ch/4, self.output_ch/8, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/4)),
dc4 = L.Deconvolution2D(self.output_ch/8, self.input_ch, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/8)),
bnd0l = L.BatchNormalization(self.out_size*self.out_size*self.output_ch),
bnd0 = L.BatchNormalization(self.output_ch),
bnd1 = L.BatchNormalization(self.output_ch/2),
bnd2 = L.BatchNormalization(self.output_ch/4),
bnd3 = L.BatchNormalization(self.output_ch/8),
)
def __call__(self, x, sigmoid=True):
"""AutoEncoder"""
# 下記、encodeとdecodeの中身をこの中に書いても良いがencodeとdecodeは他でも使うので再利用性を高めるために
return self.decode(self.encode(x)[0], sigmoid)
def encode(self, x, test=False):
# 推論モデル, 中間表現のベクトルqを学習
h = F.relu(self.bne0(self.c0(x)))
h = F.relu(self.bne1(self.c1(h), test=test))
h = F.relu(self.bne2(self.c2(h), test=test))
h = F.relu(self.bne3(self.c3(h), test=test))
mu = (self.l4_mu(h))
var = (self.l4_var(h))
return mu, var
def decode(self, z, sigmoid=True, test=False):
# 中間表現ベクトルqを入力として(z), 画像を生成
h = F.reshape(F.relu(self.bnd0l(self.l0z(z), test=test)), (z.data.shape[0], self.output_ch, self.out_size, self.out_size))
h = F.relu(self.bnd1(self.dc1(h), test=test))
h = F.relu(self.bnd2(self.dc2(h), test=test))
h = F.relu(self.bnd3(self.dc3(h), test=test))
x = (self.dc4(h))
if sigmoid:
return F.sigmoid(x)
else:
return x
def get_loss_func(self, C=1.0, k=1, train=True):
"""Get loss function of VAE.
Args:
C (int): Usually this is 1.0. Can be changed to control the
second term of ELBO bound, which works as regularization.
k (int): Number of Monte Carlo samples used in encoded vector.
train (bool): If true loss_function is used for training.
"""
def lf(x):
mu, ln_var = self.encode(x)
batchsize = len(mu.data)
# reconstruction loss
rec_loss = 0
for l in six.moves.range(k):
z = F.gaussian(mu, ln_var)
rec_loss += F.bernoulli_nll(x, self.decode(z, sigmoid=False)) / (k * batchsize)
#rec_loss += F.mean_squared_error(x, self.decode(z)) / (k)
self.rec_loss = rec_loss
# reguralization
self.loss = self.rec_loss + C * gaussian_kl_divergence(mu, ln_var) / batchsize
return self.loss
return lf
<file_sep>#!/bin/sh
PYCMD=/home/tokita/.pyenv/shims/python
TIME=`date '+%y/%m/%d %H:%M:%S'`
echo ${TIME} "ae_sp02"
${PYCMD} chainer_AE_image_conv.py --gpu=0 --label=ae_sp02 --epoch_num=200 --latent_dimension=10000 --adam_alpha=0.0001 --out_interval=100 > logs/ae_sp02-20160601.log
TIME=`date '+%y/%m/%d %H:%M:%S'`
echo ${TIME} "ae_sp03"
${PYCMD} chainer_AE_image_conv.py --gpu=0 --label=ae_sp03 --epoch_num=200 --latent_dimension=10000 --adam_alpha=0.001 --out_interval=100 > logs/ae_sp03-20160601.log
TIME=`date '+%y/%m/%d %H:%M:%S'`
echo ${TIME} "ae_sp04"
${PYCMD} chainer_AE_image_conv.py --gpu=0 --label=ae_sp04 --epoch_num=200 --latent_dimension=50000 --adam_alpha=0.0001 --out_interval=100 > logs/ae_sp04-20160601.log
TIME=`date '+%y/%m/%d %H:%M:%S'`
echo ${TIME} "ae_sp05"
${PYCMD} chainer_AE_image_conv.py --gpu=0 --label=ae_sp05 --epoch_num=200 --latent_dimension=10000 --adam_alpha=0.0001 --max_convolution_size=1024 --out_interval=100 > logs/ae_sp05-20160601.log
<file_sep>#!/bin/sh
PYCMD=/home/tokita/.pyenv/shims/python
TIME=`date '+%y/%m/%d %H:%M:%S'`
echo ${TIME} "vae_sp02"
${PYCMD} chainer_VAE_image_conv.py --gpu=1 --label=vae_sp02 --epoch_num=200 --latent_dimension=10000 --kl_weight=1.0 --adam_alpha=0.0001 --out_interval=100 > logs/vae_sp02-20160601.log
TIME=`date '+%y/%m/%d %H:%M:%S'`
echo ${TIME} "vae_sp03"
${PYCMD} chainer_VAE_image_conv.py --gpu=1 --label=vae_sp03 --epoch_num=200 --latent_dimension=10000 --kl_weight=10.0 --adam_alpha=0.0001 --out_interval=100 > logs/vae_sp03-20160601.log
TIME=`date '+%y/%m/%d %H:%M:%S'`
echo ${TIME} "vae_sp04"
${PYCMD} chainer_VAE_image_conv.py --gpu=1 --label=vae_sp04 --epoch_num=200 --latent_dimension=10000 --kl_weight=0.1 --adam_alpha=0.0001 --out_interval=100 > logs/vae_sp04-20160601.log
TIME=`date '+%y/%m/%d %H:%M:%S'`
echo ${TIME} "vae_sp05"
${PYCMD} chainer_VAE_image_conv.py --gpu=1 --label=vae_sp05 --epoch_num=200 --latent_dimension=50000 --kl_weight=1.0 --adam_alpha=0.0001 --out_interval=100 > logs/vae_sp05-20160601.log
<file_sep>
# coding: utf-8
# # オートエンコーダー(一般画像)
# * アニメ顔とかのオートエンコーダーを作ってみる
# * 中間層にKL正規化項を入れ、変分AEにしている
# * ネットワークはConvolution - Deconcolutionネットワークを使う
# In[ ]:
get_ipython().magic(u'matplotlib inline')
import sys, os
import numpy as np
import pandas as pd
from PIL import Image
from StringIO import StringIO
import math
import chainer
from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
from chainer.functions.loss.vae import gaussian_kl_divergence
import six
import matplotlib.pyplot as plt
# chainer exampleに付属のdata.pyをimportする. mnistのダウンロードのため
import data
# ## GPU設定
# In[ ]:
gpu_flag = 0
if gpu_flag >= 0:
cuda.check_cuda_available()
xp = cuda.cupy if gpu_flag >= 0 else np
# ## データのロード
# In[ ]:
# img_size
size = 96
# image path
image_dir = "./images/celeb_sample"
#image_dir = "./images/sample/"
# load images
fs = os.listdir(image_dir)
dataset = []
for fn in fs:
f = open('%s/%s'%(image_dir,fn), 'rb')
img_bin = f.read()
img = np.asarray(Image.open(StringIO(img_bin)).convert('RGB')).astype(np.float32).transpose(2, 0, 1)
dataset.append(img)
f.close()
dataset = np.asarray(dataset)
print("num_of_images : %s"%dataset.shape[0])
## 画素が(-1~1)の範囲に収まるように調整する関数の定義
def clip_img(x):
return np.float32(-1 if x<(-1) else (1 if x>1 else x))
# In[ ]:
def draw_img_mc(data):
size = 96
n = data.shape[0]
plt.figure(figsize=(n*2, 2))
cnt = 1
for idx in np.arange(n):
plt.subplot(1, n, cnt)
X, Y = np.meshgrid(range(size),range(size))
Z = data[idx].reshape(size,size) # convert from vector to 28x28 matrix
Z = Z[::-1,:] # flip vertical
plt.xlim(0,size)
plt.ylim(0,size)
plt.pcolor(X, Y, Z)
plt.gray()
plt.tick_params(labelbottom="off")
plt.tick_params(labelleft="off")
cnt+=1
plt.show()
def draw_img_rgb(data):
size = 96
n = data.shape[0]
plt.figure(figsize=(n*2, 2))
data /= data.max()
cnt = 1
for idx in np.arange(n):
plt.subplot(1, n, cnt)
tmp = data[idx,:,:,:].transpose(1,2,0)
plt.imshow(tmp)
plt.tick_params(labelbottom="off")
plt.tick_params(labelleft="off")
cnt+=1
plt.show()
draw_img_rgb( dataset[np.random.permutation( dataset.shape[0] )[:10]] )
# In[ ]:
N = dataset.shape[0]
train_rate = 0.7
N_train = int(N*train_rate)
N_test = N - N_train
print('N_dataset={}, N_train={}, N_test={}'.format(N, N_train, N_test))
# 正規化(0~1に)
dataset /= 255
# 訓練データとテストデータに分割
x_train, x_test = np.split(dataset, [N_train])
print x_train.shape
## 訓練データとテストデータは決定論的に分割(単純に最初から7割をくんれんデータにして、残りをテストデータ)
# ## 学習パラメータの設定
# In[ ]:
batchsize = 100 # ミニバッチのサイズ
n_epoch = 200 # epoch数
n_latent = 10000 # 潜在変数の次元(DCGANで言うところのプライヤーベクトルの次元)
beta = 1.0 # KL正則化項の重み
conv_size = 512 # convolution層の最大チャネルサイズ
# Optimizer(Adam)
al = 0.0001 # 0.001だと学習が安定しなかった(発散して、nanが出る。正則化項のlossで)
b1 = 0.9
b2 = 0.999
# モデルの出力インターバル
model_interval = 20
# モデルファイルの出力先
out_model_dir = './out/out_models_celeb_vae_01'
try:
os.mkdir(out_model_dir)
except:
pass
# ## モデルの定義
# In[ ]:
class VAE(chainer.Chain):
"""AutoEncoder"""
def __init__(self, n_latent=100, input_size=96, input_ch=3, output_ch=512):
self.input_ch = input_ch
self.output_ch = output_ch
self.input_size = input_size
self.out_size = input_size/(2**4)
super(VAE, self).__init__(
## ネットワーク構造の定義
# encoder
c0 = L.Convolution2D(self.input_ch, self.output_ch/8, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.input_ch)),
c1 = L.Convolution2D(self.output_ch/8, self.output_ch/4, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/8)),
c2 = L.Convolution2D(self.output_ch/4, self.output_ch/2, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/4)),
c3 = L.Convolution2D(self.output_ch/2, self.output_ch, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/2)),
l4_mu = L.Linear(self.out_size*self.out_size*self.output_ch, n_latent, wscale=0.02*math.sqrt(self.out_size*self.out_size*self.output_ch)),
l4_var = L.Linear(self.out_size*self.out_size*self.output_ch, n_latent, wscale=0.02*math.sqrt(self.out_size*self.out_size*self.output_ch)),
bne0 = L.BatchNormalization(self.output_ch/8),
bne1 = L.BatchNormalization(self.output_ch/4),
bne2 = L.BatchNormalization(self.output_ch/2),
bne3 = L.BatchNormalization(self.output_ch),
# decoder
l0z = L.Linear(n_latent, self.out_size*self.out_size*self.output_ch, wscale=0.02*math.sqrt(n_latent)),
dc1 = L.Deconvolution2D(self.output_ch, self.output_ch/2, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch)),
dc2 = L.Deconvolution2D(self.output_ch/2, self.output_ch/4, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/2)),
dc3 = L.Deconvolution2D(self.output_ch/4, self.output_ch/8, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/4)),
dc4 = L.Deconvolution2D(self.output_ch/8, self.input_ch, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/8)),
bnd0l = L.BatchNormalization(self.out_size*self.out_size*self.output_ch),
bnd0 = L.BatchNormalization(self.output_ch),
bnd1 = L.BatchNormalization(self.output_ch/2),
bnd2 = L.BatchNormalization(self.output_ch/4),
bnd3 = L.BatchNormalization(self.output_ch/8),
)
def __call__(self, x, sigmoid=True):
"""AutoEncoder"""
# 下記、encodeとdecodeの中身をこの中に書いても良いがencodeとdecodeは他でも使うので再利用性を高めるために
return self.decode(self.encode(x)[0], sigmoid)
def encode(self, x, test=False):
# 推論モデル, 中間表現のベクトルqを学習
h = F.relu(self.bne0(self.c0(x)))
h = F.relu(self.bne1(self.c1(h), test=test))
h = F.relu(self.bne2(self.c2(h), test=test))
h = F.relu(self.bne3(self.c3(h), test=test))
mu = (self.l4_mu(h))
var = (self.l4_var(h))
return mu, var
def decode(self, z, sigmoid=True, test=False):
# 中間表現ベクトルqを入力として(z), 画像を生成
h = F.reshape(F.relu(self.bnd0l(self.l0z(z), test=test)), (z.data.shape[0], self.output_ch, self.out_size, self.out_size))
h = F.relu(self.bnd1(self.dc1(h), test=test))
h = F.relu(self.bnd2(self.dc2(h), test=test))
h = F.relu(self.bnd3(self.dc3(h), test=test))
x = (self.dc4(h))
if sigmoid:
return F.sigmoid(x)
else:
return x
def get_loss_func(self, C=1.0, k=1, train=True):
"""Get loss function of VAE.
Args:
C (int): Usually this is 1.0. Can be changed to control the
second term of ELBO bound, which works as regularization.
k (int): Number of Monte Carlo samples used in encoded vector.
train (bool): If true loss_function is used for training.
"""
def lf(x):
mu, ln_var = self.encode(x)
batchsize = len(mu.data)
# reconstruction loss
rec_loss = 0
for l in six.moves.range(k):
z = F.gaussian(mu, ln_var)
rec_loss += F.bernoulli_nll(x, self.decode(z, sigmoid=False)) / (k * batchsize)
#rec_loss += F.mean_squared_error(x, self.decode(z)) / (k)
self.rec_loss = rec_loss
# reguralization
self.loss = self.rec_loss + C * gaussian_kl_divergence(mu, ln_var) / batchsize
return self.loss
return lf
# ## Optimizerの設定
# In[ ]:
# モデルの設定
model = VAE(input_size=size, n_latent=n_latent, output_ch=conv_size)
if gpu_flag >= 0:
cuda.get_device(gpu_flag).use()
model.to_gpu()
xp = np if gpu_flag < 0 else cuda.cupy
# Optimizerを定義する
optimizer = optimizers.Adam(alpha=al, beta1=b1, beta2=b2)
optimizer.setup(model)
# ## 訓練の実行
# In[ ]:
loss_arr = []
recloss_arr = []
for epoch in six.moves.range(1, n_epoch + 1):
print('epoch', epoch)
# training
## 訓練データのsampler
perm = np.random.permutation(N_train)
## lossのbuffer
sum_loss = 0 # total loss
sum_rec_loss = 0 # reconstruction loss
## バッチ学習
for i in six.moves.range(0, N_train, batchsize):
x = chainer.Variable(xp.asarray(x_train[perm[i:i + batchsize]])) # バッチ分のデータの抽出
model.zerograds()
loss = model.get_loss_func(C=beta)(x)
loss.backward()
optimizer.update()
sum_loss += float(model.loss.data) * len(x.data)
sum_rec_loss += float(model.rec_loss.data) * len(x.data)
print('train mean loss={}, mean reconstruction loss={}'.format(sum_loss / N, sum_rec_loss / N))
loss_arr.append(float(sum_loss)/N_train)
recloss_arr.append(float(sum_rec_loss)/N_train)
# モデルの保存
if epoch%model_interval==0:
serializers.save_hdf5("%s/model_VAE_%05d.h5"%(out_model_dir, epoch), model)
# モデルの保存(最終モデル)
if epoch%model_interval!=0:
serializers.save_hdf5("%s/model_VAE_%05d.h5"%(out_model_dir, epoch), model)
# ## 結果の可視化
# In[ ]:
plt.figure(figsize=(7, 4))
plt.plot(range(len(loss_arr)), loss_arr, color="#0000FF", label="total_loss")
plt.plot(range(len(recloss_arr)), recloss_arr, color="#FF0000", label="rec_loss")
plt.legend()
plt.plot()
# In[ ]:
## 描画テスト (Closed test)
test_ind = np.random.permutation(N_train)[:10]
print test_ind
test = chainer.Variable(xp.asarray(x_train[test_ind]), volatile='on')
y = model(test)
print "input image"
draw_img_rgb(x_train[test_ind])
print "reconstruction image"
draw_img_rgb(y.data.get())
# In[ ]:
## 描画テスト (Open test)
test_ind = np.random.permutation(N_test)[:10]
print test_ind
test = chainer.Variable(xp.asarray(x_test[test_ind]), volatile='on')
y = model(test)
print "input image"
draw_img_rgb(x_test[test_ind])
print "reconstruction image"
draw_img_rgb(y.data.get())
# In[ ]:
## 描画テスト (Open test, 固定画像)
#test_ind = np.arange(70,80)
test_ind = [1, 4, 6, 8, 42, 70, 76, 79, 153, 156]
print test_ind
test = chainer.Variable(xp.asarray(x_test[test_ind]), volatile='on')
y = model(test)
print "input image"
draw_img_rgb(x_test[test_ind])
print "reconstruction image"
draw_img_rgb(y.data.get())
# In[ ]:
# draw images from randomly sampled z
z = chainer.Variable(xp.random.normal(0, 1, (10, n_latent)).astype(np.float32))
x = model.decode(z)
print "decode image from random vector"
draw_img_rgb(x.data.get())
# ## Convolution層のフィルタを可視化
# In[ ]:
def draw_img_filter(data):
size = data.shape[3]
n = data.shape[0]
n_col = int(math.ceil(n / 15)+1)
img_data = data.get()
plt.figure(figsize=(10*2, n_col*2))
img_data /= img_data.max()
cnt = 1
for idx in np.arange(n):
plt.subplot(n_col, 15, cnt)
tmp = img_data[idx,:,:,:].transpose(1,2,0)
plt.imshow(tmp)
plt.tick_params(labelbottom="off")
plt.tick_params(labelleft="off")
cnt+=1
plt.show()
# In[ ]:
# 入力層側
draw_img_filter(model.c0.W.data)
# In[ ]:
# 出力層側
draw_img_filter(model.dc4.W.data)
# In[ ]:
<file_sep># -*- coding: utf-8 -*-
import sys, os
import numpy as np
import pandas as pd
import math
import chainer
from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
import six
class AE(chainer.Chain):
"""AutoEncoder"""
def __init__(self, n_latent=100, input_size=96, input_ch=3, output_ch=512):
self.input_ch = input_ch
self.output_ch = output_ch
self.input_size = input_size
self.out_size = input_size/(2**4)
super(AE, self).__init__(
## ネットワーク構造の定義
# encoder
c0 = L.Convolution2D(self.input_ch, self.output_ch/8, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.input_ch)),
c1 = L.Convolution2D(self.output_ch/8, self.output_ch/4, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/8)),
c2 = L.Convolution2D(self.output_ch/4, self.output_ch/2, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/4)),
c3 = L.Convolution2D(self.output_ch/2, self.output_ch, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/2)),
l4 = L.Linear(self.out_size*self.out_size*self.output_ch, n_latent, wscale=0.02*math.sqrt(self.out_size*self.out_size*self.output_ch)),
bne0 = L.BatchNormalization(self.output_ch/8),
bne1 = L.BatchNormalization(self.output_ch/4),
bne2 = L.BatchNormalization(self.output_ch/2),
bne3 = L.BatchNormalization(self.output_ch),
# decoder
l0z = L.Linear(n_latent, self.out_size*self.out_size*self.output_ch, wscale=0.02*math.sqrt(n_latent)),
dc1 = L.Deconvolution2D(self.output_ch, self.output_ch/2, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch)),
dc2 = L.Deconvolution2D(self.output_ch/2, self.output_ch/4, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/2)),
dc3 = L.Deconvolution2D(self.output_ch/4, self.output_ch/8, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/4)),
dc4 = L.Deconvolution2D(self.output_ch/8, self.input_ch, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/8)),
bnd0l = L.BatchNormalization(self.out_size*self.out_size*self.output_ch),
bnd0 = L.BatchNormalization(self.output_ch),
bnd1 = L.BatchNormalization(self.output_ch/2),
bnd2 = L.BatchNormalization(self.output_ch/4),
bnd3 = L.BatchNormalization(self.output_ch/8),
)
def __call__(self, x, sigmoid=True):
"""AutoEncoder"""
# 下記、encodeとdecodeの中身をこの中に書いても良いがencodeとdecodeは他でも使うので再利用性を高めるために
return self.decode(self.encode(x), sigmoid)
def encode(self, x, test=False):
# 推論モデル, 中間表現のベクトルqを学習
h = F.relu(self.bne0(self.c0(x)))
h = F.relu(self.bne1(self.c1(h), test=test))
h = F.relu(self.bne2(self.c2(h), test=test))
h = F.relu(self.bne3(self.c3(h), test=test))
z = F.tanh(self.l4(h))
return z
def decode(self, z, sigmoid=True, test=False):
# 中間表現ベクトルqを入力として(z), 画像を生成
h = F.reshape(F.relu(self.bnd0l(self.l0z(z), test=test)), (z.data.shape[0], self.output_ch, self.out_size, self.out_size))
h = F.relu(self.bnd1(self.dc1(h), test=test))
h = F.relu(self.bnd2(self.dc2(h), test=test))
h = F.relu(self.bnd3(self.dc3(h), test=test))
x = (self.dc4(h))
if sigmoid:
return F.sigmoid(x)
else:
return x
def get_loss_func(self, train=True):
def lf(x):
z = self.encode(x)
batchsize = len(x.data)
# reconstruction loss
#self.rec_loss = F.mean_squared_error(x, self.decode(z))
self.rec_loss = F.bernoulli_nll(x, self.decode(z, sigmoid=False)) / (batchsize)
# total_loss vanilla AEの場合はreconstruction lossとtotal lossは一緒
self.loss = self.rec_loss
return self.loss
return lf
<file_sep>
# coding: utf-8
# # VAE+GAN
# githubにあがってたものを利用する
import sys, os
import numpy as np
import pandas as pd
import six
import math
from PIL import Image
from StringIO import StringIO
import matplotlib.pyplot as plt
import chainer
from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
from chainer.functions.loss.vae import gaussian_kl_divergence
import chainer.optimizers as O
import tqdm
import time
from IPython.display import display
import json
# In[2]:
from vaegan import Encoder, Decoder, Discriminator, EncDec
from fauxtograph import get_paths, image_resize
# In[3]:
paths = get_paths('/home/tokita/projects/cinet/YouTubePriors_flv4/DividedImages/images_resize/sample_train_s/')
print len(paths)
class VAEGAN(object):
def __init__(self, img_width=64, img_height=64, color_channels=3, encode_layers=[1000, 600, 300],
decode_layers=[300, 800, 1000], disc_layers=[1000, 600, 300],
kl_ratio=1.0, latent_width=500, flag_gpu=True, mode='convolution',
enc_adam_alpha=0.0002, enc_adam_beta1=0.5,
dec_adam_alpha=0.0002, dec_adam_beta1=0.5,
disc_adam_alpha=0.0001, disc_adam_beta1=0.5,
rectifier='clipped_relu', dropout_ratio=0.5):
self.img_width = img_width
self.img_height = img_height
self.color_channels = color_channels
self.encode_layers = encode_layers
self.decode_layers = decode_layers
self.disc_layers = disc_layers
self.kl_ratio = kl_ratio
self.latent_width = latent_width
self.flag_gpu = flag_gpu
self.mode = mode
self.enc_adam_alpha = enc_adam_alpha
self.enc_adam_beta1 = enc_adam_beta1
self.dec_adam_alpha = dec_adam_alpha
self.dec_adam_beta1 = dec_adam_beta1
self.disc_adam_alpha = disc_adam_alpha
self.disc_adam_beta1 = disc_adam_beta1
self.rectifier = rectifier
self.dropout_ratio = dropout_ratio
self.enc = Encoder(img_width=self.img_width, img_height=self.img_height,
color_channels=self.color_channels, encode_layers=self.encode_layers,
latent_width=self.latent_width, mode=self.mode)
self.dec = Decoder(img_width=self.img_width,img_height=self.img_height,
color_channels=self.color_channels, decode_layers=self.decode_layers,
latent_width=self.latent_width, mode=self.mode)
self.disc = Discriminator(img_width=self.img_width, img_height=self.img_height,
color_channels=self.color_channels, disc_layers=self.disc_layers,
latent_width=self.latent_width, mode=self.mode)
if self.flag_gpu:
self.enc = self.enc.to_gpu()
self.dec = self.dec.to_gpu()
self.disc = self.disc.to_gpu()
self.enc_opt = O.Adam(alpha=self.enc_adam_alpha, beta1=self.enc_adam_beta1)
self.dec_opt = O.Adam(alpha=self.dec_adam_alpha, beta1=self.dec_adam_beta1)
self.disc_opt = O.Adam(alpha=self.disc_adam_alpha, beta1=self.disc_adam_beta1)
def _encode(self, data, test=False):
x = self.enc(data, test=test)
mean, ln_var = F.split_axis(x, 2, 1)
samp = np.random.standard_normal(mean.data.shape).astype('float32')
samp = Variable(samp)
if self.flag_gpu:
samp.to_gpu()
z = samp * F.exp(0.5*ln_var) + mean
return z, mean, ln_var
def _decode(self, z, test=False):
x = self.dec(z, test=test, rectifier=self.rectifier)
return x
def _forward(self, batch, test=False):
# TrainingSetのEncodeとDecode
encoded, means, ln_vars = self._encode(batch, test=test)
rec = self._decode(encoded, test=test)
normer = reduce(lambda x, y: x*y, means.data.shape) # データ数
kl_loss = F.gaussian_kl_divergence(means, ln_vars)/normer
#print 'means={}'.format(means.data.shape)
#print 'ln_vars={}'.format(ln_vars.data.shape)
#print 'kl_loss={}, normer={}'.format(kl_loss.data, normer)
# zのサンプル
samp_p = np.random.standard_normal(means.data.shape).astype('float32')
z_p = chainer.Variable(samp_p)
if self.flag_gpu:
z_p.to_gpu()
rec_p = self._decode(z_p)
disc_rec, conv_layer_rec = self.disc(rec, test=test, dropout_ratio=self.dropout_ratio)
disc_batch, conv_layer_batch = self.disc(batch, test=test, dropout_ratio=self.dropout_ratio)
disc_x_p, conv_layer_x_p = self.disc(rec_p, test=test, dropout_ratio=self.dropout_ratio)
dif_l = F.mean_squared_error(conv_layer_rec, conv_layer_batch)
return kl_loss, dif_l, disc_rec, disc_batch, disc_x_p
def transform(self, data, test=False):
#make sure that data has the right shape.
if not type(data) == Variable:
if len(data.shape) < 4:
data = data[np.newaxis]
if len(data.shape) != 4:
raise TypeError("Invalid dimensions for image data. Dim = %s. Must be 4d array." % str(data.shape))
if data.shape[1] != self.color_channels:
if data.shape[-1] == self.color_channels:
data = data.transpose(0, 3, 1, 2)
else:
raise TypeError("Invalid dimensions for image data. Dim = %s"
% str(data.shape))
data = Variable(data)
else:
if len(data.data.shape) < 4:
data.data = data.data[np.newaxis]
if len(data.data.shape) != 4:
raise TypeError("Invalid dimensions for image data. Dim = %s. Must be 4d array." % str(data.data.shape))
if data.data.shape[1] != self.color_channels:
if data.data.shape[-1] == self.color_channels:
data.data = data.data.transpose(0, 3, 1, 2)
else:
raise TypeError("Invalid dimensions for image data. Dim = %s"
% str(data.shape))
# Actual transformation.
if self.flag_gpu:
data.to_gpu()
z = self._encode(data, test=test)[0]
z.to_cpu()
return z.data
def inverse_transform(self, data, test=False):
if not type(data) == Variable:
if len(data.shape) < 2:
data = data[np.newaxis]
if len(data.shape) != 2:
raise TypeError("Invalid dimensions for latent data. Dim = %s. Must be a 2d array." % str(data.shape))
data = Variable(data)
else:
if len(data.data.shape) < 2:
data.data = data.data[np.newaxis]
if len(data.data.shape) != 2:
raise TypeError("Invalid dimensions for latent data. Dim = %s. Must be a 2d array." % str(data.data.shape))
assert data.data.shape[-1] == self.latent_width, "Latent shape %d != %d" % (data.data.shape[-1], self.latent_width)
if self.flag_gpu:
data.to_gpu()
out = self._decode(data, test=test)
out.to_cpu()
if self.mode == 'linear':
final = out.data
else:
final = out.data.transpose(0, 2, 3, 1)
return final
def load_images(self, filepaths):
def read(fname):
im = Image.open(fname)
im = np.float32(im)
return im/255.
x_all = np.array([read(fname) for fname in tqdm.tqdm(filepaths)])
x_all = x_all.astype('float32')
if self.mode == 'convolution':
x_all = x_all.transpose(0, 3, 1, 2)
print("Image Files Loaded!")
return x_all
def fit(self, img_data, gamma=1.0, save_freq=-1, pic_freq=-1, n_epochs=100, batch_size=100,
weight_decay=True, model_path='./VAEGAN_training_model/', img_path='./VAEGAN_training_images/',
img_out_width=10, mirroring=False):
width = img_out_width
self.enc_opt.setup(self.enc)
self.dec_opt.setup(self.dec)
self.disc_opt.setup(self.disc)
if weight_decay:
self.enc_opt.add_hook(chainer.optimizer.WeightDecay(0.00001))
self.dec_opt.add_hook(chainer.optimizer.WeightDecay(0.00001))
self.disc_opt.add_hook(chainer.optimizer.WeightDecay(0.00001))
n_data = img_data.shape[0]
batch_iter = list(range(0, n_data, batch_size))
n_batches = len(batch_iter)
c_samples = np.random.standard_normal((width, self.latent_width)).astype(np.float32)
save_counter = 0
df_col = ['epoch', 'enc_loss', 'dec_loss', 'dis_loss', 'GAN_loss', 'like_loss', 'prior_loss', 'L_base', 'L_rec', 'L_p']
self.loss_buf = pd.DataFrame(columns=df_col)
for epoch in range(1, n_epochs + 1):
print('epoch: %i' % epoch)
t1 = time.time()
indexes = np.random.permutation(n_data)
sum_l_enc = 0.
sum_l_dec = 0.
sum_l_disc = 0.
sum_l_gan = 0.
sum_l_like = 0.
sum_l_prior = 0.
sum_l_b_gan = 0.
sum_l_r_gan = 0.
sum_l_s_gan = 0.
count = 0
for i in tqdm.tqdm(batch_iter):
x = img_data[indexes[i: i + batch_size]]
size = x.shape[0]
if mirroring:
for j in range(size):
if np.random.randint(2):
x[j, :, :, :] = x[j, :, :, ::-1]
x_batch = Variable(x)
zeros = Variable(np.zeros(size, dtype=np.int32))
ones = Variable(np.ones(size, dtype=np.int32))
if self.flag_gpu:
x_batch.to_gpu()
zeros.to_gpu()
ones.to_gpu()
# kl_loss : VAE中間表現のKL正則化ロス
# dif_l : Discriminatorの中間層出力のMSE(学習データセットと再構成画像の中間出力のMSE)
# disc_{rec, batch, samp} : Discriminator出力(2次元)
kl_loss, dif_l, disc_rec, disc_batch, disc_samp = self._forward(x_batch)
# Discriminator出力のloss計算
L_batch_GAN = F.softmax_cross_entropy(disc_batch, ones)
L_rec_GAN = F.softmax_cross_entropy(disc_rec, zeros)
L_samp_GAN = F.softmax_cross_entropy(disc_samp, zeros)
l_gan = (L_batch_GAN + L_rec_GAN + L_samp_GAN)/3.
l_like = dif_l
l_prior = kl_loss
enc_loss = self.kl_ratio*l_prior + l_like
dec_loss = gamma*l_like - l_gan
disc_loss = l_gan
self.enc_opt.zero_grads()
enc_loss.backward()
self.enc_opt.update()
self.dec_opt.zero_grads()
dec_loss.backward()
self.dec_opt.update()
self.disc_opt.zero_grads()
disc_loss.backward()
self.disc_opt.update()
sum_l_enc += enc_loss.data
sum_l_dec += dec_loss.data
sum_l_disc += disc_loss.data
sum_l_gan += l_gan.data
sum_l_like += l_like.data
sum_l_prior += l_prior.data
sum_l_b_gan += L_batch_GAN.data
sum_l_r_gan += L_rec_GAN.data
sum_l_s_gan += L_samp_GAN.data
count += 1
#plot_data = img_data[indexes[:width]]
sum_l_enc /= n_batches
sum_l_dec /= n_batches
sum_l_disc /= n_batches
sum_l_gan /= n_batches
sum_l_like /= n_batches
sum_l_prior /= n_batches
sum_l_b_gan /= n_batches
sum_l_r_gan /= n_batches
sum_l_s_gan /= n_batches
msg = "enc_loss = {0}, dec_loss = {1} , disc_loss = {2}"
msg2 = "gan_loss = {0}, sim_loss = {1}, kl_loss = {2}"
print(msg.format(sum_l_enc, sum_l_dec, sum_l_disc))
print(msg2.format(sum_l_gan, sum_l_like, sum_l_prior))
t_diff = time.time()-t1
print("time: %f\n\n" % t_diff)
df_tmp = pd.DataFrame([[epoch,
sum_l_enc, sum_l_dec, sum_l_disc, sum_l_gan, sum_l_like, sum_l_prior,
sum_l_b_gan, sum_l_r_gan, sum_l_s_gan]], columns=df_col)
self.loss_buf = self.loss_buf.append(df_tmp, ignore_index=True)
# ########### モデルのインスタンス生成
vg = VAEGAN(img_width=96, img_height=96, flag_gpu=True)
# 画像ファイルのロード、正規化、transpose
x_all = vg.load_images(paths)
print 'image_data_shape = {}'.format(x_all.shape)
#vg.fit(x_all, n_epochs=10, mirroring=True)
m_path = './out/model/'
im_path = './out/images/'
vg.fit(x_all, save_freq=2, pic_freq=30, n_epochs=4, model_path = m_path, img_path=im_path, mirroring=True)
# loss系列の保存
vg.loss_buf.to_csv('./out/loss_vaegan_faux.csv')
<file_sep>
# coding: utf-8
# # オートエンコーダー(一般画像)
# * 中間層にKL正規化項を入れ、変分AEにしている
# * ネットワークはConvolution - Deconcolutionネットワークを使う
import sys, os
import numpy as np
import pandas as pd
from PIL import Image
from StringIO import StringIO
import math
import argparse
import six
import chainer
from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
from chainer.functions.loss.vae import gaussian_kl_divergence
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# AEモデルクラスのimport
from model_VAE import VAE
parser = argparse.ArgumentParser(description='option')
parser.add_argument('--gpu', '-g', default=0, type=int)
parser.add_argument('--label', '-l', default='test', type=str)
parser.add_argument('--img_dir', '-img', default='/home/tokita/projects/cinet/YouTubePriors_flv4/DividedImages/images_res', type=str)
parser.add_argument('--img_size', default=96, type=int)
parser.add_argument('--batch_size', default=100, type=int)
parser.add_argument('--epoch_num', default=10, type=int)
parser.add_argument('--latent_dimension', default=1000, type=int)
parser.add_argument('--max_convolution_size', default=512, type=int)
parser.add_argument('--adam_alpha', default=0.0001, type=float)
parser.add_argument('--adam_beta1', default=0.9, type=float)
parser.add_argument('--adam_beta2', default=0.999, type=float)
parser.add_argument('--kl_weight', default=1.0, type=float)
parser.add_argument('--out_interval', default=500, type=int)
args = parser.parse_args()
# ## GPU設定
gpu_flag = args.gpu
if gpu_flag >= 0:
cuda.check_cuda_available()
xp = cuda.cupy if gpu_flag >= 0 else np
print "##### start : chainer_VAE_image_conv.py"
# ## 学習パラメータの設定
batchsize = args.batch_size # ミニバッチのサイズ
n_epoch = args.epoch_num # epoch数
n_latent = args.latent_dimension # 潜在変数の次元(DCGANで言うところのプライヤーベクトルの次元)
conv_size = args.max_convolution_size # convolution層の最大チャネルサイズ
beta = args.kl_weight # KL正則化項の重み
# Optimizer(Adam)
al = args.adam_alpha
b1 = args.adam_beta1
b2 = args.adam_beta2
# 学習データセット
# img_size
size = args.img_size
# image path
image_dir = args.img_dir
# 訓練データの割合
train_rate = 0.7
# モデルの出力インターバル
model_interval = args.out_interval
# モデルファイルの出力先
out_model_dir = './out/out_models_%s'%args.label
try:
os.mkdir(out_model_dir)
except:
pass
## 学習パラメータの設定ここまで
# ## パラメータの確認
print('epoch_num={}'.format(n_epoch))
print('latent_dimension={}'.format(n_latent))
print('KL_Weight={}'.format(beta))
print('AdamParameter(alpha, b1, b2) = {}, {}, {}'.format(al, b1, b2))
print('output_directory={}'.format(out_model_dir))
# ## データのロード
fs = os.listdir(image_dir)
dataset = []
for fn in fs:
f = open('%s/%s'%(image_dir,fn), 'rb')
img_bin = f.read()
img = np.asarray(Image.open(StringIO(img_bin)).convert('RGB')).astype(np.float32).transpose(2, 0, 1)
dataset.append(img)
f.close()
dataset = np.asarray(dataset)
# データ数
N = dataset.shape[0]
train_rate = 0.8
N_train = int(N*train_rate)
N_test = N - N_train
# 正規化(0~1に)
dataset /= 255
# 訓練データとテストデータに分割
x_train, x_test = np.split(dataset, [N_train])
print 'x_train.shape={}'.format(x_train.shape)
print 'x_test.shape={}'.format(x_test.shape)
N_train = x_train.shape[0]
N_test = x_test.shape[0]
print('N_train={}, N_test={}'.format(N_train, N_test))
## 画像を描画する関数
def draw_img_rgb(data, fig_path):
n = data.shape[0]
plt.figure(figsize=(n*2, 2))
plt.clf()
data /= data.max()
cnt = 1
for idx in np.arange(n):
plt.subplot(1, n, cnt)
tmp = data[idx,:,:,:].transpose(1,2,0)
plt.imshow(tmp)
plt.tick_params(labelbottom="off")
plt.tick_params(labelleft="off")
cnt+=1
plt.savefig(fig_path)
# ## Optimizerの設定
# モデルの設定
model = VAE(input_size=size, n_latent=n_latent, output_ch=conv_size)
if gpu_flag >= 0:
cuda.get_device(gpu_flag).use()
model.to_gpu()
xp = np if gpu_flag < 0 else cuda.cupy
# Optimizerを定義する
optimizer = optimizers.Adam(alpha=al, beta1=b1, beta2=b2)
optimizer.setup(model)
sys.stdout.flush()
# ## 訓練の実行
loss_arr = []
recloss_arr = []
print "epoch, train_mean_loss, mean_reconstruction_loss"
for epoch in six.moves.range(1, n_epoch + 1):
# training
## 訓練データのsampler
perm = np.random.permutation(N_train)
## lossのbuffer
sum_loss = 0 # total loss
sum_rec_loss = 0 # reconstruction loss
## バッチ学習
for i in six.moves.range(0, N_train, batchsize):
x = chainer.Variable(xp.asarray(x_train[perm[i:i + batchsize]])) # バッチ分のデータの抽出
model.zerograds()
loss = model.get_loss_func(C=beta)(x)
loss.backward()
optimizer.update()
sum_loss += float(model.loss.data) * len(x.data)
sum_rec_loss += float(model.rec_loss.data) * len(x.data)
print('{}, {}, {}'.format(epoch, sum_loss/N_train, sum_rec_loss/N_train))
loss_arr.append(float(sum_loss)/N_train)
recloss_arr.append(float(sum_rec_loss)/N_train)
# モデルの保存
if epoch%model_interval==0:
serializers.save_hdf5("%s/model_VAE_%05d.h5"%(out_model_dir, epoch), model)
sys.stdout.flush()
# モデルの保存(最終モデル)
if epoch%model_interval!=0:
serializers.save_hdf5("%s/model_VAE_%05d.h5"%(out_model_dir, epoch), model)
# ## 結果の可視化
## Lossの変化
plt.figure(figsize=(7, 4))
plt.clf()
plt.plot(range(len(loss_arr)), loss_arr, color="#0000FF", label="total_loss")
plt.plot(range(len(recloss_arr)), recloss_arr, color="#FF0000", label="rec_loss")
plt.legend()
plt.savefig('%s/learning_curv_%04d.png'%(out_model_dir, epoch))
## 描画テスト (Closed test)
test_ind = np.random.permutation(N_train)[:10]
print "Reconstruct Test [Closed Test]"
print test_ind
test = chainer.Variable(xp.asarray(x_train[test_ind]), volatile='on')
y = model(test)
draw_img_rgb(x_train[test_ind], ("%s/image_closed_input.png"%(out_model_dir)))
draw_img_rgb(y.data.get(), ("%s/image_closed_reconstruct.png"%(out_model_dir)))
## 描画テスト (Open test)
test_ind = np.random.permutation(N_test)[:10]
print "Reconstruct Test [Open Test]"
print test_ind
test = chainer.Variable(xp.asarray(x_test[test_ind]), volatile='on')
y = model(test)
draw_img_rgb(x_test[test_ind], ("%s/image_open_input.png"%(out_model_dir)))
draw_img_rgb(y.data.get(), ("%s/image_open_reconstruct.png"%(out_model_dir)))
## 描画テスト (Open test, 固定画像)
test_ind = [1, 4, 6, 8, 42, 70, 76, 79, 153, 156]
print "Reconstruct Test [Open-fixedIndex Test]"
print test_ind
test = chainer.Variable(xp.asarray(x_test[test_ind]), volatile='on')
y = model(test)
draw_img_rgb(x_test[test_ind], ("%s/image_fixed_input.png"%(out_model_dir)))
draw_img_rgb(y.data.get(), ("%s/image_fixed_reconstruct.png"%(out_model_dir)))
## draw images from randomly sampled z
z = chainer.Variable(xp.random.normal(0, 1, (10, n_latent)).astype(np.float32))
x = model.decode(z)
print "Reconstruct Test [random input]"
draw_img_rgb(x.data.get(), ("%s/image_random_reconstruct.png"%(out_model_dir)))
| 4bfc620037ff5cf02f2d77c2051f8dbed24bdac7 | [
"Markdown",
"Python",
"Shell"
]
| 13 | Python | tok41/chainer-samples | 95be7fbcf37ac1616d6785bce2d9c521db37e406 | b5f2a66c944155b800e2fb85d4ebf912ec1b50f1 |
refs/heads/master | <repo_name>nandafiestafarada/Tugas-Bab6<file_sep>/src/Praktikum/Employee.java
package Praktikum;
public class Employee {
private static int anak, id;
private double salary;
public String nama, status;
public Employee(String nama, int id, double salary, int year, String status, int anak) {
this.nama = nama;
this.salary = salary;
this.status = status;
this.id = id;
}
public int getId() {
return id;
}
public String getNama() {
return nama;
}
public static void setAnak(int a) {
Employee.anak = a;
}
public String getStatus() {
return status;
}
public int getAnak() {
return anak;
}
public double getSalary() {
return salary;
}
}
<file_sep>/src/Praktikum/Manager.java
package Praktikum;
public class Manager extends Employee {
private double tunjangan, tahun, bonus, tunjangan_istri, tunjangan_anak;
public Manager(String nama, int id, double salary, int year, String status, int anak) {
super(nama, id, salary, year, status, anak);
this.tahun = year;
}
public double getTunjangan() {
if (this.tahun < 10) {
return tunjangan = 0;
} else if (this.tahun > 10) {
return tunjangan = 0.1 * this.tahun * super.getSalary();
} else {
return tunjangan = 0;
}
}
public double getTunjanganIstri() {
if (status.equals("menikah")) {
return tunjangan_istri = 0.1 * this.tahun * (super.getSalary() + getTunjangan());
} else {
return tunjangan_istri = 0;
}
}
public double getTunjanganAnak() {
if (getAnak() == 1) {
return tunjangan_anak = 0.15 * this.tahun * (super.getSalary() + getTunjangan() + getTunjanganIstri());
} else if (getAnak() == 2) {
return tunjangan_anak = 2 * 0.15 * this.tahun * (super.getSalary() + getTunjangan() + getTunjanganIstri());
} else if (getAnak() == 3) {
return tunjangan_anak = 3 * 0.15 * this.tahun * (super.getSalary() + getTunjangan() + getTunjanganIstri());
} else if (super.getAnak() > 3) {
return tunjangan_anak = 3 * 0.15 * this.tahun * (super.getSalary() + getTunjangan() + getTunjanganIstri());
} else {
return tunjangan_anak = 0;
}
}
public double getBonus() {
if ((this.tahun) < 5) {
return bonus = 0;
} else if (this.tahun < 10 && this.tahun > 5) {
return bonus = 0.05 * (this.tahun)
* super.getSalary();
} else if (this.tahun > 10) {
return bonus = 0.1 * (this.tahun) * super.getSalary();
} else {
return bonus = 0;
}
}
public double getSalary() {
double baseSalary = super.getSalary();
double plusSalary = 0.1 * this.tahun * ((super.getSalary() + getTunjangan() + getTunjanganAnak() + getTunjanganIstri()));
return baseSalary + getTunjangan() + getBonus() + getTunjanganIstri() + getTunjanganAnak() + plusSalary;
}
}
<file_sep>/src/Praktikum/PegawaiTidakTetap.java
package Praktikum;
public class PegawaiTidakTetap extends Employee {
private double tunjangan, tahun, bonus, jam;
public PegawaiTidakTetap(String name, int id, double salary, int year, String status, int anak) {
super(name, id, salary, year, status, anak);
}
public void setLembur(int jam){
this.jam = jam;
}
public int getLembur() {
if (jam > 10) {
this.bonus = 0.1 * jam;
return (int) bonus;
} else if (jam < 10) {
this.bonus = 0;
return (int) bonus;
}
return 0;
}
public double getSalary() {
double baseSalary = super.getSalary();
return baseSalary + this.bonus + getLembur();
}
}
| 3d10b5aef83b76a067b91d9143304985629aa2df | [
"Java"
]
| 3 | Java | nandafiestafarada/Tugas-Bab6 | e725eaa78eb4208b8a434f3c0b5ceb3a1ac981cc | b9c6871370758f61e412177dea91a0854f9aea9d |
refs/heads/master | <repo_name>arthurlutz/Experimental_helpers<file_sep>/ynh_download_file/ynh_download_file
#!/bin/bash
# Download and check integrity of a file from app.src_file
#
# The file conf/app.src_file need to contains:
#
# FILE_URL=Address to download the file
# FILE_SUM=Control sum
# # (Optional) Program to check the integrity (sha256sum, md5sum...)
# # default: sha256
# FILE_SUM_PRG=sha256
# # (Optionnal) Name of the local archive (offline setup support)
# # default: Name of the downloaded file.
# FILENAME=example.deb
#
# usage: ynh_download_file --dest_dir="/destination/directory" [--source_id=myfile]
# | arg: -d, --dest_dir= - Directory where to download the file
# | arg: -s, --source_id= - Name of the source file 'app.src_file' if it isn't '$app'
ynh_download_file () {
# Declare an array to define the options of this helper.
declare -Ar args_array=( [d]=dest_dir= [s]=source_id= )
local dest_dir
local source_id
# Manage arguments with getopts
ynh_handle_getopts_args "$@"
source_id=${source_id:-app} # If the argument is not given, source_id equals "$app"
# Load value from configuration file (see above for a small doc about this file
# format)
local file_url=$(grep 'FILE_URL=' "$YNH_CWD/../conf/${source_id}.src_file" | cut -d= -f2-)
local file_sum=$(grep 'FILE_SUM=' "$YNH_CWD/../conf/${source_id}.src_file" | cut -d= -f2-)
local file_sumprg=$(grep 'FILE_SUM_PRG=' "$YNH_CWD/../conf/${source_id}.src_file" | cut -d= -f2-)
local filename=$(grep 'FILENAME=' "$YNH_CWD/../conf/${source_id}.src_file" | cut -d= -f2-)
# Default value
file_sumprg=${file_sumprg:-sha256sum}
if [ "$filename" = "" ] ; then
filename="$(basename "$file_url")"
fi
local local_src="/opt/yunohost-apps-src/${YNH_APP_ID}/${filename}"
if test -e "$local_src"
then # Use the local source file if it is present
cp $local_src $filename
else # If not, download the source
local out=`wget -nv -O $filename $file_url 2>&1` || ynh_print_err $out
fi
# Check the control sum
echo "${file_sum} ${filename}" | ${file_sumprg} -c --status \
|| ynh_die "Corrupt file"
# Create the destination directory, if it's not already.
mkdir -p "$dest_dir"
# Move the file to its destination
mv $filename $dest_dir
}
<file_sep>/ynh_debian_release/ynh_debian_release
#!/bin/bash
ynh_debian_release () {
lsb_release --codename --short
}
is_stretch () {
if [ "$(ynh_debian_release)" == "stretch" ]
then
return 0
else
return 1
fi
}
is_jessie () {
if [ "$(ynh_debian_release)" == "jessie" ]
then
return 0
else
return 1
fi
}
<file_sep>/ynh_read_manifest/ynh_read_manifest
#!/bin/bash
read_json () {
sudo python3 -c "import sys, json;print(json.load(open('$1'))['$2'])"
}
read_manifest () {
if [ -f '../manifest.json' ] ; then
read_json '../manifest.json' "$1"
else
read_json '../settings/manifest.json' "$1"
fi
}
| 97fbc74adb2aca03d80e1c645d8434e33febc357 | [
"Shell"
]
| 3 | Shell | arthurlutz/Experimental_helpers | 26e12c2b7598929f3d9873d82c54663dde6b224b | cf0b7fa62c8fd0654eb01d971f58db57b9fd2d10 |
refs/heads/main | <repo_name>mserhei/cloudx<file_sep>/src/index.js
import './sass/_main.scss';
import './js/main';
<file_sep>/src/js/history/pages.js
import {drawHomeYouCanImages} from '../pages/home-you-can';
import localHeader from '../localization/localHeader.json';
import localHome from '../localization/localHome.json';
import localContacts from '../localization/localContacts.json';
import localPartners from '../localization/localPartners.json';
import localAbout from '../localization/localAbout.json';
import Header from '../../templates/Header/Header.hbs'
import Home from '../../templates/Home/Home.hbs';
import Contacts from '../../templates/Contacts/Contacts.hbs';
import Footer from '../../templates/Footer/Footer.hbs';
import Partners from '../../templates/For-partners/For-partners.hbs';
import About from '../../templates/About/About.hbs';
import {lang} from './routs';
const header = document.getElementById('header');
const root = document.getElementById('root');
const footer = document.getElementById('footer');
function homePage () {
header.innerHTML = Header(localHeader[lang]);
root.innerHTML = Home(localHome[lang]);
drawHomeYouCanImages();
footer.innerHTML = Footer();
}
function contactsPage () {
header.innerHTML = Header(localHeader[lang]);
root.innerHTML = Contacts(localContacts[lang]);
footer.innerHTML = Footer();
}
function partnersPage () {
header.innerHTML = Header(localHeader[lang]);
root.innerHTML = Partners(localPartners[lang]);
footer.innerHTML = Footer();
}
function aboutPage () {
header.innerHTML = Header(localHeader[lang]);
root.innerHTML = About(localAbout[lang]);
footer.innerHTML = Footer();
}
export {homePage, contactsPage, partnersPage, aboutPage};
<file_sep>/src/js/history/mainHistory.js
import {homePage} from './pages';
import {routs} from './routs';
import {lang} from './routs';
import {changeLang} from './routs';
const root = document.getElementById('root');
const currentPath = window.location.pathname;
const currentSearch = window.location.search;
const currentHash = window.location.hash;
const currentAllPath = currentPath + currentSearch + currentHash;
// console.log('currentPath: ', currentPath);
// console.log('currentSearch: ', currentSearch);
// console.log('currentHash: ', currentHash);
// console.log('currentAllPath: ', currentAllPath);
const currentUrl = new URL(location);
const currentUrlLang = currentUrl.searchParams.get('lang');
console.log('currentUrlLang: ', currentUrlLang);
if (currentUrlLang === lang) {
console.log('no need to change language')
} else {
console.log('need to change language')
changeLang(currentUrlLang || 'ru');
}
let routIdx = -1;
if (currentPath === '/') {
routIdx = 0;
history.replaceState(null, null, `/?lang=${lang}`);
homePage();
}
routs.forEach((rout, i) => {
if (rout.path === currentAllPath) {
console.log('ok path')
routIdx = i;
console.log('routIdx: ', routIdx);
rout.comp();
}
})
if (routIdx === -1) {
history.replaceState(null, null, `/?lang=${lang}`);
homePage();
}
// window.onpopstate = function(event) {
// const currentPath = window.location.pathname;
// let currentSearch = window.location.search;
// const currentHash = window.location.hash;
// console.log('currentPath: ', currentPath);
// console.log('currentSearch: ', currentSearch);
// console.log('currentHash: ', currentHash);
// currentSearch = `?lang=${lang}`
// const currentAllPath = currentPath + currentSearch + currentHash;
// console.log('currentAllPath: ', currentAllPath);
// history.replaceState(null, null, currentAllPath);
// };
<file_sep>/src/js/main.js
import './history/mainHistory';
import './pages/header';
import './pages/home-services';
import './pages/header-login';
import './pages/rootClicks';
<file_sep>/src/js/pages/home-you-can.js
import youCan1 from '../../img/you-can1.svg';
import youCan2 from '../../img/you-can2.svg';
import youCan3 from '../../img/you-can3.svg';
import youCan4 from '../../img/you-can4.svg';
import youCan5 from '../../img/you-can5.svg';
function drawHomeYouCanImages () {
let images = [youCan1, youCan2, youCan3, youCan4, youCan5];
let speed = [9, 6, 5, 4, 7];
let nodes = document.querySelectorAll('.home-you-can__image');
nodes.forEach((node, index) => {
node.src = `${images[index]}`;
node.style.animation = `${speed[index]}s linear 0s normal none infinite running rot`;
});
}
export {drawHomeYouCanImages};
<file_sep>/src/js/pages/rootClicks.js
const root = document.getElementById('root');
root.addEventListener('click', rootClicks);
function rootClicks (e) {
if (e.target.classList.contains('home-services__title')) {
const tabsList = document.querySelectorAll('.home-services__tabs');
const titles = document.querySelectorAll('.home-services__title');
const titleIdx = e.target.dataset.index;
titles.forEach(item => item.classList.remove('active'));
titles[titleIdx].classList.add('active');
tabsList.forEach(item => item.classList.remove('active'));
tabsList[titleIdx].classList.add('active');
}
}
<file_sep>/src/js/pages/header.js
import {lang, routs, changeLang} from '../history/routs';
const header = document.getElementById('header');
header.addEventListener('click', function (e) {
if (e.target.getAttribute('href')) {
e.preventDefault();
const link = e.target.getAttribute('href');
const nextPath = `${link}?lang=${lang}`;
history.pushState(null, null, nextPath);
routs.forEach(rout => {
if (rout.path === nextPath) {
rout.comp()
}
})
}
if (e.target.classList.contains('lang-btn')) {
langBtnClick()
}
if (e.target.classList.contains('header__btn-mobile')) {
const headerNav = document.querySelector('.header__nav');
headerNav.classList.toggle('show-mobile');
}
const headerAuthModal = document.querySelector('.header__auth');
if (e.target.classList.contains('header__buttons_modal-button')) {
headerAuthModal.classList.toggle('active');
}
if (e.target.classList.contains('header__auth_close')) {
headerAuthModal.classList.remove('active');
}
})
function langBtnClick () {
console.log('routs1' ,routs)
console.log('langBtn click')
let currentPathC = window.location.pathname;
let currentSearchC = window.location.search;
let currentHashC = window.location.hash;
let currentAllPathC = currentPathC + currentSearchC + currentHashC;
console.log('currentAllPathC', currentAllPathC)
let routIdx = null;
routs.forEach((rout, i) => {
console.log('rout path: ', rout.path)
if (currentAllPathC === rout.path) {
routIdx = i;
}
})
console.log('routIdx: ', routIdx);
console.log('lang1', lang)
const nextLang = lang === 'ru' ? 'en' : 'ru';
changeLang(nextLang);
console.log('lang2', lang)
currentSearchC = `?lang=${lang}`;
const newAllPathC = currentPathC + currentSearchC + currentHashC;
history.replaceState(null, null, newAllPathC);
routs[routIdx].comp();
console.log('routs2' ,routs);
}
<file_sep>/src/js/history/routs.js
import {load, save, remove} from '../utils/storage';
import {homePage, contactsPage, partnersPage, aboutPage} from './pages';
let lang = load('Local') || 'ru';
function changeLang (langFromUrl) {
lang = langFromUrl;
save('Local', langFromUrl);
updateRouts(langFromUrl);
}
function updateRouts (newLang) {
routs.forEach(rout => {
const oldRoutPath = rout.path.toString();
const oldRoutPathWithoutLang = oldRoutPath.slice(0, -2);
rout.path = oldRoutPathWithoutLang + newLang;
})
}
let routs = [
{
title: 'Home',
path: `/?lang=${lang}`,
comp: homePage
},
{
title: 'Contacts',
path: `/contacts?lang=${lang}`,
comp: contactsPage
},
{
title: 'Partners',
path: `/for-partners?lang=${lang}`,
comp: partnersPage
}
,
{
title: 'About',
path: `/about-us?lang=${lang}`,
comp: aboutPage
}
]
export {routs, lang, changeLang};
| 0ffdbfce80046ec93a891b13b9ad66c1123ca11b | [
"JavaScript"
]
| 8 | JavaScript | mserhei/cloudx | 94dc01349d0a1d157fef6758a5e962b80160fcff | 75bf657e1e71cc2f6e2c96328d42d0129323aee5 |
refs/heads/master | <repo_name>ke-to/super-grep<file_sep>/super-grep_var02.py
# -*- coding: utf-8 -*-
#色々な条件で色々なものに置換する
import xml.dom.minidom,os,sys,glob,re,json
import time
from threading import Timer
# 検索する文字列
search_word = ["xxx","xxx"]
#URLの数だけ検索する
def fild_all_files(csvname,word,directory):
search_arr = []
for i in search_word:
search_arr.append([i,[]])
search_data = {directory:[]}
print u"ファイルリスト抽出中..."
cnt = 0
filename = "%s.txt" % csvname
output = open(filename, 'w')
output.writelines("「%s」内で検索した結果\n\n" % str(directory))
output.write("検索したURL\t該当ファイル\n")
output.writelines("")
for root, dirs, files in os.walk(directory):
for file_ in files:
cnt += len(files)
print u"検索したファイル数: %s" % cnt
full_path = os.path.join(root, file_)
# もし対象ファイルがjspがhtmlだったらfull_pathをオープン
if (str(full_path).find("jsp") >= 0 or str(full_path).find("html") >= 0):
f = open(full_path)
data = f.read() # ファイル終端まで全て読んだデータを返す
# 1つでもヒットしたらfull_pathをjsonに格納
file_path = full_path.replace(directory,"").replace("\\","/")
json_data = {file_path:[]}
# word全検索
for i,d in enumerate(word):
if (data.find(d) >= 0):
search_arr[i][1].append(str(file_path))
f.close()
for i in search_arr: # [i,["","",""],[i,["","",""],
output.writelines(i[0])
output.writelines("\t")
for j in i[1]: # [],[],[]
output.writelines(j)
output.writelines("\t")
output.writelines("\n")
output.close()
path01 = u"C:/Users/xxx"
data1 = fild_all_files(u"sumple_01",search_word,path01)
path02 = u"C:/xxx"
data2 = fild_all_files(u"sumple_02",search_word,path02)
print('''-------------------------------------
| ALL COMPLATE! |
-------------------------------------''')
def hello():
print("closing...")
t = Timer(3.0, hello)
t.start()<file_sep>/super-grep.py
# -*- coding: utf-8 -*-
#色々な条件で色々なものに置換する
import xml.dom.minidom,os,sys,glob,re,json
# 検索する文字列
search_word = ["xxx","xxx"]
#URLの数だけ検索する
def fild_all_files(csvname,word,directory):
search_data = {directory:[]}
print u"ファイルリスト抽出中..."
cnt = 0
filename = "%s.txt" % csvname
output = open(filename, 'w')
output.writelines("「%s」内で検索した結果\n\n" % str(directory))
output.write("対象ファイル\t該当箇所\n")
output.writelines("")
for root, dirs, files in os.walk(directory):
for file_ in files:
cnt += len(files)
print u"検索したファイル数: %s" % cnt
full_path = os.path.join(root, file_)
# もし対象ファイルがjspがhtmlだったらfull_pathをオープン
if (str(full_path).find("jsp") >= 0 or str(full_path).find("html") >= 0):
f = open(full_path)
data = f.read() # ファイル終端まで全て読んだデータを返す
# 1つでもヒットしたらfull_pathをjsonに格納
file_path = full_path.replace(directory,"").replace("\\","/")
json_data = {file_path:[]}
# word全検索
for i,d in enumerate(word):
if (data.find(d) >= 0):
json_data[file_path].append(str(d))
f.close()
# 検索ディレクトリarrに1つの検索文言が入っているファイルのリストを追加
if(len(json_data[file_path]) >= 1):
output.writelines(file_path)
#output.writelines('\n')
for result in json_data[file_path]:
text = "\t%s" % str(result)
output.writelines(text)
output.writelines('\n')
search_data[directory].append(json_data)
output.close()
return search_data
path01 = u"C:/Users/xxx"
data1 = fild_all_files(u"sumple_01",search_word,path01)
path02 = u"C:/xxx"
data2 = fild_all_files(u"sumple_02",search_word,path02)
# print data2
print('''-------------------------------------
| ALL COMPLATE! |
-------------------------------------''')
def hello():
print("closing...")
t = Timer(3.0, hello)
t.start() | 60c9ae04bcbba40c7e9d21c27324e3bd3eb6e40c | [
"Python"
]
| 2 | Python | ke-to/super-grep | bea1beb5df8c3deffbdde69d79d3acf0dfd7ff8c | defea62a20a03e61797201697b93a5e20802c952 |
refs/heads/main | <file_sep>import React from 'react';
import { Navbar, Nav, Container } from 'react-bootstrap';
class AppLayout extends React.Component {
render() {
return (<div>
<Navbar bg="light" expand="lg">
<Navbar.Brand href="/">Lending Front</Navbar.Brand>
<Nav className="mr-auto">
<Nav.Link href="/">Home</Nav.Link>
</Nav>
</Navbar>
<main className='mt1'>
<Container >
<div className="row">
<div className="col-md-2">
<img className='rounded mx-auto d-block img-thumbnail' src='/logo.jpeg' alt='Logo'/>
</div>
<div className="col-md-10">
{this.props.children}
</div>
</div>
</Container>
</main>
</div>);
}
}
export default AppLayout<file_sep>import config from './../config'
class Api {
getFullURL(url){
return `${config.BASE_URL}${url}`
}
get({ url, headers = {} }){
const options = { headers }
return fetch(this.getFullURL(url), options)
}
post({ url, headers = {}, body = {} }){
const options = {
method: 'POST',
headers,
body: JSON.stringify(body)
}
return fetch(this.getFullURL(url), options)
}
}
export const postRequest = async(application) => {
const api = new Api();
try {
const res = await api.post({
url: `/applications`,
body: application,
headers: {'Content-Type': 'application/json'}
})
return await res.json();
} catch (error) {
throw error
}
}
<file_sep>import React from 'react'
export const AlertState = (props) => {
const type = props.type;
const message = `Your request was ${type.toLowerCase()}`
if(type === 'Declined'){
return <div className="alert alert-danger" role="alert">
{message}
</div>
} else if(type === 'Undecided') {
return <div className="alert alert-warning" role="alert">
{message}
</div>
} else if(type === 'Approved'){
return <div className="alert alert-success" role="alert">
{message}
</div>
} else {
return <div></div>
}
}
<file_sep>import React from 'react';
import { Button, Container } from 'react-bootstrap';
const NotFound = () => {
return (<Container className='text-center'>
<img className='rounded mx-auto d-block img-thumbnail' src='/logo.jpeg' alt='Logo'/>
<p>Sorry, page not found</p>
<Button variant='primary' onClick={() => { window.location.href = '/' }} >Go home</Button>
</Container>);
}
export default NotFound<file_sep>import React from "react";
import Layout from "../Layout";
import {Spinner} from './Spinner'
import {AlertState} from './AlertState'
import {AlertError} from './AlertError'
import {postRequest} from '../Api'
class Home extends React.Component {
state = {
tax_id: '',
business_name: '',
requested_amount: '',
loading: false,
application: '',
error: ''
}
handleSubmit = async (event) => {
event.preventDefault();
this.setState({loading: true, application: '', error: ''})
try {
const res = await postRequest(this.state);
this.setState({loading: false, application: res.state})
} catch (error) {
this.setState({loading: false, error: error.message})
}
}
onInputChange = event => {
const {id, value} = event.target;
this.setState({[id]: value})
}
render() {
return (
<Layout>
<h1>Request</h1>
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="inputTaxId">Tax Id</label>
<input type="number" required={true} autoFocus={true} className="form-control" id="tax_id" value={this.state.tax_id} onChange={(event) => {this.onInputChange(event)}}/>
</div>
<div className="form-group">
<label htmlFor="inputBusinessName">Business Name</label>
<input type="text" required={true} className="form-control" id="business_name" value={this.state.business_name} onChange={(event) => {this.onInputChange(event)}}/>
</div>
<div className="form-group">
<label htmlFor="inputRequestedAmount">Amount</label>
<input type="number" required={true} className="form-control" id="requested_amount" value={this.state.requested_amount} onChange={(event) => {this.onInputChange(event)}}/>
</div>
<div className='p2'>
{this.state.loading ?
(<Spinner />):
<button className="btn btn-primary mb1">Send Request</button>
}
</div>
</form>
<AlertState className='mt-3' type={this.state.application}/>
<AlertError className='mt-3' message={this.state.error } />
</Layout>
);
}
};
export default Home;
<file_sep>import React from 'react';
import AppLayout from '../Layout'
const Resume = () => {
return (<AppLayout>
<h1>Resumen</h1>
</AppLayout>);
}
export default Resume | 378d7918dd43fdd28b3abef0b1b8fbac94f5b042 | [
"JavaScript"
]
| 6 | JavaScript | anarpafran/lp_frontend | 65cad4a7a70ba89abad1bd2353296514c201fe90 | 50851a269dec631d1a6bc088b62cb28d7b162519 |
refs/heads/master | <repo_name>JoelEnriquez/Proyecto2Pruebas<file_sep>/Proyecto2Pruebas/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>Proyecto2Pruebas</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.jdom/jdom2 -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
</project><file_sep>/Proyecto2Pruebas/src/main/java/EntidadesHospital/Examen.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 EntidadesHospital;
import java.sql.Date;
import java.sql.Time;
/**
*
* @author <NAME>
*/
public class Examen {
private int codigo;
private Date fechaCita;
private Time horaCita;
private boolean requiereOrden;
private String codigoPaciente;
private String codigoMedico;
private String codigoTipoExamen;
public Examen(Date fechaCita, Time horaCita, boolean requiereOrden, String codigoPaciente,
String codigoMedico, String codigoTipoExamen) {
this.fechaCita = fechaCita;
this.horaCita = horaCita;
this.requiereOrden = requiereOrden;
this.codigoPaciente = codigoPaciente;
this.codigoMedico = codigoMedico;
this.codigoTipoExamen = codigoTipoExamen;
}
public Examen(int codigo, Date fechaCita, Time horaCita, boolean requiereOrden,
String codigoPaciente, String codigoMedico, String codigoTipoExamen) {
this.codigo = codigo;
this.fechaCita = fechaCita;
this.horaCita = horaCita;
this.requiereOrden = requiereOrden;
this.codigoPaciente = codigoPaciente;
this.codigoMedico = codigoMedico;
this.codigoTipoExamen = codigoTipoExamen;
}
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public boolean getRequiereOrden() {
return requiereOrden;
}
public void setRequiereOrden(boolean requiereOrden) {
this.requiereOrden = requiereOrden;
}
public Date getFechaCita() {
return fechaCita;
}
public void setFechaCita(Date fechaCita) {
this.fechaCita = fechaCita;
}
public Time getHoraCita() {
return horaCita;
}
public void setHoraCita(Time horaCita) {
this.horaCita = horaCita;
}
public String getCodigoPaciente() {
return codigoPaciente;
}
public void setCodigoPaciente(String codigoPaciente) {
this.codigoPaciente = codigoPaciente;
}
public String getCodigoMedico() {
return codigoMedico;
}
public void setCodigoMedico(String codigoMedico) {
this.codigoMedico = codigoMedico;
}
public String getCodigoTipoExamen() {
return codigoTipoExamen;
}
public void setCodigoTipoExamen(String codigoTipoExamen) {
this.codigoTipoExamen = codigoTipoExamen;
}
}
<file_sep>/Proyecto2Pruebas/src/main/java/EntidadesAsignacion/AsignacionEspecialidad.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 EntidadesAsignacion;
/**
*
* @author <NAME>
*/
public class AsignacionEspecialidad {
private String idEspecialidad;
private String codigoMedico;
public AsignacionEspecialidad(String idEspecialidad, String codigoMedico) {
this.idEspecialidad = idEspecialidad;
this.codigoMedico = codigoMedico;
}
public String getIdEspecialidad() {
return idEspecialidad;
}
public void setIdEspecialidad(String idEspecialidad) {
this.idEspecialidad = idEspecialidad;
}
public String getCodigoMedico() {
return codigoMedico;
}
public void setCodigoMedico(String codigoMedico) {
this.codigoMedico = codigoMedico;
}
}
<file_sep>/Proyecto2Pruebas/src/main/java/EntidadesHospital/InformeMedico.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 EntidadesHospital;
import java.sql.Date;
import java.sql.Time;
/**
*
* @author <NAME>
*/
public class InformeMedico {
private String codigo;
private Date fechaInforme;
private Time horaInforme;
private String descripcionInforme;
private String codigoPaciente;
private String codigoMedico;
private String codigoCitaMedico;
public InformeMedico(Date fechaInforme, Time horaInforme,
String descripcionInforme, String codigoPaciente,
String codigoMedico, String codigoCitaMedico) {
this.fechaInforme = fechaInforme;
this.horaInforme = horaInforme;
this.descripcionInforme = descripcionInforme;
this.codigoPaciente = codigoPaciente;
this.codigoMedico = codigoMedico;
this.codigoCitaMedico = codigoCitaMedico;
}
public InformeMedico(String codigo, Date fechaInforme, Time horaInforme,
String descripcionInforme, String codigoPaciente,
String codigoMedico, String codigoCitaMedico) {
this.codigo = codigo;
this.fechaInforme = fechaInforme;
this.horaInforme = horaInforme;
this.descripcionInforme = descripcionInforme;
this.codigoPaciente = codigoPaciente;
this.codigoMedico = codigoMedico;
this.codigoCitaMedico = codigoCitaMedico;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public Date getFechaInforme() {
return fechaInforme;
}
public void setFechaInforme(Date fechaInforme) {
this.fechaInforme = fechaInforme;
}
public Time getHoraInforme() {
return horaInforme;
}
public void setHoraInforme(Time horaInforme) {
this.horaInforme = horaInforme;
}
public String getDescripcionInforme() {
return descripcionInforme;
}
public void setDescripcionInforme(String descripcionInforme) {
this.descripcionInforme = descripcionInforme;
}
public String getCodigoPaciente() {
return codigoPaciente;
}
public void setCodigoPaciente(String codigoPaciente) {
this.codigoPaciente = codigoPaciente;
}
public String getCodigoMedico() {
return codigoMedico;
}
public void setCodigoMedico(String codigoMedico) {
this.codigoMedico = codigoMedico;
}
public String getCodigoCitaMedico() {
return codigoCitaMedico;
}
public void setCodigoCitaMedico(String codigoCitaMedico) {
this.codigoCitaMedico = codigoCitaMedico;
}
}
| 4e82ab6c6dc55eae2ca403d786035be7922dd834 | [
"Java",
"Maven POM"
]
| 4 | Maven POM | JoelEnriquez/Proyecto2Pruebas | 919b10f106bc16abc13108d875890e72cfbd190e | 984e064f9d4b2e6def76c23a4fcb661e8ed4630a |
refs/heads/master | <repo_name>amkulikov/extrpc<file_sep>/http_server_wrapper.go
package extrpc
import (
"bytes"
"io"
"net/http"
"net/rpc"
"sync"
)
type ServerCodecGenerator func(rwc io.ReadWriteCloser) rpc.ServerCodec
// ServerWrapper wraps http requests and responses to io.ReadWriteCloser.
type ServerWrapper struct {
rw http.ResponseWriter
req *http.Request
requestDoneCh chan struct{}
mu sync.Mutex
}
// Creates new ServerWrapper for HTTP request
func NewServerWrapper(rw http.ResponseWriter, req *http.Request) *ServerWrapper {
return &ServerWrapper{
req: req,
rw: rw,
requestDoneCh: make(chan struct{}),
}
}
// Wait returns channel, that will be closed when processing completes.
// You MUST wait for closing this channel before releasing your http handler
func (h *ServerWrapper) Wait() chan struct{} {
return h.requestDoneCh
}
// called when request processing is done
func (h *ServerWrapper) done() {
h.mu.Lock()
defer h.mu.Unlock()
// prevent closing if already closed
select {
case _, ok := <-h.requestDoneCh:
if !ok {
return
}
default:
close(h.requestDoneCh)
}
}
func (h *ServerWrapper) Read(p []byte) (int, error) {
// read content from request Body
return h.req.Body.Read(p)
}
func (h *ServerWrapper) Write(p []byte) (n int, err error) {
var n64 int64
// write content to http ResponseWriter
// you MUST block http handler with <-h.Wait() until write operation finished,
// cause "A ResponseWriter may not be used after the Handler.ServeHTTP method has returned."
// https://golang.org/pkg/net/http/#ResponseWriter
n64, err = bytes.NewReader(p).WriteTo(h.rw)
n = int(n64)
h.done()
return
}
func (h *ServerWrapper) Close() (err error) {
err = h.req.Body.Close()
h.done()
return
}
<file_sep>/README.md
# Package ExtRPC
🚧**UNDER DEVELOPMENT**🚧
Package extends net/rpc package with two important things:
* Server and client support of RPC over HTTP
* Caller interface that allows to parse and provide information about caller to called procedure with args
# How to use
Just
```
go get github.com/amkulikov/extrpc
```
## Examples
Will be soon. For now you can check [tests](extrpc_test.go) for usage examples.
<file_sep>/gob.go
package extrpc
// Gob server and client codecs, adapted for using with http ServerWrapper and ClientWrapper.
import (
"io"
"encoding/gob"
"net/rpc"
"bytes"
"bufio"
)
// net/rpc.ServerCodec implementation.
type GobServerCodec struct {
useBuffer bool
rwc io.ReadWriteCloser
dec *gob.Decoder
enc *gob.Encoder
bufWriter *bufio.Writer
encBuf *bytes.Buffer
closed bool
}
// NewGobServerCodec returns new instance of GobServerCodec for conn.
func NewGobServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec {
c := &GobServerCodec{
rwc: conn,
dec: gob.NewDecoder(conn),
}
// Buffer all output before writing if conn is a HTTP ServerWrapper.
// This is necessary to send large responses (greater than 4096 bytes) using only one write operation.
if _, ok := conn.(*ServerWrapper); ok {
c.useBuffer = true
c.encBuf = &bytes.Buffer{}
c.enc = gob.NewEncoder(c.encBuf)
} else {
c.bufWriter = bufio.NewWriter(conn)
c.enc = gob.NewEncoder(c.bufWriter)
}
return c
}
func (c *GobServerCodec) flushResponse() (err error) {
if c.useBuffer {
_, err = c.encBuf.WriteTo(c.rwc)
} else {
err = c.bufWriter.Flush()
}
if err != nil {
c.Close()
}
return
}
func (c *GobServerCodec) ReadRequestHeader(r *rpc.Request) error {
return c.dec.Decode(r)
}
func (c *GobServerCodec) ReadRequestBody(body interface{}) error {
return c.dec.Decode(body)
}
func (c *GobServerCodec) WriteResponse(r *rpc.Response, body interface{}) (err error) {
defer c.flushResponse()
if err = c.enc.Encode(r); err != nil {
return
}
err = c.enc.Encode(body)
return
}
func (c *GobServerCodec) Close() error {
if c.closed {
return nil
}
c.closed = true
return c.rwc.Close()
}
// net/rpc.ClientCodec implementation.
type GobClientCodec struct {
useBuffer bool
rwc io.ReadWriteCloser
dec *gob.Decoder
enc *gob.Encoder
bufWriter *bufio.Writer
encBuf *bytes.Buffer
}
// NewGobClientCodec creates and returns new instance of GobClientCodec for provided conn.
func NewGobClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec {
c := &GobClientCodec{
rwc: conn,
dec: gob.NewDecoder(conn),
}
// Buffer all output before writing if conn is a httpRequestWrapper.
// This is necessary to send large responses (greater than 4096 bytes) using only one write operation.
if _, ok := conn.(*httpRequestWrapper); ok {
c.useBuffer = true
c.encBuf = &bytes.Buffer{}
c.enc = gob.NewEncoder(c.encBuf)
} else {
c.bufWriter = bufio.NewWriter(conn)
c.enc = gob.NewEncoder(c.bufWriter)
}
return c
}
func (c *GobClientCodec) flushRequest() (err error) {
if c.useBuffer {
_, err = c.encBuf.WriteTo(c.rwc)
} else {
err = c.bufWriter.Flush()
}
if err != nil {
c.Close()
}
return
}
func (c *GobClientCodec) WriteRequest(r *rpc.Request, body interface{}) (err error) {
if err = c.enc.Encode(r); err != nil {
return
}
if err = c.enc.Encode(body); err != nil {
return
}
err = c.flushRequest()
return
}
func (c *GobClientCodec) ReadResponseHeader(r *rpc.Response) error {
return c.dec.Decode(r)
}
func (c *GobClientCodec) ReadResponseBody(body interface{}) error {
return c.dec.Decode(body)
}
func (c *GobClientCodec) Close() error {
return c.rwc.Close()
}
<file_sep>/extrpc.go
// Package ExtRPC extends default net/rpc package.
// It allows to use RPC over truly HTTP requests (not hijacking TCP from request)
// and to provide information about caller to called procedure.
package extrpc
import (
"net/rpc"
"reflect"
)
const CallerStructFieldName = "Caller"
// Composition of parent RPC server codec and caller data.
// Implements rpc.ServerCodec.
type rpcServerExtendCodec struct {
parentCodec rpc.ServerCodec
caller Caller
}
// NewServerExtendCodec returns a new instance of rpcServerExtendCodec.
// ParentCodec is used for processing requests.
// Important thing: ParentCodec MUST NOT to use buffered i/o, so you can safely use NewGobServerCodec from this package
// or NewServerCodec from net/jsonrpc (https://golang.org/pkg/net/rpc/jsonrpc/#NewServerCodec).
func ExtendCodec(parentCodec rpc.ServerCodec, caller Caller) *rpcServerExtendCodec {
if parentCodec == nil {
panic("extrpc: Where is your codec?")
}
return &rpcServerExtendCodec{
parentCodec: parentCodec,
caller: caller,
}
}
// add caller data to RPC args if possible
func (c *rpcServerExtendCodec) addCallerData(args interface{}) {
if ps := reflect.ValueOf(args); ps.IsValid() {
s := ps.Elem()
// arg must have a struct type
if s.Kind() == reflect.Struct {
// check caller field exists
f := s.FieldByName(CallerStructFieldName)
if f.CanSet() && f.IsValid() && reflect.TypeOf(c.caller).Implements(f.Type()) {
f.Set(reflect.ValueOf(c.caller))
}
}
}
}
// rpc.ServerCodec
func (c *rpcServerExtendCodec) ReadRequestHeader(r *rpc.Request) error {
return c.parentCodec.ReadRequestHeader(r)
}
// rpc.ServerCodec
func (c *rpcServerExtendCodec) ReadRequestBody(x interface{}) (err error) {
err = c.parentCodec.ReadRequestBody(x)
// Append caller data to args
if c.caller != nil {
c.addCallerData(x)
}
return
}
// rpc.ServerCodec
func (c *rpcServerExtendCodec) WriteResponse(r *rpc.Response, x interface{}) error {
return c.parentCodec.WriteResponse(r, x)
}
// rpc.ServerCodec
func (c *rpcServerExtendCodec) Close() error {
return c.parentCodec.Close()
}
<file_sep>/http_client_wrapper.go
package extrpc
import (
"bytes"
"sync"
"net/http"
"net/rpc"
"io"
)
type ClientCodecGenerator func(rwc io.ReadWriteCloser) rpc.ClientCodec
// httpRequestWrapper wraps http requests and responses to io.ReadWriteCloser.
type httpRequestWrapper struct {
mu sync.Mutex
rpcClient *rpc.Client
res io.ReadCloser
wc *ClientWrapper
responseWaitCh chan struct{}
}
func newHttpRequestWrapper(wc *ClientWrapper) (*httpRequestWrapper) {
return &httpRequestWrapper{
wc: wc,
responseWaitCh: make(chan struct{}),
}
}
// basicCodec returns new rpc.ClientCodec,
// created by current ClientCodecGenerator
func (h *httpRequestWrapper) basicCodec() rpc.ClientCodec {
return h.wc.cg(h)
}
// called when request processing is done
func (h *httpRequestWrapper) done() {
// prevent closing if already closed
select {
case <-h.responseWaitCh:
return
default:
close(h.responseWaitCh)
}
}
func (h *httpRequestWrapper) Read(p []byte) (int, error) {
<-h.responseWaitCh
if h.res == nil {
return 0, io.EOF
}
return h.res.Read(p)
}
func (h *httpRequestWrapper) Write(p []byte) (n int, err error) {
h.mu.Lock()
defer h.mu.Unlock()
defer h.done()
// prepare request
req, err := http.NewRequest("POST", h.wc.url, bytes.NewReader(p))
if err != nil {
return 0, io.ErrClosedPipe
}
// add custom headers to request
for key, value := range h.wc.headers {
// prevent overriding
if req.Header.Get(key) == "" {
req.Header.Add(key, value)
}
}
// do request with provided http client
res, err := h.wc.client.Do(req)
if err != nil {
return 0, io.ErrClosedPipe
}
h.res = res.Body
n = len(p)
return
}
func (h *httpRequestWrapper) Close() error {
h.mu.Lock()
defer h.mu.Unlock()
if h.rpcClient != nil {
h.rpcClient.Close()
}
if h.res != nil {
h.res.Close()
}
return nil
}
// ClientWrapper performs RCP calls through wrapper
type ClientWrapper struct {
client *http.Client
url string
headers map[string]string
cg ClientCodecGenerator
}
// Creates new ClientWrapper object.
// httpClient will used for sending http.Request. http.DefaultClient as default.
// rpcUrl is an absolute path to RPC server, that using extrpc too.
// headers is a custom http headers that will apply to every http rpc request.
// cg creates rpc.ClientCodec for io.ReadWriteCloser
func NewWrapperClient(httpClient *http.Client, rpcUrl string, headers map[string]string, cg ClientCodecGenerator) *ClientWrapper {
c := &ClientWrapper{httpClient, rpcUrl, headers, cg}
// use http.DefaultClient as default
if c.client == nil {
c.client = http.DefaultClient
}
// use GobClientCodec as default
if c.cg == nil {
c.cg = NewGobClientCodec
}
return c
}
// GoHTTP invokes the function asynchronously. It returns the Call structure representing
// the invocation. The done channel will signal when the call is complete by returning
// the same Call object. If done is nil, Go will allocate a new channel.
// If non-nil, done must be buffered or Go will deliberately crash.
// Same as net/rpc.Go, but using HTTP request.
func (wc *ClientWrapper) GoHTTP(serviceMethod string, args interface{}, reply interface{}, done chan *rpc.Call) *rpc.Call {
wr := newHttpRequestWrapper(wc)
wr.rpcClient = rpc.NewClientWithCodec(wr.basicCodec())
return wr.rpcClient.Go(serviceMethod, args, reply, done)
}
// CallHTTP invokes the named function, waits for it to complete, and returns its error status.
// Same as net/rpc.Call, but using HTTP request.
func (wc *ClientWrapper) CallHTTP(serviceMethod string, args interface{}, reply interface{}) error {
call := <-wc.GoHTTP(serviceMethod, args, reply, make(chan *rpc.Call, 1)).Done
return call.Error
}
<file_sep>/extrpc_test.go
package extrpc
import (
"log"
"net/rpc"
"net/http/httptest"
"strings"
"sync"
"testing"
"net"
"net/http"
"net/rpc/jsonrpc"
"math/rand"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
)
// Random string payload generator
func RandStringBytesMask(n int) string {
b := make([]byte, n)
for i := 0; i < n; {
if idx := int(rand.Int63() & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i++
}
}
return string(b)
}
func init() {
rpc.Register(new(Remote))
}
var testStr = "test"
var bigStr = RandStringBytesMask(1000000)
var tests = []struct {
method string
args interface{}
expect string
}{
{"Remote.EchoUpper", Args{testStr}, strings.ToUpper(testStr)},
{"Remote.ProcedureWithCaller", Args{testStr}, strings.ToUpper(testStr) + "127.0.0.1"},
{"Remote.EchoUpperTwice", Args{bigStr}, strings.ToUpper(bigStr + bigStr)},
}
type Args struct {
Param string
}
type ArgsWithCaller struct {
Param string
Caller Caller
}
type Remote int
func (t *Remote) EchoUpper(args *Args, reply *string) error {
*reply = strings.ToUpper(args.Param)
return nil
}
func (t *Remote) EchoUpperTwice(args *Args, reply *string) error {
*reply = strings.ToUpper(args.Param + args.Param)
return nil
}
func (t *Remote) ProcedureWithCaller(args *ArgsWithCaller, reply *string) error {
*reply = strings.ToUpper(args.Param) + args.Caller.IP().String()
return nil
}
func startTCPServer(cg ServerCodecGenerator) string {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
log.Fatal(err)
}
go func() {
for {
// Wait for a connection.
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
caller := NewDefaultCaller()
if err := caller.ParseConn(conn); err != nil {
log.Fatal(err)
}
rpc.ServeCodec(ExtendCodec(cg(conn), caller))
}
}()
return l.Addr().String()
}
func httpHandler(rw http.ResponseWriter, req *http.Request) {
wr := NewServerWrapper(rw, req)
caller := NewDefaultCaller()
if err := caller.ParseHTTP(req); err != nil {
log.Fatal(err)
}
var basicCodec rpc.ServerCodec
if req.Header.Get("content-type") == "application/json" {
basicCodec = jsonrpc.NewServerCodec(wr)
} else {
basicCodec = NewGobServerCodec(wr)
}
rpc.ServeCodec(ExtendCodec(basicCodec, caller))
<-wr.Wait()
return
}
func startHTTPServer() string {
return httptest.NewServer(http.HandlerFunc(httpHandler)).URL
}
func rpcTCP(t *testing.T, client *rpc.Client) {
for _, test := range tests {
var reply string
err := client.Call(test.method, test.args, &reply)
if err != nil {
t.Errorf(test.method+": expected no error but got string %q", err.Error())
}
if reply != test.expect {
t.Errorf(test.method+": expected %s got %s", test.expect, reply)
}
}
}
func rpcAsyncTCP(t *testing.T, client *rpc.Client) {
var wg sync.WaitGroup
for _, test := range tests {
wg.Add(1)
go func() {
var reply string
err := client.Call(test.method, test.args, &reply)
if err != nil {
t.Errorf(test.method+": expected no error but got string %q", err.Error())
}
if reply != test.expect {
t.Errorf(test.method+": expected %s got %s", test.expect, reply)
}
wg.Done()
}()
}
wg.Wait()
}
func rpcHTTP(t *testing.T, wr *ClientWrapper) {
for _, test := range tests {
var reply string
err := wr.CallHTTP(test.method, test.args, &reply)
if err != nil {
t.Errorf(test.method+": expected no error but got string %q", err.Error())
}
if reply != test.expect {
t.Errorf(test.method+": expected %s\n\n(%d)\n\ngot %s\n\n(%d)", test.expect, len(test.expect), reply, len(reply))
}
}
}
func rpcAsyncHTTP(t *testing.T, wr *ClientWrapper) {
var wg sync.WaitGroup
for _, test := range tests {
wg.Add(1)
go func() {
var reply string
err := wr.CallHTTP(test.method, test.args, &reply)
if err != nil {
t.Errorf(test.method+": expected no error but got string %q", err.Error())
}
if reply != test.expect {
t.Errorf(test.method+": expected %s\n\n(%d)\n\ngot %s\n\n(%d)", test.expect, len(test.expect), reply, len(reply))
}
wg.Done()
}()
}
wg.Wait()
}
func TestHTTP(t *testing.T) {
addr := startHTTPServer()
// Test with gob codec
wc := NewWrapperClient(
nil,
addr+rpc.DefaultRPCPath,
nil,
nil,
)
rpcHTTP(t, wc)
rpcAsyncHTTP(t, wc)
// Test with json codec
wc = NewWrapperClient(
nil,
addr+rpc.DefaultRPCPath,
map[string]string{"content-type": "application/json"},
jsonrpc.NewClientCodec,
)
rpcHTTP(t, wc)
rpcAsyncHTTP(t, wc)
}
func TestTCP(t *testing.T) {
// Test with gob codec
addr := startTCPServer(NewGobServerCodec)
conn, err := net.Dial("tcp", addr)
if err != nil {
t.Fatal("dialing", err)
}
defer conn.Close()
client := rpc.NewClientWithCodec(NewGobClientCodec(conn))
rpcTCP(t, client)
rpcAsyncTCP(t, client)
// Test with json codec
addr = startTCPServer(jsonrpc.NewServerCodec)
conn, err = net.Dial("tcp", addr)
if err != nil {
t.Fatal("dialing", err)
}
defer conn.Close()
client = rpc.NewClientWithCodec(jsonrpc.NewClientCodec(conn))
rpcTCP(t, client)
rpcAsyncTCP(t, client)
}
<file_sep>/caller.go
package extrpc
import (
"net"
"net/http"
"sync"
)
// Caller interface provides information about RPC client.
// This information will be sent to called procedure as field "Caller" in arguments, if exists.
type Caller interface {
// IP returns client IP, catched with Parse% method.
IP() net.IP
// Header returns header value by key if ok == true.
Header(key string) (value string, ok bool)
// ParseConn retrieves information about caller from net.Conn. Use this method before rpc.Serve on net.Conn!
ParseConn(conn net.Conn) error
// ParseHTTP retrieves information about caller from http.Request. Use this method before rpc.Serve on http.Request!
ParseHTTP(req *http.Request) error
}
// Default implementation of Caller interface Caller.
type defaultCaller struct {
ip net.IP
headers map[string]string
dataMu sync.RWMutex
}
// NewDefaultCaller returns new instance of defaultCaller.
func NewDefaultCaller() *defaultCaller {
return &defaultCaller{
headers: make(map[string]string),
}
}
func (c *defaultCaller) IP() net.IP {
c.dataMu.RLock()
defer c.dataMu.RUnlock()
return c.ip
}
func (c *defaultCaller) Header(key string) (value string, ok bool) {
c.dataMu.RLock()
defer c.dataMu.RUnlock()
value, ok = c.headers[key]
return
}
func (c *defaultCaller) ParseConn(conn net.Conn) (err error) {
c.dataMu.Lock()
defer c.dataMu.Unlock()
switch v := conn.RemoteAddr().(type) {
case *net.TCPAddr:
c.ip = v.IP
case *net.UDPAddr:
c.ip = v.IP
}
return
}
func (c *defaultCaller) ParseHTTP(req *http.Request) (err error) {
c.dataMu.Lock()
defer c.dataMu.Unlock()
// copy all http headers
for key := range req.Header {
c.headers[key] = req.Header.Get(key)
}
// get ip as remote addr
// also you can get ip from x-* headers
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
return err
}
c.ip = net.ParseIP(host)
return
}
| 40b6ef85d2ff54211fe6c1628c263acff3ce5dbf | [
"Markdown",
"Go"
]
| 7 | Go | amkulikov/extrpc | 4856241748ed246fcb164a35ba29b6b0bb5d761b | 32425a0736f5f2da4b80b07cdb09737f7a1a60ae |
refs/heads/master | <repo_name>Prosp3r0/FeatureExtractor<file_sep>/rawFeatureExtractor/preprocessing_ida.py
from func import *
from raw_graphs import *
from idc import *
import os
import argparse
RDEBUG_HOST = 'localhost'
RDEBUG_PORT = 12321
def debug():
import sys
import pydevd
print('++ debug()')
RDEBUG_EGG="/Applications/PyCharm.app/Contents/debug-eggs/pycharm-debug.egg"
sys.path.append(RDEBUG_EGG)
pydevd.settrace(RDEBUG_HOST, port=RDEBUG_PORT, stdoutToServer=True, stderrToServer=True)
def parse_command():
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument("--path", type=str, help="The directory where to store the generated .ida file")
args = parser.parse_args()
return args
def extract():
args = parse_command()
path = args.path
path = '/Users/Max/Documents/capstone/FeatureEngineering/FeatureResource/rawFeatures/'
analysis_flags = idc.GetShortPrm(idc.INF_AF) # idc.INF_START_AF
analysis_flags &= ~idc.AF_IMMOFF
# turn off "automatically make offset" heuristic
idc.SetShortPrm(idc.INF_START_AF, analysis_flags)
idaapi.autoWait()
cfgs = get_func_cfgs_c(FirstSeg())
binary_name = idc.GetInputFile() + '.ida'
fullpath = os.path.join(path, binary_name)
pickle.dump(cfgs, open(fullpath, 'w'))
print binary_name
if __name__ == '__main__':
idc.Wait()
# debug()
extract()
idc.Exit(0)<file_sep>/rawFeatureHandler/rawFeatureHandler.py
import pickle
import matplotlib.pyplot as plt
import networkx as nx
import os
import json
rawFeatures_path = '/Users/Max/Documents/capstone/FeatureResource/rawFeatures/'
class rawHandler():
def __init__(self, ida_file, error):
self.ida_filepath = ida_file
self.error = error
def extractFromGraphs(self):
if os.path.dirname(self.ida_filepath) + '/' == rawFeatures_path:
return None
print('[+] Extracting features: {}'.format(self.ida_filepath))
with open(self.ida_filepath, 'r') as f:
try:
bb = pickle.load(f)
except Exception as e:
self.error.append(e)
return None
f.close()
result = []
for nxg in bb.get_graphs():
func = {}
func['features'] = []
func['fname'] = ''
func['src'] = ''
func['succs'] = []
func_graph = nxg.old_g
func['n_num'] = len(func_graph.nodes)
for i in range(0, func['n_num']):
node_feature = []
#node_feature.append(node['numLIs'])
node_feature.append(float(func_graph.nodes[i]['numAs']))
node_feature.append(float(func_graph.nodes[i]['offs']))
node_feature.append(float(len(func_graph.nodes[i]['strings'])))
node_feature.append(float(len(func_graph.nodes[i]['consts'])))
node_feature.append(float(func_graph.nodes[i]['numTIs']))
node_feature.append(float(func_graph.nodes[i]['numCalls']))
node_feature.append(float(func_graph.nodes[i]['numIns']))
func['features'].append(node_feature)
for i in range(0, func['n_num']):
node_succ = []
for nbr, datadict in func_graph.succ[i].items():
node_succ.append(nbr)
func['succs'].append(node_succ)
func['src'] = os.path.dirname(self.ida_filepath)[len(rawFeatures_path):] + '/' + \
os.path.splitext(os.path.basename(self.ida_filepath))[0]
func['fname'] = nxg.funcname
func_str = json.dumps(func)
result.append(func_str)
return result
'''
if __name__ == '__main__':
rel = rawHandler('../rawFeatures/linuxkernel-arm-O2v54/verify_test.ida').extractFromGraphs()
print('finished')
'''
<file_sep>/rawFeatureExtractor/runIDAPro.py
import subprocess
import subprocess32
import os
import shutil
binary_dir_path = '/Users/Max/Documents/capstone/FeatureEngineering/FeatureResource/binary/'
ida64_path = '/Applications/IDA\ Pro\ 7.0/ida.app/Contents/MacOS/ida64'
ida32_path = r'/Applications/IDA\ Pro\ 7.0/ida.app/Contents/MacOS/idat'
ana_file = '/Users/Max/Documents/capstone/FeatureEngineering/FeatureExtractor/rawFeatureExtractor/preprocessing_ida.py'
rawFeatures_path = '/Users/Max/Documents/capstone/FeatureEngineering/FeatureResource/rawFeatures/'
def extractByIDAPro(binary_file_path):
print('[+] Processing {0}'.format(binary_file_path))
cmd = "{0} -L/Users/Max/Documents/capstone/FeatureExtractor/idalog/idalog.log -c -A -S{1} {2}".format(
ida32_path, ana_file, binary_file_path)
#p = subprocess.Popen(cmd, shell = True)
try:
stdout = subprocess32.check_output(cmd, stderr=subprocess32.STDOUT, shell = True, timeout=1200)
except Exception as e:
print(' [-] Error Occur in IDA Pro')
return False
#p.wait()
idb = os.path.splitext(binary_file_path)[0] + '.idb'
if os.path.exists(idb):
os.remove(idb)
binary_relative_path = binary_file_path[len(binary_dir_path):]
#rawFeature_platform_path = os.path.join(rawFeatures_path, os.path.basename(os.path.dirname(binary_file_path)))
rawFeature_platform_path = os.path.join(rawFeatures_path, os.path.dirname(binary_relative_path) + '/')
ida_file_path = os.path.join(rawFeatures_path, os.path.basename(binary_file_path) + '.ida')
#if not os.path.exists()
if not os.path.exists(rawFeature_platform_path):
os.makedirs(rawFeature_platform_path, 0755)
ida_file = os.path.join(rawFeature_platform_path, os.path.basename(ida_file_path))
if os.path.exists(ida_file):
os.remove(ida_file)
shutil.move(ida_file_path, rawFeature_platform_path)
#return os.basename(binary_file) + '.ida'
return True
def MultiThreadingExtractByIDAPro(binary_file_path_list):
for binary_file_path in binary_file_path_list:
if not os.path.exists(binary_file_path):
continue
old_name = os.path.basename(binary_file_path)
new_path = os.path.join(os.path.dirname(binary_file_path), binary_file_path[len(binary_dir_path):].replace('/', '_'))
os.rename(binary_file_path, new_path)
#binary_file_path = new_path
print('[+] Processing {0}'.format(new_path))
cmd = "{0} -L/Users/Max/Documents/capstone/FeatureExtractor/idalog/idalog.log -c -A -S{1} {2}".format(
ida32_path, ana_file, new_path)
#p = subprocess.Popen(cmd, shell = True)
try:
stdout = subprocess32.check_output(cmd, stderr=subprocess32.STDOUT, shell = True, timeout=1200)
except Exception as e:
print(' [-] Error Occur in IDA Pro')
os.rename(new_path, binary_file_path)
continue
#p.wait()
os.rename(new_path, binary_file_path)
idb = os.path.splitext(new_path)[0] + '.idb'
if os.path.exists(idb):
os.remove(idb)
binary_relative_path = new_path[len(binary_dir_path):]
#rawFeature_platform_path = os.path.join(rawFeatures_path, os.path.basename(os.path.dirname(binary_file_path)))
rawFeature_platform_path = os.path.join(rawFeatures_path, os.path.dirname(binary_relative_path) + '/')
ida_file_path = os.path.join(rawFeatures_path, os.path.basename(new_path) + '.ida')
#if not os.path.exists()
if not os.path.exists(rawFeature_platform_path):
os.makedirs(rawFeature_platform_path, 0755)
ida_file = os.path.join(rawFeature_platform_path, os.path.basename(ida_file_path))
if os.path.exists(ida_file):
os.remove(ida_file)
shutil.move(ida_file_path, rawFeature_platform_path)
if os.path.exists(ida_file):
os.rename(ida_file, os.path.join(os.path.dirname(ida_file), old_name + '.ida'))
#return os.basename(binary_file) + '.ida'
#return True
#if __name__ == "__main__":
# extractByIDAPro()<file_sep>/rawFeatureExtractor/idadebugtest.py
#import pydevd
#import idaapi
RDEBUG_HOST = 'localhost'
RDEBUG_PORT = 12321
def debug():
import sys
import pydevd
print('++ debug()')
RDEBUG_EGG="/Applications/PyCharm.app/Contents/debug-eggs/pycharm-debug.egg"
sys.path.append(RDEBUG_EGG)
pydevd.settrace(RDEBUG_HOST, port=RDEBUG_PORT, stdoutToServer=True, stderrToServer=True)
class MyPlugin_t(idaapi.plugin_t):
flags = idaapi.PLUGIN_HIDE
comment = "Test"
help = ""
wanted_name = "Test"
wanted_hotkey = ""
def init(self):
return idaapi.PLUGIN_KEEP
def run(self, arg):
print('+ run()')
debug()
#print "hello,hit break"
def term(self):
pass
def PLUGIN_ENTRY():
print('hello ')
return MyPlugin_t()
if __name__ == '__main__':
PLUGIN_ENTRY()
debug()
print("hello,hit break")<file_sep>/rawFeatureHandler/test.py
import pickle
import matplotlib.pyplot as plt
import networkx as nx
with open('../rawFeatures/linuxkernel-arm-O2v54/verify_test.ida', 'r') as f:
bb=pickle.load(f)
f.close()
for nxg in bb.get_graphs():
#if nxg.funcname == 'group_order_tests':
if nxg.funcname == 'verify_detached_signature_cert':
G = nxg.g
break
print G
#pos = nx.spring_layout(G)
nx.draw(G)
#node_labels = nx.get_node_attributes(G,'state')
#nx.draw_networkx_labels(G, pos, labels = node_labels)
#edge_labels = nx.get_edge_attributes(G,'state')
#nx.draw_networkx_edge_labels(G, pos, labels = edge_labels)
plt.savefig('this.png')
plt.show()<file_sep>/featureExtractor.py
from rawFeatureHandler.rawFeatureHandler import rawHandler
from rawFeatureExtractor.runIDAPro import extractByIDAPro, MultiThreadingExtractByIDAPro
import threading
import os, shutil
binary_dir_path = '/Users/Max/Documents/capstone/FeatureEngineering/FeatureResource/binary/'
rawFeatures_path = '/Users/Max/Documents/capstone/FeatureEngineering/FeatureResource/rawFeatures/'
final_feature_path = '/Users/Max/Documents/capstone/FeatureEngineering/FeatureResource/features/'
class featureGenerator():
def __init__(self, binary_dir, rawFeatures_dir):
self.binary_dir = binary_dir
self.rawFeature_dir = rawFeatures_dir
def extractIDAFilefromBinary(self):
print('[INFO] Generating IDA File for Binary by IDA Pro')
for root, dirs, files in os.walk(self.binary_dir):
for file_name in files:
if file_name.startswith('.') or (not file_name.endswith('.o') and not file_name.endswith('.so')):
continue
binary_file_path = os.path.join(root, file_name)
bin_file_relative_path = binary_file_path[len(binary_dir_path):]
ida_file_relative_path = bin_file_relative_path + '.ida'
if os.path.exists(os.path.join(rawFeatures_path, ida_file_relative_path)):
print("[INFO] Skiping {0}. Found {1}".format(bin_file_relative_path, ida_file_relative_path))
continue
if not extractByIDAPro(binary_file_path):
continue
def collectBinary(self):
print('[INFO] Generating IDA File for Binary by IDA Pro')
bin_to_extract = []
for root, dirs, files in os.walk(self.binary_dir):
for file_name in files:
if file_name.startswith('.') or (not file_name.endswith('.o') and not file_name.endswith('.so')):
continue
binary_file_path = os.path.join(root, file_name)
bin_file_relative_path = binary_file_path[len(binary_dir_path):]
ida_file_relative_path = bin_file_relative_path + '.ida'
if os.path.exists(os.path.join(rawFeatures_path, ida_file_relative_path)):
print("[INFO] Skiping {0}. Found {1}".format(bin_file_relative_path, ida_file_relative_path))
continue
bin_to_extract.append(binary_file_path)
#if not extractByIDAPro(binary_file_path):
# continue
return bin_to_extract
def multithreadingIDA(self):
bin_files = self.collectBinary()
if len(bin_files) > 11:
block_len = len(bin_files)/6
bin_files_1 = bin_files[0:block_len]
bin_files_2 = bin_files[block_len:block_len*2]
bin_files_3 = bin_files[block_len*2:block_len*3]
bin_files_4 = bin_files[block_len*3:block_len*4]
bin_files_5 = bin_files[block_len*4:block_len*5]
bin_files_6 = bin_files[block_len*5:]
th = [
threading.Thread(target=MultiThreadingExtractByIDAPro, args=(bin_files_1,)),
threading.Thread(target=MultiThreadingExtractByIDAPro, args=(bin_files_2,)),
threading.Thread(target=MultiThreadingExtractByIDAPro, args=(bin_files_3,)),
threading.Thread(target=MultiThreadingExtractByIDAPro, args=(bin_files_4,)),
threading.Thread(target=MultiThreadingExtractByIDAPro, args=(bin_files_5,)),
threading.Thread(target=MultiThreadingExtractByIDAPro, args=(bin_files_6,))
]
for t in th:
t.start()
for t in th:
t.join()
else:
MultiThreadingExtractByIDAPro(bin_files)
def idaFileAnalyzer(self):
print('[INFO] Extracting Features from IDA File')
errorlog = []
for root, dirs, files in os.walk(self.rawFeature_dir):
for file_name in files:
if file_name == '.DS_Store' or file_name.startswith('.'):
continue
ida_file_path = os.path.join(root, file_name)
feature_results = rawHandler(ida_file=ida_file_path, error=errorlog).extractFromGraphs()
if feature_results == None:
continue
#feature_file_path = os.path.join(final_feature_path, os.path.basename(root)) + '.json'
feature_file_path = os.path.join(final_feature_path, root[len(rawFeatures_path):].split('/')[0] + '.json')
#if not os.path.exists(feature_file_path):
# os
print(' Writing Features into {}'.format(feature_file_path))
with open(feature_file_path, 'a+') as f:
for func in feature_results:
f.write(func)
f.write('\n')
if len(errorlog) > 0:
print('[INFO] Error When Extracting: ')
with open('ErrorExtractIDA.log', 'w') as f:
for error in errorlog:
e = '[-] ' + error
print(e)
f.write(e + '/n')
if __name__ == '__main__':
#featureGenerator(binary_dir_path, rawFeatures_path).extractIDAFilefromBinary()
featureGenerator(binary_dir_path, rawFeatures_path).multithreadingIDA()
featureGenerator(binary_dir_path, rawFeatures_path).idaFileAnalyzer() | ed09bf6cec47d47c9bf69a6f0dcdf4ddf6fb739e | [
"Python"
]
| 6 | Python | Prosp3r0/FeatureExtractor | 1286a28674c584843c57bdcb763cf5437173da25 | bb7248144798191f89b67191f948ab7940a6e134 |
refs/heads/master | <repo_name>richmondx/SaveExtension<file_sep>/Source/SaveExtension/Public/ISaveExtension.h
// Copyright 2015-2018 Piperift. All Rights Reserved.
#pragma once
#include "ModuleManager.h"
#include "Engine/Engine.h"
#include "SavePreset.h"
DECLARE_LOG_CATEGORY_EXTERN(LogSaveExtension, All, All);
class ISaveExtension : public IModuleInterface {
public:
static inline ISaveExtension& Get() {
return FModuleManager::LoadModuleChecked<ISaveExtension>("SaveExtension");
}
static inline bool IsAvailable() {
return FModuleManager::Get().IsModuleLoaded("SaveExtension");
}
static void Log(const USavePreset* Preset, const FString Message, int8 Indent)
{
Log(Preset, Message, FColor::White, false, Indent, 2.f);
}
static void Log(const USavePreset* Preset, const FString Message, FColor Color = FColor::White, bool bError = false, int8 Indent = 0, const float Duration = 2.f)
{
if (!Preset->bDebug)
return;
if (bError) {
Color = FColor::Red;
}
FString ComposedMessage = {};
if (Indent <= 0) {
ComposedMessage += "Save Extension: ";
}
else
{
for (int8 i{ 1 }; i <= Indent; ++i)
{
ComposedMessage += " ";
}
}
ComposedMessage += Message;
if (bError)
{
UE_LOG(LogSaveExtension, Error, TEXT("%s"), *ComposedMessage);
}
else
{
UE_LOG(LogSaveExtension, Log, TEXT("%s"), *ComposedMessage);
}
if (Preset->bDebugInScreen && GEngine)
{
GEngine->AddOnScreenDebugMessage(-1, Duration, Color, ComposedMessage);
}
}
};
//Only log in Editor
#if WITH_EDITORONLY_DATA
#define SE_LOG(...) ISaveExtension::Log(##__VA_ARGS__)
#else
#define SE_LOG(...)
#endif
<file_sep>/Docs/README.md
# Save Extension Documentation
Save Extension allows your projects to be saved and loaded.
This plugin is for Unreal Engine 4 and has support for versions **4.20** and **4.19**
## Introduction
At Piperift we like to release the technology we create for ourselves.
Save Extension is part of this technology, and as such, we wanted it to be public so that others can enjoy it too, making the job of the developer considerably easier.
This plugin was designed to fulfill the needs for automatic world saving and loading that are unfortunately missing in the engine at this moment in time. Automatic in the sense that any actor in the world can be saved, including AI, Players, controllers or game logic without any extra components or setups.
## Intended Usage
All our technology is designed to work for very different games and needs, but, naturally, it was created around certain requirements.
In the case of SaveExtension, it has been developed to support games with high amounts of content in the world like open worlds or narrative games.
What I mean by this is that you usually wouldn't serialize a world for a mario game. It can do it, but may not be worth it. Other games might have items to be picked, player states, AI, or streaming levels that require this serialization and here's where the strength of SaveExtension comes.
## Supported Features
#### SaveGame tag saving
Any variable tagged as `SaveGame` will be saved.
#### Full world serialization
All actors in the world are susceptible to be saved.
Only exceptions are for example StaticMeshActors
#### Asynchronous Saving and Loading
Loading and saving can run asynchronously, splitting the load between frames. <br>This states can be tracked and shown on UI.
#### Level Streaming and World Composition
Sublevels can be loaded and saved when they get streamed in or out. This allows games to keep the state of the levels even without saving the game.
*If the player exists an area where 2 enemies were damaged, when he gets in again this enemies will keep their damaged state*
#### Data Modularity
All data is structured in the way that levels can be loaded at a minimum cost.
#### Compression
Files can be compressed, getting up to 20 times smaller file sizes.<file_sep>/Source/SaveExtension/Private/SlotDataTask_LevelSaver.cpp
// Copyright 2015-2018 Piperift. All Rights Reserved.
#include "SlotDataTask_LevelSaver.h"
/////////////////////////////////////////////////////
// FSaveDataTask_LevelSaver
void USlotDataTask_LevelSaver::OnStart()
{
if (SlotData && StreamingLevel && StreamingLevel->IsLevelLoaded())
{
SerializeLevelSync(StreamingLevel->GetLoadedLevel(), StreamingLevel);
//TODO: With async tasks Serializelevel will take charge of finishing
//return;
}
Finish(true);
}
<file_sep>/Source/SaveExtension/Private/LevelStreamingNotifier.cpp
// Copyright 2015-2018 Piperift. All Rights Reserved.
#include "LevelStreamingNotifier.h"
ULevelStreamingNotifier::ULevelStreamingNotifier(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{}
<file_sep>/Docs/documentation/quick-start.md
# Quick Start
Save Extension's setup is actually very simple.
When using this plugin<file_sep>/Source/SaveExtension/Public/SlotDataTask_Saver.h
// Copyright 2015-2018 Piperift. All Rights Reserved.
#pragma once
#include "ISaveExtension.h"
#include <Engine/Level.h>
#include <Engine/LevelStreaming.h>
#include <GameFramework/Actor.h>
#include <Engine/LevelScriptActor.h>
#include <GameFramework/Controller.h>
#include <AIController.h>
#include "SavePreset.h"
#include "SlotData.h"
#include "SlotDataTask.h"
#include "SlotDataTask_Saver.generated.h"
/**
* Manages the saving process of a SaveData file
*/
UCLASS()
class USlotDataTask_Saver : public USlotDataTask
{
GENERATED_BODY()
bool bOverride;
bool bSaveThumbnail;
int32 Slot;
int32 Width;
int32 Height;
protected:
// Async variables
TWeakObjectPtr<ULevel> CurrentLevel;
TWeakObjectPtr<ULevelStreaming> CurrentSLevel;
int32 CurrentActorIndex;
TArray<TWeakObjectPtr<AActor>> CurrentLevelActors;
public:
auto Setup(int32 InSlot, bool bInOverride, bool bInSaveThumbnail, const int32 InWidth, const int32 InHeight)
{
Slot = InSlot;
bOverride = bInOverride;
bSaveThumbnail = bInSaveThumbnail;
Width = InWidth;
Height = InHeight;
return this;
}
virtual void OnStart() override;
protected:
/** BEGIN Serialization */
void SerializeSync();
void SerializeLevelSync(const ULevel* Level, const ULevelStreaming* StreamingLevel = nullptr);
void SerializeASync();
void SerializeLevelASync(const ULevel* Level, const ULevelStreaming* StreamingLevel = nullptr);
/** Serializes all world actors. */
void SerializeWorld();
private:
void SerializeLevelScript(const ALevelScriptActor* Level, FLevelRecord& LevelRecord);
void SerializeAI(const AAIController* AIController, FLevelRecord& LevelRecord);
/** Serializes the GameMode. Only with 'SaveGameMode' enabled. */
void SerializeGameMode();
/** Serializes the GameState. Only with 'SaveGameState' enabled. */
void SerializeGameState();
/** Serializes the PlayerState. Only with 'SavePlayerState' enabled. */
void SerializePlayerState(int32 PlayerId);
/** Serializes PlayerControllers. Only with 'SavePlayerControllers' enabled. */
void SerializePlayerController(int32 PlayerId);
/** Serializes Player HUD Actor and its Properties.
Requires 'SaveGameMode' flag to be used. */
void SerializePlayerHUD(int32 PlayerId);
/** Serializes Current Player's Pawn and its Properties.
Requires 'SaveGameMode' flag to be used. */
//void SerializePlayerPawn(int32 PlayerId);
/** Serializes Game Instance Object and its Properties.
Requires 'SaveGameMode' flag to be used. */
void SerializeGameInstance();
/** Serializes an actor into this Actor Record */
bool SerializeActor(const AActor* Actor, FActorRecord& Record);
/** Serializes an actor into this Controller Record */
bool SerializeController(const AController* Actor, FControllerRecord& Record);
/** Serializes the components of an actor into a provided Actor Record */
void SerializeActorComponents(const AActor* Actor, FActorRecord& ActorRecord, int8 indent = 0);
/** END Serialization */
/** BEGIN FileSaving */
bool SaveFile(const FString& InfoName, const FString& DataName) const;
/** End FileSaving */
};
<file_sep>/Source/SaveExtension/Private/FileAdapter.cpp
// Copyright 2015-2018 Piperift. All Rights Reserved.
#include "FileAdapter.h"
#include <UObjectGlobals.h>
#include <MemoryReader.h>
#include <MemoryWriter.h>
#include <SaveGameSystem.h>
#include <ArchiveSaveCompressedProxy.h>
#include <ArchiveLoadCompressedProxy.h>
#include "SavePreset.h"
static const int UE4_SAVEGAME_FILE_TYPE_TAG = 0x53415647; // "sAvG"
struct FSaveGameFileVersion
{
enum Type
{
InitialVersion = 1,
// serializing custom versions into the savegame data to handle that type of versioning
AddedCustomVersions = 2,
// -----<new versions can be added above this line>-------------------------------------------------
VersionPlusOne,
LatestVersion = VersionPlusOne - 1
};
};
/*********************
* FSaveFileHeader
*/
FSaveFileHeader::FSaveFileHeader()
: FileTypeTag(0)
, SaveGameFileVersion(0)
, PackageFileUE4Version(0)
, CustomVersionFormat(static_cast<int32>(ECustomVersionSerializationFormat::Unknown))
{}
FSaveFileHeader::FSaveFileHeader(TSubclassOf<USaveGame> ObjectType)
: FileTypeTag(UE4_SAVEGAME_FILE_TYPE_TAG)
, SaveGameFileVersion(FSaveGameFileVersion::LatestVersion)
, PackageFileUE4Version(GPackageFileUE4Version)
, SavedEngineVersion(FEngineVersion::Current())
, CustomVersionFormat(static_cast<int32>(ECustomVersionSerializationFormat::Latest))
, CustomVersions(FCustomVersionContainer::GetRegistered())
, SaveGameClassName(ObjectType->GetPathName())
{}
void FSaveFileHeader::Empty()
{
FileTypeTag = 0;
SaveGameFileVersion = 0;
PackageFileUE4Version = 0;
SavedEngineVersion.Empty();
CustomVersionFormat = (int32)ECustomVersionSerializationFormat::Unknown;
CustomVersions.Empty();
SaveGameClassName.Empty();
}
bool FSaveFileHeader::IsEmpty() const
{
return (FileTypeTag == 0);
}
void FSaveFileHeader::Read(FMemoryReader& MemoryReader)
{
Empty();
MemoryReader << FileTypeTag;
if (FileTypeTag != UE4_SAVEGAME_FILE_TYPE_TAG)
{
// this is an old saved game, back up the file pointer to the beginning and assume version 1
MemoryReader.Seek(0);
SaveGameFileVersion = FSaveGameFileVersion::InitialVersion;
}
else
{
// Read version for this file format
MemoryReader << SaveGameFileVersion;
// Read engine and UE4 version information
MemoryReader << PackageFileUE4Version;
MemoryReader << SavedEngineVersion;
MemoryReader.SetUE4Ver(PackageFileUE4Version);
MemoryReader.SetEngineVer(SavedEngineVersion);
if (SaveGameFileVersion >= FSaveGameFileVersion::AddedCustomVersions)
{
MemoryReader << CustomVersionFormat;
CustomVersions.Serialize(MemoryReader, static_cast<ECustomVersionSerializationFormat::Type>(CustomVersionFormat));
MemoryReader.SetCustomVersions(CustomVersions);
}
}
// Get the class name
MemoryReader << SaveGameClassName;
}
void FSaveFileHeader::Write(FMemoryWriter& MemoryWriter)
{
// write file type tag. identifies this file type and indicates it's using proper versioning
// since older UE4 versions did not version this data.
MemoryWriter << FileTypeTag;
// Write version for this file format
MemoryWriter << SaveGameFileVersion;
// Write out engine and UE4 version information
MemoryWriter << PackageFileUE4Version;
MemoryWriter << SavedEngineVersion;
// Write out custom version data
MemoryWriter << CustomVersionFormat;
CustomVersions.Serialize(MemoryWriter, static_cast<ECustomVersionSerializationFormat::Type>(CustomVersionFormat));
// Write the class name so we know what class to load to
MemoryWriter << SaveGameClassName;
}
/*********************
* FSaveFileHeader
*/
bool FFileAdapter::SaveFile(USaveGame* SaveGameObject, const FString& SlotName, const USavePreset* Preset)
{
check(Preset);
QUICK_SCOPE_CYCLE_COUNTER(STAT_FileAdapter_SaveFile);
ISaveGameSystem* SaveSystem = IPlatformFeaturesModule::Get().GetSaveGameSystem();
// If we have a system and an object to save and a save name...
if (SaveSystem && SaveGameObject && !SlotName.IsEmpty())
{
TArray<uint8> ObjectBytes;
FMemoryWriter MemoryWriter(ObjectBytes, true);
FSaveFileHeader SaveHeader(SaveGameObject->GetClass());
SaveHeader.Write(MemoryWriter);
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_FileAdapter_SaveFile_Serialize);
// Serialize SaveGame Object
FObjectAndNameAsStringProxyArchive Ar(MemoryWriter, false);
SaveGameObject->Serialize(Ar);
}
TArray<uint8> CompressedBytes;
//Ptr looking towards the compressed file data
TArray<uint8>* ObjectBytesPtr = &ObjectBytes;
if (Preset->bUseCompression)
{
ObjectBytesPtr = &CompressedBytes;
// Compress SaveGame Object
FArchiveSaveCompressedProxy Compressor = FArchiveSaveCompressedProxy(CompressedBytes, ECompressionFlags::COMPRESS_ZLIB);
Compressor << ObjectBytes;
Compressor.Flush();
Compressor.FlushCache();
Compressor.Close();
}
// Stuff that data into the save system with the desired file name
return SaveSystem->SaveGame(false, *SlotName, 0, *ObjectBytesPtr);
}
return false;
}
USaveGame* FFileAdapter::LoadFile(const FString& SlotName, const USavePreset* Preset)
{
check(Preset);
QUICK_SCOPE_CYCLE_COUNTER(STAT_FileAdapter_LoadFile);
ISaveGameSystem* SaveSystem = IPlatformFeaturesModule::Get().GetSaveGameSystem();
// If we have a save system and a valid name..
if (SaveSystem && !SlotName.IsEmpty())
{
// Load raw data from slot
TArray<uint8> ObjectBytes;
bool bSuccess = SaveSystem->LoadGame(false, *SlotName, 0, ObjectBytes);
if (bSuccess)
{
TArray<uint8> UncompressedBytes;
//Ptr looking towards the uncompressed file data
TArray<uint8>* ObjectBytesPtr = &ObjectBytes;
if (Preset->bUseCompression)
{
ObjectBytesPtr = &UncompressedBytes;
FArchiveLoadCompressedProxy Decompressor(ObjectBytes, ECompressionFlags::COMPRESS_ZLIB);
if (Decompressor.GetError())
return nullptr;
Decompressor << UncompressedBytes;
Decompressor.Close();
}
FMemoryReader MemoryReader(*ObjectBytesPtr, true);
FSaveFileHeader SaveHeader;
SaveHeader.Read(MemoryReader);
// Try and find it, and failing that, load it
UClass* SaveGameClass = FindObject<UClass>(ANY_PACKAGE, *SaveHeader.SaveGameClassName);
if (SaveGameClass == nullptr)
SaveGameClass = LoadObject<UClass>(nullptr, *SaveHeader.SaveGameClassName);
// If we have a class, try and load it.
if (SaveGameClass != nullptr)
{
USaveGame* SaveGameObj = NewObject<USaveGame>(GetTransientPackage(), SaveGameClass);
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_FileAdapter_LoadFile_Deserialize);
FObjectAndNameAsStringProxyArchive Ar(MemoryReader, true);
SaveGameObj->Serialize(Ar);
}
return SaveGameObj;
}
}
}
return nullptr;
}
bool FFileAdapter::DeleteFile(const FString& SlotName)
{
if (ISaveGameSystem* SaveSystem = IPlatformFeaturesModule::Get().GetSaveGameSystem())
{
return SaveSystem->DeleteGame(false, *SlotName, 0);
}
return false;
}
bool FFileAdapter::DoesFileExist(const FString& SlotName)
{
if (ISaveGameSystem* SaveSystem = IPlatformFeaturesModule::Get().GetSaveGameSystem())
{
return SaveSystem->DoesSaveGameExist(*SlotName, 0);
}
return false;
}
<file_sep>/Docs/SUMMARY.md
# Save Extension Documentation
- Documentation
* [Asynchronous](documentation/asynchronous.md)
* [Level Streaming](documentation/level-streaming.md)
* [Presets](documentation/presets.md)
* [Quick Start](documentation/quick-start.md)
* [Saving And Loading](documentation/saving-and-loading.md)
* [Slot Templates](documentation/slot-templates.md)
* [Installation](installation.md)
<file_sep>/Source/SaveExtension/Public/FileAdapter.h
// Copyright 2015-2018 Piperift. All Rights Reserved.
#pragma once
#include <CoreMinimal.h>
#include <GameFramework/SaveGame.h>
#include <EngineVersion.h>
#include <SubclassOf.h>
#include <CustomVersion.h>
#include <PlatformFeatures.h>
#include <ObjectAndNameAsStringProxyArchive.h>
#include "ISaveExtension.h"
class USavePreset;
/** Based on GameplayStatics to add multi-threading */
struct FSaveFileHeader
{
FSaveFileHeader();
FSaveFileHeader(TSubclassOf<USaveGame> ObjectType);
void Empty();
bool IsEmpty() const;
void Read(FMemoryReader& MemoryReader);
void Write(FMemoryWriter& MemoryWriter);
int32 FileTypeTag;
int32 SaveGameFileVersion;
int32 PackageFileUE4Version;
FEngineVersion SavedEngineVersion;
int32 CustomVersionFormat;
FCustomVersionContainer CustomVersions;
FString SaveGameClassName;
};
/** Based on GameplayStatics to add multi-threading */
class FFileAdapter
{
public:
static bool SaveFile(USaveGame* SaveGameObject, const FString& SlotName, const USavePreset* Preset);
static USaveGame* LoadFile(const FString& SlotName, const USavePreset* Preset);
static bool DeleteFile(const FString& SlotName);
static bool DoesFileExist(const FString& SlotName);
};
<file_sep>/Source/SaveExtension/Private/SlotDataTask_Saver.cpp
// Copyright 2015-2018 Piperift. All Rights Reserved.
#include "SlotDataTask_Saver.h"
#include <Kismet/GameplayStatics.h>
#include <Engine/LocalPlayer.h>
#include <GameFramework/GameModeBase.h>
#include <GameFramework/GameStateBase.h>
#include <GameFramework/PlayerController.h>
#include <GameFramework/HUD.h>
#include <Serialization/MemoryWriter.h>
#include <Components/CapsuleComponent.h>
#include "SaveManager.h"
#include "SlotInfo.h"
#include "SlotData.h"
#include "SavePreset.h"
#include "FileAdapter.h"
/////////////////////////////////////////////////////
// USaveDataTask_Saver
void USlotDataTask_Saver::OnStart()
{
USaveManager* Manager = GetManager();
Manager->TryInstantiateInfo();
bool bSave = true;
const FString InfoCard = Manager->GenerateSaveSlotName(Slot);
const FString DataCard = Manager->GenerateSaveDataSlotName(Slot);
//Overriding
{
const bool bInfoExists = FFileAdapter::DoesFileExist(InfoCard);
const bool bDataExists = FFileAdapter::DoesFileExist(DataCard);
if (bOverride)
{
// Delete previous save
if (bInfoExists)
{
FFileAdapter::DeleteFile(InfoCard);
}
if (bDataExists)
{
FFileAdapter::DeleteFile(DataCard);
}
}
else
{
//Only save if previous files don't exist
//We don't want to serialize since it won't be saved anyway
bSave = !bInfoExists && !bDataExists;
}
}
if (bSave)
{
USlotInfo* CurrentInfo = Manager->GetCurrentInfo();
SlotData = Manager->GetCurrentData();
SlotData->Clean(false);
check(CurrentInfo && SlotData);
const bool bSlotWasDifferent = CurrentInfo->Id != Slot;
CurrentInfo->Id = Slot;
if (bSaveThumbnail)
{
CurrentInfo->SaveThumbnail(Width, Height);
}
// Time stats
{
CurrentInfo->SaveDate = FDateTime::Now();
// If this info has been loaded ever
const bool bWasLoaded = CurrentInfo->LoadDate.GetTicks() > 0;
if (bWasLoaded)
{
// Now - Loaded
const FTimespan SessionTime = CurrentInfo->SaveDate - CurrentInfo->LoadDate;
CurrentInfo->TotalPlayedTime += SessionTime;
if (!bSlotWasDifferent)
CurrentInfo->SlotPlayedTime += SessionTime;
else
CurrentInfo->SlotPlayedTime = SessionTime;
}
else
{
// Slot is new, played time is world seconds
CurrentInfo->TotalPlayedTime = FTimespan::FromSeconds(World->TimeSeconds);
CurrentInfo->SlotPlayedTime = CurrentInfo->TotalPlayedTime;
}
}
//Save Level info in both files
CurrentInfo->Map = World->GetFName();
SlotData->Map = World->GetFName().ToString();
SerializeSync();
SaveFile(InfoCard, DataCard);
// Clean serialization data
SlotData->Clean(true);
SE_LOG(Preset, "Finished Saving", FColor::Green);
}
Finish(bSave);
}
void USlotDataTask_Saver::SerializeSync()
{
// Save World
SerializeWorld();
if (Preset->bStoreGameInstance)
SerializeGameInstance();
if (Preset->bStoreGameMode)
{
SerializeGameMode();
SerializeGameState();
const TArray<ULocalPlayer*>& LocalPlayers = World->GetGameInstance()->GetLocalPlayers();
for (const auto* LocalPlayer : LocalPlayers)
{
int32 PlayerId = LocalPlayer->GetControllerId();
SerializePlayerState(PlayerId);
SerializePlayerController(PlayerId);
//SerializePlayerPawn(PlayerId);
SerializePlayerHUD(PlayerId);
}
}
}
void USlotDataTask_Saver::SerializeWorld()
{
check(World);
SE_LOG(Preset, "World '" + World->GetName() + "'", FColor::Green, false, 1);
// Save current game seconds
SlotData->TimeSeconds = World->TimeSeconds;
SerializeLevelSync(World->GetCurrentLevel());
const TArray<ULevelStreaming*>& Levels = World->GetStreamingLevels();
for (const ULevelStreaming* Level : Levels)
{
if (Level->IsLevelLoaded())
{
SerializeLevelSync(Level->GetLoadedLevel(), Level);
}
}
}
void USlotDataTask_Saver::SerializeLevelSync(const ULevel* Level, const ULevelStreaming* StreamingLevel)
{
check(IsValid(Level));
const FName LevelName = StreamingLevel ? StreamingLevel->GetWorldAssetPackageFName() : FPersistentLevelRecord::PersistentName;
SE_LOG(Preset, "Level '" + LevelName.ToString() + "'", FColor::Green, false, 1);
FLevelRecord* LevelRecord = &SlotData->MainLevel;
if (StreamingLevel)
{
// Find or create the sub-level
int32 Index = SlotData->SubLevels.IndexOfByKey(StreamingLevel);
if (Index == INDEX_NONE)
{
Index = SlotData->SubLevels.Add({ StreamingLevel });
}
LevelRecord = &SlotData->SubLevels[Index];
}
check(LevelRecord);
// Empty level before we serialize
LevelRecord->Clean();
//All actors of a class
for (auto ActorItr = Level->Actors.CreateConstIterator(); ActorItr; ++ActorItr)
{
const AActor* Actor = *ActorItr;
if (ShouldSaveAsWorld(Actor))
{
const UClass* ActorClass = Actor->GetClass();
if (const AAIController* AI = Cast<AAIController>(Actor))
{
SerializeAI(AI, *LevelRecord);
}
else if (const ALevelScriptActor* LevelScript = Cast<ALevelScriptActor>(Actor))
{
SerializeLevelScript(LevelScript, *LevelRecord);
}
else
{
FActorRecord Record;
SerializeActor(Actor, Record);
LevelRecord->Actors.Add(Record);
//SE_LOG(Preset, "Actor '" + Actor->GetName() + "'", FColor::White, false, 2);
}
}
}
}
void USlotDataTask_Saver::SerializeLevelScript(const ALevelScriptActor* Level, FLevelRecord& LevelRecord)
{
if (Preset->bStoreLevelBlueprints)
{
check(Level);
if (Level->IsInPersistentLevel())
{
SerializeActor(Level, LevelRecord.LevelScript);
}
else
{
//TODO: Serialize into its own streaming level
}
SE_LOG(Preset, "Level Blueprint '" + Level->GetName() + "'", FColor::White, false, 2);
}
}
void USlotDataTask_Saver::SerializeAI(const AAIController* AIController, FLevelRecord& LevelRecord)
{
if (Preset->bStoreAIControllers)
{
check(AIController);
FControllerRecord Record;
SerializeController(AIController, Record);
LevelRecord.AIControllers.Add(Record);
SE_LOG(Preset, "AI Controller '" + AIController->GetName() + "'", FColor::White, 1);
}
}
void USlotDataTask_Saver::SerializeGameMode()
{
FActorRecord& Record = SlotData->GameMode;
const bool bSuccess = SerializeActor(World->GetAuthGameMode(), Record);
SE_LOG(Preset, "Game Mode '" + Record.Name.ToString() + "'", FColor::Green, !bSuccess, 1);
}
void USlotDataTask_Saver::SerializeGameState()
{
const auto* GameState = World->GetGameState();
FActorRecord& Record = SlotData->GameState;
SerializeActor(GameState, Record);
SE_LOG(Preset, "Game State '" + Record.Name.ToString() + "'", 1);
}
void USlotDataTask_Saver::SerializePlayerState(int32 PlayerId)
{
const auto* Controller = UGameplayStatics::GetPlayerController(World, PlayerId);
if (Controller)
{
FActorRecord& Record = SlotData->PlayerState;
const bool bSuccess = SerializeActor(Controller->PlayerState, Record);
SE_LOG(Preset, "Player State '" + Record.Name.ToString() + "'", FColor::Green, !bSuccess, 1);
}
}
void USlotDataTask_Saver::SerializePlayerController(int32 PlayerId)
{
APlayerController* PlayerController = UGameplayStatics::GetPlayerController(World, PlayerId);
FControllerRecord& Record = SlotData->PlayerController;
const bool bSuccess = SerializeController(PlayerController, Record);
SE_LOG(Preset, "Player Controller '" + Record.Name.ToString() + "'", FColor::Green, !bSuccess, 1);
}
void USlotDataTask_Saver::SerializePlayerHUD(int32 PlayerId)
{
const auto* Controller = UGameplayStatics::GetPlayerController(World, PlayerId);
if (Controller)
{
FActorRecord& Record = SlotData->PlayerHUD;
const bool bSuccess = SerializeActor(Controller->MyHUD, Record);
SE_LOG(Preset, "Player HUD '" + Record.Name.ToString() + "'", FColor::Green, !bSuccess, 1);
}
}
void USlotDataTask_Saver::SerializeGameInstance()
{
UGameInstance* GameInstance = UGameplayStatics::GetGameInstance(World);
if (!GameInstance)
{
SE_LOG(Preset, "Game Instance - No Game Instance Found", FColor::White, true, 1);
return;
}
FObjectRecord Record { GameInstance };
//Serialize into Record Data
FMemoryWriter MemoryWriter(Record.Data, true);
FSaveExtensionArchive Archive(MemoryWriter, false);
GameInstance->Serialize(Archive);
SlotData->GameInstance = MoveTemp(Record);
SE_LOG(Preset, "Game Instance '" + Record.Name.ToString() + "'", FColor::White, 1);
}
bool USlotDataTask_Saver::SerializeActor(const AActor* Actor, FActorRecord& Record)
{
if (!ShouldSave(Actor))
return false;
//Clean the record
Record = { Actor };
Record.bHiddenInGame = Actor->bHidden;
Record.bIsProcedural = IsProcedural(Actor);
if (SavesTags(Actor))
{
Record.Tags = Actor->Tags;
}
const bool bSavesPhysics = SavesPhysics(Actor);
if (SavesTransform(Actor) || bSavesPhysics)
{
Record.Transform = Actor->GetTransform();
}
if (bSavesPhysics)
{
USceneComponent* const Root = Actor->GetRootComponent();
if (Root && Root->Mobility == EComponentMobility::Movable)
{
if (auto* const Primitive = Cast<UPrimitiveComponent>(Root))
{
Record.LinearVelocity = Primitive->GetPhysicsLinearVelocity();
Record.AngularVelocity = Primitive->GetPhysicsAngularVelocityInRadians();
}
else
{
Record.LinearVelocity = Root->GetComponentVelocity();
}
}
}
if (SavesComponents(Actor))
{
SerializeActorComponents(Actor, Record, 1);
}
FMemoryWriter MemoryWriter(Record.Data, true);
FSaveExtensionArchive Archive(MemoryWriter, false);
const_cast<AActor*>(Actor)->Serialize(Archive);
return true;
}
bool USlotDataTask_Saver::SerializeController(const AController* Actor, FControllerRecord& Record)
{
if (ShouldSave(Actor))
{
const bool bResult = SerializeActor(Actor, Record);
if (bResult && Preset->bStoreControlRotation)
{
Record.ControlRotation = Actor->GetControlRotation();
}
return bResult;
}
return false;
}
void USlotDataTask_Saver::SerializeActorComponents(const AActor* Actor, FActorRecord& ActorRecord, int8 Indent)
{
const TSet<UActorComponent*>& Components = Actor->GetComponents();
for (auto* Component : Components)
{
if (!IsValid(Component) ||
!ShouldSave(Component))
{
continue;
}
FComponentRecord ComponentRecord;
ComponentRecord.Name = Component->GetFName();
ComponentRecord.Class = Component->GetClass();
if (SavesTransform(Component))
{
const USceneComponent* Scene = CastChecked<USceneComponent>(Component);
if (Scene->Mobility == EComponentMobility::Movable)
{
ComponentRecord.Transform = Scene->GetRelativeTransform();
}
}
if (SavesTags(Component))
{
ComponentRecord.Tags = Component->ComponentTags;
}
if (!Component->GetClass()->IsChildOf<UPrimitiveComponent>())
{
FMemoryWriter MemoryWriter(ComponentRecord.Data, true);
FSaveExtensionArchive Archive(MemoryWriter, false);
Component->Serialize(Archive);
}
ActorRecord.ComponentRecords.Add(ComponentRecord);
}
}
bool USlotDataTask_Saver::SaveFile(const FString& InfoName, const FString& DataName) const
{
USaveManager* Manager = GetManager();
const USavePreset* Preset = Manager->GetPreset();
USlotInfo* CurrentInfo = Manager->GetCurrentInfo();
USlotData* CurrentData = Manager->GetCurrentData();
if (FFileAdapter::SaveFile(CurrentInfo, InfoName, Preset) &&
FFileAdapter::SaveFile(CurrentData, DataName, Preset))
{
return true;
}
return false;
}
<file_sep>/Docs/documentation/presets.md
# Presets
**A preset is an asset that serves as a configuration preset for Save Extension.**
Within other settings, presets define how the world is saved, what is saved and what is not.
### Default Preset
Under *Project Settings* -> *Game* -> *Save Extension: Default Preset* you will find the default values for all presets.

This default settings page is useful in case you have many presets, or in case you have none (because without any preset, default is used).
{% hint style='hint' %} All settings have defined tooltips describing what they are used for {% endhint %}
#### Gameplay
Defines the runtime behavior of the plugin. Slot templates, maximum numbered slots, autosave, autoload, etc. Debug settings are inside Gameplay as well.
[Check Saving & Loading](saving&loading.md)
#### Serialization
What should be stored and what should not. Here you can decide if you want to store for example AI.
You can also enable compression to reduce drastically
#### Asynchronous
Should load be asynchronous? Should save be asynchronous?
[Check Asynchronous](asynchronous.md)
#### Level Streaming
Should sublevels be saved and loaded individually?
Sublevels will be loaded and saved when they get shown or loaded.
[Check Level Streaming](level-streaming.md)
### Multiple presets
Because presets are assets, the active preset can be switched in runtime allowing different saving setups for different maps or gamemodes.
#### Creating a Preset

You can create a new preset by right-clicking on the content browser -> *Save Extension* -> *Preset*
#### Setting the active Preset
You can set the active preset in editor inside *Project Settings* -> *Game* -> *Save Extension*
<file_sep>/Source/SaveExtension/Public/SlotInfo.h
// Copyright 2015-2018 Piperift. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Engine/Texture2D.h"
#include "GameFramework/SaveGame.h"
#include "SlotInfo.generated.h"
/**
* USaveInfo is the savegame object in charge of saving basic and light info about a saved game.
* E.g: Dates, played time, progress, level
*/
UCLASS(ClassGroup = SaveExtension, hideCategories = ("Activation", "Actor Tick", "Actor", "Input", "Rendering", "Replication", "Socket", "Thumbnail"))
class SAVEEXTENSION_API USlotInfo : public USaveGame
{
GENERATED_UCLASS_BODY()
public:
/** Slot where this SaveInfo and its saveData are saved */
UPROPERTY(Category = SlotInfo, BlueprintReadOnly)
int32 Id;
/**
* Name of this slot
* Could be player written
*/
UPROPERTY(Category = SlotInfo, BlueprintReadWrite)
FText Name;
/**
* Subname of this slot
* Could be used as the name of the place we are saving from. E.g Frozen Lands
*/
UPROPERTY(Category = SlotInfo, BlueprintReadWrite)
FText Subname;
/** Played time since this saved game was started. Not related to slots, slots can change. */
UPROPERTY(Category = SlotInfo, BlueprintReadOnly)
FTimespan TotalPlayedTime;
/** Played time since this slot was created. */
UPROPERTY(Category = SlotInfo, BlueprintReadOnly)
FTimespan SlotPlayedTime;
/** Last date this slot was saved. */
UPROPERTY(Category = SlotInfo, BlueprintReadOnly)
FDateTime SaveDate;
/** Date at which this slot was loaded. */
UPROPERTY(Category = SlotInfo, Transient, BlueprintReadOnly)
FDateTime LoadDate;
/** Opened level when this Slot was saved. Streaming levels wont count, only root levels. */
UPROPERTY(Category = SlotInfo, BlueprintReadOnly)
FName Map;
private:
/** Route to the thumbnail. */
UPROPERTY()
FString ThumbnailPath;
UPROPERTY(Transient)
UTexture2D * CachedThumbnail;
public:
/** Returns a loaded thumbnail if any */
UFUNCTION(BlueprintCallable, Category = SlotInfo)
UTexture2D* GetThumbnail() const;
/** Saves a thumbnail for the current slot */
bool SaveThumbnail(const int32 Width = 640, const int32 Height = 360);
/** Internal Usage. Will be called when an screenshot is captured */
void SetThumbnailPath(const FString& Path);
/** Internal Usage. Will be called to remove previous thumbnail */
FString GetThumbnailPath() { return ThumbnailPath; }
};
| 260ad2710bd94241d854f67bc9d539269ec7d165 | [
"Markdown",
"C++"
]
| 12 | C++ | richmondx/SaveExtension | 2f833b576e7920ae3a5f5075b24194e2aec47c53 | 92bb85b3c33049f1767432b94be356c5a87bec28 |
refs/heads/main | <repo_name>shaie001/Employee-Directory-<file_sep>/build/precache-manifest.cdeaab813e5818ae96696800d9bb5fe2.js
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "<KEY>067461<KEY>",
"url": "/Employee-Directory-/index.html"
},
{
"revision": "f0502039a5cf0d2ec136",
"url": "/Employee-Directory-/static/css/2.74189dbb.chunk.css"
},
{
"revision": "41d131bcf898175d1ffe",
"url": "/Employee-Directory-/static/css/main.c445a03f.chunk.css"
},
{
"revision": "f0502039a5cf0d2ec136",
"url": "/Employee-Directory-/static/js/2.9ce86cb0.chunk.js"
},
{
"revision": "e88a3e95b5364d46e95b35ae8c0dc27d",
"url": "/Employee-Directory-/static/js/2.9ce86cb0.chunk.js.LICENSE.txt"
},
{
"revision": "41d131bcf898175d1ffe",
"url": "/Employee-Directory-/static/js/main.86e687c3.chunk.js"
},
{
"revision": "0e98d41602d6c4d6c2d5",
"url": "/Employee-Directory-/static/js/runtime-main.a7b66dbd.js"
}
]); | 7625b25223d4d8a75ed473cdfbe395a8cccea8d9 | [
"JavaScript"
]
| 1 | JavaScript | shaie001/Employee-Directory- | cdc37717d43284bbff5bf9de7bf446453e9867ff | b0c8ed12ec10675e34deb73bf6fa7af8410904fc |
refs/heads/master | <repo_name>nodm/the-weather<file_sep>/src/app/modules/forecast/facades/forecast-facade.ts
import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { selectForecast, State, loadForecast } from '../store';
import { ForecastCard } from '../models';
@Injectable()
export class ForecastFacade {
public forecastCard$: Observable<ForecastCard> = this.store.select(selectForecast);
constructor(private store: Store<State>) {}
public loadForecast(locationId: string) {
this.store.dispatch(loadForecast({ locationId }));
}
}
<file_sep>/src/app/modules/forecast/constants/index.ts
export { DARK_SKY_API } from './dark-sky.constant';
export { FORECAST_STATE_ID, ERROR_SNACKBAR_DURATION } from './forecast.constant';
<file_sep>/src/app/modules/app-shell/store/forecast-locations.actions.ts
import { createAction, props } from '@ngrx/store';
import { ForecastLocation } from '~shared/models/forecast-location.interface';
export const initForecastLocation = createAction(
'[Forecast Locations] Initialize',
);
export const addForecastLocation = createAction(
'[Forecast Locations] Add forecast location',
props<{ forecastLocation: ForecastLocation }>(),
);
export const addForecastLocations = createAction(
'[Forecast Locations] Add forecast locations',
props<{ forecastLocations: ForecastLocation[] }>(),
);
<file_sep>/src/app/modules/forecast/guards/forecast.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import { ForecastFacade } from '../facades/forecast-facade';
@Injectable()
export class ForecastGuard implements CanActivate {
constructor(private forecastFacade: ForecastFacade) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
): boolean {
const { locationId } = next.params;
this.forecastFacade.loadForecast(locationId);
return true;
}
}
<file_sep>/src/app/modules/app-update/services/app-update.service.ts
import { ApplicationRef, Injectable } from '@angular/core';
import { SwUpdate, UpdateAvailableEvent } from '@angular/service-worker';
import { MatSnackBar } from '@angular/material/snack-bar';
import { concat, interval } from 'rxjs';
import { first } from 'rxjs/operators';
import { INSTALL_UPDATE_SNACKBAR_DURATION, NEW_VERSION_ACTIVATED_SNACKBAR_DURATION } from '../constants/app-update.constants';
@Injectable()
export class AppUpdateService {
constructor(
private appRef: ApplicationRef,
private swUpdate: SwUpdate,
private snackBar: MatSnackBar,
) {
if (swUpdate.isEnabled) {
this.createNewVersionAvailableSubscription();
this.createNewVersionActivatedSubscription();
this.createUpdateCheckerScheduler();
}
}
private createNewVersionAvailableSubscription() {
this.swUpdate.available.subscribe((updateAvailableEvent: UpdateAvailableEvent) => {
const newVersionData = updateAvailableEvent.available.appData as { version: string, whatsNew: string };
const snackBarRef = this.snackBar.open(
`Version ${newVersionData.version} is available. Updates:${newVersionData.whatsNew}`,
'INSTALL',
{ duration: INSTALL_UPDATE_SNACKBAR_DURATION }
);
snackBarRef.onAction().subscribe(() => {
this.swUpdate.activateUpdate().then(() => {
window.location.reload();
});
});
});
}
private createNewVersionActivatedSubscription() {
this.swUpdate.activated.subscribe(event => {
this.snackBar.open(
`A new application version is activated (${event.current})`,
'OK',
{ duration: NEW_VERSION_ACTIVATED_SNACKBAR_DURATION }
);
});
}
private createUpdateCheckerScheduler() {
const appIsStable$ = this.appRef.isStable.pipe(first(isStable => isStable === true));
const everyHour$ = interval(60 * 60 * 1000);
const everySixHoursOnceAppIsStable$ = concat(appIsStable$, everyHour$);
everySixHoursOnceAppIsStable$.subscribe(() => this.swUpdate.checkForUpdate());
}
}
<file_sep>/src/app/shared/models/index.ts
export { CallState } from './call-state.type';
export { ForecastLocation } from './forecast-location.interface';
<file_sep>/src/app/shared/models/call-state.type.ts
import { LoadingState } from '../constants/loading-state.enum';
export type CallState = LoadingState | Error;
<file_sep>/src/app/modules/app-shell/index.ts
export { selectForecastLocationEntities, selectForecastLocationList } from './store';
export { HomeComponent } from './components/home/home.component';
export { ShellComponent } from './components/shell/shell.component';
export { AppShellModule } from './app-shell.module';
<file_sep>/src/app/modules/forecast/services/index.ts
export { DarkSkyHttpService } from './dark-sky-http.service';
export { GeoLocationService } from './geo-location.service';
<file_sep>/src/app/modules/app-shell/components/shell/shell.component.ts
import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';
import { MediaMatcher } from '@angular/cdk/layout';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { AppConfigService } from '~shared/services/app-config.service';
import { ForecastLocation } from '~shared/models/forecast-location.interface';
import { APPLICATION_NAME } from '../../constants/shell.constants';
import { State, initForecastLocation, selectForecastLocationList } from '../../store';
@Component({
selector: 'app-shell',
templateUrl: './shell.component.html',
styleUrls: ['./shell.component.scss']
})
export class ShellComponent implements OnInit, OnDestroy {
public readonly appName = APPLICATION_NAME;
public readonly buildNumber = this.appConfigService.buildNumber;
public readonly forecastLocationList$: Observable<ForecastLocation[]> = this.store.select(selectForecastLocationList);
public mobileQuery: MediaQueryList;
private mobileQueryListener: () => void;
constructor(
private changeDetectorRef: ChangeDetectorRef,
private media: MediaMatcher,
private store: Store<State>,
private appConfigService: AppConfigService,
) {}
ngOnInit() {
this.mobileQuery = this.media.matchMedia('(max-width: 600px)');
this.mobileQueryListener = () => this.changeDetectorRef.detectChanges();
this.mobileQuery.addListener(this.mobileQueryListener);
this.store.dispatch(initForecastLocation());
}
ngOnDestroy(): void {
this.mobileQuery.removeListener(this.mobileQueryListener);
}
}
<file_sep>/src/app/modules/notification-management/services/push-notification.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { SwPush } from '@angular/service-worker';
import { AppConfigService } from '~shared/services/app-config.service';
import { MatSnackBar } from '@angular/material/snack-bar';
@Injectable()
export class PushNotificationService {
constructor(
private httpClient: HttpClient,
private swPush: SwPush,
private router: Router,
private apiConfigService: AppConfigService,
private snackBar: MatSnackBar,
) {
this.swPush.notificationClicks.subscribe(this.onNotificationClick.bind(this));
}
public requestSubscriptionToPush(): Promise<boolean> {
if (!this.swPush.isEnabled) {
return Promise.resolve(false);
}
return this.swPush.requestSubscription({ serverPublicKey: this.apiConfigService.vapidPublicKey })
.then((subscription: PushSubscription) => this.registerSubscription(subscription))
.catch(() => false);
}
public send(message?: string): void {
this.httpClient.post('/api/send', { message } || null).subscribe(
() => this.snackBar.open('Push message sent successfully.', 'Ok', { duration: 3000 }),
(err) => this.snackBar.open(`Error: ${err.message}`, 'Ok'),
);
}
private registerSubscription(subscription: PushSubscription): Promise<boolean> {
return this.httpClient.post('/api/subscribe', subscription).toPromise()
.then(() => true)
.catch(() => false);
}
private onNotificationClick(event: { action: string, notification: NotificationOptions & { title: string }}) {
switch (event.action) {
case 'show_forecast_warsaw':
this.router.navigate(['/forecast', '52-233-21-017']);
break;
case 'show_forecast_kyiv':
this.router.navigate(['/forecast', '50-45-30-524']);
}
}
}
<file_sep>/src/app/modules/forecast/store/forecast.effects.ts
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRoute } from '@angular/router';
import { Store } from '@ngrx/store';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { map, mergeMap, catchError, tap, switchMap } from 'rxjs/operators';
import { selectForecastLocationEntities } from '~modules/app-shell';
import { ERROR_SNACKBAR_DURATION } from '../constants';
import { Forecast } from '../models';
import { DarkSkyHttpService } from '../services';
import {
loadForecast,
fetchForecast,
fetchForecastSuccess,
fetchForecastError,
} from './forecast.actions';
import { State } from './forecast.state';
@Injectable()
export class ForecastEffects {
constructor(
private activatedRoute: ActivatedRoute,
private store: Store<State>,
private actions$: Actions,
private snackBar: MatSnackBar,
private darkSkyHttpService: DarkSkyHttpService,
) {}
public loadForecast$ = createEffect(() => this.actions$.pipe(
ofType(loadForecast),
switchMap((action) => this.store.select(selectForecastLocationEntities).pipe(
map((forecastLocationEntities) => {
const forecastLocation = forecastLocationEntities[action.locationId];
return fetchForecast({ forecastLocation });
})
))
));
public fetchForecast$ = createEffect(() => this.actions$.pipe(
ofType(fetchForecast),
mergeMap(action => this.darkSkyHttpService.fetchForecast(action.forecastLocation).pipe(
map((forecast: Forecast) => fetchForecastSuccess({ forecastLocation: action.forecastLocation, forecast })),
catchError((error: Error) => of(fetchForecastError({ forecastLocation: action.forecastLocation, error }))),
)),
));
public fetchForecastError$ = createEffect(() => this.actions$.pipe(
ofType(fetchForecastError),
tap((action) => {
this.snackBar.open(
`Error fetching forecast data for ${action.forecastLocation.name}`,
'OK',
{ duration: ERROR_SNACKBAR_DURATION }
);
}),
), { dispatch: false });
}
<file_sep>/src/app/modules/forecast/components/forecast/forecast.component.ts
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { ForecastCard } from '../../models';
@Component({
selector: 'app-forecast',
templateUrl: './forecast.component.html',
styleUrls: ['./forecast.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ForecastComponent {
@Input() forecastCard: ForecastCard;
}
<file_sep>/src/app/modules/forecast/guards/forecast.guard.spec.ts
import { TestBed, async, inject } from '@angular/core/testing';
import { ForecastGuard } from './forecast.guard';
describe('ForecastGuard', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ForecastGuard]
});
});
it('should ...', inject([ForecastGuard], (guard: ForecastGuard) => {
expect(guard).toBeTruthy();
}));
});
<file_sep>/src/app/modules/notification-management/components/notification-management/notification-management.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { PushNotificationService } from '../../services/push-notification.service';
@Component({
selector: 'app-notification-management',
templateUrl: './notification-management.component.html',
styleUrls: ['./notification-management.component.scss']
})
export class NotificationManagementComponent implements OnInit {
public isNotificationsEnabled = false;
public notificationForm: FormGroup;
constructor(
private formBuilder: FormBuilder,
private pushNotificationService: PushNotificationService,
) { }
public ngOnInit(): void {
this.notificationForm = this.formBuilder.group({
message: this.formBuilder.control(''),
});
this.pushNotificationService.requestSubscriptionToPush()
.then((isEnable) => {
this.isNotificationsEnabled = isEnable;
});
}
public onSubmit() {
const { message } = this.notificationForm.value;
this.pushNotificationService.send(message);
}
}
<file_sep>/src/app/modules/app-update/constants/app-update.constants.ts
export const INSTALL_UPDATE_SNACKBAR_DURATION = 15000;
export const NEW_VERSION_ACTIVATED_SNACKBAR_DURATION = 10000;
<file_sep>/src/app/modules/forecast/store/forecast.selectors.ts
import { createFeatureSelector, createSelector } from '@ngrx/store';
import { FORECAST_STATE_ID } from '../constants';
import { ForecastCard } from '../models';
import { State } from './forecast.state';
import { ForecastUtils } from '../utils/forecast.utils';
const selectForecastState = createFeatureSelector<State>(FORECAST_STATE_ID);
const selectForecastPayload = createSelector(
selectForecastState,
(state: State) => state.payload,
);
export const selectForecast = createSelector(
selectForecastPayload,
(payload): ForecastCard => {
return payload ? ForecastUtils.mapForecast2ForecastCard(payload.forecast) : null;
}
);
<file_sep>/src/app/modules/forecast/components/index.ts
export { ForecastComponent } from './forecast/forecast.component';
export { ForecastContainerComponent } from './forecast-container/forecast-container.component';
export { ForecastDetailedComponent } from './forecast-detailed/forecast-detailed.component';
export { ForecastPlaceholderComponent } from './forecast-placeholder/forecast-placeholder.component';
export { ForecastShortComponent } from './forecast-short/forecast-short.component';
export { WeatherIconComponent } from './weather-icon/weather-icon.component';
<file_sep>/src/app/modules/forecast/store/forecast.reducer.ts
import { Action, createReducer, on } from '@ngrx/store';
import { fetchForecastSuccess, cleanForecastState } from './forecast.actions';
import { initialState, State } from './forecast.state';
const forecastReducer = createReducer(
initialState,
on(fetchForecastSuccess, (state, payload) => ({
...state,
payload,
})),
on(cleanForecastState, () => initialState),
);
export function reducer(state: State | undefined, action: Action) {
return forecastReducer(state, action);
}
<file_sep>/src/app/modules/forecast/components/forecast-container/forecast-container.component.ts
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { ForecastFacade } from '../../facades/forecast-facade';
@Component({
selector: 'app-forecast-container',
templateUrl: './forecast-container.component.html',
styleUrls: ['./forecast-container.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ForecastContainerComponent {
public forecastCard$ = this.forecastFacade.forecastCard$;
constructor(private forecastFacade: ForecastFacade) {
}
}
<file_sep>/src/app/modules/forecast/services/dark-sky-http.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import { DarkSkyHttpService } from './dark-sky-http.service';
xdescribe('DarkSkyHttpService', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [
HttpClientModule,
DarkSkyHttpService,
],
}));
it('should be created', () => {
const service: DarkSkyHttpService = TestBed.get(DarkSkyHttpService);
expect(service).toBeTruthy();
});
});
<file_sep>/src/app/modules/forecast/store/forecast.actions.ts
import { createAction, props } from '@ngrx/store';
import { ForecastLocation } from '~shared/models';
import { Forecast } from '../models';
export const loadForecast = createAction(
'[Forecast effect] Load forecast',
props<{ locationId: string }>()
);
export const fetchForecast = createAction(
'[Forecast effect] Fetch forecast',
props<{ forecastLocation: ForecastLocation }>()
);
export const fetchForecastSuccess = createAction(
'[Forecast effect] Fetch forecast success',
props<{ forecastLocation: ForecastLocation, forecast: Forecast }>()
);
export const fetchForecastError = createAction(
'[Forecast effect] Fetch forecast error',
props<{ forecastLocation: ForecastLocation, error: Error }>()
);
export const cleanForecastState = createAction('[Forecast] Clean forecast state');
<file_sep>/src/app/modules/forecast/models/daily-forecast.interface.ts
import { WeatherSummary } from './weather-summary.type';
export interface DailyForecast {
// The percentage of sky occluded by clouds, between 0 and 1, inclusive.
cloudCover: number;
// The relative humidity, between 0 and 1, inclusive.
humidity: number;
// A machine-readable text summary of this data point, suitable for selecting an icon for display.
// If defined, this property will have one of the following values: clear-day, clear-night, rain,
// snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night.
// (Developers should ensure that a sensible default is defined, as additional values, such as
// hail, thunderstorm, or tornado, may be defined in the future.)
icon?: WeatherSummary;
// A human-readable text summary of this data point. (This property has millions of possible values,
// so don’t use it for automated purposes: use the icon property, instead!)
summary?: string;
// The probability of precipitation occurring, between 0 and 1, inclusive.
precipProbability?: number;
// The type of precipitation occurring at the given time. If defined, this property will have one of
// the following values: "rain", "snow", or "sleet" (which refers to each of freezing rain, ice pellets,
// and “wintery mix”). (If precipIntensity is zero, then this property will not be defined. Additionally,
// due to the lack of data in our sources, historical precipType information is usually estimated, rather
// than observed.)
precipType?: string;
// The sea-level air pressure in millibars.
pressure?: string;
// The UNIX time of when the sun will rise during a given day.
sunriseTime?: number;
// The UNIX time of when the sun will set during a given day.
sunsetTime?: number;
// The daytime high temperature
temperatureHigh: number;
// The overnight low temperature.
temperatureLow: number;
// The UNIX time at which this data point begins. minutely data point are always aligned to the top of the
// minute, hourly data point objects to the top of the hour, daily data point objects to midnight of the
// day, and currently data point object to the point of time provided all according to the local time zone.
time: number;
// The direction that the wind is coming from in degrees, with true north at 0° and progressing clockwise.
// (If windSpeed is zero, then this value will not be defined.)
windBearing?: number;
// The wind speed in miles per hour.
windSpeed?: number;
}
<file_sep>/README.md
[](https://travis-ci.com/nodm/the-weather)
#  theWeather
This project is a [Progressive Web Application](https://en.wikipedia.org/wiki/Progressive_web_application) (also known as a PWA) built with [Angular](https://angular.io).
You can check the weather forecast for your current location or for a set of predefined locations, including Kyiv and some cities in Scandinavia.
You can get the application with the [link](https://the-weather-8210d.firebaseapp.com/). You can install and place it on a home screen on Android, iOS, MacOS, Linux and Windows.
**theWeather** app checks for updates, notifies user and asks for installation. So you could always use the latest version.
## Development
### Prerequisites
* register on [Dark Sky](https://darksky.net/dev) website to get a secret API key (trial account allows up to 1,000 free calls per day to evaluate the Dark Sky API)
* generate a VAPID (VAPID stands for **V**oluntary **A**pplication **S**erver **I**dentification for Web Push protocol) key pair:
```shell script
npm i -g web-push
web-push generate-vapid-keys --json
```
A VAPID key pair looks like:
```json
{
"publicKey":"<KEY>",
"privateKey":"<KEY>"
}
```
Replace `<YOUR_DARK_SKY_API_KEY>` with your secret API key and `<YOUR_VAPID_PUBLIC_KEY>` with VAPID's public key in file `src/app/shared/services/app-config.service.ts`
### Application development without service worker support
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
### PWA Application development
Because `ng serve` does not work with service workers, you must use a separate HTTP server to test your project locally.
You can use any HTTP server (for example [serve](https://github.com/zeit/serve), [http-server](https://www.npmjs.com/package/http-server) etc. ).
I prefer the [http-server](https://www.npmjs.com/package/http-server) package from 'npm'. To reduce the possibility of
conflicts and avoid serving stale content, test on a dedicated port and disable caching.
To run the application with service worker support run the following commands:
* build the app in a **production** mode
```shell script
ng build --prod
```
* serve the directory containing your web files with **http-server**
```shell script
http-server -c-1 -p 8080 --proxy http://localhost dist/the-weather
```
* navigate to `http://localhost:8080`
>In order for service workers to be registered, the app must be accessed over HTTPS, not HTTP. Browsers ignore service workers on pages that are served over an
insecure connection. The reason is that service workers are quite powerful, so extra care needs to be taken to ensure the service worker script has not been tampered with.
There is one exception to this rule: to make local development easier, browsers do not require a secure connection when accessing an app on localhost.
([Angular Service Workers & PWA](https://angular.io/guide/service-worker-getting-started#serving-with-http-server))
### Web Push Notifications
To test Web Push Notifications you should run a [server](https://github.com/nodm/the-weather-service).
Clone the repo, copy `src/app-config.json.dist` to `src/app-config.json` and replace:
* `port` with `80`,
* `< Your VAPID public key>` with a VAPID public key, generated in [Prerequisites](#prerequisites) section,
* `< Your VAPID private key >` with a VAPID private key, generated in [Prerequisites](#prerequisites) section,
* `< Your email >` with your email address,
* `< You DarkSky API key >` with a VAPID private key, generated in [Prerequisites](#prerequisites) section,
Run the server with a command:
```shell script
node start
```
Now you can send and receive Web Push notifications!
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Useful links
1. [Progressive Web Apps](https://developers.google.com/web/progressive-web-apps/)
2. [Your first Progressive Web App](https://codelabs.developers.google.com/codelabs/your-first-pwapp/#0) codelab by Google.
3. [The Web App Manifest](https://developers.google.com/web/fundamentals/web-app-manifest)
4. [Web App Manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest#Members) on `developer.mozilla.org`
5. [The Basics of Web Workers](https://www.html5rocks.com/en/tutorials/workers/basics/)
6. [Service Workers: an Introduction](https://developers.google.com/web/fundamentals/primers/service-workers)
7. [Caching best practices & max-age gotchas](https://jakearchibald.com/2016/caching-best-practices/) by <NAME>
8. [Angular Service Worker & PWA](https://angular.io/guide/service-worker-intro)
9. [Service Workers & Angular](https://medium.com/bratislava-angular/service-workers-angular-3c1551f0c203) by <NAME>, Bratislava Angular
10. [Service Workers - Practical Guided Introduction (several examples)](https://blog.angular-university.io/service-workers/) by Angular University
11. [Angular Service Worker - Step-By-Step Guide for turning your Application into a PWA](https://blog.angular-university.io/angular-service-worker/) by Angular University
12. [Angular Push Notifications: a Complete Step-by-Step Guide](https://blog.angular-university.io/angular-push-notifications/) by Angular University
13. [How to Cache HTTP Requests in an Angular App (PWA)](https://christianlydemann.com/how-to-cache-http-requests-in-an-angular-pwa/) by <NAME>
14. [The Beginners Guide to Service Workers and Angular](https://blog.ng-book.com/service-workers-and-angular/) <NAME>
15. [Web PUSH Notifications быстро и просто](https://habr.com/ru/post/321924/)
16. [Beginners guide to Web Push Notifications using Service Workers](https://medium.com/izettle-engineering/beginners-guide-to-web-push-notifications-using-service-workers-cb3474a17679)
17. [Web Push Book](https://web-push-book.gauntface.com/)
18. [Add to Home Screen](https://developers.google.com/web/fundamentals/app-install-banners) by <NAME>
19. [Patterns for Promoting PWA Installation (mobile)](https://developers.google.com/web/fundamentals/app-install-banners/promoting-install-mobile) by <NAME>
20. [Advanced angular 7 PWA tutorial ( Part -1)](https://www.youtube.com/watch?v=f26hgzyGdHM)
21. [Angular Service Worker Tutorial](https://www.youtube.com/watch?v=5YtNQJQu31Y)
<file_sep>/src/app/modules/forecast/store/forecast.state.ts
import { ForecastLocation } from '~shared/models';
import { Forecast } from '../models';
export interface State {
payload: {
forecastLocation: ForecastLocation,
forecast: Forecast,
};
}
export const initialState: State = {
payload: null,
};
<file_sep>/src/app/modules/forecast/services/dark-sky-http.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AppConfigService } from '~shared/services/app-config.service';
import { ForecastLocation } from '~shared/models';
import { DARK_SKY_API } from '../constants';
import { Forecast } from '../models';
@Injectable()
export class DarkSkyHttpService {
constructor(
private httpClient: HttpClient,
private appConfigService: AppConfigService,
) {}
public fetchForecast(forecastLocation: ForecastLocation): Observable<Forecast> {
const { latitude, longitude } = forecastLocation;
const coordinates = [latitude, longitude].join(',');
const url = [DARK_SKY_API, this.appConfigService.darkSkyApiKey, coordinates].join('/');
const params = new HttpParams()
.set('exclude', 'minutely,hourly,alerts,flags')
.set('units', 'si');
return this.httpClient.get<Forecast>(url, { params });
}
}
<file_sep>/src/app/modules/app-shell/store/forecast-locations.reducer.ts
import { Action, createReducer, on } from '@ngrx/store';
import { addForecastLocation, addForecastLocations } from './forecast-locations.actions';
import { initialState, State, adapter } from './forecast-locations.state';
const forecastLocationsReducer = createReducer(
initialState,
on(addForecastLocation, (state, { forecastLocation }) => {
return adapter.upsertOne(forecastLocation, state);
}),
on(addForecastLocations, (state, { forecastLocations }) => {
return adapter.upsertMany(forecastLocations, state);
}),
);
export function reducer(state: State | undefined, action: Action) {
return forecastLocationsReducer(state, action);
}
<file_sep>/src/app/modules/forecast/utils/forecast.utils.ts
import { Forecast } from '../models/forecast.interface';
import { DetailedForecast, ForecastCard, ShortForecast } from '../models/forecast-card.interface';
import { DailyForecast } from '../models/daily-forecast.interface';
export const ForecastUtils = {
mapForecast2ForecastCard: (forecast: Forecast): ForecastCard => {
const forecastLocation = forecast.forecastLocation;
const [ current, ...dailyList ] = forecast.daily.data;
const currently: DetailedForecast = {
time: forecast.currently.time,
summary: forecast.currently.summary,
icon: forecast.currently.icon,
temperature: forecast.currently.temperature,
humidity: forecast.currently.humidity,
windSpeed: forecast.currently.windSpeed,
windBearing: forecast.currently.windBearing,
sunriseTime: current.sunriseTime,
sunsetTime: current.sunsetTime,
};
const daily: ShortForecast[] = dailyList.map((dailyForecast: DailyForecast) => ({
time: dailyForecast.time,
icon: dailyForecast.icon,
summary: dailyForecast.summary,
temperatureHigh: dailyForecast.temperatureHigh,
temperatureLow: dailyForecast.temperatureLow,
}));
return { forecastLocation, currently, daily };
},
};
<file_sep>/src/app/modules/forecast/constants/forecast.constant.ts
export const FORECAST_STATE_ID = 'forecast';
export const ERROR_SNACKBAR_DURATION = 3000;
<file_sep>/src/app/shared/constants/app-routes.ts
export const enum AppRoutes {
forecast = 'forecast',
notificationManagement = 'notification-management',
}
<file_sep>/src/app/modules/forecast/forecast.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { MatCardModule } from '@angular/material/card';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { ForecastRoutingModule } from './forecast-routing.module';
import {
ForecastComponent,
ForecastContainerComponent,
ForecastDetailedComponent,
ForecastPlaceholderComponent,
ForecastShortComponent,
WeatherIconComponent,
} from './components';
import { FORECAST_STATE_ID } from './constants';
import { ForecastFacade } from './facades/forecast-facade';
import { DarkSkyHttpService, GeoLocationService } from './services';
import { reducer, ForecastEffects } from './store';
@NgModule({
declarations: [
ForecastContainerComponent,
ForecastComponent,
ForecastDetailedComponent,
ForecastShortComponent,
ForecastPlaceholderComponent,
WeatherIconComponent,
],
imports: [
CommonModule,
HttpClientModule,
MatCardModule,
MatSnackBarModule,
MatTooltipModule,
StoreModule.forFeature(FORECAST_STATE_ID, reducer),
EffectsModule.forFeature([ForecastEffects]),
ForecastRoutingModule,
],
providers: [
ForecastFacade,
DarkSkyHttpService,
GeoLocationService,
],
})
export class ForecastModule { }
<file_sep>/src/app/modules/forecast/components/weather-icon/weather-icon.component.ts
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { WeatherSummary } from '../../models';
@Component({
selector: 'app-weather-icon',
template: `<img class="icon" [src]="imageSource" [alt]="summary">`,
styleUrls: ['./weather-icon.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class WeatherIconComponent {
@Input() name: WeatherSummary;
@Input() summary: string;
public get imageSource(): string {
return `assets/images/${this.name}.svg`;
}
}
<file_sep>/src/app/modules/forecast/components/forecast-short/forecast-short.component.ts
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { ShortForecast } from '../../models/forecast-card.interface';
@Component({
selector: 'app-forecast-short',
templateUrl: './forecast-short.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ForecastShortComponent {
@Input() forecast: ShortForecast;
}
<file_sep>/src/app/modules/forecast/models/forecast-card.interface.ts
import { ForecastLocation } from '~shared/models/forecast-location.interface';
import { WeatherSummary } from './weather-summary.type';
export interface ShortForecast {
time: number;
icon: WeatherSummary;
summary: string;
temperatureHigh: number;
temperatureLow: number;
}
export interface DetailedForecast {
time: number;
summary: string;
icon: WeatherSummary;
temperature: number;
humidity: number;
windSpeed: number;
windBearing: number;
sunriseTime: number;
sunsetTime: number;
}
export interface ForecastCard {
forecastLocation: ForecastLocation;
currently: DetailedForecast;
daily: ShortForecast[];
}
<file_sep>/src/app/modules/app-shell/store/forecast-locations.effects.ts
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { merge, of, EMPTY } from 'rxjs';
import { map, catchError, switchMap } from 'rxjs/operators';
import { LocationUtils } from '~shared/utils/location.utils';
import { initForecastLocation, addForecastLocations, addForecastLocation } from './forecast-locations.actions';
import { FORECAST_LOCATION_LIST, COORDINATE_PRECISION, CURRENT_LOCATION_NAME } from '../constants/forecast-locations.constant';
import { GeoLocationService } from '../services/geo-location.service';
@Injectable()
export class ForecastLocationsEffects {
constructor(
private actions$: Actions,
private snackBar: MatSnackBar,
private geoLocationService: GeoLocationService,
) {}
public initForecastLocation$ = createEffect(() => this.actions$.pipe(
ofType(initForecastLocation),
switchMap(() => {
const addCurrentLocation$ = this.geoLocationService.getCurrentPosition().pipe(
map((position: Position) => {
const latitude = LocationUtils.round(position.coords.latitude, COORDINATE_PRECISION);
const longitude = LocationUtils.round(position.coords.longitude, COORDINATE_PRECISION);
const id = LocationUtils.getId({ latitude, longitude });
const forecastLocation = {
id,
name: CURRENT_LOCATION_NAME,
order: 0,
latitude,
longitude,
};
return addForecastLocation({ forecastLocation });
}),
catchError(() => EMPTY),
);
return merge(addCurrentLocation$, of(addForecastLocations({ forecastLocations: FORECAST_LOCATION_LIST })));
}),
));
}
<file_sep>/src/app/modules/app-shell/constants/shell.constants.ts
export const APPLICATION_NAME = 'the Weather';
<file_sep>/src/app/shared/services/app-config.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class AppConfigService {
// @ts-ignore
private readonly config = window.appConfig;
public get buildNumber(): string {
return `build ${this.config.buildNumber || '#'}`;
}
public get darkSkyApiKey(): string {
// return this.config.darkSkyApiKey === '%DARK_SKY_API_KEY%' ? '<YOUR_DARK_SKY_API_KEY>' : this.config.darkSkyApiKey;
return this.config.darkSkyApiKey === '%DARK_SKY_API_KEY%' ? '59cd2c19bac276c0e4555230f327e3ee' : this.config.darkSkyApiKey;
}
public get vapidPublicKey(): string {
return this.config.vapidPublicKey === '%VAPID_PUBLIC_KEY%'
? '<KEY>'
// ? '<YOUR_VAPID_PUBLIC_KEY>'
: this.config.vapidPublicKey;
}
}
<file_sep>/src/app/modules/forecast/models/forecast.interface.ts
import { ForecastLocation } from '~shared/models/forecast-location.interface';
import { CurrentForecast } from './current-forecast.interface';
import { DailyForecast } from './daily-forecast.interface';
import { WeatherSummary } from './weather-summary.type';
export interface Forecast {
forecastLocation: ForecastLocation;
currently: CurrentForecast;
daily: {
data: DailyForecast[];
icon: WeatherSummary;
summary: string;
};
latitude: number;
longitude: number;
offset: number;
timezone: string;
}
<file_sep>/src/app/modules/forecast/store/index.ts
export { State } from './forecast.state';
export { reducer } from './forecast.reducer';
export { loadForecast } from './forecast.actions';
export { ForecastEffects } from './forecast.effects';
export { selectForecast } from './forecast.selectors';
<file_sep>/src/app/modules/app-shell/constants/forecast-locations.constant.ts
import { LocationUtils } from '~shared/utils/location.utils';
import { ForecastLocation } from '~shared/models/forecast-location.interface';
export const FORECAST_LOCATIONS_STATE_ID = 'forecast-locations';
export const CURRENT_LOCATION_NAME = 'Current location';
export const FORECAST_LOCATION_LIST: ForecastLocation[] = [
{
name: 'Kyiv',
order: 1,
latitude: 50.450,
longitude: 30.524,
}, {
name: 'Warsaw',
order: 2,
latitude: 52.233,
longitude: 21.017,
},
{
name: 'København',
order: 3,
latitude: 55.676,
longitude: 12.568,
},
{
name: 'Oslo',
order: 4,
latitude: 59.917,
longitude: 10.733,
},
{
name: 'Stockholm',
order: 5,
latitude: 59.329,
longitude: 18.069,
},
{
name: 'Malmö',
order: 6,
latitude: 55.606,
longitude: 13.036,
},
{
name: 'Göteborg',
order: 7,
latitude: 57.7,
longitude: 11.967,
},
].map(forecastLocation => ({ id: LocationUtils.getId(forecastLocation), ...forecastLocation }));
export const COORDINATE_PRECISION = 3;
<file_sep>/src/app/modules/app-shell/store/forecast-locations.selectors.ts
import { createFeatureSelector, createSelector } from '@ngrx/store';
import { FORECAST_LOCATIONS_STATE_ID } from '../constants/forecast-locations.constant';
import { State, adapter } from './forecast-locations.state';
const selectForecastLocationsState = createFeatureSelector<State>(FORECAST_LOCATIONS_STATE_ID);
const { selectAll, selectEntities } = adapter.getSelectors();
export const selectForecastLocationEntities = createSelector(
selectForecastLocationsState,
selectEntities,
);
export const selectForecastLocationList = createSelector(
selectForecastLocationsState,
selectAll,
);
<file_sep>/src/app/modules/forecast/constants/dark-sky.constant.ts
export const DARK_SKY_API = 'https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast';
<file_sep>/src/app/modules/app-shell/store/forecast-locations.state.ts
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity';
import { ForecastLocation } from '~shared/models/forecast-location.interface';
export interface State extends EntityState<ForecastLocation> {}
export const adapter: EntityAdapter<ForecastLocation> = createEntityAdapter<ForecastLocation>({
sortComparer: (a: ForecastLocation, b: ForecastLocation) => (a.order - b.order),
});
export const initialState: State = adapter.getInitialState();
<file_sep>/src/app/modules/app-shell/app-shell.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatToolbarModule } from '@angular/material/toolbar';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { ShellComponent } from './components/shell/shell.component';
import { FORECAST_LOCATIONS_STATE_ID } from './constants/forecast-locations.constant';
import { reducer, ForecastLocationsEffects } from './store';
import { GeoLocationService } from './services/geo-location.service';
import { HomeComponent } from './components/home/home.component';
@NgModule({
declarations: [
ShellComponent,
HomeComponent,
],
exports: [
ShellComponent,
],
imports: [
CommonModule,
RouterModule,
MatButtonModule,
MatDividerModule,
MatIconModule,
MatListModule,
MatSidenavModule,
MatToolbarModule,
StoreModule.forFeature(FORECAST_LOCATIONS_STATE_ID, reducer),
EffectsModule.forFeature([ForecastLocationsEffects]),
],
providers: [
GeoLocationService,
],
})
export class AppShellModule { }
<file_sep>/src/app/modules/forecast/models/index.ts
export { CurrentForecast } from './current-forecast.interface';
export { DailyForecast } from './daily-forecast.interface';
export { Forecast } from './forecast.interface';
export { ForecastCard, ShortForecast, DetailedForecast } from './forecast-card.interface';
export { WeatherSummary } from './weather-summary.type';
<file_sep>/src/app/shared/utils/location.utils.ts
export const LocationUtils = {
getId: ({ latitude, longitude }): string => `${latitude}-${longitude}`.replace(/\./g, '-'),
round: (value: number, precision: number): number => {
const n = Math.pow(10, precision);
return Math.round(value * n) / n;
}
};
<file_sep>/src/app/modules/app-shell/store/index.ts
export { initForecastLocation, addForecastLocation, addForecastLocations } from './forecast-locations.actions';
export { State } from './forecast-locations.state';
export { reducer } from './forecast-locations.reducer';
export { ForecastLocationsEffects } from './forecast-locations.effects';
export { selectForecastLocationEntities, selectForecastLocationList } from './forecast-locations.selectors';
<file_sep>/src/app/modules/app-shell/services/geo-location.service.ts
import { Injectable } from '@angular/core';
import { from, Observable, throwError } from 'rxjs';
@Injectable()
export class GeoLocationService {
public readonly isEnabled = ('geolocation' in navigator);
public getCurrentPosition(): Observable<Position> {
if (!this.isEnabled) {
return throwError(new Error('Geolocation is not supported by the browser.'));
}
return from(new Promise<Position>((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject);
}));
}
}
<file_sep>/src/app/modules/forecast/components/forecast/forecast.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import { ForecastDetailedComponent } from '../forecast-detailed/forecast-detailed.component';
import { ForecastShortComponent } from '../forecast-short/forecast-short.component';
import { DarkSkyHttpService } from '../../services/dark-sky-http.service';
import { ForecastComponent } from './forecast.component';
xdescribe('ForecastComponent', () => {
let component: ForecastComponent;
let fixture: ComponentFixture<ForecastComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
HttpClientModule,
ForecastDetailedComponent,
ForecastShortComponent,
ForecastComponent,
],
providers: [
DarkSkyHttpService,
],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ForecastComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 79b6da3823cf78404ee264e58d1b77eed6261218 | [
"Markdown",
"TypeScript"
]
| 49 | TypeScript | nodm/the-weather | c6ae9c86c2e27a1b011882db4f053ebb9efc4b53 | a1c9102362b0b3f8678558f6a63dbea4976cfd86 |
refs/heads/master | <repo_name>Platekun/bare-ui<file_sep>/src/common/custom-breakpoints.ts
import keys from './keys';
import isObject from './isObject';
import isNull from './isNull';
import EMPTY_STRING from './empty-string';
/**
* Stolen from Material UI.
*/
export const bps: Record<string, number> = {
xs: 0,
sm: 600,
md: 960,
lg: 1280,
xl: 1920,
};
type IBreakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl';
export function from(key: IBreakpoint) {
return `@media (min-width: ${bps[key]}px)`;
}
export type IResponsiveProp<TProp> =
| TProp
| Partial<{
xs: TProp;
sm: TProp;
md: TProp;
lg: TProp;
xl: TProp;
}>;
type IProp = Record<string, any>;
type ICustomStyleFunction = {
prop: string;
props: IProp;
transform: (props: any) => string;
};
function customBreakpoints(opts: ICustomStyleFunction) {
const { prop, props, transform } = opts;
const propValue = props[prop];
if (!isObject(propValue) && !isNull(propValue)) {
return transform(props);
} else if (isNull(propValue)) {
return EMPTY_STRING;
}
// Force the order the responsive values are written
const breakpointsForProp = keys({
...(propValue.xs ? { xs: propValue.xs } : {}),
...(propValue.sm ? { sm: propValue.sm } : {}),
...(propValue.md ? { md: propValue.md } : {}),
...(propValue.lg ? { lg: propValue.lg } : {}),
...(propValue.xl ? { xl: propValue.xl } : {}),
});
const responsiveStyles = breakpointsForProp.reduce((acc, breakpoint) => {
const propValueForBreakpoint = (propValue as IProp)[breakpoint];
const mediaQueryForBreakpoint = breakpoint !== 'xs' ? from(breakpoint as IBreakpoint) : undefined;
const stylesForBreakpoint = transform({
...props,
[prop]: propValueForBreakpoint,
});
if (!mediaQueryForBreakpoint) {
return `
${stylesForBreakpoint}
${acc}
`;
}
return `
${acc}
${mediaQueryForBreakpoint} {
${stylesForBreakpoint}
}
`;
}, EMPTY_STRING);
return responsiveStyles;
}
export default customBreakpoints;
export type ITransformResponsiveProps<TProps, TResponsivePropName extends string, TProp> = Omit<
TProps,
TResponsivePropName
> &
TProp;
<file_sep>/src/common/isObject.ts
function isObject<T>(o: T) {
return typeof o === 'object';
}
export default isObject;
<file_sep>/src/common/isFunction.ts
function isFunction(x: any) {
return typeof x === 'function';
}
export default isFunction;
<file_sep>/src/common/styles.ts
export type IStylable = Partial<{
/**
* Class name of the component
*/
className: string;
/**
* Inline styles of the component
*/
style: Partial<React.CSSProperties>;
}>;
<file_sep>/src/common/isString.ts
function isString(x: any) {
return typeof x === 'string';
}
export default isString;
<file_sep>/test/Storyshots.test.ts
import initStoryshots from '@storybook/addon-storyshots';
initStoryshots({
storyKindRegex: /^((?!.*?VariableFlatList).)*$/,
});
<file_sep>/src/common/orientation.ts
import { IResponsiveProp } from './custom-breakpoints';
export const HORIZONTAL = 'horizontal';
export const VERTICAL = 'vertical';
export type IOrientation = 'horizontal' | 'vertical';
export type IWithOrientation = {
/**
* Orientation of the component. Either "vertical" or "horizontal". Components are vertical by default.
*/
orientation?: IOrientation;
};
export type IWithResponsiveOrientation = {
orientation?: IResponsiveProp<IOrientation>;
};
<file_sep>/src/common/isNull.ts
function isNull<T>(o: T | null) {
return o === null;
}
export default isNull;
<file_sep>/src/common/scroll-bars.ts
import EMPTY_STRING from './empty-string';
import { IWithResponsiveOrientation, IWithOrientation, VERTICAL, HORIZONTAL } from './orientation';
import { ITransformResponsiveProps } from './custom-breakpoints';
export type IWithScrollBars = {
/**
* Wheter or not the component should render the scrollbars.
*/
noScrollBars?: boolean;
};
function noScrollBarsTransform<T extends unknown & IWithScrollBars>(props: T) {
const { noScrollBars = false } = props;
if (!noScrollBars) {
return EMPTY_STRING;
}
return `
::-webkit-scrollbar {
width: 0px;
}
`;
}
function overflowYTransform<T extends unknown & IWithResponsiveOrientation>(
props: ITransformResponsiveProps<T, 'orientation', IWithOrientation>
) {
if (props.orientation === HORIZONTAL) {
return '';
}
const overflowY = 'scroll';
return `overflow-y: ${overflowY};`;
}
function overflowXTransform<T extends unknown & IWithResponsiveOrientation>(
props: ITransformResponsiveProps<T, 'orientation', IWithOrientation>
) {
if (props.orientation === VERTICAL) {
return '';
}
const overflowY = 'scroll';
return `overflow-x: ${overflowY};`;
}
export default noScrollBarsTransform;
export { overflowYTransform, overflowXTransform };
<file_sep>/src/components/theme.ts
type IKeywordFontWeight = 'normal' | 'bold';
type IRelativeFontWeight = 'lighter' | 'bolder';
type IGlobalFontWeight = 'inherit' | 'initial' | 'unset';
type IVariableFontWeight = number;
export type ICommonFontWeight =
| 'thin'
| 'extra-light'
| 'light'
| 'normal'
| 'medium'
| 'semi-bold'
| 'bold'
| 'extra-bold'
| 'black'
| 'extra-black';
export type IFontWeight =
| IKeywordFontWeight
| IRelativeFontWeight
| IGlobalFontWeight
| IVariableFontWeight
| ICommonFontWeight;
export type ITheme = {
colors: Record<string, string>;
fontWeight?: IFontWeight;
fontSizeInPx?: number;
lineHeight?: number;
headingFontFamily?: Array<string>;
bodyFontFamily?: Array<string>;
};
<file_sep>/stories/common-theme.ts
const theme = {
colors: {
primary: '#512DA8',
secondary: '#E91E63',
success: '#4CAF50',
information: '#448AFF',
error: '#F44336',
white: 'white',
default: '#212121',
},
headingFontFamily: ['serif', 'Times new roman'],
bodyFontFamily: ['Helvetica'],
};
export default theme;
<file_sep>/src/components/index.ts
export * from './List';
export * from './Stack';
export { default as Divider } from './Divider';
export { default as Image } from './Image';
export { default as ScrollView } from './ScrollView';
export { default as Spacer } from './Spacer';
export { default as Text } from './Text';
export { default as Button } from './Button';
<file_sep>/src/common/keys.ts
function keys(o?: object | null) {
if (typeof o === 'undefined' || o === null) {
return [];
}
return Object.keys(o);
}
export default keys;
<file_sep>/src/components/Stack/index.ts
export { default as HStack } from './HStack';
export { default as Stack } from './Stack';
export { default as VStack } from './VStack';
<file_sep>/src/components/List/common.ts
import React from 'react';
import { css } from 'styled-components';
import { stackCSS, IStackProps } from '../Stack/Stack';
import { IWithResponsiveOrientation } from '../../common/orientation';
type Key = string;
export type IWithKey = { key: string };
export type IUnknownWithKey = unknown & IWithKey;
export type IMapCallbackFunction<TDataListItemType> = (
item: TDataListItemType,
index: number,
data: Array<TDataListItemType>
) => React.ReactElement;
export type IKeyExtractorFunction<TDataListItemType> = (
item: TDataListItemType,
index: number,
data: Array<TDataListItemType>
) => Key;
export type ICommonFlatListProps<TDataListItemType, TListType> = {
/**
* For simplicity, data is a plain array.
*/
data: Array<TDataListItemType>;
/**
* Takes an item from data and renders it into the list.
*/
renderItem: IMapCallbackFunction<TDataListItemType>;
/**
* Props of the list item container
*/
listItemProps?: React.HTMLAttributes<HTMLLIElement> & IStackProps;
/**
* Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks item.key, then falls back to using an uuid.
*/
keyExtractor?: IKeyExtractorFunction<TDataListItemType>;
/**
* Used to extract a unique test id for a given item at the specified index. The test id is used for identifying an item during a UI test.
*/
testIdExtractor?: IKeyExtractorFunction<TDataListItemType>;
} & IWithResponsiveOrientation &
Omit<TListType, 'children' | 'itemCount' | 'layout'> &
IStackProps;
export const stackListCSS = css`
${stackCSS};
list-style-type: none;
padding-left: 0;
margin: 0;
`;
export const DEFAULT_LIST_ITEM_ELEMENT = 'li';
export const DEFAULT_LIST_ELEMENT = 'ul';
<file_sep>/src/components/List/index.ts
export { default as FlatList } from './FlatList';
export { default as List } from './List';
export { default as VariableFlatList } from './VariableFlatList';
<file_sep>/README.md
# Bare UI
Bare UI is a set of basic React components. By "basic" I mean they are just components with an opinionated API that you can use to built your own abstractions.
## Who is this library for
This library is for people who just want basic abstractions without the hassle of rewriting them everytime from scrath for every new React project.
I tried keeping away from design choises since I'm no designer. Sometimes I just wanna make my UIs look OK so that's why I took looked up some sane default choices for the `Text` and `Button` component.
## Collection
The complete list of components is the following:
- Text: A React component for displaying text. Should be used with a theme object.
- Button: A React component to create basic buttons. Should be used with a theme object.
- Divider: A React component that serves as a thin line that separates groups content in lists and layouts. It replaces the horizontal rule tag.
- Image: A React component for displaying different types of images. It replaces the image tag and supports: "Fallingback to alternate sources when loading an image fails", "Using text or a component placeholder", "Image captioning" and "Making `alt` required".
- ScrollView: A React component that allows the view hierarchy placed within it to be scrolled.
- Spacer: A React component that represents a flexible space that expands vertically or horizontally.
- List: A React component for rendering a basic list of content. No optimizations, only defaults. It replaces the unordered list tag.
- FlatList: A React component for performant rendering for list of content (Flat lists). It replaces the unordered list tag.
- FlatList (with variable items): A React component for performant rendering for list of content (Flat lists). It replaces the unordered list tag.
- Stack: A React component that arranges its children in a vertical or horizontal line.
The listed components are thought to be flexible enough to many of my day-to-day use cases. I recommend checking out the storybook of the project since there are a lot of ways to use them.
Storybook: [https://Platekun.github.io/bare-ui/](https://Platekun.github.io/bare-ui/)
## Inspiration and Thanks!
This library is based on Swift UI and React Native.
<file_sep>/src/common/join-strings.ts
function joinStrings(arr: Array<string>) {
return arr.join(', ');
}
export default joinStrings;
| 04b2ab0a0aba3598d57bd5f81d2e2a604f702ae5 | [
"Markdown",
"TypeScript"
]
| 18 | TypeScript | Platekun/bare-ui | 0e412dc917159f5f60bbcdeb32ec1c80f7e139b2 | 902c6c000934602ee6ef3230f062b9af21a5a035 |
refs/heads/master | <file_sep>#!/usr/bin/python
import threading, time, urllib
from gps import *
import settings
# Based on example from Stack Overflow answer: <http://stackoverflow.com/questions/6146131/python-gps-module-reading-latest-gps-data>
class GpsPoller(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.session = gps(mode=WATCH_ENABLE)
self.current_value = None
def get_current_value(self):
return self.current_value
def run(self):
try:
while True:
data = self.session.next()
if data['class'] == u'TPV' and 'lat' in data.keys():
self.current_value = data
except StopIteration:
pass
if __name__ == '__main__':
gpsp = GpsPoller()
gpsp.daemon = True # <http://stackoverflow.com/questions/1635080/terminate-a-multi-thread-python-program>
gpsp.start()
no_data = 0
while 1:
data = gpsp.get_current_value()
if data:
epoch = time.time()
print('%s: [%s,%s]' % (epoch, data.lat, data.lon,))
urllib.urlopen(settings.url, 'lat=%s&lon=%s&epoch=%s' % (data.lat, data.lon, time.time(),))
else:
if no_data > 4:
print('It seems like there will never be any data. Check that all hardware works as expected and/or try restarting the script.')
break
no_data += 1
print('No data yet')
time.sleep(settings.interval)
<file_sep>raspberry-pi-gps-tracker
========================
Some scripts turning the Raspberry Pi into a GPS tracker.
My hardware used for this project is:
* A Raspberry Pi (model B).
* A Bluetooth dongle.
* A Holux M-1200 Bluetooth GPS.
This could probably be used with other hardware as well.
gpst.py is a simple script checking GPS device for location and reporting that location to a website once in a while.
Copy settings-example.py to settings.py and tune it to your needs.
If you want to use this on the go, I'd recommend using a 3G-modem and the excellent Sakis3G script to connect to the internet: <http://www.sakis3g.org/>.
<file_sep>#!/usr/bin/python
# This file contains the settings for the GSP tracker. Tweak as you like.
# The URL to HTTP POST lat/lon to
url = 'http://your.site/some-tracking-page/'
# How often to post lat/lon (in seconds)
interval = 5
<file_sep>#!/bin/bash
# This is a script I use when there seems to be a problem with the GPS.
# I Don't know if all of it is necessary, but it works (most of the
# time).
#
# I'm using a Bluetooth rfcomm configuration similar to the one found
# at: <http://www.catb.org/gpsd/bt.html>
echo "******************************************************"
echo """
Procedure:
* Remove BT dongle form Pi
* Turn on Pi
* Turn on GPS
* Plug in BT dongle
* Make sure it's working (blue light blinking)
* Run this script
"""
echo "******************************************************"
sudo service bluetooth restart
sleep 5
sudo rfcomm release /dev/rfcomm0
sleep 1
sudo rfcomm bind rfcomm0
sleep 5
sudo service gpsd restart
sleep 5
echo "******************************************************"
echo " Should be ready now. Try running one of the scripts. "
echo "******************************************************"
| b2ccd2b0b1efaa249da744b400218af8e984746d | [
"Markdown",
"Python",
"Shell"
]
| 4 | Python | gucio1200/raspberry-pi-gps-tracker | fde3c0507afd2272d17785e89cd7b22ff4ad48b9 | c94d25fcd1896951c48f3676629eda33cbb96c41 |
refs/heads/master | <file_sep>var express = require('express');
var router = express.Router();
var http = require('http');
router.get("/", function (req, res, next) {
console.log("I think it's index");
res.render('index', {
Header: "Welcome to the Star Wars Index!"
});
});
module.exports = router;<file_sep>var express = require('express');
var router = express.Router();
var http = require('http');
router.get("/", function (req, res, next) {
console.log("I think it's your planets page");
var options = {
host: 'www.swapi.co',
path: '/api/planets/'
};
callback = function(response) {
var data = '';
//build data object
response.on('data', function (chunk) {
data += chunk;
});
//Build and render data
response.on('end', function () {
data = JSON.parse(data);
console.log(data.results);
res.render('planets', {
obj: data.results,
header: "Star Wars Planets Index"
});
});
}
http.request(options, callback).end();
});
module.exports = router;<file_sep>// MODULES
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var path = require('path');
var serveStatic = require('serve-static');
// Set Routes
var routes = require('./routes/index');
var characters = require('./routes/characters');
var planets = require('./routes/planets');
var films = require('./routes/films');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var jsonParser = bodyParser.json();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// Apply Routes
app.use(express.static('views'));
app.use('/', routes);
app.use('/characters', characters);
app.use('/planets', planets);
app.use('/films', films);
app.listen(port, function () {
console.log('Example app listening on port' + port + '!')
})
<file_sep>var express = require('express');
var router = express.Router();
var http = require('http');
router.get("/", function (req, res, next) {
console.log("I think it's your charachters page");
var options = {
host: 'www.swapi.co',
path: '/api/people/'
};
callback = function(response) {
var data = '';
//build data object
response.on('data', function (chunk) {
data += chunk;
});
//Build and render data
response.on('end', function () {
data = JSON.parse(data);
//console.log(data.results);
res.render('characters', {
obj: data.results,
header: "Star Wars Character Index"
});
});
}
http.request(options, callback).end();
var options2 = {
host: 'www.swapi.co',
path: '/api/films/'
};
callback2 = function(response) {
var data = '';
//append data
response.on('data', function (chunk) {
data += chunk;
});
//Still need to figure out how to make two calls on a page
response.on('end', function () {
data = JSON.parse(data);
//console.log(data);
// res.render('characters', {
// filmObj: data.results,
// header: "Star Wars Character Index"
// });
});
}
var getFilms = function (){
http.request(options2, callback2).end();
}
getFilms();
});
module.exports = router; | 56bc8ee600eabac9d6ad9bbb98650a8704405e5a | [
"JavaScript"
]
| 4 | JavaScript | JustinianH/star-wars-api-app | b74f8d4c754437133b75eaf699ce0f2009569a8c | 65a4baf28fb2e096cdfdd113ea964efcced0f899 |
refs/heads/master | <repo_name>codingteam/naggum<file_sep>/docs/about.rst
About
=====
Disclaimer
----------
Naggum doesn't aim to be yet another Common Lisp or Scheme or whatever
implementation. Instead, we are trying to deliver a modern Lisp dialect that
makes use of most of CLI benefits.
Features
--------
Naggum provides both direct access to low-level features of CLI, and allows its
user to define types and functions just like any other high-level language. At
the same time, it combines power of Lisp-inspired metaprogramming (macros) with
strictness of strong-typed language.
Contribute
----------
- Source Code: https://github.com/codingteam/naggum
- Issue Tracker: https://github.com/codingteam/naggum/issues
License
-------
Naggum is licensed under the terms of MIT License. See `License.md`_ for
details.
.. _License.md: https://github.com/codingteam/naggum/blob/develop/License.md
<file_sep>/Naggum.Interactive/Program.cs
using System;
using System.IO;
using Naggum.Runtime;
namespace Naggum.Interactive
{
class Program
{
static void Main(string[] args)
{
Stream input = System.Console.OpenStandardInput();
for (; ; )
{
System.Console.Out.Write(">");
Object obj = Reader.Read(input);
System.Console.Out.WriteLine(obj.ToString());
}
input.Close();
}
}
}
<file_sep>/docs/usage.rst
Naggum usage
============
Currently there are two dialects of Naggum: high-level *Compiler* and low-level
*Assembler*.
Naggum Compiler
---------------
Command line syntax for Naggum Compiler is::
$ Naggum.Compiler source.naggum... [/r:assembly]...
Each input source file will be compiled to a separate executable assembly (i.e.
an ``.exe`` file) in the current directory. You can also pass a list of files to
be referenced by these assemblies.
``.naggum`` extension is recommended for high-level Naggum files.
Naggum Assembler
----------------
Naggum Assembler uses low-level Naggum dialect. Command line syntax is::
$ Naggum.Assembler source.nga...
Each input file may contain zero or more assembly constructs. Every assembly
will be saved to its own executable file in the current directory.
``.nga`` extension is recommended for low-level Naggum files.
S-expression syntax
-------------------
Each Naggum program (either high-level or low-level) is written as a sequence of
S-expression forms. In s-expression, everything is either an atom or a list.
Atoms are written as-is, lists should be taken into parens.
Possible atom values are::
"A string"
1.4e-5 ; a number
System.Console ; a symbol
A symbol is a sequence of letters, digits, and any of the following characters:
``+-*/=<>!?.``.
Lists are simply sequences of s-expressions in parens::
(this is a list)
(this (is ("Also") a.list))
Naggum source code may also include comments. Everything after ``;`` character
will be ignored till the end of the line::
(valid atom) ; this is a comment
Low-level syntax
----------------
Naggum low-level syntax is closer to `CIL`_. It may be used to define CLI
constructs such as assemblies, modules, types and methods. Every ``.nga`` file
may contain zero or more assembly definitions.
Assembly definition
^^^^^^^^^^^^^^^^^^^
Assembly defitinion should have the following form::
(.assembly Name
Item1
Item2
...)
Assembly items can be methods and types. Top level methods defined in an
``.assembly`` form will be compiled to global CIL functions.
Type definitions are not supported yet.
Each assembly may contain one entry point method (either a static type method or
an assembly global function marked by ``.entrypoint`` property).
Method definition
^^^^^^^^^^^^^^^^^
Method definition should have the following form::
(.method Name (argument types) return-type (metadata items)
body-statements
...)
Method argument and return types should be fully-qualified (e.g. must include a
namespace: for example, ``System.Void``).
The only supported metadata item is ``.entrypoint``. It marks a method as an
assembly entry point.
Method example::
(.method Main () System.Void (.entrypoint)
(ldstr "Hello, world!")
(call (mscorlib System.Console WriteLine (System.String) System.Void))
(ret))
Method body should be a CIL instruction sequence.
CIL instructions
^^^^^^^^^^^^^^^^
Currently only a small subset of all available CIL instructions is supported by
Naggum. This set will be extended in future.
#. Call instruction::
(call (assembly type-name method-name (argument types) return-type))
Currently assembly name is ignored; only ``mscorlib`` methods can be called.
Static assembly function calls are not supported yet.
Method argument and return types should be fully-qualified.
#. Load string instruction::
(ldstr "Hello, world")
Loads a string onto a CLI stack.
#. Return instruction::
(ret)
Return from current method.
Example assembly definition
^^^^^^^^^^^^^^^^^^^^^^^^^^^
::
(.assembly Hello
(.method Main () System.Void (.entrypoint)
(ldstr "Hello, world!")
(call (mscorlib System.Console WriteLine (System.String) System.Void))
(ret)))
High-level syntax
-----------------
Every high-level Naggum program is a sequence of function definitions and a
top-level executable statements. Functions defined in an assembly are also
available as public static methods to be called by external assemblies.
Functions are defined using ``defun`` special form::
(defun function-name (arg1 arg2)
statement1
statement2)
For example::
(defun println (arg)
(System.Console.WriteLine arg))
Naggum is a Lisp-2, henceforth a function and a variable can share their names.
Currently executable statements may be one of the following.
#. Let bindings::
(let ((variable-name expression)
(variable-name-2 expression-2))
body
statements)
Creates a lexical scope, evaluates initial values, binds them to corresponding
names and evaluates the body, returning the value of last expression.
Naggum's ``let`` is a loner: every one is inherently iterative (like ``let*``)
and recursive (like `let rec`).
#. Arithmetic statements::
(+ 2 2)
#. Function calls::
(defun func () (+ 2 2))
(func)
#. Static CLI method calls::
(System.Console.WriteLine "Math:")
#. Conditional statements::
(if condition
true-statement
false-statement)
If the ``condition`` is true (as in "not null, not zero, not false") it
evaluates the ``true-statement`` form and returns its result. If the
``condition`` evaluates to false, null or zero, then the ``false-statement``
form is evaluated and its result is returned from ``if``.
#. Reduced if statements::
(if condition
true-statement)
#. Constructor calls::
(new Naggum.Runtime.Cons "OK" "FAILURE")
Calls an applicable constructor of a type named `Naggum.Runtime.Cons` with the
given arguments and returns an object created.
.. _CIL: https://en.wikipedia.org/wiki/Common_Intermediate_Language
<file_sep>/Naggum.Runtime/Properties/AssemblyInfo.cs
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Naggum.Runtime")]
[assembly: AssemblyProduct("Naggum")]
[assembly: AssemblyCopyright("Copyright © Naggum authors 2011–2016")]
[assembly: ComVisible(false)]
[assembly: Guid("4d6a7899-d5cd-4df7-8bab-dbc94b258e57")]
[assembly: AssemblyVersion("0.0.1.0")]
<file_sep>/Readme.md
Naggum [![Status Enfer][status-enfer]][andivionian-status-classifier] [![Build status][build-status-appveyor]][appveyor] [![Build Status][build-status-travis]][travis]
======
Naggum (named in honor of [<NAME>][eric-naggum]) /(is|will be)/ a Lisp
dialect based on Common Language Infrastructure (aka .NET Framework / Mono).
## Disclaimer
Naggum does not aim to be yet another Common Lisp or Scheme or Emacs Lisp or
whatever implementation. Instead, we are trying to deliver a modern Lisp dialect
that makes use of most of .Net's benefits.
## Documentation
The documentation is available on [ReadTheDocs][read-the-docs].
## License
Naggum is licensed under the terms of MIT License. See License.md file for
details.
[andivionian-status-classifier]: https://github.com/ForNeVeR/andivionian-status-classifier
[appveyor]: https://ci.appveyor.com/project/ForNeVeR/naggum/branch/develop
[eric-naggum]: https://en.wikipedia.org/wiki/Erik_Naggum
[read-the-docs]: http://naggum.readthedocs.org/
[travis]: https://travis-ci.org/codingteam/naggum
[build-status-appveyor]: https://ci.appveyor.com/api/projects/status/ulgo3ry7eudc5d7a/branch/develop?svg=true
[build-status-travis]: https://travis-ci.org/codingteam/naggum.svg?branch=develop
[status-enfer]: https://img.shields.io/badge/status-enfer-orange.svg
<file_sep>/docs/specification.rst
Naggum Specification
====================
Features
--------
- based on CLR;
- Lisp-2;
- compiles to CIL assemblies;
- is not a Common Lisp implementation;
- seamlessly interoperates with other CLR code.
Language
--------
Special forms
~~~~~~~~~~~~~
1. ``(let (bindings*) body*)`` where ``bindings`` follow a pattern of
``(name initial-value)`` creates a lexical scope, evaluates initial
values, binds them to corresponding names and evaluates the body,
returning the value of last expression. Naggum’s ``let`` is a loner:
every one is inherently iterative (like ``let*``) and recursive
(like ``let rec``).
2. ``(defun name (parms*) body*)`` defines a function (internally it
will be a public static method). Naggum is a Lisp-2, henceforth a
function and a variable can share their names.
3. ``(if condition if-true [if-false])`` evaluates given ``condition``.
If it is true (as in “not null, not zero, not false”) it evaluates
``if-true`` form and returns it’s result. If ``condition`` evaluates
to false, null or zero then ``if-false`` form (if given) is
evaluated and it’s result (or null, if no ``if-false`` form is
given) is returned from ``if``.
4. ``(fun-name args*)`` applies function named ``fun-name`` to given
arguments.
5. ``(new type-name args*)`` calls applicable constructor of type named
``type-name`` with given arguments and returns created object.
``(new (type-name generic-args*) args*)`` ``new`` form calls
applicable constructor of generic type named ``type-name``, assuming
generic parameters in ``generic-args`` and with given arguments and
returns created object.
6. ``(call method-name object-var args*)`` Performs virtual call of
method named ``method-name`` on object referenced by ``object-var``
with given arguments.
7. ``(lambda (parms*) body*)`` Constructs anonymous function with
``parms`` as parameters and ``body`` as body and returns it as a
result.
8. ``(eval form [environment])`` evaluates form using supplied lexical
environment. If no environment is given, uses current one.
9. ``(error error-type args*)`` throws an exception of ``error-type``,
constructed with ``args``.
10. ``(try form (catch-forms*))`` where ``catch-forms`` follow a pattern
of ``(error-type handle-form)`` tries to evaluate ``form``. If any
error is encountered, evaluates ``handle-form`` with the most
appropriate ``error-type``.
11. ``(defmacro name (args*))`` defines a macro that will be expanded at
compile time.
12. ``(require namespaces*)`` states that ``namespaces`` should be used
to search for symbols.
13. ``(cond (cond-clauses*))`` where ``cond-clauses`` follow a pattern
of ``(condition form)`` sequentially evaluates conditions, until one
of them is evaluated to ``true``, non-null or non-zero value, then
the corresponding ``form`` is evaluated and it’s result returned.
14. ``(set var value)`` sets the value of ``var`` to ``value``. ``var``
can be a local variable, function parameter or a field of some
object.
Quoting
~~~~~~~
1. ``(quote form)`` indicates simple quoting. ``form`` is returned
as-is.
2. ``(quasi-quote form)`` returns ``form`` with ``unquote`` and
``splice-unquote`` expressions inside evaluated and substituted with
their results accordingly
3. ``(unquote form)`` if encountered in ``quasi-quote`` form, will be
substituted by a result of ``form`` evaluation
4. ``(splice-unquote form)`` same as ``unquote``, but if ``form``
evaluation result is a list, then it’s elements will be spliced as an
elements of the containing ``list``.
Type declaration forms
~~~~~~~~~~~~~~~~~~~~~~
- ``(deftype type-name ([parent-types*]) members*)`` Defines CLR type,
inheriting from ``parent-types`` with defined members.
- ``(deftype (type-name generic-parms*) ([parent-types*]) members*)``
Defines generic CLR type, polymorphic by ``generic-parms``,
inheriting from ``parent-types`` with defined members.
- ``(definterface type-name ([parent-types*]) members*)`` Defines CLR
interface type, inheriting from ``parent-types`` with defined
members.
- ``(definterface (type-name generic-parms*) ([parent-types*]) members*)``
Defines generic CLR interface type, polymorphic by ``generic-parms``,
inheriting from ``parent-types`` with defined members.
If no ``parent-types`` is supplied, ``System.Object`` is assumed.
Member declaration forms
~~~~~~~~~~~~~~~~~~~~~~~~
- ``(field [access-type] field-name)`` declares a field with name given
by ``field-name`` and access permissions defined by ``access-type``.
- ``(method [access-type] method-name (parms*) body*)`` declares an
instance method. Otherwise identical to ``defun``.
Available values for ``access-type`` are ``public``\ (available to
everybody), ``internal``\ (available to types that inherit from this
type) and ``private``\ (available only to methods in this type). If no
``access-type`` is given, ``private`` is assumed.
Standard library
----------------
Naggum is designed to use CLR standard libraries, but some types and
routines are provided to facilitate lisp-style programming.
Cons
~~~~
Cons-cell is the most basic building block of complex data structures.
It contains exactly two objects of any types, referenced as *CAR* (left
part, head) and *CDR* (right part, tail)
Symbol
~~~~~~
Symbol is a type that represents language primitives like variable,
function and type names.
Naggum Reader
~~~~~~~~~~~~~
Reader reads Lisp objects from any input stream, returning them as lists
and atoms.
Naggum Writer
~~~~~~~~~~~~~
Writer writes Lisp objects to any output stream, performing output
formatting if needed.
<file_sep>/Naggum.Runtime/Reader.cs
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Naggum.Runtime
{
public class Reader
{
/// <summary>
/// Checks if the character is constituent, i.e. not whitespace or list separator.
/// </summary>
/// <param name="c">character to be checked</param>
/// <returns>true if the character is constituent, false otherwise</returns>
public static bool isConstituent(char c)
{
return (!Char.IsWhiteSpace(c))
&& c != '('
&& c != ')';
}
/// <summary>
/// Reads a symbol from a stream.
/// </summary>
/// <param name="stream">stream to read from</param>
/// <returns></returns>
private static Object ReadSymbol(StreamReader reader)
{
bool in_symbol = true;
StringBuilder symbol_name = new StringBuilder();
while (in_symbol)
{
var ch = reader.Peek();
if (ch < 0) throw new IOException("Unexpected end of stream.");
if (isConstituent((char)ch))
{
symbol_name.Append((char)reader.Read());
}
else
{
in_symbol = false;
}
}
if (symbol_name.Length > 0)
return new Symbol(symbol_name.ToString());
else
throw new IOException("Empty symbol.");
}
/// <summary>
/// Reads a list from input stream.
/// </summary>
/// <param name="stream">stream to read from</param>
/// <returns></returns>
private static Object ReadList(StreamReader reader)
{
bool in_list = true;
Stack<Object> list_stack = new Stack<object>();
Cons list = null;
while (in_list)
{
var ch = reader.Peek();
if (ch < 0) throw new IOException("Unexpected end of stream.");
if ((char)ch != ')')
{
list_stack.Push(ReadObject(reader));
}
else
{
reader.Read(); //consume closing paren
in_list = false;
}
}
while (list_stack.Count > 0) list = new Cons(list_stack.Pop(), list);
return list;
}
/// <summary>
/// Reads a string from input stream
/// </summary>
/// <param name="stream">input stream</param>
/// <returns>a string that was read</returns>
private static string ReadString(StreamReader reader)
{
bool in_string = true;
bool single_escape = false;
StringBuilder sbld = new StringBuilder();
while (in_string)
{
var ch = reader.Read();
if (single_escape)
{
single_escape = false;
switch (ch)
{
case 'n': sbld.Append('\n'); break;
case 'r': sbld.Append('\r'); break;
case '\"': sbld.Append('"'); break;
case 't': sbld.Append('\t'); break;
case '\\': sbld.Append('\\'); break;
default: throw new Exception("Unknown escape sequence: \\" + ch);
}
}
else
{
switch (ch)
{
case '\"': in_string = false; break;
case '\\': single_escape = true; break;
default: sbld.Append((char)ch); break;
}
}
}
return sbld.ToString();
}
private static Object ReadObject(StreamReader reader)
{
while (Char.IsWhiteSpace((char)reader.Peek())) reader.Read(); //consume all leading whitespace
var ch = reader.Peek();
if (ch < 0) return null;
if (ch == '(') //beginning of a list
{
reader.Read(); //consume opening list delimiter.
return ReadList(reader);
}
if (ch == '\"') //beginning of a string
{
reader.Read(); //consume opening quote
return ReadString(reader);
}
if (isConstituent((char)ch))
return ReadSymbol(reader);
throw new IOException("Unexpected char: " + (char)ch);
}
/// <summary>
/// Reads an object from input stream.
/// </summary>
/// <param name="stream">stream to read from</param>
/// <returns></returns>
public static Object Read(Stream stream)
{
StreamReader reader = new StreamReader(stream);
var obj = ReadObject(reader);
return obj;
}
}
}
<file_sep>/docs/index.rst
Naggum documentation
====================
.. toctree::
:maxdepth: 2
about
build-guide
usage
specification
Naggum (named in honor of `<NAME>`_) is a modern statically typed Lisp
variant that is targeting `Common Language Infrastructure`_ (CLI) runtime
system.
.. _Common Language Infrastructure: http://www.ecma-international.org/publications/standards/Ecma-335.htm
.. _<NAME>: https://en.wikipedia.org/wiki/Erik_Naggum
<file_sep>/Naggum.Runtime/Symbol.cs
using System;
namespace Naggum.Runtime
{
public class Symbol : IEquatable<Symbol>
{
public String Name { get; set; }
/// <summary>
/// Constructs new symbol object.
/// </summary>
/// <param name="aName">Symbol name</param>
public Symbol(String aName)
{
Name = aName;
}
bool IEquatable<Symbol>.Equals(Symbol other)
{
return AreEqual(this, other);
}
public override bool Equals(object obj)
{
var symbol = obj as Symbol;
if (symbol != null)
{
return AreEqual(this, symbol);
}
return false;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
/// <summary>
/// </summary>
/// <returns>Returns symbol's name as string.</returns>
public override string ToString()
{
return Name;
}
private static bool AreEqual(Symbol one, Symbol other)
{
return one.Name.Equals(other.Name);
}
}
}
<file_sep>/docs/build-guide.rst
Build guide
===========
To use Naggum, first of all you need to build it from source.
Windows
-------
To build Naggum on Windows, just use Visual Studio or MSBuild like that::
$ cd naggum
$ nuget restore
$ msbuild /p:Configuration=Release Naggum.sln
Linux
-----
See general build instructions for Linux in the file ``.travis.yml`` inside the
Naggum source directory.
You'll need `Mono`_, `NuGet`_ and `F# Compiler`_ installed. Some of them may or
may not be part of your Mono installation; just make sure you've got them all.
Please note that currently the project is compatible with Mono 4.4.2+.
Below is an example of setting up these tools on `NixOS Linux`_; feel free to
add instructions for any other distributions.
NixOS Linux
^^^^^^^^^^^
*The instructions have been verified on NixOS 16.03. If something doesn't work, please file an issue.*
Enter the development environment::
$ cd naggum
$ nix-shell
After that you can download the dependencies and build the project using
``xbuild``::
$ nuget restore
$ xbuild /p:Configuration=Release /p:TargetFrameworkVersion="v4.5"
After that, you can run ``Naggum.Compiler``, for example::
$ cd Naggum.Compiler/bin/Release/
$ mono Naggum.Compiler.exe ../../../tests/test.naggum
$ mono test.exe
Documentation
-------------
You can build a local copy of Naggum documentation. To do that, install
`Python`_ 2.7 and `Sphinx`_. Ensure that you have ``sphinx-build`` binary in
your ``PATH`` or define ``SPHINXBUILD`` environment variable to choose an
alternative Sphinx builder. After that go to `docs` directory and execute ``make
html`` (on Linux) or ``.\make.bat html`` (on Windows).
.. _F# Compiler: http://fsharp.org/
.. _Mono: http://www.mono-project.com/
.. _NixOS Linux: http://nixos.org/
.. _NuGet: http://www.nuget.org/
.. _Python: https://www.python.org/
.. _Sphinx: http://sphinx-doc.org/
<file_sep>/Naggum.Interactive/Properties/AssemblyInfo.cs
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Naggum.Interactive")]
[assembly: AssemblyProduct("Naggum")]
[assembly: AssemblyCopyright("Copyright © Naggum authors 2013–2016")]
[assembly: ComVisible(false)]
[assembly: Guid("fe6d0e11-90e5-4715-9a40-878ecf803b52")]
[assembly: AssemblyVersion("0.0.1.0")]
<file_sep>/Naggum.Runtime/Cons.cs
using System;
using System.Text;
using System.Collections;
namespace Naggum.Runtime
{
/// <summary>
/// Cons-cell and basic cons manipulation functions.
/// </summary>
public class Cons : IEquatable<Cons>
{
public Object pCar { get; set; }
public Object pCdr { get; set; }
/// <summary>
/// The real cons-cell constructor.
/// </summary>
/// <param name="aCar">CAR part of the new cell</param>
/// <param name="aCdr">CDR part of the new cell </param>
public Cons(Object aCar, Object aCdr)
{
pCar = aCar;
pCdr = aCdr;
}
/// <summary>
/// </summary>
/// <param name="aCons">Cons-cell</param>
/// <returns>CAR part of given cell</returns>
public static Object Car(Cons aCons)
{
return aCons.pCar;
}
/// <summary>
/// </summary>
/// <param name="aCons">Cons-cell</param>
/// <returns>CDR part of given cell</returns>
public static Object Cdr(Cons aCons)
{
return aCons.pCdr;
}
/// <summary>
/// Checks if the cons-cell is a list
/// </summary>
/// <param name="aCons">Cons-cell</param>
/// <returns>True if CDR part of the cell is a list or is null.
/// False otherwise.</returns>
public static bool IsList(Cons aCons)
{
if (aCons == null) return true; //Empty list is still a list.
if (aCons.pCdr == null) return true; //List with one element is a list;
else if (aCons.pCdr.GetType() == typeof(Cons)) return IsList((Cons)aCons.pCdr);
else return false; //If it's not null or not a list head, then it's definitely not a list.
}
/// <summary>
/// Converts cons-cell to string representation.
/// </summary>
/// <returns>String representation of cons-cell.</returns>
public override String ToString()
{
StringBuilder buffer = new StringBuilder("");
buffer.Append("(");
if (IsList(this))
{
for (Cons it = this; it != null; it = (Cons)it.pCdr)
{
buffer.Append(it.pCar.ToString());
if (it.pCdr != null) buffer.Append(" ");
}
}
else
{
buffer.Append(pCar.ToString()).Append(" . ").Append(pCdr.ToString());
}
buffer.Append(")");
return buffer.ToString();
}
/// <summary>
/// Checks cons cell for equality with other cell.
/// </summary>
/// <param name="other">Other cons cell</param>
/// <returns>True if other cell is equal to this; false otherwise.</returns>
bool IEquatable<Cons>.Equals(Cons other)
{
return pCar == other.pCar && pCdr == other.pCdr;
}
/// <summary>
/// Constructs a list.
/// </summary>
/// <param name="elements">Elements of a list.</param>
/// <returns>List with given elements.</returns>
public static Cons List(params object[] elements)
{
Cons list = null;
Array.Reverse(elements);
foreach (var element in elements)
{
var tmp = new Cons(element, list);
list = tmp;
}
return list;
}
}
}
| 6d2e8f0c90400b5587e6117a6ca3e364ec6b5b7b | [
"Markdown",
"C#",
"reStructuredText"
]
| 12 | reStructuredText | codingteam/naggum | f63f71ffb0d57cd5b56e5954f584b591f8abe411 | 7e3079eb7795dbdda3a71ca0c178cb402df81354 |
refs/heads/master | <file_sep>import React, { Component } from "react";
import { NavLink } from "react-router-dom";
class PostListItem extends Component {
constructor(props) {
super(props);
this.onShowPost = this.onShowPost.bind(this);
}
onShowPost() {
window.location.pathname = `/posts/${this.props.post._id}`;
}
renderTags(tags) {
return tags.map(tag => (
<span style={{ "margin-right": "10px" }} className="tag-span">
{tag}
</span>
));
}
state = {};
render() {
const { post } = this.props;
return (
<React.Fragment key={post._id}>
<div className="cards-wrapper">
<div className="card-grid-space">
<a
className="card"
style={{ backgroundImage: "url(./images/javascript.jpg)" }}
>
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
<NavLink to="/post">
<button onClick={this.onShowPost}>Show</button>
</NavLink>
<div className="tags">
<div className="tag">{this.renderTags(post.tags)}</div>
</div>
</div>
</a>
</div>
</div>
</React.Fragment>
);
}
}
export default PostListItem;
<file_sep>import React, { Component } from "react";
import {
BrowserRouter as Router,
Route,
Switch,
Redirect
} from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import Register from "./Register";
import Login from "./Login";
import Navbar from "./navbar";
import Home from "./Home";
import Profile from "./Profile";
import Article from "./Article";
import AddBlog from "./Addblog";
import Post from "./Post";
import LandingPage from "./LandingPage";
class App extends Component {
render() {
return (
<React.Fragment>
<Router>
<Navbar />
<Switch>
<Route path="/addBlog" component={AddBlog}></Route>
<Route path="/article" component={Article}></Route>
<Route path="/profile" component={Profile}></Route>
<Route path="/register" component={Register}></Route>
<Route path="/login" component={Login}></Route>
<Route path="/posts/:id" component={Post} Redirect={Home}></Route>
<Route path="/posts" component={Home}></Route>
<Route path="/" component={LandingPage}></Route>
</Switch>
</Router>
</React.Fragment>
);
}
}
export default App;
<file_sep>import React, { Component } from "react";
import { NavLink } from "react-router-dom";
const Profile = () => {
return (
<React.Fragment>
<div className="author-card card">
<div className="image-container">
<img
className="author-img"
src={require("./images/Mariam_Hasan.jpg")}
></img>
</div>
<span> <NAME></span>
<span>
<a>Follow</a>
</span>
<p>11 Followers</p>
<p>20 Following</p>
</div>
<div className="card">
<div className="img-container">
<img
src={require("./images/javascript.jpg")}
alt="Avatar"
style={{ width: "100%" }}
/>
</div>
<div className="article-author-container">
<div className="article-container">
<h4>
<NavLink className="nav-link" to="/article">
<h3 style={{ color: "black" }}>Article Title</h3>
</NavLink>
</h4>
<p className="article-desc">
Article description
hfewgfhsweedhdjejefwnijefjfjfbhrnbghfgrhrfbhgbrffghrgb
</p>
</div>
<div className="author-Container">
<div className="image-container">
<img
className="author-img"
src={require("./images/Mariam_Hasan.jpg")}
></img>
</div>
<div className="author-data">
<div className="author-name" style={{ color: "black" }}>
Author Name
</div>
</div>
{/* <time className="article-desc"> June 9,2019</time> */}
</div>
</div>
</div>
<div className="card">
<div className="img-container">
<img
src={require("./images/javascript.jpg")}
alt="Avatar"
style={{ width: "100%" }}
/>
</div>
<div className="article-author-container">
<div className="article-container">
<h4>
<NavLink className="nav-link" to="/profile">
<h3 style={{ color: "black" }}>Article Title</h3>
</NavLink>
</h4>
<p className="article-desc">
Article description
hfewgfhsweedhdjejefwnijefjfjfbhrnbghfgrhrfbhgbrffghrgb
</p>
</div>
<div className="author-Container">
<div className="image-container">
<img
className="author-img"
src={require("./images/Mariam_Hasan.jpg")}
></img>
</div>
<div className="author-data">
<div className="author-name" style={{ color: "black" }}>
Author Name
</div>
</div>
</div>
</div>
</div>
</React.Fragment>
);
};
export default Profile;
<file_sep>import React from "react";
import { NavLink } from "react-router-dom";
import { useForm } from "react-hook-form";
import "./styles.css";
const Login = () => {
const { register, handleSubmit, errors } = useForm();
const onSubmit = data => {
// alert(JSON.stringify(data));
console.log(data);
};
return (
<React.Fragment>
<form
className="col-md-4 col-md-offset-4 container"
onSubmit={handleSubmit(onSubmit)}
>
<div className="form-group">
<label htmlFor="exampleInputEmail1">Email address</label>
<input
type="email"
className="form-control"
id="exampleInputEmail1"
aria-describedby="emailHelp"
placeholder="Enter email"
name="email"
ref={register({
required: "Email is required",
pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
})}
/>
{errors.email && (
<p style={{ color: "red" }}>{errors.email.message}</p>
)}
</div>
<div className="form-group">
<label htmlFor="exampleInputPassword1">Password</label>
<input
type="password"
className="form-control"
id="exampleInputPassword1"
placeholder="<PASSWORD>"
name="password"
ref={register({
required: "Password required",
minLength: { value: 8, message: "Too short password" }
})}
/>
{errors.password && (
<p style={{ color: "red" }}>{errors.password.message}</p>
)}
</div>
<div className="form-actions">
<input id="inputsubmit" type="submit" className="btn btn-primary" />
</div>
<div className="form-actions">
<small>
Don't have an email?
<NavLink to="/login"> Sign up</NavLink>
</small>
</div>
</form>
</React.Fragment>
);
};
export default Login;
| 0c80ba1f8373a399acec767f1e33dd99a403d8b3 | [
"JavaScript"
]
| 4 | JavaScript | mariamhasan/blog-frontend | c91aadc7e23ed1072799b9d4d07c87703da0edc2 | 06c07d1bbc3e819f15fab9e7e1eaa58918287895 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import NavMenu from '../NavMenu/NavMenu';
import { Toast } from 'antd-mobile';
class List extends Component{
constructor(props){
super(props);
this.state={
inputVal:'',
list:[
'one',
'two'
]
}
}
//添加条目
addItem=()=>{
if( this.state.inputVal ){
this.setState({
list: [...this.state.list, this.state.inputVal],
inputVal: ''
});
}else{
Toast.info('不能为空!', 1, null, false);
}
}
//删除条目
delItem=(index)=>{
var list = [...this.state.list];
list.splice(index, 1);
this.setState({
list: list
});
}
getInputVal=(ev)=>{
this.setState({
inputVal: ev.target.value
});
}
getInputVal2=(ev)=>{
if( ev.keyCode === 13 ){
this.addItem();
}
}
render(){
return (
<div className="page">
<div className="todolist">
<div>
<input value={this.state.inputVal} onChange={this.getInputVal} onKeyUp={this.getInputVal2}/>
<button onClick={this.addItem}>添加</button>
</div>
<ul>
{
this.state.list.map((item, index)=>{
return <li key={index}>{item} <span onClick={this.delItem.bind(this,index)}>x</span></li>
})
}
</ul>
</div>
<NavMenu />
</div>
);
}
}
export default List;<file_sep>## react项目模板
1、npm install
2、npm start
3、npm test
4、npm run build
5、npm run eject<file_sep>import React, { Component, Fragment } from 'react';
import NavMenu from '../NavMenu/NavMenu';
import imgUrl from '../../assets/images/01.jpg';
class Home extends Component{
render(){
let imgStyle = {
width:'5rem',
height:'5rem'
}
return (
// Fragments 可以让你聚合一个子元素列表,并且不在DOM中增加额外节点。
<Fragment>
Home
<div>
<img src={imgUrl} style={imgStyle} alt={'图片'}/>
</div>
<div>
<NavMenu />
</div>
</Fragment>
);
}
}
export default Home; | 8b4b2fa6e23b9008c5e5059e4da88ca9bccc5a9f | [
"JavaScript",
"Markdown"
]
| 3 | JavaScript | Zion0707/myReact | 131f6030396f0c4f7fc95358f00b199a85ea226d | 7d374897cc1c3bdb8998e1b3e39dd5617c8b08bd |
refs/heads/master | <file_sep>$(function() {
var waitUntil = function(condidate, interval, callback) {
var inner = function() {
if (condidate()) {
return callback();
} else {
setTimeout(function() { inner(condidate, interval, callback) }, interval);
}
};
setTimeout(inner, interval);
};
var exportToCalendar = function() {
var $trip = $('.trip-content');
var location = function () {
var $waypoints = $trip.find('.waypoint-address .first-line h2');
return {
from: $waypoints.filter(':first').text(),
to: $waypoints.filter(':last').text()
};
};
var details = function () {
var normalizeText = function(text) {
return text.replace(/\s+/g, " ").trim();
};
var transit = function() {
var transit = '↓';
var $directions = $trip.find('.directions-mode-group.closed');
for(var i = 0; i < $directions.length; i++) {
var $transitStops = $($directions[i]).find('.transit-stop');
var $transitSteps = $($directions[i]).find('.transit-logical-step-content .transit-logical-step-header');
for (var j = 0; j < Math.max($transitStops.length, $transitSteps.length); j++) {
if ($transitStops[j]) {
transit += '\n' + normalizeText($transitStops[j].innerText);
}
if ($transitSteps[j]) {
transit += '\n' + '↓ ' + normalizeText($transitSteps[j].innerText);
}
}
};
return transit;
};
var $waypoints = $trip.find('.waypoint');
if ($waypoints[0]) {
return normalizeText($waypoints.filter(':first').text())
+ '\n' + transit()
+ '\n' + normalizeText($waypoints.filter(':last').text())
+ '\n'
+ '\n' + document.URL;
} else {
return document.URL;
}
};
var dates = function () {
var $startTime = $trip.find('.directions-mode-group-departure-time.time-with-period:first');
var $endTime = $trip.find('.directions-mode-group-arrival-time.time-with-period:last');
if ($startTime.length == 0 || $endTime.length == 0) {
return "";
}
var parseDate = function($time, baseDate) {
var parseTransitTime = function (timeText) {
return {
hour: parseInt(timeText.split(':')[0], 10),
minutes: parseInt(timeText.split(':')[1], 10)
};
};
var time = parseTransitTime($time.text());
return new Date(baseDate.getFullYear(), baseDate.getMonth(), baseDate.getDate(), time.hour, time.minutes, 0, 0);
};
var baseDate =
(document.URL.match(/!8j(\d+)/))
? new Date((parseInt(RegExp.$1) - 9 * 60 * 60) * 1000)
: new Date();
var formatAsUTC = function (date) {
var fillZero = function(x) {
return ('00' + x).slice(-2);
};
return ""
+ date.getUTCFullYear()
+ fillZero(date.getUTCMonth() + 1)
+ fillZero(date.getUTCDate()) + 'T'
+ fillZero(date.getUTCHours())
+ fillZero(date.getUTCMinutes())
+ '00Z';
};
return formatAsUTC(parseDate($startTime, baseDate)) + '/' + formatAsUTC(parseDate($endTime, baseDate));
};
var location = location();
var dates = dates();
window.open('http://www.google.com/calendar/event?action=TEMPLATE'
+ '&text=' + location.from + ' → ' + location.to
+ '&details=' + encodeURIComponent(details())
+ (dates ? '&dates=' + dates : '')
+ '&location=' + location.to
+ '&trp=true');
};
var prependTriggerButton = function() {
if ($(".__route_export_trigger").length == 0) {
var trigger = $('<button>').addClass('__route_export_trigger').attr({ title: "Google Maps Transit Scheduler" });
trigger.click(exportToCalendar);
$(".section-directions-details-action").prepend(trigger);
}
};
var actionExists = function() {
return $(".section-directions-details-action").length > 0;
};
waitUntil(actionExists, 100, prependTriggerButton);
});
<file_sep>#  Google Maps Transit Scheduler
Chrome Extension to export transit on Google Maps to Google Calendar.
## Getting started
1. Install from [Chrome Web Store](https://chrome.google.com/webstore/detail/google-maps-transit-sched/bgmhgdighiicpabknccklffnlmmkfldh)
## Usage

## Build
```bash
$ cd chrome-google-maps-transit-scheduler
$ yarn install
$ gulp dist # => target/Google Maps Transit Scheduler-vX.X.X.zip
```
License
-------
Copyright (c) 2016 <NAME>
Google Maps Transit Scheduler is released under the [MIT License](./LICENSE)
| ec5c630f9132bec90a6d98cd5406210f76e8802a | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | negokaz/chrome-google-maps-transit-scheduler | 44416fe905ec0417c5b64407df0a8fd976f64def | 23de47b5cc2203766072b72e2d45cb25aa2bf8df |
refs/heads/main | <file_sep>import './App.css';
import Signup from "./pages/Signup";
// import SignIn from "./pages/SignIn";
import Navbar from "./components/Navbar"
function App() {
console.log(process.env)
return (
<div className="App">
<Navbar/>
<br></br> <br></br>
<Signup/>
</div>
);
}
export default App;
<file_sep>import React from "react";
import { Button,Grid,Container} from '@material-ui/core';
import TextField from '@material-ui/core/TextField';
import { useFormik } from 'formik';
import firebase from "../firebase/firebase.utils"
import firebaseUtils from "../firebase/firebase.utils";
function Signup(){
console.log(firebase)
const validate = values => {
const errors = {};
if (!values.username) {
errors.username = 'Required';
} else if (values.username.length > 15) {
errors.username = 'Must be 15 characters or less';
}
if (!values.email) {
errors.email = 'Required';
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address';
}
if (!values.password) {
errors.password = '<PASSWORD>';
} else if (values.password.length > 20) {
errors.password = 'Must be 20 characters or less';
}
return errors;
};
const formik = useFormik({
initialValues: {
username: '',
email: '',
password: '',
},
validate,
onSubmit: (values) => {
// alert(JSON.stringify(values, null, 2));
firebase.register(values.email,values.password)
},
});
const handleGooglebutton = () => {
firebase.useGoogleProvider();
}
return(
<form onSubmit={formik.handleSubmit}>
<Container maxWidth="sm">
<Grid container spacing={3}>
<Grid item xs={12}>
<TextField
name="username"
label="Username"
variant="outlined"
fullWidth
value={formik.values.username}
onChange={formik.handleChange}
/>
{formik.errors.username ? <div>{formik.errors.username}</div> : null}
</Grid>
<Grid item xs={12} >
<TextField
name="email"
label="E-mail"
variant="outlined"
fullWidth
onChange={formik.handleChange}
value={formik.values.email}/>
{formik.errors.email ? <div>{formik.errors.email}</div> : null}
</Grid>
<Grid item xs={12}>
<TextField
name="password"
label="Password"
variant="outlined"
fullWidth
onChange={formik.handleChange}
value={formik.values.password}
type="password"/>
</Grid>
<Grid item xs={12} >
<Button type="submit" variant="contained" color="primary" fullWidth>Submit</Button >
</Grid>
<Grid item xs={12}>
<Button variant="contained" color="primary" fullWidth onClick={handleGooglebutton}>SignUp With Google</Button>
</Grid>
</Grid>
</Container>
</form>
);
}
export default Signup<file_sep>
import firebase from "firebase/app";
import "firebase/auth"
const devConfig = {
apiKey: process.env.REACT_APP_APIKEY,
authDomain:process.env.REACT_APP_AUTHDOMAIN,
projectId:process.env.REACT_APP_PROJECT_ID,
storageBucket:process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId:process.env.REACT_APP_MESSAGING_SENDER_ID,
appId:process.env.REACT_APP_APP_ID
};
const prodConfig={};
const config = process.env.NODE_ENV === "development" ? devConfig : prodConfig;
class Firebase{
constructor(){
firebase.initializeApp(config)
this.firebaseAuth=firebase.auth();
}
// -----SIGN IN WITH EMAIL AND PPASSWORD-----
register(email,password){
this.firebaseAuth.createUserWithEmailAndPassword(email,password);
}
// -----------------SIGN IN WITH GOOGLE ------------
useGoogleProvider(){
const googleProvider =new firebase.auth.GoogleAuthProvider();
googleProvider.setCustomParameters({prompt:"select_account"})
this.firebaseAuth.signInWithPopup(googleProvider)
}
}
export default new Firebase
<file_sep>import React from "react";
import { Button,Grid,Container} from '@material-ui/core';
import TextField from '@material-ui/core/TextField';
import { Formik,Form,Field } from 'formik';
import firebase from "../firebase/firebase.utils"
import firebaseUtils from "../firebase/firebase.utils";
function validateEmail(value) {
let error;
if (!value) {
error = 'Required';
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
error = 'Invalid email address';
}
return error;
}
function validateUsername(value) {
let error;
if (value === 'admin') {
error = 'Nice try!';
}
return error;
}
const handleGooglebutton = () => {
firebase.useGoogleProvider();
}
function SignIn(){
console.log(firebase)
return(
<Formik
initialValues= {{
username:"",
email:"",
password: '',
}}
onSubmit={values => {
// same shape as initial values
console.log(values);
}}>
<form onSubmit={Formik.handleSubmit}>
<Container maxWidth="sm">
<Grid container spacing={3}>
<Grid item xs={12}>
<TextField
name="username"
label="Username"
variant="outlined"
fullWidth
value={Formik.values.username}
onChange={Formik.handleChange}
/>
</Grid>
<Grid item xs={12} >
<TextField
name="email"
label="E-mail"
variant="outlined"
fullWidth
onChange={Formik.handleChange}
value={Formik.values.email}/>
</Grid>
<Grid item xs={12}>
<TextField
name="password"
label="<PASSWORD>"
variant="outlined"
fullWidth
onChange={Formik.handleChange}
value={Formik.values.password}
type="password"/>
</Grid>
<Grid item xs={12} >
<Button type="submit" variant="contained" color="primary" fullWidth>Submit</Button >
</Grid>
<Grid item xs={12}>
<Button variant="contained" color="primary" fullWidth onClick={handleGooglebutton}>SignUp With Google</Button>
</Grid>
</Grid>
</Container>
</form>
</Formik>
);
}
export default SignIn | 6f8dec1c5c5537f7b69599e691f882a8e4e6e420 | [
"JavaScript"
]
| 4 | JavaScript | hellenkuttery/share-project | 9d975fb2387251dcd21f8d54ff0ca9cc8a093306 | 623117d24437fb9658c606705c589c5be4a2c163 |
refs/heads/master | <repo_name>MarcyMagi/xbox-controller-display<file_sep>/src/js/main.js
let start
let elements = []
let config_stick
function elementsConnect() {
elements.push(document.getElementById("A"))
elements.push(document.getElementById("B"))
elements.push(document.getElementById("X"))
elements.push(document.getElementById("Y"))
elements.push(document.getElementById("LB"))
elements.push(document.getElementById("RB"))
elements.push(document.getElementById("LT"))
elements.push(document.getElementById("RT"))
elements.push(document.getElementById("SELECT"))
elements.push(document.getElementById("START"))
elements.push(document.getElementById("LEFT_STICK"))
elements.push(document.getElementById("RIGHT_STICK"))
elements.push(document.getElementById("UP_PAD"))
elements.push(document.getElementById("DOWN_PAD"))
elements.push(document.getElementById("LEFT_PAD"))
elements.push(document.getElementById("RIGHT_PAD"))
for(let i = 0; i < elements.length; i++) {
elements[i].setAttribute("fill-opacity", "0");
}
}
function configSticks() {
let sticks = [document.getElementById("LEFT_STICK"), document.getElementById("RIGHT_STICK")]
let death_point = [parseFloat(sticks[0].getAttribute("cx")), parseFloat(sticks[0].getAttribute("cy"))]
config_stick = {
sticks: sticks,
death_point: death_point,
r: 7
}
}
function displaySticks(axes) {
if(Math.abs(axes[0]) < 0.1) {
config_stick.sticks[0].setAttribute("cx", String(config_stick.death_point[0]))
} else {
config_stick.sticks[0].setAttribute("cx", String(config_stick.death_point[0] + (axes[0] * config_stick.r)))
}
if(Math.abs(axes[1]) < 0.1) {
config_stick.sticks[0].setAttribute("cy", String(config_stick.death_point[1]))
} else {
config_stick.sticks[0].setAttribute("cy", String(config_stick.death_point[1] + (axes[1] * config_stick.r)))
}
if(Math.abs(axes[2]) < 0.1) {
config_stick.sticks[1].setAttribute("cx", String(config_stick.death_point[0]))
} else {
config_stick.sticks[1].setAttribute("cx", String(config_stick.death_point[0] + (axes[2] * config_stick.r)))
}
if(Math.abs(axes[3]) < 0.1) {
config_stick.sticks[1].setAttribute("cy", String(config_stick.death_point[1]))
} else {
config_stick.sticks[1].setAttribute("cy", String(config_stick.death_point[1] + (axes[3] * config_stick.r)))
}
}
function gameLoop() {
let gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads : []);
if (!gamepads) {
return;
}
let gp = gamepads[0]
displaySticks(gp.axes)
for(let i = 0; i < gp.buttons.length - 1; i++) {
elements[i].setAttribute("fill-opacity", String(gp.buttons[i].value));
}
requestAnimationFrame(gameLoop)
}
window.onload = function() {
configSticks()
elementsConnect()
window.addEventListener("gamepadconnected", function(e) {
gameLoop()
});
} | 4317864bd89918c1f8dd29b2d18c4deef6a4a72d | [
"JavaScript"
]
| 1 | JavaScript | MarcyMagi/xbox-controller-display | faa266970b1a776b5408651a78db31be931c72f5 | 8f5e51d538c0383b4289455d582f7a2b19c04a22 |
refs/heads/master | <repo_name>Subwayway/stm32-function<file_sep>/function/dht11/Src/main.c
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "dwt_stm32_delay.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
uint32_t millis_cnt=0;
uint32_t millis(){
return millis_cnt;
}
uint32_t micros(){
uint32_t val = SysTick->VAL;
uint32_t load = SysTick->LOAD;
return (millis_cnt&0x3FFFFF)*1000 + (load-val)/((load+1)/1000);
}
void delay_us(uint32_t us){
uint32_t temp = micros() + us;
while(temp > micros());
}
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
#define DHT11_port GPIOA
#define DHT11_pin 1
#define DHT11_pinmode CRL // if(pin < 8) CRL , else CRH
#define DHT11_read IDR
#pragma anon_unions
union {
uint32_t data;
struct {
uint8_t temp_d;
uint8_t temp_i;
uint8_t rh_d;
uint8_t rh_i;
};
} DHT;
uint8_t DHT_read () {
uint8_t i, check_sum;
uint32_t start;
check_sum = 0;
DHT.data = 0;
GPIOA->CRL = (DHT11_port->DHT11_pinmode&(~(15<<((DHT11_pin%8)*4))))|(7<<((DHT11_pin%8)*4)); // Output Open-drain (Master send LOW signal)
HAL_Delay(18);
GPIOA->CRL = (DHT11_port->DHT11_pinmode&(~(15<<((DHT11_pin%8)*4))))|(4<<((DHT11_pin%8)*4)); // Floating input (Master send HIGH signal & data receive)
start = micros();
while (DHT11_port->DHT11_read&(1<<DHT11_pin)) { // HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_9);
if (micros()-start > 50) return 1; // 20~40us
}
start = micros();
while (!(DHT11_port->DHT11_read&(1<<DHT11_pin))) {
if (micros()-start > 120) return 2; // 80us
}
start = micros();
while (DHT11_port->DHT11_read&(1<<DHT11_pin)) {
if (micros()-start > 120) return 3; // 80us
}
for (i = 0; i < 32; i++) {
while (!(DHT11_port->DHT11_read&(1<<DHT11_pin))); // 50us
start = micros();
while (DHT11_port->DHT11_read&(1<<DHT11_pin));
if (micros()-start > 50) DHT.data |= (0x80000000 >> i); // "0"=26~28us, "1"=70us
}
for (i = 0; i < 8; i++) {
while (!(DHT11_port->DHT11_read&(1<<DHT11_pin))); // 50us
start = micros();
while (DHT11_port->DHT11_read&(1<<DHT11_pin));
if (micros()-start > 50) check_sum |= (0x80 >> i);
}
if ((DHT.rh_i + DHT.rh_d + DHT.temp_i + DHT.temp_d) == check_sum) return 0;
else return 4;
}
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart2;
/* USER CODE BEGIN PV */
UART_HandleTypeDef huart2;
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
uint8_t Rh_byte1, Rh_byte2, Temp_byte1, Temp_byte2,Temp_value, Rh_value;
uint16_t sum, RH, TEMP;
uint8_t check = 0;
GPIO_InitTypeDef GPIO_InitStruct;
void set_gpio_output (void)
{
/*Configure GPIO pin output: PA2 */
GPIO_InitStruct.Pin = GPIO_PIN_1;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
void set_gpio_input (void)
{
/*Configure GPIO pin input: PA2 */
GPIO_InitStruct.Pin = GPIO_PIN_1;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
void DHT11_start (void)
{
set_gpio_output (); // set the pin as output
HAL_GPIO_WritePin (GPIOA, GPIO_PIN_1, 0); // pull the pin low
delay_us (18000);
HAL_GPIO_WritePin (GPIOA, GPIO_PIN_1, 1); // wait for 18ms
set_gpio_input (); // set as input
}
void check_response (void)
{
delay_us (40);
if (!(HAL_GPIO_ReadPin (GPIOA, GPIO_PIN_1))) // if the pin is low
{
delay_us (80); // wait for 80us
if ((HAL_GPIO_ReadPin (GPIOA, GPIO_PIN_1))) check = 1; // now if the pin is high response = ok i.e. check =1
}
while ((HAL_GPIO_ReadPin (GPIOA, GPIO_PIN_1))); // wait for the pin to go low
}
uint8_t read_data (void)
{
uint8_t i,j;
for (j=0;j<8;j++)
{
while (!(HAL_GPIO_ReadPin (GPIOA, GPIO_PIN_1))); // wait for the pin to go high
delay_us (40); // wait for 40 us
if ((HAL_GPIO_ReadPin (GPIOA, GPIO_PIN_1)) == 0) // if the pin is low
{
i&= ~(1<<(7-j)); // write 0
}
else i|= (1<<(7-j)); // if the pin is high, write 1
while ((HAL_GPIO_ReadPin (GPIOA, GPIO_PIN_1))); // wait for the pin to go low
}
return i;
}
void DHT11_getdata()
{
DHT11_start();
check_response ();
Rh_byte1 = read_data ();
Rh_byte2 = read_data ();
Temp_byte1 = read_data ();
Temp_byte2 = read_data ();
sum = read_data();
if (sum == (Rh_byte1+Rh_byte2+Temp_byte1+Temp_byte2)) // if the data is correct
{
Temp_value = ((Temp_byte1/10)+48)+((Temp_byte1%10)+48);
Rh_value = ((Rh_byte1/10)+48)+((Rh_byte1%10)+48);
}
}
int fputc(int ch,FILE *f)
{
HAL_UART_Transmit(&huart2, (uint8_t*)&ch, 1 , 0xFFFF);
return ch;
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART2_UART_Init();
DWT_Delay_Init ();
/* USER CODE BEGIN 2 */
HAL_Delay (1000);
char str[20];
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
Rh_byte1=0;
Rh_byte2=0;
Temp_byte1=0;
Temp_byte2=0;
DHT11_start ();
check_response ();
Rh_byte1 = read_data ();
Rh_byte2 = read_data ();
Temp_byte1 = read_data ();
Temp_byte2 = read_data ();
sum = read_data();
if (sum == (Rh_byte1+Rh_byte2+Temp_byte1+Temp_byte2)) // if the data is correct
{
printf("%d %d \n", Rh_byte1, Temp_byte1);
HAL_Delay (5000);
}
//set_gpio_output ();
HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);
HAL_Delay(300);
HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);
HAL_Delay(300);
/*
uint8_t error_no = DHT_read();
printf("%d %d \n", DHT.temp_i, DHT.rh_i);
HAL_Delay(1000);
*/
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief USART2 Initialization Function
* @param None
* @retval None
*/
static void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin : B1_Pin */
GPIO_InitStruct.Pin = B1_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : PA1 */
GPIO_InitStruct.Pin = GPIO_PIN_1;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pin : LD2_Pin */
GPIO_InitStruct.Pin = LD2_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(LD2_GPIO_Port, &GPIO_InitStruct);
/* EXTI interrupt init*/
HAL_NVIC_SetPriority(EXTI15_10_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(EXTI15_10_IRQn);
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/README.md
### stm32-function
-stm32f103Rb와 stm32f103C8ta 의 다양한 기능들을 구현하는 라이브러리 저장소입니다.
| b66d7aa645833a232e59e59349e32f09695f1900 | [
"Markdown",
"C"
]
| 2 | C | Subwayway/stm32-function | d0599c11c6149b3d32a62bdfd2c226b1c3aad545 | 0998ee482c8e8d7b45a91358e2db4f5818bda632 |
refs/heads/master | <file_sep># lambdata
A collection of data science helper functions
This is a file for making your own package of helper functions
<file_sep>"""
utility functions for working with DataFrames
"""
import pandas
import numpy as np
TEST_DF = pandas.DataFrame([1, 2, 3])
class df_functions:
def list_to_column(self, X, list, name='column'):
"""
adds list to dataframe
paramters:
X = DataFrame
list = list type
name = str type
"""
X[name] = list
return X
def round_Data_Frame(self, X, n=2):
"""
Will round all numbers within the dataframe to defined
parameters:
X = DataFrame
n = int type. will round to this value. 2 if not defined
"""
for x in X.columns:
if type(X[x][0]) == np.float64:
temp = []
for y in X[x]:
temp.append(round(y, n))
X[x] = temp
return X
| 47a1dbf67c6c7219c85f4797c3c8d46177fc6aff | [
"Markdown",
"Python"
]
| 2 | Markdown | scottwmwork/lambdata | acfbc724958eaa37cfc917f5f0cfe058e2872326 | 4aba95df277a37d55acd060a1454dc033c0521e8 |
refs/heads/master | <repo_name>jayeshc1990/slackbot<file_sep>/plugins/hi.py
import time
import requests
import shutil
import re
crontable = []
outputs = []
from slackclient import SlackClient
def process_message(data):
token = "<PASSWORD>" #This is your own slack token
sc = SlackClient(token)
if data['text'].lower().startswith("hi") or data['text'].lower().startswith("hello"):
print sc.api_call("users.info",user=data['user'])
capturestring = sc.api_call("users.info",user=data['user'])
namestring = re.split('"|:|,',capturestring)
#print namestring[23]
sendstring = "Hiii... %s. I am BOT." %namestring[23]
outputs.append([data['channel'], sendstring])
| 458b67cb82e1650d45871bb0df76616a893a67e7 | [
"Python"
]
| 1 | Python | jayeshc1990/slackbot | 20a6fcaedb4e819e647a0c70fa5c6f4971d136a6 | ea3a56f0922b925703f50edc80a2e514b1d44ff4 |
refs/heads/master | <file_sep>#!/usr/bin/env ruby
# encoding: utf-8
require 'net/http'
Given /^I am on the Administration page$/ do
visit AdministrationViewPage
end
Given /^I am on the New Staff page under Group$/ do
on AdministrationViewPage do |page|
sleep(5)
page.group_element.fire_event 'mouseover'
sleep(2)
page.organization_element.fire_event 'mouseover'
sleep(2)
page.new_staff_element.when_present.click
end
end
Given /^I create a new user account with username "(.*?)" and password "(.*?)" and firstname "(.*?)" and lastname "(.*?)" and email "(.*?)"$/ do |name, password, firstname, lastname, email|
on AdministrationViewPage do |page|
page.create_new_user(name, password, firstname, lastname, email)
on PreferencePage do |page|
page.ok
sleep(5)
end
end
end
Given /^I login with "(.*?)" and "(.*?)"$/ do |name, password|
on DashboardPage do |page|
page.logout
end
on LoginPage do |page|
page.login_user(name, password)
end
end
Then /^I should see the dashboard page$/ do
on DashboardPage do |page|
page.show_install_info_element.when_present.click
page.logout
end
on LoginPage do |page|
page.login_user("admin","admin")
end
end
Given /^I navigate to Site Editor to edit the current dashboard page$/ do
on AdministrationViewPage do |page|
sleep(3)
page.site_editor_element.fire_event 'mouseover'
sleep(2)
page.edit_page_element.when_present.click
end
end
When /^I add a portlet$/ do
on AdministrationViewPage do |page|
page.gw_portlets_element.when_present.click
sleep(2)
<EMAIL>(:title => "Event Console").simulateDragSortable({ move: 10, -10 });
#@browser.div(:title => "Event Console").drag_and_drop_by(100, -200)
@browser.div(:title => "Custom Groups").fire_event "onmousedown"
sleep(2)
@browser.driver.action.click_and_hold(page.customgroup_element.wd).perform
sleep(2)
@browser.driver.action.move_to(page.droppable_area_element.wd).click.perform
sleep(2)
@browser.div(:title => "Custom Groups" ).fire_event "onmouseup"
#a = @browser.div(:title => "Event Console")
#b = @browser.div(:class => "UIRowContainer")
#a.drag_and_drop_on b
#sleep(2)
#<EMAIL>.drag_and_drop(a, b).perform
end
end
And /^I edit the portlet configuration$/ do
sleep(10)
3.times do
@browser.div(:id => /UIPortlet/).fire_event 'mouseover'
end
sleep(2)
on AdministrationViewPage do |page|
page.edit_portlet_element.when_present.click
end
@browser.text_field(:id => 'title').when_present.set 'Custom Group'
@browser.checkbox(:name => 'showInfoBar').when_present.set
@browser.link(:text => 'Save And Close').when_present.click
sleep(10)
end
And /^I add another portlet and edit its configuration$/ do
on AdministrationViewPage do |page|
page.gw_portlets_element.when_present.click
sleep(2)
@browser.div(:title => "Event Portlet").fire_event "onmousedown"
sleep(2)
@browser.driver.action.click_and_hold(page.event_portlet_element.wd).perform
sleep(2)
@browser.driver.action.move_to(page.droppable_area_element.wd).click.perform
sleep(2)
@browser.div(:title => "Event Portlet" ).fire_event "onmouseup"
3.times do
@browser.div(:id => /UIPortlet/, :index => 1).fire_event 'mouseover'
end
sleep(2)
#page.edit_portlet_element.when_present.click
@browser.link(:title => /Edit Portlet/, :index => 1).when_present.click
@browser.radio(:id => 'radioEntireNetwork_ELP').when_present.set
@browser.text_field(:name => 'customPortletTitle').when_present.set 'All Events'
@browser.button(:value => 'Save Preferences').when_present.click
@browser.link(:text => 'Close').when_present.click
#page.finish_element.when_present(30).click
page.gw_portlets_element.when_present.click
sleep(5)
@browser.link(:class => /EdittedSaveButton/).when_present.click
sleep(10)
end
end
Then /^I should see the added portlets$/ do
@browser.button(:value => 'Select All').when_present.click
sleep(10)
@browser.button(:value => 'Deselect All').when_present.click
sleep(5)
@browser.div(:class => 'customgroupframe').span(:text => /No CustomGroups Available!/).exists?.should == true
@browser.div(:class => 'customgroupframe').button(:value => 'Create New CustomGroup').when_present.click
sleep(5)
#on CustomGroupPage do |page|
# page.form_button_element.when_present.click
# sleep(5)
#end
visit DashboardPage
end
When /^I delete the added portlets$/ do
on AdministrationViewPage do |page|
#@browser.div(:class)div(:class => /UIComponentBlock/).div(:class => /EDITION-BLOCK EDITION-PORTLET/ ).div(:class => /NewLayer/).when_present.hover
2.times do
page.gw_portlets_element.when_present.click
sleep(2)
@browser.div(:id => /UIPortlet/).fire_event 'mouseover'
@browser.div(:id => /UIPortlet/).fire_event 'mouseover'
@browser.div(:id => /UIPortlet/).fire_event 'mouseover'
#@browser.div(:id => /UIPortlet/).when_present.click
sleep(2)
page.delete_portlet_element.when_present.click
sleep(3)
@browser.alert.ok
sleep(3)
#page.finish_element.when_present(30).click
sleep(5)
end
@browser.link(:class => /EdittedSaveButton/).when_present.click
end
end
Then /^I should not see the portlets$/ do
@browser.div(:class => 'customgroupframe').span(:text => /No CustomGroups Available!/).exists?.should == false
@browser.button(:value => 'Select All').exists?.should == false
sleep(5)
end
Given /^I navigate to Site Editor to add a new page$/ do
on AdministrationViewPage do |page|
sleep(5)
page.site_editor_element.when_present.hover
sleep(4)
page.add_page_element.when_present.click
end
end
Given /^I go to User Management under Groups$/ do
on AdministrationViewPage do |page|
sleep(5)
page.group_element.fire_event 'mouseover'
sleep(2)
page.organization_element.fire_event 'mouseover'
sleep(2)
page.user_management_element.when_present.click
end
end
Given /^I select Search users$/ do
on AdministrationViewPage do |page|
page.search_textbox_element.when_present.set 'optimus'
#page.search_icon_element.when_present.click
@browser.send_keys :enter
sleep(3)
end
end
When /^I delete the user with name "(.*?)"$/ do |name|
#on AdministrationViewPage do |page|
# page.delete_new_user_element.when_present.click
@browser.image(:class => /DeleteUserIcon/).when_present.click
@browser.alert.ok
end
Then /^the user should be deleted$/ do
on AdministrationViewPage do |page|
page.search_textbox_element.when_present.set 'optimus'
#page.search_icon_element.when_present.click
@browser.send_keys :enter
page.no_results_message_element.when_present.exists?.should == true
on PreferencePage do |page|
page.ok
sleep(5)
end
end
end
#OptimusComment: Added to display build version in results
Given /^Build and version$/ do
on DashboardPage do |page|
page.show_install_info_element.when_present.click
info_text = @browser.span(:id => "last_checked").p(:text => /PostgreSQL/).text.split("\n")
name = info_text.grep(/^name/)[0].split("= ")[1]
version = info_text.grep(/^version/)[0].split("= ")[1]
gw_build = info_text.grep(/^gw_build/)[0].split("= ")[1]
bitrock_build = info_text.grep(/^bitrock_build/)[0].split("= ")[1]
puts "Name:" + name + " ---- Version:" + version + " ---- GW_build:" + gw_build + " ---- bitrock_build:" + bitrock_build
end
end
#Added on 18 Feb 2015
Given /^I am on the User Management page$/ do
on AdministrationViewPage do |page|
sleep(5)
page.group_element.fire_event 'mouseover'
sleep(2)
page.organization_element.fire_event 'mouseover'
sleep(2)
page.user_management_element.when_present.click
sleep(5)
end
end
And /^I navigate to membership management$/ do
on UserManagementPage do |page|
page.membership_management_element.click
sleep(5)
end
end
And /^I navigate to group management$/ do
on UserManagementPage do |page|
page.group_management_element.when_present.click
sleep(5)
end
end
And /^I logout and login with "(.+)"$/ do |user|
on DashboardPage do |page|
page.logout
end
on LoginPage do |page|
page.login_user(user,user)
end
end
And /^I "(.*?)" portal user "(.*?)" to access modules "(.*?)" and "(.*?)"$/ do |permission,user,module1,module2|
on UserManagementPage do |page|
page.access_restriction(user,permission,module1,module2)
end
end
Then /^accessing "(.+)" and "(.+)" should display access error$/ do |module1,module2|
on UserManagementPage do |page|
page.access_error(module1)
page.access_error(module2)
end
end
Then /^"(.+)" and "(.+)" should be accessible and should not display any errors$/ do |module1,module2|
on UserManagementPage do |page|
page.access_granted(module1)
page.access_granted(module2)
end
end
And /^I "(.+)" user - "(.+)" in group - "(.+)"$/ do |add,user,group|
on UserManagementPage do |page|
page.add_group(add,user,group)
end
end
<file_sep>class NagiosServiceStatusDetailsPage
include PageObject
direct_url BASE_URL + "advanced/nagios-app/NagiosServiceDetailView"
in_frame(:id => 'myframe') do |frame|
link :localhost_local_cpu_httpd, :text => /local_cpu_httpd/, :frame => frame
end
link :passive_check_result, :text => /Submit passive check result for this service/
text_field :check_output, :name => /plugin_output/
text_field :perf_data, :name => /performance_data/
button :commit, :name => /btnSubmit/
def goto_nagios_service_url(host,service)
new_base_url = String.new
# copying the BASE_URL to a new string
new_base_url = BASE_URL
# slicing off the /portal/classic/ from the BASE_URL
if new_base_url.include? "/portal/classic/"
#puts new_base_url.slice "/portal/classic/"
new_base_url["/portal/classic/"]= ""
end
# creating the new URL to acces the page
submit_passive_check_result_url = String.new
submit_passive_check_result_url = new_base_url + "/nagios-app/cmd.cgi?cmd_typ=30&host="+host+"&service="+service
#puts submit_passive_check_result_url
# now accessing the Nagios Submit passive check result page of the service via the new URL
@browser.goto submit_passive_check_result_url
end
end
<file_sep>class AutomationPage
include PageObject
direct_url BASE_URL + "auto-disc/automation"
in_frame(:id => 'myframe') do |frame|
radio :automation_schema, :value => /GroundWork-Discovery-Pro/, :frame => frame
button :next, :value => /Next >>/, :frame => frame
button :close, :name => "close", :frame => frame
button :rename, :name => "rename", :frame => frame
button :cancel_rename, :name => "cancel_rename", :frame => frame
button :new_schema, :name => "new_schema", :frame => frame
button :cancel, :name => "cancel", :frame => frame
button :add, :name => "add", :frame => frame
button :save, :name => "save", :frame => frame
button :delete, :name => "delete", :frame => frame
button :confirm_delete, :text => "Yes", :frame => frame
button :delete_no, :value => "No", :frame => frame
button :save_as_template, :value => "Save As Template", :frame => frame
button :edit_record, :name => /edit_rec_qa-ubuntu-12-04-64-2/, :frame => frame
button :add_service, :text => "Add Service", :frame => frame
button :add_instance, :text => "Add Instance", :frame => frame
button :view, :text => 'View', :frame => frame
text_field :schema_name, :name => "automation_name", :frame => frame
text_field :data_source, :name => "data_source", :frame => frame
text_field :rename_schema, :name => "new_name", :frame => frame
text_field :host_name, :name => "host_name", :frame => frame
text_field :alias, :name => "alias", :frame => frame
text_field :address, :name => "address", :frame => frame
select :profiles_host, :name => "profiles_host", :frame => frame
select :monarch_groups, :name => "monarch_groups", :frame => frame
select :profiles_service, :name => "profiles_service", :frame => frame
select :hostgroups, :name => "hostgroups", :frame => frame
select :parents, :name => "parents", :frame => frame
select :contactgroups, :name => "contactgroups", :frame => frame
select :service_add, :name => "service_add", :frame => frame
select :delimiter, :name => "delimiter", :frame => frame
link :remove_service, :name => "remove_service_http_alive", :frame => frame
select :type, :name => "type", :frame => frame
select :template, :name => "template", :frame => frame
end
def click(button)
if button == "close"
self.close_element.when_present.click
elsif button == "cancel_rename"
self.rename_element.when_present.click
self.cancel_rename_element.when_present.click
elsif button == "cancel"
self.close_element.when_present.click
self.new_schema_element.when_present.click
self.cancel_element.when_present.click
elsif button == "delete"
self.delete_element.when_present.click
end
end
def verify_page(button)
if button == 'close' || button == 'cancel'
@browser.frame(:id => 'myframe').text.include?("Automation Home")
elsif button == 'cancel_rename'
@browser.frame(:id => 'myframe').text.include?("Modify Automation Schema")
elsif button == 'delete'
@browser.frame(:id => 'myframe').text.include?("Are you sure you want to remove automation schema")
self.confirm_delete_element.exists?.should == true
self.delete_no_element.exists?.should == true
self.delete_no_element.when_present.click
end
end
def create_schema(schema)
self.new_schema_element.when_present.click
if schema == "schema_type"
self.schema_name_element.set schema
self.type_element.option(:value => 'host-import').when_present.select
self.add_element.when_present.click
self.data_source_element.set "/usr/local/groundwork/core/monarch/automation/data/"+schema+".txt"
elsif schema == "schema_template" || schema == "schema_template_1"
self.schema_name_element.set schema
self.template_element.option(:value => 'GroundWork-Default-Pro').when_present.select
self.add_element.when_present.click
self.data_source_element.set "/usr/local/groundwork/core/monarch/automation/data/"+schema+".txt"
elsif schema == "schema_type_template"
self.schema_name_element.set schema
self.type_element.option(:value => 'host-import').when_present.select
self.template_element.option(:value => 'GroundWork-Default-Pro').when_present.select
self.add_element.when_present.click
self.data_source_element.set "/usr/local/groundwork/core/monarch/automation/data/"+schema+".txt"
elsif schema == "template"
end
self.save_element.when_present.click
end
def perform(action,schema)
if action == 'rename'
self.rename_element.when_present.click
self.rename_schema_element.set schema+"_renamed"
self.rename_element.when_present.click
elsif action == 'delete'
self.delete_element.when_present.click
self.confirm_delete_element.when_present.click
end
end
def edit_host(host)
self.host_name_element.when_present.clear
self.host_name_element.when_present.set host+"-renamed"
self.address_element.when_present.clear
self.address_element.when_present.set "192.168.3.11"
self.alias_element.when_present.clear
self.alias_element.when_present.set host+"-alias"
self.profiles_host_element.select("host-profile-ssh-unix")
self.monarch_groups_element.select("windows-gdma-2.1")
self.profiles_service_element.select("ssh-unix")
self.hostgroups_element.select("Linux Servers")
self.parents_element.select("localhost")
self.contactgroups_element.select("nagiosadmin")
self.service_add_element.select("local_load")
self.add_service_element.when_present.click
sleep(3)
@browser.frame(:id => 'myframe').radio(:value => 'local_load').when_present.set
sleep(2)
@browser.frame(:id => 'myframe').text_field(:name => 'instance_add').set '_instance'
self.add_instance_element.when_present.click
end
def create_schema_from_template(schema,template)
self.new_schema_element.when_present.click
self.schema_name_element.when_present.set schema
self.template_element.select(template)
self.add_element.when_present.click
end
def create_template(template)
self.new_schema_element.when_present.click
self.schema_name_element.set template
self.template_element.option(:value => 'GroundWork-Default-Pro').when_present.select
self.add_element.when_present.click
self.data_source_element.set "/usr/local/groundwork/core/monarch/automation/data/"+template+".txt"
self.delimiter_element.select(",")
end
end
<file_sep>class PreferencePage
include PageObject
link :preference, :text => "GroundWork Administrator"
link :restuser, :text => "test user"
#link :edit_profile, :text => "Edit profile"
text_field :firstname, :id => "firstName"
text_field :lastname, :id => "lastName"
link :submit, :text => "Save"
link :ok, :text => "OK"
link :close, :text => "Close"
end
<file_sep>source "http://rubygems.org"
gem "rake"
gem "cucumber", ">0.0"
gem "rspec", ">0.0"
gem "watir-webdriver"
gem "cuporter", ">0.0"
gem "headless", ">0.0"
gem "yard-cucumber"
gem "rdiscount"
gem "prawn"
gem "pry"
gem "net-ssh"
gem 'page-object'
gem 'browsermob-proxy'
gem "rb-readline"
gem "webdriver-user-agent"
gem "faker"
gem "quoth"
gem "net-ssh"
gem "net-scp"
gem "rest-client"
gem "nokogiri", '~> 1.5.9'
gem "watir-dom-wait"
<file_sep>class CustomGroupPage
include PageObject
direct_url BASE_URL + "groundwork-administration/customgroupsview"
@@group_type = { "HostGroup" => 1, "ServiceGroup" => 2, "CustomGroup" => 3}
button :form_button, :value => "Create New CustomGroup"
text_field :name, :class =>/iceInpTxt portlet-form-input-field text/
select_list :children, :class => /iceSelMnyLb portlet-form-field/, :id => /createCustomGroupForm:SlctChildren_leftList/
select_list :children_edit, :id => /editCustomGroupForm:SlctChildren_leftList/
button :add_children, :alt => /Add Selected Item/
button :add_children_edit, :id => /editCustomGroupForm:SlctChildren_addBtn/
button :save_and_publish, :value => /Save and Publish/
button :save, :value => /Save/
table :groups_table, :class => /iceDatTbl/
button :edit_group, :value => /Edit CustomGroup/
button :delete_group, :value => /Delete CustomGroup/
button :confirm_delete, :value => "Delete"
#button :confirm_delete, :name => /:cgListFrm:deleteConfirmPanel-accept/
span :error_msg, :class => /iceMsgsInfo portlet-msg-info/
#span :no_groups_available, :id => /cgListFrm:j_id13/
#span :no_groups_available, :id => /G3a9e913a_2dffb2_2d48df_2da03b_2dad1c8a13f78e:cgListFrm:j_id13/
span :no_groups_available, :text => /No CustomGroups Available!/
span :delete_confirm_message, :text => /Please confirm your delete action!/
span :edit_error_message, :text => /Cannot edit multiple custom groups!/
span :create_error_message, :text => /Custom Group with CG1 already exists/
span :mix_error_message, :text => /You cannot mix HostGroups, ServiceGroups or CustomGroups!/
#checkbox :custom_group1, :id => /cgListFrm:customGroups:0:j_id17/
checkbox :custom_group1, :id => /cgListFrm:customGroups:0/
#checkbox :custom_group2, :id => /cgListFrm:customGroups:1:j_id17/
checkbox :custom_group2, :id => /cgListFrm:customGroups:1/
span :child_error_message, :text => /Please add atleast one child!/
button :remove_button, :id => /editCustomGroupForm:SlctChildren_removeAllBtn/
link :configuration, :text => /Configuration/
link :administration, :text => /Administration/
link :customgroups, :text => /CustomGroups/
link :control, :text => /Control/
button :continue, :name =>/continue/
link :services, :text => /Services/
def create(name,type,*children_to_add)
self.name = name
if @@group_type.has_key?(type)
@browser.radio(:value => "#{@@group_type["#{type}"]}").set
sleep(1)
end
children_to_add.each do |child|
if self.children_element.include?("#{child}")
self.children = child
end
end
sleep(2)
self.add_children
#This sleep is necessary to wait until the child is load
#Next step not important upto now is to make is wait until the child appears in the selected list
sleep(1)
end
def edit(name, host_to_add)
found = false
self.groups_table_element.to_a.each do |row|
row.to_a.each do |cell|
if cell.text == name
row.to_a[0].checkbox_element.check
self.edit_group
sleep(1)
found = true
break
end
end
break if found
end
if found
if self.children_edit_element.include?("#{host_to_add}")
self.children_edit = host_to_add
self.add_children_edit
"OK"
else
"Invalid child to add"
end
else
"Invalid Custom group name"
end
end
def check_group(name)
found = false
self.groups_table_element.to_a.each do |row|
row.to_a.each do |cell|
if cell.text == name
row.to_a[0].checkbox_element.check
found = true
break
end
end
break if found
end
found
end
def delete(name)
found = false
self.groups_table_element.to_a.each do |row|
row.to_a.each do |cell|
if cell.text == name
row.to_a[0].checkbox_element.check
self.delete_group
self.confirm_delete
found = true
break
end
end
break if found
end
found
end
end
<file_sep>When /^I select only a host on the status viewer page$/ do
on StatusviewerPage do |page|
page.linux_servers_element.when_present(100).click
page.localhost_element.when_present(100).click
end
end
When /^I select downtime option$/ do
on StatusviewerPage do |page|
page.downtime_element.when_present.click
page.schedule_downtime_element.when_present.click
sleep(8)
end
end
When /^I schedule downtime$/ do
on StatusviewerPage do |page|
page.comment ="down by qa"
page.type_down = 'Fixed'
page.downtime_button_element.when_present.click
end
end
Then /^I wait and check host downtime status on status viewer page$/ do
on StatusviewerPage do |page|
sleep(45)
page.linux_servers_element.when_present.click
page.localhost_element.when_present.click
page.downtime_value == "Yes"
page.downtime_comment_tab_element.when_present.click
sleep(3)
page.downtime_comment_element.when_present.text == /This host has been scheduled for fixed downtime/
end
end
Then /^the host downtime event gets displayed$/ do
on EventconsolePage do |page|
page.host_groups_events_element.click
page.LS_link_element.when_present.click
sleep(5)
end
end
When /^I schedule service downtime$/ do
on StatusviewerPage do |page|
page.service_comment ="down by qa"
page.service_type_down = 'Fixed'
page.service_downtime_button_element.when_present.click
end
end
Then /^I select a service on the status viewer page$/ do
on StatusviewerPage do |page|
page.linux_servers_element.when_present.click
page.localhost_element.when_present.click
page.local_cpu_httpd_element.when_present.click
end
end
Then /^I wait and check service downtime status on status viewer page$/ do
on StatusviewerPage do |page|
sleep(45)
page.linux_servers_element.when_present.click
page.localhost_element.when_present.click
page.local_cpu_httpd_element.when_present.click
page.service_downtime_value == "Yes"
page.service_downtime_comment_element.when_present.text == /This service has been scheduled for fixed downtime/
end
end
Then /^I select the search tab and search a host by "(.+)"$/ do |search|
on StatusviewerPage do |page|
page.search_for_host(search)
sleep(1)
end
end
Then /^I should see the host as the search result$/ do
on StatusviewerPage do |page|
sleep(2)
results = page.search_count
if results.split(" ")[0].to_i == 1
page.search_result_element.exists?
puts page.search_result_element.attribute_value("text")
end
end
end
When /^I select a host "(.+)" on status viewer page$/ do |host|
visit AutodiscoveryPage
visit StatusviewerPage
sleep(3)
on StatusviewerPage do |page|
page.select_hostname(host)
sleep(6)
end
end
When /^I select "(.+)" downtime option with "(.+)","(.+)"$/ do |option,comment,time|
on StatusviewerPage do |page|
page.downtime(option,comment,time)
end
end
When /^then submit passive check result with "(.+)"$/ do |state|
on StatusviewerPage do |page|
page.submit_check_results_host(state)
end
end
Then /^verify that host "(.+)" is in "(.+)" status$/ do |host,state|
on StatusviewerPage do |page|
page.downtime_comment_tab_element.when_present.click
sleep(3)
@browser.table(:id => /HVform:CPtblComments/).tr(:id => /HVform:CPtblComments:0/).span(:text => /CPtxtCommentValue/, :text => /This host has been scheduled for fixed downtime/).exists?.should == true
page.verify_hoststatus_hostsummary(state)
page.verify_hostdown_entire_network(host,/#{state}:Scheduled/)
page.verify_hostdown_hostgroup(state)
visit EventconsolePage
on EventconsolePage do |page|
page.verify_hostdown_eventconsole
visit NagiosHostStatusDetailsPage
on NagiosHostStatusDetailsPage do |page|
page.localhost_element.when_present.click
sleep(3)
@browser.td(:class => /stateInfoPanel/).td(:class => /stateInfoTable1/).div(:text => state).exists? == true
end
end
end
end
And /^since time should be displayed for "(.+)"$/ do |option|
date = @browser.span(:id => /txtHostStateSince/).text.to_s
date = date.reverse[0...22].reverse
puts date
end
Then /^verify that host "(.+)" is in "(.+)" status on host summary page$/ do |host,state|
on StatusviewerPage do |page|
page.verify_hoststatus_hostsummary(state)
end
end
Then /^verify that host "(.+)" is in "(.+)","(.+)" status on Entire Network page$/ do |host,state,index|
on StatusviewerPage do |page|
page.verify_hoststatus_entire_network(host,state,index)
end
end
Then /^verify that host "(.+)" is in "(.+)" status on Hostgroup summary page$/ do |host,state|
on StatusviewerPage do |page|
page.verify_hoststatus_hostgroup(host,state)
end
end
Then /^verify that host "(.+)" is in "(.+)" status on Event Console page$/ do |host,state|
visit EventconsolePage
on EventconsolePage do |page|
page.verify_hoststatus_eventconsole(host,state)
end
end
Then /^verify that host is in "(.+)" state on Nagios Host Status Details page$/ do |state|
visit NagiosHostStatusDetailsPage
on NagiosHostStatusDetailsPage do |page|
sleep(5)
page.localhost_element.when_present.click
sleep(3)
@browser.td(:class => /stateInfoPanel/).td(:class => /stateInfoTable1/).div(:text => state).exists? == true
end
end
When /^disable "(.+)" for the host$/ do |option|
on StatusviewerPage do |page|
if option == "notification"
page.notification_element.when_present(100).click
page.disable_notification_element.when_dom_changed.click
elsif option == "active checks"
page.settings_element.when_present(100).click
page.disable_active_check_element.flash
page.disable_active_check_element.when_dom_changed.click
elsif option == "passive checks"
page.settings_element.when_dom_changed.click
page.disable_passive_check_host_element.when_dom_changed.click
elsif option == "flap detection"
page.settings_element.when_present(100).click
page.disable_flap_detection_host_element.when_dom_changed.click
elsif option == "event handler"
page.event_handlers_dropdown_element.when_dom_changed.click
page.disable_event_handlers_host_element.when_dom_changed.click
end
page.submit_button_element.when_present.click
sleep(100)
end
end
Then /^verify that "(.+)" are disabled for "(.+)"$/ do |option,host|
on StatusviewerPage do |page|
if option == "notifications"
visit StatusviewerPage
page.linux_servers_element.when_present.click
page.localhost_element.when_present.click
@browser.link(:text => /Enable Notifications/).when_dom_changed.exists?.should == true
page.navigate_entire_network
page.verify_notification_disable_entire_network(host)
visit NagiosHostStatusDetailsPage
on NagiosHostStatusDetailsPage do |page|
page.localhost_element.when_present.click
@browser.frame(:id => /myframe/).td(:text => /Notifications:/).div(:class => /checksDISABLED/).exists?.should == true
end
elsif option == "active checks"
page.verify_disable_active_check_host_summary_element.when_dom_changed.exists?.should == true
visit NagiosHostStatusDetailsPage
on NagiosHostStatusDetailsPage do |page|
page.localhost_element.when_present.click
@browser.frame(:id => /myframe/).td(:text => /Active Checks:/).div(:class => /checksDISABLED/).exists?.should == true
end
elsif option == "passive checks"
visit NagiosHostStatusDetailsPage
on NagiosHostStatusDetailsPage do |page|
page.localhost_element.when_present.click
@browser.frame(:id => /myframe/).td(:text => /Passive Checks:/).div(:class => /checksDISABLED/).exists?.should == true
end
elsif option == "flap detection"
visit NagiosHostStatusDetailsPage
on NagiosHostStatusDetailsPage do |page|
page.localhost_element.when_present.click
@browser.frame(:id => /myframe/).div(:class => /flapdetectionDISABLED/).exists?.should == true
end
elsif option == "event handler"
visit NagiosHostStatusDetailsPage
on NagiosHostStatusDetailsPage do |page|
page.localhost_element.when_present.click
@browser.frame(:id => /myframe/).div(:class => /eventhandlersDISABLED/).exists?.should == true
end
end
end
end
When /^enable "(.+)" for the host$/ do |option|
on StatusviewerPage do |page|
if option == "notification"
page.notification_element.when_present(100).click
page.enable_notification_element.when_dom_changed.click
elsif option == "active checks"
page.settings_element.when_present.click
page.enable_active_check_element.flash
page.enable_active_check_element.when_dom_changed.click
elsif option == "passive checks"
page.settings_element.when_present(100).click
page.enable_passive_check_host_element.flash
page.enable_passive_check_host_element.when_dom_changed.click
elsif option == "flap detection"
page.settings_element.when_present.click
page.enable_flap_detection_host_element.when_dom_changed.click
elsif option == "event handler"
page.event_handlers_dropdown_element.when_dom_changed.click
page.enable_event_handlers_host_element.when_dom_changed.click
elsif option == "reschedule next check"
page.check_results_element.when_present(100).click
page.reschedule_next_check_element.when_present(100).click
sleep(4)
page.next_check_time = "12/30/2014 2:03:43"
page.force_check_element.when_present.check
end
page.submit_button_element.when_present.click
sleep(100)
end
end
Then /^verify that "(.+)" are enabled for "(.+)"$/ do |option,host|
on StatusviewerPage do |page|
if option == "notification"
page.verify_notification_enable_host_summary
page.navigate_entire_network
page.verify_notification_enable_entire_network(host)
visit NagiosHostStatusDetailsPage
on NagiosHostStatusDetailsPage do |page|
page.localhost_element.when_present.click
@browser.frame(:id => /myframe/).td(:text => /Notifications:/).div(:class => /checksENABLED/).exists?.should == true
end
elsif option == "active checks"
page.verify_enable_active_check_host_summary_element.exists?.should == true
visit NagiosHostStatusDetailsPage
on NagiosHostStatusDetailsPage do |page|
page.localhost_element.when_present.click
@browser.frame(:id => /myframe/).td(:text => /Active Checks:/).div(:class => /checksENABLED/).exists?.should == true
end
elsif option == "passive checks"
visit NagiosHostStatusDetailsPage
on NagiosHostStatusDetailsPage do |page|
page.localhost_element.when_present.click
@browser.frame(:id => /myframe/).td(:text => /Passive Checks:/).div(:class => /checksENABLED/).exists?.should == true
end
elsif option == "flap detection"
visit NagiosHostStatusDetailsPage
on NagiosHostStatusDetailsPage do |page|
page.localhost_element.when_present.click
@browser.frame(:id => /myframe/).div(:class => /flapdetectionENABLED/).exists?.should == true
end
elsif option == "event handler"
visit NagiosHostStatusDetailsPage
on NagiosHostStatusDetailsPage do |page|
page.localhost_element.when_present.click
@browser.frame(:id => /myframe/).div(:class => /eventhandlersENABLED/).exists?.should == true
end
elsif option == "reschedule next check"
@browser.span(:text => '12/30/2014 10:39:01 PM').exists?.should == true
end
end
end
When /^I goto search tab$/ do
on StatusviewerPage do |page|
@browser.link(:name => /frmTree:pnlTbSet:0.2/).td(:text => /Search/).when_present.click
sleep(2)
end
end
When /^enter host name "(.+)" to be searched$/ do |hostname|
on StatusviewerPage do |page|
page.search_box = hostname
page.go_search_element.when_present.click
sleep(5)
end
end
Then /^verify that "(.+)" is displayed as a search result$/ do |hostname|
on StatusviewerPage do |page|
@browser.link(:id => /frmTree:pnlTbSet:0:STtblResults:0:lnkSearchNdClick/).span(:text => hostname).exists?.should == true
end
end
Then /^last check time for "(.+)" should be displayed$/ do |option|
on StatusviewerPage do |page|
if option == "host"
page.host_last_check_element.exists?.should ==true
b = @browser.windows.size
puts b
elsif option == "service"
page.service_local_cpu_element.when_present.click
sleep(3)
page.service_last_check_element.exists?.should ==true
end
end
end
When /^I select host availabilty portlet$/ do
on StatusviewerPage do |page|
page.host_availability_portlet_element.when_present(100).click
sleep(5)
end
end
When /^select custom date-time$/ do
on StatusviewerPage do |page|
@browser.select(:id => /HVform:HAmenuTimeSelector/).select('Custom Date-Time')
end
end
Then /^calendar should be displayed and date-time should be editable$/ do
on StatusviewerPage do |page|
page.start_time_host_portlet = '02/26/2014 00:08'
page.end_time_host_portlet = '03/29/2014 23:09'
page.apply_host_portlet_element.when_present.click
page.calendar_img1_element.when_dom_changed.click
page.start_date_element.when_present.click
page.calendar_img2_element.when_dom_changed.click
page.end_date_element.when_present.click
page.apply_host_portlet_element.when_present.click
end
end
When /^click acknowledge button and fill details "(.+)"$/ do |comment|
on StatusviewerPage do |page|
page.acknowledge_element.when_present(100).click
sleep(2)
page.acknowledge_host_element.when_dom_changed.click
sleep(7)
page.services_ack_element.when_present(10).set
page.acknowledge_comment = comment
sleep(3)
page.submit_ack_element.when_present.click
end
end
Then /^verify that comment "(.+)" is "(.+)" on host portlet under events tab,comments section and hostgroup page$/ do |comment,action|
on StatusviewerPage do |page|
if action == 'updated'
@browser.span(:text => /Events/).when_dom_changed.click
@browser.table(:id => 'HVform:tbleventTableID').span(:text => comment).exists?.should == true
@browser.span(:text => /Events/).when_dom_changed.click
@browser.span(:text => /Comments/).when_dom_changed.click
@browser.table(:id => 'HVform:CPtblComments').span(:text => comment).wait_until_present
Watir::Wait.until { @browser.table(:id => 'HVform:CPtblComments').span(:text => comment).exists?.should == true }
@browser.table(:id => 'HVform:CPtblComments').span(:text => comment).exists?.should == true
@browser.span(:text => /Linux Servers/).when_present.click
@browser.span(:text => /Events, Nagios Statistics & Host List/).when_present(100).click
@browser.table(:id => 'HGVform:hostgrouptableID').span(:text => comment).wait_until_present
@browser.table(:id => 'HGVform:hostgrouptableID').span(:text => comment).exists?.should == true
elsif action == 'deleted'
visit StatusviewerPage
sleep(15)
page.select_hostname("localhost")
@browser.span(:text => /Events/).when_dom_changed.click
@browser.table(:id => 'HVform:tbleventTableID').span(:text => comment).exists?.should == false
@browser.span(:text => /Events/).when_dom_changed.click
@browser.span(:text => /Comments/).when_dom_changed.click
@browser.table(:id => 'HVform:CPtblComments').span(:text => comment).exists?.should == false
@browser.span(:text => /Linux Servers/).when_present.click
@browser.span(:text => /Events, Nagios Statistics & Host List/).when_present(100).click
@browser.table(:id => 'HGVform:hostgrouptableID').span(:text => comment).exists?.should == false
end
end
end
When /^remove the comment added$/ do
on StatusviewerPage do |page|
@browser.span(:text => /Comments/).wait_until_present
@browser.span(:text => /Comments/).when_dom_changed.click
page.delete_comment_element.when_present(100).click
page.commit_element.when_present(100).click
sleep(10)
end
end
Then /^verify that comment "(.+)" is "(.+)" on nagios page$/ do |comment,action|
visit NagiosHostStatusDetailsPage
on NagiosHostStatusDetailsPage do |page|
if action == 'updated'
sleep(20)
page.localhost_element.when_present.click
@browser.frame(:id => /myframe/).td(:text => comment).exists?.should == true
elsif action == 'deleted'
page.localhost_element.when_present.click
@browser.frame(:id => /myframe/).td(:text => comment).exists?.should == false
end
end
end
When /^set service "(.+)" of this host to "(.+)" state$/ do |service,state|
on StatusviewerPage do |page|
@browser.span(:text => /#{service}/).when_present.click
sleep(5)
page.submit_check_results_service(state)
sleep(15)
end
end
Then /^verify "(.+)" appears on service page under comment portlet$/ do |comment|
on StatusviewerPage do |page|
@browser.span(:text => /#{comment}/).exists?.should == true
end
end
Then /^I select Entire Network tab$/ do
on StatusviewerPage do |page|
@browser.link(:id => /frmNavigationTabset:icePnlTbSet:0:icePnlTabClick/).span(:text => /Entire Network/).when_dom_changed.click
end
end
Then /^verify if notifications have been enabled globally$/ do
on StatusviewerPage do |page|
@browser.wait_until(450) do
@browser.table(:id => /frmNV:nagiosPortlet_panelgridNotifications/).tr(:class => /icePnlGrdRow Row iceDatTbl_typERow iceDatTblRow1_typE/).td(:id => /frmNV:nagiosPortlet_panelgridNotifications-0-0/, :class => /icePnlGrdCol Col iceDatTbl_typECol iceDatTblCol1_typE/).span(:text => /Disabled/).exists?.should == false
end
end
end
Then /^verify if notifications have been disabled globally$/ do
on StatusviewerPage do |page|
@browser.table(:id => /frmNV:nagiosPortlet_panelgridNotifications/).tr(:class => /icePnlGrdRow Row iceDatTbl_typERow iceDatTblRow1_typE/).td(:id => /frmNV:nagiosPortlet_panelgridNotifications-0-0/, :class => /icePnlGrdCol Col iceDatTbl_typECol iceDatTblCol1_typE/).span(:text => /Disabled/).exists?.should == true
end
end
Then /^verify if Flap Detection has been enabled globally$/ do
on StatusviewerPage do |page|
@browser.table(:id => /frmNV:nagiosPortlet_panelgridFlapDetection/).tr(:class => /icePnlGrdRow Row iceDatTbl_typERow iceDatTblRow1_typE/).td(:id => /frmNV:nagiosPortlet_panelgridFlapDetection-0-0/, :class => /icePnlGrdCol Col iceDatTbl_typECol iceDatTblCol1_typE/).span(:text => /Disabled/).exists?.should == false
end
end
Then /^verify if Flap Detection has been disabled globally$/ do
on StatusviewerPage do |page|
@browser.table(:id => /frmNV:nagiosPortlet_panelgridFlapDetection/).tr(:class => /icePnlGrdRow Row iceDatTbl_typERow iceDatTblRow1_typE/).td(:id => /frmNV:nagiosPortlet_panelgridFlapDetection-0-0/, :class => /icePnlGrdCol Col iceDatTbl_typECol iceDatTblCol1_typE/).span(:text => /Disabled/).exists?.should == true
end
end
Then /^I select the Groups for this Hosts link$/ do
on StatusviewerPage do |page|
page.group_for_host_element.when_dom_changed.click
end
end
Then /^the hostgroup is displayed$/ do
on StatusviewerPage do |page|
page.group_for_host_linuxservers_element.exists?.should == true
end
end
Then /^I close the Groups for this host window$/ do
on StatusviewerPage do |page|
page.close_window_element.when_present.click
end
end
Then /^I select a service "(.+)" of host "(.+)" on status viewer page$/ do |service,host|
@browser.refresh()
on StatusviewerPage do |page|
sleep(10)
page.linux_servers_element.when_present.click
@browser.span(:text => host).when_present.click
sleep(2)
@browser.span(:text => service).when_present.click
end
end
When /^then submit passive check result for service with "(.+)"$/ do |state|
on StatusviewerPage do |page|
sleep(25)
page.submit_check_results_service(state)
sleep(50)
end
end
When /^verify that service "(.+)" is in "(.+)" status on Entire Network page$/ do |service,state|
on StatusviewerPage do |page|
visit StatusviewerPage
sleep(25)
if state == "CRITICAL"
Watir::Wait.until{
@browser.table(:id => 'frmNV:tblServiceStatistics').link(:text => /Critical:UnScheduled/).exists?.should == true
}
@browser.table(:id => 'frmNV:tblServiceStatistics').link(:text => /Critical:UnScheduled/).when_dom_changed.click
=begin
@browser.table(:id => /frmNV:servicestatusportlet_PanelMain-0-1/).link(:text => /Critical:UnScheduled/).exists?.should == true
}
@browser.table(:id => /frmNV:servicestatusportlet_PanelMain-0-1/).link(:text => /Critical:UnScheduled/).when_dom_changed.click
=end
elsif state == "WARNING"
Watir::Wait.until{
@browser.table(:id => 'frmNV:tblServiceStatistics').link(:text => /Warning/).exists?.should == true
}
@browser.table(:id => 'frmNV:tblServiceStatistics').link(:text => /Warning/).when_dom_changed.click
elsif state == "UNKNOWN"
Watir::Wait.until{
@browser.table(:id => 'frmNV:tblServiceStatistics').link(:text => /Unknown/).exists?.should == true
}
@browser.table(:id => 'frmNV:tblServiceStatistics').link(:text => /Unknown/).when_dom_changed.click
elsif state == "OK"
Watir::Wait.until{
@browser.table(:id => 'frmNV:tblServiceStatistics').link(:text => /Ok/).exists?.should == true
}
@browser.table(:id => 'frmNV:tblServiceStatistics').link(:text => /Ok/).when_dom_changed.click
end
sleep(10)
@browser.div(:id => 'frmNV:pnlpopupService').table(:id => 'frmNV:tblServiceListDatatable').span(:text => service).when_present.click
sleep(10)
end
end
When /^verify that service is in "(.+)" status on Service Summary page$/ do |state|
on StatusviewerPage do |page|
sleep(30)
if state == "CRITICAL"
@browser.span(:id => /SVform:SHtxtServiceState/, :text => /Unscheduled Critical/).when_dom_changed.exists?.should == true
@browser.img(:src => /service-red.gif/).wait_until_present(180)
elsif state == "WARNING"
@browser.span(:id => /SVform:SHtxtServiceState/, :text => /Warning/).when_dom_changed.exists?.should == true
@browser.img(:src => /service-yellow.gif/).wait_until_present(180)
elsif state == "UNKNOWN"
@browser.span(:id => /SVform:SHtxtServiceState/, :text => /Unknown/).when_dom_changed.exists?
@browser.img(:src => /service-gray.gif/).wait_until_present(180)
elsif state == "OK"
@browser.span(:id => /SVform:SHtxtServiceState/, :text => /Ok/).when_dom_changed.exists?
@browser.img(:src => /service-green.gif/).wait_until_present(180)
end
end
end
Then /^I navigate to "(.+)" "(.+)" Nagios service page$/ do |host,service|
on StatusviewerPage do |page|
page.navigate_service_page_nagios(host,service)
end
end
When /^verify that service is in "(.+)" status on Nagios service page$/ do |state|
if state == "CRITICAL"
@browser.div(:class => /serviceCRITICAL/, :text => /CRITICAL/).when_present(45).exists?
end
if state == "WARNING"
@browser.div(:class => /serviceWARNING/, :text => /WARNING/).when_present(45).exists?
end
if state == "UNKNOWN"
@browser.div(:class => /serviceUNKNOWN/, :text => /UNKNOWN/).when_present(45).exists?
end
if state == "OK"
@browser.div(:class => /serviceOK/, :text => /OK/).when_present(45).exists?
end
end
Then /^I select the Services tab on Status Viewer$/ do
on StatusviewerPage do |page|
page.services_tab_element.when_present.click
end
end
Then /^I select a service group "(.+)" on status viewer page$/ do |service_group|
on StatusviewerPage do |page|
@browser.span(:text => service_group).when_present.click
sleep(5)
end
end
When /^verify that service "(.+)" is in "(.+)" status on Servicegroup Summary page$/ do |service,state|
on StatusviewerPage do |page|
if state == "CRITICAL"
@browser.span(:id => /SGVform:SGHSGHtxtHostState/, :text => /Unscheduled Critical/).when_dom_changed.exists?
@browser.div(:id => /SGVform:frmServicefrom_panelsgrpError1/).link(:text => /Critical:UnScheduled/).when_dom_changed.click
sleep(2)
@browser.span(:text => service).exists?
@browser.button(:name => /SGVform:cmdCloseWindow/).when_present.click
sleep(2)
page.check_event_service_group_summary_page(service)
end
if state == "WARNING"
@browser.span(:id => /SGVform:SGHSGHtxtHostState/, :text => /Warning/).when_dom_changed.exists?
@browser.link(:text => /Warning/).when_dom_changed.click
sleep(2)
@browser.span(:text => service).exists?
@browser.button(:name => /SGVform:cmdCloseWindow/).when_present.click
sleep(2)
page.check_event_service_group_summary_page(service)
end
if state == "UNKNOWN"
@browser.span(:id => /SGVform:SGHSGHtxtHostState/, :text => /Unknown/).when_dom_changed.exists?
@browser.link(:text => /Unknown/).when_dom_changed.click
sleep(2)
@browser.span(:text => service).exists?
@browser.button(:name => /SGVform:cmdCloseWindow/).when_present.click
sleep(2)
page.check_event_service_group_summary_page(service)
end
if state == "OK"
@browser.span(:id => /SGVform:SGHSGHtxtHostState/, :text => /Ok/).when_dom_changed.exists?
@browser.link(:text => /Ok/).when_dom_changed.click
sleep(2)
@browser.span(:text => service).exists?
@browser.button(:name => /SGVform:cmdCloseWindow/).when_present.click
sleep(2)
page.check_event_service_group_summary_page(service)
end
end
end
When /^I select the "(.+)" downtime option with comment "(.+)" and time "(.+)"$/ do |option,comment,time|
on StatusviewerPage do |page|
page.downtime_service(option,comment,time)
sleep(30)
end
end
Then /^verify that service "(.+)" of host "(.+)" is in "(.+)" downtime$/ do |service,host,option|
on StatusviewerPage do |page|
if option=='Fixed'
@browser.span(:id => /SVform:SItxtServiceDowntimeValue/, :text => /Yes/).when_dom_changed.exists?
@browser.span(:text => /This service has been scheduled for fixed downtime/).when_dom_changed.exists?
page.navigate_service_page_nagios(host,service)
@browser.div(:class => /downtimeACTIVE/, :text => /YES/).when_dom_changed.exists?
@browser.td(:class => /commentOdd/, :text => /This service has been scheduled for fixed downtime/).when_dom_changed.exists?
else
@browser.span(:text => /This service has been scheduled for flexible downtime/).when_dom_changed.exists?
page.navigate_service_page_nagios(host,service)
@browser.td(:class => /commentOdd/, :text => /This service has been scheduled for flexible downtime/).when_dom_changed.exists?
end
end
end
When /^I disable notifications of the service$/ do
on StatusviewerPage do |page|
@browser.span(:text => /Notifications/).when_present.click
@browser.span(:text => /Disable Notifications/).when_present.click
sleep(2)
@browser.button(:name => /SVform:actionsPortlet_btnSubmit/).click
sleep(30)
end
end
Then /^I verify notifications of service "(.+)" in sg "(.+)" of host "(.+)" have been disabled$/ do |service,sg,host|
on StatusviewerPage do |page|
page.services_tab_element.when_present.click
page.select_service_group(sg)
@browser.table(:id => /SGVform:stackedNagiosPortlet_panelgridNotifications/).link(:text => /Disabled Services/).when_present.click
sleep(2)
@browser.span(:text => service).exists?
puts "1. SG -> verified with "[email protected](:text => service).text
@browser.button(:value => /Close Window/).click
page.linux_servers_element.when_present.click
sleep(2)
@browser.span(:text => /Events, Nagios Statistics & Host List/).when_present.click
sleep(3)
@browser.table(:id => /HGVform:nagiosPortlet_panelgridNotifications/).link(:text => /Disabled Services/).when_present.click
sleep(2)
@browser.span(:text => service).exists?
puts "2. HG -> verified with "[email protected](:text => service).text
@browser.button(:value => /Close Window/).click
@browser.span(:text => /Events, Nagios Statistics & Host List/).when_present.click
@browser.link(:id => /frmNavigationTabset:icePnlTbSet:0:icePnlTabClick/).span(:text => /Entire Network/).when_present.click
sleep(3)
@browser.table(:id => /frmNV:nagiosPortlet_panelgridNotifications/).link(:text => /Disabled Services/).when_present.click
sleep(2)
@browser.span(:text => service).exists?
puts "3. HG -> verified with "[email protected](:text => service).text
@browser.button(:value => /Close Window/).click
page.navigate_service_page_nagios(host,service)
@browser.div(:class => /notificationsDISABLED/, :text => /DISABLED/).exists?
puts "4. Nagios -> "[email protected](:class => /notificationsDISABLED/, :text => /DISABLED/).text
end
end
Then /^I acknowledge the service problem$/ do
on StatusviewerPage do |page|
sleep(65)
@browser.span(:text => /Acknowledge/).click
sleep(1)
@browser.span(:text => /Acknowledge Problem/).click
sleep(1)
@browser.textarea(:name => /SVform:actionsPortlet_txtComment/, :id => /SVform:actionsPortlet_txtComment/).set "Ack sent by QA"
@browser.button(:name => /SVform:actionsPortlet_btnSubmit/).click
end
end
When /^I enable notifications of the service$/ do
on StatusviewerPage do |page|
@browser.span(:text => /Notifications/).when_present.click
@browser.span(:text => /Enable Notifications/).when_present.click
sleep(2)
@browser.button(:name => /SVform:actionsPortlet_btnSubmit/).click
sleep(20)
end
end
Then /^I verify notifications of service "(.+)" in sg "(.+)" of host "(.+)" have been enabled$/ do |service,sg,host|
on StatusviewerPage do |page|
page.services_tab_element.when_present.click
@browser.span(:text => sg).when_present.click
@browser.td(:id => /SGVform:SGVpanel4-0-0/).link(:text => /Ok/).when_present.click
sleep(2)
@browser.span(:text => service).exists?
puts "1. Verified on SG summary page: "[email protected](:text => service).text
@browser.button(:value => /close window/).click
page.linux_servers_element.when_present.click
sleep(2)
@browser.table(:id => /HGVform:HGVpanel8/).link(:text => /Ok/).when_present.click
sleep(2)
@browser.span(:text => service).exists?
puts "2. Verified on HG summary page: "[email protected](:text => service).text
@browser.button(:value => /close window/, :name => /HGVform:cmdCloseWindow/).click
@browser.link(:id => /frmNavigationTabset:icePnlTbSet:0:icePnlTabClick/).span(:text => /Entire Network/).when_present.click
sleep(3)
@browser.table(:id => /frmNV:networkViewPortlet_panel5/).link(:text => /Ok/).when_present.click
sleep(2)
@browser.span(:text => service).exists?
puts "3. Verified on Entire Network page: "[email protected](:text => service).text
@browser.button(:value => /close window/, :name => /frmNV:cmdCloseWindow/).click
page.navigate_service_page_nagios(host,service)
@browser.div(:class => /notificationsENABLED/, :text => /ENABLED/).exists?
puts "4. Nagios -> "[email protected](:class => /notificationsENABLED/, :text => /ENABLED/).text
end
end
When /^I disable flap detection of the service$/ do
on StatusviewerPage do |page|
@browser.span(:text => /Settings/).when_present.click
@browser.span(:text => /Disable Flap Detection/).when_present.click
sleep(2)
@browser.button(:value => /Submit/, :name => /SVform:actionsPortlet_btnSubmit/).click
end
end
Then /^I verify flap detection of service "(.+)" in sg "(.+)" of host "(.+)" have been disabled$/ do |service,sg,host|
on StatusviewerPage do |page|
page.navigate_service_page_nagios(host,service)
@browser.div(:class => /flapdetectionDISABLED/, :text => /DISABLED/).exists?
end
end
When /^I enable flap detection of the service$/ do
on StatusviewerPage do |page|
@browser.span(:text => /Settings/).when_present.click
@browser.span(:text => /Enable Flap Detection/).when_present.click
sleep(2)
@browser.button(:value => /Submit/, :name => /SVform:actionsPortlet_btnSubmit/).click
end
end
Then /^I verify flap detection of service "(.+)" in sg "(.+)" of host "(.+)" have been enabled$/ do |service,sg,host|
on StatusviewerPage do |page|
page.navigate_service_page_nagios(host,service)
@browser.div(:class => /flapdetectionENABLED/, :text => /ENABLED/).exists?
end
end
When /^I disable active checks of the service$/ do
on StatusviewerPage do |page|
@browser.span(:text => /Settings/).when_present.click
@browser.span(:text => /Disable Active Checks on Service/).when_present.click
sleep(2)
@browser.button(:value => /Submit/).click
end
end
Then /^I verify active checks of service "(.+)" in sg "(.+)" of host "(.+)" have been disabled$/ do |service,sg,host|
on StatusviewerPage do |page|
page.navigate_service_page_nagios(host,service)
@browser.div(:class => /checksDISABLED/, :text => /DISABLED/).exists?
puts "1. Nagios -> "[email protected](:class => /checksDISABLED/, :text => /DISABLED/).text
visit StatusviewerPage
page.linux_servers_element.when_present.click
sleep(2)
@browser.span(:text => /Events, Nagios Statistics & Host List/).when_present.click
sleep(2)
@browser.table(:id => /HGVform:nagiosPortlet_panelgridActiveChecks/).link(:text => /Disabled Service/).when_present.click
sleep(2)
@browser.span(:text => service).exists?
puts "2. Verified on HG summary page: "[email protected](:text => service).text
@browser.button(:value => /Close Window/, :name => /HGVform:nagiosPortlet_btnClose/).click
@browser.span(:text => /Events, Nagios Statistics & Host List/).when_present.click
page.services_tab_element.when_present.click
@browser.span(:text => sg).when_present.click
@browser.table(:id => /SGVform:stackedNagiosPortlet_panelgridActiveChecks/).link(:text => /Disabled Service/).when_present.click
sleep(2)
@browser.span(:text => service).exists?
puts "3. Verified on SG summary page: "[email protected](:text => service).text
@browser.button(:value => /Close Window/).click
@browser.link(:id => /frmNavigationTabset:icePnlTbSet:0:icePnlTabClick/).span(:text => /Entire Network/).when_present.click
sleep(3)
@browser.table(:id => /frmNV:nagiosPortlet_panelgridActiveChecks/).link(:text => /Disabled Service/).when_present.click
sleep(2)
@browser.span(:text => service).exists?
puts "4. Verified on Entire Network page: "[email protected](:text => service).text
@browser.button(:value => /Close Window/, :name => /frmNV:nagiosPortlet_btnClose/).click
end
end
When /^I enable active checks of the service$/ do
on StatusviewerPage do |page|
@browser.span(:text => /Settings/).when_present.click
@browser.span(:text => /Enable Active Checks on Service/).when_present.click
sleep(2)
@browser.button(:value => /Submit/, :name => /SVform:actionsPortlet_btnSubmit/).click
end
end
Then /^I verify active checks of service "(.+)" in sg "(.+)" of host "(.+)" have been enabled$/ do |service,sg,host|
on StatusviewerPage do |page|
page.navigate_service_page_nagios(host,service)
@browser.div(:class => /checksENABLED/, :text => /ENABLED/).exists?
puts "Nagios -> "[email protected](:class => /checksENABLED/, :text => /ENABLED/).text
end
end
When /^I disable passive checks of the service$/ do
on StatusviewerPage do |page|
@browser.span(:text => /Settings/).when_present.click
@browser.span(:text => /Disable Passive Checks/).when_present.click
sleep(2)
@browser.button(:value => /Submit/, :name => /SVform:actionsPortlet_btnSubmit/).click
end
end
Then /^I verify passive checks of service "(.+)" in sg "(.+)" of host "(.+)" have been disabled$/ do |service,sg,host|
on StatusviewerPage do |page|
page.navigate_service_page_nagios(host,service)
@browser.div(:class => /checksDISABLED/, :text => /DISABLED/).exists?
puts "1. Nagios -> "[email protected](:class => /checksDISABLED/, :text => /DISABLED/).text
visit StatusviewerPage
page.linux_servers_element.when_present.click
sleep(2)
@browser.span(:text => /Events, Nagios Statistics & Host List/).when_present.click
sleep(2)
@browser.table(:id => /HGVform:nagiosPortlet_panelgridPassiveChecks/).link(:text => /Disabled Service/).when_present.click
sleep(2)
@browser.span(:text => service).exists?
puts "2. Verified on HG summary page: "[email protected](:text => service).text
@browser.button(:value => /Close Window/, :name => /HGVform:nagiosPortlet_btnClose/).click
@browser.span(:text => /Events, Nagios Statistics & Host List/).when_present.click
page.services_tab_element.when_present.click
@browser.span(:text => sg).when_present.click
@browser.table(:id => /SGVform:stackedNagiosPortlet_panelgridPassiveChecks/).link(:text => /Disabled Service/).when_present.click
sleep(2)
@browser.span(:text => service).exists?
puts "3. Verified on SG summary page: "[email protected](:text => service).text
@browser.button(:value => /Close Window/).click
@browser.link(:id => /frmNavigationTabset:icePnlTbSet:0:icePnlTabClick/).span(:text => /Entire Network/).when_present.click
sleep(3)
@browser.table(:id => /frmNV:nagiosPortlet_panelgridPassiveChecks/).link(:text => /Disabled Service/).when_present.click
sleep(2)
@browser.span(:text => service).exists?
puts "4. Verified on Entire Network page: "[email protected](:text => service).text
@browser.button(:value => /Close Window/, :name => /frmNV:nagiosPortlet_btnClose/).click
end
end
When /^I enable passive checks of the service$/ do
on StatusviewerPage do |page|
@browser.span(:text => /Settings/).when_present.click
@browser.span(:text => /Enable Passive Checks/).when_present.click
sleep(2)
@browser.button(:value => /Submit/, :name => /SVform:actionsPortlet_btnSubmit/).click
end
end
Then /^I verify passive checks of service "(.+)" in sg "(.+)" of host "(.+)" have been enabled$/ do |service,sg,host|
on StatusviewerPage do |page|
page.navigate_service_page_nagios(host,service)
@browser.div(:class => /checksENABLED/, :text => /ENABLED/).exists?
puts "Nagios -> "[email protected](:class => /checksENABLED/, :text => /ENABLED/).text
end
end
When /^I select service group "(.+)" on status viewer page$/ do |sg|
on StatusviewerPage do |page|
page.services_tab_element.when_present(60).click
@browser.span(:text => sg).when_present(60).click
sleep(2)
end
end
When /^I schedule "(.+)" downtime for all services with comment "(.+)" and time "(.+)"$/ do |option,comment,time|
on StatusviewerPage do |page|
page.downtime_element.when_present.click
@browser.span(:text => /Schedule Downtime For All Services/).click
sleep(3)
@browser.textarea(:name => /SGVform:actionsPortlet_txtComment/).set comment
@browser.select(:name => /SGVform:actionsPortlet_menuType/).select option
if option == 'Flexible'
@browser.text_field(:name => /SGVform:actionsPortlet_txtHours/).set time
@browser.text_field(:name => /SGVform:actionsPortlet_txtMinutes/).set time
elsif option == 'Fixed'
# in Fixed Downtime the time cannot be set.
end
@browser.button(:name => /SGVform:actionsPortlet_btnSubmit/).when_present.click
sleep(20)
end
end
Then /^I verify "(.+)" downtime of the service "(.+)" of host "(.+)"$/ do |option,service,host|
on StatusviewerPage do |page|
sleep(15)
@browser.link(:name => /frmTree:pnlTbSet:0.0/).when_present.click
sleep(15)
page.select_hostname(host)
page.select_service(service)
sleep(2)
if option=='Fixed'
@browser.span(:id => /SVform:SItxtServiceDowntimeValue/, :text => /Yes/).when_dom_changed.exists?
@browser.span(:text => /This service has been scheduled for fixed downtime/).when_dom_changed.exists?
page.navigate_service_page_nagios(host,service)
@browser.div(:class => /downtimeACTIVE/, :text => /YES/).when_present(150).exists?
@browser.td(:class => /commentOdd/, :text => /This service has been scheduled for fixed downtime/).when_present(150).exists?
elsif option=='Flexible'
@browser.span(:text => /This service has been scheduled for flexible downtime/).when_dom_changed.exists?
page.navigate_service_page_nagios(host,service)
@browser.td(:class => /commentOdd/, :text => /This service has been scheduled for flexible downtime/).when_present(150).exists?
end
end
end
When /^I "(.+)" notifications of all services$/ do |state|
on StatusviewerPage do |page|
sleep(3)
@browser.span(:text => /Notifications/).when_present(45).click
sleep(1)
if state == "disable"
@browser.span(:text => /Disable notifications for all Services/).click
elsif state == "enable"
@browser.span(:text => /Enable notifications for all Services/).click
end
sleep(3)
@browser.button(:value => /Submit/).click
sleep(25)
end
end
Then /^I verify notifications of service "(.+)" of host "(.+)" have been "(.+)"$/ do |service,host,option|
on StatusviewerPage do |page|
page.navigate_service_page_nagios(host,service)
if option=="disabled"
@browser.div(:class => /notificationsDISABLED/, :text => /DISABLED/).when_present(45).exists?
puts "Nagios -> "[email protected](:class => /notificationsDISABLED/, :text => /DISABLED/).text
elsif option=="enabled"
@browser.div(:class => /notificationsENABLED/, :text => /ENABLED/).when_present(60).exists?
puts "Nagios -> "[email protected](:class => /notificationsENABLED/, :text => /ENABLED/).text
end
end
end
When /^I "(.+)" active checks of all services of the "(.+)"$/ do |state,group|
on StatusviewerPage do |page|
sleep(3)
@browser.span(:text => /Settings/).when_present(45).click
sleep(2)
if state == "disable"
@browser.span(:text => /Disable Active Checks for all Services/).click
else state == "enable"
@browser.span(:text => /Enable Active Checks for all Services/).click
end
sleep(3)
@browser.button(:value => /Submit/).click
sleep(70)
end
end
Then /^I verify active checks of service "(.+)" of host "(.+)" have been "(.+)"$/ do |service,host,option|
on StatusviewerPage do |page|
if option=="disabled"
page.navigate_service_page_nagios(host,service)
@browser.div(:class => /checksDISABLED/, :text => /DISABLED/).when_present(45).exists?
#puts "Nagios -> "[email protected](:class => /checksDISABLED/, :text => /DISABLED/).text
puts "Nagios -> DISABLED"
elsif option=="enabled"
page.navigate_service_page_nagios("qa-ubuntu-12-4-64","local_cpu_httpd")
@browser.div(:class => /checksENABLED/, :text => /ENABLED/).exists?
#puts "Nagios -> "[email protected](:class => /checksENABLED/, :text => /ENABLED/).text
puts "Nagios -> ENABLED"
end
end
end
Given /^I add the host "(.+)" to the new host group$/ do |host|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /members_nonmembers/).select host
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /members_add_member/).click
end
Then /^I select a hostgroup "(.+)" on status viewer page$/ do |hostgroup|
on StatusviewerPage do |page|
@browser.span(:text => hostgroup).when_present.click
end
end
When /^I schedule "(.+)" downtime for all "(.+)" with comment "(.+)" and time "(.+)"$/ do |option,object,comment,time|
on StatusviewerPage do |page|
page.downtime_element.when_present(45).click
if object == "hosts"
@browser.span(:text => /Schedule Downtime For All Hosts/).click
elsif object == "services"
@browser.span(:text => /Schedule Downtime For All Services/).click
end
sleep(3)
@browser.textarea(:name => /HGVform:actionsPortlet_txtComment/).set comment
@browser.select(:name => /HGVform:actionsPortlet_menuType/).select option
if option == 'Flexible'
@browser.text_field(:name => /HGVform:actionsPortlet_txtHours/).set time
@browser.text_field(:name => /HGVform:actionsPortlet_txtMinutes/).set time
elsif option == 'Fixed'
# in Fixed Downtime the time cannot be set.
end
@browser.button(:name => /HGVform:actionsPortlet_btnSubmit/).when_present.click
sleep(30)
end
end
Then /^I verify "(.+)" downtime for the host "(.+)"$/ do |option,host|
on StatusviewerPage do |page|
if option=='Fixed'
page.select_hostname(host)
sleep(3)
page.downtime_value == "Yes"
@browser.span(:text => /Comments/).when_dom_changed.click
sleep(3)
@browser.span(:text => /This host has been scheduled for fixed downtime/).when_present(45).exists?
#puts @browser.span(:text => /This host has been scheduled for fixed downtime/).text
@browser.span(:text => /Comments/).when_dom_changed.click
page.navigate_host_page_nagios(host)
@browser.div(:class => /downtimeACTIVE/, :text => /YES/).exists?
@browser.td(:class => /commentOdd/, :text => /This host has been scheduled for fixed downtime/).when_present(45).exists?
elsif option=='Flexible'
page.select_hostname(host)
sleep(3)
@browser.span(:text => /Comments/).when_dom_changed.click
sleep(2)
@browser.span(:text => /This host has been scheduled for flexible downtime/).when_present(45).exists?
#puts @browser.span(:text => /This host has been scheduled for flexible downtime/).text
@browser.span(:text => /Comments/).when_dom_changed.click
page.navigate_host_page_nagios(host)
@browser.td(:class => /commentOdd/, :text => /This host has been scheduled for flexible downtime/).when_present(45).exists?
end
end
end
When /^I "(.+)" notifications of all hosts$/ do |state|
on StatusviewerPage do |page|
sleep(2)
@browser.span(:text => /Notifications/).when_present(45).click
sleep(1)
if state == "disable"
@browser.span(:text => /Disable notifications for all Hosts/).when_present(45).click
elsif state == "enable"
@browser.span(:text => /Enable notifications for all Hosts/).when_present(45).click
end
sleep(3)
@browser.button(:value => /Submit/).click
sleep(25)
end
end
Then /^I verify notifications are "(.+)" for the host "(.+)"$/ do |option,host|
on StatusviewerPage do |page|
page.navigate_host_page_nagios(host)
if option=='disabled'
@browser.div(:class => /notificationsDISABLED/, :text => /DISABLED/).when_present(45).exists?
elsif option=='enabled'
@browser.div(:class => /notificationsENABLED/, :text => /ENABLED/).when_present(45).exists?
end
end
end
Then /^I verify active checks of the service "(.+)" of host "(.+)" have been "(.+)"$/ do |service,host,option|
on StatusviewerPage do |page|
page.navigate_service_page_nagios(host,service)
sleep(10)
if option=="disabled"
@browser.div(:class => /checksDISABLED/, :text => /DISABLED/).exists?
puts "Nagios -> "[email protected](:class => /checksDISABLED/, :text => /DISABLED/).text
elsif option=="enabled"
@browser.div(:class => /checksENABLED/, :text => /ENABLED/).exists?
puts "Nagios -> "[email protected](:class => /checksENABLED/, :text => /ENABLED/).text
end
end
end
When /^I verify that service "(.+)" is added to service group "(.+)" on Status Viewer page$/ do |service,sg|
on StatusviewerPage do |page|
sleep(10)
@browser.span(:text => /#{service}/).exists?.should == true
puts @browser.span(:text => /#{service}/).text
end
end
When /^I should verify that service "(.+)" is removed from service group on Status Viewer page$/ do |serv|
on StatusviewerPage do |page|
sleep(10)
@browser.td(:id => /j_id6-0-0/).span(:text => /#{serv}/).exists?.should == true
end
end
And /^remove acknowledgement of problem$/ do
on StatusviewerPage do |page|
page.acknowledge_element.when_present(100).click
sleep(2)
page.remove_acknowledge_element.when_dom_changed.click
sleep(3)
page.submit_ack_element.when_present.click
end
end
<file_sep>Given(/^I am on License Page$/) do
visit AdministrationViewPage
on AdministrationViewPage do |page|
page.go_to_subtab("License")
end
end
When(/^I enter a password "(.+)" for "(.+)"$/) do |password, account_name|
on LicensePage do |page|
if password == "<PASSWORD>"
page.set_nullpassword(account_name)
else
page.set_password(account_name,password)
end
end
end
And(/^I click on "(.+)" button to "(.+)"$/) do |account_update, operation|
if operation == 'update'
if account_update == 'Update API Account'
@ws_token_before_update = @browser.span(:id => /sysacctmgmtform:encApiCredentials/).text.to_s
end
on LicensePage do |page|
if account_update != 'Update Remote Account'
@last_updated_timestamp_before = page.timestamp(account_update)
end
end
@browser.button(:value => /#{account_update}/).when_present.click
@browser.alert.ok
sleep(5)
elsif operation == 'test'
@browser.button(:id => /#{account_update}/).when_present.click
elsif operation == 'generate'
@password_before_generate = @browser.td(:id => /toolpanel-1-1/).text.to_s
@browser.button(:value => /#{account_update}/).when_present.click
elsif operation == 'test all passwords'
@browser.button(:id => /sysacctmgmtform:test/).when_present.click
end
end
Then(/^"(.+)" message should be displayed for "(.+)"$/) do |message_status, account_name|
$message_span = @browser.span(:class => /info-message/).when_present
if message_status == 'confirmation'
on LicensePage do |page|
page.confirm_message(account_name, $message_span)
end
elsif message_status == 'error'
on LicensePage do |page|
page.error_message(account_name)
end
elsif message_status == 'warning'
@browser.span(:id => /sysacctmgmtform/, :class => /iceMsgError/).text.include? ('Value is required.')
elsif message_status == 'test'
if account_name == 'Webervices API Account Info'
$message_span.text.include?('API account testing(SOAP): SUCCESS! ==> 200 OK').should == true
elsif account_name == 'Proxy Account Info'
$message_span.text.include? ('Proxy account testing(Cacti) : SUCCESS! ==> 200 OK').should == true
elsif account_name == 'API and Proxy accounts'
message_table = @browser.table(:id => /sysacctmgmtform:messagesOutput/)
message_table.tr(:index => 0).text.include?('API account testing(SOAP): SUCCESS! ==> 200 OK').should == true
message_table.tr(:index => 1).text.include?('Proxy account testing(Cacti) : SUCCESS! ==> 200 OK').should == true
end
end
end
And (/^last updated timestamp should be "(.+)" after "(.+)"$/) do |status, account_update|
on LicensePage do |page|
if account_update != 'Update Remote Account'
@last_updated_timestamp_after = page.timestamp(account_update)
end
if status == 'updated'
if account_update != 'Update Remote Account'
if @last_updated_timestamp_before == @last_updated_timestamp_after
puts 'Timestamp is same. Update failed'
raise
else
puts 'Timestamp is different. Update successful'
end
end
elsif status == 'unchanged'
if @last_updated_before == @last_updated_after
puts 'Timestamp is same. Update failed. This is expected'
else
puts 'Timestamp is different. Update failed'
raise
end
end
end
end
And (/^a new token should be generated for "(.+)"$/) do |account_name|
if account_name == 'Webervices API Account Info'
@ws_token_after_update = @browser.span(:id => /sysacctmgmtform:encApiCredentials/).text.to_s
if @ws_token_before_update == @ws_token_after_update
puts 'Token is same. Update failed'
raise
else
puts 'Token is different.'
end
elsif
puts 'Token is not generated in the account'
end
end
Then(/^error message should be displayed for "(.+)"$/) do |account_name|
on LicensePage do |page|
page.error_message(account_name)
end
end
When(/^I enter "(.+?)" as password under the Encryption Tool$/) do |password|
@browser.text_field(:id => /toolCredentials/).set password
end
Then(/^a new encrypted password should be generated$/) do
@password_after_generate = @browser.td(:id => /toolpanel-1-1/).text.to_s
if (@password_before_generate == @password_after_generate)
puts "Password is same after generation. Generate Failed!"
raise
else
puts "New encrypted password generated!"
end
end
<file_sep>Given(/^I select the dashboard "(.*?)" subtab$/) do |subtab|
on DashboardPage do |page|
sleep(5)
page.go_to_subtab(subtab)
end
end
Then(/^the dashboard subtab "(.*?)" should appear$/) do |subtab|
on DashboardPage do |page|
sleep(5)
page.check_subtab(subtab)
end
end
Given(/^I am on the My Groundwork page$/) do
visit MyGroundworkPage
end
Given(/^I select the my groundwork subtab "(.*?)"$/) do |subtab|
on MyGroundworkPage do |page|
sleep(5)
page.go_to_subtab(subtab)
end
end
Then(/^the my groundwork subtab "(.*?)" should appear$/) do |subtab|
on MyGroundworkPage do |page|
sleep(5)
page.check_subtab(subtab)
end
end
Then(/^The event console page should appear$/) do
on EventconsolePage do |page|
page.page_title_element.when_present.text.should == "Event Console"
@browser.text.include?("All Open Events").should == true
end
end
Then(/^the status viewer page should appear$/) do
on StatusviewerPage do |page|
page.page_title_element.when_present.text.should == "Status"
@browser.text.include?("Monitoring Statistics :").should == true
end
end
Then(/^the nagvis view page should appear$/) do
on NagvisViewsPage do |page|
page.page_title_element.when_present.text.should == "Views"
page.check_tab
end
end
Given(/^I am on the Reports page$/) do
visit ReportsPage
end
Given(/^I select the reports "(.*?)" subtab$/) do |subtab|
on ReportsPage do |page|
sleep(5)
page.go_to_subtab(subtab)
end
end
Then(/^the reports subtab "(.*?)" should appear$/) do |subtab|
on ReportsPage do |page|
sleep(5)
if subtab == "BIRT Report Viewer"
@browser.div(:class => /iceTreeRow/).link(:id => /reportTreePortlet_frmTree:reportTreePortlet_reportTree:0/).when_present.click
elsif subtab == "SLA Reports"
@browser.frame(:id => "myframe").div(:id => /content/).button(:value => /Website Report/).when_present.click
sleep(5)
else
page.check_subtab(subtab)
end
end
end
Given(/^I select the autodiscovery "(.*?)" subtab$/) do |subtab|
on AutodiscoveryPage do |page|
page.go_to_subtab(subtab)
end
end
Then(/^the autodiscovery subtab "(.*?)" should appear$/) do |subtab|
on AutodiscoveryPage do |page|
page.check_subtab(subtab)
end
end
Given(/^I am on the Configuration page$/) do
visit ConfigurationPage
end
Given(/^I select the configuration "(.*?)" subtab$/) do |subtab|
on ConfigurationPage do |page|
sleep(5)
page.go_to_subtab(subtab)
end
end
Then(/^the configuration subtab "(.*?)" should appear$/) do |subtab|
on ConfigurationPage do |page|
sleep(5)
page.check_subtab(subtab)
end
end
Given(/^I select the administration "(.*?)" subtab$/) do |subtab|
on AdministrationViewPage do |page|
sleep(5)
page.go_to_subtab(subtab)
end
end
Then(/^the administration subtab "(.*?)" should appear$/) do |subtab|
on AdministrationViewPage do |page|
sleep(5)
page.check_subtab(subtab)
end
end
Given(/^I am on the Advanced page$/) do
visit AdvancedPage
end
Given(/^I select the advanced "(.*?)" subtab$/) do |subtab|
on AdvancedPage do |page|
sleep(5)
page.go_to_subtab(subtab)
end
end
Then(/^the advanced subtab "(.*?)" should appear$/) do |subtab|
on AdvancedPage do |page|
sleep(5)
page.check_subtab(subtab)
end
end
Given(/^I am on the Resources page$/) do
visit ResourcesPage
end
Given(/^I select the resources "(.*?)" subtab$/) do |subtab|
on ResourcesPage do |page|
sleep(5)
page.go_to_subtab(subtab)
end
end
Then(/^the resources subtab "(.*?)" should appear$/) do |subtab|
on ResourcesPage do |page|
sleep(5)
page.check_subtab(subtab)
end
end
Given(/^I am on the Business page$/) do
visit BSMPage
end
Given(/^I select the Business "(.*?)" subtab$/) do |subtab|
on BSMPage do |page|
sleep(5)
page.go_to_subtab(subtab)
end
end
Then(/^the Business subtab "(.*?)" should appear$/) do |subtab|
on BSMPage do |page|
sleep(5)
page.check_subtab(subtab)
end
end
And /^I select the subtab "(.+)" under "(.+)"$/ do |subtab,tab|
on ConfigurationPage do |page|
sleep(5)
page.go_to_subtab_within(tab,subtab)
end
end
Then /^the Maintenence subtab "(.+)" should appear$/ do |subtab|
on ConfigurationPage do |page|
sleep(5)
page.check_subtab(subtab)
end
end
Then /^the Downtime subtab "(.+)" should appear$/ do |subtab|
on ConfigurationPage do |page|
sleep(5)
page.check_subtab(subtab)
end
end
<file_sep>class HostconfigurationPage
include PageObject
direct_url BASE_URL + "config/hosts"
link :configuration_section, :text => 'Configuration'
link :control_section, :text => 'Control'
link :service_section, :text => 'Services'
#En este branch arrastramos el bug de un iframe adentro de otro y no se esta usando pero igual lo dejo
#poruqe en algun momento cuando se resuelva el bug se va a usar
in_frame(:id => 'myframe') do |frame|
in_frame({:name => 'monarch_left'}, frame) do |frame|
link :host_groups, :text => /Host groups/, :frame => frame
link :host_groups_modify, :text => "Modify", :frame => frame
link :host_groups_modify_linux_server, :text=> "Linux Servers", :frame => frame
link :host_group_new, :text => 'New', :frame => frame
link :service_groups, :text => "Service groups", :frame => frame
link :service_groups_new, :text => 'New', :href => "service_groups&task=new", :frame => frame
link :commit_nagios, :text => 'Commit', :frame => frame
link :hosts, :text => /Hosts/, :frame => frame
end
in_frame({:id => 'monarch_main'}, frame) do |frame_main|
select_list :memebers, :name => 'memebers', :frame => frame_main
button :remove_members, :value => "Remove >>", :frame => frame_main
button :save_host_group, :name => 'save', :frame => frame_main
text_field :hots_group_name, :name => "name", :frame => frame_main
text_field :host_group_alias, :name => "alias", :frame => frame_main
select_list :nonmembers, :name => "nonmembers", :frame => frame_main
button :add_memebers, :value => "<< Add", :frame => frame_main
button :confirm_add_members, :name => "add", :frame => frame_main
text_field :service_group_name, :name => "name", :frame => frame_main
text_field :service_group_alias, :name => "alias", :frame => frame_main
button :service_group_add, :name => "add", :frame => frame_main
button :service_add_host, :name => 'add_hosts', :frame => frame_main
button :service_save, :name => 'save', :frame => frame_main
button :confirm_nagios_commit, :name => 'commit', :frame => frame_main
text_field :address, :name => 'address', :frame => frame_main
select :contactgroup, :id => 'contactgroup.members', :frame => frame_main
link :services, :value => 'Services', :frame => frame_main
select_list :service_add, :name => 'add_service', :frame => frame_main
end
end
def visit_host_configuration
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Hosts/).when_present.click
frameleft.link(:text => /Linux Servers /).when_present.click
frameleft.link(:text => /localhost /).when_present.click
frameleft.link(:text => /Detail/).when_present.click
framemain.button(:name => /host_profile/).when_present.click
end
def verify_host_profile_addition(host_profile)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.select(:name => /profile_host/).option(:value => host_profile).exists?.should == true
end
def verify_host_profile_deletion(host_profile)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.select(:name => /profile_host/).option(:value => host_profile).exists?.should == false
end
def visit_host_configuration_new(host)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Hosts/).when_present.click
frameleft.link(:text => /Linux Servers /).when_present.click
frameleft.link(:text => /#{host}/).when_present.click
frameleft.link(:text => /Detail/).when_present.click
end
end
<file_sep>require 'net/ssh'
require 'net/scp'
fn = File.dirname(File.expand_path(__FILE__))
hostname = ENV["SERVER"]
username = "root"
password = <PASSWORD>"
Net::SSH.start(hostname, username, :password => password) do |ssh|
ssh.exec!('service groundwork stop gwservices')
ssh.scp.upload!(fn + '/monarch.sql','.')
ssh.scp.upload!(fn + '/gwcollagedb.sql','.')
ssh.exec!('export PGPASSWORD=123 && /usr/local/groundwork/postgresql/bin/psql monarch < monarch.sql')
ssh.exec!('export PGPASSWORD=123 && /usr/local/groundwork/postgresql/bin/psql gwcollagedb < gwcollagedb.sql')
ssh.exec!('rm /usr/local/groundwork/nagvis/etc/maps/*.cfg')
maps = `ls scripts/net-ssh/maps/`
maps.split.each do |map|
ssh.scp.upload!(fn + '/maps/' + map,'/usr/local/groundwork/nagvis/etc/maps/' + map)
end
ssh.exec!('service groundwork start gwservices')
end
<file_sep>class ResourcesPage
include PageObject
direct_url BASE_URL + 'resources'
link :preference, :text => "Support"
#link :support, :text => "Support"
span :support_text, :text => "Support"
div :page_title, :class => "BreadcumbsInfoBar ClearFix"
@@subtab_text = { "Documentation" => "Welcome to Bookshelf 7", "Support" => "Recently Updated"}
def go_to_subtab(subtab)
@browser.link(:text => /Resources/).fire_event 'mouseover'
@browser.link(:text => /#{subtab}/).when_present.click
end
def check_subtab(subtab)
@browser.frame(:src => /kb.groundworkopensource.com/).div(:class => /wiki-content/).text.include? @@subtab_text[subtab]
end
end
<file_sep>Given /^I am on the Custom groups page$/ do
visit CustomGroupPage
end
When /^I create a new custom group "(.+)" with type "(.+)" and children "(.+)"$/ do |name, type, children|
on CustomGroupPage do |page|
#page.configuration_element.when_present.click
visit HostsConfigurationPage
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Host groups/).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /New/ ).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name, /name/).when_present.set children
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name, /alias/).set children
$selectList = @browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /nonmembers/)
$selectContent = $selectList.options.map(&:text).each { |element|
if element == "localhost"
$host_array << element
$selectList.select(element)
end
}
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:value, /<< Add/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, "add").click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, "continue").click
#page.control_element.when_present.click
visit ControlPage # new line added to go to Nagios
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Commit/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, 'commit').when_present.click
sleep(10)
@browser.frame(:id => "myframe").text.include?('Success')
#page.administration_element.when_present.click
#page.customgroups_element.when_present.click
visit CustomGroupPage
page.form_button_element.when_present(15).click
page.wait_until do
page.name_element.exists?
end
page.create(name, type, children)
end
end
When /^I create a custom group "(.+)" with type "(.+)" and children "(.+)"$/ do |name, type, children|
on CustomGroupPage do |page|
#page.customgroups_element.when_present.click
page.form_button_element.when_present(35).click
page.wait_until do
page.name_element.exists?
end
page.create(name, type, children)
end
end
When /^I save and publish$/ do
on CustomGroupPage do |page|
sleep(4)
page.save_and_publish_element.when_present.click
sleep(4)
#page.error_msg_element.exists?.should == false
end
end
Then /^I verify status "(.+)" for custom group "(.+)" with type "(.+)"$/ do |status, name, type|
sleep(5)
found = 0
on CustomGroupPage do |page|
page.groups_table_element.when_present.to_a.each do |row|
row.to_a.each do |cell|
if cell.text == name || cell.text == status
found += 1
end
break if found == 2
end
break if found == 2
end
found.should == 2
end
sleep(5) #sleep increased from 15 to 25 to 35 to 50
visit StatusviewerPage
sleep(5)
on StatusviewerPage do |page|
page.custom_group_element.text == name
end
visit EventconsolePage
on EventconsolePage do |page|
page.group_exists?(name, type).should == true
end
end
Given /^I have a Custom group to "(.*?)"$/ do |arg1|
on CustomGroupPage do |page|
page.groups_table_element.exists?
page.groups_table_element.exists?.should == true
page.groups_table_element.rows.should > 1
end
end
When /^I edit custom group with name "(.+)" and add "(.+)" as a child$/ do |name, host_to_add|
on CustomGroupPage do |page|
page.edit(name, host_to_add).should == "OK"
#Optimus Comment: No error comes when 'sleep' is commented.
#sleep(4)
end
end
Then /^I verify that changes were done for custom group "(.+)" with type "(.+)"-"(.+)" and status "(.+)"$/ do |name, type, hg, status|
sleep(5)
found = 0
on CustomGroupPage do |page|
page.groups_table_element.when_present.to_a.each do |row|
row.to_a.each do |cell|
if cell.text == name || cell.text == status || cell.text == "Linux Servers\n#{hg}"
found += 1
end
break if found == 3
end
break if found == 3
end
found.should == 3
end
sleep(5) # sleep increased from 25 to 35 to 50
visit StatusviewerPage
on StatusviewerPage do |page|
page.select_host(name, "Linux Servers", hg)
end
visit EventconsolePage
on EventconsolePage do |page|
if page.group_exists?(name,type)
@browser.link(:id => /naviPanel:systemFilterTree:1-0/).when_present.click
#custom_group = @browser.div(:id => /naviPanel:systemFilterTree-d-1-0-c/)
custom_group = @browser.div(:id => /naviPanel:systemFilterTree-d-1-0/).when_present
custom_group.link(:text => /Linux Servers/).when_present.exists?.should == true
end
end
end
When /^I delete the custom group "(.+)"$/ do |name|
on CustomGroupPage do |page|
page.delete(name).should == true
end
end
Then /^I verify that custom group "(.*?)" with type "(.*?)" was deleted$/ do |name, type|
on CustomGroupPage do |page|
#Optimus Comment: 'sleep' is required for the page to load.
sleep(2)
page.no_groups_available_element.when_present.exists?.should == true
end
sleep(15) #sleep increased from 15 to 35
visit StatusviewerPage
on StatusviewerPage do |page|
#page.custom_group_element.exists?.should == false
(page.custom_group_element.text == name).should == false
end
visit EventconsolePage
on EventconsolePage do |page|
page.group_exists?(name, type).should == false
end
end
Given /^I create two Custom groups "(.*?)" of type "(.*?)" with child "(.*?)" and "(.*?)" of type "(.*?)" with child "(.*?)"$/ do |cg1, type1, child1, cg2, type2, child2|
groups = {cg1 => [type1,child1], cg2 => [type2,child2]}
visit ServiceConfigurationPage
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Service groups/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /New/, :href => /service_groups&task=new/).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name, /name/).when_present.set 'SG1'
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name, /alias/).set 'SG1'
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, /add/).click
#$selectListnew = @browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /host/)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /host/).option(:text => /localhost/).when_present.select
#$selectContentnew = $selectListnew.options.map(&:text).each { |element|
#$selectListnew.select(element)
#}
sleep(3)
#<EMAIL>.frame(:id => "myframe").frame(:name => "monarch_main").when_present.select(:name => /services/).select(/local_/)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").when_present.select(:name => /services/).option(:text => /local_/).when_present.select
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, 'add_services').click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, /save/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, /continue/).click
visit ControlPage
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Commit/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, 'commit').when_present.click
sleep(10)
@browser.frame(:id => "myframe").text.include?('Success')
visit CustomGroupPage
on CustomGroupPage do |page|
groups.each do |key,value|
page.form_button_element.when_present(35).click
page.wait_until do
page.name_element.exists?
end
page.create("#{key}","#{value[0]}","#{value[1]}")
page.save_and_publish_element.when_present.click
end
end
end
When /^I try to edit two Custom groups at the same time$/ do
sleep(3)
@browser.checkbox(:name => /:cgListFrm:customGroups:0:/).set
sleep(2)
@browser.checkbox(:name => /:cgListFrm:customGroups:1:/).set
on CustomGroupPage do |page|
#page.custom_group1_element.when_present.check
#page.custom_group2_element.when_present.check
page.edit_group
end
end
Then /^an error "(.*?)" should appear$/ do |arg1|
on CustomGroupPage do |page|
page.edit_error_message_element.when_present.exists?.should == true
end
end
When /^I delete two Custom groups "(.*?)" and "(.*?)" at the same time$/ do |name1,name2|
@browser.checkbox(:name => /:cgListFrm:customGroups:0:/).set
@browser.checkbox(:name => /:cgListFrm:customGroups:1:/).set
on CustomGroupPage do |page|
#page.check_custom_group1.check
#page.check_custom_group2.check
sleep(5)
page.delete_group
end
end
Then /^a warning "(.*?)" should appear$/ do |arg1|
on CustomGroupPage do |page|
page.delete_confirm_message_element.exists?.should == true
page.confirm_delete
end
end
When /^I try to create an identical custom group with name "(.+)" type "(.+)" and child "(.+)"$/ do |name, type, child|
on CustomGroupPage do |page|
sleep(5)
page.form_button_element.when_present(35).click
page.wait_until do
page.name_element.exists?
end
page.create(name, type, child)
end
end
Then /^an error message should appear$/ do
on CustomGroupPage do |page|
page.save_and_publish_element.when_present.click
page.create_error_message_element.when_present.exists?.should == true
end
end
Given /^I create a service custom group "(.+)" of type "(.+)" and child "(.+)"$/ do |name,type,child|
on CustomGroupPage do |page|
page.form_button_element.when_present(35).click
page.wait_until do
page.name_element.exists?
end
page.create(name,type,child)
end
end
When /^I create a custom group "(.+)" of type "(.+)" with the ones created before "(.+)" and "(.+)"$/ do |name,type,cg1,cg2|
on CustomGroupPage do |page|
page.form_button_element.when_present(35).click
page.wait_until do
page.name_element.exists?
end
page.create(name,type,cg1,cg2)
page.save_and_publish_element.when_present.click
end
end
Then /^I should see the mixing children error$/ do
on CustomGroupPage do |page|
page.mix_error_message_element.when_present.exists?.should == true
end
end
Given /^I delete custom groups created$/ do
@browser.checkbox(:name => /:cgListFrm:customGroups:0:/).set
on CustomGroupPage do |page|
#page.check_custom_group1
page.delete_group
page.confirm_delete
end
end
When /^I save$/ do
on CustomGroupPage do |page|
sleep(5)
page.save_element.when_present.click
sleep(5)
end
end
Then /^it should not appear on Status viewer$/ do
visit StatusviewerPage
on StatusviewerPage do |page|
@browser.span(:text => "CG2").exists?.should == false
end
end
When /^I apply the filter Host Group$/ do
on EventconsolePage do |page|
page.filter_type("Host Group")
end
end
Then /^the groups should be in order$/ do
@browser.link(:id => /naviPanel:systemFilterTree:n-1-0:j_id22/, :text => "CG1")
@browser.link(:id => /naviPanel:systemFilterTree:n-1-1:j_id22/, :text => /Linux Servers/)
end
Given /^I delete "(.+)" Host group$/ do |group|
on HostconfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Host groups/).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Modify/ ).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /#{group}/ ).when_present.click
sleep(5)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, /delete/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:value, /Yes/).click
end
end
Given /^I delete "(.+)" Service group$/ do |group|
on ServiceConfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Service groups/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Modify/ ).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /#{group}/ ).when_present.click
sleep(5)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, /delete/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:value, /Yes/).click
end
end
When /^I select the existing custom group created and remove all its children$/ do
on CustomGroupPage do |page|
page.custom_group1_element.when_present.check
page.edit_group
sleep(3)
page.remove_button
end
end
When /^I save and publish the custom group$/ do
on CustomGroupPage do |page|
sleep(4)
page.save_and_publish_element.when_present.click
sleep(4)
end
end
Then /^an error message for selecting children should appear$/ do
on CustomGroupPage do |page|
page.child_error_message_element.when_present.exists?.should == true
end
end
#OptimusComment: Moved step definitions from Bug folder
Given /^I create a custom group "(.*?)" with type "(.*?)" and children "(.*?)" $/ do |name, type, children |
on CustomGroupPage do |page|
has_custom_group = false
if page.CG1_element.exists?
page.check_CG1
has_custom_group = true
end
if page.CG2_element.exists?
page.check_CG2
has_custom_group = true
end
if has_custom_group
page.delete_group
page.confirm_delete
end
page.form_button_element.when_present(35).click
page.wait_until do
page.name_element.exists?
end
page.create(name, type, children )
page.save_and_publish_element.when_present.click
end
end
Given /^I select the custom group created$/ do
on StatusviewerPage do |page|
@services_number = page.total_services_element.when_present.text
page.custom_group
end
end
Then /^I should not open a hostgroup view and delete custom group created "(.*?)"$/ do |name|
on StatusviewerPage do |page|
page.total_services_element.when_present.text.should == @services_number
visit CustomGroupPage
on CustomGroupPage do |page|
page.groups_table_element.exists?
page.groups_table_element.exists?.should == true
page.groups_table_element.rows.should > 1
page.delete(name).should == true
end
end
end
When /^I select the custom group on Event Console of type "(.*?)"$/ do |type|
on EventconsolePage do |page|
@showing_number = page.number_showing_events_element.when_present.text
page.filter_type(type)
page.custom_group_element.when_present
end
end
Then /^the custom group should not be highlighted$/ do
on EventconsolePage do |page|
page.number_showing_events_element.when_present.text.should == @showing_number
end
end
<file_sep>class ViewPage
include PageObject
direct_url BASE_URL + "nagvis"
in_frame(:id => 'myframe') do |frame|
span :options, :text => "Options", :id => "wui-ddheader", :frame => frame
link :managemap, :text => /Manage Maps/, :frame => frame
select :renamemapdrop, :name => 'map', :frame => frame
text_field :entermap, :name => 'map_new_name', :frame => frame
button :rename, :value => 'Rename', :frame => frame
span :verifyrename, :text => "Open", :frame => frame
link :openmap, :text => 'Maps', :frame => frame
link :map1, :id => /map-testmap-icon/, :frame => frame
link :map2, :id => /map-World-icon/, :frame => frame
link :map9, :id => /map-testgw-icon/, :frame => frame
link :geooffice, :id => /map-GeoOffice-icon/, :frame => frame
link :autohost, :id => /map-auto_hostgroups-icon/, :frame => frame
link :map5, :id => /map-PublicWeb-icon/, :frame => frame
link :SANJOSE, :text => /SanJoseSAN/, :frame => frame
link :newmap, :id => /map-testmap123-icon/, :frame => frame
span :usermenu, :text => /User menu/, :id => "user-ddheader", :frame => frame
link :manageuser, :text => /Manage Roles/, :frame => frame
span :editmap, :text => /Edit Map/, :id => /map-ddheader/, :frame => frame
link :addicon, :id => /map-addicon-ddheader/, :frame => frame
link :addline, :id => /map-addline-ddheader/, :frame => frame
link :addhost, :text => /Host/, :frame => frame
link :serviceline, :text => /Service/, :frame => frame
img :background, :id => /backgroundImage/, :frame => frame
select :modifymapdrop, :id => 'roleId', :frame => frame
checkbox :selectcheck, :name => 'perm_1', :frame => frame
checkbox :selectcheck1, :name => 'perm_12', :frame => frame
checkbox :selectcheck2, :name => 'perm_19', :frame => frame
button :saveuser, :id => 'submit', :frame => frame
img :object, :alt => /host-localhost/, :frame => frame
img :object1, :alt => /host-itmon-win/, :frame => frame
div :header, :id => /header/, :frame => frame
link :unlock, :text => /Unlock/, :frame => frame
link :modify, :text => 'Modify object', :frame => frame
select :localhost, :value => 'localhost', :id => 'host_name', :frame => frame
select :bsmhost, :value => 'itmon-win', :id => 'host_name', :frame => frame
link :map6, :text => /World/, :frame => frame
select :hostname, :id => "host_name", :name => "host_name", :frame => frame
select :hostgroup, :id => "hostgroup_name", :name => "hostgroup_name", :frame => frame
select :servicegroup, :id => "servicegroup_name", :name => "servicegroup_name", :frame => frame
select :service_desc, :id => /service_description/, :name => /service_description/, :frame => frame
button :modify_button, :id => /commit/, :name => /submit/, :frame => frame
link :lockunlock, :text => 'Lock/Unlock all', :frame => frame
link :lock, :text => /Lock/, :frame => frame
#img :hostadded, :alt => 'host-itmon-win', :frame => frame
#img :hostadded, :src => '/nagvis_share/userfiles/images/iconsets/std_big_up.png', :frame => frame
#link :hostadded1, :href => '/portal-statusviewer/urlmap?host=itmon-win', :frame => frame
#img :hostgroupadded, :alt => "hostgroup-HG2", :frame => frame
#img :servicegroupadded, :alt => "servicegroup-SG1", :frame => frame
link :serviceadded1, :href => '/portal-statusviewer/urlmap?host=itmon-win&service=icmp_ping_alive', :frame => frame
#img :serviceadded, :src => '/nagvis_share/userfiles/images/iconsets/std_big_ok.png', :frame => frame
img :serviceadded, :id => /-icon/, :frame => frame
link :delhostobject, :text => /Delete object/, :frame => frame
link :addspecial, :id => /map-addspecial-ddheader/, :frame => frame
link :specialtextbox, :text => /Textbox/, :frame => frame
text_field :textname, :id => /text/, :name => /text/, :frame => frame
checkbox :selectnegative, :name => /toggle_w/, :frame => frame
checkbox :selectnegative1, :name => /toggle_h/, :frame => frame
span :textboxadded, :text => /textbox/, :frame => frame
link :mapoptions, :text => /Map Options/, :frame => frame
select_list :mapbackgrnd, :id => /map_image/, :frame => frame
checkbox :selectalias, :name => /toggle_alias/, :frame => frame
text_field :aliasname, :id => /alias/, :frame => frame
checkbox :selectcolor, :name => /toggle_background_color/, :frame => frame
text_field :backcolor, :id => /background_color_inp/, :frame => frame
select :mapiconset, :id => /iconset/, :frame => frame
img :modifybackgrnd, :src => '/nagvis_share/userfiles/images/maps/OfficeLan.png', :frame => frame
#img :modifyicon, :src => '/nagvis_share/userfiles/images/iconsets/earth_up.png', :frame => frame
img :modifyicon, :src => /earth_/, :frame => frame
#manage background scenario
link :managebackgrnd, :text => /Manage Backgrounds/, :frame => frame
text_field :imagename, :name => /image_name/, :frame => frame
text_field :imagecolor, :id => /image_color/, :frame => frame
text_field :imagewidth, :name => /image_width/, :frame => frame
text_field :imageheight, :name => /image_height/, :frame => frame
file_field :uploadimage, :class => /upload/, :name => /image_file/, :frame => frame
file_field :uploadmap, :class => /upload/, :name => /map_file/, :frame => frame
button :upload_submit, :value => /Upload/, :name => /submit/, :frame => frame
select :deletebackgrnd, :name => /map_image/, :frame => frame
button :deletesubmit, :value => /Delete/, :name => /submit/, :frame => frame
button :import_submit, :value => /Import/, :name => /submit/, :frame => frame
#manage shape
link :manageshape, :text => /Manage Shapes/, :frame => frame
link :addshape, :text => /Shape/, :frame => frame
select :shapeicon, :name => /icon/, :frame => frame
select :icondelete, :name => /image/, :frame => frame
img :iconshape, :src => /test-shape.png/, :frame => frame
text_field :boxcolor, :id => /background_color_inp/, :frame => frame
checkbox :boxcolorset, :name => /toggle_background_color/, :frame => frame
#export & error static map
span :action, :id => /action-ddheader/, :frame => frame
link :export_to_static, :text => /Export to static map/, :frame => frame
text_field :target, :id => /target/, :frame => frame
link :staticmap, :text => /statictest/, :frame => frame
td :error_staticmap, :text => /Invalid target option given./, :frame => frame
#error message in making child a parent of its parent map
checkbox :selectparent, :name => /toggle_parent_map/, :frame => frame
select :parentmap, :id => /parent_map/, :frame => frame
#add container
link :addcontainer, :text => /Container/, :frame => frame
text_field :containerurl, :name => /url/, :frame => frame
text_field :contwidth, :name => /w/, :frame => frame
text_field :contheight, :name => /h/, :frame => frame
img :ebay, :id => /gh-logo/, :frame => frame
td :urlerror, :text => /The attribute needs to be set./, :frame => frame
div :containerdelete, :id => /-label/, :frame => frame
#div :containerdelete, :class => /box resizeMe/, :frame => frame
#add stateless line
link :addstateless, :text => /Stateless Line/, :frame => frame
canvas :stateline, :id => /canvas1/, :frame => frame
img :stateline1, :id => /-link1/, :frame => frame
#img :stateline1, :src => '/nagvis_share/userfiles/images/iconsets/20x20.gif', :frame => frame
#add icon as a service
link :addservice, :text => /Service/, :frame => frame
img :serviceicon, :src => '/nagvis_share/userfiles/images/iconsets/std_big_ok.png', :frame => frame
link :addhostgroup, :text => /Hostgroup/, :frame => frame
link :addservicegroup, :text => /Servicegroup/, :frame => frame
#add icon as a map
link :addmapicon, :text => /Map/, :frame => frame
select :mapname, :name => "map_name", :frame => frame
#img :mapicon, :alt => 'map-GeoOffice', :frame => frame
#add line as host
link :linehost, :text => /Host/, :frame => frame
img :lineadded, :src => "/nagvis_share/userfiles/images/iconsets/20x20.gif", :frame => frame
#add a line as map
link :linemap, :text => /Map/, :frame => frame
img :icon1, :id => /-icon/, :frame => frame
span :open, :text => "Open", :frame => frame
link :deleted_map, :text => /test_map/, :frame => frame
link :manage_maps, :text => "Manage Maps", :frame => frame
link :verify_maps, :text => /gjuik/, :frame => frame
text_field :map, :name => "map", :frame => frame
select_list :map_image_list, :name => "map_image", :frame => frame
button :submit_button, :name => "submit", :frame => frame
select :iconset, :name => "map_iconset", :frame => frame
select :delete_map, :id => "table_map_delete", :name => "map", :frame => frame
button :delete_button, :id => "commit", :frame => frame
link :map_addicon_ddheader, :id => "map-addicon-ddheader", :frame => frame
link :host_link, :text => "Host", :frame => frame
image :background_image, :id => "background", :frame => frame
select_list :hostname_list, :id => "host_name", :frame => frame
select_list :view_type_list, :id => "view_type", :frame => frame
select_list :gadget_url_list, :id => "gadget_url", :frame => frame
text_field :x_text_field, :id => "x", :frame => frame
text_field :y_text_field, :id => "y", :frame => frame
link :service_link, :text => "Service", :frame => frame
select_list :service_description_list, :id => "service_description", :frame => frame
link :hostgroup_link, :text => "Hostgroup", :frame => frame
select_list :hostgroup_list, :id => "hostgroup_name", :frame => frame
link :servicegroup_link, :text => "Servicegroup", :frame => frame
select_list :service_name_list, :id => "servicegroup_name", :frame => frame
image :test_map_image, :src => /TestMap/, :frame => frame
link :test_map_link, :text => "TestMap", :frame => frame
link :map_link, :text => "Map", :frame => frame
select_list :map_name_list, :id => "map_name", :frame => frame
image :performance_map_image, :id => "icon_map_0", :frame => frame
link :views, :text => "Views"
table :error, :id => "messageBox"
#cloning an object
checkbox :enable_z_coordinate, :name => /toggle_z/, :frame => frame
text_field :z_text, :name => /z/, :frame => frame
checkbox :chk_label, :name => /toggle_label_show/, :frame => frame
select_list :chk_label_option, :name => /label_show/, :frame => frame
checkbox :chk_host_label, :name => /toggle_label_text/, :frame => frame
text_field :text_host_label, :name => /label_text/, :frame => frame
link :clone, :text => /Clone object/, :frame => frame
#Verify rename and display of a map placed on a map
img :corpweb, :alt => /map-CorpWeb/, :frame => frame
end
def host_object_add(object)
sleep(2)
@browser.frame(:id => "myframe").image(:alt => 'host-'+object).fire_event('click')
end
def host_object_add_hover(object)
sleep(2)
@browser.frame(:id => "myframe").image(:alt => 'host-'+object).fire_event 'hover'
end
def host_object_right_click(object)
sleep(2)
@browser.frame(:id => "myframe").image(:alt => 'host-'+object).when_present.right_click
end
def icon_select(option, object)
self.map9_element.when_present.click
sleep(3)
self.editmap_element.fire_event 'mouseover'
self.addicon_element.fire_event 'mouseover'
if option == 'host'
self.addhost_element.when_present.click
self.background_element.when_present(40).click
self.hostname = object
elsif option == 'service'
self.addservice_element.when_present.click
sleep(2)
self.background_element.when_present(40).click
self.hostname = object
sleep(3)
self.service_desc = /icmp_ping_alive/
elsif option == 'hostgroup'
self.addhostgroup_element.when_present(40).click
self.background_element.when_present(40).click
self.hostgroup = object
elsif option == 'servicegroup'
self.addservicegroup_element.when_present(40).click
self.background_element.when_present(40).click
self.servicegroup = object
elsif option == 'map'
self.addmapicon_element.when_present.click
sleep(2)
self.background_element.when_present.click
sleep(2)
self.mapname = object
end
self.modify_button_element.when_present.click
sleep(5)
end
def icon_verify(option, object)
if option == 'host'
self.host_object_add(object)
sleep(5)
@browser.span(:id => "HVform:txthostName", :text => /#{object}/).exists?.should == true
elsif option == 'service'
sleep(3)
self.serviceadded_element.fire_event('click')
sleep(5)
@browser.span(:id => "SVform:SHtxtServiceName", :text => /icmp_ping_alive/).exists?.should == true
elsif option == 'hostgroup'
sleep(3)
@browser.frame(:id => "myframe").img(:alt => 'hostgroup-'+object).fire_event('click')
sleep(5)
@browser.span(:id => "HGVform:hghtxtHostGroup", :text => /#{object}/).exists?.should == true
elsif option == 'servicegroup'
sleep(3)
@browser.frame(:id => "myframe").img(:alt => 'servicegroup-'+object).fire_event('click')
sleep(5)
@browser.span(:id => "SGVform:SGHtxtServiceGroupName", :text => /#{object}/).exists?.should == true
elsif option == 'map'
@browser.frame(:id => "myframe").img(:alt => 'map-'+object).fire_event('click')
sleep(5)
@browser.frame(:id => "myframe").img(:src => '/nagvis_share/userfiles/images/maps/OfficeLan.png').exists?.should == true
end
end
def icon_delete(object, option)
self.map9_element.when_present.click
sleep(4)
if option == 'host'
self.host_object_add_hover(object)
sleep(2)
self.host_object_right_click(object)
self.unlock_element.when_present.click
sleep(1)
self.host_object_right_click(object)
self.delhostobject_element.when_present.click
@browser.alert.ok
sleep(1)
@browser.frame(:id => "myframe").image(:alt => 'host-'+object).exists?.should == false
elsif option == 'service'
sleep(3)
self.serviceadded_element.fire_event 'hover'
sleep(2)
self.serviceadded_element.when_present.right_click
self.unlock_element.when_present.click
sleep(1)
self.serviceadded_element.when_present.right_click
self.delhostobject_element.when_present.click
@browser.alert.ok
sleep(1)
self.serviceadded_element.exists?.should == false
elsif option == 'hostgroup'
sleep(3)
@browser.frame(:id => "myframe").img(:alt => 'hostgroup-'+object).fire_event 'hover'
sleep(2)
@browser.frame(:id => "myframe").img(:alt => 'hostgroup-'+object).when_present.right_click
self.unlock_element.when_present.click
sleep(1)
@browser.frame(:id => "myframe").img(:alt => 'hostgroup-'+object).when_present.right_click
self.delhostobject_element.when_present.click
@browser.alert.ok
sleep(1)
@browser.frame(:id => "myframe").img(:alt => 'hostgroup-'+object).exists?.should == false
elsif option == 'servicegroup'
@browser.frame(:id => "myframe").img(:alt => 'servicegroup-'+object).fire_event 'hover'
sleep(2)
@browser.frame(:id => "myframe").img(:alt => 'servicegroup-'+object).when_present.right_click
self.unlock_element.when_present.click
sleep(1)
@browser.frame(:id => "myframe").img(:alt => 'servicegroup-'+object).when_present.right_click
self.delhostobject_element.when_present.click
@browser.alert.ok
sleep(1)
@browser.frame(:id => "myframe").img(:alt => 'servicegroup-'+object).exists?.should == false
elsif option == 'map'
@browser.frame(:id => "myframe").img(:alt => 'map-'+object).fire_event 'hover'
sleep(2)
@browser.frame(:id => "myframe").img(:alt => 'map-'+object).when_present.right_click
self.unlock_element.when_present.click
sleep(1)
@browser.frame(:id => "myframe").img(:alt => 'map-'+object).when_present.right_click
self.delhostobject_element.when_present.click
@browser.alert.ok
sleep(1)
@browser.frame(:id => "myframe").img(:alt => 'map-'+object).exists?.should == false
end
end
def line_select(option, object)
self.map9_element.when_present.click
sleep(3)
self.editmap_element.fire_event 'mouseover'
self.addline_element.fire_event 'mouseover'
if option == 'host'
self.linehost_element.fire_event('click')
self.background_element.when_present.click
self.background_element.drag_and_drop_by 200, -200
self.background_element.fire_event('click')
sleep(2)
self.hostname = object
elsif option == 'service'
self.serviceline_element.fire_event('click')
self.background_element.when_present.click
self.background_element.drag_and_drop_by 200, -200
self.background_element.fire_event('click')
sleep(2)
self.hostname = object
sleep(3)
self.service_desc = /icmp_ping_alive/
elsif option == 'hostgroup'
self.addhostgroup_element.when_present(40).click
self.background_element.when_present(40).click
self.background_element.drag_and_drop_by 200, -200
self.background_element.fire_event('click')
sleep(2)
self.hostgroup = object
elsif option == 'servicegroup'
self.addservicegroup_element.when_present(40).click
self.background_element.when_present(40).click
self.background_element.drag_and_drop_by 200, -200
self.background_element.fire_event('click')
sleep(2)
self.servicegroup = object
elsif option == 'map'
self.linemap_element.fire_event('click')
self.background_element.when_present.click
self.background_element.drag_and_drop_by 200, -200
self.background_element.fire_event('click')
sleep(2)
self.mapname = object
end
self.modify_button_element.when_present.click
sleep(5)
self.lineadded_element.fire_event('click')
sleep(5)
end
def line_verify(option, object)
if option == 'host'
@browser.span(:id => "HVform:txthostName", :text => /#{object}/).exists?.should == true
sleep(2)
elsif option == 'service'
@browser.span(:id => "SVform:SHtxtServiceName", :text => /icmp_ping_alive/).exists?.should == true
elsif option == 'hostgroup'
sleep(5)
@browser.span(:id => "HGVform:hghtxtHostGroup", :text => /#{object}/).exists?.should == true
elsif option == 'servicegroup'
sleep(5)
@browser.span(:id => "SGVform:SGHtxtServiceGroupName", :text => /#{object}/).exists?.should == true
elsif option == 'map'
@browser.frame(:id => "myframe").img(:src => '/nagvis_share/userfiles/images/maps/OfficeLan.png').exists?.should == true
sleep(3)
end
end
def modify_user(gwuser)
self.modifymapdrop_element.option(:text => gwuser).when_present.select
end
def rename_map(oldname, newname)
self.renamemapdrop_element.option(:value => oldname).when_present.select
self.entermap_element.value = newname
self.rename_element.when_present.click
sleep(2)
@browser.alert.ok
sleep(10)
end
def select_map(newname)
if newname == 'testmap'
self.map1_element.when_present.click
sleep(5)
elsif newname == 'World'
self.map2_element.when_present.click
sleep(5)
elsif newname == 'PublicWeb'
self.map5_element.when_present.click
sleep(5)
end
end
def create_user(name, password, email)
self.create_user_account_element.when_present.click
self.wait_until(5) do
self.username_element.exists?
end
self.username = name
self.email = email
self.password = <PASSWORD>
self.confirm_password = <PASSWORD>
self.submit
self.submit_role_element.when_present.click
self.submit_confirmation_element.when_present.click
end
def create_new_user(name, password, firstname, lastname, email)
self.user_name = name
self.pwd = <PASSWORD>
self.confirm_pwd = <PASSWORD>
self.firstname = firstname
self.lastname = lastname
self.mail = email
self.save_element.click
sleep(3)
@browser.span(:class => /PopupTitleIcon/).link(:class => /CloseButton/).click
end
def delete_user(user)
self.wait_until(10) do
self.search_users_textfield_element.exists?
end
self.search_users_textfield = user
self.search_users_button_element.when_present.click
sleep(2)
self.delete_user_element.when_present.click
self.submit_delete_user_element.when_present.click
end
def go_to_subtab(subtab)
@browser.link(:text => /GroundWork Administration/).fire_event 'mouseover'
@browser.link(:text => /#{subtab}/).when_present.click
end
def check_subtab(subtab)
self.wait_until(10) do
self.page_title.include? subtab
if subtab == "Foundation" || subtab == "Views"
@browser.frame(:id => "myframe").h1.text.include? @@subtab_text[subtab]
elsif subtab == "GroundWork Cloud Hub"
@browser.frame(:id => "myframe").div(:id => "container").text.include? @@subtab_text[subtab]
else
@browser.text.include? @@subtab_text[subtab]
end
end
end
def delete_map(delete_name)
@browser.frame(:id => 'myframe').table(:id => "table_map_delete").td(:class => "tdfield").select(:name => "map").option(:text => delete_name).select
self.delete_button_element.when_present.click
@browser.alert.ok
end
end
<file_sep>class ControlPage
include PageObject
direct_url BASE_URL + "config/control"
=begin
in_frame(:id => 'myframe') do |frame|
in_frame({:name => 'monarch_left'}, frame) do |frame|
link :nagios_main, :text => /Nagios main configuration/, :frame => frame
link :notification, :text => /Notification/, :frame => frame
end
in_frame({:id => 'monarch_main'}, frame) do |frame_main|
checkbox :enable_check, :name => /enable_notifications/, :frame => frame
end
button :save_next, :name => /next/, :frame => frame
end
=end
def enable_notification
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /Nagios main configuration/).when_present.click
sleep(5)
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /Notification/).when_present.click
sleep(6)
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).checkbox(:name => /enable_notifications/).clear
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).checkbox(:name => /enable_notifications/).set
end
def save_next
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).button(:name => /next/).when_present.click
end
def disable_notification
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /Nagios main configuration/).when_present.click
sleep(5)
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /Notification/).when_present.click
sleep(6)
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).checkbox(:name => /enable_notifications/).clear
end
def enable_flap_detection
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /Nagios main configuration/).when_present.click
sleep(5)
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /Flapping Control/).when_present.click
sleep(6)
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).checkbox(:name => /enable_flap_detection/).clear
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).checkbox(:name => /enable_flap_detection/).set
end
def disable_flap_detection
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /Nagios main configuration/).when_present.click
sleep(5)
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /Flapping Control/).when_present.click
sleep(6)
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).checkbox(:name => /enable_flap_detection/).clear
end
end <file_sep>Given /^I log in with "(.+)"$/ do |user|
on DashboardPage do |page|
page.logout
end
on LoginPage do |page|
page.login_user(user,user)
end
end
Then /^I should see the dashboard page for "(.+)"$/ do |user|
on DashboardPage do |page|
page.verify_user(user)
end
end
Given /^I login with unauthorized "(.+)"$/ do |user|
on DashboardPage do |page|
page.logout
end
on LoginPage do |page|
page.login_user(user,"1<PASSWORD>")
end
end
Then /^I should see an error message$/ do
puts "Expected message is "[email protected]
error_message = @browser.h1.text
if error_message == "HTTP Status 402 -"
puts 'true'
else
puts 'false'
raise
end
end
<file_sep>class AutodiscPage
include PageObject
direct_url BASE_URL + "auto-disc"
#changing the frame
in_frame(:id => 'myframe') do |frame|
button :delete_range, :value => 'delete range/filter', :frame => frame
button :confirm_delete_filter, :name => /yes/, :frame => frame
button :add_new_filters, :name => /add_filter/, :frame => frame
button :go ,:name => /go/, :frame => frame
button :start_new_discovery ,:name => /clear_discovery/, :frame => frame
button :confirm_go, :name => /go_discover/, :frame => frame
button :cancel_discovery, :value => /Cancel/, :frame => frame
button :close_discovery, :value => /Close/, :frame => frame
text_field :range_name, :name => /filter_name/, :frame => frame
text_field :range_pattern, :name => /filter_value/, :frame => frame
select_list :range_type, :name => /filter_type/, :frame => frame
radio_button :interactive, :value => /Interactive/, :frame => frame
radio_button :auto, :value => /Auto/, :frame => frame
radio_button :auto_commit, :value => /Auto-Commit/, :frame => frame
checkbox :accept_discovery, :name => /accept/, :frame => frame
table :discovered_hosts_table, :id => /reportTable/, frame =>frame
end
def delete_old_filter
while(self.delete_range_element.exists?)
self.delete_range_element.click
sleep(3)
self.confirm_delete_filter_element.when_present.click
sleep(5)
end
end
def add_filter(name, type, pattern)
self.range_name = name
self.range_type = type
self.range_pattern = pattern
self.add_new_filters
end
def discovered_elements
if(self.discovered_hosts_table.exists?)
host_array = Array.new
table.rows.each do |row|
row.cells.each do |cell|
if(cell.text.match(/Linux*/))
host_array << (cell-1).text
end
end
end
end
end
end
<file_sep>class AdministrationViewPage
include PageObject
direct_url BASE_URL + "groundwork-administration"
@@subtab_title = { "Portal Management" => "Management Portlet", "User Management" => "User management portlet", "Foundation" => "Foundation Administration", "Views" => "NagVis", "CustomGroups" => "Custom Groups entry", "Cloud Hub for VMWare" => "Cloud Hub for VMWare", "GroundWork License" => "GWOS Monitor Enterprise license entry"}
#@@subtab_text = { "Portal Management" => "Manage portals", "User Management" => "Create new user", "Foundation" => "Foundation Framework", "Views" => "Welcome admin, to the Views Administration Page", "CustomGroups" => "No CustomGroups Available", "Cloud Hub for VMWare" => "Cloud Hub Configuration wizard for VMWare", "GroundWork License" => "The current license for this GWOS Enterprise Edition installation"}
@@subtab_text = { "Foundation" => "Foundation Framework", "CustomGroups" => "No CustomGroups Available", "GroundWork Cloud Hub" => "CloudHub Configuration wizard", "GroundWork License" => "The current license for this GWOS Enterprise Edition installation"}
link :views, :text => "Views", :href => "/portal/auth/portal/groundwork-monitor/admin/nagvis-admin"
link :customGroups, :text => "CustomGroups", :href => "/portal/auth/portal/groundwork-monitor/admin/customgroupsview"
button :create_group, :id => "jbpns_2fgroundwork_2dmonitor_2fadmin_2fcustomgroupsview_2fCustomGroupInstanceWindowsnpbj:cgListFrm:btn_add"
text_field :customGroup_name, :class =>"iceInpTxt portlet-form-input-field text"
select_list :host_name_list, :id =>"jbpns_2fgroundwork_2dmonitor_2fadmin_2fcustomgroupsview_2fCustomGroupInstanceWindowsnpbj:createCustomGroupForm:SlctChildren_leftList"
button :add_host_button, :id => "jbpns_2fgroundwork_2dmonitor_2fadmin_2fcustomgroupsview_2fCustomGroupInstanceWindowsnpbj:createCustomGroupForm:SlctChildren_addBtn"
button :save_publish_button, :id => "jbpns_2fgroundwork_2dmonitor_2fadmin_2fcustomgroupsview_2fCustomGroupInstanceWindowsnpbj:createCustomGroupForm:btn_publish"
span :customGroupCreated, :id => "jbpns_2fgroundwork_2dmonitor_2fadmin_2fcustomgroupsview_2fCustomGroupInstanceWindowsnpbj:cgListFrm:customGroups:0:groupName"
span :customGroup_state, :id => "jbpns_2fgroundwork_2dmonitor_2fadmin_2fcustomgroupsview_2fCustomGroupInstanceWindowsnpbj:cgListFrm:customGroups:0:groupState"
checkbox :custom_group, :id => "jbpns_2fgroundwork_2dmonitor_2fadmin_2fcustomgroupsview_2fCustomGroupInstanceWindowsnpbj:cgListFrm:customGroups:0:j_id17"
button :delete_custom_group_button, :id => "jbpns_2fgroundwork_2dmonitor_2fadmin_2fcustomgroupsview_2fCustomGroupInstanceWindowsnpbj:cgListFrm:btn_delete"
button :confirm_delete_custom_group, :id => "jbpns_2fgroundwork_2dmonitor_2fadmin_2fcustomgroupsview_2fCustomGroupInstanceWindowsnpbj:cgListFrm:deleteConfirmPanel-accept"
button :edit_custom_group, :id => "jbpns_2fgroundwork_2dmonitor_2fadmin_2fcustomgroupsview_2fCustomGroupInstanceWindowsnpbj:cgListFrm:customGroups:0:j_id17"
button :remove_host_button, :id => "jbpns_2fgroundwork_2dmonitor_2fadmin_2fcustomgroupsview_2fCustomGroupInstanceWindowsnpbj:editCustomGroupForm:SlctChildren_removeBtn"
text_field :linux_server_child, :id => "jbpns_2fgroundwork_2dmonitor_2fadmin_2fcustomgroupsview_2fCustomGroupInstanceWindowsnpbj:cgListFrm:customGroups:0:childrenId:0"
link :user_management, :text => "User Management"
link :create_user_account, :text => "Create new user account"
text_field :username, :id => "_jbpns_2fgroundwork_2dmonitor_2fadmin_2fusers_2fIdentityAdminPortletWindowsnpbj:j_id44:register-form:username"
text_field :email, :id => "_jbpns_2fgroundwork_2dmonitor_2fadmin_2fusers_2fIdentityAdminPortletWindowsnpbj:j_id44:register-form:email"
text_field :password, :id => <PASSWORD>_2<PASSWORD>_2dmonitor_2fadmin_2fusers_2fIdentityAdminPortletWindowsnpbj:j_<PASSWORD>:<PASSWORD>"
text_field :confirm_password, :id => "_jbpns_2fgroundwork_2dmonitor_2fadmin_2fusers_2fIdentityAdminPortletWindowsnpbj:j_id44:register-form:passwordCheck"
button :submit, :id => "_jbpns_2fgroundwork_2dmonitor_2fadmin_2fusers_2fIdentityAdminPortletWindowsnpbj:j_id44:register-form:submit"
button :submit_role, :id => "_jbpns_2fgroundwork_2dmonitor_2fadmin_2fusers_2fIdentityAdminPortletWindowsnpbj:j_id28:register-role-form:submit"
button :submit_confirmation, :id => "_jbpns_2fgroundwork_2dmonitor_2fadmin_2fusers_2fIdentityAdminPortletWindowsnpbj:j_id36:confirm-form:admin"
link :portal_management, :text => "Portal Management"
link :groundwork_monitor, :text => "groundwork-monitor"
link :dashboard, :text => "dashboard"
link :summary, :text => "summary"
link :page_layout, :text => "Page layout"
select_list :center_region, :id => "_jbpns_2fgroundwork_2dmonitor_2fadmin_2fdefault_2fAdminPortletWindowsnpbj:j_id66:layoutForm:selectMany_center"
button :delete_button, :value => "Delete"
link :date_time, :text => "DateTimeInstance"
button :add_button, :value => "Add"
link :search_users, :text => "Search users"
text_field :search_users_textfield, :id => "_jbpns_2fgroundwork_2dmonitor_2fadmin_2fusers_2fIdentityAdminPortletWindowsnpbj:j_id58:search-user-form:searchString"
button :search_users_button, :value => "Search users"
link :delete_user, :text => "Delete"
button :submit_delete_user, :value => "Submit"
div :page_title, :class => "BreadcumbsInfoBar ClearFix"
#according to GW 7.0 dashboards
link :group, :text => /Group/
link :organization, :text => /Organization/
link :new_staff, :text => /New Staff/
link :management, :text => /Users and groups management/
link :site_editor, :text => /Site Editor/
link :edit_page, :text => /Edit Page/
link :add_page, :text => /Add New Page/
link :level_up, :class => /LevelUpArrowIcon/, :title => /Up Level/
link :save, :text => "Save"
link :gw_portlets, :text => /Groundwork Portlets/
link :finish, :class => 'EdittedSaveButton', :title => 'Finish'
link :delete_portlet, :title => /Delete Portlet/
link :edit_portlet, :title => /Edit Portlet/
link :user_management, :text => /Users and groups/
img :delete_new_user, :class => /DeleteUserIcon/
button :next, :text => /Next/
button :search_icon, :class => /SimpleSearchIcon/, :nicetitle => /Quick Search/
button :search_icon_1, :class => /SimpleSearchIcon/, :title => /Quick Search/
text_field :user_name, :id => "username"
text_field :pwd, :id => "<PASSWORD>"
text_field :confirm_pwd, :id => "<PASSWORD>"
text_field :firstname, :id => "firstName"
text_field :lastname, :id => "lastName"
text_field :mail, :id => "email"
text_field :page_name, :id => "pageName"
text_field :display_name, :id => "i18nizedLabel"
text_field :search_textbox, :id => /searchTerm/
span :no_results_message, :text => /No result found/
div :customgroup, :title => "Custom Groups"
div :event_portlet, :title => "Event Portlet"
div :droppable_area, :id => "OneColumnContainer", :class => /UIContainer EdittingContainer/
div :layout, :text => /Dashboard Layout/
div :custom_text, :class => /iceOutTxt/, :text => /No CustomGroups Available/
#end for GW7.0
in_frame(:id => 'myframe') do |frame|
link :manage_maps, :text => "Manage Maps", :frame => frame
text_field :map, :name => "map", :frame => frame
select_list :map_image_list, :name => "map_image", :frame => frame
button :submit_button, :name => "submit", :frame => frame
link :map_addicon_ddheader, :id => "map-addicon-ddheader", :frame => frame
link :host_link, :text => "Host", :frame => frame
image :background_image, :id => "background", :frame => frame
select_list :hostname_list, :id => "host_name", :frame => frame
select_list :view_type_list, :id => "view_type", :frame => frame
select_list :gadget_url_list, :id => "gadget_url", :frame => frame
text_field :x_text_field, :id => "x", :frame => frame
text_field :y_text_field, :id => "y", :frame => frame
link :service_link, :text => "Service", :frame => frame
select_list :service_description_list, :id => "service_description", :frame => frame
link :hostgroup_link, :text => "Hostgroup", :frame => frame
select_list :hostgroup_list, :id => "hostgroup_name", :frame => frame
link :servicegroup_link, :text => "Servicegroup", :frame => frame
select_list :service_name_list, :id => "servicegroup_name", :frame => frame
image :test_map_image, :src => /TestMap/, :frame => frame
link :test_map_link, :text => "TestMap", :frame => frame
link :map_link, :text => "Map", :frame => frame
select_list :map_name_list, :id => "map_name", :frame => frame
image :performance_map_image, :id => "icon_map_0", :frame => frame
end
def create_user(name, password, email)
self.create_user_account_element.when_present.click
self.wait_until(5) do
self.username_element.exists?
end
self.username = name
self.email = email
self.password = <PASSWORD>
self.confirm_password = <PASSWORD>
self.submit
self.submit_role_element.when_present.click
self.submit_confirmation_element.when_present.click
end
def create_new_user(name, password, firstname, lastname, email)
self.user_name = name
self.pwd = <PASSWORD>
self.confirm_pwd = <PASSWORD>
self.firstname = firstname
self.lastname = lastname
self.mail = email
self.save_element.click
sleep(3)
<EMAIL>.div(:class => /UIAction MessageActionBar/).link(:text => /OK/).when_present.click
<EMAIL>.span(:class => /PopupTitleIcon/).link(:class => /CloseButton/).click
end
def delete_user(user)
self.wait_until(10) do
self.search_users_textfield_element.exists?
end
self.search_users_textfield = user
self.search_users_button_element.when_present.click
sleep(2)
self.delete_user_element.when_present.click
self.submit_delete_user_element.when_present.click
end
def go_to_subtab(subtab)
@browser.link(:text => /GroundWork Administration/).fire_event 'mouseover'
#<EMAIL>.ul(:class => /MenuItemContainer/).li(:class => /MenuItem NormalItem/).link(:text => /#{subtab}/).when_present.click
@browser.link(:text => /#{subtab}/).when_present.click
end
def check_subtab(subtab)
self.wait_until(10) do
self.page_title.include? subtab
if subtab == "Foundation" || subtab == "Views"
@browser.frame(:id => "myframe").h1.text.include? @@subtab_text[subtab]
elsif subtab == "GroundWork Cloud Hub"
@browser.frame(:id => "myframe").div(:id => "container").text.include? @@subtab_text[subtab]
else
@browser.text.include? @@subtab_text[subtab]
end
end
end
end
<file_sep>class ContactsPage
include PageObject
direct_url BASE_URL + "config/contacts"
in_frame(:id => 'myframe') do |frame|
in_frame({:name => 'monarch_left'}, frame) do |frame|
#td :table, :class => /row1_menuitem/, :frame => frame
link :contacts, :text => /Contact/, :frame => frame
link :contacts_new, :text => /New/, :frame => frame
end
in_frame({:name => 'monarch_main'}, frame) do |frame_main|
text_field :contact_name, :name => /name/, :frame => frame_main
text_field :contact_alias, :name => /alias/, :frame => frame_main
text_field :contact_email, :name => /email/, :frame => frame_main
select_list :contact_template, :name => /template/, :frame => frame_main
button :contact_add, :name => "add", :frame => frame_main
button :continue, :value => "Continue", :frame => frame_main
end
end
def create_contact(name,alias_name,email)
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).td(:class => /row1_menuitem/).link(:text => /Contacts/).when_present.click
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /New/).when_present.click
sleep(5)
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).text_field(:name => /name/).when_present.set name
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).text_field(:name => /alias/).when_present.set alias_name
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).text_field(:name => /email/).when_present.set email
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).select(:name => /template/).option(:value => /generic-contact-1/).when_present.select
sleep(3)
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).td(:class => /buttons/).button(:name => /add/).when_present.click
sleep(2)
end
def create_contact_group(group_name,alias_name)
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /Contact groups/).when_present.click
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /New/).when_present.click
sleep(5)
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).text_field(:name => /name/).when_present.set group_name
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).text_field(:name => /alias/).when_present.set alias_name
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).select(:name => /contact_nonmembers/).option(:value => /contact/).when_present.select
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).button(:name => /contact_add_member/).when_present.click
sleep(3)
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).td(:class => /buttons/).button(:name => /add/).when_present.click
sleep(2)
end
def delete_contact(contact)
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).td(:class => /row1_menuitem/).link(:text => /Contacts/).when_present.click
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /Modify/).when_present.click
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /#{contact}/).when_present.click
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).td(:class => /buttons/).button(:name => /delete/).when_present.click
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).button(:value => /Yes/).when_present.click
end
def delete_contact_group(contactgroup)
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /Contact groups/).when_present.click
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /Modify/).when_present.click
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /#{contactgroup}/).when_present.click
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).td(:class => /buttons/).button(:name => /delete/).when_present.click
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).button(:value => /Yes/).when_present.click
end
def create_contact_template(name)
#@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).td(:class => /row1_menuitem/).link(:text => /Contact templates/).when_present.click
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /Contact templates/).when_present.click
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).link(:text => /New/).when_present.click
sleep(5)
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).text_field(:name => /name/).when_present.set name
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).select(:name => /host_notification_period/).when_present.select "workhours"
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).checkbox(:value => /d/).when_present.set(true)
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).checkbox(:value => /u/).when_present.set(true)
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).select(:name => /host_notification_commands/).when_present.select "host-notify-by-sendemail"
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).select(:name => /service_notification_period/).when_present.select "workhours"
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).checkbox(:value => /c/).when_present.set(true)
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).checkbox(:value => /u/).when_present.set(true)
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).select(:name => /service_notification_commands/).when_present.select "service-notify-by-sendemail"
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).td(:class => /buttons/).button(:name => /add/).when_present.click
sleep(2)
end
end
<file_sep>When /^I start new docker configuration and set all fields as "(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)"$/ do |displayname,gwserver,wsuser,passwd,docker_server,prefix,check_interval,connection_retries|
on CloudHubPage do |page|
page.display_name = displayname
page.groundwork_server = gwserver
page.wsuser_name = wsuser
page.wsuser_password = <PASSWORD>
page.app_server = docker_server
page.conn_prefix = prefix
page.interval = check_interval
page.connection_retries = connection_retries
end
end
And /^servers should be displayed on the Status viewer and Event console with host prefix "(.+)"$/ do |prefix|
sleep(75)
visit StatusviewerPage
#server_id = @browser.div(:id => /frmTree:pnlTbSet:0:hstTree-d-root-c/).span(:text => /DOCK-H:/).id
#puts server_id
@browser.div(:id => /frmTree:pnlTbSet:0:hstTree-d-root-c/).span(:text => /DOCK-H:/).when_present.click
sleep(5)
@browser.div(:id => /frmTree:pnlTbSet:0:hstTree-d-root-c/).span(:text => /#{prefix}/).when_present.click
#server.include? (/#{prefix}/)
end
When /^I select a "(.+)" service "(.+)" and set thresholds as "(.+)" and "(.+)"$/ do |type,service,warning,critical|
sleep(5)
if type == "Docker Engine"
@browser.frame(:id => /myframe/).checkbox(:id => /hyp_monitored_1/).when_present.set
@browser.frame(:id => /myframe/).text_field(:id => /hyp_warningThreshold_1/).when_present.set warning
@browser.frame(:id => /myframe/).text_field(:id => /hyp_criticalThreshold_1/).when_present.set critical
$Service1 = service
$Warning = warning
$Critical = critical
else
@browser.frame(:id => /myframe/).checkbox(:id => /vm_monitored_1/).when_present.set
@browser.frame(:id => /myframe/).text_field(:id => /vm_warningThreshold_1/).when_present.set warning
@browser.frame(:id => /myframe/).text_field(:id => /vm_criticalThreshold_1/).when_present.set critical
$Service1 = service
$Warning = warning
$Critical = critical
end
end
Then /^I verify changes are done to "(.+)" on Status viewer page$/ do |type|
sleep(60)
visit StatusviewerPage
if type == "Hypervisor"
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:4/).click
sleep(3)
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:4-0/).click
sleep(3)
@browser.link(:text => /#{$Service}/).exists?.should == false
@browser.link(:text => /#{$Service1}/).click
sleep(5)
@browser.span(:id => /SVform:SItxtServiceStatusValue/, :text => /#{"W\/C="+$Warning+"\/"+$Critical}/).exists?.should == true
else
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:2/).click
sleep(3)
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:2-0/).click
sleep(3)
@browser.link(:text => /#{$Service}/).exists?.should == false
@browser.link(:text => /#{$Service1}/).click
sleep(5)
@browser.span(:id => /SVform:SItxtServiceStatusValue/, :text => /#{"W\/C="+$Warning+"\/"+$Critical}/).exists?.should == true
end
end
And /^I remove "(.+)" service "(.+)"$/ do |type,service|
if type == "Docker Engine"
@browser.frame(:id => /myframe/).checkbox(:id => /hyp_monitored_2/).clear
$Service = service
else
@browser.frame(:id => /myframe/).checkbox(:id => /vm_monitored_4/).clear
$Service = service
end
end
When /^the connection test-docker exists$/ do
Watir::Wait.until {
@browser.frame(:id => "myframe").div(:id => /example_wrapper/).text.include? 'test_docker'
}
end
Then /^host prefix validation message should be displayed$/ do
Watir::Wait.until {
@browser.frame(:id => "myframe").div(:id => /testConResultMsg/).text.include? 'Please chose another prefix.'
}
end
Then /^validation message should be displayed$/ do
Watir::Wait.until {
@browser.alert.exists?.should == true
sleep(2)
@browser.alert.ok
}
end
<file_sep>class AdvancedPage
include PageObject
direct_url BASE_URL + "nagios"
div :page_title, :class => "BreadcumbsInfoBar ClearFix"
@@subtab_title = { "Network Graphing" => "Cacti", "Protocol Analyzer" => "ntop", "Network Map" => "weathermap", "Network Discovery" => "Nedi", "Nagios" => "Tactical View"}
@@subtab_text = { "Network Graphing" => "You are now logged into Cacti", "Protocol Analyzer" => "About", "Network Map" => "Welcome", "Network Discovery" => "Devices", "Nagios" => "Monitoring Performance"}
def go_to_subtab(subtab)
@browser.link(:text => /Advanced/).fire_event 'mouseover'
@browser.link(:text => /#{subtab}/).when_present.click
end
def check_subtab(subtab)
self.wait_until(10) do
self.page_title.include? subtab
if subtab == "Protocol Analyzer"
@browser.frame(:id => "myframe").td(:class => "ThemeOfficeMainItem").text.include? @@subtab_text[subtab]
elsif subtab == "Network Map"
@browser.frame(:id => "myframe").div(:class => "dlgTitlebar").text.include? @@subtab_text[subtab]
elsif subtab == "Network Discovery"
@browser.frame(:id => "myframe").span(:class => "ThemeNMainFolderText").text.include? @@subtab_text[subtab]
elsif subtab == "Nagios"
@browser.frame(:id => "myframe").td(:class => "perfTitle").text.include? @@subtab_text[subtab]
else
@browser.frame(:id => "myframe").div(:id => "main").text.include? @@subtab_text[subtab]
end
end
end
end
<file_sep>require 'watir-webdriver'
include Selenium
#capabilities = WebDriver::Remote::Capabilities.firefox(:javascript_enabled => true, :platform=>:any)
#browser = Watir::Browser.new(:remote, :url => "http://qa-jenkins-server:4444/wd/hub", :desired_capabilities => capabilities)
browser = Watir::Browser.new :firefox
browser.goto "http://qa-sles-10-64.groundwork.groundworkopensource.com/portal/auth/portal/groundwork-monitor"
browser.text_field(:name => 'josso_username').set 'admin'
browser.text_field(:name => 'josso_password').set '<PASSWORD>'
browser.button(:value => 'Login').click
i=0
while true do
i+=1
puts "Iteracion nro: #{i}"
browser.link(:text => "Status").when_present.click
sleep(15)
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-0:TxtNdClick").when_present.click
sleep(5)
browser.span(:id => "HGVform:eventHeader").when_present.click
sleep(15)
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-0-0:TxtNdClick").when_present.click
sleep(5)
browser.span(:id => "HVform:hostAvailHeader").when_present.click
sleep(15)
browser.span(:id => "HVform:servicelistHeader").when_present.click
sleep(5)
browser.span(:id => "HVform:eventHeader").when_present.click
sleep(5)
browser.span(:id => "HVform:commentsHeader").when_present.click
sleep(5)
browser.button(:id => "HVform:CPaddNewComment").when_present.click
sleep(3)
browser.text_field(:id => "HVform:CPtxtCommentArea").set "test"
sleep(3)
browser.button(:id => "HVform:CPcmdAddPopUpCommit").when_present.click
sleep(15)
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-0-0-0:TxtNdClick").when_present.click
sleep(5)
browser.span(:id => "SVform:serviceAvailHeader").when_present.click
sleep(5)
browser.span(:id => "SVform:eventHeader").when_present.click
sleep(15)
#Vamos a probar de cerrar el HG1 y Linux server para no tener que hacer un logout
browser.img(:src => "/portal-statusviewer/images/tree_nav_middle_close.gif").when_present.click
browser.img(:src => "/portal-statusviewer/images/tree_nav_bottom_open.gif").when_present.click
end
browser.close
<file_sep>When /^I open hosts all filter$/ do
on StatusviewerPage do |page|
page.hosts_all_link_element.when_present.click
end
end
Then /^I should see all the hosts$/ do
sleep(2)
@browser.div(:id => "frmTree:pnlTbSet:0:hstTree-d-1-c").when_present.divs.to_a.count.should == 10
end
When /^I open group all filter$/ do
on StatusviewerPage do |page|
page.services_link_element.when_present.click
page.group_all_link_element.when_present.click
end
$mapsInfo = Array.new
$mapsInfo << NagvisMapInfo.new("hostgroups")
$mapsInfo << NagvisMapInfo.new("servicegroups")
$mapsInfo << NagvisMapInfo.new("submaps")
#$mapsInfo << NagvisMapInfo.new("Hosts_Up")
#$mapsInfo << NagvisMapInfo.new("geomap")
end
Then /^I should see all the services$/ do
sleep(2)
service_number = @browser.div(:id => "frmTree:pnlTbSet:0:treeSrvc-d-0-c").divs.to_a.count / 2
service_number.should == 10
end
Given /^I am on the Nagvis View Page$/ do
visit NagvisViewsPage
@browser.driver.manage.window.maximize
#Need to remove these declarations
$mapsInfo = Array.new
$mapsInfo << NagvisMapInfo.new("hostgroups")
$mapsInfo << NagvisMapInfo.new("servicegroups")
$mapsInfo << NagvisMapInfo.new("submaps")
#$mapsInfo << NagvisMapInfo.new("Hosts_Up")
#$mapsInfo << NagvisMapInfo.new("geomap")
end
When /^I hover the hostsGroup map$/ do
hosts_group_map_info = @browser.frame(:id => "myframe").link(:id => "map-3-icon")
hosts_group_map_info.hover
end
When /^I hover the "(.*?)"$/ do |map_name|
on NagvisViewsPage do |page|
$map = page.obtainMap(map_name)
sleep(4)
$map.hover
sleep(4)
end
end
Then /^the "(.*?)" summary state should be "(.*?)"$/ do |map_name, state|
on NagvisViewsPage do |page|
index = page.map_index["#{map_name}"]
page.validateState(state,index).should == true
end
end
Then /^the "(.*?)" summary output should match$/ do |map_name|
on NagvisViewsPage do |page|
index = page.map_index["#{map_name}"]
output = $mapsInfo[index].output
page.validateOutput(output,index).should == true
end
end
Then /^the "(.*?)" map child information should match$/ do |map_name|
on NagvisViewsPage do |page|
index_map = page.map_index["#{map_name}"]
puts index_map
children = $mapsInfo[index_map].children
page.validateChildren(children,index_map)
end
end
Given /^I click on "(.*?)" map$/ do |map_name|
on NagvisViewsPage do |page|
map = page.obtainMap(map_name)
sleep(4)
map.when_present.click
sleep(10)
end
end
When /^I hover "(.*?)" icon on "(.*?)" map$/ do |host_group_name,map_name|
on NagvisViewsPage do |page|
id = "#{map_name}-#{host_group_name}"
$icon = page.obtainIcon(id)
sleep(4)
$icon.hover
sleep(4)
end
end
Then /^the Host "(.*?)" state should be "(.*?)"$/ do |host_group_name, state|
on NagvisViewsPage do |page|
index = page.hostgroup_index["#{host_group_name}"]
page.validateState_embedded_map(state,index).should == true
end
end
Then /^the Host "(.*?)" output should match$/ do |host_group_name|
on NagvisViewsPage do |page|
index = page.hostgroup_index["#{host_group_name}"]
output = $mapsInfo[0].group["#{host_group_name}"]["output"]
page.validateOutput_embedded_map_hostgroups(output,index).should == true
end
end
Then /^the Host "(.*?)" child information should match$/ do |host_group_name|
on NagvisViewsPage do |page|
index = page.hostgroup_index["#{host_group_name}"]
children = $mapsInfo[0].group["#{host_group_name}"]["children"]
page.validateChildren(children,index)
end
end
Then /^the Service "(.*?)" state should be "(.*?)"$/ do |service_group_name, state|
on NagvisViewsPage do |page|
index = page.servicegroup_index["#{service_group_name}"]
page.validateState_embedded_map(state,index).should == true
end
end
Then /^the Service "(.*?)" output should match$/ do |service_group_name|
on NagvisViewsPage do |page|
index = page.servicegroup_index["#{service_group_name}"]
output = $mapsInfo[1].group["#{service_group_name}"]["output"]
page.validateOutput_embedded_map_groups(output,index)
end
end
Then /^the Service "(.*?)" child information should match$/ do |service_group_name|
on NagvisViewsPage do |page|
index = page.servicegroup_index["#{service_group_name}"]
children = $mapsInfo[1].group["#{service_group_name}"]["children"]
page.validateChildren(children,index)
end
end
Then /^the Map "(.*?)" state should be "(.*?)"$/ do |map_name, state|
on NagvisViewsPage do |page|
index = page.mapname_index["#{map_name}"]
page.validateState_embedded_map(state,index).should == true
end
end
Then /^the Map "(.*?)" output should match$/ do |map_name|
on NagvisViewsPage do |page|
index = page.mapname_index["#{map_name}"]
output = $mapsInfo[2].group["#{map_name}"]["output"]
page.validateOutput_embedded_map_groups(output,index)
end
end
Then /^the Map "(.*?)" child information should match$/ do |map_name|
on NagvisViewsPage do |page|
index = page.mapname_index["#{map_name}"]
children = $mapsInfo[2].group["#{map_name}"]["children"]
page.validateChildren(children,index)
end
end
Given /^I select the map "(.*?)"$/ do |map_name|
on NagvisViewsPage do |page|
map = page.obtainIcon("map-#{map_name}")
sleep(4)
map.when_present.click
sleep(4)
end
end
Then /^the Host Up "(.*?)" state should be "(.*?)"$/ do |host_name, state|
on NagvisViewsPage do |page|
index = page.hostup_index["#{host_name}"]
puts index
page.validateState_second_level_maps(state,index).should == true
end
end
Then /^the Host Up "(.*?)" output should match$/ do |host_name|
on NagvisViewsPage do |page|
index = page.hostup_index["#{host_name}"]
puts index
output = $mapsInfo[3].group["#{host_name}"]["output"]
page.validateOutput(output,index).should == true
end
end
Then /^the Host Up "(.*?)" child information should match$/ do |host_name|
on NagvisViewsPage do |page|
index = page.hostup_index["#{host_name}"]
children = $mapsInfo[3].group["#{host_name}"]["children"]
page.validateChildren(children,index)
end
end
Then(/^the Host Up "(.*?)" "(.*?)" should match$/) do |host_name, attribute|
on NagvisViewsPage do |page|
index = page.hostup_index[host_name]
json_attribute = $mapsInfo[3].group[host_name][attribute]
page.validateAttribute(attribute, json_attribute, index).should == true
end
end
#OptimusComment: Moved step definitions from Bug folder
Given /^I create a new map$/ do
on AdministrationViewPage do |page|
page.map= 'GadgetMap'
page.map_image_list='dc_floorplan.png'
page.submit_button_element.when_present.click
@browser.frame(:id => "myframe").table(:id, "messageBox").when_present.wait_while_present
end
end
When /^I add a gadget raw number icon for service$/ do
on AdministrationViewPage do |page|
@browser.frame(:id => "myframe").dt(:id => "map-ddheader").when_present.hover
page.map_addicon_ddheader_element.when_present.hover
page.service_link_element.when_present.click
page.background_image_element.when_present.click
page.hostname_list="localhost"
page.service_description_list="local_cpu_nagios"
page.x_text_field='200'
page.y_text_field='200'
page.view_type_list="gadget"
page.gadget_url_list="rawNumbers.php"
page.submit_button
@browser.frame(:id => "myframe").table(:id, "messageBox").when_present.wait_while_present
end
end
When /^I add a gadget chart pie icon for service$/ do
on AdministrationViewPage do |page|
@browser.frame(:id => "myframe").dt(:id => "map-ddheader").when_present.hover
page.map_addicon_ddheader_element.when_present.hover
page.service_link_element.when_present.click
page.background_image_element.when_present.click
page.hostname_list="localhost"
page.service_description_list="local_mem_nagios"
page.x_text_field='200'
page.y_text_field='320'
page.view_type_list="gadget"
page.gadget_url_list="pChartPieChart.php"
page.submit_button
@browser.frame(:id => "myframe").table(:id, "messageBox").when_present.wait_while_present
end
end
When /^I add a gadget bar icon for service$/ do
on AdministrationViewPage do |page|
@browser.frame(:id => "myframe").dt(:id => "map-ddheader").when_present.hover
page.map_addicon_ddheader_element.when_present.hover
page.service_link_element.when_present.click
page.background_image_element.when_present.click
page.hostname_list="localhost"
page.service_description_list="local_nagios_latency"
page.x_text_field='200'
page.y_text_field='400'
page.view_type_list="gadget"
page.gadget_url_list="std_bar.php"
page.submit_button
@browser.frame(:id => "myframe").table(:id, "messageBox").when_present.wait_while_present
end
end
When /^I add a gadget thermo icon for service$/ do
on AdministrationViewPage do |page|
@browser.frame(:id => "myframe").dt(:id => "map-ddheader").when_present.hover
page.map_addicon_ddheader_element.when_present.hover
page.service_link_element.when_present.click
page.background_image_element.when_present.click
page.hostname_list="localhost"
page.service_description_list="local_disk_root"
page.x_text_field='70'
page.y_text_field='100'
page.view_type_list="gadget"
page.gadget_url_list="thermo.php"
page.submit_button
@browser.frame(:id => "myframe").table(:id, "messageBox").when_present.wait_while_present
end
end
Then /^I should be able to see the map with the (\d+) gadgets$/ do |arg1|
on NagvisViewsPage do |page|
page.test_map_image_element.exists?
page.gadget_raw_number_image_element.exists?
page.gadget_thermo_image_element.exists?
page.gadget_bar_image_element.exists?
page.gadget_chart_pie_image_element.exists?
end
end
<file_sep>$Odl
Given /^I am on the Net Hub page$/ do
visit NetHubPage
end
When /^I start a new configuration and set all fields as "(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)"$/ do |displayname,gwserver,wsuser,wsuserpwd,odlserver,username,pwd,interval|
on NetHubPage do |page|
page.display_name = displayname
page.groundwork_server = gwserver
page.odl_server = odlserver
page.username = username
page.password = pwd
page.wsuser_name = wsuser
page.wsuser_pwd = <PASSWORD>
page.interval = interval
end
$Odl = odlserver[0...11]
end
Then /^ODL-H and ODl-M servers should be displayed on the Status viewer and Event console page$/ do
sleep(45)
visit StatusviewerPage
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree/, :text => /#{"ODL-H:"+$Odl}/).exists?.should == true
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree/, :text => /#{"ODL-M:"+$Odl}/).exists?.should == true
=begin
on StatusviewerPage do |page|
$Odl
page.ODL_H_element.exists?.should == true
page.ODL_M_element.exists?.should == true
end
=end
visit EventconsolePage
on EventconsolePage do |page|
page.host_groups_events_element.when_present.click
sleep(10)
#page.ODL_H_element.exists?.should == true
#page.ODL_M_element.exists?.should == true
end
@browser.link(:text => /#{"ODL-H:"+$Odl}/).exists?.should == true
@browser.link(:text => /#{"ODL-M:"+$Odl}/).exists?.should == true
end
Then /^error messages should be displayed$/ do
Watir::Wait.until {
@browser.frame(:id => "myframe").span(:text => /Not a valid number./).exists?.should==true
}
end
And /^I add a "(.+)" service "(.+)"$/ do |type,service|
if type == "Network Controller"
table = @browser.frame(:id => /myframe/).table(:id => /example/, :class => /display/)
table_row = table.td(:text => service).parent
table_row.checkbox(:id => /monitored/).set
sleep(5)
$Service = service
else
@browser.frame(:id => /myframe/).checkbox(:id => /vm_monitored_1/).set
$Service = service
end
end
Then /^I verify service is added to "(.+)" on the Status viewer page$/ do |type|
sleep(60)
visit StatusviewerPage
if type == "Network Controller"
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:3/).click
sleep(3)
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:3-0/).click
sleep(3)
@browser.link(:text => /#{$Service}/).exists?.should == true
else
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:2/).click
sleep(3)
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:2-0/).click
sleep(3)
@browser.link(:text => /#{$Service}/).exists?.should == true
end
end
<file_sep>class HostsConfigurationPage
include PageObject
direct_url BASE_URL + "config/hosts"
def remove_host(host_IP, host_name)
short_IP = host_IP[0,11]+"*"
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Delete hosts/).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select_list(:name => "search").when_present.select short_IP
if browser.text.include? (host_name)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:value => host_name).set
else
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:value => host_IP).set
end
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:value => "Delete").when_present.click
end
def remove_all_host(subnet_name)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => "Delete hosts").when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select_list(:name => "search").when_present.select subnet_name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:value => "Check All").when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:value => "Delete").when_present.click
end
def open_generic_host
frame = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frame.link(:text => /Host templates/).when_present.click
frame.link(:text => /Modify/).when_present.click
frame.link(:text => /generic-host/).when_present.click
end
end
<file_sep>import time
from fabric.api import *
from fabric.contrib.files import *
from fabric.utils import *
env.keepalive = 10
env.shell = "/bin/bash -l -i -c"
build_host = 'morat'
bitsize = '64'
edition = 'groundworkenterprise'
user = 'root'
build_storage_dir = '/var/www/html/tools/DEVELOPMENT/builds/BitRock/6.0' # Daily Build directory on morat server
install_dir = '/usr/local/groundwork'
build_dir ='/qa' #The basic directory where this script and required folders are present.
def setup():
if not exists(build_dir):
run('mkdir -p ' + build_dir)
run('rm -rf ' + build_dir + '/*')
def cleangwos():
with settings(warn_only=True), cd(build_dir):
run('service groundwork status')
run(install_dir + '/uninstall --mode unattended')
run('rm -f /tmp/bitrock_installer*')
run('pkill -SIGKILL -u nagios')
run('killall nagios')
run('fuser -k -n tcp 80')
run('killall -s 9 httpd')
run('pkill -SIGKILL -u mysql')
run('fuser -k -n tcp 3306')
run('killall -s 9 postgres')
run('pkill -SIGKILL perl.bin')
run('userdel nagios')
run('userdel mysql')
run('userdel postgres')
run('rm -rf ' + install_dir)
def download(version = "latest"):
with cd(build_dir):
if version == "latest":
#latest
filename = run('ssh ' + user + '@' + build_host + ' ls -c -t ' + build_storage_dir + '/ |grep ${edition}- |head -1')
if not exists(filename):
run('scp ' + user + '@' + build_host + ':' + build_storage_dir + '/' + filename + ' ' + build_dir + '/' + filename)
run('chmod +x ' + build_dir + '/' + filename)
if version == "6.7":
run('wget -N http://morat/build/builds/BitRock/6.0/groundworkenterprise-6.7.0-br287-gw1571-linux-64-installer.run')
if version == "6.6.1":
run('wget -N http://morat/build/builds/BitRock/6.0/groundworkenterprise-6.6.1-br254-gw1311-linux-64-installer.run')
if version == "6.6":
run('wget -N http://morat/build/releases/6_6_0/groundworkenterprise-6.6.0-br238-gw1248-linux-64-installer.bin')
if version == "6.5":
run('wget -N http://morat/build/releases/6_5/groundworkenterprise-6.5.0-br220-gw1197-linux-64-installer.bin')
if version == "6.4":
run('wget -N http://morat/build/releases/6_4/groundworkenterprise-6.4-br212-gw1035-linux-64-installer.bin')
if version == "6.3":
run('wget -N http://morat/build/releases/6_3/groundworkenterprise-6.3-br194-gw893-linux-64-installer.bin')
run('chmod +x *')
def install(version = "latest"):
with cd(build_dir):
run('touch /tmp/gw-backup-20120827141505.tar.gz')
if version == "latest":
filename = run('ls -c -t | sort -r | grep ${edition}- |head -1')
run('./' + filename + ' --mode unattended --postgres_password 123')
else:
filename = run('ls groundworkenterprise-' + version + '* |head -1')
if (version >= '6.6'):
run('./' + filename + ' --mode unattended --postgres_password 123')
elif (version < '6.6'):
run('./' + filename + ' --mode unattended --mysql_password 123')
run('service groundwork status')
time.sleep(60)
jbosspid = run('ps -ef |grep -v grep|grep "jboss"|awk "{print $2}"')
run('/usr/local/groundwork/foundation/feeder/find_cacti_graphs')
run('service groundwork status')
# abort
def uploadlatestbuild():
download("latest")
filename = run('ssh ' + user + '@' + build_host + ' ls -c -t ' + build_storage_dir + '/ |grep ${edition}- |head -1')
if 's3://Groundwork/' + filename != run('s3cmd ls s3://Groundwork/' + filename + '| awk \'{print $4}\''):
run('s3cmd put ' + build_dir + '/' + filename + ' s3://Groundwork/' + filename)
run('s3cmd setacl --acl-public --recursive s3://Groundwork')
else:
print 'Build already in bucket'
<file_sep>class MyGroundworkPage
include PageObject
require 'yaml'
fn = File.dirname(File.expand_path(__FILE__)) + '/../../features/support/config.yml'
configFile = YAML::load(File.open(fn))
hostname = ENV['SERVER'] || configFile['server']
direct_url "http://#{hostname}/portal/auth/dashboard/default"
@@subtab_title = { "Welcome" => "My Groundwork", "Configure" => "My Groundwork Configuration"}
@@subtab_text = { "Welcome" => "application is used to create personal views of monitoring information.", "Configure" => "My Groundwork Page Editor"}
def go_to_subtab(subtab)
@browser.link(:text => /MyGroundwork/).when_present.hover
@browser.link(:text => subtab).when_present.click
end
def check_subtab(subtab)
self.wait_until(10) do
@browser.text.include? @@subtab_title[subtab]
if subtab == "Welcome"
@browser.frame.p.text.include? @@subtab_text[subtab]
else
@browser.text.include? @@subtab_text[subtab]
end
end
end
end
<file_sep>Given /^I select the report "(.+)"$/ do |report|
on ReportsPage do |page|
page.select_report(report)
end
end
And /^I select the parameters for viewing the report "(.+)"$/ do |report|
on ReportsPage do |page|
if report == 'event history overview'
page.event_reports_element.when_present.click
else
page.open_report(report)
end
end
end
Then /^I should be able to view the "(.+)" as selected$/ do |report|
on ReportsPage do |page|
page.verify_report(report)
end
end
<file_sep>class BSMPage
include PageObject
direct_url BASE_URL + "business-tools"
div :page_title, :class => "BreadcumbsInfoBar ClearFix"
link :hostname, :href => "http://qa-ubuntu-12-4-64.groundwork.groundworkopensource.com/portal-statusviewer/urlmap?host=localhost"
@@subtab_text = { "Business Service Monitoring" => "Business", "SLA Management" => "Service level Management", "SLA Reports" => "Reports", "SLA" => "SLA", "Calendar" => "Calendars", "Holidays" => "Holidays", "Operation Time" => "Manage your operation time!", "Contracts" => "Manage contracts!", "Downtimes" => "Downtimes" }
def go_to_subtab(subtab)
if subtab == "SLA" || subtab == "Calendar" || subtab == "Holidays" || subtab == "Operation Time" || subtab == "Contracts" || subtab == "Downtimes"
@browser.link(:text => /Business/).fire_event 'mouseover'
@browser.link(:text => /SLA Management/).fire_event 'mouseover'
@browser.link(:text => /#{subtab}/).when_present.click
else
@browser.link(:text => /Business/).fire_event 'mouseover'
@browser.link(:text => /#{subtab}/).when_present.click
end
end
def check_subtab(subtab)
self.wait_until(10) do
self.page_title.include? subtab
@browser.frame(:id => "myframe").div(:id => 'content').text.include? @@subtab_text[subtab]
end
end
end
<file_sep>class StatusviewerPage
include PageObject
direct_url BASE_URL + "status"
span :pending_host_groups_statics, :id =>'frmNV:tblHostGroupStatistics:3:outputtxtTotalValue'
span :pending_host_statics, :id =>'frmNV:tblhostStatistics:3:outputtxtHostTotalValue'
span :pending_service_groups_statics, :id =>'frmNV:tblServiceGroupStatistics:4:outputtxtTotalValue'
span :pending_service_statics, :id =>'frmNV:tblServiceStatistics:4:outputtxtServiceTotalValue'
span :total_services, :id => "frmNV:tblServiceStatistics:outtxtTotalServiceCount"
span :total_hosts, :id => "frmNV:tblhostStatistics:outputtxtTotalHostCount"
span :performance_filter, :text =>'Host Availability & Performance Measurement'
image :host_graph, :id => 'HVform:j_id957'
span :linux_servers, :text => /Linux Servers/
span :localhost, :text => 'localhost'
span :local_cpu_httpd, :text => /local_cpu_httpd/
#for scheduling downtime
span :downtime, :text => /Downtime/
span :schedule_downtime, :text => /Schedule Downtime/
textarea :comment, :id => /HVform:actionsPortlet_txtComment/
select_list :type_down, :id => "HVform:actionsPortlet_menuType"
button :downtime_button, :id => "HVform:actionsPortlet_btnSubmit"
span :downtime_value, :id => "HVform:HItxtHostDowntimeValue"
span :downtime_comment_tab, :id => "HVform:commentsHeader"
span :downtime_comment, :id => /HVform:CPtblComments:0/
#for scheduling service downtime
text_field :service_comment, :id => /SVform:actionsPortlet_txtComment/
select_list :service_type_down, :id => "SVform:actionsPortlet_menuType"
button :service_downtime_button, :id => "SVform:actionsPortlet_btnSubmit"
span :service_downtime_value, :id => "SVform:SItxtServiceDowntimeValue"
span :service_downtime_comment, :id => /SVform:CPtblComments:0/
span :logged_in_user, :id =>'HVform:tblperfmeasurement_Portlet:1:PMpnlCollapsible_outtxt'
image :logged_in_user_image, :id =>'HVform:tblperfmeasurement_Portlet:1:j_id991'
span :memory_usage, :id =>'HVform:tblperfmeasurement_Portlet:2:PMpnlCollapsible_outtxt'
image :memory_usage_image, :id =>'HVform:tblperfmeasurement_Portlet:2:j_id991'
span :processes_usage, :id =>'HVform:tblperfmeasurement_Portlet:3:PMpnlCollapsible_outtxt'
image :processes_usage_image, :id =>'HVform:tblperfmeasurement_Portlet:3:j_id991'
#span :custom_group, :class => "iceOutTxt", :text => "CG1"
#div :custom_group, :id => /frmTree:pnlTbSet:0:hstTree/, :text => "CG1"
div :custom_group, :id => /frmTree:pnlTbSet:0:hstTree-d-0/
link :hosts_link, :id => "frmTree:pnlTbSet:0.0"
link :services_link, :id => "frmTree:pnlTbSet:0.1"
link :open_servicegroup, :id => "frmTree:pnlTbSet:0:treeSrvc:0"
link :local_cpu_httpd, :text => "local_cpu_httpd"
#link :icmp_ping_alive, :text => "icmp_ping_alive"
span :check_results, :text => /Check Results/
span :passive_result, :text => /Submit Passive Check Result/
#for services check
text_field :check_output, :id => "SVform:actionsPortlet_txtCheckOutputValue"
text_field :performance_data, :id => "SVform:actionsPortlet_txtPerformanceDataValue"
select_list :check_results_list, :id => "SVform:actionsPortlet_menuCheckResult"
button :submit_button_service, :id => /SVform:actionsPortlet_btnSubmit/
#for hosts check
text_field :check_output_host, :id => /txtCheckOutputValue/
text_field :performance_data_host, :id => /txtPerformanceDataValue/
select :check_results_list_host, :id => /menuCheckResult/
button :submit_button_host, :id => /HVform:actionsPortlet_btnSubmit/
select_list :downtime_option, :id => /HVform:actionsPortlet_menuType/
link :hosts_tab, :id => /frmTree:pnlTbSet:0.0/, :name => /frmTree:pnlTbSet:0.0/
link :services_tab, :id => /frmTree:pnlTbSet:0.1/, :name => /frmTree:pnlTbSet:0.1/
link :search_tab, :id => /frmTree:pnlTbSet:0.2/, :name => /frmTree:pnlTbSet:0.2/
text_field :search_box, :id => "frmTree:pnlTbSet:0:STtxtSearchQuery"
button :search_button, :value => "Go"
span :search_count, :id => "frmTree:pnlTbSet:0:STtxtSearchCount"
span :search_result, :id => /frmTree:pnlTbSet:0:STtblResults:0:STsrchNdClick/, :text => /localhost/
link :hosts_all_link, :id => "frmTree:pnlTbSet:0:hstTree:0"
link :group_all_link, :id => "frmTree:pnlTbSet:0:treeSrvc:0"
div :page_title, :class => "BreadcumbsInfoBar ClearFix"
span :page_text, :id => "frmNV:HostGrpStatusPortlet_TxtHstGpStats"
link :status, :text => "Status"
span :host_status, :text => "BSM:Business Objects"
span :hostname, :text => "baden"
link :zurich, :id => "frmTree:pnlTbSet:0:hstTree:7"
link :linux_host_machine, :id => "frmTree:pnlTbSet:0:hstTree:7-3"
span :bern_host_machine, :text => /VEMA:bern/
span :cpu_usage, :text => /summary.quickStats.overallCpuUsage/
link :vss_vermont, :id => "frmTree:pnlTbSet:0:hstTree:8"
link :vss_zurich, :id => "frmTree:pnlTbSet:0:hstTree:8-4"
link :zurich, :id => "frmTree:pnlTbSet:0:hstTree:7"
span :cpu_uptime, :text => /summary.quickStats.uptimeSeconds/
select :filter, :id => /frmTree:pnlTbSet:0:STmenuSortSelect/
link :net_view, :id => /frmTree:pnlTbSet:0:hstTree/, :text => /NET:/
link :pool_view, :id => /frmTree:pnlTbSet:0:hstTree/, :text => /POOL:/
link :storage_view, :id => /frmTree:pnlTbSet:0:hstTree/, :text => /STOR:/
link :esx_bernina,:id => /frmTree:pnlTbSet:0:hstTree/, :text => /ESX:bernina/
link :esx_morges,:id => /frmTree:pnlTbSet:0:hstTree/, :text => /ESX:morges/
link :esx_thun,:id => /frmTree:pnlTbSet:0:hstTree/, :text => /ESX:thun/
link :esx_wil,:id => /frmTree:pnlTbSet:0:hstTree/, :text => /ESX:wil/
link :esx_zurich,:id => /frmTree:pnlTbSet:0:hstTree/, :text => /ESX:zurich/
span :esx_vss_zurich,:text => /VEMA:zurich.groundwork.groundworkopensource.com/
link :esx_vssvermont,:id => /frmTree:pnlTbSet:0:hstTree/, :text => /VSS:vermont/
link :rhev_vm, :id => /frmTree:pnlTbSet:0:hstTree/, :text => /RHEV-H:/
link :rhev_m, :id => /frmTree:pnlTbSet:0:hstTree/, :text => /RHEV-M:eng-rhev-m-1.groundwork.groundworkopensource.com/
#entire network page
span :entire_network, :text => /Entire Network/
#disable/enable notifications
span :notification, :text => /Notifications/
span :disable_notification, :text => 'Disable Notifications'
button :submit_button, :name => /HVform:actionsPortlet_btnSubmit/
span :enable_notification, :text => /Enable Notifications/
#disable/enable active checks for hosts
span :settings, :text => /Settings/
span :disable_active_check, :text => /Disable Active Checks on Host/
link :verify_disable_active_check_host_summary, :text => /Enable Check/
span :enable_active_check, :text => /Enable Active Checks on Host/
link :verify_enable_active_check_host_summary, :text => /Disable Check/
#disable/enable passive checks for hosts
span :disable_passive_check_host, :text => /Disable Passive Checks/
span :enable_passive_check_host, :text => /Enable Passive Checks/
#disable/enable flap detection for hosts
span :disable_flap_detection_host, :text => /Disable Flap Detection/
span :enable_flap_detection_host, :text => /Enable Flap Detection/
#disable/enable event handler for hosts
span :event_handlers_dropdown, :text => /Event Handlers/
span :disable_event_handlers_host, :text => /Disable Event Handler/
span :enable_event_handlers_host, :text => /Enable Event Handler/
span :reschedule_next_check, :text => /Re-Schedule the Next Check/
text_field :next_check_time, :id => /HVform:actionsPortlet_txtCheckTimeValue/
checkbox :force_check, :name => /HVform:actionsPortlet_chkBoxForceCheck/
text_field :search_box, :name => /frmTree:pnlTbSet:0:STtxtSearchQuery/
button :go_search, :name => /frmTree:pnlTbSet:0:STsearchTreePortlet_btnSearch/
span :host_last_check, :id => /HVform:HItxtLastCheckTime/
span :service_local_cpu, :text => /local_cpu_httpd/
span :service_last_check, :id => /SVform:SItxtLastCheckTime/
span :host_availability_portlet, :text => /Host Availability & Performance Measurement/
select :host_availability_dropdown, :id => /HVform:HAmenuTimeSelector/
text_field :start_time_host_portlet, :name => /HVform:HAstartDateTime/
text_field :end_time_host_portlet, :name => /HVform:HAendDateTime/
button :apply_host_portlet, :name => /HVform:HAsubmitApply/
#Acknowledge
link :acknowledge, :text => /Acknowledge/
#span :acknowledge, :text => /Acknowledge/
span :acknowledge_host, :text => /Acknowledge This Host Problem/
checkbox :services_ack, :class => /iceSelBoolChkbx portlet-form-field/
textarea :acknowledge_comment, :id => /HVform:actionsPortlet_txtComment/
button :submit_ack, :id => /HVform:actionsPortlet_btnSubmit/
checkbox :services_check_result_ack, :class => /iceSelOneMnu portlet-form-field/
text_field :check_output, :name => /SVform:actionsPortlet_txtCheckOutputValue/
text_field :perf_data, :name => /SVform:actionsPortlet_txtPerformanceDataValue/
button :submit_ack_service, :name => /SVform:actionsPortlet_btnSubmit/
span :remove_acknowledge, :text => /Remove Acknowledgment of Problem/
#calendar
image :calendar_img1, :id => /HVform:j_id879/
image :calendar_img2, :id => /HVform:j_id881/
td :start_date, :class => /day/, :text => /14/
td :end_date, :class => /day/, :text => /16/
#delete comment
button :delete_comment, :name => /CPcmdDeleteComment/
button :commit, :name => /CPcmdDeletePopUpCommit/
link :group_for_host, :id => /HVform:linkGroupPoup/, :text => /Groups for this Host/
span :group_for_host_linuxservers, :text => /Linux Servers/
button :close_window, :name => /HVform:btnGroupPopClose/, :title => /Close Window/
def state_pending?
self.pending_host_groups_statics_element.when_present.text != '0' or
self.pending_host_statics_element.when_present.text != '0' or
self.pending_service_groups_statics_element.when_present.text != '0' or
self.pending_service_statics_element.when_present.text != '0'
end
def select_host(hostGroup, host, patch_host)
@browser.span(:text => "#{hostGroup}").when_present.click
sleep(3)
@browser.span(:text => "#{patch_host}").when_present.click
if host == ""
@browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-0-3:TxtNdClick").when_present.click
else
@browser.span(:text => "#{host}").when_present.click
end
end
def get_host(index)
tree = @browser.div(:id => "frmTree:pnlTbSet:0:treeSrvc-d-0-c").when_present
element = tree.div(:class => "iceTreeRow", :index => index)
element.text[/\(.*?\)/].gsub('(','').gsub(')','')
end
#for service status
def submit_check_results(state)
#self.check_results_element.when_present.click
self.check_results_element.when_dom_changed.click
sleep(2)
if self.passive_result_element.exists?
#self.passive_result_element.when_present.click
self.passive_result_element.when_dom_changed.click
else
#self.check_results_element.when_present.click
self.check_results_element.when_dom_changed.click
#self.passive_result_element.when_present.click
self.passive_result_element.when_dom_changed.click
end
self.check_results_list = state
self.check_output = state
self.performance_data = state
end
#for host status
def submit_check_results_host(state)
self.check_results_element.wait_while_present(60)
self.check_results_element.when_dom_changed.click
if self.passive_result_element.exists?
self.passive_result_element.when_dom_changed.click
else
self.check_results_element.wait_while_present(60)
self.check_results_element.when_dom_changed.click
self.passive_result_element.when_dom_changed.click
end
@browser.div(:id => /HVform:actionsPortlet_panelPopupExecute/).wait_until_present(60)
if @browser.div(:id => /HVform:actionsPortlet_panelPopupExecute/).exists?
puts 'Proceeding with required inputs'
else
self.check_results_element.when_dom_changed.click
self.passive_result_element.when_dom_changed.click
end
self.check_results_list_host = state
self.check_output_host = state
self.performance_data_host = state
self.submit_button_host_element.when_present.click
sleep(15)
end
def search_for_host(host)
self.search_tab_element.when_present.click
self.wait_until(10) do
self.search_box_element.exists?
end
self.search_box = host
sleep(2)
self.search_button
sleep(2)
results = self.search_count
results.split(" ")[0].to_i
end
def results_not_found(host)
self.search_tab_element.when_present.click
self.wait_until(10) do
self.search_box_element.exists?
end
self.search_box = host
sleep(1)
self.search_button
sleep(2)
@browser.text.include? "No results found"
end
def status_verify(view)
if view == "Storage View"
self.storage_view_element.exists?.should == true
self.storage_view_element.when_present.click
sleep(5)
elsif view == "Network View"
self.net_view_element.exists?.should == true
self.net_view_element.when_present.click
sleep(5)
elsif view == "Resource Pool"
self.pool_view_element.exists?.should == true
self.pool_view_element.when_present.click
sleep(5)
end
end
def selecthost(hostgroup, host)
@browser.span(:text => hostgroup).when_present.click
sleep(3)
@browser.span(:text => host).when_present.click
sleep(2)
end
def select_hostname(host)
self.linux_servers_element.when_present.click
@browser.div(:id => /frmTree:pnlTbSet:0:hstTree/).span(:text => /#{host}/).when_present.click
#@browser.span(:text => host).when_present.click
end
def downtime(option,comment,time)
self.downtime_element.wait_until_present(60)
self.downtime_element.when_dom_changed.click
if self.schedule_downtime_element.exists?
self.schedule_downtime_element.when_dom_changed.click
else
self.downtime_element.wait_until_present(60)
self.downtime_element.when_dom_changed.click
self.schedule_downtime_element.when_dom_changed.click
end
@browser.div(:id => /HVform:actionsPortlet_panelPopupExecute/).wait_until_present(60)
@browser.textarea(:name => /HVform:actionsPortlet_txtComment/).set comment
self.downtime_option = option
if option == 'Flexible'
@browser.text_field(:name => /HVform:actionsPortlet_txtHours/).set time
@browser.text_field(:name => /HVform:actionsPortlet_txtMinutes/).set time
@browser.button(:name => /HVform:actionsPortlet_btnSubmit/).when_present.click
else
@browser.button(:name => /HVform:actionsPortlet_btnSubmit/).when_present.click
sleep(3)
end
end
def verify_hostdown_entire_network(host,state)
@browser.link(:id => /frmNavigationTabset:icePnlTbSet:0:icePnlTabClick/).span(:text => /Entire Network/).when_present.click
@browser.link(:id => /frmNV:tblhostStatistics:1:lnkhoststatus/,:text => state).when_present.click
sleep(1)
@browser.span(:text => host).when_present.exists?.should == true
end
def verify_hostdown_hostgroup(state)
@browser.span(:text => /Linux Servers/).when_present.click
@browser.span(:text => /#{state.capitalize}/).when_present.exists?.should == true
end
def verify_hoststatus_hostsummary(state)
sleep(10)
@browser.table(:id => /HVform:HVpanel15/).div(:id => /HVform:panelGridHostHealthInfo/).tr(:index => 2).td(:index => 1).span(:id => /HVform:txtHostState/, :text => /#{state.capitalize}/).wait_until_present(60)
puts 'State verified'
end
def verify_hoststatus_entire_network(host,state,index)
sleep(10)
@browser.span(:text => /Entire Network/).when_present(60).click
@browser.table(:id => /frmNV:tblhostStatistics/).link(:text => /#{state.capitalize}/).when_present(60).click
@browser.div(:id => /frmNV:pnlpopuphost/).wait_until_present(60)
@browser.div(:id => /frmNV:pnlpopuphost/).table(:id => /frmNV:tblhostListDatatable/).span(:text => /#{host}/).exists?.should == true
end
def verify_hoststatus_hostgroup(host,state)
sleep(10)
@browser.span(:text => /Linux Servers/).when_present.click
@browser.table(:id => /HGVform:tblhostStatistics/).wait_until_present
@browser.table(:id => /HGVform:tblhostStatistics/).link(:text => /#{state.capitalize}/).when_present(100).click
sleep(3)
@browser.div(:id => /HGVform:pnlpopuphost/).wait_until_present(60)
HGVform:tblhostListDatatable
@browser.div(:id => /HGVform:pnlpopuphost/).table(:id => /HGVform:tblhostListDatatable/).span(:text => /#{host}/).exists?.should == true
end
def navigate_entire_network
@browser.link(:id => /frmNavigationTabset:icePnlTbSet:0:icePnlTabClick/).span(:text => /Entire Network/).when_present.click
end
def verify_notification_disable_entire_network(host)
@browser.link(:id => /frmNV:nagiosPortlet_linkNotificationsHosts/).when_present(100).click
sleep(2)
@browser.span(:text => host).when_present(200).exists?.should == true
end
def verify_notification_disable_host_summary
@browser.link(:text => /Enable Notifications/).when_present(400).exists?.should == true
end
def verify_notification_enable_host_summary
@browser.link(:text => /Disable Notifications/).when_present.exists?.should == true
end
def verify_notification_enable_entire_network(host)
@browser.link(:id => /frmNV:nagiosPortlet_linkNotificationsHosts/).when_present.click
sleep(2)
@browser.span(:text => host).when_present.exists?.should == false
end
def verify_disable_active_check_entire_network(host)
@browser.link(:id => /frmNV:nagiosPortlet_linkActiveChecksHosts/).when_present(100).click
sleep(2)
@browser.span(:text => host).when_present(400).exists?.should == false
end
def select_service(service)
@browser.span(:text => service).when_present.click
sleep(2)
end
def submit_check_results_service(state)
self.check_results_element.when_dom_changed.click
self.passive_result_element.when_dom_changed.click
sleep(6)
self.check_results_list = state
self.check_output = state
self.performance_data = state
self.submit_button_service_element.when_present.click
end
def navigate_service_page_nagios(host,service)
#URL to access the page
#http://server.groundworkopensource.com/nagios-app/extinfo.cgi?type=2&host=localhost&service=local_cpu_httpd
new_base_url = String.new
# copying the BASE_URL to a new string
new_base_url = BASE_URL
# slicing off the /portal/classic/ from the BASE_URL
if new_base_url.include? "/portal/classic/"
new_base_url["/portal/classic/"]= ""
end
# creating the new URL to access the Nagios service page
nagios_servive_page_url = String.new
nagios_servive_page_url = new_base_url +
"/nagios-app/extinfo.cgi?type=2&host="+host+"&service="+service
# now accessing the page via the new URL
@browser.goto nagios_servive_page_url
sleep(2)
end
def select_service_group(service_group)
@browser.span(:text => service_group).when_present.click
sleep(2)
end
def check_event_service_group_summary_page(service)
@browser.span(:id => /SGVform:eventHeader/, :text=> /Events & Service List/).click
sleep(2)
@browser.span(:id => /SGVform:SLtblService:0:SLtxtNameService/, :text => service).exists?
proof2 = @browser.span(:id => /SGVform:SLtblService:0:SLtxtNameService/, :text => service).text
#puts proof2
@browser.span(:id => /SGVform:eventHeader/, :text=> /Events & Service List/).click
end
def downtime_service(option,comment,time)
@browser.span(:text => /Downtime/).when_present.click
@browser.span(:text => /Schedule Downtime For This Service/).when_present.click
sleep(2)
@browser.textarea(:name => /SVform:actionsPortlet_txtComment/).set comment
@browser.select(:name => /SVform:actionsPortlet_menuType/).select option
sleep(2)
if option == 'Flexible'
@browser.text_field(:name => /SVform:actionsPortlet_txtHours/).set time
@browser.text_field(:name => /SVform:actionsPortlet_txtMinutes/).set time
end
@browser.button(:name => /SVform:actionsPortlet_btnSubmit/).when_present.click
sleep(3)
end
def navigate_host_page_nagios(host)
new_base_url = String.new
# copying the BASE_URL to a new string
new_base_url = BASE_URL
# slicing off the /portal/classic/ from the BASE_URL
if new_base_url.include? "/portal/classic/"
new_base_url["/portal/classic/"]= ""
end
# creating the new URL to access the Nagios service page
nagios_host_page_url = String.new
nagios_host_page_url = new_base_url +
"/nagios-app/extinfo.cgi?type=1&host="+host
# now accessing the page via the new URL
@browser.goto nagios_host_page_url
sleep(2)
end
end
<file_sep>Given(/^I am on the auto\-disc page$/) do
visit AutodiscPage
end
When(/^I delete old filters$/) do
on AutodiscPage do |page|
page.delete_old_filter
end
end
When(/^I Enter Range\/Filter Name "(.*?)", Type "(.*?)" and Range\/Filter Pattern "(.*?)" and click the button$/) do |name, type, value|
on AutodiscPage do |page|
page.add_filter(name, type, value)
sleep(5)
end
end
When(/^I check the auto\-commit radio button$/) do
on AutodiscPage do |page|
page.select_auto_commit
end
end
When(/^I click Go button$/) do
on AutodiscPage do |page|
page.go
sleep(2)
end
end
When(/^I check the checkbox of Accept and click go$/) do
on AutodiscPage do |page|
if (page.start_new_discovery_element.exists?)
sleep(3)
page.start_new_discovery
sleep(5)
page.check_accept_discovery
sleep(2)
page.confirm_go
sleep(3)
else
sleep(2)
page.check_accept_discovery
sleep(2)
page.confirm_go
sleep(3)
end
end
end
Then(/^the close button is visible and I click on that$/) do
on AutodiscPage do |page|
sleep(30)
page.close_discovery_element.wait_until_present
page.close_discovery
end
end
Given(/^I navigate to the status viewer page$/) do
visit StatusPage
end
When(/^I click on the Search button$/) do
on StatusPage do |page|
page.search_button
sleep(4)
end
end
When(/^I enter the host ip "(.*?)" in the text field$/) do |value|
on StatusPage do |page|
page.search_textfield = value
sleep(1)
page.go_search_button
sleep(3)
end
end
Then(/^the host is visible in the results$/) do
on StatusPage do |page|
(page.text.include? '1 Results').should ==true
end
end
<file_sep>class ProfilesConfigurationPage
include PageObject
direct_url BASE_URL + "config/profiles"
link :profile_importer_link, :text=> /Profile importer/
button :import_button, :name=> /import/
def open_all_profiles
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Profile importer/).when_present.click
frameleft.link(:text => /Import/).when_present.click
frameleft.link(:text => /GDMA /).when_present.click
end
def import_host_profile
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
self.wait_until do
framemain.td(:class => /row_lt/).checkbox(:value => /gdma-21-linux-host.xml/).set
framemain.td(:class => /row_dk/).checkbox(:value => /gdma-21-windows-host.xml/).set
framemain.checkbox(:value => /gdma-22-windows-host.xml/).set
framemain.checkbox(:value => /gdma-aix-host.xml/).set
framemain.checkbox(:name => /overwrite/).set
framemain.button(:name=> /import/).when_present.click
framemain.button(:value=> /Close/).when_present.click
end
end
def visit_host_profile
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Host profiles/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
end
def verify_host_profile
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
sleep(3)
frameleft.link(:text => /gdma-21-linux-host/).exists?.should == true
frameleft.link(:text => /gdma-21-windows-host/).exists?.should == true
frameleft.link(:text => /gdma-22-windows-host/).exists?.should == true
frameleft.link(:text => /gdma-aix-host/).exists?.should == true
end
def import_service_profile
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
self.wait_until do
framemain.checkbox(:value => /service-profile-Hitachi-AMS.xml/).set
framemain.checkbox(:value => /service-profile-Hitachi-USPV.xml/).set
framemain.checkbox(:value => /service-profile-citrix-system.xml/).set
framemain.checkbox(:value => /service-profile-citrix-xenapp-services.xml/).set
framemain.checkbox(:name => /overwrite/).set
framemain.button(:name=> /import/).when_present.click
framemain.button(:value=> /Close/).when_present.click
end
end
def visit_service_profile
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Service profiles/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
end
def verify_service_profile
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
sleep(3)
frameleft.link(:text => /Hitachi-AMS/).exists?.should == true
frameleft.link(:text => /Hitachi-USPV/).exists?.should == true
frameleft.link(:text => /citrix-system/).exists?.should == true
frameleft.link(:text => /citrix-xenapp-services/).exists?.should == true
end
def create_host_profile(hp_name,hp_desc)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Host profiles/).when_present.click
frameleft.link(:text => /New /).when_present.click
framemain.text_field(:name => /name/).when_present.set hp_name
framemain.text_field(:name => /description/).when_present.set hp_desc
framemain.select(:name => /template/).option(:value => /gdma-aix-host/).when_present.select
framemain.button(:name => /add/).when_present.click
end
def assign_host
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain.link(:text => /Assign Hosts/).when_present.click
framemain.select(:name => /hosts_nonmembers/).option(:value => /localhost/).when_present.select
framemain.button(:name => /hosts_add_member/).when_present.click
framemain.button(:name => /save/).when_present.click
end
def create_servce_profile(sp_name,sp_desc)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Service profiles/).when_present.click
frameleft.link(:text => /New /).when_present.click
framemain.text_field(:name => /name/).when_present.set sp_name
framemain.text_field(:name => /description/).when_present.set sp_desc
framemain.button(:name => /add/).when_present.click
end
def assign_service
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.select(:id => /services.nonmembers/).option(:value => /local_cpu_java/).when_present.select
framemain.button(:name => /services_add_member/).when_present.click
framemain.button(:name => /save/).when_present.click
end
def select_host_profile
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /test_hp/).when_present.click
end
def select_service_profile
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /test_sp/).when_present.click
end
def delete_host_profile
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain.button(:name => /delete/).when_present.click
framemain.button(:name => /confirm_delete/).when_present.click
end
end
<file_sep>
Given /^I enable notifications from nagios main configuration$/ do
on ControlPage do |page|
page.enable_notification
end
end
Given /^I click save and next$/ do
on ControlPage do |page|
page.save_next
end
end
Given /^I disable notifications from nagios main configuration$/ do
on ControlPage do |page|
page.disable_notification
end
end
Given /^I enable flap detection from nagios main configuration$/ do
on ControlPage do |page|
page.enable_flap_detection
end
end
Given /^I disable flap detection from nagios main configuration$/ do
on ControlPage do |page|
page.disable_flap_detection
end
end
<file_sep>Given /^I am on the Contacts page$/ do
visit ContactsPage
end
Given /^I create a new contact "(.+)"$/ do |contact|
on ContactsPage do |page|
page.create_contact(contact,contact,contact+'<EMAIL>')
end
end
Then /^the contact "(.+)" should be created$/ do |contact|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text.include?("Contact \"#{contact}\" added.")
end
Given /^I create a new contact group "(.+)"$/ do |contactgroup|
on ContactsPage do |page|
page.create_contact_group(contactgroup,contactgroup)
end
end
Then /^the contact group "(.+)" should be created$/ do |contactgroup|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text.include?("Contactgroup \"#{contactgroup}\" has been saved.")
end
Given /^I am on the Hosts page$/ do
visit HostconfigurationPage
end
Given /^I add contact group to the hostgroup$/ do
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).select(:id => /contactgroup.nonmembers/).option(:value => /contactgroup/).when_present.select
@browser.frame(:id => /myframe/).frame(:name => /monarch_main/).button(:name => /contactgroup_add_member/, :value => /<< Add/).when_present.click
end
Given /^I delete Contact "(.+)"$/ do |contact|
on ContactsPage do |page|
page.delete_contact(contact)
end
end
Then /^the contact "(.+)" should be deleted$/ do |contact|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text.include?("Removed:")
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text.include?(contact)
end
Given /^I delete Contact group "(.+)"$/ do |contactgroup|
on ContactsPage do |page|
page.delete_contact_group(contactgroup)
end
end
Then /^the contact group "(.+)" should be deleted$/ do |contactgroup|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text.include?("Removed:")
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text.include?(contactgroup)
end
############################################################################################
# for "modifying" a contact group
And /^I "(.+)" a contact group with name "(.+)"$/ do |action,group_name|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Contact groups/).when_present.click
if action == 'copy'
frameleft.link(:text => /Copy/).when_present.click
frameleft.link(:text => /#{group_name}/).when_present.click
framemain.text_field(:name => /name/).when_present.set "cpy-"+group_name
framemain.text_field(:name => /alias/).when_present.set "cpy-"+group_name
framemain.button(:value => "Add").when_present.click
#framemain.button(:name => /continue/).when_present.click
elsif action == 'rename'
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{group_name}/).when_present.click
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => 'new_name').set group_name+"-renamed"
framemain.button(:value => /Rename/).when_present.click
#framemain.button(:name => /continue/).when_present.click
elsif action == 'modify'
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{group_name}/).when_present.click
framemain.select(:name => /contact/).select "contact1"
framemain.button(:name => /contact_remove_member/).when_present.click
framemain.select(:name => /contact_nonmembers/).select "nagiosadmin"
framemain.button(:name => /contact_add_member/).when_present.click
framemain.button(:name => /save/).when_present.click
#framemain.button(:name => /continue/).when_present.click
end
end
Then /^a new copy contact group with name "(.+)" should be created$/ do |group_name|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{group_name}/).exists?.should == true
end
Then /^the renamed contact group with name "(.+)" should exist$/ do |group_name|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Contact groups/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{group_name}/).exists?.should == true
end
And /^I rename the contact group "(.+)" to "(.+)"$/ do |old_name,new_name|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /#{old_name}/).when_present.click
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => 'new_name').set new_name
framemain.button(:value => /Rename/).when_present.click
framemain.button(:name => /continue/).when_present.click
end
Then /^the modifications to contact group "(.+)" should exist$/ do |group_name|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /#{group_name}/).when_present.click
framemain.select(:name => /contact/).option(:text => /nagiosadmin/).exists?.should == true
end
# for Modifying, renaming, copying and deleting a new contact
And /^I "(.+)" the contact "(.+)"$/ do |action,contact|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
if action == 'copy'
frameleft.link(:text => /Copy/).when_present.click
frameleft.link(:text => /#{contact}/).when_present.click
framemain.text_field(:name => /name/).when_present.clear
framemain.text_field(:name => /name/).when_present.set "cpy-"+contact
framemain.text_field(:name => /alias/).when_present.clear
framemain.text_field(:name => /alias/).when_present.set "cpy-"+contact
framemain.button(:value => "Add", :name => "add").when_present.click
elsif action == 'rename'
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{contact}/).when_present.click
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => 'new_name').set contact+"-renamed"
framemain.button(:value => /Rename/).when_present.click
elsif action == 'modify'
frameleft.link(:text => /Contacts/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{contact}/).when_present.click
framemain.text_field(:name => /alias/).set "new_alias"
framemain.select(:name => /template/).select "generic-contact-2"
framemain.button(:name => /save/).when_present.click
end
end
Then /^the contact "(.+)" should be "(.+)" successfully$/ do |contact,action|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
if action == 'modified'
framemain.td(:class => 'data0').text.include? ("Change to contact \"#{contact}\" accepted.")
elsif action == 'copied'
framemain.td(:class => 'data0').text.include? ("Contact \"#{contact}\" added.")
elsif action == 'renamed'
framemain.td(:class => 'data0').text.include? ("Renamed:")
end
end
# for creating a new contact template
And /^I create a new contact template "(.+)"$/ do |contact|
on ContactsPage do |page|
page.create_contact_template(contact)
end
end
Then /^the template "(.+)" should be created$/ do |template|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.td(:class => 'data0').text.include? ("Contact template \"#{template}\" has been saved.")
framemain.button(:name => /continue/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{template}/).when_present.click
framemain.checkbox(:value => /d/).when_present.set?
framemain.checkbox(:value => /u/).when_present.set?
framemain.checkbox(:value => /c/).when_present.set?
end
# for Modifying, copying and renaming a new contact template
And /^I "(.+)" the contact template "(.+)"$/ do |action,template|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
if action == 'modify'
frameleft.link(:text => /Contact templates/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{template}/).when_present.click
framemain.select(:name => /host_notification_period/).when_present.select "24x7"
framemain.select(:name => /service_notification_period/).when_present.select "24x7"
framemain.button(:name => /save/).when_present.click
elsif action == 'copy'
frameleft.link(:text => /Copy/).when_present.click
frameleft.link(:text => /#{template}/).when_present.click
framemain.text_field(:name => /name/).when_present.set "cpy-"+template
framemain.button(:value => "Add", :name => "add").when_present.click
elsif action == 'rename'
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{template}/).when_present.click
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => 'new_name').set template+"-renamed"
framemain.button(:value => /Rename/).when_present.click
elsif action == 'delete'
frameleft.link(:text => /Contact templates/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{template}/).when_present.click
framemain.button(:value => /Delete/).when_present.click
framemain.button(:value => /Yes/).when_present.click
end
end
Then /^the contact template "(.+)" should be "(.+)" successfully$/ do |template,action|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
if action == 'modified'
framemain.td(:class => 'data0').text.include? ("Changes to contact template \"#{template}\" have been saved.")
elsif action == 'copied'
framemain.td(:class => 'data0').text.include? ("Contact template \"#{template}\" has been saved.")
elsif action == 'renamed'
framemain.td(:class => 'data0').text.include? ("Renamed:")
elsif action == 'deleted'
framemain.td(:class => 'data0').text.include? ('Removed:')
framemain.td(:class => 'data0').text.include? (" "+template+"-renamed ")
end
end
# for Verifying a contact template cannot be deleted which is used in a contact
And /^I assign the contact template "(.+)" to contact "(.+)"$/ do |template,contact|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft.link(:text => /Contacts/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{contact}/).when_present.click
framemain.select(:name => /template/).select template
framemain.button(:name => /save/).when_present.click
framemain.button(:name => /continue/).when_present.click
end
And /^I delete the contact template "(.+)"$/ do |template|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft.link(:text => /Contact templates/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{template}/).when_present.click
framemain.button(:name => /delete/).when_present.click
end
######################### HOST ESCALATIONS ##############################
# for Creating a host escalation tree
And /^I create a new host escalation "(.+)"$/ do |escalation|
on EscalationPage do |page|
page.create_host_escaltion(escalation)
end
end
Then /^the host escalation "(.+)" should be created successfully$/ do |escalation|
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').text.include? ("Host escalation \"#{escalation}\" has been saved.")
end
And /^I create a host escalation tree "(.+)" using "(.+)"$/ do |tree,escaltion|
visit EscalationPage
on EscalationPage do |page|
page.create_host_escalation_tree(tree,escaltion)
end
end
Then /^the host escalation tree "(.+)" should be created successfully$/ do |tree|
visit EscalationPage
on EscalationPage do |page|
page.verify_host_tree(tree)
end
end
# for Assign a host escalation tree to a host
And /^I assign the host escalation tree "(.+)" to host "(.+)"$/ do |tree,host|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft.link(:text => /Hosts/).click
frameleft.link(:text => /Linux Servers/).click
frameleft.link(:text => /#{host}/).click
frameleft.link(:text => /Detail/).click
framemain.button(:value => /Escalation Trees/).when_present.click
framemain.select(:name => 'host_escalation').select(tree)
framemain.button(:value => 'Save').when_present.click
framemain.td(:class => 'data0').text.include? ("Changes to \"#{host}\" accepted.")
framemain.button(:value => 'Close').when_present.click
end
Then /^the host escalation tree "(.+)" should be applied successfully for "(.+)"$/ do |tree,host|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
visit HostconfigurationPage
frameleft.link(:text => /Hosts/).when_present.click
frameleft.link(:text => /Linux Servers /).when_present.click
frameleft.link(:text => /#{host}/).when_present.click
frameleft.link(:text => /Detail/).click
framemain.button(:value => /Escalation Trees/).when_present.click
framemain.select(:name => /host_escalation/).option(:value => tree).attribute_value("selected") == ""
end
# for Assigning a host escalation tree to a host group
And /^I assign the host escalation tree "(.+)" to host group "(.+)"$/ do |tree,group|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft.link(:text => /Host groups/).click
frameleft.link(:text => /Modify/).click
frameleft.link(:text => /#{group}/).click
framemain.select(:name => /host_escalation_id/).select tree
framemain.button(:value => 'Save').when_present.click
framemain.td(:class => 'data0').text.include? ("Changes to hostgroup \"#{group}\" have been saved.")
framemain.button(:value => 'Continue').when_present.click
end
Then /^the host escalation tree "(.+)" should be applied successfully for host group "(.+)"$/ do |tree,group|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
visit HostconfigurationPage
frameleft.link(:text => /Host groups/).click
frameleft.link(:text => /Modify/).click
frameleft.link(:text => /#{group}/).click
framemain.select(:name => /host_escalation_id/).option(:value => tree).attribute_value("selected") == ""
end
# for Modifying and renaming a host escalation
And /^I "(.+)" the host escalation "(.+)"$/ do |action,escalation|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
if action == 'modify'
frameleft.link(:text => /Escalations/).when_present.click
frameleft.link(:text => /host escalation/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{escalation}/).click
framemain.text_field(:name => 'first_notification').set '2'
framemain.text_field(:name => 'last_notification').set '4'
framemain.text_field(:name => 'notification_interval').set '30'
framemain.checkbox(:value => 'd', :name => 'escalation_options').clear
framemain.checkbox(:value => 'r', :name => 'escalation_options').when_present.set
framemain.button(:value => 'Save').when_present.click
elsif action == 'rename'
frameleft.link(:text => /#{escalation}/).click
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => /new_name/).set escalation+"-renamed"
framemain.button(:value => /Rename/).when_present.click
framemain.td(:class => 'data0').text.include? ('Renamed:')
framemain.td(:class => 'data0').text.include? (" "+escalation+"-renamed")
framemain.button(:value => /Continue/).when_present.click
elsif action == "delete"
frameleft.link(:text => /Escalations/).when_present.click
frameleft.link(:text => /host escalation/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{escalation}/).click
framemain.button(:value => /Delete/).when_present.click
framemain.button(:name => /confirm_delete/).when_present.click
framemain.td(:class => 'data0').text.include? ("Removed:")
framemain.td(:class => 'data0').text.include? (" "+escalation+"-renamed")
framemain.button(:value => /Continue/).when_present.click
end
end
Then /^the host escalation "(.+)" should be "(.+)" successfully$/ do |escalation,action|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
if action == 'modified'
framemain.td(:class => 'data0').text.include? ("Changes to \"#{escalation}\" have been saved.")
elsif action == 'renamed'
frameleft.link(:text => /Escalations/).when_present.click
frameleft.link(:text => /host escalation/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{escalation}/).exists?.should == true
elsif action == "deleted"
frameleft.link(:text => /Escalations/).when_present.click
frameleft.link(:text => /host escalation/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{escalation}/).exists?.should == false
end
end
# for Renaming a host escalation tree
And /^I rename the host escalation tree "(.+)"$/ do |tree|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft.link(:text => /Escalation trees/).when_present.click
frameleft.link(:text => /host escalation tree/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{tree}/).click
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => /new_name/).set tree+"-renamed"
framemain.button(:value => /Rename/).when_present.click
framemain.td(:class => 'data0').text.include? ('Renamed:')
framemain.td(:class => 'data0').text.include? (" "+tree+"-renamed")
framemain.button(:value => /Continue/).when_present.click
end
Then /^the host escalation tree "(.+)" should be renamed successfully$/ do |tree|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft.link(:text => /Escalation tree/).when_present.click
frameleft.link(:text => /host escalation tree/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{tree}/).exists?.should == true
end
# for deleting the host escalation tree
And /^I delete the host escalation tree "(.+)"$/ do |tree|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft.link(:text => /Escalation trees/).when_present.click
frameleft.link(:text => /host escalation tree/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{tree}/).click
framemain.button(:value => /Delete/).when_present.click
framemain.button(:name => /confirm_delete/).when_present.click
framemain.td(:class => 'data0').text.include? ("Removed:")
framemain.td(:class => 'data0').text.include? (" "+tree+"-renamed")
framemain.button(:value => /Continue/).when_present.click
end
Then /^the host escalation tree "(.+)" should be deleted successfully$/ do |tree|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft.link(:text => /Escalation tree/).when_present.click
frameleft.link(:text => /host escalation tree/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{tree}/).exists?.should == false
end
Then(/^the cloned "(.+)" "(.+)" should preserve the contact group assignment "(.+)"$/) do |item,object,cg|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
if item == "host"
visit HostconfigurationPage
frameleft.link(:text => /Hosts/).click
frameleft.link(:text => /Linux Servers/).click
frameleft.link(:text => /#{object}/).click
frameleft.link(:text => /Detail/).click
elsif item == "service"
visit ServiceConfigurationPage
frameleft.link(:text => /Services/).click
frameleft.link(:text => /#{object}/).click
end
#framemain.select(:name => /contactgroup/).include?(cg)
framemain.select(:name => /contactgroup/).option(:value => cg).exists?.should == true
end
<file_sep>class StatusPage
include PageObject
direct_url BASE_URL + "status"
link :linux_servers, :id => /frmTree:pnlTbSet:0:hstTree:6/
a :search_button, :id => /frmTree:pnlTbSet:0.2/
text_field :search_textfield, :id => /frmTree:pnlTbSet:0:STtxtSearchQuery/
button :go_search_button, :id => /frmTree:pnlTbSet:0:STsearchTreePortlet_btnSearch/
def hosts_under_linux_severs
sleep(3)
linux_server_hosts = Array.new
@browser.linux_servers.span.each do |hosts|
linux_server_hosts = hosts.text
return linux_server_hosts
end
end
end
<file_sep>Given(/^I am on profile page$/) do
visit ProfilesConfigurationPage
end
When(/^I select a profile to import$/) do
on ProfilesConfigurationPage do |page|
page.open_all_profiles
end
end
When(/^select host files to import$/) do
on ProfilesConfigurationPage do |page|
page.import_host_profile
end
end
Then(/^it should be added to Host Profiles$/) do
visit ProfilesConfigurationPage do |page|
page.visit_host_profile
page.verify_host_profile
end
end
When(/^select service files to import$/) do
on ProfilesConfigurationPage do |page|
page.import_service_profile
end
end
Then(/^it should be added to Service Profiles$/) do
visit ProfilesConfigurationPage do |page|
page.visit_service_profile
page.verify_service_profile
end
end
When(/^I create a new host profile "(.*?)" with description "(.*?)"$/) do |hp_name,hp_desc|
on ProfilesConfigurationPage do |page|
page.create_host_profile(hp_name,hp_desc)
end
end
When(/^select a host and save$/) do
on ProfilesConfigurationPage do |page|
page.assign_host
end
end
Then(/^host profile "(.*?)" should be added to that host on configuration page$/) do |host_profile|
visit HostconfigurationPage do |page|
page.visit_host_configuration
page.verify_host_profile_addition(host_profile)
end
end
When(/^I create a new service profile "(.*?)" with description "(.*?)"$/) do |sp_name,sp_desc|
on ProfilesConfigurationPage do |page|
page.create_servce_profile(sp_name,sp_desc)
end
end
When(/^select a service and save$/) do
on ProfilesConfigurationPage do |page|
page.assign_service
end
end
Then(/^service profile "(.*?)" should be added to that service on configuration page$/) do |service_profile|
visit ServiceConfigurationPage do |page|
page.visit_service_configuration
page.verify_service_profile_addition(service_profile)
end
end
When(/^I navigate to new host profile created$/) do
on ProfilesConfigurationPage do |page|
page.visit_host_profile
end
end
When(/^select host profile$/) do
on ProfilesConfigurationPage do |page|
page.select_host_profile
end
end
When(/^I delete it$/) do
on ProfilesConfigurationPage do |page|
page.delete_host_profile
end
end
Then(/^host profile "(.*?)" should be deleted$/) do |host_profile|
visit HostconfigurationPage do |page|
page.visit_host_configuration
page.verify_host_profile_deletion(host_profile)
end
end
When(/^I navigate to new service profile created$/) do
on ProfilesConfigurationPage do |page|
page.visit_service_profile
end
end
When(/^select service profile$/) do
on ProfilesConfigurationPage do |page|
page.select_service_profile
end
end
Then(/^service profile "(.*?)" should be deleted$/) do |service_profile|
visit ServiceConfigurationPage do |page|
page.visit_service_configuration
page.verify_service_profile_deletion(service_profile)
end
end<file_sep>class NagiosHostStatusDetailsPage
include PageObject
direct_url BASE_URL + "advanced/nagios-app/NagiosHostsView"
in_frame(:id => 'myframe') do |frame|
link :localhost, :title => /127.0.0.1/, :text => /localhost/, :frame => frame
end
end
<file_sep>#!/bin/bash
chromium results.html&
har run.har
<file_sep>class SupportPage
include PageObject
direct_url BASE_URL + '/resources/support'
link :support, :text => "Support"
span :support_text, :text => "Support"
div :page_title, :class => "BreadcumbsInfoBar ClearFix"
@@subtab_title = { "Documentation" => "Documentation", "Support" => "GroundWork Connect", "Developer" => "GroundWork Developer Kit (GDK)", "Exchange" => "Exchange", "Community" => "Community"}
@@subtab_text = { "Documentation" => "Welcome to Bookshelf", "Support" => "Recently Updated", "Developer" => "GroundWork Developer Kit (GDK)", "Exchange" => "GroundWork Monitor Enterprise", "Community" => "What Is GroundWork?"}
def go_to_subtab(subtab)
@browser.link(:text => /Resources/).when_present.hover
@browser.link(:text => /#{subtab}/).when_present.click
end
def check_subtab(subtab)
self.wait_until(10) do
self.page_title.include? subtab
if subtab == "Exchange"
@browser.frame.h3.text.include? @@subtab_text[subtab]
elsif subtab == "Developer"
self.page_title.include? @@subtab_title[subtab]
else
@browser.frame.h4.text.include? @@subtab_text[subtab]
end
end
end
end
<file_sep>class ServiceConfigurationPage
include PageObject
direct_url BASE_URL + "config/services"
link :service_templates, :text => " Service templates"
text_field :max_check_attempts, :name => "max_check_attempts"
in_frame(:id => 'myframe') do |frame|
in_frame({:name => 'monarch_left'}, frame) do |frame|
link :new_service, :text => /New service/, :frame => frame
link :search_service, :text => /Search/, :frame => frame
end
in_frame({:id => 'monarch_main'}, frame) do |frame_main|
text_field :service_name, :name => /name/, :frame => frame_main
textarea :command_line, :name => /command_line/, :frame => frame_main
text_field :search_field, :name => /input/, :frame => frame_main
select_list :service_template, :name => /template/, :frame => frame_main
select_list :service_command, :name => /command/, :frame => frame_main
button :add, :value => /Add/, :frame => frame_main
button :save, :value => /Save/, :frame => frame_main
button :delete, :value => /Delete/, :frame => frame_main
button :yes, :value => /Yes/, :frame => frame_main
link :service_check, :text => /Service Check/, :frame => frame_main
end
end
def open_generic_service
frame = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frame.link(:text => /Service templates/).when_present.click
frame.link(:text => /Modify/).when_present.click
frame.link(:text => /generic-service/).when_present.click
end
def set_max_attempts
frame = @browser.frame(:id => "myframe").frame(:name => "monarch_main").when_present
frame.text_field(:name => "max_check_attempts").when_present.set "1"
frame.button(:name => "save").when_present.click
end
def open_services
frame = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frame.link(:text => /Services/).when_present.click
end
def check_service(name)
frame = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frame.link(:text => /#{name}/).when_present.click
end
def set_max_check_attempts
frame = @browser.frame(:id => "myframe").frame(:name => "monarch_main").when_present
frame.text_field(:name => "max_check_attempts").when_present.set "1"
frame.checkbox(:name => /active_checks_enabled/).clear
frame.button(:name => "save").when_present.click
end
def reset_max_check_attempts
frame = @browser.frame(:id => "myframe").frame(:name => "monarch_main").when_present
frame.text_field(:name => "max_check_attempts").when_present.set "3"
frame.checkbox(:name => /active_checks_enabled/).set
frame.button(:name => "save").when_present.click
end
def visit_service_configuration
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Services/).when_present.click
frameleft.link(:text => /local_cpu_java/).when_present.click
framemain.link(:text => /Service Profiles/).when_present.click
end
def verify_service_profile_addition(service_profile)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.select(:id => /profiles.members/).option(:value => service_profile).exists?.should == true
end
def verify_service_profile_deletion(service_profile)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.select(:id => /profiles.members/).option(:value => service_profile).exists?.should == false
end
def create_service(name)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /New service/).when_present.click
framemain.text_field(:name => /name/).set name
framemain.select(:name => /template/).select("generic-service")
framemain.button(:value => /Add/).when_present.click
framemain.link(:text => /Service Check/).when_present.click
framemain.select(:name => /command/).select("check_http")
framemain.textarea(:name => /command_line/).clear
framemain.textarea(:name => /command_line/).set 'check_http!20!70'
framemain.button(:value => /Save/).when_present.click
end
def search_service(name)
@browser.frame(:id => 'myframe').frame(:name => 'monarch_left').link(:text => /Search/).when_present.click
sleep(5)
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').text_field(:name => 'input').set name
sleep(5)
end
def create_template(name)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Service templates/).when_present.click
frameleft.div(:id => /service_templates/).link(:text => /New/).when_present.click
framemain.text_field(:name => 'name').set name
framemain.button(:value => /Add/).when_present.click
framemain.select(:name => 'template').select('generic-service')
framemain.checkbox(:name => 'check_period_override').when_present.clear
framemain.select(:name => 'check_period').select('workhours')
framemain.checkbox(:name => 'max_check_attempts_override').when_present.clear
framemain.text_field(:name => 'max_check_attempts').set '5'
framemain.button(:value => /Save/).when_present.click
sleep(3)
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').text.include? ('Saved:')
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').text.include? (name)
end
def create_dependency(name)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Service dependencies/).when_present.click
frameleft.div(:id => /service_dependencies/).link(:text => /New/).when_present.click
framemain.text_field(:name => 'name').set name
framemain.select(:name => 'service_name').select('local_cpu_httpd')
framemain.checkbox(:name => 'execution_failure_criteria', :value => 'c').when_present.set
framemain.checkbox(:name => 'execution_failure_criteria', :value => 'u').when_present.set
framemain.checkbox(:name => 'notification_failure_criteria', :value => 'c').when_present.set
framemain.checkbox(:name => 'notification_failure_criteria', :value => 'u').when_present.set
framemain.button(:value => /Add/).when_present.click
end
def create_extended_template(name)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Service extended info/).when_present.click
frameleft.div(:id => /service_extended_info/).link(:text => /New/).when_present.click
framemain.text_field(:name => 'name').set name
framemain.textarea(:name => 'notes').set 'testing service extended info template'
framemain.text_field(:name => 'notes_url').set 'www.gwos.com'
framemain.text_field(:name => 'action_url').set 'www.gwos.com'
framemain.select(:name => 'icon_image').select("3d_cloud.gif")
framemain.text_field(:name => 'icon_image_alt').set '3d_cloud'
framemain.button(:value => /Add/).when_present.click
end
def open_service_group(name)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Service groups/).when_present.click
frameleft.div(:id => /service_groups/).link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{name}/).when_present.click
end
end
<file_sep>class CloudHubPage
include PageObject
direct_url BASE_URL + "groundwork-administration/cloudhubview"
in_frame(:id => 'myframe') do |frame|
radio_button :vmware, :id => /vmware/, :frame => frame
radio_button :redhat, :id => /redhat/, :frame => frame
#Modifications
link :add_vmware, :href => /vmware/, :class => /button-l/, :frame => frame
link :add_redhat, :href => /rhev/, :class => /button-l/, :frame => frame
text_field :rh_display_name, :name => /common.displayName/, :frame => frame
text_field :rh_groundwork_server, :name => /gwos.gwosServer/, :frame => frame
#Modification
text_field :app_server, :name => /connection.server/, :frame => frame
text_field :rh_entrypoint, :name => /connection.url/, :frame => frame
text_field :rh_password, :name => /connection.password/, :frame => frame
text_field :rh_storepath, :name => /connection.certificateStore/, :frame => frame
text_field :rh_passcode, :name => /connection.certificatePassword/, :frame => frame
text_field :rh_check_interval, :id => /check.interval/, :frame => frame
text_field :rh_sync_interval, :id => /sync.interval/, :frame => frame
text_field :display_name, :id => /common.displayName/, :frame => frame
text_field :groundwork_server, :id => /groundwork.server.name/, :frame => frame
text_field :conn_prefix, :name => /connection.prefix/, :frame => frame
text_field :wsuser_name, :id => /groundwork.webservices.username/, :frame => frame
#Modifications
text_field :wsuser_password, :id => /groundwork.webservices.password/, :frame => frame
text_field :server_name, :id => /virtualEnv.serverName/, :frame => frame
text_field :tenant_id, :id => /virtualEnv.tenantId/, :frame => frame
text_field :tenant_name, :id => /virtualEnv.tenantName/, :frame => frame
text_field :nova_port, :id => /virtualEnv.novaPort/, :frame => frame
text_field :keystone_port, :id => /virtualEnv.keystonePort/, :frame => frame
text_field :ceilometer_port, :id => /virtualEnv.ceilometerPort/, :frame => frame
text_field :connection_retries, :id => /connectionRetries/, :frame => frame
#text_field :vmware_server, :id => /virtualEnv.serverName/, :frame => frame
text_field :username, :id => /virtualEnv.username/, :frame => frame
text_field :password, :name => /connection.password/, :frame => frame
text_field :interval, :id => /check.interval/, :frame => frame
button :add, :value => /Add/, :frame => frame
button :save, :value => /Save/, :frame => frame
button :test_connection, :value => /Test Connection/, :frame => frame
button :next, :value => /Next/, :frame => frame
button :home, :value => /Home/, :frame => frame
button :startconnection, :id => /startStopServerbtn/, :frame => frame
div :green, :class => /greencircle/, :frame => frame
button :modify, :value => /Modify/, :frame => frame
button :next, :value => /Next/, :frame => frame
p :cloudhub, :text => /Cloud Hub Configuration wizard for VMware/, :frame => frame
p :rh_cloudhub, :text => /CloudHub Configuration wizard for RHEV-M/, :frame => frame
button :delete, :value => /Delete/, :frame => frame
td :testconnection, :text => "test", :frame => frame
checkbox :hypervisor_service, :id => /hyp_monitored_5/, :frame => frame
button :save, :value => /Save/, :frame => frame
checkbox :vm_service, :id => /vm_monitored_18/, :frame => frame
text_field :hyp_warning_threshold, :id => /hyp_warningThreshold_1/, :frame => frame
text_field :hyp_critical_threshold, :id => /hyp_criticalThreshold_1/, :frame => frame
text_field :vm_warning_threshold, :id => /vm_warningThreshold_1/, :frame => frame
text_field :vm_critical_threshold, :id => /vm_criticalThreshold_1/, :frame => frame
checkbox :storage_view, :id => /storageView/, :frame => frame
checkbox :network_view, :id => /networkView/, :frame => frame
checkbox :resource_view, :id => /resourcePoolView/, :frame => frame
end
def home_confirm
@browser.frame(:id => "myframe").input(:value => /Home/).when_present.click
end
end
<file_sep>Given /^I am on Resources page$/ do
visit ResourcesPage
end
When /^I click on Support$/ do
visit SupportPage
end
Then /^I should see the community support page$/ do
on ResourcesPage do |page|
page.support_text_element.exists?
end
end
Given /^I am on My Preference page$/ do
on PreferencePage do |page|
page.preference
end
end
When /^I edit my profile with "(.*?)", "(.*?)"$/ do |namefirst, namelast|
on PreferencePage do |page|
#page.edit_profile_element.when_present.click
page.firstname = namefirst
page.lastname = namelast
end
end
When /^I submit it$/ do
on PreferencePage do |page|
page.submit
sleep(5)
page.ok
sleep(5)
page.close
sleep(5)
end
end
Given /^I edit My GroundWork$/ do
on PreferencePage do |page|
page.restuser
end
end
When /^I edit my username with "(.*?)", "(.*?)"$/ do |namefirst, namelast|
on PreferencePage do |page|
#page.edit_profile_element.when_present.click
page.firstname = namefirst
page.lastname = namelast
end
end
When /^I save it$/ do
on PreferencePage do |page|
page.submit
sleep(5)
page.ok
sleep(5)
page.close
sleep(5)
end
visit DashboardPage
on DashboardPage do |page|
sleep(3)
page.logout
end
end
Given /^I am on Login page$/ do
visit LoginPage
@browser.div(:text => /2014 GroundWork Inc. All rights reserved/).exists?.should == true
end
When /^I click on the Knowledge Base link$/ do
on LoginPage do |page|
page.knowledge_base_element.when_present.click
sleep(3)
end
end
When /^I click on the Case Manager link$/ do
on LoginPage do |page|
page.case_manager_element.when_present.click
sleep(3)
end
end
When /^I click on the Forums link$/ do
on LoginPage do |page|
page.forums_element.when_present.click
sleep(3)
end
end
When /^I click on the Groundwork link$/ do
on LoginPage do |page|
page.groundwork_element.when_present.click
sleep(3)
end
end
Then /^I should be redirected to the Knowledge Base Page$/ do
#sleep(2)
@browser.window(:title => /Home - Support - GWConnect/).when_present.use
sleep(2)
@browser.div(:text => /Welcome to the public area of the GroundWork Knowledge Base/).exists?.should == true
end
Then /^I should be redirected to the Case Manager Page$/ do
#sleep(2)
@browser.window(:title => /System Dashboard - GroundWork Case Manager/).when_present.use
#sleep(5)
@browser.link(:text => /Dashboards/).when_present.when_present.click
#sleep(2)
#@browser.frame(:class => "gadget-iframe").div(:text => /Welcome to the GroundWork Case Manager (GWCM)/).exists?.should == true
end
Then /^I should be redirected to the Forums Page$/ do
#sleep(2)
@browser.window(:title => /GroundWork Forums/).when_present.use
#sleep(2)
@browser.link(:text => /Members/).when_present.click
#sleep(2)
@browser.link(:text => /Forums/).when_present.click
#sleep(2)
@browser.window(:title =>/GroundWork Forums/).when_present.use
#sleep(2)
end
Then /^I should be redirected to the Groundwork home Page$/ do
#sleep(2)
@browser.link(:text => /Features/).when_present.click
@browser.link(:text => /Pricing/).when_present.click
end
<file_sep>require 'net/http'
require 'open-uri'
require 'rest_client'
require 'nokogiri'
#Scenario: Validate license key
Given /^I am on Monitor Enterprise license page$/ do
#on LicensePage do |page|
#end
visit LicensePage
sleep(3)
end
When /^I add the license key$/ do
#visit LicensePage
on LicensePage do |page|
page.license_element.clear
sleep(2)
page.license_element.set '#Wed Apr 30 20:21:56 PDT 2014
property_param_11=<KEY>
property_param_10=30819f300d06092a864886f70d010101050003818d0030818902818100d31e16fdccecabb8920cf9daf591097e8d2b20a977c6c6ec41b9d832d9b5d3114dc1aa6fb493191ddcbad07f081a8e6259a89bc3a536f060fe67c31702df544676dbc399ca6cf1ee830e4259500cee86a670676206a290603981028b7fe14e907157efe78ce2d0e364cea39f1058bf1427f3344336aab22858780943307b39750203010001
creationDate=1398914516390
startDate=1398816000000
property_param_9=
property_param_8=YnbTwbTVwYLiJJFsRaRYssJJwRFLnYadnbdFRRsadsJV
property_param_7=TnYVJYVLJaFsHHRbdTdabbLbwRmLnVLJbTJmRwaLJaiR
property_param_6=Habw
property_param_5=TmnR
property_param_4=nRYmiRLbsmdHLsbVJVnJFLmVVLFRTawmJmLYHJTFsVFamFsHbnYHssRbTnbRnTRTaYRJHRRiiRVTaYnHJJFFHHHHYVibsYYY
property_param_3=mR
property_param_2=FFHsTHYaRaHsdH
property_param_1=dniVHwwnYV
property_orderID=GroundWork-7.0.2-CORE
expireAfterFirstRun=1903910400000
signature=3e129876f23df350fd6573b3b567cc7cb08f21f08809b2789cd68e4328a668bc2e42aa132484897bac86864b7fc4379e25b8c4787a722dff67b27969a24addfb7c928292cb24ae58003bb11252760095ca702b313d20b6262e24080d913d982ef2761e45c159b0cbd2c4770f93bddb688fcfbb8fa37b5d4b1d64e5539ea3dd3a
expirationDate=1903910400000
property_param_12=Y<KEY>'
sleep(3)
page.applylicense_element.click
sleep(5)
end
end
Then /^the license key should be validated$/ do
sleep(5)
visit DashboardPage
=begin
on LicensePage do |page|
Watir::Wait.until {
@browser.td(:text =>'Thank you for validating the license. Your license is activated now. Happy Monitoring!').exists?
}
visit AdministrationViewPage
end
=end
end
#Scenario: Validate build number
When /^I select show install info$/ do
on DashboardPage do |page|
#page.dashboard_element.when_present.click
sleep(2)
page.show_install_info_element.when_present.click
end
end
Then /^I should see the correct build number$/ do |build|
on DashboardPage do |page|
info_text = @browser.span(:id => "last_checked").p(:text => /PostgreSQL/).text.split("\n")
name = info_text.grep(/^name/)[0].split("= ")[1]
version = info_text.grep(/^version/)[0].split("= ")[1]
name.should == NAME
version.should == VERSION
end
end
#Scenario: Auto Discovery
Given /^I specify a filter "(.+?)" of type "(.+?)" and a Range\/Filter Pattern "(.+?)"$/ do |filterName, type, range|
on AutodiscoveryPage do |page|
#page.delete_old_filters
page.add_filter('include','test','172.28.113.160-170')
page.select_control_type
page.check_range_filter_name
end
end
Then /^no errors should appear for "(.+?)"$/ do |filterName|
@browser.frame(:id => "myframe").text.include?('Success')
end
#Scenario: Create Host and Service Group.
Given /^I am on the Host Configuration page$/ do
visit HostconfigurationPage
end
Given /^I remove all hosts from the hosts groups except localhost$/ do
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Host groups/).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Modify/).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Linux Servers/).when_present.click
$selectList = @browser.frame(:id => "myframe").frame(:name => "monarch_main").when_present(15).select(:name => "members")
$selectList.options.map(&:text).each { |element|
if element != "localhost"
$selectList.when_present.select(element)
end
}
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:value, "Remove >>").click
end
Given /^I create a new Host group "(.+?)"$/ do |groupName|
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Host groups/).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /New/ ).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name, /name/).when_present.set groupName
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name, /alias/).set groupName
end
Given /^I add the hosts except localhost to the new host group$/ do
$selectList = @browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /nonmembers/)
$selectContent = $selectList.options.map(&:text).each { |element|
if element == "localhost"
$host_array << element
$selectList.select(element)
end
}
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:value, /<< Add/).click
end
When /^I "(.*?)" the changes$/ do |arg1|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, "#{arg1}").click
end
Then /^"(.*?)" changes were "(.*?)" correctly$/ do |arg1, arg2|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text.include?("Changes to hostgroup \"#{arg1}\" have been #{arg2}.")
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, "continue").click
end
#Scenario Create Service group
Given /^I am on the Service Configuration page$/ do
visit ServiceConfigurationPage
end
Given /^I create a new Service Group "(.+)"$/ do |group|
=begin
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Service groups/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /New/, :href => /service_groups&task=new/).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name, /name/).when_present.set 'SG1'
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name, /alias/).set 'SG1'
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, /add/).click
$selectList = @browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /host/)
$selectContent = $selectList.options.map(&:text).each { |element|
$selectList.select(element)
}
=end
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Service groups/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /New/, :href => /service_groups&task=new/).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name, /name/).when_present.set group
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name, /alias/).set group
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, /add/).click
#$selectListnew = @browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /host/)
#$selectContentnew = $selectListnew.options.map(&:text).each { |element|
#$selectListnew.select(element)
#}
sleep(3)
#<EMAIL>.frame(:id => "myframe").frame(:name => "monarch_main").when_present.select(:name => /services/).select(/local_/)
end
Given /^I add the services to the new Service Group$/ do
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /host/).option(:text => /localhost/).when_present.select
@browser.frame(:id => "myframe").frame(:name => "monarch_main").when_present.select(:name => /services/).option(:text => /local_/).when_present.select
#@<EMAIL>.frame(:id => "myframe").frame(:name => "monarch_main").when_present.select(:name => /services/).select(/local_/)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, 'add_services').click
end
Then /^service group should be created sucessfully$/ do
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, /save/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, /continue/).click
end
When /^I delete the service group "(.+?)"$/ do |groupName|
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Service groups/).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Modify/ ).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /#{groupName}/).when_present.click
end
Then /^the service group should be deleted$/ do
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, "delete").click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, "confirm_delete").click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, "continue").click
end
#Scenario: Commit changes to Nagios
Given /^I am on Control Configuration page$/ do
visit ControlPage
end
When /^I commit new objects to Nagios$/ do
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Commit/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, 'commit').when_present.click
#Optimuscomment: For processing required after commit
sleep(5)
end
Then /^the commit should be successful$/ do
@browser.frame(:id => "myframe").text.include?('Success')
end
#Scenario: Apply Applications on Event Console
Given /^I am on the Event Console page$/ do
visit EventconsolePage
end
When /^I apply the filter System under Applications$/ do
on EventconsolePage do |page|
@browser.div(:class => "iceTreeRow", :index => 1).link(:index => 0).when_present.click
page.application_system_event_element.when_present.click
page.wait_until do
page.events_application_types_element.when_present.text == "Events by ApplicationTypes=SYSTEM"
end
end
end
Then /^I should see no errors$/ do
sleep(5)
rows = @browser.div(:class => "tableStatus").span(:class => "iceOutFrmt").when_present.text.to_i
rows.times do |x|
output = @browser.span(:id => /_monitorStatus/, :index => x).text
if output == "OK"
output.should == "OK"
elsif output == "WARNING"
output.should == "WARNING"
else
output.should == "WARNING"
end
end
end
When /^I apply the filter Nagios under Applications$/ do
on EventconsolePage do |page|
@browser.div(:class => "iceTreeRow", :index => 1).link(:index => 0).when_present.click
page.application_nagios_event_element.when_present.click
page.wait_until do
page.events_application_types_element.when_present.text == "Events by ApplicationTypes=NAGIOS"
end
end
end
Then /^I should see there are events in this view$/ do
on EventconsolePage do |page|
page.number_showing_events_element.when_present.text.to_i.should >= 1
end
end
#Scenario: Apply Host Groups on Event Console
When /^I apply the filter "(.*?)" under "(.*?)"$/ do |arg1, arg2|
on EventconsolePage do |page|
if arg2 == "Host Groups"
@browser.div(:class => "iceTreeRow", :index => 2).link(:index => 0).when_present.click
elsif arg2 == "Service Group"
@browser.div(:class => "iceTreeRow", :index => 3).link(:index => 0).when_present.click
else
@browser.div(:class => "iceTreeRow", :index => 4).link(:index => 0).when_present.click
end
@browser.link(:text => /#{arg1}/).when_present.click
end
end
#Scenario: Check no pending state on Status Viewer
Given /^I am on the Status Viewer page$/ do
visit StatusviewerPage
end
When /^all Hosts and Service states are set up$/ do
on StatusviewerPage do |page|
page.wait_until(610) do
page.state_pending? == false
end
end
end
Then /^all states should not be on PENDING$/ do
on StatusviewerPage do |page|
page.state_pending?.should == false
end
end
#Scenario: Check RDD graphs
When /^I select a Host$/ do
on StatusviewerPage do |page|
page.select_host("HG1","#{$host_array[0]}", "Linux Servers")
end
end
Then /^I should see the RRD shown$/ do
on StatusviewerPage do |page|
page.performance_filter_element.when_present(10).click
page.wait_until(10) do
if !page.host_graph_element.exists?
page.performance_filter_element.when_present.click
end
page.host_graph_element.when_present
end
end
end
#Scenario: Check Cacti graphs
When /^I select localhost$/ do
on StatusviewerPage do |page|
page.linux_servers_element.when_present.click
page.localhost_element.when_present.click
end
end
Then /^I should see that Cacti Graphs shown$/ do
on StatusviewerPage do |page|
page.performance_filter_element.when_present(10).click
page.wait_until(60) do
#Logged in user
page.logged_in_user_element.when_present(10).click
page.logged_in_user_image_element.when_present
#Memory Usage
page.memory_usage_element.when_present(10).click
page.memory_usage_image_element.when_present.click
#Processes Usage
page.processes_usage_element.when_present(10).click
page.processes_usage_image_element.when_present.click
end
end
end
#Scenario Check groundwork default users login
Given /^I am on the Dashboard page$/ do
#visit DashboardPage
end
Given /^I logout$/ do
on DashboardPage do |page|
page.logout
end
end
When /^I login with (.+) user$/ do |user|
on LoginPage do |page|
page.login_user(user,user)
end
end
Then /^I should see Welcome, (.+) message on dashboard$/ do |user|
on DashboardPage do |page|
page.correct_login?(user)
end
end
Given /^I am on the "(.+)" page$/ do |page|
if page == 'Event Console'
visit EventconsolePage
elsif page == 'Views'
visit ViewPage
elsif page == 'BSM'
visit BSMPage
end
end
And /^I select host "(.+)" on "(.+)" page$/ do |host,page|
sleep(20)
if page == 'Event Console'
on EventconsolePage do |page|
page.all_events_element.when_present.click
page.host_search_element.set host
page.search_link_element.when_present.click
@browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:0/, :text => host).when_present.click
end
elsif page == 'Views'
on ViewPage do |page|
page.geooffice_element.when_present.click
sleep(3)
page.editmap_element.fire_event 'mouseover'
page.addicon_element.fire_event 'mouseover'
page.addhost_element.when_present.click
page.background_element.when_present(40).click
page.hostname = host
page.modify_button_element.when_present.click
sleep(2)
@browser.frame(:id => 'myframe').image(:alt => 'host-'+host).when_present.click
sleep(5)
end
elsif page == 'BSM'
@browser.frame(:id => "myframe").link(:text => 'Manage groups').when_present.click
@browser.frame(:id => "myframe").link(:class => "update").when_present.click
@browser.frame(:id => "myframe").div(:id => 'yw0').div(:id => 'all_members').span(:text => 'H: '+host).when_present.click
@browser.frame(:id => "myframe").div(:id => 'yw0').div(:id => 'all_members').span(:text => 'H: '+host).when_present.click
@browser.frame(:id => "myframe").div(:class => "form").button(:value => "Add >").when_present.click
@browser.frame(:id => "myframe").button(:value => "Save").when_present.click
@browser.frame(:id => "myframe").div(:class => "bsmgroup").table(:class => "bsmtreetable").td(:text => "GroundWork Monitor").when_present.click
sleep(5)
@browser.frame(:id => "myframe").div(:class => "bsmtreeRow host").table(:class => "bsmtreetable").link(:text => /#{host}/).when_present.click
@browser.window(:title => 'status').when_present.use
end
end
Then /^selected host "(.+)" should be redirected to the Status Viewer page$/ do |host|
on StatusviewerPage do |page|
page.status_element.exists?.should == true
end
@browser.span(:text => host).exists?.should == true
end
And /^I remove host "(.+)" from "(.+)" page$/ do |host,page|
if page == 'Event Console'
visit EventconsolePage
elsif page == 'Views'
visit ViewPage
on ViewPage do |page|
page.geooffice_element.when_present.click
sleep(3)
@browser.frame(:id => 'myframe').image(:alt => 'host-'+host).when_present.right_click
page.unlock_element.when_present.click
sleep(2)
@browser.frame(:id => 'myframe').image(:alt => 'host-'+host).when_present.right_click
page.delhostobject_element.when_present.click
sleep(2)
@browser.alert.ok
sleep(5)
end
elsif page == 'BSM'
@browser.window(:title => 'Business').when_present.use
@browser.frame(:id => "myframe").link(:text => 'Manage groups').when_present.click
@browser.frame(:id => "myframe").link(:class => "update").when_present.click
@browser.frame(:id => "myframe").div(:id => 'yw2').div(:id => 'selected_members_box').span(:text => 'H: '+host).when_present.click
@browser.frame(:id => "myframe").div(:class => "form").button(:value => "< Remove").when_present.click
@browser.frame(:id => "myframe").button(:value => "Save").when_present.click
@browser.frame(:id => "myframe").div(:class => "bsmtreeRow").link(:text => /#{host}/).exists?.should == false
end
end
<file_sep>class EventconsolePage
include PageObject
direct_url BASE_URL + "console"
link :filter_events_applications, :id =>/naviPanel:systemFilterTree:0/
td :events_application_types, :class => /icePnlGrdCol1/, :index => 0
link :applications_events, :id => /naviPanel:systemFilterTree:0/
link :application_nagios_event, :text => /NAGIOS/
link :host_groups_events, :id => /naviPanel:systemFilterTree:1/
#link :service_groups_events, :id => /naviPanel:systemFilterTree:2/
link :operation_status_events_open, :id => /naviPanel:systemFilterTree:3/
link :operation_status_events, :id => /naviPanel:systemFilterTree:3/
link :operation_status_events_accepted, :text => /ACCEPTED/
link :operation_status_events_notified, :text => /NOTIFIED/
link :host_groups_events, :id =>/naviPanel:systemFilterTree:1/
link :open_filter, :text => "OPEN"
link :close_filter, :text => "CLOSED"
#for linux server --> localhost option inside Host Groups
span :localhost, :text => /127.0.0.1/
span :number_showing_events, :class => "iceOutFrmt"
link :custom_group, :id => /naviPanel:systemFilterTree:n-1-0/
div :children, :id => /naviPanel:systemFilterTree-d-1-0-c/
link :all_events, :text => /All Events/
link :last_10_nagios_critical, :text => /Last 10 Minutes NAGIOS Critical/
link :last_5_snmptrap_warning, :text => /Last 5 SNMPTRAP Warning/
link :nagios_warning, :text => /Nagios Warning/
link :warnings, :text => /Warning/
link :criticals, :text => /Critical/
link :open_log_message, :text => /Open/, :id => /contentPanel:icepnltabset:0:j_id141/
link :close_log_message, :text => /Close/
link :accept_log_message, :text => /Accept/
link :notify_log_message, :text => /Notify/
text_field :message_search, :id => /searchEvents_messages/
text_field :host_search, :id => /searchEvents_hosts/
select :severity_search, :id => /searchEvents_severity/
select :opstatus_search, :id => /searchEvents_opStatus/
select :monstatus_search, :id => /searchEvents_monStatus/
link :reset, :text => /Reset/
link :search, :text => /Search/
link :all_open_events, :text => "All Open Events"
text_field :messages_search_box, :id => /contentPanel:icepnltabset:0:searchEvents_messages/
text_field :messages_search_box_newtab, :id => /contentPanel:icepnltabset:1:searchEvents_messages/
link :search_link, :text => /Search/
span :new_tab, :text => "New tab"
table :events_table, :id => /contentPanel:icepnltabset:0:eventTableID/
# link :SG1_link, :text => /SG1/
link :LS_link, :text => /Linux Servers/
div :page_title, :class => "BreadcumbsInfoBar ClearFix"
span :page_text, :id => /contentPanel:icepnltabset:0:j_id56/
button :close_tab, :name => /contentPanel:icepnltabset:1:j_id71/
link :hostname, :href => "/portal-statusviewer/urlmap?host=baden"
link :esx_bernina, :text => /ESX:bernina/
link :esx_morges, :text => /ESX:morges/
link :esx_thun, :text => /ESX:thun/
link :esx_wil, :text => /ESX:wil/
link :esx_zurich, :text => /ESX:zurich/
link :vssvermont, :text => /VSS:vermont2/
link :rhev_vm, :text => /RHEV-H:/
link :rhev_m, :text => /RHEV-M:eng-rhev-m-1.groundwork.groundworkopensource.com/
link :pool_view, :text => /POOL:/
link :net_view, :text => /NET:/
link :storage_view, :text => /STOR:/
in_frame(:id => 'myframe') do |frame|
span :esx_vssvermont, :text => /ESX:VSS:vermont2/, :frame => frame
end
link :vss_vermont, :text => /naviPanel:systemFilterTree:n-1-7:j_id22/
span :cpu_usage, :id => /contentPanel:icepnltabset:0:eventTableID:0:txt_textMessage/
link :esx_zurich, :text => /ESX:zurich.groundwork.groundworkopensource.com/
span :cpu_uptime, :id => /contentPanel:icepnltabset:0:eventTableID:0:txt_textMessage/
#link :rhev_vm, :text => /naviPanel:systemFilterTree:n-1-8:j_id22/
#link :rhev_m, :text => /naviPanel:systemFilterTree:n-1-9:j_id22/
#updating label of tab
text_field :update_label, :name => /update_label/
link :update_button, :text=> /Update Label/
#All Events link under Filter Events
link :all_events, :text => /All Events/
#displaying error message on blank search
span :error_message, :text => /Please enter atleast one search criteria to perform search/
button :error_ok, :value => /OK/
#Actions button and Nagios Acknowledge
span :actions, :text => /Actions/
span :nagios_ack, :text => /Nagios Acknowledge/
textarea :nagios_ack_comment, :name => /popupform/, :id => /popupText/
button :nagios_ack_comment_button, :value => /Submit/
#searching a device
text_field :device, :name => /searchEvents_hosts/
#searching a device by hostname in the table
span :hosts_displayed, :id => /contentPanel:icepnltabset:0:eventTableID:0:j_id475/, :class => /iceOutTxt/
link :show_event_tile_link, :text => /Show Event Tile/
def filter_type(type)
if type == "Host Group"
self.host_groups_events
elsif type == "Service Group"
self.service_groups_events
else
self.operation_status_events
end
end
def group_exists?(name,type)
self.filter_type(type)
self.custom_group_element.when_present.text == name
end
def check_events_message(message, tab)
table = @browser.table(:id => /contentPanel:icepnltabset:#{tab}:eventTableID/).when_present
size = table.rows.length - 2
size.times do |current|
self.wait_until do
element = get_element(tab, current)
element.text.include?(message)
end
end
if tab == 1
@browser.button(:src => "/portal-statusviewer/images/delete.png", :index => 1).click
sleep(2)
end
end
def get_element(tab, current)
@browser.span(:id => /icepnltabset:#{tab}:eventTableID:#{current}:txt_textMessage/)
end
def check_event_status(host, status)
#table = @browser.table(:id => "jbpns_2fgroundwork_2dmonitor_2fconsole_2fEventConsoleWindowsnpbj:contentPanel:icepnltabset:0:eventTableID").when_present
table = @browser.table(:id => /contentPanel:icepnltabset:0:eventTableID/).when_dom_changed
size = table.rows.length - 2
size.times do |current|
#if host == @browser.span(:id => "jbpns_2fgroundwork_2dmonitor_2fconsole_2fEventConsoleWindowsnpbj:contentPanel:icepnltabset:0:eventTableID:#{current}:j_id226").text
if host == @browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:#{current}:j_id/).text
self.wait_until do
#status == @browser.span(:id => "jbpns_2fgroundwork_2dmonitor_2fconsole_2fEventConsoleWindowsnpbj:contentPanel:icepnltabset:0:eventTableID:#{current}:txt_monitorStatus").text
status == @browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:#{current}:txt_monitorStatus/).text
end
end
end
end
def event_status_verify(view)
if view == "Storage View"
self.storage_view_element.exists?.should == true
self.storage_view_element.when_present.click
sleep(5)
elsif view == "Network View"
self.net_view_element.exists?.should == true
self.net_view_element.when_present.click
sleep(5)
elsif view == "Resource Pool"
self.pool_view_element.exists?.should == true
self.pool_view_element.when_present.click
sleep(5)
end
end
def verify_hoststatus_eventconsole(host,state)
@browser.div(:id => /contentPanel:icepnltabset:0:eventTableID:0:pnl_host/).span(:id => /contentPanel:icepnltabset:0:eventTableID:0/,:text => /#{host}/).exists?.should == true
@browser.div(:id => /contentPanel:icepnltabset:0:eventTableID:0:pnl_monitorStatus/).span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_monitorStatus/,:text => /#{state}/).exists?.should == true
puts @browser.div(:id => /contentPanel:icepnltabset:0:eventTableID:0:pnl_monitorStatus/).span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_monitorStatus/,:text => /#{state}/).text
end
end
<file_sep>require 'cucumber'
require 'cucumber/rake/task'
Cucumber::Rake::Task.new(:cucumber) do |t|
t.profile = 'default'
end
Cucumber::Rake::Task.new(:bugs) do |t|
t.profile = 'bugs'
end
task :daily do
sh "cucumber features/smoke_test/smoke_test.feature"
sh "cucumber features/smoke_test/upgrade_view_test.feature"
sh "cucumber features/nagvis_test/nagvis_smoke.feature"
sh "cucumber features/custom_groups_test/custom_groups.feature"
end
task :upgrade_check do
sh "cucumber features/smoke_test/upgrade_view_test.feature"
end
task :event_console do
sh "cucumber features/event_console/event_console.feature"
end
task :home_page do
sh "cucumber features/home_page/home_page_test.feature"
end
task :auto_discovery do
sh "cucumber features/auto_discovery/auto_discovery_test.feature"
end
task :dashboard do
sh "cucumber features/dashboard/dashboard.feature"
end
task :nagvis_advanced do
sh "cucumber features/nagvis_test/nagvis_advanced.feature"
end
task :default => :cucumber
<file_sep>Given /^I am on the Cloud Hub page$/ do
visit CloudHubPage
end
When /^I select "(.+)" for new connection$/ do |connection|
if connection == "RedHat"
@browser.frame(:id => "myframe").link(:href => /rhev/, :class => /button-l/).click
else
connection = connection.downcase
@browser.frame(:id => "myframe").link(:href => /#{connection}/, :class => /button-l/).click
=begin
on CloudHubPage do |page|
#Modification
#page.vmware_element.when_present.set
#page.add_element.when_present.click
page.add_vmware_element.when_present.click
end
=end
end
sleep(3)
end
#Modification -- regarding wsuser password , (.+) -> (.*?)
When /^I start new configuration and set all fields as "(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)"$/ do |displayname,gwserver,wsuser,passwd,vmserver,username,pwd,interval|
on CloudHubPage do |page|
page.display_name = displayname
page.groundwork_server = gwserver
page.wsuser_name = wsuser
page.wsuser_password = <PASSWORD>
page.server_name = vmserver
page.username = username
page.password = pwd
page.interval = interval
end
end
When /^I select the Storage View, Network View and Resource Pool View$/ do
on CloudHubPage do |page|
page.storage_view_element.set
page.network_view_element.set
page.resource_view_element.set
end
end
When /^I save the connection$/ do
on CloudHubPage do |page|
page.save_element.when_present.click
sleep(3)
end
end
When /^test connection is done$/ do
on CloudHubPage do |page|
page.test_connection_element.wait_until_present
page.test_connection_element.when_present.click
sleep(3)
end
end
And /^verify connection is established$/ do
Watir::Wait.until {
@browser.frame(:id => "myframe").div(:id => /testConResultMsg/).text.include? 'Connection successful!'
}
end
And /^I navigate to cloud hub home page$/ do
on CloudHubPage do |page|
page.home_element.when_present.click
end
end
Then /^I should navigate to the home page$/ do
on CloudHubPage do |page|
page.home.click
end
end
And /^I delete the connection - "(.+)" created$/ do |name|
=begin on CloudHubPage do |page|
page.delete_element.when_present.click
page.wait_until(5) do
@browser.alert.ok
end
end
=end
$table = @browser.frame(:id => /myframe/).table(:id => /example/, :class => /display dataTable/)
table_row = $table.td(:text => name).parent
table_row.button(:value => /Delete/).click
sleep(2)
@browser.alert.ok
sleep(5)
end
Then /^the connection - "(.+)" added should be in Stop state$/ do |name|
#@browser.frame(:id => "myframe").td(:class => /serverStatusCol/).div(:class => /redcircle/).click
$table = @browser.frame(:id => /myframe/).table(:id => /example/, :class => /display dataTable/)
table_row = $table.td(:text => name).parent
table_row.button(:value => /Start/).exists?.should == true
end
Given /^I start the new connection - "(.+)" created$/ do |name|
=begin
on CloudHubPage do |page|
page.startconnection_element.when_present.click
sleep(5)
end
=end
$table = @browser.frame(:id => /myframe/).table(:id => /example/, :class => /display dataTable/)
table_row = $table.td(:text => name).parent
table_row.button(:value => /Start/).click
sleep(10)
end
Then /^connection - "(.+)" should be started$/ do |name|
=begin
on CloudHubPage do |page|
page.green_element.exists?.should == true
end
=end
table_row = $table.td(:text => name).when_present.parent
table_row.button(:value => /Stop/).exists?.should == true
end
#26
Then /^ESX-Vermont servers should be displayed on the Status viewer and Event console page$/ do
sleep(240)
visit StatusviewerPage
on StatusviewerPage do |page|
#<EMAIL>(:id => "myframe").link(:id => "frmTree:pnlTbSet:0:hstTree:n-3:lnkNdClick").span(:text => /ESX:bernina.groundwork.groundworkopensource.com/).exists?.should == true
#page.wait_until(360) do
page.esx_bernina_element.exists?.should == true
page.esx_morges_element.exists?.should == true
page.esx_thun_element.exists?.should == true
page.esx_wil_element.exists?.should == true
page.esx_zurich_element.exists?.should == true
page.esx_vssvermont_element.exists?.should == true
#end
end
visit EventconsolePage
on EventconsolePage do |page|
page.host_groups_events_element.when_present.click
sleep(10)
page.esx_bernina_element.exists?.should == true
page.esx_morges_element.exists?.should == true
page.esx_thun_element.exists?.should == true
page.esx_wil_element.exists?.should == true
page.esx_zurich_element.exists?.should == true
page.vssvermont_element.exists?.should == true
end
end
When /^I click modify button of connection - "(.+)"$/ do |name|
=begin
on CloudHubPage do |page|
page.modify_element.when_present.click
end
=end
$table = @browser.frame(:id => /myframe/).table(:id => /example/, :class => /display dataTable/)
table_row = $table.td(:text => name).parent
table_row.button(:value => /Modify/).click
end
When /^I click next button$/ do
on CloudHubPage do |page|
page.next_element.when_present.click
end
end
When /^verify Cloud Hub Configuration page for "(.*?)" should be opened$/ do |connection|
if connection == "RedHat"
@browser.frame(:id => /myframe/).p(:text => /CloudHub Configuration wizard for RHEV-M/).exists?.should == true
else
@browser.frame(:id => /myframe/).p(:text => /#{"Cloud Hub Configuration wizard for "+connection}/).when_present.exists?.should == true
end
=begin
on CloudHubPage do |page|
page.cloudhub_element.exists?.should == true
end
=end
end
When /^I click delete button$/ do
on CloudHubPage do |page|
page.delete_element.when_present.click
page.wait_until(5) do
@browser.alert.ok
end
end
end
Then /^verify connection - "(.+)" should be deleted$/ do |name|
table_row = $table.td(:text => name).exists?.should == false
=begin
on CloudHubPage do |page|
page.wait_until(10) do
page.testconnection_element.exists?.should == false
end
end
=end
end
When /^I select one "(.+)" service "(.+)" and set thresholds as "(.+)" and "(.+)"$/ do |type,service,warning,critical|
sleep(5)
if type == "Hypervisor"
@browser.frame(:id => /myframe/).checkbox(:id => /hyp_monitored_5/).when_present.set
@browser.frame(:id => /myframe/).text_field(:id => /hyp_warningThreshold_5/).when_present.set warning
@browser.frame(:id => /myframe/).text_field(:id => /hyp_criticalThreshold_5/).when_present.set critical
$Service1 = service
$Warning = warning
$Critical = critical
else
@browser.frame(:id => /myframe/).checkbox(:id => /vm_monitored_18/).when_present.set
@browser.frame(:id => /myframe/).text_field(:id => /vm_warningThreshold_18/).when_present.set warning
@browser.frame(:id => /myframe/).text_field(:id => /vm_criticalThreshold_18/).when_present.set critical
$Service1 = service
$Warning = warning
$Critical = critical
end
end
And /^I remove one "(.+)" service "(.+)"$/ do |type,service|
if type == "Hypervisor"
@browser.frame(:id => /myframe/).checkbox(:id => /hyp_monitored_4/).clear
$Service = service
else
@browser.frame(:id => /myframe/).checkbox(:id => /vm_monitored_17/).clear
$Service = service
end
end
When /^save it$/ do
on CloudHubPage do |page|
page.save_element.when_present.click
sleep(10)
end
end
Then /^verify changes are done to "(.+)" on Status viewer page$/ do |type|
sleep(60)
visit StatusviewerPage
if type == "Hypervisor"
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:32/).click
sleep(3)
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:32-23/).click
sleep(10)
@browser.link(:text => /#{$Service1}/).click
sleep(5)
@browser.span(:id => /SVform:SItxtServiceStatusValue/, :text => /#{"W\/C="+$Warning+"\/"+$Critical}/).exists?.should == true
@browser.link(:text => /#{$Service}/).exists?.should == false
else
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:5/).click
sleep(3)
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:5-0/).click
sleep(15)
@browser.link(:text => /#{$Service1}/).click
sleep(5)
@browser.span(:id => /SVform:SItxtServiceStatusValue/, :text => /#{"W\/C="+$Warning+"\/"+$Critical}/).exists?.should == true
@browser.link(:text => /#{$Service}/).exists?.should == false
end
end
When /^I select a vm service "(.+)"$/ do |service|
on CloudHubPage do |page|
page.vm_service_element.when_present.set
end
end
=begin
Then /^verify vm changes are done on Status viewer page$/ do
sleep(100)
visit StatusviewerPage
on StatusviewerPage do |page|
page.esx_zurich_element.click
sleep(2)
page.bern_host_machine_element.click
sleep(3)
#page.cpu_uptime_element.exists?.should==true
page.cpu_uptime_element.exists?.should==true
sleep(3)
end
end
=end
When /^I select RedHat for new connection$/ do
on CloudHubPage do |page|
#page.redhat_element.when_present.set
#page.add_element.click
#sleep(3)
page.add_redhat_element.when_present.click
end
end
When /^I start new redhat configuration and set all fields as "(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)"$/ do |displayname,gwserver,wsuser,wsuser_passwd,rhserver,entrypoint,rhpwd,storepath,passcode,check_interval,sync_interval|
on CloudHubPage do |page|
page.rh_display_name = displayname
page.rh_groundwork_server = gwserver
page.wsuser_name = wsuser
page.wsuser_password = <PASSWORD>
page.server_name = rhserver
page.rh_entrypoint = entrypoint
page.rh_password = <PASSWORD>
page.rh_storepath = storepath
page.rh_passcode = passcode
page.rh_check_interval = check_interval
page.rh_sync_interval = sync_interval
end
end
Then /^rhev servers should be displayed on the Status viewer and Event console page$/ do
=begin
sleep(600)
visit StatusviewerPage
on StatusviewerPage do |page|
#page.wait_until(360) do
page.rhev_vm_element.exists?.should == true
page.rhev_m_element.exists?.should == true
#end
end
=end
visit EventconsolePage
on EventconsolePage do |page|
page.host_groups_events_element.when_present.click
sleep(5)
page.rhev_m_element.exists?.should == true
page.rhev_vm_element.exists?.should == true
end
end
=begin
When /^verify Cloud Hub Configuration page for RHEVM should be opened$/ do
on CloudHubPage do |page|
page.wait_until(5) do
page.rh_cloudhub_element.exists?.should == true
end
end
end
=end
#---------------------
When /^I move to next page$/ do
on CloudHubPage do |page|
page.next_element.click
sleep(10)
end
end
When /^I enter value in hypervisor warning threshold and critical threshold as"(.+)","(.+)"$/ do |hyp_warning_threshold,hyp_critical_threshold|
on CloudHubPage do |page|
page.hyp_warning_threshold = hyp_warning_threshold
page.hyp_critical_threshold = hyp_critical_threshold
end
end
When /^I enter value in vm warning threshold and critical threshold as"(.+)","(.+)"$/ do |vm_warning_threshold,vm_critical_threshold|
on CloudHubPage do |page|
page.vm_warning_threshold = vm_warning_threshold
page.vm_critical_threshold = vm_critical_threshold
end
end
And /^threshold validation messages should be displayed$/ do
Watir::Wait.until {
@browser.frame(:id => "myframe").div(:id => /controlbg/).text.include? 'Not a valid number.'
}
end
Then /^verify connection is not established$/ do
sleep(3)
@browser.frame(:id => "myframe").div(:text => /GWOS connection failed!/).exists?.should==true
on CloudHubPage do |page|
page.next_element.should be_disabled
end
#@browser.frame(:id => "myframe").div(:id => /testConResultMsg/).text.include? 'RHEV-M server connection failed!' or 'GWOS connection failed!'
end
#Then /^verify red hat connection is not established$/ do
# sleep(3)
# @browser.frame(:id => "myframe").div(:text => /RHEV-M server connection failed!/).exists?.should==true
#end
Then /^different validation messages should appear$/ do
Watir::Wait.until {
@browser.frame(:id => "myframe").span(:text => /Display name cannot be empty./).exists?.should==true
@browser.frame(:id => "myframe").span(:text => /Server name cannot be empty./).exists?.should==true
@browser.frame(:id => "myframe").span(:text => /User name cannot be empty./).exists?.should==true
@browser.frame(:id => "myframe").span(:text => /Password cannot be empty./).exists?.should==true
@browser.frame(:id => "myframe").span(:text => /Not a valid check interval/).exists?.should==true
@browser.frame(:id => "myframe").span(:text => /Not a valid retry interval/).exists?.should==true
}
on CloudHubPage do |page|
page.test_connection_element.should be_disabled
sleep(3)
end
end
Then /^check interval validation message should be displayed$/ do
Watir::Wait.until {
@browser.frame(:id => "myframe").span(:text => /Not a valid check interval/).exists?.should==true
}
end
#New steps to verify Views
Given /^I am on the Status page$/ do
visit StatusviewerPage
end
Given /^I am on the Event page$/ do
visit EventconsolePage
end
Given /^I verify the "(.+?)" hosts on Status viewer page$/ do |view|
on StatusviewerPage do |page|
sleep(5)
page.status_verify(view)
end
end
Then /^the hosts should be visible$/ do
end
Given /^I verify the "(.+?)" hosts on Event console page$/ do |view|
on EventconsolePage do |page|
page.host_groups_events_element.when_present.click
sleep(5)
page.event_status_verify(view)
end
end
And /^I delete all other connections created$/ do
while @browser.frame(:id => /myframe/).button(:value => /Delete/).exists?
@browser.frame(:id => /myframe/).button(:value => /Delete/).click
sleep(2)
@browser.alert.ok
sleep(3)
end
end
#Openstack
$OS
When /^I start new configuration and set fields as "(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)","(.+)"$/ do |displayname,gwserver,wsuser,passwd,oserver,tenant_id,tenant_name,username,pwd,nova_port,keystone_port,ceilometer_port,check_interval,connection_retries|
on CloudHubPage do |page|
page.display_name = displayname
page.groundwork_server = gwserver
page.wsuser_name = wsuser
page.wsuser_password = <PASSWORD>
page.server_name = oserver
page.tenant_id = tenant_id
page.tenant_name = tenant_name
page.username = username
page.password = pwd
page.nova_port = nova_port
page.keystone_port = keystone_port
page.ceilometer_port = ceilometer_port
page.interval = check_interval
page.connection_retries = connection_retries
end
$OS = oserver[0...25]
end
Then /^OS-H and OS-M servers should be displayed on the Status viewer and Event console page$/ do
sleep(60)
visit StatusviewerPage
visit StatusviewerPage
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree/, :text => /#{"OS-H:"+$OS}/).exists?.should == true
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree/, :text => /#{"OS-M:"+$OS}/).exists?.should == true
visit EventconsolePage
on EventconsolePage do |page|
page.host_groups_events_element.when_present.click
sleep(7)
end
@browser.link(:text => /#{"OS-H:"+$OS}/).exists?.should == true
@browser.link(:text => /#{"OS-M:"+$OS}/).exists?.should == true
end
Then /^I verify Openstack connection is not established$/ do
sleep(3)
@browser.frame(:id => "myframe").div(:text => /OpenStack server connection failed/).exists?.should==true
#@browser.frame(:id => "myframe").div(:id => /testConResultMsg/).text.include? 'RHEV-M server connection failed!' or 'GWOS connection failed!'
end
And /^I remove a "(.+)" service "(.+)"$/ do |type,service|
if type == "Hypervisor"
@browser.frame(:id => /myframe/).checkbox(:id => /hyp_monitored_2/).clear
$Service = service
else
@browser.frame(:id => /myframe/).checkbox(:id => /vm_monitored_1/).clear
$Service = service
end
end
And /^I select "(.+)" service "(.+)" and set thresholds as "(.+)" and "(.+)"$/ do |type,service,warning,critical|
if type == "Hypervisor"
@browser.frame(:id => /myframe/).checkbox(:id => /hyp_monitored_1/).when_present.set
@browser.frame(:id => /myframe/).text_field(:id => /hyp_warningThreshold_1/).when_present.set warning
@browser.frame(:id => /myframe/).text_field(:id => /hyp_criticalThreshold_1/).when_present.set critical
$Service1 = service
$Warning = warning
$Critical = critical
else
@browser.frame(:id => /myframe/).checkbox(:id => /vm_monitored_2/).when_present.set
@browser.frame(:id => /myframe/).text_field(:id => /vm_warningThreshold_2/).when_present.set warning
@browser.frame(:id => /myframe/).text_field(:id => /vm_criticalThreshold_2/).when_present.set critical
$Service1 = service
$Warning = warning
$Critical = critical
end
end
Then /^verify changes are applied for "(.+)" on Status viewer page$/ do |type|
sleep(60)
visit StatusviewerPage
if type == "Hypervisor"
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:4/).click
sleep(3)
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:4-0/).click
sleep(3)
@browser.link(:text => /#{$Service}/).exists?.should == false
@browser.link(:text => /#{$Service1}/).click
sleep(5)
@browser.span(:id => /SVform:SItxtServiceStatusValue/, :text => /#{"W\/C="+$Warning+"\/"+$Critical}/).exists?.should == true
else
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:3/).click
sleep(3)
@browser.link(:id => /frmTree:pnlTbSet:0:hstTree:3-0/).click
sleep(3)
@browser.link(:text => /#{$Service}/).exists?.should == false
@browser.link(:text => /#{$Service1}/).click
sleep(5)
@browser.span(:id => /SVform:SItxtServiceStatusValue/, :text => /#{"W\/C="+$Warning+"\/"+$Critical}/).exists?.should == true
end
end
And /^I clear all fields$/ do
on CloudHubPage do |page|
page.display_name_element.clear()
page.groundwork_server_element.clear()
page.wsuser_name_element.clear()
page.wsuser_password_element.clear()
page.interval_element.clear()
page.connection_retries_element.clear()
end
end
#for redhat
And /^I clear all the fields$/ do
on CloudHubPage do |page|
page.rh_display_name_element.clear()
page.rh_groundwork_server_element.clear()
page.wsuser_name_element.clear()
page.wsuser_password_element.clear()
page.interval_element.clear()
page.connection_retries_element.clear()
end
end
<file_sep>class PerformanceViewReportPage
include PageObject
direct_url BASE_URL + "reports/performanceview"
end
<file_sep>class NagvisViewsPage
include PageObject
direct_url BASE_URL + "nagvis"
in_frame(:id => 'myframe') do |frame|
image :test_map_image, :src => /TestMap/, :frame => frame
image :gadget_raw_number_image, :alt => "service-localhost-local_cpu_nagios",:frame => frame
image :gadget_thermo_image, :alt => "service-localhost-local_disk_root",:frame => frame
image :gadget_bar_image, :alt => "service-localhost-local_nagios_latency",:frame => frame
image :gadget_chart_pie_image, :alt => "service-localhost-local_mem_nagios",:frame => frame
end
div :page_title, :class => "BreadcumbsInfoBar ClearFix"
@@map_id = {"hostgroups" => "map-hostgroups", "servicegroups" => "map-servicegroups", "submaps" => "map-submaps", "geomap" => "map-geomap"}
@@map_index = {"hostgroups" => 0, "servicegroups" => 1, "submaps" => 2}
@@hostsgroup_index = {"hosts all" => 0, "hosts critical" => 1, "hosts ok" => 2, "hosts pending" => 3, "hosts unknown" => 4, "hosts warning" => 5, "hosts up" => 6, "hosts down" => 7}
@@servicegroup_index = {"group-all" => 0, "group-ok" => 1, "group-warning" => 2, "group-critical" => 3, "group-unknown" => 4, "group-pending" => 5 }
@@mapname_index = {"Hosts_Up" => 0, "Hosts_Down" => 1, "hostgroups" => 2, "servicegroups" => 3}
@@hostup_index = {"host-up-ok" => 0, "host-up-warning" => 1, "host-up-critical" => 2, "host-up-unknown" => 3, "host-up-pending" => 4}
def map_index
@@map_index
end
def hostgroup_index
@@hostsgroup_index
end
def servicegroup_index
@@servicegroup_index
end
def mapname_index
@@mapname_index
end
def hostup_index
@@hostup_index
end
def obtainMap(map_name)
alt = @@map_id["#{map_name}"]
@browser.frame(:id => "myframe").image(:alt => "#{alt}")
end
def obtainIcon(identifier)
@browser.frame(:id => "myframe").image(:alt => "#{identifier}")
end
def validateState(state,index)
text = @browser.frame(:id => "myframe").table(:class => "hover_table", :index => index).rows[2].cells[1].text
text.include?(state)
end
def validateState_second_level_maps(state,index)
text = @browser.frame(:id => "myframe").table(:class => "hover_table", :index => index).rows[12].cells[1].text
text.include?(state)
end
def validateOutput(output,index)
text = @browser.frame(:id => "myframe").table(:class => "hover_table", :index => index).rows[3].cells[1].text.gsub("\n"," ")
text.include?(output)
end
def validateState_embedded_map(state,index)
text = @browser.frame(:id => "myframe").table(:class => "hover_table", :index => index).rows[4].cells[1].text
text.include?(state)
end
def validateOutput_embedded_map_hostgroups(output,index)
text = @browser.frame(:id => "myframe").table(:class => "hover_table", :index => index).rows[5].cells[1].text.gsub("\n"," ")
text.include?(output)
end
#created since the normal validateoutput method was not working for service groups.
def validateOutput_embedded_map_groups(output,index)
text = @browser.frame(:id => "myframe").table(:class => "hover_table", :index => index).rows[5].cells[1].text.gsub("\n"," ")
if text = output
else
puts 'failure'
raise
end
end
def validateChildren(children,index_map)
table = @browser.frame(:id => "myframe").table(:class => "hover_table", :index => index_map).table
children.each_with_index do |child,index|
table.rows[index+1].cells[0].text.include? child["name"]
table.rows[index+1].cells[1].text.include? child["state"]
table.rows[index+1].cells[2].text.gsub("\n"," ").include? child["output"]
end
end
def validateAttribute(attribute, json_attribute, index)
table = @browser.frame(:id => "myframe").table(:class => "hover_table", :index => index)
table.rows.each do |row|
if row.cells[0].text.downcase.include? attribute
return row.cells[1].text.include? json_attribute
end
end
false
end
def check_tab
self.wait_until(10) do
@browser.frame.table.text.include? "Map Index"
end
end
end
<file_sep>class EscalationPage
include PageObject
direct_url BASE_URL + "config/escalations"
def create_escaltion(name)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Escalations/).when_present.click
frameleft.link(:text => /service escalation/).when_present.click
frameleft.link(:text => /New/).when_present.click
framemain.text_field(:name => 'name').when_present.set name
framemain.text_field(:name => 'first_notification').set '1'
framemain.text_field(:name => 'last_notification').set '3'
framemain.text_field(:name => 'notification_interval').set '60'
framemain.select(:name => 'escalation_period').select('24x7')
framemain.checkbox(:value => 'c', :name => 'escalation_options').when_present.set
framemain.button(:value => 'Add').when_present.click
end
def create_escalation_tree(tree,escalation)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Escalation trees/).when_present.click
frameleft.link(:text => /service escalation tree/).when_present.click
frameleft.link(:text => /New/).when_present.click
framemain.text_field(:name => 'name').when_present.set tree
framemain.button(:value => 'Add').when_present.click
framemain.select(:name => 'escalation').select(escalation)
framemain.button(:value => 'Add Escalation').when_present.click
framemain.select(:name => 'contactgroups_nonmembers').select('nagiosadmin')
framemain.button(:value => /<< Add/).when_present.click
framemain.button(:value => 'Save').when_present.click
framemain.button(:value => 'Assign Hosts').when_present.click
framemain.select(:name => 'hosts_nonmembers').select('localhost')
framemain.button(:value => /<< Add/).when_present.click
framemain.button(:value => 'Save').when_present.click
end
def verify_tree(tree)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Escalations/).when_present.click
frameleft.link(:text => /Escalation trees/).when_present.click
frameleft.link(:text => /service escalation tree/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{tree}/).exists?.should == true
end
########################## HOST ESCALATION ##############################
def create_host_escaltion(escalation)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Escalations/).when_present.click
frameleft.link(:text => /host escalation/).when_present.click
frameleft.link(:text => /New/).when_present.click
framemain.text_field(:name => 'name').when_present.set escalation
framemain.text_field(:name => 'first_notification').set '1'
framemain.text_field(:name => 'last_notification').set '3'
framemain.text_field(:name => 'notification_interval').set '60'
framemain.select(:name => 'escalation_period').select('24x7')
framemain.checkbox(:value => 'd', :name => 'escalation_options').when_present.set
framemain.button(:value => 'Add').when_present.click
end
def create_host_escalation_tree(tree,escalation)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Escalation trees/).when_present.click
frameleft.link(:text => /host escalation tree/).when_present.click
frameleft.link(:text => /New/).when_present.click
framemain.text_field(:name => 'name').when_present.set tree
framemain.button(:value => 'Add').when_present.click
framemain.select(:name => 'escalation').select(escalation)
framemain.button(:value => 'Add Escalation').when_present.click
framemain.select(:name => 'contactgroups_nonmembers').select('nagiosadmin')
framemain.button(:value => /<< Add/).when_present.click
framemain.button(:value => 'Save').when_present.click
framemain.button(:value => 'Assign Hosts').when_present.click
framemain.select(:name => 'hosts_nonmembers').select('localhost')
framemain.button(:value => /<< Add/).when_present.click
framemain.button(:value => 'Save').when_present.click
end
def verify_host_tree(tree)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Escalations/).when_present.click
frameleft.link(:text => /Escalation trees/).when_present.click
frameleft.link(:text => /host escalation tree/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{tree}/).exists?.should == true
end
end
<file_sep>Given /^I specify subnet filter pattern "(.+?)" of type "(.+?)" and range "(.+?)"$/ do |filterName, type, range|
on AutodiscoveryPage do |page|
page.add_filter(type, filterName, range)
page.select_control_type
end
end
When /^I launch an Auto Discovery for stress testing$/ do
on AutodiscoveryPage do |page|
page.launch_autodiscovery
page.wait_until(3000) do
page.scan_status_element.text.include?('All records processed')
end
end
end
Then /^hosts should be discovered correctly$/ do
on AutodiscoveryPage do |page|
array_increments_by?(1,page.range_discover).should == true
end
end
Then /^hosts of "(.+?)" for the filter "(.+?)" should appear on status viewer$/ do |subnet, filterName|
on AutodiscoveryPage do |page|
$hosts = page.hosts_discover
page.commit_results
end
#Optimuscomment: Sleep required for newely discovered hosts to be visible in Status viewer
sleep(10)
visit StatusviewerPage
on StatusviewerPage do |page|
page.total_hosts.to_f.should >= $hosts.count
end
visit AutodiscoveryPage
on AutodiscoveryPage do |page|
page.delete_filter(filterName)
end
visit HostsConfigurationPage
on HostsConfigurationPage do |page|
page.remove_all_host(subnet)
end
end<file_sep>class LoginPage
include PageObject
direct_url BASE_URL
text_field :user, :name => 'josso_username'
text_field :password, :name => '<PASSWORD>'
button :login, :value => 'Login'
link :knowledge_base, :text => /Knowledge Base/
link :case_manager, :text => /Case Manager/
link :forums, :text => /Forums/
link :groundwork, :text => /www.gwos.com/
def login_user(user,password)
self.user = user
self.password = <PASSWORD>
self.login
end
end
<file_sep>Given /^I create a duplicate range-filter with name "(.+?)", type "(.+?)" and range "(.+?)"$/ do |filterName, type, range|
on AutodiscoveryPage do |page|
page.delete_old_filters
sleep(3)
page.add_filter(type, filterName, range)
sleep(3)
page.filter_type = type
page.range_filter_name = filterName
page.range_filter_pattern = range
end
end
When /^I try to add the Range\/Filter$/ do
on AutodiscoveryPage do |page|
page.save_filter
end
end
Then /^I should see the duplicate message error for "(.+?)"$/ do |filterName|
@browser.frame(:id => "myframe").td(:class => "row1").text.include?("A filter named \""+ filterName + "\" already exists").should == true
on AutodiscoveryPage do |page|
page.delete_filter(filterName)
end
end
Given /^I use the default discovery definition$/ do
on AutodiscoveryPage do |page|
page.wait_until(10) do
page.default_definition_element.exists?
end
page.select_default_definition
#OptimusComment: With multiple discovery definitions some processing is done on selecting a discovery definition
sleep(1)
page.delete_old_filters #to delete localhost filter during first run
end
end
Given /^I add a list of hosts to this definition with name "(.+?)", type "(.+?)" and range "(.+?)"$/ do |filterName, type, range|
on AutodiscoveryPage do |page|
page.wait_until(10) do
page.range_filter_pattern_element.exists?
end
page.add_filter(type, filterName, range)
end
end
Given /^I change the mode to auto$/ do
on AutodiscoveryPage do |page|
page.select_control_type
end
end
Then /^the hosts "(.+?)" and "(.+?)" for the filter "(.+?)" should be visible in status viewer$/ do |host1, host2, filterName|
visit AutodiscoveryPage
on AutodiscoveryPage do |page|
page.delete_filter(filterName)
end
visit StatusviewerPage
#OptimusComment: Sleep is required, for the processing required for a host to be available in status viewer
sleep(15)
on StatusviewerPage do |page|
page.search_for_host(host1).should >= 1
page.search_for_host(host2).should >= 1
end
end
Then /^I remove the hosts "(.+?)" - "(.+?)" and "(.+?)" - "(.+?)"$/ do |host1, hostName1, host2, hostName2|
visit HostsConfigurationPage
on HostsConfigurationPage do |page|
page.remove_host(host1, hostName1)
page.remove_host(host2, hostName2)
end
end
Given /^I create a discovery definition "(.+?)" and select "(.+?)" filter of type "(.+?)" and range "(.+?)"$/ do |defName, filterName, type, range|
on AutodiscoveryPage do |page|
page.add_filter(type,filterName,range)
page.new_discovery_definition
page.discovery_definition_name = defName
page.discovery_definition_description= defName
@browser.frame(:id => "myframe").select(:name => "schema").select("GroundWork-Discovery-Pro")
@browser.frame(:id => "myframe").select(:name => "auto").select("Auto")
@browser.frame(:id => "myframe").select(:name => "template").select("GroundWork-Default-Pro")
page.create_group
end
end
When /^I Uncheck definition methods$/ do
on AutodiscoveryPage do |page|
page.uncheck_NmapTCP
page.uncheck_SNMP
page.check_range_filter_name
end
end
When /^save the definition$/ do
on AutodiscoveryPage do |page|
page.save_group
end
end
Given /^I launch go$/ do
on AutodiscoveryPage do |page|
page.go
end
end
Then /^I should see no method assign message error for "(.+?)"$/ do |name|
@browser.frame(:id => "myframe").td(:class => "row1").text.include?("There are no methods assigned to \""+ name +"\". You must assign at least one discovery method.")
on AutodiscoveryPage do |page|
page.delete_filter(name)
page.edit_discovery_definition
page.delete_group
page.yes_discovery_def_delete
end
end
Given /^I add an address filter "(.+?)" of type "(.+?)" with range "(.+?)"$/ do |filterName, type, range|
on AutodiscoveryPage do |page|
page.wait_until(10) do
page.range_filter_pattern_element.exists?
end
page.add_filter(type, filterName, range)
end
end
Given /^I add a new address filter$/ do
on AutodiscoveryPage do |page|
page.wait_until(10) do
page.range_filter_pattern_element.exists?
end
page.add_filter("include","Include","172.28.113.152-153")
end
end
Then /^I should see "(.+?)"-"(.+?)" but not the excluded host "(.+?)" in status viewer and host page$/ do |includeRange, includeHostname, excludeRange|
visit StatusviewerPage
#OptimusComment: Sleep is required, for the processing required for a host to be available in status viewer
sleep(15)
on StatusviewerPage do |page|
page.search_for_host(includeRange).should >= 1
end
visit HostsConfigurationPage
on HostsConfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Search hosts/).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:id, "val1").when_present.set excludeRange
sleep(5)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").td(:text => /Nothing found/).exists?.should == true
page.remove_host(includeRange, includeHostname)
end
end
Then /^I remove the added hosts "(.+?)" and "(.+?)"$/ do |exculdeName, includeName|
visit AutodiscoveryPage
on AutodiscoveryPage do |page|
page.delete_filter(exculdeName)
page.delete_filter(includeName)
end
end
Given /^I change the mode to auto commit$/ do
on AutodiscoveryPage do |page|
@browser.frame(:id => "myframe").radio(:name => "auto_GroundWork-Discovery-Pro", :index => 2).when_present.set
end
end
Given /^I specify address range$/ do
on AutodiscoveryPage do |page|
page.add_filter("include","auto-commit","172.28.113.205-207")
end
end
When /^I start the discovery$/ do
on AutodiscoveryPage do |page|
page.launch_autodiscovery
page.wait_until(600) do
page.scan_status_element.text.include? "Discovery process has completed"
end
page.close_auto_commit_element.when_present.click
@browser.frame(:id => "myframe").radio(:name => "auto_GroundWork-Discovery-Pro", :index => 1).when_present.set
end
end
Then /^I should see the hosts "(.+?)" in Status viewer$/ do |host|
visit StatusviewerPage
#OptimusComment: Sleep is required, for the processing required for a host to be available in status viewer
sleep(15)
on StatusviewerPage do |page|
page.search_for_host(host).should >= 1
end
end
Then /^I remove the filter "(.+?)" and the host "(.+?)"-"(.+?)"$/ do |filterName, range, hostName|
visit AutodiscoveryPage
on AutodiscoveryPage do |page|
page.delete_filter(filterName)
end
visit HostsConfigurationPage
on HostsConfigurationPage do |page|
page.remove_host(range, hostName)
end
end
Given /^I change the mode to interactive$/ do
@browser.frame(:id => "myframe").radio(:name => "auto_GroundWork-Discovery-Pro", :index => 0).when_present.set
end
Given /^I launch the Auto Discovery with interactive mode$/ do
on AutodiscoveryPage do |page|
page.launch_autodiscovery
page.wait_until(300) do
page.scan_status_element.text.include? "Discovery stage has completed"
end
page.next_element.when_present.click
end
end
When /^I select process records$/ do
on AutodiscoveryPage do |page|
#page.wait_until(10) do
# page.record_checkbox_element.exists?
#end
sleep(10)
page.record_checkbox_element.when_present.set
page.process_records_element.when_present.click
end
end
When /^I select process records and continue$/ do
on AutodiscoveryPage do |page|
page.process_record_element.when_present.click
page.continue_element.when_present.click
end
end
Then /^the Auto Discovery UI shows properly$/ do
sleep(10)
Watir::Wait.until{ @browser.frame(:id => "myframe").td(:class => "data0").td(:class => "head").text.include? "Auto Discovery" }
#on AutodiscoveryPage do |page|
#@browser.frame(:id => "myframe").td(:class => "data0").td(:class => "row1").td(:class => "match_selected").radio(:name => "discover_name_select").when_present.set
#end
end
Given /^I add two overlapping ranges "(.+?)" for filter name "(.+?)" of type "(.+?)"$/ do |range, filterName, type|
on AutodiscoveryPage do |page|
page.delete_filter(filterName)
page.add_filter(type, filterName, range)
page.select_control_type
@browser.frame(:id => "myframe").radio(:name => "auto_GroundWork-Discovery-Pro", :index => 1).when_present.set
end
end
#for last scenario
Given /^I Uncheck SNMP definition method$/ do
on AutodiscoveryPage do |page|
page.uncheck_SNMP
page.check_range_filter_name
end
end
Then /^the repeated hosts for the range "(.+?)" should be autodiscovered once$/ do |filterName|
on AutodiscoveryPage do |page|
array_increments_by?(1,page.range_discover_without_SNMP_Scan).should == true
end
visit AutodiscoveryPage
on AutodiscoveryPage do |page|
page.delete_filter(filterName)
end
end
Then /^I should see a correct auto discover without invalid range "(.+?)"$/ do |filterName|
on AutodiscoveryPage do |page|
page.range_discover.count.should == 1
end
visit AutodiscoveryPage
on AutodiscoveryPage do |page|
page.delete_filter(filterName)
end
end
#OptimusComment: Moved the step definitions from smoke_steps.rb file
Given /^I am on the Auto Discovery page$/ do
visit AutodiscoveryPage
end
Given /^I launch the Auto Discovery$/ do
on AutodiscoveryPage do |page|
page.launch_autodiscovery
page.wait_until(450) do
page.scan_status_element.text.include?('All records processed')
end
end
end
When /^I commit the results$/ do
on AutodiscoveryPage do |page|
page.commit_results
page.close_scan
end
end
#Steps for Autodiscovery --> Automation page
Given /^I am on the Automation page$/ do
visit AutomationPage
end
And /^I select the "(.+)" button$/ do |button|
if button == 'close' || button == 'cancel_rename' || button == 'cancel' || button == 'delete'
on AutomationPage do |page|
page.automation_schema_element.when_present.set
page.next_element.when_present.click
page.click(button)
end
elsif button == 'edit' || button == 'close_scan' || button == 'disable_overrides'
on AutodiscoveryPage do |page|
page.click(button)
end
end
end
Then /^I should be redirected to the correct page for "(.+)"$/ do |button|
if button == 'close' || button == 'cancel_rename' || button == 'cancel' || button == 'delete'
on AutomationPage do |page|
page.verify_page(button)
end
elsif button == 'edit' || button == 'close_scan' || button == 'disable_overrides'
on AutodiscoveryPage do |page|
page.verify_page(button)
end
end
end
And /^I create a new automation schema "(.+)"$/ do |schema|
on AutomationPage do |page|
page.create_schema(schema)
end
end
And /^I create a new automation template "(.+)"$/ do |template|
on AutomationPage do |page|
page.create_template(template)
end
end
And /^I save it as a template$/ do
on AutomationPage do |page|
page.save_as_template_element.when_present.click
end
#Watir::Wait.until {
#<EMAIL>.frame(:id => 'myframe').text("Template saved to /usr/local/groundwork/core/monarch/automation/templates/schema-template-\#{template}\.xml").exists?
#}
end
And /^I create an automation schema "(.+)" using template "(.+)"$/ do |schema,template|
visit AutomationPage
on AutomationPage do |page|
page.create_schema_from_template(schema,template)
end
end
And /^I "(.+)" the "(.+)"$/ do |action,schema|
if action == 'delete'
@browser.frame(:id => 'myframe').radio(:value => schema+"_renamed").when_present.set
else
@browser.frame(:id => 'myframe').radio(:value => schema).when_present.set
end
on AutomationPage do |page|
page.next_element.when_present.click
page.perform(action,schema)
end
end
Then /^the schema "(.+)" should be successfully "(.+)"$/ do |schema,status|
if status == 'created'
@browser.frame(:id => 'myframe').text.include? ("Changes to \"#{schema}\" saved to database.")
elsif status == 'renamed'
@browser.frame(:id => 'myframe').text.include? (schema+"_renamed")
elsif status == 'deleted'
@browser.frame(:id => 'myframe').text.include? ("Removed:")
@browser.frame(:id => 'myframe').text.include? (" "+schema+" ")
end
end
And /^I create a new discovery defintion using "(.+)"$/ do |schema|
on AutodiscoveryPage do |page|
page.new_discovery_definition
page.discovery_definition_name = schema
page.discovery_definition_description= schema
@browser.frame(:id => "myframe").select(:name => "schema").select(schema)
@browser.frame(:id => "myframe").select(:name => "auto").select("Auto-Commit")
page.create_group_element.when_present.click
end
end
And /^I edit the different parameters for host "(.+)"$/ do |host|
on AutomationPage do |page|
page.edit_record_element.when_present.click
sleep(5)
#modifying the existing parameters for a host
page.edit_host(host)
end
end
Then /^the changes should be reflected on Status Viewer for host "(.+)"-"(.+)" and Host Configuration page$/ do |host,hostname|
host_name=hostname+"-renamed"
visit StatusviewerPage
sleep(15)
on StatusviewerPage do |page|
page.selecthost("Linux Servers",host_name)
end
#verify services and instances
#<EMAIL>.span(:text => 'http_alive_instance').exists?.should == true
#@browser.span(:text => 'http_alive_instance').when_present.click
@browser.span(:text => /local_load/).exists?.should == true
@browser.span(:text => /local_load/).when_present.click
#@browser.span(:text => /ssh_alive/).exists?.should == true
#@browser.span(:text => /ssh_alive/).when_present.click
@browser.span(:text => /tcp_ssh/).exists?.should == true
@browser.span(:text => /tcp_ssh/).when_present.click
on StatusviewerPage do |page|
page.search_for_host(host).should >= 1
end
@browser.td(:class => 'iceDatTblCol2').span(:text => /#{host_name}/).when_present.click
#verifying host alias name
@browser.span(:id => 'HVform:txthostAlias').text.include? (host_name+'-alias')
#verifying parent for the host
@browser.link(:id => 'HVform:linkParentPoup', :text => /Parents for this Host/).when_present.click
sleep(5)
@browser.link(:id => 'HVform:tblGroupPop:0:lnkParent').text.include? (' localhost')
@browser.input(:id => 'HVform:btnDependentParentPopClose').when_present.click
sleep(2)
#verifying hostgroup
@browser.link(:id => 'HVform:linkGroupPoup', :text => /Groups for this Hosts/).when_present.click
sleep(5)
@browser.span(:id => 'HVform:tblDependentParentPop:0:txtMember').text.include? (' Linux Servers')
@browser.input(:id => 'HVform:btnGroupPopClose').when_present.click
sleep(2)
visit HostconfigurationPage
on HostconfigurationPage do |page|
page.visit_host_configuration_new(host_name)
sleep(5)
end
#verifying updated address
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').text_field(:name => /address/).attribute_value("value") == "192.168.127.12"
#verifying contact group
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').select(:id => /contactgroup.members/).option(:text => 'nagiosadmin').exists?.should == true
#verifying host profile
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').button(:value => 'Host Profile').when_present.click
sleep(5)
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').select(:name => 'profile_host').option(:value => 'host-profile-ssh-unix').attribute_value("selected") == ""
#verifying service profile
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').button(:value => 'Service Profiles').when_present.click
sleep(5)
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').text.include? (' ssh-unix ')
end
And /^I check the Nmap TCP definition method$/ do
on AutodiscoveryPage do |page|
page.NmapTCP_element.when_present.check
end
end
And /^I remove filter "(.+?)"$/ do |filterName|
visit AutodiscoveryPage
on AutodiscoveryPage do |page|
page.delete_filter(filterName)
end
end
And /^I select the default schema$/ do
on AutomationPage do |page|
page.automation_schema_element.when_present.set
page.next_element.when_present.click
end
end
And /^I view the data source file$/ do
on AutomationPage do |page|
page.view_element.when_present.click
end
end
Then /^the data source file should not exist$/ do
@browser.window(:title => /Monarch Auto Config/).when_present.use
@browser.td(:class => 'error').text.include? (" Data source file does not exist. ")
@browser.window(:title => /Monarch Auto Config/).when_present.close
@browser.window(:title => 'automation').when_present.use
end
Then /^the entry for the host "(.+)" "(.+)" should exist in the data source file$/ do |address,hostname|
@browser.window(:title => /Monarch Auto Config/).when_present.use
@browser.td(:class => 'row_lt').text.include? (address)
@browser.td(:class => 'row_lt').text.include? (hostname)
@browser.window(:title => /Monarch Auto Config/).when_present.close
end
And /^I Enable Overrides and modify the different parameters$/ do
on AutodiscoveryPage do |page|
page.enable_overrides_element.when_present.click
page.override
end
end
Then /^changes should reflect on Status Viewer for host "(.+)" "(.+)" and Host Configuration page$/ do |address,host|
visit StatusviewerPage
sleep(15)
on StatusviewerPage do |page|
page.selecthost("Linux Servers",host)
end
#<EMAIL>.span(:text => 'http_alive').exists?.should == true
#<EMAIL>.span(:text => 'http_alive').when_present.click
@browser.span(:text => 'local_process_snmptt').exists?.should == true
@browser.span(:text => 'local_process_snmptt').when_present.click
@browser.span(:text => 'snmp_if_1').exists?.should == true
@browser.span(:text => 'snmp_if_1').when_present.click
@browser.span(:text => 'snmp_ifbandwidth_1').exists?.should == true
@browser.span(:text => 'snmp_ifbandwidth_1').when_present.click
@browser.span(:text => 'snmp_ifoperstatus_1').exists?.should == true
@browser.span(:text => 'snmp_ifoperstatus_1').when_present.click
#@browser.span(:text => 'ssh_alive').exists?.should == true
@browser.span(:text => 'udp_snmp').when_present.click
@browser.span(:text => 'udp_snmp').exists?.should == true
on StatusviewerPage do |page|
page.search_for_host(address).should >= 1
end
@browser.td(:class => 'iceDatTblCol2').span(:text => /#{host}/).when_present.click
#verifying parent for the host
@browser.link(:id => 'HVform:linkParentPoup', :text => /Parents for this Host/).when_present.click
sleep(5)
@browser.link(:id => 'HVform:tblGroupPop:0:lnkParent').text.include? (' localhost')
@browser.input(:id => 'HVform:btnDependentParentPopClose').when_present.click
sleep(2)
#verifying hostgroup
@browser.link(:id => 'HVform:linkGroupPoup', :text => /Groups for this Hosts/).when_present.click
sleep(5)
@browser.span(:id => 'HVform:tblDependentParentPop:0:txtMember').text.include? (' Linux Servers')
@browser.input(:id => 'HVform:btnGroupPopClose').when_present.click
sleep(2)
visit HostconfigurationPage
on HostconfigurationPage do |page|
page.visit_host_configuration_new(host)
sleep(5)
end
#verifying contact group
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').select(:id => /contactgroup.members/).option(:text => 'nagiosadmin').exists?.should == true
#verifying host profile
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').button(:value => 'Host Profile').when_present.click
sleep(5)
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').select(:name => 'profile_host').option(:value => 'host-profile-snmp-network').attribute_value("selected") == ""
#verifying service profile
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').button(:value => 'Service Profiles').when_present.click
sleep(5)
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').text.include? (' snmp-network ')
end
And /^"(.+)" the definition "(.+)"$/ do |action, definition|
if action == 'rename'
on AutodiscoveryPage do |page|
page.rename_element.when_present.click
page.definition_new_name_element.when_present.set definition+'_renamed'
page.rename_element.when_present.click
end
elsif action == 'edit'
@browser.frame(:id => 'myframe').radio(:value => definition).when_present.set
on AutodiscoveryPage do |page|
page.edit_discovery_definition_element.when_present.click
end
elsif action == 'delete'
if (@browser.frame(:id => 'myframe').button(:text => 'Go >>').exists?)
@browser.frame(:id => 'myframe').radio(:value => definition+'_renamed').when_present.set
on AutodiscoveryPage do |page|
page.edit_discovery_definition_element.when_present.click
page.delete_element.when_present.click
page.method_filter_element.when_present.set
page.method_filter_element.when_present.clear
page.confirm_delete_filter_element.when_present.click
end
else
on AutodiscoveryPage do |page|
page.delete_element.when_present.click
page.method_filter_element.when_present.check
page.method_filter_element.when_present.uncheck
page.confirm_delete_filter_element.when_present.click
end
end
end
end
Then /^the definition "(.+)" should be "(.+)"$/ do |definition,action|
if action == 'renamed'
@browser.frame(:id => 'myframe').td(:class => 'wizard_title_heading').text.include? (definition+'_renamed')
on AutodiscoveryPage do |page|
page.save_element.when_present.click
end
@browser.frame(:id => 'myframe').radio(:value => definition+'_renamed').attribute_value("selected") == ""
elsif action == 'deleted'
@browser.frame(:id => 'myframe').td(:text => definition+'_renamed').exists?.should == false
end
end
And /^I create a new auto discovery definition "(.+)"$/ do |defName|
on AutodiscoveryPage do |page|
page.new_discovery_definition
page.discovery_definition_name = defName
page.discovery_definition_description= defName
@browser.frame(:id => "myframe").select(:name => "schema").select("GroundWork-Discovery-Pro")
@browser.frame(:id => "myframe").select(:name => "auto").select("Auto")
@browser.frame(:id => "myframe").select(:name => "template").select("GroundWork-Default-Pro")
page.create_group
end
end
And /^I change the Nmap scan timeout mode to "(.+)"$/ do |timeout|
on AutodiscoveryPage do |page|
page.edit_discovery_definition_element.when_present.click
page.NmapTCP_element.when_present.check
page.SNMP_element.when_present.uncheck
page.edit_nmap_element.when_present.click
page.scan_timeout_element.select(timeout)
page.save_element.when_present.click
page.save_element.when_present.click
end
end
And /^I change the Nmap scan type mode to "(.+)"$/ do |scan_type|
on AutodiscoveryPage do |page|
page.edit_discovery_definition_element.when_present.click
page.NmapTCP_element.when_present.check
page.SNMP_element.when_present.uncheck
page.edit_nmap_element.when_present.click
if scan_type == 'TCP SYN SCAN'
page.tcp_syn_scan_element.when_present.set
elsif scan_type == 'TCP CONNECT SCAN'
page.tcp_con_scan_element.when_present.set
elsif scan_type == 'UDP SCAN'
page.udp_scan_element.when_present.set
end
page.save_element.when_present.click
page.save_element.when_present.click
end
end
And /^I launch Auto Discovery$/ do
on AutodiscoveryPage do |page|
page.launch_autodiscovery
end
end
Then /^the discovery should show results of SNMP only$/ do
#if (@browser.frame(:id => 'myframe').div(:id => 'method_status', :text => /SNMP/).exists?)
#@browser.frame(:id => 'myframe').div(:id => 'method_status', :text => /SNMP/).wait_while_present(150)
#end
on AutodiscoveryPage do |page|
page.method_status_snmp_element.wait_while_present(150)
page.wait_until(150) do
page.scan_status_element.text.include? "Discovery stage has completed"
end
end
#if (@browser.frame(:id => 'myframe').div(:id => 'method_status', :text => /SNMP/).exists?)
#@browser.frame(:id => 'myframe').div(:id => 'method_status', :text => /SNMP/).wait_while_present
#end
#@browser.frame(:id => 'myframe').div(:id => 'method_status', :text => /SNMP/).wait_while_present
column = @browser.frame(:id => 'myframe').table(:id => "reportTable").row.cells.length
puts column
row = @browser.frame(:id => 'myframe').table(:id => "reportTable").rows.length
puts row
for i in 4..row-1
for j in 3..column
status = @browser.frame(:id => 'myframe').table(:id => "reportTable").td(:class => 'discover_info' ,:text => /SNMP SCAN/).exists?
if status == true
puts status
else
puts status
raise
end
end
end
end
Then /^the discovery should show results of Nmap only$/ do
on AutodiscoveryPage do |page|
page.method_status_nmap_element.wait_while_present(300)
page.wait_until(300) do
page.scan_status_element.text.include? "Discovery stage has completed"
end
end
column = @browser.frame(:id => 'myframe').table(:id => "reportTable").row.cells.length
puts column
row = @browser.frame(:id => 'myframe').table(:id => "reportTable").rows.length
puts row
for i in 4..row-1
for j in 3..column
status = @browser.frame(:id => 'myframe').table(:id => "reportTable").td(:class => 'discover_info' ,:text => /SNMP SCAN/).exists?
if status == true
puts status
raise
else
puts status
end
end
end
end
And /^I Uncheck Nmap and check SNMP definition method$/ do
on AutodiscoveryPage do |page|
page.NmapTCP_element.when_present.uncheck
page.SNMP_element.when_present.check
page.save_element.when_present.click
end
end
And /^I edit default discovery defintion$/ do
on AutodiscoveryPage do |page|
page.default_definition_element.when_present.set
page.edit_discovery_definition_element.when_present.click
end
end
=begin
And /^I check Nmap and uncheck SNMP definition method$/ do
on AutodiscoveryPage do |page|
page.check_NmapTCP
page.uncheck_SNMP
page.save_element.when_present.click
end
end
And /^I check Nmap and check SNMP definition method$/ do
on AutodiscoveryPage do |page|
page.check_NmapTCP
page.check_SNMP
page.save_element.when_present.click
end
end
=end
And /^I "(.+)" Nmap and "(.+)" SNMP definition method$/ do |nmap,snmp|
if nmap == 'check' || snmp == 'uncheck'
on AutodiscoveryPage do |page|
page.NmapTCP_element.when_present.check
page.SNMP_element.when_present.uncheck
page.save_element.when_present.click
end
elsif nmap == 'uncheck' || snmp == 'check'
on AutodiscoveryPage do |page|
page.NmapTCP_element.when_present.uncheck
page.SNMP_element.when_present.check
page.save_element.when_present.click
end
else
on AutodiscoveryPage do |page|
page.NmapTCP_element.when_present.check
page.SNMP_element.when_present.check
page.save_element.when_present.click
end
end
end
And /^I edit the default discovery definition$/ do
on AutodiscoveryPage do |page|
page.select_default_definition
page.edit_discovery_definition_element.when_present.click
end
end
And /^I "(.+)" the Traceroute Option$/ do |status|
on AutodiscoveryPage do |page|
if status == 'disable'
page.uncheck_enable_traceroute
sleep(5)
elsif status == 'enable'
page.check_enable_traceroute
end
end
end
Then /^the max hops and timeout fields should be "(.+)"$/ do |status|
on AutodiscoveryPage do |page|
if status == 'disabled'
page.max_hops_element.disabled?.should == true
page.timeout_element.disabled?.should == true
elsif status == 'enabled'
page.max_hops_element.enabled?
page.timeout_element.enabled?
end
end
end
And /^I input "(.+)" in max hops and timeouts fields$/ do |values|
on AutodiscoveryPage do |page|
page.check_enable_traceroute
page.max_hops_element.set values
page.timeout_element.set values
end
end
Then /^there should be a validation message$/ do
@browser.frame(:id => 'myframe').td(:class => 'row1', :text => /The traceroute max hops value must be a positive integer/).exists?.should == true
@browser.frame(:id => 'myframe').td(:class => 'row1', :text => /The traceroute timeout value must be an integer greater than 1/).exists?.should == true
end
And /^I delete "(.+)"-"(.+)" host from the GW application$/ do |range,hostName|
visit HostsConfigurationPage
on HostsConfigurationPage do |page|
page.remove_host(range, hostName)
end
end
<file_sep>class DashPage
include PageObject
link :auto_disc, :text => /Auto Discovery/
direct_url BASE_URL + "/portal/classic/"
end
<file_sep>class DashboardPage
include PageObject
direct_url BASE_URL + "dashboard"
@@subtab_text = { "Summary" => "Getting started", "Trouble View" => "Received By GW", "Monitoring" => "Service Check Execution Time", "System View" => "Status Information Details", "Enterprise View" => "Monitoring Statistics : Host Groups", "Webmetrics" => "GroundWork has partnered with Neustar Webmetrics for web performance management monitoring." }
link :sign_out, :text => "Sign out"
link :show_install_info, :text => "Show Install Info"
def logout
#<EMAIL>(:class => "UITab portlet-menu-item").when_present.click
@browser.li(:class => "UITab portlet-menu-item").fire_event 'mouseover'
self.sign_out
end
def correct_login?(user)
if user == "admin"
user = "Administrator"
end
@browser.li(:class => "Name").text.should == "GroundWork #{user.capitalize}"
end
def check_in_dashboard
self.wait_until(10) do
@browser.text.include? "Getting started"
end
end
def find_correct_potlets potlet
self.wait_until(10) do
@browser.text.include? potlet
end
end
def go_to_subtab(subtab)
@browser.link(:text => /Dashboards/).fire_event 'mouseover'
@browser.link(:text => /#{subtab}/).when_present.click
end
def check_subtab(subtab)
self.wait_until(10) do
@browser.text.include? subtab
if subtab == "Webmetrics"
@browser.frame.div.text.include? @@subtab_text[subtab]
else
@browser.text.include? @@subtab_text[subtab]
end
end
end
def verify_user(username)
if username == "admin"
@browser.a(:text => /Configuration/).when_present.click
@browser.frame(:id => /myframe/).frame(:name => /monarch_left/).td(:class => /row1_menuitem/).a(:text => /Host wizard/).when_present.click
elsif username == "operator"
@browser.a(:text => /Event Console/).exists?.should==true
@browser.a(:text => /Event Console/).when_present.click
@browser.a(:text => /Status/).exists?.should==true
@browser.a(:text => /Status/).when_present.click
elsif username == "user"
@browser.a(:text => /Event Console/).exists?.should==false
@browser.a(:text => /Status/).exists?.should==true
@browser.a(:text => /Status/).when_present.click
elsif username == "restricted_user"
@browser.a(:text => /Event Console/).exists?.should==false
@browser.a(:text => /Status/).exists?.should==true
@browser.a(:text => /Status/).when_present.click
end
end
end
<file_sep>curl -L https://github.com/downloads/webmetrics/browsermob-proxy/browsermob-proxy-2.0-beta-6-bin.zip > browsermob-proxy.zip
unzip -d lib/ browsermob-proxy.zip
chmod +x lib/browsermob-proxy-2.0-beta-6/bin/browsermob-proxy
rm browsermob-proxy.zip
<file_sep>class LicensePage
include PageObject
direct_url BASE_URL + "groundwork-administration/licenseview"
text_field :license, :name => /licform:keyTxt/
button :applylicense, :value => /Validate License Key/
text_field :master_password, :id => /masterkeyCredentials/
text_field :ws_password, :id => /apiCredentials/
text_field :remote_password, :id => /remoteapiCredentials/
text_field :proxy_password, :id => /proxyCredentials/
text_field :encryption_tool, :id => /toolCredentials/
def timestamp(account_update)
if account_update == 'Update API Account'
@last_updated_timestamp = @browser.span(:id => /lastUpdateAPICredentials/).text.to_s
elsif account_update == 'Update Master Password'
@last_updated_timestamp = @browser.span(:id => /lastUpdateMainCredentials/).text.to_s
elsif account_update == 'Update Proxy Account'
@last_updated_timestamp = @browser.span(:id => /lastUpdateProxyCredentials/).text.to_s
end
return @last_updated_timestamp
end
def set_license lic
self.license = lic
self.apply_license
end
def set_encryption(password)
self.encryption_tool = password
end
def set_password (account_name,password)
if account_name == 'Webervices API Account Info'
self.ws_password = <PASSWORD>
elsif account_name == 'Master Account Info'
self.master_password = <PASSWORD>
elsif account_name == 'Remote API Account Info'
self.remote_password = <PASSWORD>
elsif account_name == 'Proxy Account Info'
self.proxy_password = <PASSWORD>
end
end
def set_nullpassword (account_name)
if account_name == 'Webervices API Account Info'
self.ws_password_element.clear
elsif account_name == 'Master Account Info'
self.master_password_element.clear
elsif account_name == 'Remote API Account Info'
self.remote_password_element.clear
elsif account_name == 'Proxy Account Info'
self.proxy_password_element.clear
end
end
def confirm_message(account_name, message_span)
if account_name == 'Webervices API Account Info'
message_span.text.include?('Confirmation : API account updated successfully!').should == true
elsif account_name == 'Master Account Info'
message_table = @browser.table(:id => /sysacctmgmtform:messagesOutput/)
message_table.tr(:index => 0).text.include?('API account testing(SOAP): SUCCESS! ==> 200 OK').should == true
proxy = message_table.tr(:index => 1).text
puts proxy
message_table.tr(:index => 1, :text => /#{proxy}/).exists?.should == true
message_table.tr(:index => 2).text.include?('Confirmation : API account updated successfully!').should == true
message_table.tr(:index => 3).text.include?('Confirmation : Proxy account updated successfully!').should == true
message_table.tr(:index => 4).text.include?('Confirmation : Master password updated successfully!').should == true
elsif account_name == 'Remote API Account Info'
message_span.text.include?('Confirmation : Remote API account updated successfully!').should == true
end
end
def error_message(account_name)
error_span = @browser.span(:class => /error-message/).when_present
puts error_span.text
if account_name == 'Master Account Info'
@browser.span(:id => /sysacctmgmtform/, :class => /iceMsgError/, :text => /MasterPassword: Validation Error/ ).exists?
elsif account_name == 'Proxy Account Info'
error_span.text.include?('Proxy account testing(Cacti) : FAILED! ==> 401 Unauthorized').should == true
elsif account_name == 'Webervices API Account Info'
error_span.text.include?('API account testing(SOAP) : FAILED! ==> 401 Unauthorized').should == true
end
end
end
<file_sep>class LoginPage
include PageObject
direct_url BASE_URL1
text_field :username, :class => 'fk-input login-form-input user-email'
text_field :password, :class => 'fk-input login-form-input user-pwd'
button :login_user, :class => 'submit-btn login-btn btn'
def login(username, password)
<EMAIL>.text_field(:class,'fk-input login-form-input user-email').when_present.set username
#<EMAIL>.input(:class,'fk-input login-form-input user-pwd').when_present.set password
<EMAIL>.input(:class,'submit-btn login-btn btn').when_present.click
self.username = username
self.password = <PASSWORD>
self.login_user
end
end
<file_sep>class NetHubPage
include PageObject
direct_url BASE_URL + "groundwork-administration/nethubview"
in_frame(:id => 'myframe') do |frame|
link :add_opendaylight, :class => /button-l/, :href => /opendaylight/, :frame => frame
text_field :display_name, :id => /common.displayName/, :frame => frame
text_field :groundwork_server, :id => /groundwork.server.name/, :frame => frame
text_field :odl_server, :id => /virtualEnv.serverName/, :frame => frame
text_field :username, :id => /virtualEnv.username/, :frame => frame
text_field :password, :name => /connection.password/, :frame => frame
text_field :wsuser_name, :id => /groundwork.webservices.username/, :frame => frame
text_field :wsuser_pwd, :name => /gwos.wsPassword/, :frame => frame
text_field :interval, :name => /common.uiCheckIntervalMinutes/, :frame => frame
text_field :ns_warning_threshold, :id => /vm_warningThreshold_1/, :frame => frame
text_field :ns_critical_threshold, :id => /vm_criticalThreshold_1/, :frame => frame
button :save, :value => /Save/, :frame => frame
button :test_connection, :value => /Test Connection/, :frame => frame
button :home, :value => /Home/, :frame => frame
button :startconnection, :id => /startStopServerbtn/, :frame => frame
button :modify, :value => /Modify/, :frame => frame
button :next, :value => /Next/, :frame => frame
button :delete, :value => /Delete/, :frame => frame
button :next, :value => /Next/, :frame => frame
div :green, :class => /greencircle/, :frame => frame
p :nethub, :text => /Net Hub Configuration wizard for Open Daylight /, :frame => frame
td :testconnection, :text => "test", :frame => frame
end
end
<file_sep>class CentloginPage
include PageObject
direct_url BASE_URL2
text_field :user, :name =>"josso_username"
text_field :password, :name =>"<PASSWORD>"
button :logging, :value =>"Login"
def login(user, password)
self.user = user
self.password = <PASSWORD>
self.logging
end
end
<file_sep>class UserManagementPage
include PageObject
link :membership_management, :class => /MembershipButton/
link :group_management, :class => /GroupButton/
def access_restriction(user,permission,module1,module2)
if user == 'admin'
table_row = @browser.table(:class => /UIGrid/).td(:text => /gw-monitoring-administrator/).parent
table_row.img(:class => /EditMembershipIcon/).when_present.click
elsif user == 'root'
table_row = @browser.table(:class => /UIGrid/).td(:text => /gw-portal-administrator/).parent
table_row.img(:class => /EditMembershipIcon/).when_present.click
elsif user == 'user'
@browser.link(:text => '2').when_present.when_present.click
sleep(5)
table_row = @browser.table(:class => /UIGrid/).td(:text => /gw-portal-user/).when_present.parent
sleep(5)
table_row.img(:class => /EditMembershipIcon/).when_present.click
elsif user == 'operator'
table_row = @browser.table(:class => /UIGrid/).td(:text => /gw-monitoring-operator/).parent
table_row.img(:class => /EditMembershipIcon/).when_present.click
else
puts 'User not valid'
end
sleep(5)
if permission == 'deny'
@browser.checkbox(:name => /#{module1}/).clear
@browser.checkbox(:name => /#{module2}/).clear
elsif permission == 'grant'
@browser.checkbox(:name => /#{module1}/).set
@browser.checkbox(:name => /#{module2}/).set
else
puts 'Wrong permission defined'
end
sleep(3)
@browser.link(:text => /Save/).when_present.click
@browser.span(:text => /saved successfully/).wait_until_present
@browser.link(:text => /OK/).when_present.click
sleep(4)
end
def access_error(gw_module)
if gw_module == 'Cacti'
gw_module_actual = 'Advanced'
elsif gw_module == 'Monarch'
gw_module_actual = 'Configuration'
elsif gw_module == 'Nagvis'
gw_module_actual = 'Views'
elsif gw_module == 'BIRT-Reports'
gw_module_actual = 'Reports'
end
@browser.link(:text => /#{gw_module_actual}/).when_present.click
sleep(8)
if gw_module == 'BIRT-Reports'
@browser.link(:id => /reportTreePortlet_frmTree:reportTreePortlet_reportTree:0/).when_present.click
@browser.span(:text => 'host availability').when_present.click
sleep(5)
@browser.frame(:id => "birtViewer").body.text.include?("Application BIRT-Reports not authorized for this membership. Please contact GroundWork Administrator").should == true
else
#<EMAIL>(:id => "myframe").head(:title => /Authorization Error/).should == true
@browser.frame(:id => "myframe").body.text.include?("Application #{gw_module} not authorized for this membership. Please contact GroundWork Administrator").should == true
end
end
def access_granted(gw_module)
if gw_module == 'Cacti'
gw_module_actual = 'Advanced'
title = 'Console'
elsif gw_module == 'Monarch'
gw_module_actual = 'Configuration'
title = 'Monarch'
elsif gw_module == 'Nagvis'
gw_module_actual = 'Views'
title = 'NagVis 1.7.9'
elsif gw_module == 'BIRT-Reports'
gw_module_actual = 'Reports'
end
if gw_module == 'CloudHub'
@browser.goto BASE_URL + "groundwork-administration/cloudhubview"
else
@browser.link(:text => /#{gw_module_actual}/).when_present.click
end
sleep(8)
if gw_module == 'BIRT-Reports'
@browser.link(:id => /reportTreePortlet_frmTree:reportTreePortlet_reportTree:0/).when_present.click
@browser.span(:text => 'host availability').when_present.click
sleep(5)
@browser.frame(:id => 'birtViewer').div(:id => 'parameterDialogokButton').button(:title => 'OK').when_present.click
elsif gw_module == 'Monarch'
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Host wizard/).when_present.click
elsif gw_module == 'Cacti'
@browser.frame(:id => /myframe/).link(:text => /New Graphs/).when_present.click
elsif gw_module == 'Nagvis'
@browser.frame(:id => /myframe/).span(:text => /Options/, :id => /wui-ddheader/).when_present.click
elsif gw_module == 'CloudHub'
@browser.frame(:id => "myframe").link(:href => /rhev/, :class => /button-l/).when_present.click
end
end
def add_group(add,user,group)
@browser.link(:text => group).click
sleep(3)
if add == 'add'
@browser.text_field(:id => /username/).set user
if user == 'user'
@browser.select_list(:class => /selectbox/).select "gw-portal-user"
elsif user == 'operator'
@browser.select_list(:class => /selectbox/).select "gw-monitoring-operator"
end
sleep(2)
@browser.link(:text => /Save/).click
sleep(3)
elsif add == 'remove'
table_row = @browser.table(:class => /UIGrid/).td(:text => user).parent
table_row.img(:class => /Delete/).when_present.click
sleep(2)
@browser.alert.ok
sleep(5)
end
end
end
<file_sep>require 'json'
class NagvisMapInfo
attr_accessor :state, :output, :children, :group
def initialize(group)
file = open('./lib/nagvis.json')
json = file.read
parsed = JSON.parse(json)
if group != "Hosts_UP"
overview = parsed["overview"]
@state = overview[group]["state"]
@output = overview[group]["output"]
@children = overview[group]["children"]
end
@group = parsed[group]
end
end
<file_sep>Given(/^I am on the Profiles Configuration page$/) do
visit ProfilesConfigurationPage
end
#################################################################################################
######################### SERVICE ########################################################
And /^I create a new service "(.+)"$/ do |service_name|
on ServiceConfigurationPage do |page|
page.create_service(service_name)
end
end
And /^I apply "(.+)" to a host$/ do |service|
visit HostconfigurationPage
on HostconfigurationPage do |page|
page.visit_host_configuration
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').button(:name => 'services').when_present.click
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').select(:name => 'add_service').select(service)
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').button(:name => 'submit').when_present.click
end
visit ServiceConfigurationPage
on ServiceConfigurationPage do |page|
page.open_services
page.check_service(service)
end
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.link(:text => /Apply Hosts/).when_present.click
framemain.checkbox(:name => 'apply_check').when_present.set
framemain.radio(:value => 'merge').when_present.set
framemain.button(:value => 'Apply').when_present.click
end
And /^I apply the copy of "(.+)" to a host$/ do |service_name|
visit HostconfigurationPage
service=service_name+"-copy"
on HostconfigurationPage do |page|
page.visit_host_configuration
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').button(:name => 'services').when_present.click
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').select(:name => 'add_service').select(service)
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').button(:name => 'submit').when_present.click
end
visit ServiceConfigurationPage
on ServiceConfigurationPage do |page|
page.open_services
page.check_service(service)
end
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.link(:text => /Apply Hosts/).when_present.click
framemain.checkbox(:name => 'apply_check').when_present.set
framemain.radio(:value => 'merge').when_present.set
framemain.button(:value => 'Apply').when_present.click
end
Then /^the changes made for "(.+)" should reflect in Status Viewer$/ do |service_name|
sleep(20)
visit StatusviewerPage
on StatusviewerPage do |page|
page.selecthost('Linux Servers', 'localhost')
@browser.span(:text => service_name).exists?.should == true
@browser.span(:text => service_name).when_present.click
sleep(3)
end
end
Then /^the changes made for copy of "(.+)" should reflect in Status Viewer$/ do |service|
sleep(20)
visit StatusviewerPage
service_name=service+"-copy"
on StatusviewerPage do |page|
page.selecthost('Linux Servers', 'localhost')
@browser.span(:text => service_name).exists?.should == true
@browser.span(:text => service_name).when_present.click
sleep(3)
end
end
And /^I delete the service "(.+)"$/ do |service_name|
visit ServiceConfigurationPage
on ServiceConfigurationPage do |page|
page.open_services
page.check_service(service_name)
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').button(:value => /Delete/).when_present.click
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').button(:value => /Yes/).when_present.click
end
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').text.include? ("Removed:")
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').text.include? (" "+service_name+" ")
end
And /^I delete the "(.+)" service "(.+)"$/ do |type,service|
visit ServiceConfigurationPage
if type == "copied"
service_name=service+"-copy"
elsif type == "renamed"
service_name=service+"-copy_renamed"
end
on ServiceConfigurationPage do |page|
page.open_services
page.check_service(service_name)
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').button(:value => /Delete/).when_present.click
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').button(:value => /Yes/).when_present.click
end
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').text.include? ("Removed:")
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').text.include? (" "+service_name+" ")
end
And /^I search for a service with keyword "(.+)"$/ do |keyword|
on ServiceConfigurationPage do |page|
page.search_service(keyword)
end
sleep(5)
end
Then /^all the services having the "(.+)" in their name should be displayed in search results$/ do |keyword|
row = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').div(:id => 'resultdiv').table(:align => 'left').rows.length
puts row
for i in 0..row-1
status = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').div(:id => 'resultdiv').table(:align => 'left').td(:class => 'row_lt' ,:text => /#{keyword}/).exists?
if status == true
puts status
else
puts status
puts i
raise
end
end
end
And /^I clone the service "(.+)"$/ do |service_name|
@browser.frame(:id => 'myframe').frame(:name => 'monarch_left').link(:text => /Clone service/).when_present.click
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.select(:name => 'clone_service').select(service_name)
framemain.button(:name => 'next').when_present.click
framemain.text_field(:name => 'name').attribute_value("value") == service_name+"-copy"
framemain.button(:name => 'next').when_present.click
end
Then /^a copy of the service "(.+)" should be created$/ do |service_name|
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').td(:class => 'data0').text.include? (service_name+"-copy")
end
And /^I create a service template "(.+)"$/ do |template|
on ServiceConfigurationPage do |page|
page.create_template(template)
end
end
And /^I apply the template "(.+)" to the copy of "(.+)"$/ do |template, service_name|
visit ServiceConfigurationPage
service=service_name+"-copy"
on ServiceConfigurationPage do |page|
page.open_services
page.check_service(service)
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => 'new_name').set service+"_renamed"
framemain.button(:value => /Rename/).when_present.click
framemain.select(:name => /template/).select(template)
framemain.button(:value => /Save/).when_present.click
end
end
Then /^the template "(.+)" should be applied successfully for renamed copy of "(.+)"$/ do |template, service_name|
visit ServiceConfigurationPage
service=service_name+"-copy_renamed"
on ServiceConfigurationPage do |page|
page.open_services
page.check_service(service)
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').select(:name => /template/).option(:value => template).attribute_value("selected") == ""
end
end
And /^I "(.+)" the service template "(.+)"$/ do |action, template|
visit ServiceConfigurationPage
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
if action == 'modify'
frameleft.link(:text => /Service templates/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{template}/).when_present.click
framemain.checkbox(:name => 'check_freshness_override').when_present.clear
framemain.checkbox(:name => 'check_freshness').when_present.set
framemain.checkbox(:name => 'notification_interval_override').when_present.clear
framemain.text_field(:name => 'notification_interval').when_present.set '30'
framemain.button(:value => /Save/).when_present.click
elsif action == 'rename'
frameleft.link(:text => /Service templates/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{template}/).when_present.click
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => 'new_name').set template+"-renamed"
framemain.button(:value => /Rename/).when_present.click
elsif action == 'delete'
frameleft.link(:text => /Service templates/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{template}/).when_present.click
framemain.button(:value => /Delete/).when_present.click
framemain.button(:value => /Yes/).when_present.click
end
end
Then /^template "(.+)" should be "(.+)" successfully$/ do |template, action|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
if action == 'modified'
framemain.text.include? ('Saved:')
elsif action == 'renamed'
framemain.td(:class => 'data0').text.include? ('Renamed:')
framemain.td(:class => 'data0').text.include? (template+"-renamed")
elsif action == 'deleted'
framemain.td(:class => 'data0').text.include? ('Removed:')
framemain.td(:class => 'data0').text.include? (template+"-renamed")
end
end
And /^I create a service dependency "(.+)"$/ do |dependency|
on ServiceConfigurationPage do |page|
page.create_dependency(dependency)
end
end
And /^I apply the dependency "(.+)" to service "(.+)"$/ do |dependency, service|
on ServiceConfigurationPage do |page|
page.open_services
page.check_service(service)
end
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
#framemain.link(:text => /Service Dependencies/).when_present.click
#framemain.select(:name => /dep_template/).select(dependency)
#framemain.select(:name => /depend_on_host/).select('same host')
#framemain.button(:value => /Add Dependency/).when_present.click
framemain.link(:text => /Apply Hosts/).when_present.click
framemain.checkbox(:name => 'apply_dependencies').when_present.set
framemain.radio(:value => 'merge').when_present.set
framemain.button(:value => 'Apply').when_present.click
framemain.td(:class => 'data0').text.include? ('Changes applied to 1 services. ')
end
And /^I "(.+)" the service dependency "(.+)"$/ do |action, dependency|
visit ServiceConfigurationPage
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Service dependencies/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{dependency}/).when_present.click
if action == 'modify'
framemain.select(:name => 'service_name').select('local_users')
framemain.button(:value => /Save/).when_present.click
elsif action == 'rename'
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => 'new_name').set dependency+"-renamed"
framemain.button(:value => /Rename/).when_present.click
elsif action == 'delete'
framemain.button(:value => /Delete/).when_present.click
framemain.button(:value => /Yes/).when_present.click
frameleft.link(:text => /Service dependencies/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{dependency}/).when_present.click
framemain.button(:value => /Delete/).when_present.click
framemain.button(:value => /Yes/).when_present.click
elsif action == 'copy'
frameleft.link(:text => /Copy/).when_present.click
frameleft.link(:href => /obj=service_dependency_templates&task=copy/, :text => /#{dependency}/).when_present.click
framemain.text_field(:name => 'name').set dependency+"-copy"
framemain.button(:value => /Add/).when_present.click
end
end
And /^delete the assigned service dependency "(.+)"$/ do |dependency|
visit ServiceConfigurationPage
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Service dependencies/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{dependency}/).when_present.click
framemain.button(:value => /Delete/).when_present.click
end
Then /^the dependency "(.+)" should be "(.+)" successfully$/ do |dependency, action|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
if action == 'applied'
framemain.td(:class => 'data0').text.include? (dependency)
elsif action == 'created'
framemain.td(:class => 'data0').text.include? ("Service dependency template \"#{dependency}\" has been saved.")
elsif action == 'modified'
framemain.td(:class => 'data0').text.include? ("Changes to service dependency template \"#{dependency}\" have been saved.")
elsif action == 'renamed'
framemain.td(:class => 'data0').text.include? ('Renamed:')
framemain.td(:class => 'data0').text.include? (dependency+"-renamed")
elsif action == 'deleted'
framemain.td(:class => 'data0').text.include? ('Removed:')
framemain.td(:class => 'data0').text.include? (" "+dependency+"-renamed ")
elsif action == 'copied'
framemain.td(:class => 'data0').text.include? ("Service dependency template \"#{dependency}-copy\" has been saved.")
end
end
And /^remove dependency from "(.+)"$/ do |service|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
on ServiceConfigurationPage do |page|
page.open_services
page.check_service(service)
end
framemain.link(:text => /Service Dependencies/).when_present.click
framemain.link(:text => /remove service dependency assignment/).when_present.click
end
Then /^"(.+)" should be removed successfully$/ do |dependency|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.td(:class => 'data2', :text => dependency).exists?.should == false
end
And /^I apply dependency "(.+)" to host localhost for service "(.+)"$/ do |dependency, service|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Hosts/).when_present.click
frameleft.link(:text => /Linux Servers /).when_present.click
frameleft.link(:text => /localhost /).when_present.click
frameleft.link(:text => /#{service}/).when_present.click
framemain.button(:value => /Service Dependencies/).when_present.click
framemain.select(:name => /dep_template/).select(dependency)
framemain.select(:name => /depend_on_host/).select('localhost')
framemain.button(:value => /Add Dependency/).when_present.click
end
And /^remove dependency from localhost for service "(.+)"$/ do |service|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Hosts/).when_present.click
frameleft.link(:text => /Linux Servers /).when_present.click
frameleft.link(:text => /localhost/).when_present.click
frameleft.link(:text => /#{service}/).when_present.click
framemain.button(:value => /Service Dependencies/).when_present.click
framemain.link(:text => /remove service dependency assignment/).when_present.click
end
Then /^there should be a validation message due to existing dependency$/ do
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').td(:id => 'errors').text.include? (' Please correct the following:')
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').td(:id => 'errors').text.include? (' Cannot delete until all dependencies are removed/reassigned. ')
end
And /^I create a service extended info template "(.+)"$/ do |template|
on ServiceConfigurationPage do |page|
page.create_extended_template(template)
end
end
Then /^the extended info template "(.+)" should be "(.+)" successfully$/ do |template, action|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
if action == 'created'
framemain.td(:class => 'data0').text.include? ("Extended service info template \"#{template}\" has been saved.")
elsif action == 'applied'
visit HostconfigurationPage
frameleft.link(:text => /Hosts/).when_present.click
frameleft.link(:text => /Linux Servers /).when_present.click
frameleft.link(:text => /localhost/).when_present.click
frameleft.link(:text => /local_cpu_java/).when_present.click
framemain.select(:name => 'ext_info').option(:value => template).attribute_value("selected") == ""
elsif action == 'modified'
framemain.td(:class => 'data0').text.include? ("Changes to extended service info template \"#{template}\" have been saved.")
visit ServiceConfigurationPage
frameleft.link(:text => /Service extended info/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{template}/).when_present.click
framemain.select(:name => 'icon_image').option(:value => 'aix.gif').attribute_value("selected") == ""
elsif action == 'renamed'
framemain.td(:class => 'data0').text.include? ('Renamed:')
framemain.td(:class => 'data0').text.include? (" "+template+"-renamed ")
elsif action == 'deleted'
framemain.td(:class => 'data0').text.include? ('Removed:')
elsif action == 'copied'
framemain.td(:class => 'data0').text.include? ("Extended service info template \"#{template}\"-copied has been saved.")
end
end
And /^I apply the extended info template "(.+)" to service "(.+)"$/ do |template, service|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
on ServiceConfigurationPage do |page|
page.open_services
page.check_service(service)
end
framemain.select(:name => 'ext_info').select(template)
framemain.button(:value => /Save/).when_present.click
framemain.td(:class => 'data0').text.include? ('Saved:')
framemain.td(:class => 'data0').text.include? (service)
framemain.link(:text => /Apply Hosts/).when_present.click
framemain.checkbox(:name => 'apply_extinfo_service').when_present.set
framemain.radio(:value => 'merge').when_present.set
framemain.button(:value => 'Apply').when_present.click
framemain.td(:class => 'data0').text.include? ('Changes applied to 1 services. ')
end
And /^I "(.+)" the service extended info template "(.+)"$/ do |action, template|
visit ServiceConfigurationPage
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
if action == 'modify'
frameleft.link(:text => /Service extended info/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{template}/).when_present.click
framemain.select(:name => 'icon_image').select("aix.gif")
framemain.text_field(:name => 'icon_image_alt').clear
framemain.text_field(:name => 'icon_image_alt').set 'aix.gif'
framemain.button(:value => /Save/).when_present.click
elsif action == 'rename'
frameleft.link(:text => /Service extended info/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{template}/).when_present.click
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => 'new_name').set template+"-renamed"
framemain.button(:value => /Rename/).when_present.click
elsif action == 'copy'
frameleft.link(:text => /Service extended info/).when_present.click
frameleft.link(:text => /Copy/).when_present.click
frameleft.link(:text => /#{template}/).when_present.click
framemain.text_field(:name => 'name').set template+"-copy"
framemain.button(:value => 'Add').when_present.click
elsif action == 'delete'
template_renamed=template+"-renamed"
frameleft.link(:text => /Service extended info/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{template_renamed}/).when_present.click
framemain.button(:value => /Delete/).when_present.click
framemain.button(:value => /Yes/).when_present.click
visit ServiceConfigurationPage
template_copied=template+"-copy"
frameleft.link(:text => /Service extended info/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{template_copied}/).when_present.click
framemain.button(:value => /Delete/).when_present.click
framemain.button(:value => /Yes/).when_present.click
end
end
And /^I remove the service extended info template from service "(.+)"$/ do |service|
on ServiceConfigurationPage do |page|
page.open_services
page.check_service(service)
end
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.select(:name => 'ext_info').select("")
framemain.button(:value => /Save/).when_present.click
framemain.link(:text => /Apply Hosts/).when_present.click
framemain.checkbox(:name => 'apply_extinfo_service').when_present.set
framemain.radio(:value => 'merge').when_present.set
framemain.button(:value => 'Apply').when_present.click
framemain.td(:class => 'data0').text.include? ('Changes applied to 1 services. ')
end
Then /^the info template "(.+)" should be removed successfully$/ do |template|
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').link(:text => /Service Detail/).when_present.click
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').select(:name => 'ext_info').option(:value => "").attribute_value("selected") == ""
end
And /^I "(.+)" the service group "(.+)"$/ do |action, group|
visit ServiceConfigurationPage
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
frameleft.link(:text => /Service groups/).when_present.click
frameleft.div(:id => /service_groups/).link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{group}/).when_present.click
if action == 'modify'
framemain.select(:name => 'host').select('localhost')
sleep(5)
framemain.select(:name => 'services').select('local_users')
framemain.button(:name => 'add_services').when_present.click
framemain.button(:value => /Save/).when_present.click
elsif action == 'rename'
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => 'new_name').set group+"-renamed"
framemain.button(:value => /Rename/).when_present.click
elsif action == 'delete'
visit ServiceConfigurationPage
frameleft.link(:text => /Service groups/).when_present.click
frameleft.div(:id => /service_groups/).link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{group}/).when_present.click
framemain.button(:value => /Delete/).when_present.click
framemain.button(:value => /Yes/).when_present.click
end
end
Then /^"(.+)" should be "(.+)" successfully$/ do |group, action|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
if action == 'modified'
framemain.td(:class => 'data0').text.include? (" Changes to \"#{group}\" accepted. ")
elsif action == 'renamed'
framemain.td(:class => 'data0').text.include? ('Renamed:')
framemain.td(:class => 'data0').text.include? (" "+group+"-renamed ")
elsif action == 'deleted'
framemain.td(:class => 'data0').text.include? ('Removed:')
framemain.td(:class => 'data0').text.include? (/#{group}/)
end
end
Given /^I am on the Escalation page$/ do
visit EscalationPage
end
And /^I create a new service escalation "(.+)"$/ do |escalation|
on EscalationPage do |page|
page.create_escaltion(escalation)
end
end
Then /^the escalation "(.+)" should be created successfully$/ do |escalation|
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').text.include? ("Service escalation \"#{escalation}\" has been saved.")
end
And /^I create a service escalation tree "(.+)" using "(.+)"$/ do |escalation_tree, escaltion|
visit EscalationPage
on EscalationPage do |page|
page.create_escalation_tree(escalation_tree,escaltion)
end
end
Then /^the escalation tree "(.+)" should be created successfully$/ do |escalation_tree|
visit EscalationPage
on EscalationPage do |page|
page.verify_tree(escalation_tree)
end
end
And /^I assign the service escalation tree "(.+)" to service "(.+)"$/ do |tree,service|
on ServiceConfigurationPage do |page|
page.open_services
page.check_service(service)
end
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.select(:name => 'escalation').select(tree)
framemain.link(:text => 'Apply Hosts').when_present.click
framemain.checkbox(:name => 'apply_escalation_service').when_present.set
framemain.radio(:value => 'merge').when_present.set
framemain.button(:value => 'Apply').when_present.click
framemain.td(:class => 'data0').text.include? ('Changes applied to 1 services. ')
end
Then /^the escalation tree "(.+)" should be applied successfully for "(.+)"$/ do |tree,service|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
visit HostconfigurationPage
frameleft.link(:text => /Hosts/).when_present.click
frameleft.link(:text => /Linux Servers /).when_present.click
frameleft.link(:text => /localhost/).when_present.click
frameleft.link(:text => /#{service}/).when_present.click
framemain.select(:name => 'escalation').option(:value => tree).attribute_value("selected") == ""
end
And /^I assign the escalation tree "(.+)"$/ do |tree|
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').select(:name => 'escalation').select(tree)
end
And /^tree "(.+)" should be assigned to service group "(.+)"$/ do |tree,group|
visit ServiceConfigurationPage
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
on ServiceConfigurationPage do |page|
page.open_service_group(group)
end
framemain.select(:name => 'escalation').option(:value => tree).attribute_value("selected") == ""
end
And /^I assign service group "(.+)"$/ do |group|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.button(:name => 'assign_service_groups').when_present.click
framemain.select(:name => 'servicegroups_nonmembers').select(group)
framemain.button(:value => /<< Add/).when_present.click
framemain.button(:value => 'Save').when_present.click
end
Then /^there should be an error message for duplicate service group "(.+)"$/ do |group|
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
framemain.td(:class => 'error').text.include? (" Duplicate: Service group \"#{group}\" already exists. ")
end
Then /^there should be a validation message for illegal characters$/ do
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').div(:id => 'messageBox').text.include? ('There is a problem with your form.')
@browser.frame(:id => 'myframe').frame(:name => 'monarch_main').div(:id => 'messageBox').text.include? ('Field [name]: The name field cannot contain any of the following characters:')
end
##########################################################################
######################## SERVICE Escalation #########################
# for Renaming and modifying a service escalation
And /^I "(.+)" the service escalation "(.+)"$/ do |action,escalation|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
if action == 'rename'
frameleft.link(:text => /Escalations/).when_present.click
frameleft.link(:text => /service escalation/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{escalation}/).click
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => /new_name/).set escalation+"-renamed"
framemain.button(:value => /Rename/).when_present.click
framemain.td(:class => 'data0').text.include? ('Renamed:')
framemain.td(:class => 'data0').text.include? (" "+escalation+"-renamed")
framemain.button(:value => /Continue/).when_present.click
elsif action == 'modify'
frameleft.link(:text => /#{escalation}/).click
framemain.text_field(:name => 'first_notification').set '2'
framemain.text_field(:name => 'last_notification').set '4'
framemain.text_field(:name => 'notification_interval').set '30'
framemain.checkbox(:value => 'c', :name => 'escalation_options').clear
framemain.checkbox(:value => 'w', :name => 'escalation_options').when_present.set
framemain.button(:value => 'Save').when_present.click
elsif action == "delete"
frameleft.link(:text => /Escalations/).when_present.click
frameleft.link(:text => /service escalation/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{escalation}/).click
framemain.button(:value => /Delete/).when_present.click
framemain.button(:name => /confirm_delete/).when_present.click
framemain.td(:class => 'data0').text.include? ("Removed:")
framemain.td(:class => 'data0').text.include? (" "+escalation+"-renamed")
framemain.button(:value => /Continue/).when_present.click
end
end
Then /^the service escalation "(.+)" should be "(.+)" successfully$/ do |escalation,action|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
if action == 'renamed'
frameleft.link(:text => /Escalations/).when_present.click
frameleft.link(:text => /service escalation/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{escalation}/).exists?.should == true
elsif action == 'modified'
framemain.td(:class => 'data0').text.include? ("Changes to \"#{escalation}\" have been saved.")
framemain.button(:value => /Continue/).when_present.click
elsif action == "deleted"
frameleft.link(:text => /Escalations/).when_present.click
frameleft.link(:text => /service escalation/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{escalation}/).exists?.should == false
end
end
# for Renaming and deleting a service escalation tree
And /^I "(.+)" the service escalation tree "(.+)"$/ do |action,tree|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft.link(:text => /Escalation trees/).when_present.click
frameleft.link(:text => /service escalation tree/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{tree}/).click
if action == 'rename'
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => /new_name/).set tree+"-renamed"
framemain.button(:value => /Rename/).when_present.click
framemain.td(:class => 'data0').text.include? ('Renamed:')
framemain.td(:class => 'data0').text.include? (" "+tree+"-renamed")
framemain.button(:value => /Continue/).when_present.click
elsif action == 'delete'
framemain.button(:value => /Delete/).when_present.click
framemain.button(:name => /confirm_delete/).when_present.click
framemain.td(:class => 'data0').text.include? ("Removed:")
framemain.td(:class => 'data0').text.include? (" "+tree+"-renamed")
end
end
Then /^the service escalation tree "(.+)" should be "(.+)" successfully$/ do |tree,action|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft.link(:text => /Escalation tree/).when_present.click
frameleft.link(:text => /service escalation tree/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
if action == 'renamed'
frameleft.link(:text => /#{tree}/).exists?.should == true
elsif action == 'deleted'
frameleft.link(:text => /#{tree}/).exists?.should == false
end
end
# for Deleting a service escalation tree
And /^I rename the service escalation tree "(.+)"$/ do |tree|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft.link(:text => /Escalation trees/).when_present.click
frameleft.link(:text => /service escalation tree/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{tree}/).click
framemain.button(:value => /Rename/).when_present.click
framemain.text_field(:name => /new_name/).set tree+"-renamed"
framemain.button(:value => /Rename/).when_present.click
framemain.td(:class => 'data0').text.include? ('Renamed:')
framemain.td(:class => 'data0').text.include? (" "+tree+"-renamed")
framemain.button(:value => /Continue/).when_present.click
end
Then /^the service escalation tree "(.+)" should be renamed successfully$/ do |tree|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft.link(:text => /Escalation tree/).when_present.click
frameleft.link(:text => /service escalation tree/).when_present.click
frameleft.link(:text => /Modify/).when_present.click
frameleft.link(:text => /#{tree}/).exists?.should == true
end
##########################################################################
######################## SERVICE #####################################
And /^I select the service "(.+)"$/ do |service|
frameleft = @browser.frame(:id => "myframe").frame(:name => "monarch_left").when_present
framemain = @browser.frame(:id => 'myframe').frame(:name => 'monarch_main').when_present
frameleft.link(:text => /Services/).when_present.click
frameleft.link(:text => /#{service}/).when_present.click
end
# for Deleting hosts should remove their corresponding services from service group (Status Viewer Scenario)
Given /^I create a new Service Group with name "(.+)"$/ do |sg_name|
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text, /Service groups/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /New/, :href => /service_groups&task=new/).when_present.click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name, /name/).when_present.set sg_name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name, /alias/).set sg_name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, /add/).click
sleep(3)
end
Given /^I add the service "(.+)" of host "(.+)" to the new Service Group$/ do |service,host|
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /host/).option(:text => host).when_present.select
@browser.frame(:id => "myframe").frame(:name => "monarch_main").when_present.select(:name => /services/).option(:text => service).when_present.select
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name, 'add_services').click
end
When /^I select the service group "(.+)"$/ do |sg|
on ServiceConfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Service groups/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{sg}/).click
sleep(2)
end
end
When /^I remove the service "(.+)" of host "(.+)" from service group "(.+)"$/ do |service,host,sg|
on ServiceConfigurationPage do |page|
#view=service_group&obj=servicegroups&name=SG4&host=&service=&del_host=qa-ubuntu-12-4-64&del_service=icmp_ping_alive&remove_service=1
href_value = String.new("")
href_value = "view=service_group&obj=servicegroups&name="+sg+"&host=&service=&del_host="+host+"&del_service="+service+"&remove_service=1"
puts href_value
#Removing the service with the above URL
@browser.frame(:id => "myframe").frame(:name => "monarch_main").link(:href => /#{href_value}/).click
puts @browser.frame(:id => "myframe").frame(:name => "monarch_main").link(:href => /#{href_value}/).text
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /save/).click
end
end
###################################################################
################ HOST GROUP ################################
Then(/^I remove member host "(.+)" and add "(.+)"$/) do |host_init,host_final|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /members/).select host_init
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /members_remove_member/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /members_nonmembers/).select host_final
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /members_add_member/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /save/).click
end
Then(/^I verify that host "(.+)" is a member of hostgroup "(.+)" on "(.+)"$/) do |host,hg,page|
if page=="Host Configuration page"
# Checking the presence of the host on the on Hosts Configuration Page
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /members/).include?(host)
else
sleep(4)
@browser.span(:text => hg).when_present.click
sleep(2)
# Checking the presence of hosts on the on Hosts Configuration Page
@browser.div(:id => /divContents/).span(:text => host).exists?.should == true
end
end
# for Verify changing contactgroup associated with a hostgroup
Then(/^I select the hostgroup "(.+)"$/) do |hostgroup|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Host groups/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{hostgroup}/).click
sleep(2)
end
Then(/^I change the contact group from "(.+)" to "(.+)"$/) do |cg_init,cg_final|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /contactgroup/).select cg_init
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /contactgroup_remove_member/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /contactgroup_nonmembers/).select cg_final
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /contactgroup_add_member/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /save/).click
end
Then(/^I verify that the Contact Group is "(.+)"$/) do |cg_changed|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /contactgroup/).include?(cg_changed)
puts @browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /contactgroup/).include?(cg_changed)
end
Given /^I add the hosts except the host localhost to the new host group$/ do
$selectList = @browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /nonmembers/)
$selectContent = $selectList.options.map(&:text).each { |element|
if element != "localhost"
$host_array << element
$selectList.select(element)
end
}
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:value, /<< Add/).click
# printing the hosts
puts "Number of hosts added : "+ $host_array.length.to_s
$host_array.each do |host_array|
puts host_array
end
end
# for Verify copying a hostgroup
Then(/^I copy the host group with name copy-"(.+)"$/) do |hg|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Host groups/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Copy/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{hg}/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /name/).set "copy-"+hg
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /alias/).set "copy-"+hg
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "add").click
sleep(2)
end
Then(/^I verify the copy of hostgroup "(.+)" has been added to the GW portal$/) do |hg|
copy_of_hg = "copy-"+hg
on HostconfigurationPage do |page|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Host groups/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{copy_of_hg}/).click
sleep(2)
# Checking the presence of hosts on the on Hosts Configuration Page
$host_array.each do |host_array|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /members/).include?(host_array)
end
end
on StatusviewerPage do |page|
visit StatusviewerPage
sleep(4)
@browser.span(:text => copy_of_hg).when_present.click
sleep(2)
# Checking the presence of hosts on the on Hosts Configuration Page
$host_array.each do |host_array|
@browser.div(:id => /divContents/).span(:text => host_array).exists?.should == true
end
end
end
# for renaming a host group
Then(/^I rename the hostgroup to renamed-"(.+)"$/) do |hg|
new_name = "renamed-"+hg
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /rename/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /new_name/).set new_name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /rename/).click
sleep(2)
end
Then(/^I verify that hostgroup has been renamed to renamed-"(.+)"$/) do |hg|
new_name = "renamed-"+hg
on HostconfigurationPage do |page|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Host groups/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{new_name}/).click
sleep(2)
puts "Hosts on Hosts Configuration: "
# Checking the presence of hosts on the on Hosts Configuration Page
$host_array.each do |host_array|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /members/).include?(host_array)
puts @browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /members/).option(:value => host_array).text
end
end
on StatusviewerPage do |page|
visit StatusviewerPage
sleep(4)
@browser.span(:text => new_name).when_present.click
sleep(2)
puts "Hosts on Status Viewer: "
# Checking the presence of hosts on the on Hosts Configuration Page
$host_array.each do |host_array|
@browser.div(:id => /divContents/).span(:text => host_array).exists?.should == true
puts @browser.div(:id => /divContents/).span(:text => host_array).text
end
end
end
##################################################################################################
########################### HOSTS ########################################################
#for Verify creating a host using Host Wizard
Then(/^I select the "(.+)" option$/) do |option|
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{option}/).when_present.click
end
Then(/^I add a new host "(.+)" with IP address "(.+)" and services "(.+)" and "(.+)" as a "(.+)"$/) do |host_name,ip,service1,service2,save_as|
on HostconfigurationPage do |page|
#page 1 of host wizard
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /name/).set host_name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /alias/).set host_name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /address/).set ip
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /next/).click
sleep(2)
#page 2 of host wizard
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /host_template/).when_present(45).select "generic-host"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /next/).click
sleep(2)
#page 3 of host wizard
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /hostgroups_nonmembers/).select "Linux Servers"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /hostgroups_add_member/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /next/).click
sleep(2)
#page 4 of host wizard
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /services/).select service1
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /add_service/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /services/).select service2
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /add_service/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /next/).click
sleep(2)
#last page of Host Wizard
if save_as == "host"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /continue/).click
else
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /save_as_profile/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /save/).click
end
end
end
Then(/^I verify that the host "(.+)" has been added to the GW portal$/) do |host_name|
on HostconfigurationPage do |page|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Hosts/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Linux Servers/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => host_name).exists?
end
on StatusviewerPage do |page|
visit StatusviewerPage
sleep(10)
page.linux_servers_element.when_present.click
sleep(2)
@browser.span(:text => host_name).exists?
end
end
# for Verify changing ip address for a host if 2 hosts have same ip address
Then(/^I verify ip address of host "(.+)" has been updated to "(.+)"$/) do |host,ip|
on HostconfigurationPage do |page|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Hosts/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Linux Servers/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{host}/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Detail/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /address/).attribute_value("value") == ip
end
end
#for Verify checking hostname duplicacy and deleting host
Then(/^I attempt to add a new host with name "(.+)" with IP address "(.+)" and services "(.+)" and "(.+)"$/) do |host_name,ip,service1,service2|
on HostconfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /name/).set host_name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /alias/).set host_name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /address/).set ip
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /next/).click
end
end
Then(/^a host wizard error message for host "(.+)" should be generated$/) do |host_name|
on HostconfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").td(:text => "Host "+host_name+" already exists.").exists?
end
end
Then(/^I select the host "(.+)" of hostgroup "(.+)"$/) do |host_name,hostgroup|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Hosts/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Linux Servers/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{host_name}/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Detail/).click
sleep(3)
end
Then(/^I delete the host$/) do
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /delete/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /confirm_delete_host/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /continue/).click
end
Then(/^I verify that the host "(.+)" has been deleted$/) do |host_name|
on StatusviewerPage do |page|
visit StatusviewerPage
sleep(50)
page.linux_servers_element.when_present.click
sleep(10)
@browser.span(:text => host_name).exists?.should == false
end
end
# for Verify cloning a host
Then(/^I clone the host "(.+)"$/) do |hostname|
on HostconfigurationPage do |page|
sleep(3)
clone_name = "clone-"+hostname
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /name/).set clone_name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /alias/).set clone_name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /address/).set "127.0.0.2"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /host/).select hostname
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /add_clone_host/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /save/).click
end
end
Then(/^I verify that the clone of host "(.+)" with services "(.+)" and "(.+)" has been added to the GW portal$/) do |host_name,service1,service2|
sleep(3)
clone_name = "clone-"+host_name
on HostconfigurationPage do |page|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Hosts/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Linux Servers/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => clone_name).exists?
end
on StatusviewerPage do |page|
visit StatusviewerPage
sleep(4)
page.linux_servers_element.when_present.click
sleep(2)
@browser.span(:text => clone_name).exists?
@browser.span(:text => clone_name).click
@browser.span(:text => service1).exists?
@browser.span(:text => service2).exists?
sleep(1)
end
end
Then(/^I select the clone of host "(.+)" of hostgroup "(.+)"$/) do |host_name,hostgroup|
sleep(3)
clone_name = "clone-"+host_name
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Hosts/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Linux Servers/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{clone_name}/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Detail/).click
sleep(3)
end
# for Verify creating a host using Host Wizard and saving it as a profile
Then(/^I verify host "(.+)" exists as a "(.+)" profile$/) do |host_name,type|
visit ProfilesConfigurationPage
sleep(3)
if type == "host"
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Host profiles/).click
else
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Service profiles/).click
end
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).click
sleep(1)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => host_name).exists? == true
end
# for Verify searching a host using hostname and host IP
Then(/^I search a host by "(.+)"$/) do |option|
on HostconfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /input/).set option
sleep(5)
end
end
Then(/^the search output should be "(.+)"$/) do |output|
on HostconfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").td(:text => output).exists?.should == false
end
end
# for Verify modifying a host
Then(/^I rename the host "(.+)"$/) do |host|
on HostconfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /rename/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /new_name/).set "renamed-"+host
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /rename/).click
sleep(2)
end
end
Then(/^I edit host alias$/) do
on HostconfigurationPage do |page|
host_alias = String.new("")
host_alias = @browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /alias/).attribute_value("value")
puts host_alias
host_alias = "edited_"+host_alias
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /alias/).set host_alias
sleep(2)
end
end
Then(/^I edit host IP address as "(.+)"$/) do |address|
on HostconfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /address/).set address
end
end
Then(/^I change host template as "(.+)"$/) do |template|
on HostconfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /template/).select template
sleep(1)
end
end
And(/^I change its contact group from "(.+)" to "(.+)"$/) do |cg_old,cg_new|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:name => /contactgroup_override/).clear
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /contactgroup/).select cg_old
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /contactgroup_remove_member/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /contactgroup_nonmembers/).select cg_new
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /contactgroup_add_member/).click
sleep(1)
end
Then(/^I save the host editing$/) do
on HostconfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /save/).click
end
end
Then(/^I save the service editing$/) do
on HostconfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /save/).click
end
end
Then(/^I verify that changes to host "(.+)" have been saved with address as "(.+)" and template as "(.+)"$/) do |host,address,template|
host_alias = "edited_"+host
#checking host alias
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /alias/).attribute_value("value") == host_alias
#checking host IP Address
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /address/).attribute_value("value") == host_alias
#checking host template
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /template/).selected?(template)
end
Then(/^I revert the changes made with the host$/) do
on HostconfigurationPage do |page|
#renaming the host
name = String.new("")
name = @browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /name/).attribute_value("value")
if name.include? "renamed-"
puts name.slice "renamed-"
name["renamed-"]= ""
end
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /rename/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /new_name/).set name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /rename/).click
sleep(2)
#renaming the host alias
host_alias = String.new("")
host_alias = @browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /alias/).attribute_value("value")
puts host_alias
if host_alias.include? "edited_"
puts host_alias.slice "edited_"
host_alias["edited_"]= ""
end
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /alias/).set host_alias
sleep(2)
#resetting the IP Address
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /address/).set "172.28.113.207"
#reselecting the host template
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /template/).select "generic-host"
#saving the changes
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /save/).click
end
end
# Verify deleting a host using 'Delete Host' option
Then(/^I select host "(.+)" to be deleted$/) do |host|
on HostconfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /search/).select "*"
sleep(4)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:value => host).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "remove_host").when_present.click
sleep(5)
end
end
# Verify deleting a host using 'Delete Host Services' option
Then(/^I select and delete the service "(.+)" of host "(.+)" to be deleted$/) do |service,host|
on HostconfigurationPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /service/).select service
sleep(4)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:value => host).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "remove_host").when_present.click
sleep(5)
end
end
# Verify deleting a service using 'Delete host services' option
Then(/^I verify that the service "(.+)" of host "(.+)" has been deleted$/) do |service,host|
on StatusviewerPage do |page|
visit StatusviewerPage
page.linux_servers_element.when_present.click
sleep(10)
@browser.span(:text => host).when_present.click
sleep(3)
@browser.div(:id => /divContents/).span(:text => service).exists?.should == false
end
end
# Verify modifying a host on cfg file
Then(/^I open the hosts.cfg file$/) do
on ControlPage do |page|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").link(:href => "/monarch/monarch_file.cgi?file=/monarch/workspace/hosts.cfg").click
sleep(3)
end
end
Then(/^I verify host "(.+)" with alias "(.+)" and ip "(.+)" and template "(.+)" on hosts.cfg file$/) do |host,host_alias,ip,template|
@browser.window(:title => "hosts.cfg").when_present.use
sleep(2)
<EMAIL>? ("host_name "+host)
<EMAIL>.include? ("alias "+/#{host_alias}/) # gives "can't convert Regexp into String (TypeError) " error
@browser.pre(:text => " alias "+host_alias+" ").exists?.should == true
#actual line from cfg file inside quotes ---> " alias kjdscsbc "
sleep(2)
@browser.window(:title =>/control/).when_present.use
@browser.window(:title =>"hosts.cfg").close
sleep(5)
end
################################################################################################
################## PARENT CHILD PAIR #########################################################
Then(/^I create a new Parent Child pair with "(.+)" as parent and "(.+)" as child$/) do |parent,child|
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /New/).when_present.click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /parent/).select parent
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /children_nonmembers/).select child
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "children_add_member").click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "save").click
end
Then(/^I verify that pair exists with "(.+)" as parent and "(.+)" as child$/) do |parent,child|
on HostconfigurationPage do |page|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Parent child/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{parent}/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /children/).include?(child)
puts "On Host Configuration page: "
puts "Parent : "+parent
puts "Child : "[email protected](:id => "myframe").frame(:name => "monarch_main").select(:name => /children/).option(:value => child).text
end
on StatusviewerPage do |page|
sleep(15)
visit StatusviewerPage
page.linux_servers_element.when_present.click
sleep(2)
@browser.span(:text => child).when_present.click
sleep(2)
@browser.link(:text => /Parents for this Host/).when_present.click
sleep(3)
@browser.span(:text => /#{parent}/).exists?.should == true
puts "On Status Viewer: "
puts "Parent : "[email protected](:text => /#{parent}/).text
puts "Child : "+child
end
end
Then(/^I select the "(.+)" "(.+)" parent child pair$/) do |parent,child|
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).when_present.click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{parent}/).click
sleep(3)
end
Then(/^I delete the "(.+)" "(.+)" parent child pair$/) do |parent,child|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /delete/).click
end
Then(/^I verify that "(.+)" "(.+)" parent child pair has been deleted$/) do |parent,child|
on HostconfigurationPage do |page|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Parent child/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{parent}/).exists?.should == false
end
on StatusviewerPage do |page|
sleep(15)
visit StatusviewerPage
page.linux_servers_element.when_present.click
sleep(2)
@browser.span(:text => child).when_present.click
sleep(2)
@browser.link(:text => /Parents for this Host/).when_present.click
sleep(3)
@browser.span(:text => /#{parent}/).exists?.should == true
puts "On Status Viewer: "
puts "Parent : "[email protected](:text => /#{parent}/).text
puts "Child : "+child
end
end
################################################################################################
################## Host Template #############################################################
# for Verify creating a host template
Then(/^I create a new host template with name "(.+)"$/) do |name|
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /New/).when_present.click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /name/).set name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:name => /active_checks_enabled/).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:name => /passive_checks_enabled/).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /check_command/).select "check_http"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /command_line/).set ""
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /check_period/).select "workhours"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /check_interval/).set "1"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /retry_interval/).set ""
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /max_check_attempts/).set "4"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:name => /check_freshness/).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /freshness_threshold/).set "50"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:name => /obsess_over_host/).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:name => /flap_detection_enabled/).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /low_flap_threshold/).set "10"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /high_flap_threshold/).set "100"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:name => /event_handler_enabled/).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /event_handler/).select "check-host-alive"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:value => /d/, :name => /stalking_options/).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:name => /process_perf_data/).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:name => /notifications_enabled/).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:value => /d/, :name => /notification_options/).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:value => /r/, :name => /notification_options/).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /notification_period/).select "workhours"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /notification_interval/).set "5"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /contactgroup_nonmembers/).select "nagiosadmin"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /contactgroup_add_member/).click
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:name => /retain_status_information/).set(true)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").checkbox(:name => /retain_nonstatus_information/).set(true)
=begin
*Active checks enabled: Checked
*Passive checks enabled: Checked
*Check command: check_http
*Command line: Leave it blank
*Check period: workhours
*Check interval: 1
*#Retry Interval: blank
*Max check attempts: 4
*Check freshness: Checked
*Freshness threshold: 50
*Obsess over host: Checked
*Flap detection enabled: Checked
*Low flap threshold: 10
*High flap threshold: 100
*Event handler enabled: Checked
*Event handler: Check-host-alive
*Stalking options: Down
*Process perf data: Checked
*Notifications enabled: Checked
*Notification options: Down, Recovery
*Notification period: workhours
*Notification interval: 5
*Contact Groups: Helpdesk
*Retain status information: Checked
*Retain nonstatus information: Checked
=end
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "add").click
sleep(2)
end
Then(/^I verify that a new host template with name "(.+)" has been "(.+)"$/) do |name,action|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Host templates/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).click
sleep(3)
if action=='created'
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{name}/).exists?.should == true
puts "Host Template on Host Configuration page : "[email protected](:id => "myframe").frame(:name => "monarch_left").link(:text => /#{name}/).text
elsif action == 'deleted'
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{name}/).exists?.should == false
puts "Host Template "+name+" on Host Configuration page no longer exists."
end
end
# for Verify copying and deleting a host template
Then(/^I copy the host template with name "(.+)"$/) do |name|
copy_name = "copy-"+name
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Host templates/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Copy/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{name}/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /name/).set copy_name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "add").click
end
Then(/^I delete the host template "(.+)"$/) do |name|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Host templates/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{name}/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "delete").click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "confirm_delete").click
end
Then(/^I attempt to delete the host template "(.+)"$/) do |name|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Host templates/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{name}/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "delete").click
end
# for Verify a host template which is applied to a host cannot be deleted
Then(/^an error message with respect to host "(.+)" is displayed$/) do |host|
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").td(:text => /Cannot delete until all dependencies are removed/).exists?.should == true
@browser.frame(:id => "myframe").frame(:name => "monarch_main").td(:text => /#{host}/).exists?.should == true
end
# for Verify modifying a host template
Then(/^I select the host template "(.+)" for modifying$/) do |name|
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).when_present.click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{name}/).click
sleep(2)
end
Then(/^I rename the host template to renamed-"(.+)"$/) do |name|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /rename/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /new_name/).set "renamed-"+name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /rename/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => /continue/).click
end
Then(/^I change Max check attempts = "(.+)" and Check Interval = "(.+)" of the host template$/) do |max_chk_atpt,chk_ivl|
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /check_interval/).set chk_ivl
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /max_check_attempts/).set max_chk_atpt
end
Then(/^I save the modifications$/) do
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "save").click
end
Then(/^I verify host template modifications have been made$/) do
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /check_interval/).value == "5"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /max_check_attempts/).value == "6"
end
# for creating a host extended info template and applying it to a host
Then(/^I create a new host extended info template with name "(.+)"$/) do |name|
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /New/).when_present.click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /name/).set name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /notes/).set "East block switch"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /notes_url/).set "http://www.gwos.com/"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /action_url/).set "http://www.gwos.com/"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /icon_image/).select "switch.gif"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /icon_image_alt/).set "Switch"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /vrml_image/).select "switch.jpg"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /statusmap_image/).select "switch.gd2"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /2d_coords/).set ""
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => /3d_coords/).set ""
=begin
Name: extended_info_host
Note: East block switch
Notes url: http://www.gwos.com/
Action url: http://www.gwos.com/
Icon image: switch.gif
Icon image alt: Switch
Vrml image: switch.jpg
Statusmap image: switch.gd2
2nd coords: Leave it blank
3rd coords: Leave it blank
Click on Add.
=end
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "add").click
sleep(2)
end
Then(/^I verify that a new host extended info template with name "(.+)" has been "(.+)"$/) do |name,action|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Host extended info/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).click
sleep(3)
if action=='created'
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{name}/).exists?.should == true
puts "Host extended info template on Host Configuration page : "[email protected](:id => "myframe").frame(:name => "monarch_left").link(:text => /#{name}/).text
elsif action=='deleted'
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{name}/).exists?.should == false
puts "Host extended info template "+name+" on Host Configuration page no longer exists."
end
end
Then(/^I "(.+)" its host extended info template as "(.+)"$/) do |action,name|
if action=="save"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /extended_info/).select name
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "save").click
sleep(2)
elsif action=="verify"
@browser.frame(:id => "myframe").frame(:name => "monarch_main").select(:name => /extended_info/).selected?(name)
end
end
# for Verify copying a host extended info template and deleting it
Then(/^I copy the host extended info template with name copy-"(.+)"$/) do |name|
copy_name= "copy-"+name
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Copy/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{name}/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").text_field(:name => "name").set copy_name
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "add").click
end
Then(/^I delete the host extended info template with name "(.+)"$/) do |name|
visit HostconfigurationPage
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Host extended info/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /Modify/).click
sleep(3)
@browser.frame(:id => "myframe").frame(:name => "monarch_left").link(:text => /#{name}/).click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "delete").click
sleep(2)
@browser.frame(:id => "myframe").frame(:name => "monarch_main").button(:name => "confirm_delete").click
end
<file_sep>Given(/^I navigate to flipkart$/) do
@browser.goto"http://www.flipkart.com"
end
When(/^I clicked the login button$/) do
@browser.a(:class,'no-border js-login login-required').when_present.click
end
When(/^I login with the (\w++) and (\w++)$/) do |username, password|
on LoginPage do |page|
page.login(username, password)
end
end
Then(/^Error should come$/) do
@browser.div(:class =>'fk-inline-block err_text').wait_until_present
(@browser.text.include? 'Invalid details. Please try again.').should == true
end
<file_sep>Given /^I am on the Views page$/ do
visit ViewPage
end
And /^I select "(.+)" and rename it with "(.+)"$/ do |oldname, newname|
on ViewPage do |page|
page.options_element.fire_event 'mouseover'
sleep(2)
page.managemap_element.fire_event('click')
page.rename_map(oldname, newname)
end
end
Given /^I save a map with "(.+?)"$/ do |name|
on ViewPage do |page|
page.options_element.fire_event 'mouseover'
sleep(2)
page.managemap_element.fire_event('click')
sleep(2)
page.map = name
page.iconset = "std_big"
page.map_image_list = "CorporateWebSite.png"
page.submit_button_element.when_present.click
sleep(3)
end
end
Given /^I delete the map with "(.+?)"$/ do |delete_map|
on ViewPage do |page|
sleep(2)
page.options_element.fire_event 'mouseover'
sleep(2)
page.managemap_element.fire_event('click')
sleep(2)
#<EMAIL>(:id => "myframe").table(:id => /popupWindowMaster/).table(:id => /table_map_delete/).td(:class => "tdfield").select_list(:name => "map").option(:text => delete_map).select
page.delete_map(delete_map)
sleep(2)
end
end
Given /^I verify that the map with "(.+?)" has been deleted$/ do |delete_map|
on ViewPage do |page|
page.open_element.fire_event 'mouseover'
sleep(2)
@browser.frame(:id => "myframe").link(:text => delete_map).exists?.should == false
end
end
And /^I import a map$/ do
on ViewPage do |page|
page.options_element.fire_event 'mouseover'
sleep(2)
page.managemap_element.when_present.click
sleep(2)
page.uploadmap_element.set("/usr/nagvisdata/test.cfg")
page.import_submit_element.when_present.click
sleep(4)
@browser.frame(:id => "myframe").link(:id => /map-test-icon/).when_present.click
sleep(4)
end
end
And /^I delete the imported map "(.+?)"$/ do |delete_map|
on ViewPage do |page|
page.options_element.fire_event 'mouseover'
sleep(2)
page.managemap_element.when_present.click
page.delete_map(delete_map)
sleep(2)
page.open_element.fire_event 'mouseover'
sleep(2)
@browser.frame(:id => "myframe").link(:text => delete_map).exists?.should == false
sleep(2)
end
end
And /^I give user permission to "(.+)"$/ do |gwuser|
on ViewPage do |page|
#page.usermenu_element.fire_event 'mouseover'
page.options_element.fire_event 'mouseover'
page.manageuser_element.fire_event('click')
sleep(2)
page.modify_user(gwuser)
page.selectcheck_element.when_present.clear
page.selectcheck1_element.when_present.set
page.selectcheck2_element.when_present.set
page.saveuser_element.when_present.click
end
end
And /^I give operator permission to "(.+)"$/ do |gwuser|
on ViewPage do |page|
#page.usermenu_element.fire_event 'mouseover'
page.options_element.fire_event 'mouseover'
page.manageuser_element.fire_event('click')
sleep(2)
page.modify_user(gwuser)
page.selectcheck_element.when_present.clear
page.selectcheck1_element.when_present.set
page.selectcheck2_element.when_present.set
page.saveuser_element.when_present.click
end
end
And /^I logout from current user$/ do
on DashboardPage do |page|
sleep(2)
page.logout
end
end
When /^I login with "(.+)" gwuser$/ do |user|
on LoginPage do |page|
page.login_user(user,user)
end
end
Then /^I should be able to see the "(.+)" map$/ do |newname|
on ViewPage do |page|
visit ViewPage
page.select_map(newname)
end
end
And /^I login with admin$/ do
on LoginPage do |page|
page.login_user('admin','admin')
end
end
Given /^I reset the user permission of "(.+)"$/ do |gwuser|
on ViewPage do |page|
visit ViewPage
#page.usermenu_element.fire_event 'mouseover'
page.options_element.fire_event 'mouseover'
page.manageuser_element.fire_event('click')
sleep(2)
page.modify_user(gwuser)
page.selectcheck_element.when_present.set
page.selectcheck1_element.when_present.clear
page.selectcheck2_element.when_present.clear
page.saveuser_element.when_present.click
end
end
And /^I edit a object$/ do
on ViewPage do |page|
page.map2_element.when_present.click
sleep(3)
page.object_element.when_present.right_click
page.unlock_element.fire_event('click')
page.object_element.when_present.right_click
page.modify_element.when_present.click
page.hostname = "itmon-win"
page.modify_button_element.when_present.click
sleep(5)
#page.object_element.when_present.right_click
page.editmap_element.fire_event 'mouseover'
sleep(2)
page.lockunlock_element.fire_event('click')
page.object1_element.fire_event('click')
sleep(10)
end
end
Then /^I verify that the object is modified$/ do
on StatusviewerPage do |page|
@browser.span(:id => /HVform:txthostName/, :text => /itmon-win/).exists?.should == true
end
end
And /^I revert the changes made above$/ do
on ViewPage do |page|
sleep(3)
page.map3_element.when_present.click
sleep(3)
#page.object_element.when_present.right_click
#page.lockunlock_element.when_present.click
page.editmap_element.fire_event 'mouseover'
page.lockunlock_element.fire_event('click')
page.object1_element.when_present.right_click
page.modify_element.when_present.click
page.hostname = "localhost"
page.modify_button_element.when_present.click
sleep(5)
#page.object_element.when_present.right_click
page.editmap_element.fire_event 'mouseover'
sleep(2)
page.lockunlock_element.fire_event('click')
end
end
Given /^the created map with name "(.+?)" should not be saved$/ do |name|
on ViewPage do |page|
page.open_element.fire_event 'mouseover'
sleep(2)
@browser.frame(:id => "myframe").link(:text => name).exists?.should == false
end
end
And /^I add an icon on newmap$/ do
on ViewPage do |page|
page.newmap_element.when_present.click
sleep(3)
page.editmap_element.fire_event 'mouseover'
page.addicon_element.fire_event 'mouseover'
page.addhost_element.when_present.click
page.background_element.when_present.click
sleep(3)
page.hostname = "itmon-win"
page.modify_button_element.when_present.click
sleep(5)
#page.hostadded_element.fire_event('click')
page.hostadded_element.fire_event('click')
sleep(5)
end
end
And /^I delete the host object$/ do
visit ViewPage
on ViewPage do |page|
page.newmap_element.when_present.click
sleep(3)
page.hostadded_element.fire_event 'mouseover'
page.hostadded_element.when_present.right_click
#page.hostadded_element.when_present.send_keys("{APPSKEY}")
sleep(2)
page.unlock_element.when_present.click
sleep(2)
page.hostadded_element.fire_event 'mouseover'
page.hostadded_element.when_present.right_click
sleep(2)
page.delhostobject_element.when_present.click
sleep(1)
@browser.alert.ok
sleep(5)
end
end
And /^I verify deleted host object$/ do
on ViewPage do |page|
@browser.frame(:id => "myframe").img(:alt => /host-itmon-win/).exists?.should == false
end
end
And /^I add an icon service on newmap$/ do
on ViewPage do |page|
page.newmap_element.when_present.click
sleep(3)
page.editmap_element.fire_event 'mouseover'
page.addicon_element.fire_event 'mouseover'
page.addservice_element.when_present.click
sleep(2)
page.background_element.when_present.click
sleep(3)
page.hostname = "itmon-win"
sleep(3)
page.service_desc = /icmp_ping_alive/
page.modify_button_element.when_present.click
sleep(5)
page.serviceicon_element.fire_event('click')
sleep(5)
end
end
Then /^I verify that the service object service exists$/ do
on StatusviewerPage do |page|
@browser.span(:id => "SVform:SHtxtServiceName", :text => /icmp_ping_alive/).exists?.should == true
sleep(2)
end
end
And /^I delete the serviceicon$/ do
visit ViewPage
on ViewPage do |page|
page.newmap_element.when_present.click
sleep(3)
page.serviceicon_element.when_present.right_click
page.unlock_element.when_present.click
page.serviceicon_element.when_present.right_click
page.delhostobject_element.when_present.click
@browser.alert.ok
sleep(2)
end
end
Then /^I verify deleted service icon$/ do
on ViewPage do |page|
page.serviceicon_element.exists?.should == false
end
end
And /^I add a hostline$/ do
on ViewPage do |page|
page.newmap_element.when_present.click
page.editmap_element.fire_event 'mouseover'
page.addline_element.fire_event 'mouseover'
page.linehost_element.fire_event('click')
page.background_element.when_present.click
sleep(2)
page.background_element.drag_and_drop_by 200, -200
sleep(2)
page.background_element.fire_event('click')
sleep(3)
page.hostname = "itmon-win"
sleep(3)
page.modify_button_element.when_present.click
sleep(5)
page.lineadded_element.fire_event('click')
sleep(5)
end
end
Then /^I verify that the host object exists$/ do
on StatusviewerPage do |page|
@browser.span(:id => "HVform:txthostName", :text => /itmon-win/).exists?.should == true
sleep(2)
end
end
And /^I add a line$/ do
on ViewPage do |page|
page.newmap_element.when_present.click
page.editmap_element.fire_event 'mouseover'
page.addline_element.fire_event 'mouseover'
page.serviceline_element.fire_event('click')
page.background_element.when_present.click
sleep(2)
page.background_element.drag_and_drop_by 200, -200
sleep(2)
page.background_element.fire_event('click')
sleep(3)
page.hostname = "itmon-win"
sleep(3)
page.service_desc = /icmp_ping_alive/
page.modify_button_element.when_present.click
sleep(5)
page.lineadded_element.fire_event('click')
sleep(5)
end
end
And /^I add a line as map$/ do
on ViewPage do |page|
page.newmap_element.when_present.click
page.editmap_element.fire_event 'mouseover'
page.addline_element.fire_event 'mouseover'
page.linemap_element.fire_event('click')
page.background_element.when_present.click
sleep(2)
page.background_element.drag_and_drop_by 200, -200
sleep(2)
page.background_element.fire_event('click')
sleep(3)
page.mapname = "GeoOffice"
page.modify_button_element.when_present.click
sleep(5)
page.lineadded_element.fire_event('click')
sleep(5)
end
end
And /^I add a special textbox with "(.+?)"$/ do |name|
on ViewPage do |page|
page.SANJOSE_element.when_present.click
page.editmap_element.fire_event 'mouseover'
page.addspecial_element.fire_event 'mouseover'
page.specialtextbox_element.fire_event('click')
page.background_element.when_present.click
sleep(2)
page.background_element.drag_and_drop_by 200, -200
sleep(2)
page.background_element.fire_event('click')
page.textname = name
page.contwidth = "515"
page.contheight = "283"
page.boxcolorset_element.when_present.set
page.boxcolor = "#FF216B"
#page.selectnegative_element.when_present.clear
#page.selectnegative1_element.when_present.clear
page.submit_button_element.when_present.click
sleep(10)
end
end
And /^I verify the textbox$/ do
on ViewPage do |page|
page.textboxadded_element.exists?.should == true
end
end
And /^I delete the textboxadded$/ do
on ViewPage do |page|
page.textboxadded_element.when_present.right_click
sleep(1)
page.unlock_element.when_present.click
page.textboxadded_element.when_present.right_click
sleep(1)
page.delhostobject_element.when_present.click
@browser.alert.ok
end
end
And /^I verify deleted textboxadded$/ do
on ViewPage do |page|
page.textboxadded_element.exists?.should == false
end
end
And /^I modify map with backgrnd "(.+?)" aliasname "(.+?)" color "(.+?)" mapiconset "(.+?)"$/ do |backgrnd, aliasname, color, iconset|
on ViewPage do |page|
page.map9_element.when_present.click
page.editmap_element.fire_event 'mouseover'
page.mapoptions_element.fire_event('click')
page.mapbackgrnd = backgrnd
page.selectalias_element.when_present.set
page.aliasname = aliasname
page.selectcolor_element.when_present.set
page.backcolor = color
page.mapiconset = iconset
page.submit_button_element.when_present.click
sleep(6)
end
end
And /^I verify modified map options "(.+?)"$/ do |iconset|
on ViewPage do |page|
page.modifybackgrnd_element.exists?.should == true
@browser.frame(:id => "myframe").body(:style => 'background-color: rgb(255, 33, 107);').exists?.should == true
#page.modifycolor_element.exists?.should == true
page.open_element.fire_event 'mouseover'
sleep(2)
@browser.frame(:id => "myframe").link(:text => iconset).when_present.click
sleep(3)
page.editmap_element.fire_event 'mouseover'
page.addicon_element.fire_event 'mouseover'
page.addhost_element.when_present.click
page.background_element.when_present.click
sleep(1)
page.hostname = "itmon-win"
page.submit_button_element.when_present.click
sleep(10)
page.modifyicon_element.exists?.should == true
sleep(2)
end
end
And /^I create a views background name "(.+?)" color "(.+?)" width "(.+?)" height "(.+?)"$/ do |name, color, width, height|
on ViewPage do |page|
page.options_element.fire_event 'mouseover'
sleep(2)
page.managebackgrnd_element.when_present.click
page.imagename = name
page.imagecolor_element.set ('#'+color)
page.imagewidth = width
page.imageheight = height
page.submit_button_element.when_present.click
sleep(4)
end
end
And /^I create a map with backgroundimage$/ do
on ViewPage do |page|
page.options_element.fire_event 'mouseover'
sleep(2)
page.managemap_element.when_present.click
sleep(2)
page.map = "name"
page.iconset = "std_big"
page.map_image_list = "testimage.png"
page.submit_button_element.when_present.click
sleep(3)
end
end
And /^I upload a background image$/ do
on ViewPage do |page|
page.options_element.fire_event 'mouseover'
sleep(2)
page.managebackgrnd_element.when_present.click
page.uploadimage_element.set("/usr/nagvisdata/windows.png")
page.upload_submit_element.when_present.click
sleep(10)
end
end
And /^I create a map with uploadimage$/ do
on ViewPage do |page|
page.options_element.fire_event 'mouseover'
sleep(2)
page.managemap_element.when_present.click
sleep(2)
page.map = "uploadimage"
page.iconset = "cloud"
page.map_image_list = "windows.png"
page.submit_button_element.when_present.click
sleep(3)
end
end
And /^I delete created background "(.+?)" and "(.+?)"$/ do | delete_map, delete_upload|
on ViewPage do |page|
sleep(2)
page.options_element.fire_event 'mouseover'
sleep(2)
page.managemap_element.when_present.click
page.delete_map(delete_map)
sleep(2)
page.options_element.fire_event 'mouseover'
sleep(2)
page.managemap_element.when_present.click
page.delete_map(delete_upload)
sleep(2)
page.options_element.fire_event 'mouseover'
sleep(2)
page.managebackgrnd_element.when_present.click
page.deletebackgrnd = "testimage.png"
page.deletesubmit_element.when_present.click
@browser.alert.ok
sleep(4)
page.options_element.fire_event 'mouseover'
sleep(2)
page.managebackgrnd_element.when_present.click
page.deletebackgrnd = "windows.png"
page.deletesubmit_element.when_present.click
@browser.alert.ok
sleep(3)
page.options_element.fire_event 'mouseover'
sleep(2)
page.managebackgrnd_element.when_present.click
sleep(2)
@browser.select(:name => /map_image/, :text => /testimage.png/).exists?.should == false
sleep(2)
@browser.select(:name => /map_image/, :text => /windows.png/).exists?.should == false
sleep(2)
end
end
And /^I upload a shape$/ do
on ViewPage do |page|
page.options_element.fire_event 'mouseover'
sleep(2)
page.manageshape_element.when_present.click
sleep(2)
page.uploadimage_element.set("/usr/nagvisdata/test-shape.png")
page.upload_submit_element.when_present.click
sleep(3)
end
end
And /^I create a map with the shape$/ do
on ViewPage do |page|
page.map5_element.when_present.click
page.editmap_element.fire_event 'mouseover'
page.addspecial_element.fire_event 'mouseover'
page.addshape_element.when_present.click
page.background_element.when_present.click
page.shapeicon = "test-shape.png"
page.submit_button_element.when_present.click
sleep(8)
page.iconshape_element.exists?.should == true
end
end
And /^I delete the shape that cannot be deleted$/ do
on ViewPage do |page|
page.options_element.fire_event 'mouseover'
sleep(2)
page.manageshape_element.when_present.click
sleep(2)
page.icondelete = "test-shape.png"
page.deletesubmit_element.when_present.click
@browser.alert.ok
end
end
And /^I delete the shape$/ do
on ViewPage do |page|
page.map5_element.when_present.click
sleep(2)
page.iconshape_element.when_present.right_click
page.unlock_element.when_present.click
page.iconshape_element.when_present.right_click
page.delhostobject_element.when_present.click
@browser.alert.ok
sleep(2)
page.iconshape_element.exists?.should == false
end
end
And /^I upload a shape with invalid format$/ do
on ViewPage do |page|
page.options_element.fire_event 'mouseover'
sleep(3)
page.manageshape_element.when_present.click
sleep(2)
page.uploadimage_element.set("/usr/nagvisdata/test.txt")
page.upload_submit_element.when_present.click
end
end
And /^I see validation message$/ do
on ViewPage do |page|
shape_error = @browser.alert.text
shape_validation = 'You have to select an image in a supported format (Png, Gif, Jpg).'
if
shape_error == shape_validation
sleep(2)
@browser.alert.ok
else
puts shape_error
raise
sleep(2)
end
end
end
And /^I export a map to static$/ do
on ViewPage do |page|
page.map2_element.when_present.click
sleep(2)
page.action_element.fire_event 'mouseover'
sleep(2)
page.export_to_static_element.when_present.click
sleep(2)
page.target = "statictest"
page.submit_button_element.when_present.click
sleep(2)
page.open_element.fire_event 'mouseover'
sleep(3)
page.staticmap_element.when_present.click
sleep(2)
end
end
And /^I delete the static map "(.+?)"$/ do |delete_map|
on ViewPage do |page|
page.options_element.fire_event 'mouseover'
sleep(2)
page.managemap_element.when_present.click
sleep(2)
page.delete_map(delete_map)
sleep(2)
page.open_element.fire_event 'mouseover'
sleep(2)
@browser.frame(:id => "myframe").link(:text => delete_map).exists?.should == false
sleep(2)
end
end
And /^error message appears appears saving invalid staticmap$/ do
on ViewPage do |page|
page.map2_element.when_present.click
sleep(2)
page.action_element.fire_event 'mouseover'
sleep(2)
page.export_to_static_element.when_present.click
page.target = "!@"
page.submit_button_element.when_present.click
sleep(2)
page.error_staticmap_element.exists?.should == true
end
end
And /^I make a parent child map$/ do
on ViewPage do |page|
page.map5_element.when_present.click
sleep(2)
page.editmap_element.fire_event 'mouseover'
page.mapoptions_element.fire_event('click')
page.selectparent_element.when_present.set
sleep(2)
page.parentmap = "World"
page.submit_button_element.when_present.click
sleep(2)
end
end
And /^I verfiy error message appears$/ do
on ViewPage do |page|
page.map2_element.when_present.click
sleep(2)
page.editmap_element.fire_event 'mouseover'
page.mapoptions_element.fire_event('click')
page.selectparent_element.when_present.set
sleep(2)
page.parentmap = "PublicWeb"
page.submit_button_element.when_present.click
sleep(2)
page.error_staticmap_element.exists?.should == true
end
end
And /^I make a container witout url with error$/ do
on ViewPage do |page|
page.SANJOSE_element.when_present.click
sleep(2)
page.editmap_element.fire_event 'mouseover'
page.addspecial_element.fire_event 'mouseover'
page.addcontainer_element.when_present.click
page.background_element.fire_event('click')
page.background_element.drag_and_drop_by 100, -200
page.background_element.fire_event('click')
sleep(3)
page.submit_button_element.when_present.click
page.urlerror_element.exists?.should == true
end
end
And /^I make a container$/ do
on ViewPage do |page|
page.containerurl = "http://en.wikipedia.org/wiki/Cucumber_%28software%29"
page.contwidth = "700"
page.contheight = "210"
page.submit_button_element.when_present.click
sleep(10)
end
end
And /^I verify the weblink inside container$/ do
on ViewPage do |page|
@browser.frame(:id => "myframe").frame(:src => "http://en.wikipedia.org/wiki/Cucumber_(software)").link(:text => "acceptance tests").when_present.click
sleep(6)
@browser.frame(:id => "myframe").frame(:src => "http://en.wikipedia.org/wiki/Cucumber_(software)").span(:text => "Acceptance testing").exists?.should == true
end
end
And /^I delete the container$/ do
on ViewPage do |page|
page.editmap_element.fire_event 'mouseover'
page.lockunlock_element.fire_event('click')
#page.containerdelete_element.when_present.right_click
page.containerdelete_element.fire_event 'hover'
sleep(2)
page.containerdelete_element.when_present.right_click
<EMAIL>(:id => "myframe").frame(:src => "http://en.wikipedia.org/wiki/Cucumber_(software)").when_present.right_click
<EMAIL>(:id => "myframe").div(:id => /-context/).link(:text => /Delete object/).fire_event('click')
sleep(2)
page.delhostobject_element.when_present.click
@browser.alert.ok
sleep(2)
page.editmap_element.fire_event 'mouseover'
page.lockunlock_element.when_present.click
sleep(2)
end
end
And /^I verify deleted container$/ do
on ViewPage do |page|
page.containerdelete_element.exists?.should == false
end
end
And /^I make and verify stateless line$/ do
on ViewPage do |page|
page.map5_element.when_present.click
sleep(2)
page.editmap_element.fire_event 'mouseover'
page.addspecial_element.fire_event 'mouseover'
page.addstateless_element.when_present.click
page.background_element.fire_event('click')
page.background_element.drag_and_drop_by 100, -200
page.background_element.fire_event('click')
sleep(2)
page.x_text_field = '305,558'
page.y_text_field = '45,43'
page.submit_button_element.when_present.click
sleep(6)
page.stateline_element.exists?.should == true
end
end
And /^I delete and verify stateless line$/ do
on ViewPage do |page|
page.editmap_element.fire_event 'mouseover'
sleep(1)
page.lockunlock_element.when_present.click
sleep(2)
page.stateline1_element.when_present.right_click
page.delhostobject_element.when_present.click
sleep(2)
@browser.alert.ok
sleep(2)
page.editmap_element.fire_event 'mouseover'
page.lockunlock_element.when_present.click
page.stateline_element.exists?.should == false
end
end
And /^I select icon "(.+?)" and create "(.+?)"$/ do |option, object|
on ViewPage do |page|
page.icon_select(option, object)
end
end
And /^I verify "(.+?)" and "(.+?)"$/ do |option, object|
on ViewPage do |page|
page.icon_verify(option, object)
end
end
And /^I delete "(.+?)" and verify "(.+?)"$/ do |object, option|
visit ViewPage
on ViewPage do |page|
page.icon_delete(object, option)
end
end
And /^I select line "(.+?)" and create "(.+?)"$/ do |option, object|
on ViewPage do |page|
page.line_select(option, object)
end
end
And /^I verify the line "(.+?)" and "(.+?)"$/ do |option, object|
on ViewPage do |page|
page.line_verify(option, object)
end
end
Then /^I delete and verify the line$/ do
visit ViewPage
on ViewPage do |page|
page.map9_element.when_present.click
sleep(2)
page.lineadded_element.fire_event 'hover'
sleep(2)
page.lineadded_element.when_present.right_click
page.unlock_element.when_present.click
sleep(1)
page.lineadded_element.when_present.right_click
page.delhostobject_element.when_present.click
@browser.alert.ok
sleep(1)
page.lineadded_element.exists?.should == false
end
end
And /^I add host "(.+)" of type icon "(.+)" on the map$/ do |object, type|
on ViewPage do |page|
page.map2_element.when_present.click
sleep(3)
page.editmap_element.fire_event 'mouseover'
page.addicon_element.fire_event 'mouseover'
sleep(2)
if type == 'host'
page.addhost_element.when_present.click
page.background_element.when_present(40).click
page.hostname = object
page.enable_z_coordinate_element.when_present.set
page.z_text.clear
page.z_text_element.set "19"
page.chk_label_element.when_present.set
page.chk_label_option_element.when_dom_changed.select "Yes"
page.chk_host_label_element.when_present.set
page.text_host_label_element.when_present.clear
page.text_host_label_element.when_present.set "the-"+object
elsif type == 'map'
page.addmapicon_element.when_present.click
page.background_element.when_present.click
page.mapname = object
end
page.modify_button_element.when_present.click
sleep(5)
end
end
Then /^I clone the object "(.+)"$/ do |object|
on ViewPage do |page|
sleep(3)
page.host_object_add_hover(object)
sleep(2)
#page.hostadded_element.when_present.right_click
page.host_object_right_click(object)
page.unlock_element.when_present.click
page.host_object_right_click(object)
page.clone_element.when_present.click
sleep(2)
page.background_element.fire_event 'click'
sleep(3)
#page.z_text_element.when_present.attribute_value("value") == "29"
page.z_text_element.when_present.attribute_value("value").should == "19"
page.text_host_label_element.when_present.attribute_value("value").should == "the-"+object
page.modify_button_element.when_present.click
sleep(10)
page.lockunlock_element.fire_event('click')
end
end
And /^I delete both the objects "(.+)" added$/ do |object|
on ViewPage do |page|
sleep(5)
2.times do
page.host_object_add_hover(object)
sleep(2)
page.host_object_right_click(object)
page.unlock_element.when_present.click
sleep(1)
page.host_object_right_click(object)
page.delhostobject_element.when_present.click
@browser.alert.ok
sleep(5)
end
end
end
Then /^the map should get renamed to name "(.+)" on the map$/ do |map_name|
on ViewPage do |page|
@browser.frame(:id => /myframe/).img(:alt => "map-"+map_name).exists?.should == true
end
end
And /^I delete "(.+)" icon on map$/ do |map_name|
on ViewPage do |page|
@browser.frame(:id => "myframe").image(:alt => 'map-'+map_name).fire_event 'hover'
@browser.frame(:id => "myframe").image(:alt => 'map-'+map_name).when_present.right_click
page.unlock_element.when_present.click
sleep(1)
@browser.frame(:id => "myframe").image(:alt => 'map-'+map_name).when_present.right_click
page.delhostobject_element.when_present.click
@browser.alert.ok
sleep(5)
@browser.frame(:id => /myframe/).img(:alt => "map-"+map_name).exists?.should == false
end
end
<file_sep>class ReportsPage
include PageObject
direct_url BASE_URL + "reports"
span :page_title, :class => "portlet-titlebar-title", :index => 2
@@subtab_title = { "Performance View" => "Performance Viewer", "Alerts" => "Alerts Report", "Notifications" => "Notifications Report", "Outages" => "Outages Report", "SLA Management" => "SLA Management"}
#@@subtab_text = { "Performance View" => "Performance", "Alerts" => "Show Top Alarms by", "Notifications" => "Show Top Notifications by", "Outages" => "Show Top Measurements by", "SLA Management" => "Service level Management"}
@@subtab_text = { "Performance View" => "Performance Views", "Alerts" => "Show Top Alarms by", "Notifications" => "Show Top Notifications by", "Outages" => "Show Top Measurements by"}
in_frame(:id => 'birtViewer') do |frame|
select :host, :id => 'HostName_selection', :frame => frame
select :host_service_state, :id => 'hostName_selection', :frame => frame
select :service, :id => 'serviceName_selection', :frame => frame
select :hostgroup, :id => 'HostGroupName_selection', :frame => frame
select :hostgroup_events, :id => 'Host Group_selection', :frame => frame
select :host_events, :id => 'Host Name_selection', :frame => frame
select :host_perf, :id => 'Host_selection', :frame => frame
select :perf_indicator, :id => 'PerformanceIndicator_selection', :frame => frame
select :unit, :id => 'Unit_selection', :frame => frame
select :perf_name, :id => 'PerformanceName_selection', :frame => frame
select :host_right_axis, :id => 'HostName_Right_selection', :frame => frame
select :unit_right_axis, :id => 'Unit_Right_selection', :frame => frame
select :perf_name_right_axis, :id => 'PerformanceName_Right_selection', :frame => frame
select :hostgroup_perf, :id => 'HostGroup_selection', :frame => frame
select :hostgroup_name, :id => 'HostGroupName_selection', :frame => frame
select :hostgroup_name_right_axis, :id => 'HostGroupName_Right_selection', :frame => frame
text_field :from_date, :id => 'FromDate', :frame => frame
text_field :to_date, :id => 'ToDate', :frame => frame
text_field :start_date, :id => 'DateStart', :frame => frame
text_field :end_date, :id => 'DateEnd', :frame => frame
end
link :availability_reports, :id => /reportTreePortlet_frmTree:reportTreePortlet_reportTree:0/
link :event_reports, :id => /reportTreePortlet_frmTree:reportTreePortlet_reportTree:1/
link :performance_reports, :id => /reportTreePortlet_frmTree:reportTreePortlet_reportTree:2/
link :status_reports, :id => /reportTreePortlet_frmTree:reportTreePortlet_reportTree:3/
def select_report(report)
if report == 'host availability' || report == 'host state transitions' || report == 'hostgroup availability' || report == 'service state transitions'
if self.availability_reports_element.image(:src =>/tree_nav_middle_close.gif/).exists?
self.availability_reports_element.image(:src =>/tree_nav_middle_close.gif/).when_present.click
self.availability_reports_element.when_present.click
else
self.availability_reports_element.when_present.click
end
@browser.span(:text => report).when_present.click
sleep(5)
elsif report == 'event history' || report == 'event history overview'
if self.event_reports_element.image(:src =>/tree_nav_middle_close.gif/).exists?
self.event_reports_element.image(:src =>/tree_nav_middle_close.gif/).when_present.click
self.event_reports_element.when_present.click
else
self.event_reports_element.when_present.click
end
elsif report == 'epr host' || report == 'epr host multi variable' || report == 'epr hostgroup' || report == 'epr hostgroup multi variable' || report == 'epr hostgroup topfive'
if self.performance_reports_element.image(:src =>/tree_nav_middle_close.gif/).exists?
self.performance_reports_element.image(:src =>/tree_nav_middle_close.gif/).when_present.click
self.performance_reports_element.when_present.click
else
self.performance_reports_element.when_present.click
end
elsif report == 'host status' || report == 'hostgroup status'
if self.status_reports_element.image(:src =>/tree_nav_middle_close.gif/).exists?
self.status_reports_element.image(:src =>/tree_nav_middle_close.gif/).when_present.click
self.status_reports_element.when_present.click
else
self.status_reports_element.when_present.click
end
end
@browser.span(:text => report).when_present.click
@browser.frame(:id => 'birtViewer').div(:id => 'progressBar').table(:id => 'birtviewer_progressbar').wait_while_present
end
def open_report(report)
if report == 'host availability' || report == 'host status'
self.host_element.select('localhost')
elsif report == 'hostgroup availability' || report == 'hostgroup status'
self.hostgroup_element.select('Linux Servers')
elsif report == 'host state transitions'
@browser.frame(:id => 'birtViewer').div(:class => 'birtviewer_parameter_dialog').select(:id => 'hostName_selection').select('localhost')
elsif report == 'service state transitions'
@browser.frame(:id => 'birtViewer').div(:class => 'birtviewer_parameter_dialog').select(:id => 'hostName_selection').select('localhost')
self.service_element.select('tcp_http')
elsif report == 'event history'
self.from_date_element.clear
self.from_date_element.set '2014-01-01 10:00:00'
self.to_date_element.clear
self.to_date_element.set '2014-01-31 10:00:00'
self.hostgroup_events_element.select('Linux Servers')
sleep(3)
self.host_events_element.select('ALL')
elsif report == 'epr host'
self.host_perf_element.select('localhost')
self.perf_indicator_element.when_present.select('tcp_http_size')
elsif report == 'epr host multi variable'
self.host_element.select('localhost')
self.unit_element.when_present.select('http')
self.perf_name_element.when_present.select('tcp_http_size')
self.host_right_axis_element.when_present.select('localhost')
self.unit_right_axis_element.when_present.select('http')
self.perf_name_right_axis_element.when_present.select('tcp_http_size')
elsif report == 'epr hostgroup'
self.hostgroup_perf_element.select('Linux Servers')
self.perf_indicator_element.when_present.select('local_swap_swap')
elsif report == 'epr hostgroup multi variable'
self.hostgroup_name_element.select('Linux Servers')
self.unit_element.when_present.select('sec')
self.perf_name_element.when_present.select('tcp_nsca_time')
self.hostgroup_name_right_axis_element.when_present.select('Linux Servers')
self.unit_right_axis_element.when_present.select('ms')
self.perf_name_right_axis_element.when_present.select('tcp_gw_listener_time')
elsif report == 'epr hostgroup topfive'
self.hostgroup_perf_element.select('Linux Servers')
self.perf_indicator_element.when_present.select('tcp_nsca_time')
end
@browser.frame(:id => 'birtViewer').div(:id => 'parameterDialogokButton').button(:title => 'OK').when_present.click
sleep(10)
end
def verify_report(report)
if report == 'host availability'
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_4').text.include? ('Host Availability Report')
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_9').text.include? ('Host Service Availability')
elsif report == 'host state transitions'
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_4').text.include? ('GroundWork Host State Transitions Report')
elsif report == 'hostgroup availability'
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_4').text.include? ('HostGroup Availability for Host and Services')
elsif report == 'service state transitions'
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_4').text.include? ('GroundWork Service State Transitions Report')
elsif report == 'host status'
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_6').text.include? ('Host Status')
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_7').text.include? ('Host Service Status Summary')
elsif report == 'hostgroup status'
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_4').text.include? ('Host And Service Status')
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_6').text.include? ('Host Group Service Status')
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_7').text.include? ('Host Group Host Status')
elsif report == 'event history'
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_5').text.include? ('Event History Report')
elsif report == 'event history overview'
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_4').text.include? ('Event History Overview Report')
elsif report == 'epr host multi variable' || report == 'epr hostgroup multi variable'
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_3').text.include? ('Enterprise Performance Report')
elsif report == 'epr host' || report == 'epr hostgroup topfive'
@browser.frame(:id => 'birtViewer').div(:id => 'AUTOGENBOOKMARK_4').text.include? ('GroundWork Enterprise Performance Report')
end
end
def go_to_subtab(subtab)
@browser.link(:text => /Reports/).fire_event 'mouseover'
@browser.link(:text => /#{subtab}/).when_present.click
end
def check_subtab(subtab)
self.wait_until(10) do
@browser.text.include? @@subtab_title[subtab]
if subtab == "Performance View"
@browser.frame(:id => "myframe").frame(:name => "perfchart_left").td(:class => /menu_head/).text.include? @@subtab_text[subtab]
elsif subtab == "SLA Reports"
@browser.div(:id => /content/).button(:value => /Website Report/).when_present.click
elsif subtab == "BIRT Report Viewer"
@browser.div(:id => /iceTreeRow/).link(:id => "reportTreePortlet_frmTree:reportTreePortlet_reportTree:0").when_present.click
else
@browser.frame(:id => "myframe").div(:id => "container").text.include? @@subtab_text[subtab]
end
end
end
end
<file_sep>When /^I apply the filter "(.+)" under Applications$/ do |apptype|
on EventconsolePage do |page|
@browser.div(:class => "iceTreeRow", :index => 1).link(:index => 0).when_present.click
sleep(10)
@browser.link(:text => "#{apptype}").when_present.click
sleep(5)
page.wait_until(20) do
page.events_application_types_element.when_present.text == "Events by ApplicationTypes="+apptype
end
end
end
When /^I apply the filter "(.+)"$/ do |filter|
on EventconsolePage do |page|
#page.criticals_element.when_present.click
@browser.link(:text => "#{filter}").when_present.click
page.wait_until(20) do
if filter == "All Events"
page.events_application_types_element.when_dom_changed.text == "All Events"
else
page.events_application_types_element.when_dom_changed.text == "Events by=" + filter
end
end
end
end
When /^I select (\d+) event$/ do |arg1|
on EventconsolePage do |page|
page.number_showing_events_element.when_present.text.to_i.should >= 1
#cell = @browser.tr(:class => "iceDatTblRow portlet-section-body Row textRow odd iceRowSel")
cell = @browser.tr(:id => /contentPanel:icepnltabset:0:eventTableID:0/)
span_message = cell.span(:id => /txt_textMessage/)
$message = span_message.text
$message = $message[0...-5]
span_message.when_present.click
sleep(4)
end
end
When /^I perform the action open log message$/ do
on EventconsolePage do |page|
sleep(3)
page.open_log_message_element.when_present.click
@browser.text_field(:name => /popupform:j_id208/).when_present.set "Comment"
@browser.button(:name => /popupform:closeInputModal/).click
sleep(5)
end
end
When /^I navigate to operation status open filter$/ do
on EventconsolePage do |page|
puts "Message #{$message}"
page.operation_status_events_open_element.when_present.click
page.open_filter_element.when_present.click
page.message_search = $message
page.search_element.when_present.click
sleep(10)
end
end
When /^I perform the action close log message$/ do
#visit EventconsolePage
on EventconsolePage do |page|
sleep(3)
page.close_log_message_element.when_present.click
@browser.text_field(:name => /popupform:j_id208/).when_present.set "Comment"
@browser.button(:name => /popupform:closeInputModal/).click
sleep(5)
end
end
When /^I navigate to operation status close filter$/ do
on EventconsolePage do |page|
puts "Message #{$message}"
page.operation_status_events_open_element.when_present.click
page.close_filter_element.when_present.click
page.message_search = $message
page.search_element.when_present.click
sleep(10)
end
end
Then /^the events selected must be display$/ do
on EventconsolePage do |page|
page.number_showing_events_element.when_present.text.to_i.should >= 1
$message_new = @browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_textMessage/).text
$message_new = $message_new[0...-5]
$message_new.should == "#{$message}"
end
end
Given /^I select all open events$/ do
on EventconsolePage do |page|
page.all_open_events_element.when_present.click
end
end
Given /^I search for the events with the message "(.*?)"$/ do |message|
on EventconsolePage do |page|
sleep(5)
page.message_search = message
end
end
And /^I click the Search button$/ do
on EventconsolePage do |page|
page.search_link_element.when_dom_changed.click
sleep(5)
end
end
Then /^I should only see events with the message "(.+)"$/ do |message|
on EventconsolePage do |page|
page.check_events_message(message, 0)
end
end
And /^I click on the new tab button$/ do
on EventconsolePage do |page|
page.new_tab_element.click
sleep(5)
end
end
Then /^I see the window for new tab$/ do
=begin
on EventconsolePage do |page|
page.wait_until do
sleep(5)
@browser.span(:class => "iceOutTxt", :text => "All Open Events", :index => 1).exists?
end
end
=end
@browser.span(:class => "iceOutTxt", :text => "All Events").when_dom_changed.exists?
end
And /^I search for the events with the message "(.*?)" on the new tab$/ do |message|
on EventconsolePage do |page|
page.message_search = message
end
end
Then /^I should only see events with the message "(.+)" on the new tab$/ do |message|
on EventconsolePage do |page|
page.check_events_message(message, 1)
end
end
Given /^I am on Services Configuration page$/ do
visit ServiceConfigurationPage
end
Given /^I modify max check attempts and disable active checks in generic services$/ do
on ServiceConfigurationPage do |page|
page.open_generic_service
page.set_max_check_attempts
end
end
Given /^I am on Host Configuration page$/ do
visit HostsConfigurationPage
end
Given /^I modify max check attempts and disable active checks in generic hosts$/ do
on HostsConfigurationPage do |page|
page.open_generic_host
on ServiceConfigurationPage do |page|
page.set_max_check_attempts
end
end
end
Given /^I revert max check attempts and disable active checks in generic hosts$/ do
on HostsConfigurationPage do |page|
page.open_generic_host
on ServiceConfigurationPage do |page|
page.reset_max_check_attempts
end
end
end
Given /^I select a host and a service$/ do
on StatusviewerPage do |page|
#page.services_link
#page.open_servicegroup_element.when_present.click
#$hostname = page.get_host(0)
#page.hosts_link
#page.select_host("HG1", $hostname, "Linux Servers")
#sleep(1)
@browser.span(:class => "iceOutTxt", :text => /Linux Servers/).when_dom_changed.click
@browser.span(:class => "iceOutTxt", :text => /localhost/).when_dom_changed.click
sleep(1)
page.local_cpu_httpd_element.when_dom_changed.click
end
end
Given /^I select submit passive Check Result with "(.*?)"$/ do |state|
on StatusviewerPage do |page|
sleep(5)
page.submit_check_results_service(state)
sleep(15)
end
end
When /^I submit and navigate to Event Console$/ do
on StatusviewerPage do |page|
page.submit_button_service_element.when_dom_changed.click
end
sleep(15)
visit EventconsolePage
end
Then /^I see an event gets displayed with status as "(.+)"$/ do |status|
on EventconsolePage do |page|
page.check_event_status($hostname, status)
end
end
Given /^I select submit host passive Check Result with "(.*?)"$/ do |state|
on StatusviewerPage do |page|
sleep(10)
page.submit_check_results_host(state)
end
end
#@new TCs
#Verify updation of tab label
And /^I enter a new tab name "(.+)"$/ do |tab_name|
on EventconsolePage do |page|
page.update_label = tab_name
page.update_button_element.click
end
end
Then /^the tab name gets updated as "(.+)"$/ do |tab_name|
on EventconsolePage do |page|
#page.wait_until(20) do
#page.events_application_types_element.when_present.text == "Test Tab"
#@browser.span(:text => tab_name).exists?.should == true
#end
@browser.span(:text => tab_name).when_present(10).exists?.should == true
end
end
And /^I revert the change to the tab made above$/ do
on EventconsolePage do |page|
page.all_events_element.when_present.click
end
end
#verify running blank search
And /^I run a blank search$/ do
on EventconsolePage do |page|
page.search_element.when_dom_changed.click
sleep(2)
end
end
Then /^an error message for running blank search is generated$/ do
on EventconsolePage do |page|
page.error_message_element.when_dom_changed.exists?
page.error_ok_element.click
end
end
#updation of tab label with an invalid name
Then /^I enter an invalid tab name$/ do
on EventconsolePage do |page|
page.update_label = '!@#$^&*()'
page.update_button_element.click
end
end
Then /^an error message gets generated$/ do
on EventconsolePage do |page|
#error message validation
end
end
Then /^the tab name does not get updated$/ do
on EventconsolePage do |page|
#tab name validation
end
end
#verify acknowledging an Nagios event
And /^I select the Actions button$/ do
on EventconsolePage do |page|
page.actions_element.click
end
end
And /^I select the Nagios Acknowledge option and fill in the acknowledge comment as "(.+)"$/ do |comment|
on EventconsolePage do |page|
#selecting the Nagios Acknowledge option
page.actions_element.click
page.nagios_ack_element.click
sleep(5)
#filling in the comment and submitting
#page.nagios_ack_comment_element = "Nagios Event Acknowledged by QA"
#@browser.div(:class => /icePnlPop/).td(:class => "icePnlGrdCol1 Col1 popupModalBodyCol1").textarea(:id => /iceInpTxtArea portlet-form-input-field popupText/).set "Nagios Event Acknowledged by QA"
#@browser.div(:class => /icePnlPop/).textarea(:id => /iceInpTxtArea portlet-form-input-field popupText/, :name => /:popupform:j_id/).set "Nagios Event Acknowledged by QA"
#@browser.textarea(:id=> 'G005c7bb8_2d847a_2d4467_2d9dc5_2d4d3aebb5f4ad:popupform:j_id199').set "Nagios Event Acknowledged by QA"
#@browser.textarea(:name => /popupform:j_id199/).set "Nagios Event Acknowledged by QA"
#@browser.textarea(:name => /popupform:j_id199/, :class => /iceInpTxtArea portlet-form-input-field popupText/).set comment
@browser.textarea(:name => /popupform:j_id/, :class => /iceInpTxtArea portlet-form-input-field popupText/).set comment
page.nagios_ack_comment_button_element.click
sleep(5)
end
end
Then /^I see acknowledgement comment "(.+)" gets updated in the comment column of event$/ do |comment|
@browser.refresh
sleep(6)
@browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_acknowledgeComment/).text == comment
puts "Comment on Console: "[email protected](:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_acknowledgeComment/).text
end
When /^I apply the filter All Events$/ do
on EventconsolePage do |page|
page.all_events_element.when_present.click
sleep(5)
end
end
And /^I search a device "(.+)"$/ do |device|
on EventconsolePage do |page|
page.device = device
page.search_link_element.click
sleep(3)
end
end
Then /^I see all the events of device "(.+)" only are displayed$/ do |device|
text11 = @browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:0:j_id/).text.include?(device)
#on EventconsolePage do |page|
#thetext = page.hosts_displayed_element.when_present.text.include?('bsm-host')
#end
puts text11
end
#accepting log messages on event console
When /^I perform the action accept log message$/ do
on EventconsolePage do |page|
sleep(3)
page.accept_log_message_element.when_present.click
@browser.text_field(:name => /popupform:j_id208/).when_present.set "Comment"
@browser.button(:name => /popupform:closeInputModal/).click
sleep(5)
end
end
When /^I navigate to operation status "(.+)" filter$/ do |filter|
on EventconsolePage do |page|
puts "Message #{$message}"
if $message.include? "...."
puts $message.slice "...."
$message["...."]= ""
end
if filter == "accepted"
page.operation_status_events_open_element.when_present.click
page.operation_status_events_accepted_element.when_present.click
elsif filter == "notified"
page.operation_status_events_open_element.when_present.click
page.operation_status_events_notified_element.when_present.click
end
sleep(2)
page.message_search = $message
page.search_element.when_present.click
sleep(10)
end
end
When /^I revert the changes$/ do
on EventconsolePage do |page|
page.applications_events_element.when_present.click
page.operation_status_events_open_element.when_present.click
sleep(2)
end
end
#notifying log messages on event console
When /^I perform the action notify log message$/ do
on EventconsolePage do |page|
sleep(3)
page.notify_log_message_element.when_present.click
@browser.text_field(:name => /popupform:j_id208/).when_present.set "Comment"
@browser.button(:name => /popupform:closeInputModal/).click
sleep(5)
end
end
#Verify functionality of Reset button
When /^I fill in some values in textboxes and dropdowns$/ do
on EventconsolePage do |page|
page.device = "bsm-host"
page.message_search = "CRITICAL"
page.severity_search = "UNREACHABLE"
page.opstatus_search = "OPEN"
page.monstatus_search = "UNKNOWN"
end
end
When /^I select the Reset button$/ do
on EventconsolePage do |page|
page.reset_element.when_present.click
sleep(5)
end
end
Then /^all fields should get cleared$/ do
on EventconsolePage do |page|
# dev_val = String.new
# dev_val = page.device_element.attribute_value("value")
# puts dev_val
page.device_element.attribute_value("value") == ""
page.message_search_element.attribute_value("value") == ""
page.severity_search_element.attribute_value("value") == /Any/
page.opstatus_search_element.attribute_value("value") == /Any/
page.monstatus_search_element.attribute_value("value") == /Any/
end
end
#For Scenario: Generating event from Nagios and verifying on Event Console
#below given step navigates user to the "Service Status Details For All Hosts" page under Nagios.
Given /^I am on Nagios Service Status Details page$/ do
visit NagiosServiceStatusDetailsPage
end
When /^I select the service "(.+)" of host "(.+)"$/ do |service,host|
service_href = "extinfo.cgi?type=2&host="+host+"&service="+service
on NagiosServiceStatusDetailsPage do |page|
#page.localhost_local_cpu_httpd_element.when_present.click
#@browser.link(:href => service_href).when_present.click
#@browser.link(:href => service_href, :text => service).when_present.click
#@browser.table(:class => /status/).link(:href => service_href).when_present.click
@browser.table(:class => /status/).link(:href => service_href, :text => service).when_present.click
end
end
And /^I submit passive check result for "(.+)" "(.+)" with "(.+)"$/ do |host,service,status|
on NagiosServiceStatusDetailsPage do |page|
#if
#<EMAIL>.link(:text => /Submit passive check result/).exists?.should == true
#<EMAIL>.table(:class => 'command').td(:class => 'command').link(:text => /Submit passive check/).exists?.should == true
#@browser.td(:class => 'command').link(:text => /Submit passive check/).exists?.should == true
#page.passive_check_result_element.when_present.click
#<EMAIL>(:class => 'command').td(:class => 'command').link(:text => /Submit passive check/).when_present.click
#@browser.td(:class => 'command').link(:text => /Submit passive check/).when_present.click
#@browser.goto 'http://qa-rhel-6-64.groundwork.groundworkopensource.com/nagios-app/cmd.cgi?cmd_typ=30&host=localhost&service=local_cpu_httpd'
#@browser.goto submit_passive_check_result_url
#page.goto submit_passive_check_result_url
#end
# The following is the function defined in NagiosServiceStatusDetailsPage which
# navigates to the page where plugin state and output have to be submitted.
page.goto_nagios_service_url(host,service)
sleep(5)
@browser.table(:class => /optBox/).td(:class => /optBoxItem/).table(:class => /optBox/).select(:name => /plugin_state/).select status
page.check_output = "Passive check result submitted by QA"
page.perf_data = "Passive check result submitted by QA"
page.commit_element.when_present.click
sleep(10)
end
end
Then /^I see an event in "(.+)" status is generated on Event Console page$/ do |status|
on EventconsolePage do |page|
sleep(5)
page.all_events_element.when_present.click
sleep(2)
page.number_showing_events_element.when_present.text.to_i.should >= 1
@browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_monitorStatus/, :text => /#{status}/).when_dom_changed.exists?.should == true
end
end
When /^I search for the events by severity and OpStatus and MonStatus$/ do
on EventconsolePage do |page|
page.severity_search = "OK"
page.opstatus_search = "OPEN"
page.monstatus_search = "UP"
sleep(3)
end
end
#####################################################################################################
#####################################################################################################
#for Verify if actions taken in console of User1 show up for other logged in users
Given /^I logout of GW portal$/ do
on DashboardPage do |page|
sleep(5)
page.logout
sleep(5)
end
end
Then /^I should see event is generated of host "(.+)" in status "(.+)"$/ do |host,status|
on EventconsolePage do |page|
sleep(10)
page.all_events_element.when_present.click
sleep(2)
page.number_showing_events_element.when_present.text.to_i.should >= 1
@browser.refresh()
sleep(5)
@browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_monitorStatus/).text.should == "DOWN"
puts "Event Generated on Event Console: "+host+" -- "[email protected](:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_monitorStatus/).text
end
end
#for Verify System Filter and Public Filter panes are collapsible
When /^I click On "(.+)" pane heading$/ do |filter|
#@browser.div(:id => /naviPanel:panelSystemFilter/).span(:text => filter).when_present.click
@browser.div(:class => /icePnlGrp sideBarWrapper/).span(:text => filter).when_present.click
sleep(4)
end
When /^I verify (.+) pane has collapsed$/ do |filter|
if filter=="System Filters"
@browser.link(:text => /Applications/).exists?.should == false
elsif
@browser.link(:text => "All Events").exists?.should == false
end
end
# for Verify the list of host groups displayed under HostGroups under System Filter
When /^I make a list of all the "(.+)" currently present$/ do |group|
if group =="Host Groups"
id_count=0
$hg = Array.new
hg_span_id = "frmTree:pnlTbSet:0:hstTree:n-0:TxtNdClick"
while @browser.span(:id => hg_span_id).exists?
group_name = @browser.span(:id => hg_span_id).text
$hg << group_name
id_count += 1
hg_span_id="frmTree:pnlTbSet:0:hstTree:n-"+id_count.to_s+":TxtNdClick"
end
puts "HGs present are: "
$hg.each do |hg|
puts hg
end
else
on StatusviewerPage do |page|
page.services_tab_element.when_present.click
end
sleep(4)
id_count=0
$sg = Array.new
sg_span_id = "frmTree:pnlTbSet:0:treeSrvc:n-0:TxtNdClick"
while @browser.span(:id => sg_span_id).exists?
group_name = @browser.span(:id => sg_span_id).text
$sg << group_name
id_count += 1
sg_span_id="frmTree:pnlTbSet:0:treeSrvc:n-"+id_count.to_s+":TxtNdClick"
end
puts "SGs present are: "
$sg.each do |sg|
puts sg
end
end
end
When /^I verify each "(.+)" present on Status Viewer is also visible on Event Console$/ do |group|
if group =="hostgroup"
@browser.div(:class => /icePnlGrp sideBarWrapper/).link(:id => /naviPanel:systemFilterTree:1/).when_present.click
sleep(3)
$hg.each do |hg|
@browser.div(:class => /icePnlGrp sideBarWrapper/).link(:text => hg).exists?.should == true
end
puts "All HostGroups present on Event Console."
else
@browser.div(:class => /icePnlGrp sideBarWrapper/).link(:id => /naviPanel:systemFilterTree:2/).when_present.click
sleep(3)
$sg.each do |sg|
@browser.div(:class => /icePnlGrp sideBarWrapper/).link(:text => sg).exists?.should == true
end
puts "All ServiceGoups present on Event Console."
end
end
# for Verify the functionality of Resume/Pause Incoming Events
When /^I select All Events filter$/ do
@browser.link(:text => /All Events/).click
sleep(10)
end
When /^verify that events have been stopped$/ do
@browser.link(:text => /Resume Incoming Events/).exists?.should == true
end
When /^I open a new browser window and generate an event "(.+)" for "(.+)"$/ do |state,host|
browser = Watir::Browser.new
browser.driver.manage.window.maximize
#@browser2.goto StatusviewerPage
#@browser2.goto BASE_URL + "status"
#@browser.window(:title =>/status/).when_present.use
#@browser.window(:id =>/newtab-window/).when_present.use
#@browser.window(:title =>/New Tab/).when_present.use
browser.goto BASE_URL + "status"
browser.text_field(:name => /josso_username/).set "admin"
browser.text_field(:name => /josso_password/).set "<PASSWORD>"
browser.button(:value => /Login/).click
sleep(5)
browser.goto BASE_URL + "status"
sleep(3)
browser.div(:id => /divContents/).span(:text => /Linux Servers/).when_present.click
sleep(3)
browser.div(:id => /divContents/).span(:text => host).when_present.click
sleep(3)
browser.span(:text => /Check Results/).click
sleep(1)
browser.span(:text => /Submit Passive Check Result/).click
sleep(4)
browser.select(:name => /HVform:actionsPortlet_menuCheckResult/).select state
browser.text_field(:name => /HVform:actionsPortlet_txtCheckOutputValue/).set state+" from window 2"
browser.text_field(:name => /HVform:actionsPortlet_txtPerformanceDataValue/).set state+" from window 2"
browser.button(:name => /HVform:actionsPortlet_btnSubmit/).click
sleep(5)
browser.close
end
Then /^verify no new event is populated for "(.+)" in state "(.+)"$/ do |host,state|
@browser.window(:title =>/console/).use
event_status_span_id = "contentPanel:icepnltabset:0:eventTableID:0:txt_monitorStatus"
event_name_span_id = "contentPanel:icepnltabset:0:eventTableID:0:j_id226"
id_count=0
while @browser.span(:id => event_status_span_id).exists?
if @browser.span(:id => event_status_span_id).text == state
@browser.span(:id => event_name_span_id).text != host
end
id_count += 1
event_status_span_id = "contentPanel:icepnltabset:0:eventTableID:"+id_count.to_s+":txt_monitorStatus"
event_name_span_id = "contentPanel:icepnltabset:0:eventTableID:"+id_count.to_s+":j_id226"
end
end
When /^I Resume Incoming Events$/ do
sleep(10)
@browser.link(:text => /Resume Incoming Events/).when_present.click
@browser.refresh
end
Then /^I verify that that new events are populated for "(.+)" in state "(.+)"$/ do |host,state|
if host=="localhost"
host="127.0.0.1"
end
event_name_span_id = "contentPanel:icepnltabset:0:eventTableID:0:j"
event_message_span_id = "contentPanel:icepnltabset:0:eventTableID:1:txt_textMessage"
id_count=0
puts @browser.div(:class => "tableWrapper").span(:id => event_name_span_id).text
=begin
while @browser.div(:class => "tableWrapper").span(:id => event_name_span_id).text == host
if @browser.span(:id => event_name_span_id).text == host
@browser.span(:id => event_message_span_id).text == state+" from window 2"
puts "Event generated for "+host+"in state "+state
end
id_count += 1
event_name_span_id = "contentPanel:icepnltabset:0:eventTableID:"+id_count.to_s+":j"
event_message_span_id = "contentPanel:icepnltabset:0:eventTableID:"+id_count.to_s+":txt_textMessage"
end
=end
=begin
event_name_span_id = "contentPanel:icepnltabset:0:eventTableID:0:j_id226"
event_message_span_id = "contentPanel:icepnltabset:0:eventTableID:1:txt_textMessage"
id_count=0
while @browser.span(:id => event_name_span_id).exists?
if @browser.span(:id => event_name_span_id).text == host
@browser.span(:id => event_message_span_id).text == state+" from window 2"
puts "Event generated for "+host+"in state "+state
end
id_count += 1
event_name_span_id = "contentPanel:icepnltabset:0:eventTableID:"+id_count.to_s+":j_id226"
event_message_span_id = "contentPanel:icepnltabset:0:eventTableID:"+id_count.to_s+":txt_textMessage"
end
=end
end
And /^I select the Show Event Tile link$/ do
on EventconsolePage do |page|
page.show_event_tile_link_element.when_present.click
end
end
And /^I select the host group "(.+)"$/ do |group|
sleep(3)
if group== "Linux Servers"
group= "filterValue=Linux"
elsif
group= "filterValue="+group
end
#@browser.link(:href => /#{group}/).image(:alt => //).when_present.click
@browser.link(:href => /#{group}/).image(:src => /portal-statusviewer/).when_present.click
#@browser.td(:class => /icePnlPopBody/).link(:href => /#{group}/).image(:alt => //).when_present.click
#@browser.div(:id => /eventTileForm:icePnlSrsConsole/).link(:href => /#{group}/).image(:alt => //).when_present.click
#@browser.div(:id => /eventTileForm/).link(:href => /#{group}/).image(:alt => //).when_present.click
#@browser.div(:id => /eventTileForm/, :class => /icePnlSrs/).link(:href => /#{group}/).image(:alt => //).when_present.click
#@browser.div(:name => /eventTileForm:popupEventTileDiv/).link(:href => /#{group}/).image(:alt => //).when_present.click
end
Then /^I see all events of host "(.+)" only are displayed$/ do |host|
sleep(3)
event_host_div_id = "contentPanel:icepnltabset:0:eventTableID:0:pnl_host"
row = @browser.table(:id => /eventTableID/).rows.length
puts "Rows in table: "+row.to_s
for i in 1..row-1
host_found = @browser.table(:id => /eventTableID/).div(:id => /#{event_host_div_id}/).link(:href => /#{host}/).span(:text => /#{host}/).exists?
if host_found == true
puts "Verified for host : "+host
event_host_div_id = "contentPanel:icepnltabset:0:eventTableID:"+i.to_s+":pnl_host"
else
puts "Failed!"
puts i
raise
end
end
end
Given /^I am on the Dashboard Enterprise View page$/ do
@browser.goto BASE_URL + "dashboard/enterprise"
end
And /^I select the group "(.+)" from the "(.+)" filter$/ do |group,type|
sleep(3)
if type== "HostGroups"
@browser.div(:class => /icePnlGrp sideBarWrapper/).link(:id => /naviPanel:systemFilterTree:1/).when_present.click
elsif type == "ServiceGroups"
@browser.div(:class => /icePnlGrp sideBarWrapper/).link(:id => /naviPanel:systemFilterTree:2/).when_present.click
end
sleep(3)
@browser.div(:class => /icePnlGrp sideBarWrapper/).link(:text => /#{group}/).when_present.click
end
Then /^I see all events of service "(.+)" only are displayed$/ do |service|
sleep(3)
event_service_div_id = "contentPanel:icepnltabset:0:eventTableID:0:pnl_serviceDescription"
row = @browser.table(:id => /eventTableID/).rows.length
puts "Rows in table: "+row.to_s
for i in 1..row-1
service_found = @browser.table(:id => /eventTableID/).div(:id => /#{event_service_div_id}/).link(:href => /#{service}/).span(:text => /#{service}/).exists?
if service_found == true
puts "Verified for service : "+service
event_service_div_id = "contentPanel:icepnltabset:0:eventTableID:"+i.to_s+":pnl_serviceDescription"
else
puts "Failed!"
puts i
raise
end
end
end
#acknowledging, notifying, accepting , closing and opening
And /^I select the "(.+)" button on Event Console$/ do |action|
sleep(3)
@browser.link(:text => action).when_present.click
=begin
if action== "Acknowledge"
@browser.link(:text => "Acknowledge").when_present.click
elsif action== "Notify"
@browser.link(:text => "Notify").when_present.click
elsif action== "Accept"
@browser.link(:text => "Accept").when_present.click
elsif action== "Close"
@browser.link(:text => "Close").when_present.click
elsif action== "Open"
@browser.link(:text => "Open").when_present.click
end
=end
sleep(2)
end
And /^I fill in the comment as "(.+)"$/ do |comment|
on EventconsolePage do |page|
#filling in the comment and submitting
@browser.textarea(:name => /popupform:j_id/, :class => /iceInpTxtArea portlet-form-input-field popupText/).set comment
page.nagios_ack_comment_button_element.click
sleep(5)
end
end
Then /^I see comment "(.+)" gets updated in the comment column of "(.+)"$/ do |comment,event|
@browser.refresh
sleep(5)
on EventconsolePage do |page|
if event == "NAGIOS"
#@browser.div(:id => /contentPanel:icepnltabset:0:eventTableID:3:pnl_acknowledgeComment/).span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_acknowledgeComment/, :text => /#{comment}/).exists?.should == true
if comment == "Acknowledged"
comment_console= @browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_acknowledgeComment/, :class => /iceOutTxt/).text
comment_console.should include(comment)
#@browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_acknowledgeComment/, :class => /iceOutTxt/, :text => /#{comment}/).exists?.should == true
elsif comment == "Notified"
page.operation_status_events_open_element.when_present.click
page.operation_status_events_notified_element.when_present.click
comment_console= @browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_Comments/).when_present.text
elsif comment == "Closed"
page.operation_status_events_open_element.when_present.click
page.close_filter_element.when_present.click
comment_console= @browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_Comments/).when_present.text
elsif comment == "Opened"
page.operation_status_events_open_element.when_present.click
page.open_filter_element.when_present.click
comment_console= @browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_Comments/).when_present.text
puts "Comment on Console: "+comment_console
elsif comment == "Accepted"
page.operation_status_events_open_element.when_present.click
page.operation_status_events_accepted_element.when_present.click
comment_console= @browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_Comments/).when_present.text
end
comment_console.should include(comment)
puts "Comment on Console: "+comment_console
else
#@browser.span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_Comments/, :text => /#{comment}/).exists?.should == true
@browser.div(:id => /contentPanel:icepnltabset:0:eventTableID:0:pnl_Comments/).span(:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_Comments/, :text => /#{comment}/).exists?.should == true
puts "Comment on Console: "[email protected](:id => /contentPanel:icepnltabset:0:eventTableID:0:txt_Comments/).text
end
end
end
<file_sep>#This is the script that we are going to use to take the time
require 'watir-webdriver'
include Selenium
#capabilities = WebDriver::Remote::Capabilities.firefox(:javascript_enabled => true, :platform=>:any)
#browser = Watir::Browser.new(:remote, :url => "http://qa-jenkins-server:4444/wd/hub", :desired_capabilities => capabilities)
browser = Watir::Browser.new :firefox
5.times do
browser.goto "http://qa-sles-11-64.groundwork.groundworkopensource.com/portal/auth/portal/groundwork-monitor"
browser.text_field(:name => 'josso_username').set 'admin'
browser.text_field(:name => 'josso_password').set '<PASSWORD>'
browser.button(:value => 'Login').click
browser.link(:text => "Status").when_present.click
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-0:TxtNdClick").when_present.click
browser.span(:id => "HGVform:eventHeader").when_present.click
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-0-0:TxtNdClick").when_present.click
browser.span(:id => "HVform:hostAvailHeader").when_present.click
browser.span(:id => "HVform:servicelistHeader").when_present.click
browser.span(:id => "HVform:eventHeader").when_present.click
browser.span(:id => "HVform:commentsHeader").when_present.click
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-0-0-0:TxtNdClick").when_present.click
browser.span(:id => "SVform:serviceAvailHeader").when_present.click
browser.span(:id => "SVform:eventHeader").when_present.click
#Abrir el segundo host group itmon-win
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-0-1:TxtNdClick").when_present.click
#Abrir linux servers -localhosts - algun servicio
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-1:TxtNdClick").when_present.click
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-1-0:TxtNdClick").when_present.click
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-1-0-1:TxtNdClick").when_present.click
#Volver a abrri algun host de HG1
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-0-6:TxtNdClick").when_present.click
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-0-7:TxtNdClick").when_present.click
#Volver a abrir linux servers - localhosts - algun servicio
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-1-0:TxtNdClick").when_present.click
browser.span(:id => "frmTree:pnlTbSet:0:hstTree:n-1-0-7:TxtNdClick").when_present.click
#Logout
browser.link(:text => /Log Out/).when_present.click
end
browser.close
| 8d8cf8b748d5f8818719db64c07347e515ebf23e | [
"Python",
"Ruby",
"Shell"
]
| 67 | Ruby | shubhamg2-optimus/xyz | 14a95ed58bbd38e0226d17b118ee956a45695f66 | ef538367e68b1ec7524ff17d010fa5a76c648051 |
refs/heads/master | <repo_name>msk-access/biometrics<file_sep>/biometrics/minor_contamination.py
import os
import pandas as pd
import numpy as np
import plotly.graph_objects as go
class MinorContamination():
"""
Minor contamination.
"""
def __init__(self, threshold):
self.threshold = threshold
def to_dataframe(self, samples):
data = pd.DataFrame(
columns=['sample_name', 'sample_group', 'sample_sex', 'sample_type',
'total_homozygous_sites', 'n_contributing_sites', 'minor_contamination'])
for sample_name, sample in samples.items():
row = {
'sample_name': sample.sample_name,
'sample_group': sample.sample_group,
'sample_sex': sample.sample_sex,
'sample_type': sample.sample_type,
'total_homozygous_sites': sample.metrics['minor_contamination']['n_homozygous_sites'],
'n_contributing_sites': sample.metrics['minor_contamination']['n_contributing_sites'],
'minor_contamination': sample.metrics['minor_contamination']['val']
}
data = data.append(row, ignore_index=True)
data = data.sort_values('minor_contamination', ascending=False)
return data
def plot(self, samples, outdir):
"""
Plot major contamination data.
"""
data = self.to_dataframe(samples)
data['minor_contamination'] = data['minor_contamination'].map(
lambda x: round(x, 5))
fig = go.Figure()
fig.add_trace(
go.Bar(
x=data['sample_name'],
y=data['minor_contamination'],
customdata=data.to_numpy(),
hovertemplate='<b>Sample group:</b> %{customdata[1]}' +
'<br><b>Sample name:</b> %{customdata[0]}' +
'<br><b>Sample sex:</b> %{customdata[2]}' +
'<br><b>Sample type:</b> %{customdata[3]}' +
'<br><b>Total homozygous sites:</b> %{customdata[4]}' +
'<br><b>Total contributing sites:</b> %{customdata[5]}' +
'<br><b>Minor contamination:</b> %{y:E}' +
'<extra></extra>'))
fig.update_layout(
yaxis_title="Minor contamination",
title_text="Minor contamination across samples")
fig.add_hline(y=self.threshold, line_color='red')
fig.write_html(os.path.join(outdir, 'minor_contamination.html'))
# plot VAF of contributing sites
plot_data = []
samples_with_contributing_sites = []
for i, sample_name in enumerate(data['sample_name']):
contributing_sites = samples[sample_name].metrics['minor_contamination']['contributing_sites']
if len(contributing_sites) > 0:
samples_with_contributing_sites.append(sample_name)
for site_id, site_data in contributing_sites.items():
site_data['sample_name'] = sample_name
site_data['MAF'] = site_data['minor_allele_freq']
site_data['index'] = i
plot_data.append(site_data)
plot_data = pd.DataFrame(plot_data)
fig = go.Figure()
if len(plot_data) > 0:
plot_data = plot_data[[
'sample_name', 'chrom', 'pos', 'ref', 'alt', 'MAF', 'reads_all', 'A', 'C', 'T', 'G',
'N', 'index']]
plot_data['MAF'] = plot_data['MAF'].map(lambda x: round(x, 5))
fig.add_trace(
go.Scatter(
x=plot_data['index'],
y=plot_data['MAF'],
mode='markers',
showlegend=False,
customdata=plot_data.to_numpy(),
hovertemplate='<b>Sample:</b> %{customdata[0]}' +
'<br><b>Chrom:</b> %{customdata[1]}' +
'<br><b>Pos:</b> %{customdata[2]}' +
'<br><b>Ref allele:</b> %{customdata[3]}' +
'<br><b>Alt allele:</b> %{customdata[4]}' +
'<br><b>MAF:</b> %{customdata[5]}' +
'<br><b>Total reads:</b> %{customdata[6]}' +
'<br><b>Count A:</b> %{customdata[7]}' +
'<br><b>Count C:</b> %{customdata[8]}' +
'<br><b>Count T:</b> %{customdata[9]}' +
'<br><b>Count G:</b> %{customdata[10]}' +
'<br><b>Count N:</b> %{customdata[11]}' +
'<extra></extra>'))
data = data[data['sample_name'].isin(samples_with_contributing_sites)]
data['index'] = range(len(data))
for i in data.index:
fig.add_shape(go.layout.Shape(
type="line",
x0=data.at[i, 'index'] - 0.5,
y0=data.at[i, 'minor_contamination'],
x1=data.at[i, 'index'] + 0.5,
y1=data.at[i, 'minor_contamination'],
line=dict(color='black', width=2)
))
fig.add_trace(go.Scatter(
x=[1],
y=[3],
name='Minor contamination',
line_color='black'
))
fig.add_trace(go.Scatter(
x=[1],
y=[3],
name='Threshold',
line_color='red'
))
fig.add_trace(go.Scatter(
x=[1],
y=[3],
name='Minor allele sites (MAF > 0)',
line_color='#636EFA',
mode='markers'
))
if len(plot_data) > 0:
fig.update_layout(yaxis = dict(range=(-0.005, plot_data['MAF'].max()*1.05)))
ticks = data[['sample_name', 'index']].drop_duplicates()
fig.update_layout(
yaxis_title="Minor allele frequency",
title_text="Statistics of sites that contribute to minor contamination",
xaxis = dict(
tickmode = 'array',
tickvals = ticks['index'],
ticktext = ticks['sample_name']
))
fig.add_hline(y=self.threshold, line_color='red')
fig.write_html(os.path.join(outdir, 'minor_contamination_sites.html'))
return data
def estimate(self, samples):
"""
Estimate minor contamination.
"""
for sample_name, sample in samples.items():
sites = sample.pileup
sites_notna = sites[~pd.isna(sites['genotype_class'])]
hom_sites = sites_notna[sites_notna['genotype_class'] == 'Hom']
sample.metrics['minor_contamination'] = {}
sample.metrics['minor_contamination']['n_homozygous_sites'] = len(hom_sites)
if len(hom_sites) == 0:
sample.metrics['minor_contamination']['val'] = np.nan
sample.metrics['minor_contamination']['n_contributing_sites'] = 0
sample.metrics['minor_contamination']['contributing_sites'] = {}
else:
contributing_sites = hom_sites[hom_sites['minor_allele_freq']>0]
contributing_sites.index = contributing_sites['chrom'].astype(str) + ':' + \
contributing_sites['pos'].astype(str)
sample.metrics['minor_contamination']['val'] = \
hom_sites['minor_allele_freq'].mean()
sample.metrics['minor_contamination']['n_contributing_sites'] = \
len(contributing_sites)
sample.metrics['minor_contamination']['contributing_sites'] = \
contributing_sites.to_dict(orient='index')
return samples
<file_sep>/docs/introduction.md
---
description: Basics on the usage of biometrics
---
# Introduction
Biometrics is a Python package to compute various metrics for assessing sample contamination, sample swaps, and sample sex validation. The package is composed of five tools \(see below\). All the tools \(except the sex mismatch one\) depend on you providing a VCF file of SNPs to use for computing the metrics. The sex mismatch tool requires you to provide a BED file containing the Y chromosome regions of interest.
## Extract
Running this step is **required** before running any of the other four tools. This step extracts the pileup and coverage information from your BAM file\(s\) and stores the result in a file. The file can then be accessed not just for your initial analysis but for all subsequent analyses that make use of the sample. This provides a significant speed boost to running the four downstream biometrics tools.
Click [here](extraction.md) to read more about this tool.
## Genotype
Compares each each sample against each other to verify expected sample matches and identify any unexpected matches or mismatches. Relies on computing a discordance score between each pair of samples.
Click [here](genotype.md) to read more about this tool.
## Cluster
Takes the output from the genotype comparison tool and clusters the samples into groups. Clustering is based on binarizing the discordance score into 0 or 1, and then finding the connected samples.
Click [here](cluster.md) to read more about this tool.
## Minor contamination
Minor contamination check is done to see if a patient’s sample is contaminated with a little DNA from unrelated individuals.
Click [here](minor-contamination.md) to read more about this tool.
## Major contamination
Major contamination check is done to see if a patient’s sample is contaminated with DNA from unrelated individuals.
Click [here](major-contamination.md) to read more about this tool.
## Sex mismatch
Used to determine if the predicted sex mismatches the expected sex for a given sample.
Click [here](sex-mismatch.md) to read more about this tool.
<file_sep>/biometrics/utils.py
import logging
def get_logger(debug=False):
FORMAT = '%(levelname)s - %(asctime)-15s: %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger("biometrics")
if debug:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
return logger
def standardize_sex_nomenclature(val):
if val is None:
return None
# Potential inputs
female = ['female', 'f', 'Female', 'F']
male = ['Male', 'M', 'male', 'm']
if val in female:
return 'F'
elif val in male:
return 'M'
return None
<file_sep>/biometrics/sex_mismatch.py
import pandas as pd
import numpy as np
class SexMismatch:
"""
Class to detect sex mismatch
"""
def __init__(self, threshold):
self.threshold = threshold
def predict_sex(self, sample):
if sample.region_counts is None:
return np.nan
total_count = sample.region_counts['count'].sum()
predicted_sex = 'M' if total_count > self.threshold else 'F'
return predicted_sex
def detect_mismatch(self, samples):
results = []
for i, sample_name in enumerate(samples):
sample = samples[sample_name]
predicted_sex = self.predict_sex(sample)
results.append({
'sample': sample_name,
'expected_sex': sample.sample_sex,
'predicted_sex': predicted_sex
})
results = pd.DataFrame(results)
results['sex_mismatch'] = \
(results['expected_sex'] != results['predicted_sex']).astype(str)
results.loc[pd.isna(results['predicted_sex']), 'sex_mismatch'] = np.nan
return results
<file_sep>/tests/test_biometrics.py
#!/usr/bin/env python
"""Tests for `biometrics` package."""
import os
import argparse
from unittest import TestCase
from unittest import mock
import pandas as pd
from biometrics.biometrics import get_samples, run_minor_contamination, run_major_contamination
from biometrics.cli import get_args
from biometrics.extract import Extract
from biometrics.genotype import Genotyper
from biometrics.sex_mismatch import SexMismatch
from biometrics.minor_contamination import MinorContamination
from biometrics.major_contamination import MajorContamination
CUR_DIR = os.path.dirname(os.path.abspath(__file__))
class TestExtract(TestCase):
"""Tests for the extract tool in the `biometrics` package."""
@mock.patch(
'argparse.ArgumentParser.parse_args',
return_value=argparse.Namespace(
subparser_name='extract',
input=None,
sample_bam=[
os.path.join(CUR_DIR, 'test_data/test_sample1_golden.bam'),
os.path.join(CUR_DIR, 'test_data/test_sample2_golden.bam')],
sample_name=['test_sample1', 'test_sample2'],
sample_type=['tumor', 'tumor'],
sample_group=['patient1', 'patient1'],
sample_sex=['M', 'M'],
database=os.path.join(CUR_DIR, 'test_data/'),
vcf=os.path.join(CUR_DIR, 'test_data/test.vcf'),
fafile=os.path.join(CUR_DIR, 'test_data/ref.fasta'),
bed=os.path.join(CUR_DIR, 'test_data/test.bed'),
min_mapping_quality=1,
min_base_quality=1,
min_coverage=10,
minor_threshold=0.002,
major_threshold=0.6,
discordance_threshold=0.05,
coverage_threshold=50,
min_homozygous_thresh=0.1,
zmin=None,
zmax=None,
outdir='.',
json=None,
plot=True,
default_genotype=None,
overwrite=True,
no_db_compare=False,
prefix='test',
version=False,
threads=1))
def setUp(self, mock_args):
"""Set up test fixtures, if any."""
self.args = get_args()
def test_load_vcf(self):
"""Test loading the VCF file."""
extractor = Extract(self.args)
self.assertGreater(
len(extractor.sites), 0, msg="Could not parse VCF sites.")
self.assertEqual(
len(extractor.sites), 15,
msg="Did not parse right number of sites.")
def test_load_bed(self):
"""Test loading the BED file."""
extractor = Extract(self.args)
self.assertEqual(
len(extractor.regions), 1, msg="Expected 1 region in BED file.")
def test_extract_sample(self):
extractor = Extract(self.args)
samples = get_samples(self.args, extraction_mode=True)
samples = extractor.extract(samples)
self.assertEqual(len(samples), 2, msg='Did not load 2 samples.')
self.assertEqual(samples['test_sample1'].sample_name, 'test_sample1', msg='Sample was not loaded correctly.')
self.assertIsNotNone(samples['test_sample1'].pileup, msg='Sample pileup was not loaded correctly.')
self.assertEqual(samples['test_sample1'].pileup.shape[0], 15, msg='Did not find pileup for 4 variants. Found: {}.'.format(samples['test_sample1'].pileup))
self.assertIsNotNone(
samples['test_sample1'].region_counts,
msg='Sample bed file was not loaded correctly.')
class TestLoadData(TestCase):
"""Tests load data by sample name in `biometrics` package."""
@mock.patch(
'argparse.ArgumentParser.parse_args',
return_value=argparse.Namespace(
subparser_name='extract',
input=['test_sample1', 'test_sample2'],
sample_bam=None,
sample_name=None,
sample_type=None,
sample_group=None,
sample_sex=None,
database=os.path.join(CUR_DIR, 'test_data/'),
vcf=None,
fafile=None,
bed=os.path.join(CUR_DIR, 'test_data/test.bed'),
min_mapping_quality=None,
min_base_quality=None,
min_coverage=None,
minor_threshold=0.002,
major_threshold=0.6,
discordance_threshold=0.05,
coverage_threshold=50,
min_homozygous_thresh=0.1,
zmin=None,
zmax=None,
outdir='.',
json=None,
plot=True,
default_genotype=None,
overwrite=True,
no_db_compare=False,
prefix='test',
version=False,
threads=1))
def setUp(self, mock_args):
"""Set up test fixtures, if any."""
self.args = get_args()
def test_load_by_sample_name(self):
samples = get_samples(self.args, extraction_mode=False)
self.assertEqual(len(samples), 2, msg='Did not load two samples')
class TestLoadDataPickle(TestCase):
"""Tests load data by sample name in `biometrics` package."""
@mock.patch(
'argparse.ArgumentParser.parse_args',
return_value=argparse.Namespace(
subparser_name='extract',
input=[
os.path.join(CUR_DIR, 'test_data/test_sample1.pickle'),
os.path.join(CUR_DIR, 'test_data/test_sample2.pickle')],
sample_bam=None,
sample_name=None,
sample_type=None,
sample_group=None,
sample_sex=None,
database=os.path.join(CUR_DIR, 'test_data/'),
vcf=None,
fafile=None,
bed=None,
min_mapping_quality=None,
min_base_quality=None,
min_coverage=None,
minor_threshold=0.002,
major_threshold=0.6,
discordance_threshold=0.05,
coverage_threshold=50,
min_homozygous_thresh=0.1,
zmin=None,
zmax=None,
outdir='.',
json=None,
plot=True,
default_genotype=None,
overwrite=True,
no_db_compare=False,
prefix='test',
version=False,
threads=1))
def setUp(self, mock_args):
"""Set up test fixtures, if any."""
self.args = get_args()
def test_load_by_pickle_file(self):
samples = get_samples(self.args, extraction_mode=False)
self.assertEqual(len(samples), 2, msg='Did not load two samples')
class TestDownstreamTools(TestCase):
"""Tests for downstream tools in the `biometrics` package."""
@mock.patch(
'argparse.ArgumentParser.parse_args',
return_value=argparse.Namespace(
subparser_name='extract',
input=['test_sample1', 'test_sample2'],
sample_bam=None,
sample_name=None,
sample_type=None,
sample_group=None,
sample_sex=None,
database=os.path.join(CUR_DIR, 'test_data/'),
vcf=None,
fafile=None,
bed=os.path.join(CUR_DIR, 'test_data/test.bed'),
min_mapping_quality=None,
min_base_quality=None,
min_coverage=None,
minor_threshold=0.002,
major_threshold=0.6,
discordance_threshold=0.05,
coverage_threshold=50,
min_homozygous_thresh=0.1,
zmin=None,
zmax=None,
outdir='.',
json=None,
plot=True,
default_genotype=None,
overwrite=True,
no_db_compare=False,
prefix='test',
version=False,
threads=1))
def setUp(self, mock_args):
"""Set up test fixtures, if any."""
self.args = get_args()
def test_minor_contamination(self):
samples = get_samples(self.args, extraction_mode=False)
samples = run_minor_contamination(self.args, samples)
self.assertAlmostEqual(
samples['test_sample1'].metrics['minor_contamination']['val'], 0.0043,
places=4, msg='Minor contamination is wrong.')
self.assertEqual(
samples['test_sample1'].metrics['minor_contamination']['n_contributing_sites'], 1,
msg='Count of contributing sites for minor contamination is wrong.')
def test_plot_minor_contamination(self):
samples = get_samples(self.args, extraction_mode=False)
minor_contamination = MinorContamination(threshold=self.args.minor_threshold)
samples = minor_contamination.estimate(samples)
minor_contamination.plot(samples, self.args.outdir)
def test_major_contamination(self):
samples = get_samples(self.args, extraction_mode=False)
samples = run_major_contamination(self.args, samples)
self.assertAlmostEqual(
samples['test_sample1'].metrics['major_contamination']['val'], 0.2,
places=1, msg='Major contamination is wrong.')
def test_plot_major_contamination(self):
samples = get_samples(self.args, extraction_mode=False)
major_contamination = MajorContamination(threshold=self.args.minor_threshold)
samples = major_contamination.estimate(samples)
major_contamination.plot(samples, self.args.outdir)
def test_genotyper(self):
samples = get_samples(self.args, extraction_mode=False)
genotyper = Genotyper(
no_db_compare=self.args.no_db_compare,
discordance_threshold=self.args.discordance_threshold,
threads=self.args.threads,
zmin=self.args.zmin,
zmax=self.args.zmax)
data = genotyper.compare_samples(samples)
self.assertEqual(len(data), 4, msg='There were not four comparisons done.')
self.assertEqual(set(data['Status']), set(['Expected Match']), msg='All sample comparisons were expected to match.')
def test_genotyper_plot(self):
samples = get_samples(self.args, extraction_mode=False)
genotyper = Genotyper(
no_db_compare=self.args.no_db_compare,
discordance_threshold=self.args.discordance_threshold,
threads=self.args.threads,
zmin=self.args.zmin,
zmax=self.args.zmax)
data = genotyper.compare_samples(samples)
genotyper.plot(data, self.args.outdir)
def test_sexmismatch(self):
samples = get_samples(self.args, extraction_mode=False)
sex_mismatch = SexMismatch(self.args.coverage_threshold)
results = sex_mismatch.detect_mismatch(samples)
self.assertEqual(set(results['expected_sex']), set(['M']), msg='Expected all samples to have an expected sex of M.')
self.assertEqual(set(results['predicted_sex']), set(['M']), msg='Expected all samples to not have a sex mismatch.')
class TestNASexMismatch(TestCase):
"""Test that sex mismatch returns NA if no Y chrom regions."""
@mock.patch(
'argparse.ArgumentParser.parse_args',
return_value=argparse.Namespace(
subparser_name='extract',
input=None,
sample_bam=[
os.path.join(CUR_DIR, 'test_data/test_sample1_golden.bam'),
os.path.join(CUR_DIR, 'test_data/test_sample2_golden.bam')],
sample_name=['test_sample1', 'test_sample2'],
sample_type=['tumor', 'tumor'],
sample_group=['patient1', 'patient1'],
sample_sex=['M', 'M'],
database=os.path.join(CUR_DIR, 'test_data/'),
vcf=os.path.join(CUR_DIR, 'test_data/test.vcf'),
fafile=os.path.join(CUR_DIR, 'test_data/ref.fasta'),
bed=os.path.join(CUR_DIR, 'test_data/test-noY.bed'),
min_mapping_quality=1,
min_base_quality=1,
min_coverage=10,
minor_threshold=0.002,
major_threshold=0.6,
discordance_threshold=0.05,
coverage_threshold=50,
min_homozygous_thresh=0.1,
zmin=None,
zmax=None,
outdir='.',
json=None,
plot=False,
default_genotype=None,
overwrite=True,
no_db_compare=False,
prefix='test',
version=False,
threads=1))
def setUp(self, mock_args):
"""Set up test fixtures, if any."""
self.args = get_args()
def test_sexmismatch_noY(self):
extractor = Extract(self.args)
samples = get_samples(self.args, extraction_mode=True)
samples = extractor.extract(samples)
sex_mismatch = SexMismatch(self.args.coverage_threshold)
results = sex_mismatch.detect_mismatch(samples)
self.assertTrue(
pd.isna(results.at[0, 'predicted_sex']), msg='Predicted sample sex should have been nan.')
<file_sep>/biometrics/major_contamination.py
import os
import pandas as pd
import numpy as np
import plotly.graph_objects as go
class MajorContamination():
"""
Major contamination.
"""
def __init__(self, threshold):
self.threshold = threshold
def to_dataframe(self, samples):
data = pd.DataFrame(
columns=['sample_name', 'sample_group', 'sample_sex', 'sample_type',
'total_sites', 'total_heterozygous_sites',
'major_contamination'])
for sample_name, sample in samples.items():
row = {
'sample_name': sample.sample_name,
'sample_group': sample.sample_group,
'sample_sex': sample.sample_sex,
'sample_type': sample.sample_type,
'total_sites': sample.metrics['major_contamination']['total_sites'],
'total_heterozygous_sites': sample.metrics['major_contamination']['total_heterozygous_sites'],
'major_contamination': sample.metrics['major_contamination']['val']
}
data = data.append(row, ignore_index=True)
data = data.sort_values('major_contamination', ascending=False)
return data
def plot(self, samples, outdir):
"""
Plot minor contamination data.
"""
data = self.to_dataframe(samples)
data['major_contamination'] = data['major_contamination'].map(
lambda x: round(x, 5))
fig = go.Figure()
fig.add_trace(
go.Bar(
x=data['sample_name'],
y=data['major_contamination'],
customdata=data.to_numpy(),
hovertemplate='<b>Sample group:</b> %{customdata[1]}' +
'<br><b>Sample name:</b> %{customdata[0]}' +
'<br><b>Sample sex:</b> %{customdata[2]}' +
'<br><b>Sample type:</b> %{customdata[3]}' +
'<br><b>Total sites:</b> %{customdata[5]}' +
'<br><b>Total heterozygous sites:</b> %{customdata[6]}' +
'<br><b>Major contamination:</b> %{y:E}' +
'<extra></extra>',
))
fig.update_layout(
yaxis_title="Major contamination",
title_text="Major contamination across samples")
fig.add_hline(y=self.threshold, line_color='red')
fig.write_html(os.path.join(outdir, 'major_contamination.html'))
def estimate(self, samples):
"""
Estimate major contamination.
"""
for sample_name, sample in samples.items():
sites = sample.pileup
sites_notna = sites[~pd.isna(sites['genotype_class'])]
het_sites = sites_notna[sites_notna['genotype_class'] == 'Het']
sample.metrics['major_contamination'] = {}
sample.metrics['major_contamination']['total_sites'] = len(sites_notna)
sample.metrics['major_contamination']['total_heterozygous_sites'] = len(het_sites)
if sample.metrics['major_contamination']['total_sites'] == 0:
sample.metrics['major_contamination']['val'] = np.nan
else:
sample.metrics['major_contamination']['val'] = \
len(het_sites) / len(sites_notna)
return samples
<file_sep>/tests/__init__.py
"""Unit test package for biometrics."""
<file_sep>/docs/sex-mismatch.md
---
description: Determine if a sample's predicted and known sex mismatch.
---
# Sex mismatch
This tool uses read coverage data on the Y chromosome to predict the sex for a sample, and then the compares the prediction to the expected sex to see if there is a mismatch. The metric requires the extracted coverage information from running the `extract` tool with the `--bed` flag supplied.
## How to run the tool
You can run this tool with one or more samples. There are three ways you can provide the input to the `--input` flag:
### Method 1
You can provide the sample names. This assumes there is a file named `{sample_name}.pk` in the database directory.
```
biometrics sexmismatch \
-i C-48665L-N001-d -i C-PCYP90-N001-d -i C-MH6AL9-N001-d \
-db /path/to/extract/output
```
### Method 2
You can directly provide it the python pickle file that was outputted from the `extract` tool.
```
biometrics sexmismatch \
-i /path/to/extract/output/C-48665L-N001-d.pk \
-i /path/to/extract/output/C-PCYP90-N001-d.pk \
-i /path/to/extract/output/C-MH6AL9-N001-d.pk \
```
### Method 3
You can also indicate your input samples via a CSV file, which has the same format as what you provided to the extraction tool, but you only need the `sample_name` column:
```
biometrics sexmismatch \
-i samples.csv \
-db /path/to/store/extract/output
```
## Output
All analyses output a CSV file containing the metrics for each sample. It will be saved either to the current working directory or to a folder you specify via `--outdir`. The table below describes each column in the CSV output.
| Column Name | Description |
| -------------- | -------------------------------------------- |
| sample\_name | Sample name. |
| expected\_sex | The sample's expected sex. |
| predicted\_sex | The sample's predicted sex. |
| sex\_mismatch | True if expected and predicted sex mismatch. |
<file_sep>/docs/major-contamination.md
---
description: Calculate major contamination
---
# Major contamination
Major contamination is a metric to see if a sample is contaminated with small amounts of DNA from another unrelated sample. The metric requires the extracted pileup information from running the `extract` tool.
## How to run the tool
You can run this tool with one or more samples. There are three ways you can provide the input to the `--input` flag:
#### Method 1
You can provide the sample names. This assumes there is a file named `{sample_name}.pk` in the database directory.
```text
biometrics major \
-i C-48665L-N001-d -i C-PCYP90-N001-d -i C-MH6AL9-N001-d \
-db /path/to/extract/output
```
#### Method 2
You can directly provide it the python pickle file that was outputted from the `extract` tool.
```text
biometrics major \
-i /path/to/extract/output/C-48665L-N001-d.pk \
-i /path/to/extract/output/C-PCYP90-N001-d.pk \
-i /path/to/extract/output/C-MH6AL9-N001-d.pk \
```
#### Method 3
You can also indicate your input samples via a CSV file, which has the same format as what you provided to the extraction tool, but you only need the `sample_name` column:
```text
biometrics major \
-i samples.csv \
-db /path/to/store/extract/output
```
## Output
All analyses output a CSV file containing the metrics for each sample. An interactive bar graph can also optionally be produced by supplying the `--plot` flag. These outputs are saved either to the current working directory or to a folder you specify via `--outdir`.
### CSV file
The CSV file contains metrics for each pair of samples compared \(one per line\). The table below describes each column in the CSV output:
| Column Name | Description |
| :--- | :--- |
| sample\_name | Sample name. |
| sample\_group | Sample group \(if available\). |
| sample\_sex | Sample sex \(if available\). |
| sample\_type | Sample type \(if available\). |
| total\_sites | Total number of sites. |
| total\_heterozygous\_sites | Total number of heterozygous sites. |
| major\_contamination | Major contamination metric. |
### Interactive plot
Below is an example bar plot showing the per-sample major contamination metrics. You can hover over each bar to get more information about the sample. You can also control the major contamination threshold \(the horizontal red line\) via the `--major-threshold` flag.

## Algorithm details
Major contamination is calculated as the number of heterozygous sites divided by the total number of sites. A heterozygous site is defined as one with > 10% minor allele frequency.
<file_sep>/setup.py
#!/usr/bin/env python
"""The setup script."""
import os
from setuptools import setup, find_packages
with open('README.md') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
def req_file(filename):
"""
We're using a requirements.txt file so that pyup.io can use this for security checks
:param filename:
:return str:
"""
with open(filename) as f:
content = f.readlines()
content = filter(lambda x: not x.startswith("#"), content)
return [x.strip() for x in content]
with open(os.path.join(os.path.dirname(__file__), "biometrics/VERSION"), "r") as fh:
__version__ = fh.read().strip()
setup(
author="<NAME>",
author_email='<EMAIL>',
python_requires='>=3.5',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9'
],
description="Package to generate sample based biometrics.",
entry_points={
'console_scripts': [
'biometrics=biometrics.cli:main',
],
},
install_requires=req_file("requirements.txt"),
license="Apache Software License 2.0",
long_description=readme + '\n\n' + history,
include_package_data=True,
keywords='biometrics',
name='biometrics',
packages=find_packages(include=['biometrics', 'biometrics.*']),
package_data={
"": ['requirements.txt', 'requirements_dev.txt'],
},
test_suite='tests',
url='https://github.com/msk-access/biometrics',
version=__version__,
zip_safe=False,
)
<file_sep>/Dockerfile
################## BASE IMAGE ######################
FROM python:3.6-slim
################## ARGUMENTS/Environments ##########
ARG BUILD_DATE
ARG BUILD_VERSION
ARG LICENSE="Apache-2.0"
ARG BIOMETRICS_VERSION
ARG VCS_REF
################## METADATA ########################
LABEL org.opencontainers.image.vendor="MSKCC"
LABEL org.opencontainers.image.authors="<NAME> (<EMAIL>)"
LABEL org.opencontainers.image.created=${BUILD_DATE} \
org.opencontainers.image.version=${BUILD_VERSION} \
org.opencontainers.image.licenses=${LICENSE} \
org.opencontainers.image.version.biometrics=${BIOMETRICS_VERSION} \
org.opencontainers.image.source.biometrics="https://pypi.org/project/biometrics/" \
org.opencontainers.image.vcs-url="https://github.com/msk-access/biometrics.git" \
org.opencontainers.image.vcs-ref=${VCS_REF}
LABEL org.opencontainers.image.description="This container uses python3.6 as the base image to build \
biometrics version ${BIOMETRICS_VERSION}"
################## INSTALL ##########################
WORKDIR /app
ADD . /app
RUN apt-get update \
&& apt-get install gcc g++ zlib1g-dev -y \
&& pip install -r requirements.txt \
&& pip install .
<file_sep>/docs/genotype.md
---
description: For finding sample matches and mismatches.
---
# Genotype
Compares each sample against each other to verify expected sample matches and identify any unexpected matches or mismatches. Running these comparisons requires the extracted pileup information to compute a discordance score between each pair of samples. The documentation below details the different ways to run this analysis, the output, and the methods behind them.
## How to run the tool
You need one or more samples to run this analysis. However, if you supply just one sample then it is assumed you have samples already in the database to compare with. There are two required inputs: \(1\) the names of the sample\(s\) you want to compare \(referred to as `input samples` below\), and \(2\) the database \(biometrics will automatically load all sample data from the database\). Moreover, there are two types of comparisons that are performed when running the tool:
### \(1\) Compares your input samples with each other
This only runs if you supplied two or more input samples. There are three ways you can provide the input to the `--input` flag:
#### Method 1
You can provide the sample names. This assumes there is a file named `{sample_name}.pk` in the database directory.
```text
biometrics genotype \
-i C-48665L-N001-d \
-i C-PCYP90-N001-d \
-i C-MH6AL9-N001-d \
-db /path/to/extract/output
```
#### Method 2
You can directly provide it the python pickle file that was outputted from the `extract` tool.
```text
biometrics genotype \
-i /path/to/extract/output/C-48665L-N001-d.pk \
-i /path/to/extract/output/C-PCYP90-N001-d.pk \
-i /path/to/extract/output/C-MH6AL9-N001-d.pk \
```
#### Method 3
You can also indicate your input samples via a CSV file, which has the same format as what you provided to the extraction tool, but you only need the `sample_name` column:
```text
biometrics genotype \
-i samples.csv \
-db /path/to/extract/output
```
### \(2\) Compares your input samples with remaining database samples
The second analysis will compare each of your input samples with all remaining samples in the database. However, if you wish to disable this step and not do the comparison then you can supply the `--no-db-compare` flag:
```text
biometrics genotype \
-i C-48665L-N001-d -i C-PCYP90-N001-d -i C-MH6AL9-N001-d \
--no-db-compare \
-db /path/to/store/extract/output
```
## Output
All analyses output a CSV file containing the metrics from comparing each sample. An interactive heatmap can also optionally be produced by supplying the `--plot` flag. These outputs are saved either to the current working directory or to a folder you specify via `--outdir`.
{% hint style="info" %}
It also automatically outputs two sets of clustering results: \(1\) the first set just clusters your input samples, and \(2\) the second set clusters your input samples and samples in the database. Please see the [cluster](cluster.md) documentation to understand the output files.
{% endhint %}
### CSV files
#### genotype\_comparison.csv
Contains metrics for each pair of samples compared \(one on each line\). The table below provides a description on each column.
| Column Name | Description |
| :--- | :--- |
| ReferenceSample | First sample in the comparison. |
| ReferenceSampleGroup | Group for the first sample in the comparison. |
| QuerySample | Second sample in the comparison. |
| QuerySampleGroup | Group for the second sample in the comparison. |
| CountOfCommonSites | Count of common SNP sites with enough coverage. |
| HomozygousInRef | Number of homozygous sites in the ReferenceSample. |
| TotalMatch | Total sites that match \(homozygous and heterozygous\). |
| HomozygousMatch | Number of homozygous sites that match. |
| HeterozygousMatch | Number of heterozygous sites that match. |
| HomozygousMismatch | Number of mismatching homozygous sites. |
| HeterozygousMismatch | Number of mismatching heterozygous sites. |
| DiscordanceRate | Discordance rate metric. |
| Matched | True if ReferenceSample and QuerySample have DiscordanceRate less than the threshold \(default 0.05\). |
| ExpectedMatch | True if the sample pair is expected to match. |
| Status | Takes one of the following: Expected Match, Unexpected Match, Unexpected Mismatch, or Expected Mismatch. |
### Interactive plot
Below are the two figures that are outputted from the two types of comparisons that are done. Samples that are unexpected matches or mismatches will be marked with a red star in the heatmap.

## Algorithm details
Any samples with a discordance rate of 5% or higher are considered mismatches.
$$
Discordance\ Rate = \frac{Number\ of\ matching\ homozygous\ SNPs\ in\ Reference\ but\ not\ Query}{Number\ of\ homozygous\ SNPs\ in\ Reference}\\
$$
{% hint style="info" %}
If there are <10 common homozygous sites, the discordance rate can not be calculated since this is a strong indication that coverage is too low and the samples failed other QC.
{% endhint %}
<file_sep>/docs/SUMMARY.md
# Table of contents
* [biometrics](README.md)
* [Introduction](introduction.md)
* [Extraction](extraction.md)
* [Genotype](genotype.md)
* [Cluster](cluster.md)
* [Minor contamination](minor-contamination.md)
* [Major contamination](major-contamination.md)
* [Sex mismatch](sex-mismatch.md)
<file_sep>/docs/minor-contamination.md
---
description: Calculate minor contamination
---
# Minor contamination
Minor contamination is a metric to see if a sample is contaminated with small amounts of DNA from another unrelated sample. The metric requires the extracted pileup information from running the `extract` tool.
## How to run the tool
You can run this tool with one or more samples. There are three ways you can provide the input to the `--input` flag:
#### Method 1
You can provide the sample names. This assumes there is a file named `{sample_name}.pk` in the database directory.
```text
biometrics minor \
-i C-48665L-N001-d -i C-PCYP90-N001-d -i C-MH6AL9-N001-d \
-db /path/to/extract/output
```
#### Method 2
You can directly provide it the python pickle file that was outputted from the `extract` tool.
```text
biometrics minor \
-i /path/to/extract/output/C-48665L-N001-d.pk \
-i /path/to/extract/output/C-PCYP90-N001-d.pk \
-i /path/to/extract/output/C-MH6AL9-N001-d.pk \
```
#### Method 3
You can also indicate your input samples via a CSV file, which has the same format as what you provided to the extraction tool, but you only need the `sample_name` column:
```text
biometrics minor \
-i samples.csv \
-db /path/to/store/extract/output
```
## Output
All analyses output a CSV file containing the metrics for each sample. An interactive bar graph can also optionally be produced by supplying the `--plot` flag. These outputs are saved either to the current working directory or to a folder you specify via `--outdir`.
### CSV file
The CSV file contains metrics for each pair of samples compared \(one per line\). The table below describes each column in the CSV output:
| Column Name | Description |
| :--- | :--- |
| sample\_name | Sample name. |
| sample\_group | Sample group \(if available\). |
| sample\_sex | Sample sex \(if available\). |
| sample\_type | Sample type \(if available\). |
| total\_homozygous\_sites | Total number of homozygous sites. |
| n\_contributing\_sites | Total number of contributing sites \(i.e. those that have MAF > 0\). |
| minor\_contamination | Minor contamination metric. |
### Interactive plot
Two interactive plots are produced that help you further investigate the data.
{% hint style="info" %}
The sample order is the same between the two plots.
{% endhint %}
{% hint style="info" %}
You can also control the minor contamination threshold \(the horizontal red line\) via the `--minor-threshold` flag.
{% endhint %}
#### Minor contamination plot
Shows the minor contamination for each sample, ranked from highest to lowest. You can hover over each bar to get more information about the sample.

#### Contributing sites plot
Shows statistics for each site that contributes to the minor contamination calculation. Only sites with a minor allele frequency > 0 are shown. You can hover over each point to get more information about that site.

## Algorithm details
Minor contamination is calculated as the average minor allele frequency for homozygous sites. A homozygous site is defined as one with < 10% minor allele frequency.
<file_sep>/biometrics/biometrics.py
import os
import glob
import pandas as pd
from biometrics.sample import Sample
from biometrics.extract import Extract
from biometrics.genotype import Genotyper
from biometrics.cluster import Cluster
from biometrics.minor_contamination import MinorContamination
from biometrics.major_contamination import MajorContamination
from biometrics.sex_mismatch import SexMismatch
from biometrics.utils import standardize_sex_nomenclature, get_logger
logger = get_logger()
def write_to_file(args, data, basename):
"""
Generic function to save output to a file.
"""
outdir = os.path.abspath(args.outdir)
outpath = os.path.join(outdir, basename + '.csv')
data.to_csv(outpath, index=False)
if args.json:
outpath = os.path.join(outdir, basename + '.json')
data.to_json(outpath)
def run_extract(args, samples):
"""
Extract the pileup and region information from the samples. Then
save to the database.
"""
extractor = Extract(args=args)
samples = extractor.extract(samples)
return samples
def run_sexmismatch(args, samples):
"""
Find and sex mismatches and save the output
"""
sex_mismatch = SexMismatch(args.coverage_threshold)
results = sex_mismatch.detect_mismatch(samples)
basename = 'sex_mismatch'
if args.prefix:
basename = args.prefix + '_' + basename
write_to_file(args, results, basename)
def run_minor_contamination(args, samples):
"""
Compute minor contamination and save the output and figure
"""
minor_contamination = MinorContamination(threshold=args.minor_threshold)
samples = minor_contamination.estimate(samples)
data = minor_contamination.to_dataframe(samples)
basename = 'minor_contamination'
if args.prefix:
basename = args.prefix + '_' + basename
write_to_file(args, data, basename)
if args.plot:
if len(samples) > 1000:
logger.warning('Turning off plotting functionality. You are trying to plot more than 1000 samples, which is too cumbersome.')
else:
minor_contamination.plot(samples, args.outdir)
return samples
def run_major_contamination(args, samples):
"""
Compute major contamination and save the output and figure.
"""
major_contamination = MajorContamination(threshold=args.major_threshold)
samples = major_contamination.estimate(samples)
data = major_contamination.to_dataframe(samples)
basename = 'major_contamination'
if args.prefix:
basename = args.prefix + '_' + basename
write_to_file(args, data, basename)
if args.plot:
if len(samples) > 1000:
logger.warning('Turning off plotting functionality. You are trying to plot more than 1000 samples, which is too cumbersome.')
else:
major_contamination.plot(samples, args.outdir)
return samples
def run_genotyping(args, samples):
"""
Run the genotyper and save the output and figure.
"""
genotyper = Genotyper(
no_db_compare=args.no_db_compare,
discordance_threshold=args.discordance_threshold,
threads=args.threads,
zmin=args.zmin,
zmax=args.zmax)
cluster_handler = Cluster(args.discordance_threshold)
comparisons = genotyper.compare_samples(samples)
# save genotyping output
basename = 'genotype_comparison'
if args.prefix:
basename = args.prefix + '_' + basename
write_to_file(args, comparisons, basename)
# cluster just the input samples
samples_input = dict(filter(
lambda x: not x[1].query_group, samples.items()))
samples_names = [i.sample_name for i in samples_input.values()]
comparisons_input = comparisons[
(comparisons['ReferenceSample'].isin(samples_names)) &
(comparisons['QuerySample'].isin(samples_names))].copy()
logger.info('Clustering input samples...')
clusters = cluster_handler.cluster(comparisons_input)
if clusters is not None:
basename = 'genotype_clusters_input'
if args.prefix:
basename = args.prefix + '_' + basename
write_to_file(args, clusters, basename)
# cluster all the samples
if not args.no_db_compare:
are_there_db_samples = len(samples_input) != len(samples)
if not are_there_db_samples:
logger.warning(
'The set of database and input samples are the same. Will only cluster the samples once.')
else:
logger.info('Clustering input and database samples...')
clusters = cluster_handler.cluster(comparisons)
if clusters is not None:
basename = 'genotype_clusters_database'
if args.prefix:
basename = args.prefix + '_' + basename
write_to_file(args, clusters, basename)
# save plots
if args.plot:
if len(samples) > 1000:
logger.warning('Turning off plotting functionality. You are trying to plot more than 1000 samples, which is too cumbersome.')
else:
genotyper.plot(comparisons, args.outdir)
return samples
def run_cluster(args):
comparisons = []
for input in args.input:
comparisons.append(
pd.read_csv(input)
)
comparisons = pd.concat(comparisons)
comparisons = comparisons.drop_duplicates(['ReferenceSample', 'QuerySample'])
cluster_handler = Cluster(args.discordance_threshold)
logger.info('Clustering input samples...')
clusters = cluster_handler.cluster(comparisons)
if clusters is not None:
clusters.to_csv(args.output, index=False)
def load_input_sample_from_db(sample_name, database):
"""
Loads any the given (that the user specified via the CLI) from the
database.
"""
extraction_file = os.path.join(database, sample_name + '.pickle')
if not os.path.exists(extraction_file):
extraction_file = os.path.join(database, sample_name + '.pk')
assert os.path.exists(extraction_file), 'Could not find: {}. Please rerun the extraction step.'.format(
extraction_file)
sample = Sample(query_group=False)
sample.load_from_file(extraction_file)
return sample
def load_database_samples(database, existing_samples):
"""
Loads any samples that are already present in the database AND
which were not specified as input via the CLI.
"""
samples = {}
for pattern in ['*.pickle', '*.pk']:
for pickle_file in glob.glob(os.path.join(database, pattern)):
sample_name = os.path.basename(pickle_file).replace('.pickle', '').replace('.pk', '')
if sample_name in existing_samples:
continue
sample = Sample(db=database, query_group=True)
sample.load_from_file(extraction_file=pickle_file)
samples[sample.sample_name] = sample
return samples
def get_samples_from_input(inputs, database, extraction_mode):
"""
Parse the sample information from the user-supplied CSV file.
"""
if type(inputs) != list:
inputs = [inputs]
samples = {}
for fpath in inputs:
input = pd.read_csv(fpath, sep=',')
# check if some required columns are present
assert 'sample_bam' in input.columns, 'Input file does not have the \'sample_bam\' column.'
assert 'sample_name' in input.columns, 'Input does not have \'sample_name\' column.'
input = input.to_dict(orient='records')
for row in input:
if not extraction_mode:
# if not running extract tool, then just need to get
# the sample name
sample_name = row['sample_name']
sample = load_input_sample_from_db(sample_name, database)
samples[sample.sample_name] = sample
continue
# parse in the input
sample = Sample(
sample_name=row['sample_name'],
sample_bam=row['sample_bam'],
sample_group=row.get('sample_group'),
sample_type=row.get('sample_type'),
sample_sex=standardize_sex_nomenclature(row.get('sample_sex')),
db=database)
samples[sample.sample_name] = sample
return samples
def get_samples_from_bam(args):
"""
Parse the sample information the user supplied via the CLI.
"""
samples = {}
for i, sample_bam in enumerate(args.sample_bam):
sample_sex = standardize_sex_nomenclature(
args.sample_sex[i] if args.sample_sex is not None else None)
sample_name = args.sample_name[i] if args.sample_name is not None else None
sample_group = args.sample_group[i] \
if args.sample_group is not None else args.sample_name[i]
sample_type = args.sample_type[i] \
if args.sample_type is not None else None
sample = Sample(
sample_bam=sample_bam, sample_group=sample_group,
sample_name=sample_name, sample_type=sample_type,
sample_sex=sample_sex, db=args.database)
samples[sample.sample_name] = sample
return samples
def get_samples_from_name(sample_names, database):
"""
Parse the sample information the user supplied via the CLI.
"""
if type(sample_names) != list:
sample_names = [sample_names]
samples = {}
for i, sample_name in enumerate(sample_names):
sample = load_input_sample_from_db(sample_name, database)
samples[sample.sample_name] = sample
return samples
def get_samples(args, extraction_mode=False):
"""
Parse the sample information the user supplied via the CLI.
"""
samples = {}
if extraction_mode:
if args.input:
samples.update(get_samples_from_input(
args.input, args.database, extraction_mode))
if args.sample_bam:
samples.update(get_samples_from_bam(args))
else:
for input in args.input:
if input.endswith('.pickle') or input.endswith('.pk'):
sample = Sample(db=args.database, query_group=False)
sample.load_from_file(extraction_file=input)
samples[sample.sample_name] = sample
elif input.endswith('.csv') or input.endswith('.txt'):
samples.update(get_samples_from_input(
input, args.database, extraction_mode))
else:
samples.update(get_samples_from_name(input, args.database))
existing_samples = set([i for i in samples.keys()])
if not args.no_db_compare:
samples.update(load_database_samples(
args.database, existing_samples))
return samples
def create_outdir(outdir):
if outdir is None:
return
os.makedirs(outdir, exist_ok=True)
def run_biometrics(args):
"""
Decide what tool to run based in CLI input.
"""
if args.subparser_name == 'cluster':
run_cluster(args)
return
extraction_mode = args.subparser_name == 'extract'
samples = get_samples(args, extraction_mode=extraction_mode)
# if not extraction_mode and args.plot:
if extraction_mode:
create_outdir(args.database)
run_extract(args, samples)
elif args.subparser_name == 'sexmismatch':
create_outdir(args.outdir)
run_sexmismatch(args, samples)
elif args.subparser_name == 'minor':
create_outdir(args.outdir)
run_minor_contamination(args, samples)
elif args.subparser_name == 'major':
create_outdir(args.outdir)
run_major_contamination(args, samples)
elif args.subparser_name == 'genotype':
create_outdir(args.outdir)
run_genotyping(args, samples)
<file_sep>/biometrics/cluster.py
from collections import Counter
import pandas as pd
import networkx as nx
from biometrics.utils import get_logger
logger = get_logger()
class Cluster:
def __init__(self, discordance_threshold=0.05):
self.discordance_threshold = discordance_threshold
def cluster(self, comparisons):
assert comparisons is not None, "There is no fingerprint comparison data available."
if len(comparisons) < 1:
logger.warning('There are not enough comparisons to cluster.')
return None
sample2group = dict(zip(
comparisons['ReferenceSample'], comparisons['ReferenceSampleGroup']))
sample2group.update(dict(zip(
comparisons['QuerySample'], comparisons['QuerySampleGroup'])))
comparisons['is_same_group'] = comparisons['DiscordanceRate'].map(
lambda x: 1 if ((x <= self.discordance_threshold) & (~pd.isna(x))) else 0)
graph = nx.from_pandas_edgelist(
comparisons[comparisons['is_same_group']==1], 'ReferenceSample', 'QuerySample')
clusters = []
cluster_idx = 0
for cluster_idx, group in enumerate(nx.connected_components(graph)):
samples_in_group = list(group)
sample_groups = list(set(
comparisons[comparisons['ReferenceSample'].isin(samples_in_group)]['ReferenceSampleGroup']))
occurences = Counter(sample_groups)
max_occurence = occurences.most_common()
max_occurence_val = max_occurence[0][1]
most_common_group = list(filter(lambda x: x[1] == max_occurence_val, max_occurence))
most_common_group = ':'.join([i[0] for i in most_common_group])
for i, sample in enumerate(samples_in_group):
comparisons_sample = comparisons[
(comparisons['ReferenceSample']==sample) &
(comparisons['QuerySample']!=sample)]
comparisons_cluster = comparisons_sample[
comparisons_sample['QuerySample'].isin(samples_in_group)]
sample_status_counts = comparisons_sample['Status'].value_counts()
cluster_status_counts = comparisons_cluster['Status'].value_counts()
mean_discordance = 'NA'
if len(comparisons_cluster) > 0:
mean_discordance = comparisons_cluster['DiscordanceRate'].mean()
row = {
'sample_name': sample,
'expected_sample_group': sample2group[sample],
'predicted_sample_group': most_common_group,
'cluster_index': cluster_idx,
'cluster_size': len(samples_in_group),
'avg_discordance': mean_discordance,
'count_expected_matches': cluster_status_counts.get('Expected Match', 0),
'count_unexpected_matches': cluster_status_counts.get('Unexpected Match', 0),
'count_expected_mismatches': sample_status_counts.get('Expected Mismatch', 0),
'count_unexpected_mismatches': sample_status_counts.get('Unexpected Mismatch', 0)
}
clusters.append(row)
clusters = pd.DataFrame(clusters)
logger.info(
'Clustering finished. Grouped {} samples into {} clusters. Expected {} clusters.'.format(
len(sample2group), cluster_idx + 1, len(set(clusters['expected_sample_group']))))
return clusters
<file_sep>/biometrics/__init__.py
"""Top-level package for biometrics."""
import os
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
# version info
library_path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(library_path, "VERSION"), "r") as fh:
__version__ = fh.read().strip()
<file_sep>/biometrics/sample.py
import pickle
import os
import pandas as pd
class Sample:
"""
Class to hold information related to a single sample.
"""
def __init__(self, sample_name=None, sample_bam=None, sample_group=None,
sample_sex=None, sample_type=None, db=None, query_group=False):
self.sample_bam = sample_bam
self.sample_name = sample_name
self.sample_sex = sample_sex
self.sample_type = sample_type
if sample_group is None:
self.sample_group = sample_name
else:
self.sample_group = sample_group
self.pileup = None
self.region_counts = None
self.extraction_file = None
self.query_group = query_group
self.metrics = {}
if self.sample_name is not None:
if db is not None:
self.extraction_file = os.path.join(db, self.sample_name + '.pickle')
else:
self.extraction_file = self.sample_name + '.pickle'
def save_to_file(self):
pileup_data = self.pileup.to_dict("records")
if self.region_counts is not None:
region_counts = self.region_counts.to_dict('records')
else:
region_counts = None
sample_data = {
'sample_bam': self.sample_bam,
'sample_name': self.sample_name,
'sample_sex': self.sample_sex,
'sample_group': self.sample_group,
'sample_type': self.sample_type,
'pileup_data': pileup_data,
'region_counts': region_counts
}
pickle.dump(sample_data, open(self.extraction_file, "wb"))
def load_from_file(self, extraction_file=None):
if extraction_file is not None:
self.extraction_file = extraction_file
assert self.extraction_file is not None, 'Extraction file path is None.'
assert os.path.exists(self.extraction_file), 'Extraction file does not exist: {}'.format(
self.extraction_file)
sample_data = pickle.load(open(self.extraction_file, "rb"))
region_counts = None
if sample_data.get('region_counts') is not None:
region_counts = pd.DataFrame(
sample_data['region_counts'], dtype=object)
self.pileup = pd.DataFrame(sample_data['pileup_data'])
self.sample_bam = sample_data['sample_bam']
self.sample_name = sample_data['sample_name']
self.sample_sex = sample_data['sample_sex']
self.sample_group = sample_data['sample_group'] if sample_data['sample_group'] is not None else sample_data['sample_name']
self.sample_type = sample_data['sample_type']
self.region_counts = region_counts
<file_sep>/requirements.txt
networkx
numpy
pandas
plotly
pysam
pyvcf3
python-dateutil
pytz
retrying
six
<file_sep>/tests/test_data/main.sh
# simulate BAM and FASTQ data from reference fasta and vcf file
python2 /Users/charlesmurphy/Desktop/tools/neat-genreads/genReads.py \
-r ref.fasta \
-R 50 \
-o test_sample1 \
-c 30 \
-p 12 \
-v test.vcf \
--bam \
-M 0 \
-E 0 \
--pe 120 5
~/Desktop/tools/samtools-1.10/samtools index test_sample1_golden.bam
python2 /Users/charlesmurphy/Desktop/tools/neat-genreads/genReads.py \
-r ref.fasta \
-R 50 \
-o test_sample2 \
-c 30 \
-p 12 \
-v test.vcf \
--bam \
-M 0 \
-E 0 \
--pe 120 5
~/Desktop/tools/samtools-1.10/samtools index test_sample2_golden.bam
# python biometrics/cli.py extract -sb ./tests/test_data/test_golden.bam -st tumor -ss male -sp P1 -sn test --vcf tests/test_data/test.vcf -db . --fafile ./tests/test_data/ref.fasta --overwrite
#
# python biometrics/cli.py minor -sb ./tests/test_data/test_golden.bam -st tumor -ss male -sp P1 -sn test --vcf tests/test_data/test.vcf -db . --fafile ./tests/test_data/ref.fasta
#
# python biometrics/cli.py genotype \
# -sb ./tests/test_data/test_sample1_golden.bam ./tests/test_data/test_sample2_golden.bam \
# -st tumor tumor -ss male male -sg patien1 patient1 -sn test_sample1 test_sample2 \
# --vcf tests/test_data/test.vcf -db . --fafile ./tests/test_data/ref.fasta
#
#
# python biometrics/cli.py extract \
# -sb /Users/charlesmurphy/Desktop/mskcc-analyses/200608_compare_qc_tools/manually_count_bases/C-52YNHF-N001-d_cl_aln_srt_MD_IR_FX_BR.bam \
# -st tumor -ss male -sg C-52YNHF -sn C-52YNHF-N001-d \
# --vcf /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/fingerprinting_snps.vcf \
# -db /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/ \
# --fafile /Users/charlesmurphy/Desktop/data/ref/hg19/Homo_sapiens_assembly19.fasta \
# --overwrite
#
biometrics extract \
-sb /Users/charlesmurphy/Desktop/mskcc-analyses/200608_compare_qc_tools/manually_count_bases/C-52YNHF-N001-d_cl_aln_srt_MD_IR_FX_BR.bam \
-st tumor -ss male -sg C-52YNHF -sn C-52YNHF-N002-d \
--vcf /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/fingerprinting_snps.vcf \
--bed /Users/charlesmurphy/Desktop/data/innovation/resources/MSK-ACCESS-v1.0/MSK-ACCESS-v1_0-probe-A.sorted.bed \
-db /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/db/ \
--fafile /Users/charlesmurphy/Desktop/data/ref/hg19/Homo_sapiens_assembly19.fasta \
--overwrite
#
biometrics genotype \
-sb \
/Users/charlesmurphy/Desktop/mskcc-analyses/200608_compare_qc_tools/manually_count_bases/C-52YNHF-N001-d_cl_aln_srt_MD_IR_FX_BR.bam \
/Users/charlesmurphy/Desktop/mskcc-analyses/200608_compare_qc_tools/manually_count_bases/C-52YNHF-N001-d_cl_aln_srt_MD_IR_FX_BR.bam \
-st tumor tumor -ss male male -sg C-52YNHF C-52YNHF -sn C-52YNHF-N001-d C-52YNHF-N002-d \
--vcf /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/fingerprinting_snps.vcf \
-db /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/db/ \
--fafile /Users/charlesmurphy/Desktop/data/ref/hg19/Homo_sapiens_assembly19.fasta \
--outdir ~/Desktop --json --plot
biometrics major \
-sb /Users/charlesmurphy/Desktop/mskcc-analyses/200608_compare_qc_tools/manually_count_bases/C-52YNHF-N001-d_cl_aln_srt_MD_IR_FX_BR.bam \
-st tumor -ss male -sg C-52YNHF -sn C-52YNHF-N001-d \
--vcf /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/fingerprinting_snps.vcf \
-db /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/db/ \
--fafile /Users/charlesmurphy/Desktop/data/ref/hg19/Homo_sapiens_assembly19.fasta \
--outdir ~/Desktop --json
biometrics minor \
-sb /Users/charlesmurphy/Desktop/mskcc-analyses/200608_compare_qc_tools/manually_count_bases/C-52YNHF-N001-d_cl_aln_srt_MD_IR_FX_BR.bam \
-st tumor -ss male -sg C-52YNHF -sn C-52YNHF-N001-d \
--vcf /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/fingerprinting_snps.vcf \
-db /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/db/ \
--fafile /Users/charlesmurphy/Desktop/data/ref/hg19/Homo_sapiens_assembly19.fasta \
--outdir ~/Desktop --json
biometrics sexmismatch \
-sb /Users/charlesmurphy/Desktop/mskcc-analyses/200608_compare_qc_tools/manually_count_bases/C-52YNHF-N001-d_cl_aln_srt_MD_IR_FX_BR.bam \
-st tumor -ss male -sg C-52YNHF -sn C-52YNHF-N001-d \
--vcf /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/fingerprinting_snps.vcf \
--bed /Users/charlesmurphy/Desktop/data/innovation/resources/MSK-ACCESS-v1.0/MSK-ACCESS-v1_0-probe-A.sorted.bed \
-db /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/db/ \
--fafile /Users/charlesmurphy/Desktop/data/ref/hg19/Homo_sapiens_assembly19.fasta \
--outdir ~/Desktop --json
for i in `seq 1 1000`
do
python ../../biometrics/cli.py extract \
-sb /Users/charlesmurphy/Desktop/mskcc-analyses/200608_compare_qc_tools/manually_count_bases/C-52YNHF-N001-d_cl_aln_srt_MD_IR_FX_BR.bam \
-st tumor -ss male -sg C-52YNHF -sn C-52YNHF-N002-d-$i \
--vcf /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/fingerprinting_snps.vcf \
-db /Users/charlesmurphy/Desktop/mskcc-analyses/201013_fingerprinting/db3/ \
--fafile /Users/charlesmurphy/Desktop/data/ref/hg19/Homo_sapiens_assembly19.fasta
done
<file_sep>/biometrics/genotype.py
import os
from multiprocessing import Pool
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from biometrics.utils import get_logger
EPSILON = 1e-9
logger = get_logger()
class Genotyper:
def __init__(self, no_db_compare, discordance_threshold=0.05, threads=1, zmin=None, zmax=None):
self.no_db_compare = no_db_compare
self.discordance_threshold = discordance_threshold
self.threads = threads
self.zmax = zmax
self.zmin = zmin
self.sample_type_ratio = 1
self.comparisons = None
def are_samples_same_group(self, sample1, sample2):
if sample1.sample_group is None or sample2.sample_group is None:
return np.nan
if sample1.sample_group == sample2.sample_group:
return True
else:
return False
def _plot_heatmap(self, data, outdir, name, title="Discordance calculations between samples", size_ratio=None):
width = None
height = None
if size_ratio is not None and size_ratio != 1:
width = 1400
height = (width * size_ratio)/4
fig = go.Figure()
fig.add_trace(
go.Heatmap(
x=data['ReferenceSample'],
y=data['QuerySample'],
z=data['DiscordanceRate'],
legendgroup="Discordance",
name='Discordance',
customdata=data.to_numpy(),
hovertemplate='<b>Reference sample:</b> %{customdata[0]}' +
'<br><b>Query sample:</b> %{customdata[2]}' +
'<br><b>Count of common sites:</b> %{customdata[4]}' +
'<br><b>Homozygous count in reference:</b> %{customdata[5]}' +
'<br><b>Total match count:</b> %{customdata[6]}' +
'<br><b>Homozygous match count:</b> %{customdata[7]}' +
'<br><b>Heterozygous match count:</b> %{customdata[8]}' +
'<br><b>Homozygous mismatch count:</b> %{customdata[9]}' +
'<br><b>Heterozygous mismatch count:</b> %{customdata[10]}' +
'<br><b>Discordance rate:</b> %{customdata[11]}' +
'<br><b>Status:</b> %{customdata[14]}' +
'<extra></extra>',
zmin=self.zmin,
zmax=self.zmax,
colorscale='Blues_r'
))
# add red dots to sample pairs that are unexpected match/mismatch
data_sub = data[(data['Status']=='Unexpected Match') | (data['Status']=='Unexpected Mismatch')].copy()
if len(data_sub) > 0:
fig.add_trace(
go.Scatter(
mode="markers",
x=data_sub['ReferenceSample'],
y=data_sub['QuerySample'],
marker_symbol=[17],
marker_color="red",
marker_line_width=0,
marker_size=10,
customdata=data_sub.to_numpy(),
hovertemplate='%{customdata[12]}<extra></extra>'))
fig.update_layout(
yaxis_title="Query samples",
xaxis_title="Reference samples",
legend_title_text="Discordance",
title_text=title,
width=width, height=height)
fig.write_html(os.path.join(outdir, name))
def plot(self, data, outdir):
# make plot for comparing input samples with each other
data_sub = data[~data['IsInputToDatabaseComparison']].copy()
del data_sub['IsInputToDatabaseComparison']
data_sub['DiscordanceRate'] = data_sub['DiscordanceRate'].map(
lambda x: round(x, 4))
if data_sub.shape[0] > 1:
self._plot_heatmap(
data_sub, outdir, name='genotype_comparison_input.html',
title="Discordance calculations between input samples")
# make plot for comparing input samples with database samples
data_sub = data[data['IsInputToDatabaseComparison']].copy()
del data_sub['IsInputToDatabaseComparison']
data_sub['DiscordanceRate'] = data_sub['DiscordanceRate'].map(
lambda x: round(x, 4))
if data_sub.shape[0] > 1:
self._plot_heatmap(
data_sub, outdir, name='genotype_comparison_database.html',
title="Discordance calculations between input samples and database samples",
size_ratio=self.sample_type_ratio)
def _compute_discordance(self, reference_sample, query_sample):
"""
Compute discordance between two samples
"""
pileup_ref = reference_sample.pileup
pileup_query = query_sample.pileup
common_covered = ~pd.isna(pileup_ref['genotype_class']) & ~pd.isna(pileup_query['genotype_class'])
pileup_ref = pileup_ref[common_covered]
pileup_query = pileup_query[common_covered]
row = {
'ReferenceSample': reference_sample.sample_name,
'ReferenceSampleGroup': reference_sample.sample_group,
'QuerySample': query_sample.sample_name,
'QuerySampleGroup': query_sample.sample_group}
if len(pileup_query) > 0:
row['HomozygousInRef'] = sum(pileup_ref['genotype_class'] == 'Hom')
row['TotalMatch'] = sum(pileup_ref['genotype_class'] == pileup_query['genotype_class'])
row['HomozygousMatch'] = sum((pileup_ref['genotype_class'] == pileup_query['genotype_class']) & (pileup_ref['genotype_class'] == 'Hom'))
row['HeterozygousMatch'] = sum((pileup_ref['genotype_class'] == pileup_query['genotype_class']) & (pileup_ref['genotype_class'] == 'Het'))
row['HomozygousMismatch'] = sum((pileup_ref['genotype'] != pileup_query['genotype']) & ((pileup_ref['genotype_class'] == 'Hom') & (pileup_query['genotype_class'] == 'Hom')))
row['HeterozygousMismatch'] = sum((pileup_ref['genotype_class'] != pileup_query['genotype_class']) & ((pileup_ref['genotype_class'] == 'Het') | (pileup_query['genotype_class'] == 'Het')))
row['CountOfCommonSites'] = len(pileup_query)
else:
# if there are no regions with enough coverage
row['HomozygousInRef'] = np.nan
row['TotalMatch'] = np.nan
row['HomozygousMatch'] = np.nan
row['HeterozygousMatch'] = np.nan
row['HomozygousMismatch'] = np.nan
row['HeterozygousMismatch'] = np.nan
row['CountOfCommonSites'] = 0
return row
def _compute_discordance_batch_job(self, batch_sample_pairs):
"""
batch job to take a batch of pairs of samples to compute discordance
"""
rows = []
for reference_sample, query_sample in batch_sample_pairs:
rows.append(self._compute_discordance(
reference_sample, query_sample))
return rows
def _compare_sample_lists(self, sample_set1, sample_set2, samples):
"""
Compare two lists of samples. Does so by first grouping the sample
comparisons into batches for parallel processing
"""
jobs = []
thread_pool = Pool(self.threads)
total_comparisons = len(sample_set1) * len(sample_set2)
parallel_batch_size = max(int(total_comparisons / self.threads), 1)
current_batch = []
for i, sample_name1 in enumerate(sample_set1):
for j, sample_name2 in enumerate(sample_set2):
current_batch.append([samples[sample_name1], samples[sample_name2]])
if len(current_batch) >= parallel_batch_size:
jobs.append(current_batch)
current_batch = []
# add any remaining jobs
if len(current_batch) > 0:
jobs.append(current_batch)
# analyze, collect results, and flatten the lists
results = thread_pool.map(self._compute_discordance_batch_job, jobs)
results = [item for sublist in results for item in sublist]
return results
def compare_samples(self, samples):
comparisons = []
samples_db = dict(filter(lambda x: x[1].query_group, samples.items()))
samples_input = dict(filter(
lambda x: not x[1].query_group, samples.items()))
# get the number of each type of sample and compute a ratio
# this is used to plot the heatmap when comparing with database
# samples
sample_n_db = len(samples_db)
sample_n_input = len(samples_input)
if sample_n_db > 0 and sample_n_input > 0 and sample_n_db > sample_n_input:
self.sample_type_ratio = sample_n_db / sample_n_input
# check to see if there are appropriate number of samples to
# do the analysis
if self.no_db_compare:
if len(samples_input) <= 1:
logger.warning("You should specify 2 or more samples in order to compare genotypes.")
else:
if len(samples_input) <= 1 and len(samples_db) < 1:
logger.warning("You should specify 2 or more samples in order to compare genotypes.")
# compare all the input samples to each other
results = self._compare_sample_lists(
samples_input, samples_input, samples)
for i in range(len(results)):
results[i]['IsInputToDatabaseComparison'] = False
comparisons += results
# for each input sample, compare with all the samples in the db
if not self.no_db_compare and sample_n_db > 0:
results = self._compare_sample_lists(
samples_input, samples_db, samples)
for i in range(len(results)):
results[i]['IsInputToDatabaseComparison'] = True
comparisons += results
comparisons = pd.DataFrame(comparisons)
# compute discordance rate
comparisons['DiscordanceRate'] = comparisons['HomozygousMismatch'] / (comparisons['HomozygousInRef'] + EPSILON)
# data['DiscordanceRate'] = data['DiscordanceRate'].map(lambda x: round(x, 6))
comparisons.loc[comparisons['HomozygousInRef'] < 10, 'DiscordanceRate'] = np.nan
# for each comparison, indicate if the match/mismatch is expected
# or not expected
comparisons.loc[comparisons['ReferenceSample']==comparisons['QuerySample'], 'DiscordanceRate'] = 0
comparisons['Matched'] = comparisons['DiscordanceRate'] < self.discordance_threshold
comparisons['ExpectedMatch'] = comparisons.apply(
lambda x: self.are_samples_same_group(
samples[x['ReferenceSample']],
samples[x['QuerySample']]), axis=1)
comparisons['Status'] = ''
comparisons.loc[comparisons['Matched'] & comparisons['ExpectedMatch'], 'Status'] = "Expected Match"
comparisons.loc[comparisons['Matched'] & ~comparisons['ExpectedMatch'], 'Status'] = "Unexpected Match"
comparisons.loc[
~comparisons['Matched'] & comparisons['ExpectedMatch'], 'Status'] = "Unexpected Mismatch"
comparisons.loc[
~comparisons['Matched'] & ~comparisons['ExpectedMatch'], 'Status'] = "Expected Mismatch"
comparisons.loc[pd.isna(comparisons['DiscordanceRate']), 'Status'] = ''
self.comparisons = comparisons[[
'ReferenceSample', 'ReferenceSampleGroup', 'QuerySample', 'QuerySampleGroup', 'IsInputToDatabaseComparison', 'CountOfCommonSites', 'HomozygousInRef', 'TotalMatch', 'HomozygousMatch', 'HeterozygousMatch', 'HomozygousMismatch',
'HeterozygousMismatch', 'DiscordanceRate', 'Matched',
'ExpectedMatch', 'Status']]
logger.info('Total comparisons: {}'.format(len(comparisons)))
logger.info('Count of expected matches: {}'.format(
len(comparisons[comparisons['Status']=="Expected Match"])))
logger.info('Count of unexpected matches: {}'.format(
len(comparisons[comparisons['Status']=="Unexpected Match"])))
logger.info('Count of unexpected mismatches: {}'.format(
len(comparisons[comparisons['Status']=="Unexpected Mismatch"])))
logger.info('Count of expected mismatches: {}'.format(
len(comparisons[comparisons['Status']=="Expected Mismatch"])))
return self.comparisons
<file_sep>/README.md
# biometrics
Package to generate sample based biometrics
[](https://travis-ci.com/msk-access/biometrics) [](https://pypi.python.org/pypi/biometrics)
* Free software: Apache Software License 2.0
* Documentation: https://msk-access.gitbook.io/biometrics/
* GitHub: https://github.com/msk-access/biometrics/
## Installation
From pypi:
`pip install biometrics`
From conda (python v3.6 only):
`conda create -n myenv -c bioconda -c conda-forge -c msk-access python=3.6 biometrics`
<file_sep>/docs/cluster.md
---
description: For clustering samples into groups using genotype comparison data.
---
# Cluster
Takes as input the results from running `biometrics genotype` and clusters the samples together using the discordance rate. Done by thresholding the discordance rate into 0 or 1, where 1 means the sample pair came from the same patient. The default discordance rate threshold is 0.05, but you can change it via the `--discordance-threshold` argument. The tool then uses the `networkx` package to get the groups of samples that are connected.
{% hint style="info" %}
When you run `biometrics genotype`, it automatically outputs two sets of clustering results: \(1\) the first set just clusters your input samples, and \(2\) the second set clusters your input samples and samples in the database.
{% endhint %}
{% hint style="warning" %}
Due to the limitations of the discordance rate metric, samples that have contamination can lead to many false positive matches using this clustering approach. Hence, you might want to consider removing contaminated samples before running this tool.
{% endhint %}
## How to run the tool
You simply need to provide the CSV file that is outputted from running `biometrics genotype`.
```text
biometrics cluster \
-i genotype_comparison.csv \
-o genotype_clusters.csv
```
You can also specify multiple inputs. It will automatically drop duplicate comparisons.
```text
biometrics cluster \
-i genotype_comparison_1.csv \
-i genotype_comparison_2.csv \
-i genotype_comparison_3.csv \
-o genotype_clusters.csv
```
## Output
Produces a CSV file that contains the clustering results. Each row corresponds to a different sample. The table below provides a description on each column.
| Column Name | Description |
| :--- | :--- |
| sample\_name | The sample name. |
| expected\_sample\_group | The expected group for the sample based on user input. |
| cluster\_index | The integer cluster index. All rows with the same cluster\_index are in the same cluster. |
| cluster\_size | The size of the cluster this sample is in. |
| avg\_discordance | The average discordance between this sample and all other samples in the cluster. |
| count\_expected\_matches | The count of expected matches when comparing the sample to all others in the cluster. |
| count\_unexpected\_matches | The count of unexpected matches when comparing the sample to all others in the cluster. |
| count\_expected\_mismatches | The count of expected mismatches when comparing the sample to all other samples \(inside and outside its cluster\). |
| count\_unexpected\_mismatches | The count of unexpected mismatches when comparing the sample to all other samples \(inside and outside its cluster\). |
<file_sep>/docs/README.md
# biometrics
Python package for genotyping samples, calculating sample contamination metrics, and sample sex verification.
[](https://travis-ci.com/msk-access/biometrics) [](https://pypi.python.org/pypi/biometrics)
* Free software: Apache Software License 2.0
* Documentation: [https://msk-access.gitbook.io/biometrics/](https://msk-access.gitbook.io/biometrics/)
## Installation
From pypi:
`pip install biometrics`
From conda (python v3.6 only):
`conda create -n myenv -c bioconda -c conda-forge -c msk-access python=3.6 biometrics`
<file_sep>/biometrics/cli.py
#!/usr/bin/env python
"""Console script for biometrics."""
import sys
import os
import argparse
import biometrics
from biometrics.utils import get_logger
from biometrics.biometrics import run_biometrics
logger = get_logger()
def add_extraction_args(parser):
parser.add_argument(
'-i', '--input', action="append", required=False,
help='''Path to file containing sample information (one per line).
For example: sample_name,sample_bam,sample_type,sample_sex,sample_group''')
parser.add_argument(
'-sb', '--sample-bam', action="append", required=False,
help='''Space-delimited list of BAM files.''')
parser.add_argument(
'-st', '--sample-type', action="append", required=False,
help='''Space-delimited list of sample types: Normal or Tumor.
Must be in the same order as --sample-bam.''')
parser.add_argument(
'-ss', '--sample-sex', action="append", required=False,
help='''Space-delimited list of sample sex (i.e. M or F). Must be
in the same order as --sample-bam.''')
parser.add_argument(
'-sg', '--sample-group', action="append", required=False,
help='''Space-delimited list of sample group information
(e.g. sample patient ID). Must be in the same order as --sample-bam.''')
parser.add_argument(
'-sn', '--sample-name', action="append", required=False,
help='''Space-delimited list of sample names. If not specified,
sample name is automatically figured out from the BAM file. Must
be in the same order as --sample-bam.''')
parser.add_argument(
'--vcf', required=False,
help='''VCF file containing the sites to be queried.''')
parser.add_argument(
'--bed', required=False,
help='''BED file containing the intervals to be queried.''')
parser.add_argument(
'-db', '--database', default=os.curdir,
help='''Directory to store the intermediate files after
running the extraction step.''')
parser.add_argument(
'-ov', '--overwrite', action='store_true',
help='''Overwrite any existing extraction results.''')
parser.add_argument(
'-f', '--fafile', required=True,
help='''Path to reference fasta file.''')
parser.add_argument(
'-q', '--min-mapping-quality', default=1, type=int,
help='''Minimum mapping quality of reads to be used for pileup.''')
parser.add_argument(
'-Q', '--min-base-quality', default=1, type=int,
help='''Minimum base quality of reads to be used for pileup.''')
parser.add_argument(
'-mc', '--min-coverage', default=10, type=int,
help='''Minimum coverage to count a site.''')
parser.add_argument(
'-mht', '--min-homozygous-thresh', default=0.1, type=float,
help='''Minimum threshold to define homozygous.''')
parser.add_argument(
'--default-genotype', default=None,
help='''Default genotype if coverage is too low (options are Het or Hom).''')
parser.add_argument(
'-t', '--threads', default=1, type=int,
help='''Number of threads to use to extract the samples.''')
return parser
def add_common_tool_args(parser):
parser.add_argument(
'-i', '--input', action="append", required=True,
help='''Can be one of three types: (1) path to a CSV file containing sample information (one per line). For example: sample_name,sample_bam,sample_type,sample_sex,sample_group. (2) Path to a \'*.pk\' file that was produced by the \'extract\' tool. (3) Name of the sample to analyze; this assumes there is a file named \'{sample_name}.pk\' in your database directory. Can be specified more than once.''')
parser.add_argument(
'-db', '--database', default=os.curdir,
help='''Directory to store the intermediate files after
running the extraction step.''')
parser.add_argument(
'-o', '--outdir', default='.',
help='''Output directory for results.''')
parser.add_argument(
'--prefix', default=None,
help='''Output file prefix.''')
parser.add_argument(
'-j', '--json', action='store_true',
help='''Also output data in JSON format.''')
parser.add_argument(
'-nc', '--no-db-compare', action='store_true',
help='''Do not compare the sample(s) you provided to all samples
in the database, only compare them with each other.''')
return parser
def check_arg_equal_len(vals1, vals2, name):
if vals2 is not None and len(vals1) != len(vals2):
logger.error(
'{} does not have the same number of items as --sample-bam'.format(name))
sys.exit(1)
def check_args(args):
if args.subparser_name == 'cluster':
return
if args.subparser_name != 'extract' and \
not args.input and not args.sample_name:
logger.error('You must specify either --input or --sample-name')
sys.exit(1)
if args.subparser_name == 'extract' and \
not args.input and not args.sample_bam:
logger.error(
'The extraction tool requires that you specify either --input or --sample-bam')
sys.exit(1)
if args.subparser_name == 'extract' and not args.input:
check_arg_equal_len(args.sample_name, args.sample_bam, '--sample-bam')
check_arg_equal_len(args.sample_name, args.sample_type, '--sample-type')
check_arg_equal_len(
args.sample_name, args.sample_group, '--sample-group')
check_arg_equal_len(args.sample_name, args.sample_sex, '--sample-sex')
def get_args():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='''Various tools for fingerprinting samples from BAM files.
Sample information to each sub command is supplied via input file(s)
and/or as individual samples.''')
subparsers = parser.add_subparsers(help='', dest="subparser_name")
parser.add_argument(
'-v', '--version', action='store_true',
help='''Print the version.''')
# extract parser
parser_extract = subparsers.add_parser(
'extract',
help='''Intermediate step to extract genotype info from one or more
samples. The output from this step is required for the rest of the
fingerprinting tools. However, you do not need to run this step
manually since it will run automatically if the necessary files
are missing.''',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser_extract = add_extraction_args(parser_extract)
# sex mismatch parser
parser_sexmismatch = subparsers.add_parser(
'sexmismatch', help='Check for sex mismatches.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser_sexmismatch = add_common_tool_args(parser_sexmismatch)
parser_sexmismatch.add_argument(
'--coverage-threshold', default=50, type=int,
help='''Samples with Y chromosome above this value will be considered male.''')
# minor contamination parser
parser_minor = subparsers.add_parser(
'minor', help='Check for minor contamination.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser_minor = add_common_tool_args(parser_minor)
parser_minor.add_argument(
'-p', '--plot', action='store_true',
help='''Also output plots of the data.''')
parser_minor.add_argument(
'--minor-threshold', default=0.002, type=float,
help='''Minor contamination threshold for bad sample.''')
# major contamination parser
parser_major = subparsers.add_parser(
'major', help='Check for major contamination.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser_major = add_common_tool_args(parser_major)
parser_major.add_argument(
'-p', '--plot', action='store_true',
help='''Also output plots of the data.''')
parser_major.add_argument(
'--major-threshold', default=0.6, type=float,
help='''Major contamination threshold for bad sample.''')
# genotyping parser
parser_genotype = subparsers.add_parser(
'genotype', help='Compare sample genotypes to find matches/mismatches.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser_genotype = add_common_tool_args(parser_genotype)
parser_genotype.add_argument(
'-p', '--plot', action='store_true',
help='''Also output plots of the data.''')
parser_genotype.add_argument(
'--discordance-threshold', default=0.05, type=float,
help='''Discordance values less than this are regarded
as matching samples.''')
parser_genotype.add_argument(
'-t', '--threads', default=1, type=int,
help='''Number of threads to use to extract the samples.''')
parser_genotype.add_argument(
'--zmin', type=float,
help='''Minimum z value for the colorscale on the heatmap.''')
parser_genotype.add_argument(
'--zmax', type=float,
help='''Maximum z value for the colorscale on the heatmap.''')
# cluster parser
parser_cluster = subparsers.add_parser(
'cluster', help='Cluster genotype comparison results.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser_cluster.add_argument(
'-i', '--input', action="append", required=True,
help='''Path to file containing output form \'biometrics genotype\' tool.
Can be specified more than once.''')
parser_cluster.add_argument(
'-o', '--output', default='genotype_clusters.csv',
help='''Output filename.''')
parser_cluster.add_argument(
'--discordance-threshold', default=0.05, type=float,
help='''Discordance values less than this are regarded
as matching samples.''')
args = parser.parse_args()
if args.version:
print(biometrics.__version__)
sys.exit(0)
check_args(args)
return args
def main():
args = get_args()
run_biometrics(args)
return 0
if __name__ == "__main__":
sys.exit(main())
<file_sep>/biometrics/extract.py
import os
from multiprocessing import Pool
import pandas as pd
import numpy as np
import vcf
from pysam import AlignmentFile
class Extract:
"""
Class for extracting genotype information from alignment file using
the user supplied VCF file.
"""
def __init__(self, args):
self.db = args.database
self.threads = args.threads
self.min_mapping_quality = args.min_mapping_quality
self.min_base_quality = args.min_base_quality
self.default_genotype = args.default_genotype
self.vcf = args.vcf
self.bed = args.bed
self.fafile = args.fafile
self.overwrite = args.overwrite
self.min_coverage = args.min_coverage
self.min_homozygous_thresh = args.min_homozygous_thresh
self.sites = []
self.regions = None
self._parse_vcf()
self._parse_bed_file()
def _parse_vcf(self):
if self.vcf is None:
return
for record in vcf.Reader(open(self.vcf, 'r')):
self.sites.append({
'chrom': record.CHROM,
'start': record.POS-1,
'end': record.POS,
'ref_allele': str(record.REF),
'alt_allele': str(record.ALT[0])
})
def _parse_bed_file(self):
if self.bed is None:
return
self.regions = pd.read_csv(self.bed, sep='\t', header=None)
# only keep Y chrom regions
self.regions = self.regions[self.regions[0].isin(['Y', 'chrY'])]
if len(self.regions) == 0:
print('There are no Y chromosome regions. Cannot determine if there is a sex mismatch.')
self.regions.columns = range(self.regions.shape[1])
def _extract_regions(self, sample):
"""
Code to extract the coverage information for the regions listed
in the BED file.
"""
if self.regions is None:
return sample
# get the pileup
bam = AlignmentFile(sample.sample_bam)
region_counts = []
for i in self.regions.index:
chrom = self.regions.at[i, 0]
start = int(self.regions.at[i, 1])
end = int(self.regions.at[i, 2])
count = bam.count(chrom, start, end)
region_counts.append({
'chrom': chrom,
'start': start,
'end': end,
'count': count})
if len(region_counts) > 0:
region_counts = pd.DataFrame(region_counts)
sample.region_counts = region_counts
return sample
def _get_minor_allele_freq(self, allele_counts):
coverage = sum(allele_counts)
if coverage < self.min_coverage or coverage == 0:
return np.nan
else:
return min(allele_counts) / coverage
def _get_genotype_class(self, minor_allele_freq):
"""
Determine if Het, Hom, or unknown/NA.
"""
if pd.isna(minor_allele_freq):
if self.default_genotype is not None:
return self.default_genotype
return np.nan
else:
if minor_allele_freq <= self.min_homozygous_thresh:
return 'Hom'
else:
return 'Het'
def _get_genotype(self, genotype, allele_counts, alleles):
"""
Get the genotype in terms of the allele(s) (e.g. A, T, AT, GC, etc.)
"""
if pd.isna(genotype):
return np.nan
elif genotype == 'Het':
return ''.join(alleles)
else:
if allele_counts[0] > allele_counts[1]:
return alleles[0]
else:
return alleles[1]
def _get_genotype_info(self, pileup_site, ref_allele, alt_allele):
"""
Plot minor contamination data.
"""
allele_counts = [pileup_site[ref_allele], pileup_site[alt_allele]]
pileup_site['minor_allele_freq'] = self._get_minor_allele_freq(
allele_counts)
pileup_site['genotype_class'] = self._get_genotype_class(
pileup_site['minor_allele_freq'])
pileup_site['genotype'] = self._get_genotype(
pileup_site['genotype_class'], allele_counts,
[ref_allele, alt_allele])
return pileup_site
def _add_base(self, site, old_base, old_base_qual, new_base,
new_base_qual):
"""
This function is for dealing with the various scenarios that can
arise when a read pair overlaps and how to handle when the
bases mismatch. The 'old_base' refers to the first base observed when
computing pileup information (usually the forward read). Then the
'new_base' is from the second read in the overlaping pair.
"""
if old_base is None:
return [new_base, new_base_qual]
if old_base == new_base:
return [old_base, old_base_qual]
if old_base != 'N' and new_base != 'N':
if new_base == site['ref_allele']:
return [new_base, new_base_qual]
else:
return [old_base, old_base_qual]
if old_base == site['ref_allele']:
return [old_base, old_base_qual]
elif new_base == site['ref_allele']:
return [new_base, new_base_qual]
elif old_base == site['alt_allele'] and old_base_qual >= '!':
return [old_base, old_base_qual]
elif new_base == site['alt_allele'] and new_base_qual >= '!':
return [new_base, new_base_qual]
else:
return ['N', '&']
def _pileup(self, bam, site):
"""
Get the per-site pileup information.
"""
read_data = {}
allele_counts = {'A': 0, 'C': 0, 'G': 0, 'T': 0, 'N': 0}
for pileupcolumn in bam.pileup(
contig=site['chrom'], start=site['start'], end=site['end'],
truncate=True, max_depth=30000, stepper='nofilter',
min_base_quality=self.min_base_quality):
for pileupread in pileupcolumn.pileups:
if pileupread.query_position is None:
continue
mapq = pileupread.alignment.mapping_quality
read_name = pileupread.alignment.qname
base = pileupread.alignment.query_sequence[pileupread.query_position]
# temporary fix for when alignment qualities contain non-ascii characters, which
# happens sometimes from fgbio duplex sequening toolset
try:
base_qual = pileupread.alignment.qual[pileupread.query_position]
except:
base_qual = 30
if (mapq < self.min_mapping_quality) or pileupread.is_refskip or pileupread.is_del:
# skip the read if its mapping quality is too low
# or if the site is part of an indel
continue
if read_name in read_data and read_data[read_name][0] == 'N':
continue
elif read_name in read_data:
vals = self._add_base(
site, read_data[read_name][0],
read_data[read_name][1], base, base_qual)
read_data[read_name] = vals[0:2]
else:
read_data[read_name] = [base, base_qual]
total = 0
matches = 0
mismatches = 0
for read, base_data in read_data.items():
allele_counts[base_data[0]] += 1
total += 1
if base_data[0] == site['ref_allele']:
matches += 1
else:
mismatches += 1
return {
'chrom': site['chrom'],
'pos': site['end'],
'ref': site['ref_allele'],
'alt': site['alt_allele'],
'reads_all': total,
'matches': matches,
'mismatches': mismatches,
'A': allele_counts['A'],
'C': allele_counts['C'],
'T': allele_counts['T'],
'G': allele_counts['G'],
'N': allele_counts['N']
}
def _extract_sites(self, sample):
"""
Loop through all positions and get pileup information.
"""
if not self.sites:
return sample
# get the pileup
bam = AlignmentFile(sample.sample_bam)
pileup = pd.DataFrame()
for site in self.sites:
pileup_site = self._pileup(bam, site)
pileup_site = self._get_genotype_info(
pileup_site, site['ref_allele'], site['alt_allele'])
pileup = pileup.append(pileup_site, ignore_index=True)
pileup = pileup[[
'chrom', 'pos', 'ref', 'alt', 'reads_all', 'matches', 'mismatches',
'A', 'C', 'T', 'G', 'N', 'minor_allele_freq', 'genotype_class',
'genotype']]
for col in ['pos', 'A', 'C', 'T', 'G', 'N', 'matches', 'mismatches', 'reads_all']:
pileup[col] = pileup[col].astype(int)
sample.pileup = pileup
return sample
def _extraction_job(self, sample):
"""
Function to do the extraction steps for a single sample.
Supposed to be called by multiprocessing functions to parallelize it.
"""
sample = self._extract_sites(sample)
sample = self._extract_regions(sample)
sample.save_to_file()
return sample
def extract(self, samples):
"""
Function to call to extract the pileup and region information
for the given samples.
"""
if type(samples) != dict:
samples = {samples.sample_name: samples}
# determine with samples need to be extracted, and put them in a list
samples_to_extract = []
for sample_name, sample in samples.items():
# if extraction file exists then load it
if os.path.exists(sample.extraction_file) and not self.overwrite:
sample.load_from_file()
continue
samples_to_extract.append(sample)
# if any samples need to be extracted, then do so
# (using multiprocessing)
if len(samples_to_extract) > 0:
thread_pool = Pool(self.threads)
samples_processed = thread_pool.map(
self._extraction_job, samples_to_extract)
for sample in samples_processed:
samples[sample.sample_name] = sample
return samples
<file_sep>/docs/extraction.md
---
description: Step for preparing the BAM file(s)
---
# Extraction
Running this step is a **prerequisite** before running any of the other tools. This step extracts the pileup and coverage information from your BAM file\(s\) and stores the result in a Python pickle file \(which contains JSON data\). You can determine where to store the output files by specifying `-db` argument. This allows for much faster analyses that make repeated use of your samples.
There are two main types of required input:
* **Sample information:** the BAM file and any associate annotation \(e.g. sample grouping\).
* **Supporting files:** reference FASTA, VCF, and BED file.
Moreover, there are two ways to provide the sample information: \(1\) provide a CSV file, or \(2\) specify via the command line arguments.
## CSV input
This method is easier for when you have many samples. Just provide a CSV file with five columns: sample name, sample group, sample type, sample sex, and path to the sample's BAM file. An example with three samples is below:
```text
sample_name,sample_group,sample_type,sample_sex,sample_bam
C-48665L-N001-d,C-48665L,Normal,F,/path/to/C-48665L-N001-d.bam
C-PCYP90-N001-d,C-PCYP90,Normal,M,/path/to/C-PCYP90-N001-d.bam
C-MH6AL9-N001-d,C-MH6AL9,Normal,F,/path/to/C-MH6AL9-N001-d.bam
```
Here is an example command line usage for three samples:
```text
biometrics extract \
-i inputs.csv \
--vcf /path/to/vcf \
--bed /path/to/bed/file \
-db /path/to/store/extract/output \
-f /path/to/reference.fasta
```
## Command line input
You can also specify each of your samples via command line arguments. Here is an example:
```text
biometrics extract \
-sn C-48665L-N001-d C-PCYP90-N001-d C-MH6AL9-N001-d \
-sb /path/to/C-48665L-N001-d.bam /path/to/C-PCYP90-N001-d.bam /path/to/C-MH6AL9-N001-d.bam \
-st Normal Normal Normal \
-ss F M F \
-sg C-48665L C-PCYP90 C-MH6AL9 \
--vcf /path/to/vcf \
--bed /path/to/bed/file \
-db /path/to/store/extract/output \
-f /path/to/reference.fasta
```
| e568069fd04a4c9f5fc9c3c2aa8331a43b69b51b | [
"Markdown",
"Python",
"Text",
"Dockerfile",
"Shell"
]
| 27 | Python | msk-access/biometrics | 1e87bd5b8a248f06aba6400677ecc7eea771c535 | b3f0b192f36ead38af4ddfcf92a40a4957303d5e |
refs/heads/master | <repo_name>skyeeenet/luis<file_sep>/README.md
## LUIS TEMPLATE
It was standard PSD to HTML work. <br>
The model was a typical landing page and was installed in 4 hours only via flexbox.
As result we have ready html responsive layout.
#### How can you check out work ? <br>
1. Download repository as ZIP archive
2. Unzip downloaded repository
3. Open file "index.html" via browser
<file_sep>/scripts/dropdown.js
var btn = $('#btn-show');
var dropdown = $('#dropdown-menu');
var flag = true;
btn.click(function () {
if (flag) {
dropdown.slideDown();
} else {
dropdown.slideUp();
}
flag = !flag;
});
$('.menu-btn').on('click', function (e) {
e.preventDefault();
$(this).toggleClass('menu-btn-active');
}); | ac2de1b68919bf9e740d5daf8e02499c79b8bed4 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | skyeeenet/luis | 1b533ae4cdfc966825f665b88512572a2a2819d1 | 7f2e93295e36a2c49f189deb6dc967486e108a09 |
refs/heads/main | <file_sep>package database
import (
"testing"
"github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/domain/entities"
"github.com/stretchr/testify/assert"
sqlxmock "github.com/zhashkevych/go-sqlxmock"
)
type DBTest struct{}
func NewPgEventStorageMock(t *testing.T) (*PgLinkStorage, sqlxmock.Sqlmock) {
db, mock, err := sqlxmock.Newx()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
obj, err := check(db)
if err != nil {
t.Fatalf("an error '%s' was in check", err)
}
return obj, mock
}
func Test_GetLinkByFrom(t *testing.T) {
linkStorage, mock := NewPgEventStorageMock(t)
tests := []struct {
name string
mock func()
linkFrom string
linkTo string
wantErr bool
}{
{
name: "Found",
mock: func() {
rows := sqlxmock.NewRows([]string{"fromlink"}).AddRow("/to")
mock.ExpectQuery("SELECT toLink FROM links").WithArgs("/from").WillReturnRows(rows)
},
linkFrom: "/from",
linkTo: "/to",
wantErr: false,
},
{
name: "Not Found",
mock: func() {
rows := sqlxmock.NewRows([]string{"fromlink"})
mock.ExpectQuery("SELECT toLink FROM links").WithArgs("/from").WillReturnRows(rows)
},
linkFrom: "/from",
linkTo: "",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.mock()
to, err := linkStorage.GetLinkByFrom("/from")
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.linkTo, to)
}
})
}
}
func Test_SaveLink(t *testing.T) {
linkStorage, mock := NewPgEventStorageMock(t)
tests := []struct {
name string
mock func()
link entities.Link
success bool
wantErr bool
}{
{
name: "Success",
mock: func() {
rows := sqlxmock.NewRows([]string{"success"}).AddRow("true")
mock.ExpectQuery("INSERT INTO links").WithArgs("/from", "/to").WillReturnRows(rows)
},
link: entities.Link{From: "/from", To: "/to"},
success: true,
},
{
name: "Error",
mock: func() {
rows := sqlxmock.NewRows([]string{"success"}).AddRow("false")
mock.ExpectQuery("INSERT INTO links").WithArgs("/from", "/to").WillReturnRows(rows)
},
link: entities.Link{From: "/from", To: "/true"},
success: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.mock()
success := linkStorage.SaveLink(tt.link)
// fmt.Println(mock.ExpectationsWereMet())
assert.Equal(t, tt.success, success, "Test name: %s", tt.name)
})
}
}
<file_sep>package api
import (
"bytes"
"net/http/httptest"
"testing"
"github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/domain/entities"
err "github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/domain/errors"
"github.com/stretchr/testify/assert"
)
type LinkUseCasesTest struct {
name string
f string
t string
e error
}
func (luct *LinkUseCasesTest) GetLinkByFrom(from string) (string, error) {
return luct.t, luct.e
}
func (luct *LinkUseCasesTest) CreateLink(requestData entities.Link) error {
return luct.e
}
func Test(t *testing.T) {
t.Run("GetLinkByFrom", func(t *testing.T) {
for _, test := range []LinkUseCasesTest{
{"empty from", "", "", err.ErrEmptyFromLink},
{"not empty from", "/from", "/to", nil},
{"usecase error", "/from", "/to", err.ErrEmptyToLink},
} {
server := &HttpServer{
LinkUseCases: &test,
}
to, err := server.GetLinkByFrom(test.f)
assert.Equal(t, to, test.t, "should be equal "+test.name)
assert.Equal(t, err, test.e, "should be equal "+test.name)
}
})
t.Run("CreateLink", func(t *testing.T) {
for _, test := range []LinkUseCasesTest{
{"error", "", "", err.ErrEmptyFromLink},
{"not error", "/from", "/to", nil},
} {
server := &HttpServer{
LinkUseCases: &test,
}
err := server.CreateLink(entities.Link{
From: test.f,
To: test.t,
})
assert.Equal(t, err, test.e, "should be equal "+test.name)
}
})
t.Run("Like integration POST", func(t *testing.T) {
{
req := httptest.NewRequest("POST", "/", nil)
recorder := httptest.NewRecorder()
server := &HttpServer{
LinkUseCases: &LinkUseCasesTest{
"not error", "/from", "/to", nil,
},
}
server.ServeHTTP(recorder, req)
}
{
jsonStr := []byte(`{"from":"/from", "to":"/to"}`)
req := httptest.NewRequest("POST", "/", bytes.NewBuffer(jsonStr))
recorder := httptest.NewRecorder()
server := &HttpServer{
LinkUseCases: &LinkUseCasesTest{
"not error", "/from", "/to", nil,
},
}
server.ServeHTTP(recorder, req)
}
{
jsonStr := []byte(`{"from":"", "to":""}`)
req := httptest.NewRequest("POST", "/", bytes.NewBuffer(jsonStr))
recorder := httptest.NewRecorder()
server := &HttpServer{
LinkUseCases: &LinkUseCasesTest{
"error", "", "", err.ErrEmptyFromLink,
},
}
server.ServeHTTP(recorder, req)
}
})
t.Run("Like integration GET", func(t *testing.T) {
{
req := httptest.NewRequest("GET", "/", nil)
recorder := httptest.NewRecorder()
server := &HttpServer{
LinkUseCases: &LinkUseCasesTest{"error", "", "", err.ErrEmptyFromLink},
}
server.ServeHTTP(recorder, req)
}
{
req := httptest.NewRequest("GET", "/", nil)
recorder := httptest.NewRecorder()
server := &HttpServer{
LinkUseCases: &LinkUseCasesTest{"not error", "/from", "/to", nil},
}
server.ServeHTTP(recorder, req)
}
})
/*
t.Run("up and down real server", func(t *testing.T) {
server := &HttpServer{
LinkUseCases: &LinkUseCasesTest{},
}
go func() {
done <- syscall.SIGINT
}()
server.Serve(":8080")
})
*/
}
<file_sep>module github.com/alekseysychev/avito-auto-backend-trainee-assignment
go 1.16
require (
github.com/cockroachdb/apd v1.1.0 // indirect
github.com/gofrs/uuid v4.0.0+incompatible // indirect
github.com/jackc/fake v0.0.0-20150926172116-812a484cc733 // indirect
github.com/jackc/pgx v3.6.2+incompatible
github.com/jmoiron/sqlx v1.3.1
github.com/pkg/errors v0.8.1 // indirect
github.com/shopspring/decimal v1.2.0 // indirect
github.com/stretchr/testify v1.7.0
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect
golang.org/x/text v0.3.3 // indirect
)
<file_sep>package database
import (
"github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/domain/entities"
_ "github.com/jackc/pgx/stdlib"
"github.com/jmoiron/sqlx"
)
type PgLinkStorage struct {
db *sqlx.DB
}
func NewPgEventStorage(dsn string) (*PgLinkStorage, error) {
db, err := sqlx.Open("pgx", dsn)
if err != nil {
return nil, err
}
return check(db)
}
func check(db *sqlx.DB) (*PgLinkStorage, error) {
err := db.Ping()
if err != nil {
return nil, err
}
return &PgLinkStorage{db: db}, nil
}
func (pges *PgLinkStorage) GetLinkByFrom(from string) (string, error) {
var toLink string
row := pges.db.QueryRow("SELECT toLink FROM links WHERE fromLink = $1", from)
if err := row.Scan(&toLink); err != nil {
return "", err
}
return toLink, nil
}
func (pges *PgLinkStorage) SaveLink(link entities.Link) bool {
row := pges.db.QueryRow("INSERT INTO links (fromlink, tolink) VALUES ($1, $2) ON CONFLICT DO NOTHING RETURNING true;",
link.From, link.To)
var success bool
if err := row.Scan(&success); err != nil {
return false
}
return success
}
<file_sep># Environment
FROM golang:1.16 as build-env
RUN mkdir -p /opt/avito-auto-backend-trainee-assignment
WORKDIR /opt/avito-auto-backend-trainee-assignment
COPY . .
RUN go mod download
RUN pwd
RUN CGO_ENABLED=0 go build -o /opt/service/http_server /opt/avito-auto-backend-trainee-assignment/cmd/http_server
# Release
FROM alpine:latest
COPY --from=build-env /opt/service/http_server /bin/http_server
ENTRYPOINT ["/bin/http_server"]<file_sep>package interfaces
import (
"github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/domain/entities"
)
type LinkStorage interface {
GetLinkByFrom(from string) (string, error)
SaveLink(link entities.Link) bool
}
<file_sep>package api
import (
"context"
"encoding/json"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/domain/entities"
)
type linkUsecaseInteface interface {
GetLinkByFrom(from string) (string, error)
CreateLink(requestData entities.Link) error
}
type HttpServer struct {
LinkUseCases linkUsecaseInteface
}
func (hs *HttpServer) GetLinkByFrom(from string) (string, error) {
to, err := hs.LinkUseCases.GetLinkByFrom(from)
return to, err
}
func (hs *HttpServer) CreateLink(requestData entities.Link) error {
err := hs.LinkUseCases.CreateLink(requestData)
return err
}
func (hs *HttpServer) get(rw http.ResponseWriter, r *http.Request) {
from := r.URL.Path
to, err := hs.GetLinkByFrom(from)
if err != nil {
rw.WriteHeader(http.StatusNotFound)
return
}
rw.Header().Add("Location", to)
rw.WriteHeader(http.StatusFound)
}
func (hs *HttpServer) post(rw http.ResponseWriter, r *http.Request) {
var err error
var requestData entities.Link
decoder := json.NewDecoder(r.Body)
err = decoder.Decode(&requestData)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
return
}
err = hs.CreateLink(requestData)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
log.Println(err)
return
}
rw.WriteHeader(http.StatusCreated)
}
func (hs *HttpServer) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
hs.get(rw, r)
case http.MethodPost:
hs.post(rw, r)
}
}
var done chan os.Signal
func (hs *HttpServer) Serve(addr string) {
http.Handle("/", hs)
s := &http.Server{
Addr: addr,
Handler: nil,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
done = make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
log.Print("Server Started")
<-done
log.Print("\rServer Stopped ")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
// extra handling here
cancel()
}()
if err := s.Shutdown(ctx); err != nil {
log.Fatalf("Server Shutdown Failed: %+v", err)
}
log.Print("Server Exited Properly")
}
<file_sep>[](https://codecov.io/gh/alekseysychev/avito-auto-backend-trainee-assignment)
[Сссылка на репозиторий](https://github.com/avito-tech/auto-backend-trainee-assignment)
Начал делать просто для практики.
В принципе рабочий сервис, разворачивается, проходят тесты, но нужно переделать 70% кода.
- Так и не понял как сгенерировать ссылку случайную и вставить её в базу данных таким образом, что бы она была уникальная, решил через перегенерирование ссылки, но мне кажется это костыль. Почему то очень хочется заранее сгенерировать все возможные варианты ссылок и вставлять просто на первую попавшуюся пустую.
- При вставке с генерацией ссылки не ясно какая ссылка была сгенерирована, надо переделать, что бы возвращался объект {"from":"","to":""}
- Нужен маршрут для получения списка ссылок
- Нужен маршрут для получения информации о одной ссылке
- Нужна проверка корректности ссылок. Как... Самый простой способ прогнать ссылку через регулярку, а потом сделать http запрос, ожидая 200. Может быть ещё что то придумать
- Переделать тесты, так как некоторые высосаны из пальца и сделаны только что бы покрытие было в % больше, чем на самом деле.
- Добавить in-memory кеш для ссылок. Но тут вопрос, обычный или lru. (lru что бы память не убить, но он медленнее будет на мой взгляд)<file_sep>package main
import (
"os"
"testing"
)
func Test(t *testing.T) {
os.Setenv("DB_DSN", "-")
main()
}
<file_sep>package main
import (
"log"
"os"
"github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/adapters/api"
"github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/adapters/database"
"github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/domain/usecases"
)
func main() {
dsn := os.Getenv("DB_DSN")
if dsn == "" {
dsn = "postgres://user:password@localhost:5432/postgres?sslmode=disable"
}
addr := os.Getenv("HTTP_SERVER_ADDR")
if addr == "" {
addr = ":8080"
}
linkStorage, err := database.NewPgEventStorage(dsn)
if err != nil {
log.Println(err)
return
}
linkCases := &usecases.LinkService{
LinkStorage: linkStorage,
}
server := &api.HttpServer{
LinkUseCases: linkCases,
}
server.Serve(addr)
}
<file_sep>package errors
import "errors"
var (
ErrEmptyFromLink = errors.New("empty from link")
ErrEmptyToLink = errors.New("empty to link")
ErrFromAlreadyExist = errors.New("from already exist")
ErrCantInsertNewData = errors.New("cant insert new data")
)
<file_sep>CREATE TABLE links (
fromLink VARCHAR(255) PRIMARY KEY,
toLink VARCHAR(255) NOT NULL
);<file_sep>package entities
type Link struct {
From string `json:"from" field:"linkFrom"`
To string `json:"to" field:"linkTo"`
}
<file_sep>package usecases
import (
"math/rand"
"testing"
"github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/domain/entities"
err "github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/domain/errors"
"github.com/stretchr/testify/assert"
)
type LinkStorageTest struct {
s string
e error
b bool
}
func (lst *LinkStorageTest) GetLinkByFrom(from string) (string, error) {
return lst.s, lst.e
}
func (lst *LinkStorageTest) SaveLink(link entities.Link) bool {
return lst.b
}
func Test(t *testing.T) {
t.Run("GetLinkByFrom", func(t *testing.T) {
for _, test := range []struct {
n string
f string
t string
e error
}{
{"empty from", "", "", err.ErrEmptyFromLink},
{"ot empty from", "/from", "/to", nil},
} {
service := LinkService{
LinkStorage: &LinkStorageTest{
s: test.t,
e: test.e,
},
}
to, err := service.GetLinkByFrom(test.f)
assert.Equal(t, to, test.t, "should be equal "+test.n)
assert.Equal(t, err, test.e, "should be equal "+test.n)
}
})
t.Run("generateRandomLink len", func(t *testing.T) {
for _, test := range []struct {
na string
n int
w int
}{
{"zero", 0, 6},
{"low", rand.Int() * -1, 6},
{"max", rand.Int() + 21, 6},
{"six", 6, 6},
{"four", 4, 4},
} {
r := generateRandomLink(test.n)
assert.Equal(t, len(r), test.w, "should be equal "+test.na)
}
})
t.Run("generateRandomLink just generate", func(t *testing.T) {
r1 := generateRandomLink(6)
r2 := generateRandomLink(6)
assert.NotEqual(t, r1, r2, "should be not equal")
})
t.Run("CreateLink", func(t *testing.T) {
for _, test := range []struct {
n string
f string
t string
e error
b bool
}{
{"empty from & to", "", "", err.ErrEmptyToLink, false},
{"empty from", "", "/to", nil, true},
{"empty from", "", "/to", err.ErrCantInsertNewData, false},
{"not empty from & to", "/from", "/to", nil, true},
{"not empty from & to But databaseError", "/from", "/to", err.ErrFromAlreadyExist, false},
} {
service := LinkService{
LinkStorage: &LinkStorageTest{
s: test.f,
e: test.e,
b: test.b,
},
}
err := service.CreateLink(entities.Link{
From: test.f,
To: test.t,
})
// println("\n\n")
// println(err.Error())
println("\n\n")
assert.Equal(t, err, test.e, "should be equal "+test.n)
}
})
}
<file_sep>package usecases
import (
"math/rand"
"github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/domain/entities"
"github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/domain/errors"
"github.com/alekseysychev/avito-auto-backend-trainee-assignment/internal/domain/interfaces"
)
type LinkService struct {
LinkStorage interfaces.LinkStorage
}
func (ls *LinkService) GetLinkByFrom(from string) (string, error) {
if from == "" {
return "", errors.ErrEmptyFromLink
}
link, err := ls.LinkStorage.GetLinkByFrom(from)
return link, err
}
const (
generatedLen = 10
)
func generateRandomLink(n int) string {
if n <= 0 {
n = 6
}
if n > 20 {
n = 6
}
letterRunes := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
func (ls *LinkService) CreateLink(link entities.Link) error {
if link.To == "" {
return errors.ErrEmptyToLink
}
var generated bool
if link.From == "" {
generated = true
}
var success bool
var step int
for !success && step < 10000 {
if generated {
link.From = generateRandomLink(generatedLen)
}
success = ls.LinkStorage.SaveLink(link)
// println(success)
if !success && !generated {
break
}
step++
}
if !success {
if generated {
return errors.ErrCantInsertNewData
}
return errors.ErrFromAlreadyExist
}
return nil
}
| c24c49723cc82eb1c8f6d92bd67653e21b75ff6f | [
"SQL",
"Markdown",
"Go",
"Go Module",
"Dockerfile"
]
| 15 | Go | alekseysychev/avito-auto-backend-trainee-assignment | f90a1ea8624ef559336622864402bc1b3cc17d65 | 8eb9984416aa9b4b1408f5065509dcf858fe17c6 |
refs/heads/master | <file_sep>import {
Controller,
Get,
Post,
Body,
Put,
Param,
UseGuards,
Request,
} from '@nestjs/common';
import { TaskService } from './task.service';
@Controller('/task')
export class TaskController {
constructor(private readonly taskService: TaskService) {}
@Get('/')
getAll() {
return this.taskService.findAll();
}
@Post('/Employee')
getAllForEmployee(@Body() data: string) {
console.log(data);
return this.taskService.findAllEmployeeTask(data);
}
@Post('/create')
create(@Body() data: any) {
return this.taskService.create(data);
}
@Put('/update')
update(@Body() data: any) {
return this.taskService.update(data);
}
}
<file_sep>import { Controller, Get, Post, Body, Put, Param } from '@nestjs/common';
import mailer from '../nodmailer';
@Controller('client/contact')
export class ContactController {
@Post()
contact(@Body() data: any) {
mailer(data.email, data.message, data.reason, '');
}
}
<file_sep>const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
const mailer = (emailR: string, msg: any, subject: string, html: any) => {
var transporter = nodemailer.createTransport(
smtpTransport({
service: 'gmail',
port: 465,
secure: false,
host: 'smtp.gmail.com',
auth: {
user: '<EMAIL>',
pass: '<PASSWORD>',
},
tls: {
rejectUnauthorized: false,
},
}),
);
let mailOptions = {
from: 'Irada consulting',
to: emailR,
subject: subject,
text: `${msg}`,
html: html,
};
transporter.sendMail(mailOptions, (err, info) => {
console.log('done', emailR);
});
};
export default mailer;
<file_sep>import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Client } from './client.entity';
import { ClientController } from './client.controller';
import { ClientService } from './client.service';
import { AuthModule } from '../auth/auth.module';
import { AdminModule } from '../admin/admins.module';
@Module({
imports: [TypeOrmModule.forFeature([Client]), AuthModule, AdminModule],
controllers: [ClientController],
providers: [ClientService],
})
export class ClientModule {}
<file_sep>import { Controller, Get, Post, Body, Put, Param } from '@nestjs/common';
import { EmployeeService } from './employee.service';
@Controller('/employee')
export class EmployeeController {
constructor(private readonly EmployeeService: EmployeeService) {}
@Get('')
test1() {
return this.EmployeeService.findAll();
}
@Post('/register')
create(@Body() data: any) {
return this.EmployeeService.create(data);
}
@Post('/login')
login(@Body() data: any) {
return this.EmployeeService.login(data);
}
@Post('/remove')
delete(@Body() data: any) {
return this.EmployeeService.remove(data);
}
@Put('/update')
update(@Body() data: any) {
return this.EmployeeService.update(data);
}
}
<file_sep>import { Controller, Get, Post, Body, Render } from '@nestjs/common';
import { AppService } from './app.service';
import mailer from './database/nodmailer';
const bcrypt = require('bcrypt');
@Controller('test')
export class AppController {
constructor(private readonly appService: AppService) {}
@Post('/t')
async testReseption(@Body() body: any) {
console.log(body);
const hasehd = await bcrypt.hash(body.email, 5);
let result = 'http://localhost:3000/invitation/admin/' + hasehd;
mailer(body.email, result, 'yoyo', '');
return result;
}
@Post('tt')
async testmaler(@Body() data: any) {
console.log(data);
let result = await bcrypt.compare(data.email, data.hashed);
return result;
}
@Post()
init(@Body() data: any): string {
console.log(data);
return data;
}
@Get('/nahed')
getHello(@Body() body: Body): string {
return this.appService.getHello(body);
}
@Post('ahmed')
posthello(@Body() body: Body): string {
return this.appService.posthello(body);
}
}
<file_sep>import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import e from 'express';
import { Repository } from 'typeorm';
import { EmployeeService } from '../employee/employee.service';
import { Task } from './task.entity';
export class TaskService {
constructor(
@InjectRepository(Task)
private taskRepository: Repository<Task>,
private employee: EmployeeService,
) {}
findAll(): Promise<Task[]> {
return this.taskRepository.find();
}
async findAllEmployeeTask(data) {
let { email } = data;
console.log(data);
let Employee = await this.employee.findOneByUsername(email);
console.log(Employee);
let EmployeeName = Employee.name;
return this.taskRepository.find();
}
async create(task: Task): Promise<Task> {
const admin = await this.taskRepository.create(task);
return this.taskRepository.save(admin);
}
async update(data: any) {
let id = data.id;
await this.taskRepository.update({ id }, data);
console.log(data);
return this.taskRepository.findOne(id);
}
}
<file_sep>import { Employee } from './../employee/employee.entity';
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
Unique,
} from 'typeorm';
@Entity()
export class Task {
@PrimaryGeneratedColumn()
id: number;
@Column()
EmployeeName: string;
@Column()
ClientName: string;
@CreateDateColumn()
startDate: Date;
@Column()
DueDate: Date;
@Column()
status: string;
}
<file_sep>import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { MainRef } from './MainRefference.entity';
@Injectable()
export class MainRefService {
constructor(
@InjectRepository(MainRef)
private mainRefReository: Repository<MainRef>,
) {}
findAll(): Promise<MainRef[]> {
return this.mainRefReository.find();
}
create(data: MainRef): Promise<MainRef> {
return this.mainRefReository.save(data);
}
}
<file_sep>import { Exclude } from 'class-transformer';
export class AdminEntity {
id: number;
name: string;
email: string;
@Exclude()
password: string;
constructor(partial: Partial<AdminEntity>) {
Object.assign(this, partial);
}
}
<file_sep>import { Controller, Get, Post, Body, Put, Param } from '@nestjs/common';
const bcrypt = require('bcrypt');
import mailer from '../nodmailer';
import { AdminService } from './admin.service';
@Controller('/admin')
export class AdminController {
constructor(private readonly adminservice: AdminService) {}
@Get('')
getAll() {
return this.adminservice.findAll();
}
@Post('/register/invitation')
async create(@Body() data: any) {
console.log(data);
return this.adminservice.createByAdmin(data);
}
@Put('/register/invitation/singup:id')
SingupViaInvitation(@Param('id') id: string, @Body() data: any) {
return this.adminservice.confirmCreateByAdmin(id, data);
}
@Post('/register')
Create(@Body() data: any) {
console.log(data);
return this.adminservice.create(data);
}
@Post('/remove')
test3(@Body() data: any) {
return this.adminservice.remove(data);
}
@Put('/register/invitation/singup')
async update(@Body() data: any) {
let result = await bcrypt.compare(data.email, data.hashed);
console.log(data);
console.log(result, 'hey');
if (result) {
let { hashed, ...b } = data;
console.log(b, 'hhhhhhhhhhhhhhhhhhhhhhhh');
return this.adminservice.update(data.email, b);
} else {
return false;
}
}
// @UseGuards(AuthGuard('local'))
@Post('/login')
async login(@Body() data: any) {
return await this.adminservice.login(data);
}
// @Post('/test')
// test1(@Body() data: any) {
// console.log('test1', data.name);
// }
}
<file_sep>import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(req): string {
console.log(req);
return 'Hello nahed!';
}
init(): string {
return 'server up';
}
posthello(body): string {
console.log(body);
return 'Hello World!';
}
}
<file_sep>import { Controller, Get, Post, Body, Put, Param } from '@nestjs/common';
import { ClientService } from './client.service';
@Controller('/Client')
export class ClientController {
constructor(private readonly clientservice: ClientService) {}
@Get('')
test1() {
return this.clientservice.findAll();
}
@Post('/register')
create(@Body() data: any) {
return this.clientservice.create(data);
}
@Post('/login')
login(@Body() data: any) {
return this.clientservice.login(data);
}
@Post('/remove')
delete(@Body() data: any) {
return this.clientservice.remove(data);
}
@Put(':id')
update(@Param('id') id: string, @Body() data: any) {
console.log(id);
return this.clientservice.update(id, data);
}
}
<file_sep>import { Body, Controller, Get, Post } from '@nestjs/common';
import { MainRefService } from './mainref.service';
@Controller('/References')
export class MainRefController {
constructor(private readonly mainService: MainRefService) {}
@Get('')
getall() {
return this.mainService.findAll();
}
@Post('add')
postNewReference(@Body() data: any) {
return this.mainService.create(data);
}
}
<file_sep>import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { from } from 'rxjs';
import { map } from 'rxjs/operators';
import { Repository } from 'typeorm';
import { AuthService } from '../auth/auth.service';
import { Employee } from './employee.entity';
import mailer from '../nodmailer';
@Injectable()
export class EmployeeService {
constructor(
@InjectRepository(Employee)
private employeeRepository: Repository<Employee>,
private authService: AuthService,
) {}
findAll(): Promise<Employee[]> {
return this.employeeRepository.find();
}
async create(data) {
const exists = await this.employeeRepository.findOne({
where: { email: data.email },
});
if (exists === undefined) {
if (exists === undefined) {
const passHash = await this.authService.hashPassword(data.password);
let employee: object = {
name: data.name,
password: <PASSWORD>,
email: data.email,
phoneNumber: data.phoneNumber,
};
return from(this.employeeRepository.save(employee)).pipe(
map((res: any) => {
let msg = `hey dear ${res.name},we are proud to have you
in our familly we hope that we will work together for a long
tine`;
mailer(res.email, msg, 'Welcom dear new Employee', '');
const { password, ...result } = res;
return result;
}),
);
}
const { password, ...result } = exists;
return result;
}
}
findOne(id: string): Promise<Employee> {
return this.employeeRepository.findOne(id);
}
async remove(email: string) {
await this.employeeRepository.delete(email);
return { delete: true };
}
async update(data) {
let email = data.email;
await this.employeeRepository.update({ email }, data);
return this.employeeRepository.findOne({ email });
}
/**
*
* @param username
* find an admin by username
*/
findOneByUsername(email: any) {
return this.employeeRepository.findOne({
where: { email },
});
}
/**
*
* @param data
* login confirmation or denied and send the token
*/
async login(data: any) {
const confirmed = await this.validate(data);
if (confirmed) {
const token = await this.authService.generatJWT(data);
return token;
}
}
/**
*
* @param data
* validate login data
*/
async validate(data) {
const theEmployee = await this.findOneByUsername(data.email);
if (theEmployee === undefined) {
return false;
}
const compare = await this.authService.ComparePassword(
theEmployee.password,
data.password,
);
if (compare) {
const { password, ...result } = theEmployee;
return result;
} else {
return false;
}
}
}
<file_sep>import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Any, Repository } from 'typeorm';
import { Admin } from './admin.entity';
import mailer from '../nodmailer';
import { map, switchMap } from 'rxjs/operators';
import { AuthService } from '../auth/auth.service';
import { from, Observable } from 'rxjs';
const bcrypt = require('bcrypt');
@Injectable()
export class AdminService {
constructor(
@InjectRepository(Admin)
private adminRepository: Repository<Admin>,
private authService: AuthService,
) {}
/**
* find all admins
*/
findAll(): Promise<Admin[]> {
return this.adminRepository.find();
}
/**
*
* @param data
* create an admin by invitation
*/
async createByAdmin(data: any) {
console.log(data);
const exists = await this.adminRepository.findOne({
where: { email: data.email },
});
if (exists === undefined) {
const hasehd = await bcrypt.hash(data.email, 5);
let result = 'http://localhost:3000/invitation/admin/' + hasehd;
mailer(
data.email,
result,
" You've been invited to be an admin in Irada",
'',
);
data.name = 'xXx';
data.password = '<PASSWORD>';
const admin = await this.adminRepository.create(data);
await this.adminRepository.save(admin);
return admin;
}
return exists;
}
/**
*
* @param id
* @param data
* update admin that was invited to join the group
*/
async confirmCreateByAdmin(id, data) {
const newAdmin = await this.adminRepository.findOne(id);
if (newAdmin.name === 'xXx') {
await this.adminRepository.update({ id }, data);
}
return this.adminRepository.findOne(id);
}
/**
*
* @param data
* create an admin
*/
async create(data) {
const exists = await this.adminRepository.findOne({
where: { email: data.email },
});
if (exists === undefined) {
const passHash = await this.authService.hashPassword(data.password);
let newAdmin: object = {
name: data.name,
password: <PASSWORD>,
email: data.email,
};
return from(this.adminRepository.save(newAdmin)).pipe(
map((res: any) => {
const { password, ...result } = res;
mailer(
data.email,
'your admin account was successfully saved',
data.password,
'',
);
return result;
}),
);
}
const { password, ...result } = exists;
return result;
}
/**
*
* @param email
* find an admin by email
*/
findOneByEmail(email: string) {
return this.adminRepository.findOne({
where: { email },
});
}
/**
*
* @param data
* login confirmation or denied and send the token
*/
async login(data: any) {
const confirmed = await this.validate(data);
console.log(confirmed);
if (confirmed) {
const token = await this.authService.generatJWT(data);
return token;
} else {
return false;
}
}
/**
*
* @param data
* validate login data
*/
async validate(data) {
console.log(data);
const theAdmin = await this.findOneByEmail(data.email);
if (theAdmin === undefined) {
return;
}
console.log(theAdmin);
const compare = await this.authService.ComparePassword(
theAdmin.password,
data.password,
);
if (compare) {
const { password, ...result } = theAdmin;
return result;
} else {
return false;
}
}
/**
*
* @param id
* find one admin by id
*/
findOneById(id: string): Promise<Admin> {
return this.adminRepository.findOne(id);
}
/**
*
* @param email
* delete an admin by email
*/
async remove(email: string) {
await this.adminRepository.delete(email);
return { delete: true };
}
/**
*
* @param id
* @param data
* find one by email and update it
*/
async update(email, data) {
console.log(data);
const user = await this.adminRepository.findOne({ email });
if (user) {
const notEqual = await this.validate(data);
if (!notEqual) {
const passHash = await this.authService.hashPassword(data.password);
let obj = { password: <PASSWORD>, name: data.name };
console.log(obj);
return await this.adminRepository.update({ email }, obj);
} else {
return false;
}
}
}
}
<file_sep>import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class MainRef {
@PrimaryGeneratedColumn()
id: number;
@Column()
url: string;
@Column()
project: string;
@Column()
Natureofthestudy: string;
@Column()
Client: string;
@Column()
date: Date;
@Column('integer', { default: 0 })
vue: number;
}
<file_sep>import { MainRefController } from './database/mainRef/mainref.controller';
import { MainRefService } from './database/mainRef/mainref.service';
import { MainRefModule } from './database/mainRef/mainref.module';
import { EmployeeModule } from './database/employee/employee.module';
import { TaskModule } from './database/tasks/task.module';
import { AuthModule } from './database/auth/auth.module';
import { AuthService } from './database/auth/auth.service';
import { ContactModule } from './database/contact/contact.module';
import { ClientModule } from './database/client/client.module';
import { AdminModule } from './database/admin/admins.module';
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm/dist/typeorm.module';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { Admin } from './database/admin/admin.entity';
import { JwtModule, JwtService } from '@nestjs/jwt';
@Module({
imports: [
MainRefModule,
EmployeeModule,
TaskModule,
ContactModule,
ClientModule,
AdminModule,
ContactModule,
TypeOrmModule.forRoot({
type: 'postgres',
host: 'hattie.db.elephantsql.com',
port: 5432,
username: 'qsgwmjfi',
password: '<PASSWORD>',
database: 'qsgwmjfi',
entities: [Admin],
synchronize: true,
autoLoadEntities: true,
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
<file_sep>import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { from } from 'rxjs';
import { map } from 'rxjs/operators';
import { Repository } from 'typeorm';
import { AuthService } from '../auth/auth.service';
import { Client } from './client.entity';
import mailer from '../nodmailer';
@Injectable()
export class ClientService {
constructor(
@InjectRepository(Client)
private clientRepository: Repository<Client>,
private authService: AuthService,
) {}
findAll(): Promise<Client[]> {
return this.clientRepository.find();
}
async create(data) {
const exists = await this.clientRepository.findOne({
where: { email: data.email },
});
if (exists === undefined) {
if (exists === undefined) {
const passHash = await this.authService.hashPassword(data.password);
let client: object = {
name: data.name,
password: <PASSWORD>,
email: data.email,
phoneNumber: data.phoneNumber,
};
return from(this.clientRepository.save(client)).pipe(
map((res: any) => {
let msg = `hey dear ${res.name},we welcome you
in Irada consulting. we are looking forward for working with you`;
mailer(res.email, msg, 'Welcom dear new client', '');
const { password, ...result } = res;
return result;
}),
);
}
const { password, ...result } = exists;
return result;
}
}
findOne(id: string): Promise<Client> {
return this.clientRepository.findOne(id);
}
async remove(email: string) {
await this.clientRepository.delete(email);
return { delete: true };
}
async update(id, data) {
await this.clientRepository.update({ id }, data);
return this.clientRepository.findOne(id);
}
/**
*
* @param username
* find an admin by username
*/
findOneByUsername(email: any) {
return this.clientRepository.findOne({
where: { email },
});
}
/**
*
* @param data
* login confirmation or denied and send the token
*/
async login(data: any) {
const confirmed = await this.validate(data);
if (confirmed) {
const token = await this.authService.generatJWT(data);
return token;
}
}
/**
*
* @param data
* validate login data
*/
async validate(data) {
console.log(data);
const theClient = await this.findOneByUsername(data.email);
if (theClient === undefined) {
throw new Error();
}
console.log(theClient);
const compare = await this.authService.ComparePassword(
theClient.password,
data.password,
);
if (compare) {
const { password, ...result } = theClient;
return result;
} else {
throw false;
}
}
}
<file_sep>import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { MainRefController } from './mainref.controller';
import { MainRefService } from './mainref.service';
import { MainRef } from './MainRefference.entity';
@Module({
imports: [TypeOrmModule.forFeature([MainRef])],
controllers: [MainRefController],
providers: [MainRefService],
})
export class MainRefModule {}
<file_sep>import { Injectable } from '@nestjs/common';
import { Observable, from, of } from 'rxjs';
import { JwtService } from '@nestjs/jwt';
import { map } from 'rxjs/operators';
const bcrypt = require('bcrypt');
@Injectable()
export class AuthService {
constructor(private readonly jwtService: JwtService) {}
// async validateUser(username: string, pass: string): Promise<any> {
// const admin = await this.adminservice.findOneByUsername(username);
// if (admin && admin.password === pass) {
// console.log(admin.password);
// const { password, ...result } = admin;
// return result;
// }
// return null;
// }
/**
*
* @param payload
* generate jwt token access
*/
async generatJWT(payload: object) {
const token = await this.jwtService.sign({ admin: payload });
return token;
}
/**
*
* @param password
* take a password and hash it and save it
*/
async hashPassword(password: string) {
return await bcrypt.hash(password, 5);
}
/**
*
* @param password
* @param commingPassword
* return compared password
*/
async ComparePassword(password: string, commingPassword: string) {
const comp = await bcrypt.compare(commingPassword, password);
console.log(comp);
return comp;
}
}
| 57078b99ecf1f95981ccb242caf045ed879a618b | [
"TypeScript"
]
| 21 | TypeScript | suited-team/Conslting-repo | 5e817f3a1fd9cbd1cd1c38b5f57cbcfc1622eb35 | 1eb9098690b151f26c5dc301da9c09928954e210 |
refs/heads/main | <file_sep>from beebeebot import BeeBeeBot
bot = BeeBeeBot("secret-token")
running = True
while running:
message = bot.check_new_messages()
if message != "":
print(message)
# bot.send_message(f"Your message but reversed: {message[::-1]}")
if message == "how r u?":
bot.send_message("I am doing good!!")
else:
bot.send_message(":DDD")<file_sep>from .beebeebot import BeeBeeBot<file_sep>import threading
from pathlib import Path
from collections import deque
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import atexit
class Message(object):
def __init__(self, message, sender, time=firestore.SERVER_TIMESTAMP):
self.message = message
self.sender = sender
self.time = time
@staticmethod
def from_dict(source):
message = Message(source["message"], source["sender"], source["time"])
return message
def to_dict(self):
dest = {"message": self.message, "sender": self.sender, "time": self.time}
return dest
def __repr__(self):
return (
f"Message(message='{self.message}', sender={self.sender}, time={self.time})"
)
class BeeBeeBot:
def __init__(self, secret):
self._secret = secret
parent_path = Path(__file__).parent.absolute()
service_account_file_path = parent_path / "service-account.json"
cred = credentials.Certificate(str(service_account_file_path))
firebase_admin.initialize_app(cred)
self._db = firestore.client()
print("Starting BeeBeeBot...🐝🐝\n")
chat_collection = self._db.collection("chats")
chat_ref = chat_collection.where("secret", "==", self._secret).get()
if len(chat_ref) == 0:
print("\n!!Your secret token is invalid!!")
raise SystemExit
else:
self._chat_ref = chat_ref[0]
self._messages_ref = chat_collection.document(self._chat_ref.id).collection(
"messages"
)
self._message_queue = deque()
self._watch_callback_done = threading.Event()
self._watch_messages = self._messages_ref.on_snapshot(self.__on_snapshot)
self._initial_messages_loaded = False
atexit.register(self.__exit_handler)
def __exit_handler(self):
self._watch_messages.unsubscribe()
def __on_snapshot(self, doc_snapshot, changes, read_time):
if not self._initial_messages_loaded:
self._initial_messages_loaded = True
return
new_messages = filter(lambda x: x.type.name == "ADDED", changes)
new_messages = [
Message.from_dict(message.document.to_dict()) for message in new_messages
]
new_messages = sorted(new_messages, key=lambda x: x.time)
# We filter out messages that aren't the bot's
new_messages = filter(lambda x: x.sender != "bot", new_messages)
self._message_queue.extend(new_messages)
self._watch_callback_done.set()
def send_message(self, msg):
self._messages_ref.add(Message(msg, "bot").to_dict())
def check_new_messages(self):
if len(self._message_queue) == 0:
return ""
else:
return self._message_queue.popleft().message<file_sep># BeeBeeBot
🐝 🐝 Bot
# Virtual Environment
Setup:
`python3 -m venv env`
Activate (Windows):
`env\Scripts\activate.bat`
Activate (Unix/macOS):
`source env/bin/activate`
## Install dependencies
`python3 -m pip install -r requirements.txt`
| d7dd298b9252f8965f028a9fabb7abf2663ff5be | [
"Markdown",
"Python"
]
| 4 | Python | NoahBres/BeeBeeBot | 8e75b7f7a102a05a331298ccc577c2ea1012683b | 3b2a147025168a3b7db95f9cc4bb04db54517e0a |
refs/heads/main | <file_sep>workspace "paardensprong-game"
configurations { "Debug", "Release" }
location "build"
platforms {"x64"}
project "paardensprong-game"
kind "ConsoleApp"
language "C++"
targetdir "bin/%{cfg.buildcfg}"
files { "src/**.*", "assets/**.*" }
postbuildcommands {
"{mkdir} ../bin/%{cfg.buildcfg}/assets",
"{copy} ../assets ../bin/%{cfg.buildcfg}/assets",
"{copy} ../vendor/SFML/bin/openal32.dll ../bin/%{cfg.buildcfg}"
}
filter "configurations:*"
defines { "SFML_STATIC" }
includedirs { "vendor/SFML/include" }
libdirs { "vendor/SFML/lib" }
links
{
"opengl32",
"openal32",
"freetype",
"winmm",
"gdi32",
"flac",
"vorbisenc",
"vorbisfile",
"vorbis",
"ogg",
"ws2_32"
}
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
links
{
"sfml-graphics-s-d",
"sfml-window-s-d",
"sfml-system-s-d",
"sfml-audio-s-d",
"sfml-network-s-d"
}
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
links
{
"sfml-main",
"sfml-graphics-s",
"sfml-window-s",
"sfml-system-s",
"sfml-audio-s",
"sfml-network-s"
}
<file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include <time.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <regex>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <random>
#include <chrono>
#if NDEBUG
#define assert( Expression )
#else
#define assert( Expression ) if (!Expression) {* (int *) 0 = 0;}
#endif
#define Kilobytes(Value) ((Value) * 1024)
#define Megabytes(Value) (Kilobytes(Value) * 1024)
#define Gigabytes(Value) (Megabytes(Value) * 1024)
#define eol "\n"
typedef uint64_t u64;
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;
typedef int64_t i64;
typedef int32_t i32;
typedef int16_t i16;
typedef int8_t i8;
typedef float f32;
typedef double f64;
#define PI 3.14159265358979323846
#if defined __APPLE__ && defined __MACH__
//__APPLE__ is defined on all Apple computers, __MACH__ on Mach-based kernels; together they specify OS X
#include <unistd.h>
#include <mach-o/dyld.h>
#include <errno.h>
#else
// we are on windows so include windows.h
#include <windows.h>
#endif
namespace util {
static std::string getPath() {
#if defined __APPLE__ && defined __MACH__
constexpr uint32_t i = 1024;
char buffer[i];
_NSGetExecutablePath(&s, &i);
std::string str = std::string(s);
str = str.substr(0, str.find_last_of("/"));
//if (!chdir(str.c_str()))
// throw(std::wstring("Failed to change working directory to executable path: " + strerror(errno)));
return str;
#else
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
std::string::size_type pos = std::string(buffer).find_last_of("\\/");
return std::string(buffer).substr(0, pos);
#endif
}
static std::string getAssetsPath() {
std::string cwd = getPath();
cwd += "/assets/";
return cwd;
}
static void toUpperCase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
}
static sf::Font getDefaultFont() {
sf::Font default_font;
std::string path = getPath();
default_font.loadFromFile(path+"/assets/arialbd.ttf");
return default_font;
}
static int getRandomIndex(int length) {
static std::hash<int> hasher;
static int seed = 11;
return std::abs((int)hasher(seed++)) % length;
}
static i32 floorMod(i32 a, i32 b) {
return (a % b + b) % b;
}
static f32 lerp(f32 a, f32 b, f32 mu) {
return a * (1 - mu) + b * mu;
}
static f64 lerp(f64 a, f64 b, f64 mu) {
return a * (1 - mu) + b * mu;
}
static sf::Color colorLerp(sf::Color first, sf::Color second, f32 mu) {
u8 r = (u8) lerp(first.r, second.r, mu);
u8 g = (u8) lerp(first.g, second.g, mu);
u8 b = (u8) lerp(first.b, second.b, mu);
return sf::Color( r, g, b );
}
static sf::Color colorLerp(sf::Color first, sf::Color second, f64 mu) {
u8 r = (u8) lerp(first.r, second.r, mu);
u8 g = (u8) lerp(first.g, second.g, mu);
u8 b = (u8) lerp(first.b, second.b, mu);
return sf::Color(r, g, b);
}
static sf::Color main_color = sf::Color(54, 80, 115);
static sf::Color getStandardBackgroundColor() {
return main_color;
}
static sf::Color getCellOrigColor() {
return sf::Color::White;
}
static sf::Color getCellRevealColor() {
return sf::Color::Black;
}
static sf::Color getCellTextColor() {
return sf::Color::Black;
}
static sf::Color getCellTextRevealColor() {
return main_color;
}
static sf::Color getTextColor() {
return sf::Color::White;
}
static sf::Color getInvalidTextColor() {
return sf::Color(147, 180, 191);
}
static sf::Color getInputDisabledTextColor() {
return sf::Color::White;
}
static sf::Color getInputSelectionColor() {
return sf::Color(119, 150, 189);
}
static std::string getStringFromKeyCode(const sf::Keyboard::Key& k) {
switch (k) {
case sf::Keyboard::A: return "a";
case sf::Keyboard::B: return "b";
case sf::Keyboard::C: return "c";
case sf::Keyboard::D: return "d";
case sf::Keyboard::E: return "e";
case sf::Keyboard::F: return "f";
case sf::Keyboard::G: return "g";
case sf::Keyboard::H: return "h";
case sf::Keyboard::I: return "i";
case sf::Keyboard::J: return "j";
case sf::Keyboard::K: return "k";
case sf::Keyboard::L: return "l";
case sf::Keyboard::M: return "m";
case sf::Keyboard::N: return "n";
case sf::Keyboard::O: return "o";
case sf::Keyboard::P: return "p";
case sf::Keyboard::Q: return "q";
case sf::Keyboard::R: return "r";
case sf::Keyboard::S: return "s";
case sf::Keyboard::T: return "t";
case sf::Keyboard::U: return "u";
case sf::Keyboard::V: return "v";
case sf::Keyboard::W: return "w";
case sf::Keyboard::X: return "x";
case sf::Keyboard::Y: return "y";
case sf::Keyboard::Z: return "z";
}
return "";
}
}
<file_sep>#pragma once
#include "util.h"
#include "TextField.h"
#include "CellGrid.h"
#include <SFML/Audio.hpp>
#include "LoadedSound.h"
struct PaardensprongData {
std::string solution;
std::string letters[9];
std::vector<u16> reveal_order = std::vector<u16>(9);
};
struct Game : public TextFieldListener {
u16 window_dim_x{ 800 };
u16 window_dim_y{ 600 };
std::unordered_map<std::string, LoadedSound> sound_bank;
CellGrid *cell_grid;
TextField user_input_field;
PaardensprongData paardensprong;
u32 word_index{ 0 };
std::vector<std::string> word_list;
bool solved{ false };
u32 game_round{ 0 };
bool show_avg_solve_time{ false };
f32 solve_time{ 0.0f };
std::vector<f32> solve_times = std::vector<f32>();
f32 avg_solve_time{ 0.0f };
f32 score_time_millis{ 0.0f };
i32 total_score{ 0 };
const i32 max_word_score{ 30 };
i32 word_score{ max_word_score };
sf::Font score_font{ util::getDefaultFont() };
bool cueue_reset{ false };
bool mouse_cursor_visible{ true };
bool is_in_focus{ true };
sf::Font default_font{ util::getDefaultFont() };
Game(u16 w, u16 h);
~Game() {
delete cell_grid;
}
void addSound(std::string url);
void playSound(std::string url);
void reset();
void resize(f32 width, f32 height);
void gainedFocus(bool in_focus) {
is_in_focus = in_focus;
user_input_field.in_focus = in_focus;
}
void keyPressed(sf::Event::KeyEvent& e);
void keyReleased(sf::Event::KeyEvent& e);
void mouseMoved(sf::Event::MouseMoveEvent& e);
void mousePressed(sf::Event::MouseButtonEvent& e);
PaardensprongData generatePaardenSprong(std::string word);
std::vector<std::string> loadWordlist(const char *filename);
void shuffleWordlist(std::vector<std::string>& list);
void handleWinState();
void catchTextFieldResult(const std::string& message) override;
void update(f32 dt);
void beginRender(sf::RenderWindow& window) {
window.clear();
}
void endRender(sf::RenderWindow& window) {
window.display();
}
void render(sf::RenderWindow& window);
};
<file_sep>#pragma once
#include "Game.h"
Game::Game(u16 w, u16 h): window_dim_x(w), window_dim_y(h) {
word_list = loadWordlist("word_list_EN.txt");
shuffleWordlist(word_list);
user_input_field.addListener(this);
reset();
}
void Game::addSound(std::string url) {
if (!sound_bank.count(url)) {
sound_bank.insert({ url, LoadedSound() });
if (!sound_bank[url].load(url)) {
sound_bank.erase(url);
}
}
}
void Game::playSound(std::string url) {
bool success = false;
if (!sound_bank.count(url)) {
sound_bank.insert({ url, LoadedSound() });
if (sound_bank[url].load(url)) {
success = true;
}
else {
sound_bank.erase(url);
success = false;
}
}
else {
success = true;
}
if (success) {
sound_bank[url].play();
}
}
void Game::reset() {
solved = false;
score_time_millis = 0.0f;
game_round++;
word_score = max_word_score;
paardensprong = generatePaardenSprong(word_list[word_index++]);
cell_grid = new CellGrid(*this);
cell_grid->setupGrid(paardensprong.letters);
user_input_field.disable(false);
user_input_field.reset();
}
void Game::resize(f32 width, f32 height) {
window_dim_x = width;
window_dim_y = height;
}
void Game::keyPressed(sf::Event::KeyEvent& e) {
mouse_cursor_visible = false;
if (e.alt) {
if (e.code == sf::Keyboard::T) {
show_avg_solve_time = !show_avg_solve_time;
}
return;
}
if (e.code == sf::Keyboard::Enter) {
playSound("keyboard_enter_pressed.wav");
if (solved) {
cueue_reset = true;
return;
}
}
else {
std::string index = std::to_string(util::getRandomIndex(4) + 1);
playSound("keyboard_0" + index + "_pressed.wav");
}
user_input_field.keyPressed(e);
}
void Game::keyReleased(sf::Event::KeyEvent& e) {
if (e.code == sf::Keyboard::Enter) {
playSound("keyboard_enter_released.wav");
}
else {
std::string num = std::to_string(util::getRandomIndex(4) + 1);
playSound("keyboard_0" + num + "_released.wav");
}
}
void Game::mouseMoved(sf::Event::MouseMoveEvent& e) {
mouse_cursor_visible = true;
}
void Game::mousePressed(sf::Event::MouseButtonEvent& e) {
if (solved) {
bool inside = cell_grid->inBounds((f32)e.x, (f32)e.y);
if (inside) {
cueue_reset = true;
}
}
}
PaardensprongData Game::generatePaardenSprong(std::string word) {
PaardensprongData data;
util::toUpperCase(word);
data.solution = word;
u16 start = util::getRandomIndex((u32)word.size());
i16 direction = rand() % 2 ? 1 : -1;
u16 word_index = 0;
for (u16 i = start; /* no bounds */; i += (direction * 3)) {
// wrap index around
i = util::floorMod(i, 8);
data.letters[i] = word[word_index];
data.reveal_order[word_index] = i;
word_index++;
if (word_index == 8) break;
}
return data;
}
std::vector<std::string> Game::loadWordlist(const char *filename) {
std::vector<std::string> the_list = std::vector<std::string>();
std::ifstream fs;
std::string line;
const std::regex reg("[a-z]+");
std::string path = util::getAssetsPath();
fs.open(path+filename);
if (fs.is_open()) {
while (std::getline(fs, line)) {
if (line.size() == 8) {
if (std::regex_match(line, reg)) {
the_list.push_back(line);
}
}
}
}
return the_list;
}
void Game::shuffleWordlist(std::vector<std::string>& list) {
// obtain a time-based seed:
u32 seed = (u32)std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine e(seed);
std::shuffle(std::begin(list), std::end(list), e);
}
void Game::handleWinState() {
if (!solved) {
solved = true;
total_score += word_score;
solve_times.push_back(solve_time);
f32 total_solve_time{ 0.0f };
for (const f32& time : solve_times) {
total_solve_time += time;
}
avg_solve_time = (total_solve_time) / game_round;
solve_time = 0.0f;
user_input_field.disable(true);
cell_grid->reveal(0.6f, paardensprong.reveal_order);
playSound("counter_bell.wav");
}
}
void Game::catchTextFieldResult(const std::string& message) {
std::string answer = message;
util::toUpperCase(answer);
if (answer == paardensprong.solution) {
handleWinState();
}
}
void Game::update(f32 dt) {
if (cueue_reset) {
cueue_reset = false;
reset();
}
// update scores
if (!solved) {
score_time_millis += dt;
solve_time += dt;
f32 one_second = 1000.0f;
if (score_time_millis >= one_second) {
score_time_millis = 0.0f;
word_score--;
if (word_score < 0) word_score = 0;
if (word_score == 0) {
total_score--;
playSound("clock_tick.wav");
}
}
}
// update grid
cell_grid->update(dt);
cell_grid->updateWordScore(word_score);
f32 grid_size = (f32)std::min(window_dim_y / 2, window_dim_x / 2);
cell_grid->resize(grid_size);
f32 grid_x = window_dim_x / 2.0f - cell_grid->size / 2.0f;
f32 grid_y = 0.05f * window_dim_y;
cell_grid->position(grid_x, grid_y);
// update user input field
f32 user_input_x = cell_grid->x + cell_grid->grid[0].border_width;
f32 user_input_y = cell_grid->y + cell_grid->size + 48;
user_input_field.position(user_input_x, user_input_y);
u32 user_input_text_size = u32(cell_grid->size / 6);
user_input_field.resizeText(user_input_text_size);
user_input_field.update(dt);
}
void Game::render(sf::RenderWindow& window) {
{
// draw white background
f32 w = window.getView().getSize().x;
f32 h = window.getView().getSize().y;
sf::RectangleShape bg = sf::RectangleShape({ w, h });
bg.setFillColor(util::getStandardBackgroundColor());
window.draw(bg);
}
cell_grid->paint(window);
user_input_field.paint(window);
// render total score
std::string score = std::to_string(total_score);
u32 score_text_size = u32(cell_grid->size / 6.0f);
sf::Text score_text = sf::Text(score, score_font, score_text_size);
score_text.setFillColor(sf::Color(util::getTextColor()));
score_text.setPosition(48, 48);
window.draw(score_text);
// render avg solve time
if (show_avg_solve_time) {
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << (avg_solve_time / 1000.0f);
std::string mystring = ss.str();
std::string solve_time_str = ss.str();
sf::Text solve_time_text_shape = sf::Text(solve_time_str, score_font, score_text_size);
f32 solve_time_x = window.getSize().x - 48.0f;
f32 solve_time_y = 48.0f;
sf::FloatRect bounds = solve_time_text_shape.getLocalBounds();
f32 origin_x = bounds.left + bounds.width;
f32 origin_y = solve_time_text_shape.getOrigin().y;
solve_time_text_shape.setOrigin(origin_x, origin_y);
solve_time_text_shape.setPosition({ solve_time_x, solve_time_y });
solve_time_text_shape.setFillColor(util::getTextColor());
window.draw(solve_time_text_shape);
}
}<file_sep>#pragma once
#include "CellGrid.h"
#include "Game.h"
CellGrid::CellGrid(Game& gm) : game(gm) {}
u16 CellGrid::getGridIndexForLetterIndex(u16 letter_index)
{
u16 mapping[9]{
0, 1, 2,
5, 8, 7,
6, 3, 4
};
return mapping[letter_index];
}
void CellGrid::setupGrid(std::string letters[])
{
for (u16 i = 0; i < GRID_COUNT; i++) {
u16 grid_index = getGridIndexForLetterIndex(i);
grid[grid_index] = Cell();
grid[grid_index].font = game.default_font;
if (grid_index == MIDDLE_CELL) {
grid[grid_index].orig_color = util::getStandardBackgroundColor();
grid[grid_index].text_color = util::getCellOrigColor();
}
else {
util::toUpperCase(letters[i]);
grid[grid_index].letter = letters[i];
}
}
}
void CellGrid::resize(f32 new_size)
{
size = new_size;
cell_size = new_size / dimension;
for (Cell& cell : grid) {
cell.size = cell_size;
}
}
void CellGrid::position(f32 new_x, f32 new_y) {
x = new_x;
y = new_y;
}
void CellGrid::update(f32 dt)
{
u16 grid_index = 0;
for (f32 cell_y = y; cell_y < y + dimension * cell_size; cell_y += cell_size) {
for (f32 cell_x = x; cell_x < x + dimension * cell_size; cell_x += cell_size) {
grid[grid_index].x = cell_x;
grid[grid_index].y = cell_y;
grid[grid_index].update(dt);
grid_index++;
}
}
if (should_reveal && reveal_order_index < reveal_order.size() - 1) {
reveal_time += dt;
if (reveal_time >= reveal_duration) {
reveal_time = 0.0f;
int letter_index = reveal_order[reveal_order_index++];
int grid_index = getGridIndexForLetterIndex(letter_index);
grid[grid_index].reveal(0.5f);
if (&game != nullptr) {
std::string num = std::to_string(util::getRandomIndex(4) + 1);
game.playSound("horse_gallop_0"+num+".wav");
}
}
}
}
void CellGrid::updateWordScore(i32 score)
{
std::string score_str = std::to_string(score);
grid[MIDDLE_CELL].letter = score_str;
}
void CellGrid::reveal(const f32 duration, std::vector<u16>& new_reveal_order)
{
reveal_order = new_reveal_order;
should_reveal = true;
reveal_time = 0;
reveal_duration = duration * 1000.0f;
}
void CellGrid::paint(sf::RenderWindow& window)
{
for (Cell& cell : grid) {
cell.paint(window);
}
}
<file_sep>
#include "TextField.h"
void TextField::paint(sf::RenderWindow& window)
{
// draw user input
sf::Text text_shape = sf::Text(user_input, font, text_size);
text_shape.setFillColor(text_color);
if (disabled) {
text_shape.setFillColor(util::getInputDisabledTextColor());
}
text_shape.setPosition(x, y);
//draw selection background
f32 selection_x = text_shape.findCharacterPos(cursor_index).x;
f32 selection_y = y + 4;
f32 selection_x_max = text_shape.findCharacterPos(selection_cursor_index).x;
f32 selection_width = selection_x_max - selection_x;
sf::RectangleShape selection_shape = sf::RectangleShape({ selection_width, (f32)text_size });
selection_shape.setFillColor( selection_color );
selection_shape.setPosition({ selection_x, selection_y });
// Pre-draw selection marquee
window.draw(selection_shape);
// Draw letters dimmer when exceeding the maximum word length of the puzzle
u16 puzzleword_length = 8;
if (user_input.size() > puzzleword_length) {
std::string valid_user_input = user_input.substr(0, puzzleword_length);
std::string extraneous_user_input = user_input.substr(puzzleword_length, user_input.size() - 1);
// "Regular" text shape
sf::Text valid_text_shape = sf::Text(valid_user_input, font, text_size);
valid_text_shape.setPosition(text_shape.getPosition());
valid_text_shape.setFillColor(text_shape.getFillColor());
// "Dimmed" text shape
f32 extraneous_user_input_x = valid_text_shape.findCharacterPos(valid_user_input.size()).x;
sf::Text extraneous_text_shape = sf::Text(extraneous_user_input, font, text_size);
extraneous_text_shape.setPosition(extraneous_user_input_x, valid_text_shape.getPosition().y);
extraneous_text_shape.setFillColor(util::getInvalidTextColor());
window.draw(valid_text_shape);
window.draw(extraneous_text_shape);
}
else {
window.draw(text_shape);
}
if (!disabled && in_focus) {
// draw cursor
sf::RectangleShape cursor_rect = sf::RectangleShape({ 2.0f, (f32)text_size });
// animate cursor
f32 color_mu = f32( ( std::sin(phase * 2.0 * PI) + 1.0) / 2.0 );
sf::Color cursor_color = util::colorLerp(util::getStandardBackgroundColor(), util::getTextColor(), color_mu);
cursor_rect.setFillColor(cursor_color);
f32 cursor_pos_x = text_shape.findCharacterPos(cursor_index).x;
f32 cursor_pos_y = y + 4;
cursor_rect.setPosition({ cursor_pos_x, cursor_pos_y });
window.draw(cursor_rect);
}
}
void TextField::keyPressed(sf::Event::KeyEvent& e)
{
if (disabled) return;
time_millis = 0.0f;
std::string character_input = util::getStringFromKeyCode(e.code);
if (character_input != "") {
// Delete selection
if (selecting) {
i16 erase_index = std::min(cursor_index, selection_cursor_index);
i16 erase_count = std::abs(selection_cursor_index - cursor_index);
user_input.erase(erase_index, erase_count);
cursor_index = erase_index;
selection_cursor_index = cursor_index;
}
// Insert new character
if (user_input.size() < max_input_length) {
user_input.insert(cursor_index, character_input);
cursor_index++;
}
}
else {
if (e.code == sf::Keyboard::Left) {
cursor_index--;
}
else if (e.code == sf::Keyboard::Right) {
cursor_index++;
}
else if (e.code == sf::Keyboard::Backspace) {
if (!user_input.size()) return;
if (!selecting) {
i16 erase_index = cursor_index - 1;
if (erase_index >= 0) {
user_input.erase(erase_index, 1);
cursor_index--;
}
}
else {
i16 erase_index = std::min(cursor_index, selection_cursor_index);
i16 erase_count = std::abs(selection_cursor_index - cursor_index);
user_input.erase(erase_index, erase_count);
cursor_index = erase_index;
selection_cursor_index = cursor_index;
}
}
else if (e.code == sf::Keyboard::Delete) {
if (!user_input.size()) return;
if (!selecting) {
i16 erase_index = cursor_index;
if (erase_index >= 0 && erase_index < user_input.size()) {
user_input.erase(erase_index, 1);
}
}
else {
i16 erase_index = std::min(cursor_index, selection_cursor_index);
i16 erase_count = std::abs(selection_cursor_index - cursor_index);
user_input.erase(erase_index, erase_count);
cursor_index = erase_index;
selection_cursor_index = cursor_index;
}
}
else if (e.code == sf::Keyboard::Home) {
cursor_index = 0;
}
else if (e.code == sf::Keyboard::End) {
cursor_index = (i16) user_input.size();
}
else if (e.code == sf::Keyboard::Enter) {
for (TextFieldListener* listener : listeners) {
listener->catchTextFieldResult(user_input);
}
}
if (e.control) {
if (e.code == sf::Keyboard::Left) {
cursor_index = 0;
}
else if (e.code == sf::Keyboard::Right) {
cursor_index = (i16) user_input.size();
}
}
}
// clamp cursor
if (cursor_index < 0) cursor_index = 0;
if (cursor_index > user_input.size()) cursor_index = i16(user_input.size());
if (!e.shift) {
selection_cursor_index = cursor_index;
selecting = false;
}
else {
if (cursor_index != selection_cursor_index) selecting = true;
else selecting = false;
}
}
void TextField::reset()
{
cursor_index = 0;
user_input = "";
}
<file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include <algorithm>
#include "util.h"
#include "Cell.h"
#include "LoadedSound.h"
// pre-declare Game for circular dependency..
struct Game;
struct CellGrid {
static constexpr u32 GRID_COUNT{ 9 };
static constexpr u16 MIDDLE_CELL{ 4 };
std::vector<Cell> grid = std::vector<Cell>(GRID_COUNT);
f32 x{ -10000.0 }, y{ -10000.0 };
f32 dimension{ 3.0 };
f32 cell_size{ 96.0 };
f32 size{ cell_size * dimension };
std::vector<u16> reveal_order = std::vector<u16>();
bool should_reveal{ false };
f32 reveal_time{ 0.0f };
f32 reveal_duration{ 0.0f };
u32 reveal_order_index{ 0 };
CellGrid(Game &gm);
Game &game;
u16 getGridIndexForLetterIndex(u16 letter_index);
void setupGrid(std::string letters[]);
void resize(f32 new_size);
void position(f32 new_x, f32 new_y);
void update(f32 dt);
void updateWordScore(i32 score);
bool inBounds(f32 pos_x, f32 pos_y) {
return (pos_x >= x && pos_x < x + size) && (pos_y >= y && pos_y < y + size);
}
void reveal(const f32 time, std::vector<u16> &new_reveal_order);
void paint(sf::RenderWindow& window);
};
<file_sep>#pragma once
#include <SFML/Audio.hpp>
#include "util.h"
struct LoadedSound {
std::string name;
sf::SoundBuffer buffer;
sf::Sound sound;
bool load(std::string url) {
std::string path = util::getPath();
if (buffer.loadFromFile(path+"/assets/sound/" + url)) {
name = url;
sound = sf::Sound(buffer);
return true;
}
else {
return false;
}
}
void play() {
sound.play();
}
};
<file_sep># Paardensprong Game
Simple paardensprong puzzle game made with SFML in C++
## "Paardensprong"?
"Paardensprong" is Dutch for a Knight's move (Chess). A Knight's movement is defined as: it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L).
## The game
In a 3 x 3 grid (with an empty square at the center) you have to find the 8 letter word. The word can start at any random square and has to follow the pattern of a Knight's move. The direction can either be clockwise or counter clockwise.
### Scoring
You have 30 seconds to guess the right word. Every second is worth 1 point. Any seconds remaining after you filed in the correct answer is added to the total score. But, if you're passed the 30 second mark, any second you didn't find the correct answer is subtracted from the total score.
## Build
### Use Premake to create target platform project (Visual Studio, Xcode etc.)
Use the included premake5.lua script to create a project for your current platform. More info on premake [over here](https://premake.github.io/).
IMPORTANT! Only windows (vs2019) is tested. Other platforms are untested.
### SFML
This project uses SFML for it's rendering, audio and window management. For more info go to [the SFML website](https://www.sfml-dev.org/).
<file_sep>
#include <SFML/OpenGL.hpp>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Game.h"
int main()
{
srand((u32) time(NULL));
sf::ContextSettings context_settings;
context_settings.depthBits = { 24 };
context_settings.stencilBits= { 8 };
context_settings.antialiasingLevel= { 0 };
context_settings.majorVersion = { 4 };
context_settings.minorVersion= { 2 };
std::string window_title{ "Paardensprong Game" };
u16 window_width{ 1280 };
u16 window_height{ 1024 };
u16 prev_window_width{ window_width };
u16 prev_window_height{ window_height };
bool is_fullscreen{ false };
sf::RenderWindow window(sf::VideoMode(window_width, window_height), window_title, sf::Style::Titlebar | sf::Style::Close, context_settings);
window.setActive(true);
window.setVerticalSyncEnabled(true);
i16 prev_window_pos_x = window.getPosition().x;
i16 prev_window_pos_y = window.getPosition().y;
Game *game = new Game(window_width, window_height);
sf::Clock clock;
sf::Time prev_time;
sf::Cursor hand_cursor, arrow_cursor;
hand_cursor.loadFromSystem(sf::Cursor::Hand);
arrow_cursor.loadFromSystem(sf::Cursor::Arrow);
// main loop
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed) {
window.close();
}
else if (event.type == sf::Event::Resized) {
// Reset view
sf::View view = sf::View(sf::FloatRect(0.f, 0.f, (f32)event.size.width, (f32)event.size.height));
window.setView(view);
window_width = window.getSize().x;
window_height = window.getSize().y;
game->resize(window_width, window_height);
}
else if (event.type == sf::Event::GainedFocus)
game->gainedFocus(true);
else if (event.type == sf::Event::LostFocus)
game->gainedFocus(false);
else if (event.type == sf::Event::MouseMoved) {
bool inside_cell = game->cell_grid->inBounds((f32)event.mouseMove.x, (f32)event.mouseMove.y);
if (inside_cell) {
window.setMouseCursor(hand_cursor);
}
else {
window.setMouseCursor(arrow_cursor);
}
game->mouseMoved(event.mouseMove);
}
else if (event.type == sf::Event::MouseButtonPressed) {
game->mousePressed(event.mouseButton);
}
else if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Escape) {
window.close();
delete game;
return 0;
}
else if (event.key.code == sf::Keyboard::F11) {
is_fullscreen = !is_fullscreen;
if (is_fullscreen) {
prev_window_width = window.getSize().x;
prev_window_height = window.getSize().y;
prev_window_pos_x = window.getPosition().x;
prev_window_pos_y = window.getPosition().y;
window.create(sf::VideoMode::getDesktopMode(), window_title, sf::Style::None, context_settings);
window.setPosition({ 0,0 });
}
else {
window.create(sf::VideoMode(prev_window_width, prev_window_height), window_title, sf::Style::Titlebar | sf::Style::Close, context_settings);
window.setPosition(sf::Vector2i(prev_window_pos_x < 0 ? 0 : prev_window_pos_x, prev_window_pos_y < 0 ? 0 : prev_window_pos_y));
}
window_width = window.getSize().x;
window_height = window.getSize().y;
game->resize(window_width, window_height);
}
else {
game->keyPressed(event.key);
}
}
else if (event.type == sf::Event::KeyReleased) {
game->keyReleased(event.key);
}
}
window.setMouseCursorVisible(game->mouse_cursor_visible);
// main game update and render "loop"
{
sf::Time now = clock.getElapsedTime();
f32 dt = (now.asMicroseconds() - prev_time.asMicroseconds()) / 1000.0f;
prev_time = now;
game->update(dt);
game->beginRender(window);
game->render(window);
game->endRender(window);
}
}
delete game;
return 0;
}<file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include "util.h"
struct Cell {
f32 x{ -10000.0 }, y{ -10000.0 };
f32 size{ 96.0 };
f32 border_width = size / 12;
sf::Color orig_color{ util::getCellOrigColor() };
sf::Color reveal_color{ util::getCellRevealColor() };
sf::Color text_color{ util::getCellTextColor() };
sf::Color text_reveal_color{ util::getCellTextRevealColor() };
f32 time_millis{ 0.0f };
f32 reveal_duration{ 500.0f };
f32 color_mu{ 0.0f };
bool should_reveal{ false };
sf::Font font{ util::getDefaultFont() };
std::string letter{ "-" };
void reveal(f32 duration) {
reveal_duration = duration * 1000.0f;
should_reveal = true;
}
void update(f32 dt) {
if (should_reveal) {
time_millis += dt;
color_mu = time_millis / reveal_duration;
if (color_mu > 1.0) {
color_mu = 1.0;
should_reveal = false;
}
}
}
void paint(sf::RenderWindow& window) {
f32 real_size = size - border_width * 2;
f32 real_x = x + border_width;
f32 real_y = y + border_width;
// draw background
{
sf::Color bg_color = util::colorLerp(orig_color, reveal_color, color_mu);
sf::RectangleShape shape = sf::RectangleShape({ real_size, real_size });
shape.setFillColor(bg_color);
shape.setPosition(real_x, real_y);
window.draw(shape);
}
// draw letter
{
u16 text_size = u16(real_size - (real_size / 3.0f));
sf::Text text_shape = sf::Text(letter, font, text_size);
text_shape.setStyle(sf::Text::Bold);
sf::FloatRect bounds = text_shape.getLocalBounds();
f32 origin_x = bounds.left + bounds.width / 2;
f32 origin_y = bounds.top + bounds.height / 2;
text_shape.setOrigin(origin_x, origin_y);
f32 center_x = real_x + (real_size / 2.0f);
f32 center_y = real_y + (real_size / 2.0f);
sf::Color letter_color = util::colorLerp(text_color, text_reveal_color , color_mu);
text_shape.setFillColor(letter_color);
text_shape.setPosition(center_x, center_y);
window.draw(text_shape);
}
}
};
<file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include <iostream>
#include "util.h"
class TextFieldListener {
public:
virtual ~TextFieldListener() {};
virtual void catchTextFieldResult(const std::string& message) = 0;
};
struct TextField {
std::vector<TextFieldListener *> listeners = std::vector<TextFieldListener *>();
f32 x{ 100.0f }, y{ 100.0f };
u16 max_input_length{ 20 };
u32 text_size{ 28 };
sf::Font font{ util::getDefaultFont() };
sf::Color text_color{ util::getTextColor() };
sf::Color selection_color{ util::getInputSelectionColor() };
f64 phase = 0.0;
f32 time_millis{ 0.0f };
f32 blink_duration_millis{ 1000.0f };
std::string user_input{""};
i16 cursor_index{ 0 };
i16 selection_cursor_index{ 0 };
bool disabled{ false };
bool selecting{ false };
bool in_focus{ true };
void position(f32 new_x, f32 new_y) {
x = new_x;
y = new_y;
}
void update(f32 dt) {
time_millis += dt;
if (time_millis >= blink_duration_millis) {
time_millis = 0.0f;
}
phase = time_millis / blink_duration_millis;
phase = phase - (i32)phase; //might be unnecessay
}
void resizeText(u32 text_size) {
this->text_size = text_size;
}
void paint(sf::RenderWindow& window);
void keyPressed(sf::Event::KeyEvent& e);
void reset();
void disable(bool should) {
disabled = should;
}
void addListener(TextFieldListener* listener) {
listeners.push_back(listener);
}
}; | 9f0776703c8f2b3535518cfcc14e02fdd3c7ad90 | [
"Markdown",
"C++",
"Lua"
]
| 12 | Lua | mohragk/paardensprong-cpp | 64cf229f2adeaf996ba2a4b2d928585d6417738d | 4f189bebb4e62b67e65c8e4b99d1e2f30ed5ea42 |
refs/heads/main | <repo_name>JahinH48/Es6-Recap-and-Practice-Modul-31-31.5<file_sep>/01.js
// 1 . let and const
const hubby = 'jisan';
let phone = 'iphone';
phone = 'Samsung Galaxy';
// 2 . default parameter
function maxNumber(array = []) {
const max = Math.max(...array);
return max;
}
const biggest = maxNumber();
console.log(biggest)
// 3. template string
const myNote = `I am mojnu of ${hubby}. i dont have ${phone} `;
// 4 arrow function
const square = x => x * x;
console.log(square(2))
<file_sep>/README.md
"# Es6-Recap-and-Practice-Modul-31-31.5"
<file_sep>/07.js
class Support {
name;
work = 'support Team Deverloper ';
Address;
Location = 'Bangladesh';
constructor(name, Address) {
this.name = name;
this.Address = Address;
}
Team() {
console.log(this.name, 'fhatay de Class ke ');
}
}
const jisan = new Support('jisan', 'Dinajpur');
jisan.Team()
console.log(jisan)
const jahin = new Support('jahin', 'Dinajpur');
jahin.Team()
console.log(jahin);
// programming Hero
/* class Support {
name;
designation = 'Support Web Dev';
address = 'BD';
constructor(name, address) {
this.name = name;
this.address = address;
}
startSession() {
console.log(this.name, 'start a support session');
}
}
const aamir = new Support('<NAME>', 'BD');
const salman = new Support('<NAME>', 'Dubai');
const sharuk = new Support('SRK Khan', 'Dubai');
const akshay = new Support('<NAME>', 'Dubai');
aamir.startSession();
salman.startSession();
console.log(aamir, salman, sharuk, akshay);
// console.log(salman); */ | bae21f050140cddc8c054136b77f6c1841b9b991 | [
"JavaScript",
"Markdown"
]
| 3 | JavaScript | JahinH48/Es6-Recap-and-Practice-Modul-31-31.5 | 09820c0b3bce2caafc89dfbd95f452e12cd4506f | 01872dd6cce82842a31127e1a7f9fcac48319fbe |
refs/heads/master | <repo_name>Ethanb75/Hair-Source-Salon-Suites<file_sep>/src/components/Carousel.js
import React, { Component } from 'react';
import './Carousel.css';
import cover1 from '../assets/header1.jpeg';
import salon1 from '../assets/salon1.jpg';
import cover2 from '../assets/header2.jpeg';
import cover3 from '../assets/header3-2.jpg';
import cover4 from '../assets/cover1.jpg';
import cover5 from '../assets/cover2.jpg';
import cover1Small from '../assets/header1-sm.jpeg';
import cover2Small from '../assets/header2-sm.jpeg';
import cover3Small from '../assets/header3-2-sm.jpg';
let timeout;
const CAROUSEL_TIMER = 8000;
export default class Carousel extends Component {
state = {
currentSlide: 0,
imageList: [cover3, cover4, cover5, salon1],
respImageList: [cover1Small, cover2Small, cover3Small]
}
selectImage(currentSlide) {
// clear current interval so interval doesn't trigger after a selection
clearInterval(timeout);
//set currentSlide to new index
this.setState({ currentSlide })
// reset the timeout
timeout = setInterval(() => {
this.setState({
currentSlide: this.state.currentSlide === this.state.imageList.length - 1 ? 0 : this.state.currentSlide + 1
})
}, CAROUSEL_TIMER)
}
nextImage() {
clearInterval(timeout);
this.setState({
currentSlide: this.state.currentSlide === this.state.imageList.length - 1 ? 0 : this.state.currentSlide + 1
})
timeout = setInterval(() => {
this.setState({
currentSlide: this.state.currentSlide === this.state.imageList.length - 1 ? 0 : this.state.currentSlide + 1
})
}, CAROUSEL_TIMER)
}
previousImage() {
clearInterval(timeout);
this.setState({
currentSlide: this.state.currentSlide === 0 ? this.state.imageList.length - 1 : this.state.currentSlide - 1
})
timeout = setInterval(() => {
this.setState({
currentSlide: this.state.currentSlide === this.state.imageList.length - 1 ? 0 : this.state.currentSlide + 1
})
}, CAROUSEL_TIMER)
}
componentDidMount() {
//if timeout isn't already set, set timeout
if (!timeout) {
timeout = setInterval(() => {
this.setState({
currentSlide: this.state.currentSlide === this.state.imageList.length - 1 ? 0 : this.state.currentSlide + 1
})
}, CAROUSEL_TIMER)
}
this.nextImage = this.nextImage.bind(this);
this.previousImage = this.previousImage.bind(this);
}
componentWillUnmount() {
clearInterval(timeout); //clear the interval whenever carousel is unmounted
}
render() {
const { currentSlide, imageList, respImageList } = this.state;
const imageElements = imageList.map((imageSrc, index) => {
return (
<img
src={imageSrc}
// srcSet={`${respImageList[index]} 600w, ${imageSrc} 1280w`}
// sizes="100vw"
key={index}
style={currentSlide === index ? { opacity: 1 } : {}}
alt=""
/>
)
});
let productImageSelectButtons = imageList.map((image, index) => {
return (
<button
key={image.id}
onClick={() => this.selectImage(index)}
style={currentSlide === index ? { backgroundColor: '#DB1313', transform: 'scale(1.2)' } : {}}
></button>
)
});
return (
<div className="carouselWrap">
{imageElements}
<div className="carousel__controls">
<div className="carousel__counter">
{'0' + (currentSlide + 1)} / {'0' + imageList.length}
</div>
<div>
{productImageSelectButtons}
</div>
</div>
</div>
)
}
} | 13838b878e8fd8da83a98fcee2c462cd74444781 | [
"JavaScript"
]
| 1 | JavaScript | Ethanb75/Hair-Source-Salon-Suites | a86064bea21e33f9bb589a14026cc14dc26868c4 | f2c1d0e8fb6faff0a037bb2937ac3551715f5203 |
refs/heads/master | <repo_name>alundgren/NrGsr<file_sep>/engine.js
nrGsr = (function () {
var createStrategyString = function(f) {
return btoa(f);
}
var parseStrategyString = function (s) {
var c = atob(s);
return Function('m', c);
}
//TODO: Missing intel. Opponents last guess
var simulateGame = function (c1, c2, options) {
var strats = [c1, c2]; //{ f : <fn>, m : {}, name : 'player 1', nr : 1 }
options = options || {}
options.n = options.n || 1000;
options.maxNrOfRounds = options.maxNrOfRounds || 10000; //NOTE: If both players strategy even does the bare minimum of not guessing already known wrong answers this caps out at n.
options.getCorrectNr = options.getCorrectNr || function() {
var min = 1;
var max = options.n;
return Math.floor(Math.random()*(max-min+1)+min);
}
var logEnabled = options.logEnabled || false;
var correctNr = options.getCorrectNr();
var game = {
winner : 0
}
if(logEnabled) {
game.log = ['correct nr: ' + correctNr];
}
game.nrOfRounds = 1;
var guesses = [[], []];
while(game.nrOfRounds <= options.maxNrOfRounds) {
var guess;
var current;
var other;
current = strats[1-(game.nrOfRounds%2)];
other = strats[game.nrOfRounds%2];
var currentGuesses = guesses[1-(game.nrOfRounds%2)];
var otherGuesses = guesses[game.nrOfRounds%2];
current.m.yourGuesses = currentGuesses;
current.m.opponentsGuesses = otherGuesses;
guess = current.f(current.m);
if(guess === correctNr) {
if(logEnabled) {
game.log.push(current.name + ': ' + guess);
game.log.push('--' + current.name + ' wins--');
}
game.winner = current.nr;
return game;
} else {
if(guess < correctNr) {
currentGuesses.push({ g : guess, r : 1 })
} else {
currentGuesses.push({ g : guess, r : -1 })
}
if(logEnabled) {
game.log.push(current.name + ': ' + guess);
}
}
game.nrOfRounds = game.nrOfRounds + 1;
}
if(logEnabled) {
game.log.push('-- no winner. max nr of rounds hit --');
}
return game;
}
var findBestStrategy = function(strategy1, strategy2, options) {
var result = {
nrOfGames : 0,
nrOfRounds : 0,
wins : [0, 0, 0] //draws, p1, p2
}
var r;
var c1;
var c2;
for(var i=0; i<10000; i++) {
c1 = { f : strategy1, m : {}, name : 'player 1', nr : 1 }
c2 = { f : strategy2, m : {}, name : 'player 2', nr : 2 }
if(i % 2 === 0) {
r = simulateGame(c1, c2, options);
} else {
r = simulateGame(c2, c1, options);
}
result.wins[r.winner] = result.wins[r.winner] + 1;
result.nrOfGames = result.nrOfGames + 1;
result.nrOfRounds = result.nrOfRounds + r.nrOfRounds;
}
return result;
};
return { simulateGame : simulateGame,
createStrategyString : createStrategyString,
parseStrategyString : parseStrategyString,
findBestStrategy : findBestStrategy
};
})();<file_sep>/ctr.js
var app = angular.module('app', ['ui.bootstrap', 'ngAnimate']);
app.directive('preventDefault', function ($window) {
return function (scope, element, attrs) {
element.bind('click', function (event) {
event.preventDefault();
});
};
});
app.controller('ctr', function ($scope, $window) {
$scope.strats = [
{ title:'Strategy 1', active : true },
{ title:'Strategy 2' }
];
$scope.tabNr = 1;
editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
if(localStorage.code1) {
$scope.strats[0].content = localStorage.code1;
} else {
$scope.strats[0].content = 'if(!m.lastGuess) { m.lastGuess = 1; } else { m.lastGuess = m.lastGuess + 1; } return m.lastGuess;';
}
if(localStorage.code2) {
$scope.strats[1].content = localStorage.code2;
} else {
$scope.strats[1].content = 'if(!m.lastGuess) { m.lastGuess = 1000; } else { m.lastGuess = m.lastGuess - 1; } return m.lastGuess;';
}
editor.setValue($scope.strats[$scope.tabNr-1].content);
//TODO: Make the editor work with the tabs so the fake tabs hack isnt needed
//TODO: Autosave
$scope.onSelectTab = function(tabNr) {
var previousTabNr = $scope.tabNr;
$scope.tabNr = tabNr;
if(previousTabNr <= 2){
$scope.strats[previousTabNr-1].content = editor.getValue()
if(previousTabNr === 1) {
localStorage.code1 = $scope.strats[0].content
} else {
localStorage.code2 = $scope.strats[1].content
}
}
if(tabNr === 1 || tabNr === 2) {
editor.setValue($scope.strats[$scope.tabNr-1].content)
}
}
$scope.fight = function () {
$scope.simResult = null;
var s1 = nrGsr.parseStrategyString(nrGsr.createStrategyString($scope.strats[0].content));
var s2 = nrGsr.parseStrategyString(nrGsr.createStrategyString($scope.strats[1].content));
var r = nrGsr.findBestStrategy(s1, s2);
$scope.simResult = {
log :[]
}
$scope.simResult.log.push('Strategy 1 wins: ' + Math.round(100 * r.wins[1] / r.nrOfGames, 1).toFixed(1) + '%');
$scope.simResult.log.push('Strategy 2 wins: ' + Math.round(100 * r.wins[2] / r.nrOfGames, 1).toFixed(1) + '%');
if(r.wins[0] > 0) {
$scope.simResult.log.push('Note! There were ' + Math.round(100 * r.wins[0] / r.nrOfGames, 1).toFixed(1) + '% draws meaning even after many rounds no winner was found.');
}
}
$scope.simulateGame = function () {
$scope.playResult = null;
var s1 = nrGsr.parseStrategyString(nrGsr.createStrategyString($scope.strats[0].content));
var s2 = nrGsr.parseStrategyString(nrGsr.createStrategyString($scope.strats[1].content));
var c1 = { f : s1, m : {}, name : 'player 1', nr : 1 }
var c2 = { f : s2, m : {}, name : 'player 2', nr : 2 }
if(Math.random() < 0.5) {
var tmp = c2;
c2 = c1;
c1 = tmp;
}
var r = nrGsr.simulateGame(c1, c2, { logEnabled : true});
$scope.playResult = {
log :r.log
}
}
});<file_sep>/README.md
A simple game where each player creates a strategy to play the below number guessing game.
Game:
- A random number between 1 and 1000 is picked.
- Each player takes turns guessing a number. The next player receives an answer of: first to guess (0), higher (1) or lower (-1).
- The first player to get correct wins. | 2581dd0aed281511f0b64a480c7f75d15d87f724 | [
"JavaScript",
"Markdown"
]
| 3 | JavaScript | alundgren/NrGsr | 4f030956d3cde9c518e8faf2748b445d78ef7b5a | 77c991cbc199d0c963fd9cd2399c29c1464cd53e |
refs/heads/master | <repo_name>carono/yii2-rbac<file_sep>/src/AuthorBehavior.php
<?php
namespace carono\yii2rbac;
class AuthorBehavior extends \carono\yii2behaviors\AuthorBehavior
{
}<file_sep>/README.md
# yii2-rbac
Очередная реализация RBAC для yii2.
ВВЕДЕНИЕ
--------
Этот компонент помогает распределить доступы по конкретным action в контроллерах по ролям, в конфигах прописываются доступы,
выполняется команда для сброса прав, и база наполнена всеми указанными ролями, контроллерами и акшенами. Можно не прописывать каждый
action в конкретном контроллере, а указать '*' и команда соберёт все возможные.
УСТАНОВКА
---------
`composer require carono/yii2-rbac`
Не забудьте провести миграцию для таблиц
`yii migrate --migrationPath=@yii/rbac/migrations`
НАСТРОЙКА
---------
В `config/console.php` для basic редакции и в `console/main.php` для advanced, прописываем
```
'components' => [
'authManager' => [
// Настраиваем менеджер, чтобы можно было в консоли работать с правами
'class' => 'yii\rbac\DbManager',
'defaultRoles' => ['guest', 'user'],
],
],
'controllerMap' => [
'rbac' => [
'class' => 'carono\yii2rbac\RbacController',
'roles' => [
'guest' => null,
'user' => null,
'manager' => 'user',
'director' => ['parent' => 'manager', 'description' => 'Директор'], // Наследование директора от менеджера
'root' => null
],
'permissions' => [
'*:*:*' => ['root'], // Для рута доступны все контроллеры
'Basic:Site:*' => ['guest'], // Для гостя разрешены все actions у SiteController
'Basic:Director:*' => ['director'],
'updater_perm' => ['director'], // Простые доступы тоже можно создавать как обычно
'Basic:Manager:*' => ['manager'], // Будет доступно и директору, т.к. наследуется
'Basic:Director:Index' => ['manager'], // Только один action у DirectorController
'Ajax:*:*' => ['user'] // Модуль Ajax, все контроллеры разрешаем авторизованным
]
],
]
```
После настройки, необходимо выполнить `yii rbac` чтобы создались роли и создались доступы по контроллерам.
Если настройки в конфиге изменились, то необходимо каждый раз вызывать команду. Все роли и доступы пересоздаются заново.
При этом, уже навешанные на пользователей роли не удаляются.
В базе создаются доступы вида `Module:Controller:Action`, если в настройках указывается '*' в любой части, то собираются
все модули, контроллеры или акшены.
ОСОБЕННОСТИ
-----------
Все контроллеры без модулей, всё же имеют модуль, которым является Yii::$app, поэтому SiteController->actionIndex формирует
доступ как `Basic:Site:Index`, если в конфиге (web.php) изменить id вашего приложения с basic на my-app, то нужно и в настройках
контроллера указывать соответственно: `MyApp:Site:Index`
КАК ПРИМЕНЯТЬ
-------------
В behaviors контроллера, можно использовать фильтр, который идет в комплекте
```
public function behaviors()
{
return [
'access' => [
'class' => RoleManagerFilter::className(),
]
];
}
```
или проверить самостоятельно
```
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'matchCallback' => function ($rule, $action) {
return RoleManager::checkAccess($action);
}
],
],
],
];
}
```
ХЕЛПЕРЫ
-------
* RoleManager::formPermissionByAction(Yii::$app->controller->action) = Basic:Site:index
* RoleManager::checkAccessByUrl('/site/index?page=1', $user) = true, передаем ссылки или массив, как для Url::to
* RoleManager::checkAccess('Basic:Site:Index', $user), так же принимает и класс Action
$user - класс прописанный у вас в конфигах - Yii::$app->user->identityClass, так же может быть primaryKey модели или username
РАБОТА С ADVANCED РЕДАКЦИЕЙ
---------------------------
Не сильно отличается от basic, только доступ может состоять как из 3х так и из 4х секций, Application:Module:Controller:Action
```
'controllerMap' => [
'rbac' => [
'class' => 'carono\yii2rbac\RbacController',
'roles' => [
'guest' => null,
'user' => null,
'manager' => 'user',
'director' => ['parent' => 'manager', 'description' => 'Директор'], // Наследование директора от менеджера
'root' => null
],
'permissions' => [
'*:*:*' => ['root'], // Для рута доступны все контроллеры как во frontend так и в backend
'AppFrontend:Site:*' => ['guest'], // Для гостя разрешены все actions у SiteController во frontend
'AppBackend:Director:*' => ['director'],
'AppFrontend:Ajax:*:*' => ['user'] // Модуль Ajax, все контроллеры разрешаем во frontend
'*:Site:Index' => ['guest'] // Разрешаем SiteController->index как во frontend так и backend
]
],
]
```<file_sep>/src/RoleManagerFilter.php
<?php
namespace carono\yii2rbac;
use yii\filters\AccessControl;
class RoleManagerFilter extends AccessControl
{
public $roleManagerClass = '\carono\yii2rbac\RoleManager';
public function init()
{
$rule = [
'allow' => true,
'matchCallback' => function ($rule, $action) {
return call_user_func([$this->roleManagerClass, 'checkAccess'], $action);
}
];
$this->rules[] = \Yii::createObject(array_merge($this->ruleConfig, $rule));
parent::init();
}
}<file_sep>/src/RoleManager.php
<?php
namespace carono\yii2rbac;
use yii\base\Action;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\Inflector;
use yii\helpers\Url;
use yii\rbac\Permission;
use yii\rbac\Role;
use yii\web\Controller;
use yii\web\Request;
/**
* Class RoleManager
*
* @package carono\yii2rbac
*/
class RoleManager
{
public static $identityClass;
public static $defaultApplicationId;
public static $authManager = 'authManager';
/**
* @return \yii\rbac\ManagerInterface
* @throws \Exception
*/
public static function auth()
{
if (!$authManager = \Yii::$app->get(static::$authManager)) {
throw new \Exception('Configure auth manager');
} else {
return $authManager;
}
}
/**
* @param null $user
*
* @return int|mixed|null|string
* @throws \Exception
*/
private static function getUserId($user = null)
{
$id = null;
if ($user instanceof ActiveRecord) {
$id = $user->getPrimaryKey();
} elseif (is_numeric($user)) {
$id = $user;
} elseif (is_null($user)) {
$id = CurrentUser::getId();
} elseif (is_string($user)) {
$class = static::$identityClass ? static::$identityClass : \Yii::$app->user->identityClass;
return static::getUserId($class::findByUsername($user));
}
return $id;
}
/**
* @param null $user
* @param bool $namesOnly
*
* @return array|\yii\rbac\Role[]
* @throws \Exception
*/
public static function getRoles($user = null, $namesOnly = true)
{
$id = static::getUserId($user);
$roles = static::auth()->getRolesByUser($id);
if ($namesOnly) {
return array_keys($roles);
} else {
return $roles;
}
}
/**
* @param $role
* @param null $user
*
* @return \yii\rbac\Assignment|false
* @throws \Exception
*/
public static function assign($role, $user = null)
{
$role = static::getRole($role);
if (!static::haveRole($role, $user)) {
$id = static::getUserId($user);
return static::auth()->assign($role, $id);
} else {
return false;
}
}
/**
* @param $role
* @param null $user
*
* @return bool
*/
public static function haveRole($role, $user = null)
{
if ($role instanceof Role) {
$role = $role->name;
}
return in_array($role, static::getRoles($user));
}
/**
* @param $roles
* @param null $user
* @return bool
*/
public static function haveRoles($roles, $user = null)
{
return !array_diff($roles, static::getRoles($user));
}
/**
* @param $roles
* @param null $user
* @return array
*/
public static function haveOneOfRoles($roles, $user = null)
{
return array_intersect($roles, static::getRoles($user));
}
/**
* @param $role
*
* @return bool
*/
public static function createRole($role, $attributes = [])
{
if (!static::getRole($role)) {
$model = static::auth()->createRole($role);
foreach ($attributes as $attribute => $value) {
$model->$attribute = $value;
}
return static::auth()->add($model);
} else {
return false;
}
}
/**
* @param $permission
* @return bool
*/
public static function add($permission)
{
if (is_string($permission)) {
$permission = self::getPermission($permission);
}
return static::auth()->add($permission);
}
/**
* @param $permission
* @param array $params
* @return bool
*/
public static function updatePermissionParams($permission, $params = [])
{
if (is_string($permission)) {
$permission = self::getPermission($permission);
}
foreach ($params as $param => $value) {
if ($permission->canSetProperty($param)) {
$permission->$param = $value;
}
}
return self::auth()->update($permission->name, $permission);
}
/**
* @param $role
*
* @return null|Role
*/
public static function getRole($role)
{
if ($role instanceof Role) {
return $role;
} else {
return static::auth()->getRole($role);
}
}
public static function getModuleFromPermission($permission)
{
$arr = explode(':', $permission);
if (count($arr) == 4) {
return $arr[1];
} else {
return false;
}
}
public static function getActionFromPermission($permission)
{
$arr = explode(':', $permission);
if (count($arr) == 4) {
return $arr[3];
} elseif (count($arr) == 3) {
return $arr[2];
} else {
return false;
}
}
public static function getControllerFromPermission($permission)
{
$arr = explode(':', $permission);
if (count($arr) == 4) {
return $arr[2];
} elseif (count($arr) == 3) {
return $arr[1];
} else {
return false;
}
}
public static function getApplicationFromPermission($permission)
{
$arr = explode(':', $permission);
if (count($arr) == 4 || count($arr) == 3) {
return $arr[0];
} else {
return false;
}
}
/**
* @param $action
*
* @return null|string
*/
public static function formPermissionByAction(Action $action)
{
$applicationId = static::$defaultApplicationId ? static::$defaultApplicationId : \Yii::$app->id;
$module = ArrayHelper::getValue($action->controller, 'module.id', '');
if ($module === $applicationId) {
$module = '';
}
$controller = $action->controller->id;
$name = Inflector::camelize($action->id);
return static::formPermission($controller, $name, $module, $applicationId);
}
/**
* @param $controller
* @param $action
* @param string $module
*
* @param null $application
*
* @return string
*/
public static function formPermission($controller, $action, $module, $application = null)
{
if (!$application) {
$application = \Yii::$app->id;
}
return join(
":", array_filter(
[
Inflector::camelize($application),
Inflector::camelize($module),
Inflector::camelize($controller),
Inflector::camelize($action),
]
)
);
}
/**
* @param $name
*
* @param array $params
* @return bool
*/
public static function createPermission($name, $params = [])
{
if (!static::getPermission($name)) {
$permission = static::auth()->createPermission($name);
self::updatePermissionParams($permission, $params);
return static::auth()->add($permission);
}
return false;
}
/**
* @param $controller
* @param $action
* @param string $module
*
* @param null $application
*
* @return bool
*/
public static function createSitePermission($controller, $action, $module = 'Basic', $application = null)
{
$name = static::formPermission($controller, $action, $module, $application);
return static::createPermission($name);
}
/**
* @param $permission
*
* @return null|Permission
*/
public static function getPermission($permission)
{
if ($permission instanceof Permission) {
return $permission;
} else {
return static::auth()->getPermission($permission);
}
}
/**
* @param $role
* @param $permission
*/
public static function addChild($role, $permission)
{
$role = static::getRole($role);
$permission = static::getPermission($permission);
if (!static::hasChild($role, $permission)) {
static::auth()->addChild($role, $permission);
}
}
/**
* @param $role
* @param $parent
*/
public static function addParent($role, $parent)
{
$role = static::getRole($role);
$parent = static::getRole($parent);
if (!static::auth()->hasChild($role, $parent)) {
static::auth()->addChild($role, $parent);
}
}
/**
* @param $role
*
* @throws \Exception
*/
public static function raiseRoleNotFound($role)
{
throw new \Exception("Role '$role' not found");
}
/**
* @param $permission
*
* @throws \Exception
*/
public static function raisePermissionNotFound($permission)
{
throw new \Exception("Permission '$permission' not found");
}
/**
* @param $role
* @param $permission
*
* @return bool
*/
public static function hasChild($role, $permission)
{
$roleModel = static::getRole($role);
$permissionModel = static::getPermission($permission);
if (!$roleModel) {
return false;
}
if (!$permissionModel) {
return false;
}
return static::auth()->hasChild($roleModel, $permissionModel);
}
public static function urlToRoute($url)
{
$url = Url::to($url, true);
$arr = parse_url($url);
$req = new Request();
$req->url = $arr["path"] . (isset($arr['query']) ? '?' . $arr['query'] : '');
if (isset($arr['query'])) {
parse_str($arr["query"], $query);
} else {
$query = [];
}
$result = \Yii::$app->urlManager->parseRequest($req);
if (empty($result[1]) && $query) {
$result[1] = $query;
}
return $result;
}
public static function urlToPermission($url)
{
/* @var $controller Controller */
if (!$route = static::urlToRoute($url)) {
return false;
}
$route = static::urlToRoute($url)[0];
$parts = \Yii::$app->createController($route);
[$controller, $actionID] = $parts;
if (!$controller) {
//TODO Need trace
return false;
}
if ($action = $controller->createAction($actionID)) {
return static::formPermissionByAction($action);
} else {
return false;
}
}
public static function checkAccessByUrl($url, $user = null)
{
if (!$arr = static::urlToRoute($url)) {
return false;
}
$permission = static::urlToPermission($url);
return static::checkAccess($permission, $user, $arr[1]);
}
/**
* @param string|Action $permission
* @param null $user
*
* @param array $params
* @return bool
*/
public static function checkAccess($permission, $user = null, $params = [])
{
if ($permission instanceof Action) {
$permission = static::formPermissionByAction($permission);
}
if (CurrentUser::isGuest()) {
return static::hasChild('guest', $permission);
} else {
return static::auth()->checkAccess(static::getUserId($user), $permission, $params);
}
}
/**
* @param $role
* @param null $user
*
* @return bool
* @throws \Exception
*/
public static function revoke($role, $user = null)
{
$role = static::getRole($role);
$id = static::getUserId($user);
if (static::haveRole($role, $user)) {
return static::auth()->revoke($role, $id);
} else {
return false;
}
}
/**
* @param null $user
*
* @return bool
* @throws \Exception
*/
public static function revokeAll($user = null)
{
return static::auth()->revokeAll(static::getUserId($user));
}
/**
* @param $role
*/
public static function removeRole($role)
{
$role = static::getRole($role);
static::auth()->remove($role);
}
/**
* @param $role
*/
public static function removeChildren($role)
{
$role = static::getRole($role);
static::auth()->removeChildren($role);
}
}<file_sep>/src/CurrentUser.php
<?php
namespace carono\yii2rbac;
use yii\base\Exception;
use yii\base\Model;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
class CurrentUser
{
public static $identityClass;
/**
* @param Model|string $message
*/
public static function setFlashError($message)
{
if ($message instanceof Model) {
$message = Html::errorSummary($message);
}
self::setFlash('error', $message);
}
/**
* @param $message
*/
public static function setFlashSuccess($message)
{
self::setFlash('success', $message);
}
/**
* @param $message
*/
public static function setFlashWarning($message)
{
self::setFlash('warning', $message);
}
/**
* @param $message
*/
public static function setFlashInfo($message)
{
self::setFlash('info', $message);
}
/**
* @param null $key
*
* @return string
*/
public static function showFlash($key = null)
{
$session = \Yii::$app->getSession();
if (!$key) {
$out = '';
foreach ($session->getAllFlashes(false) as $key => $value) {
$out .= self::showFlash($key);
}
return $out;
} else {
switch ($key) {
case "success":
$htmlOptions = ["class" => "alert alert-success"];
break;
case "error":
$htmlOptions = ["class" => "alert alert-danger"];
break;
case "info":
$htmlOptions = ["class" => "alert alert-info"];
break;
case "warning":
$htmlOptions = ["class" => "alert alert-warning"];
break;
default:
$htmlOptions = ["class" => "alert alert-info"];
}
if ($session->hasFlash($key)) {
return Html::tag('div', $session->getFlash($key), $htmlOptions);
}
};
return '';
}
/**
* @param $name
* @param $message
*/
public static function setFlash($name, $message)
{
if (\Yii::$app->getSession()) {
\Yii::$app->getSession()->setFlash($name, $message);
}
}
/**
* @param null $user
*
* @return bool
*/
public static function isMe($user = null)
{
return self::user($user)->id == self::getId(true);
}
/**
* @param $user
* @param bool $asRobot
*
* @return User
*/
public static function user($user, $asRobot = true)
{
if ($model = self::findUser($user)) {
return $model;
} else {
return self::get($asRobot);
}
}
public static function findUser($user)
{
$class = self::$identityClass ? self::$identityClass : \Yii::$app->user->identityClass;
if (class_exists($class)){
if (!isset(class_implements($class)['yii\web\IdentityInterface'])){
throw new Exception("$class must be implemented from yii\\web\\IdentityInterface");
}
}
$model = null;
if (is_numeric($user)) {
$model = $class::findOne($user);
} elseif (is_string($user)) {
$model = $class::findByUsername($user);
} elseif ($user instanceof $class) {
$model = $user;
}
return $model;
}
public static function getRobot($login = null)
{
$user = null;
$login = $login ? $login : (isset(\Yii::$app->params["robot"]) ? \Yii::$app->params["robot"] : null);
$user = self::findUser($login);
return $user;
}
/**
* @return \yii\web\User
*/
public static function webUser()
{
return \Yii::$app->user;
}
public static function isGuest()
{
return \Yii::$app->user->getIsGuest();
}
/**
* @param bool $asRobot
* @param null $robot
*
* @return User|null
*/
public static function get($asRobot = false, $robot = null)
{
$class = self::$identityClass ? self::$identityClass : \Yii::$app->user->identityClass;
$user = null;
if (isset(\Yii::$app->components["user"]) && !self::isGuest()) {
$user = $class::findOne(\Yii::$app->user->identity->getId());
}
if ($asRobot && !$user) {
$user = self::getRobot($robot);
}
return $user;
}
public static function getId($asRobot = false, $robot = null)
{
return ArrayHelper::getValue(self::get($asRobot, $robot), 'id');
}
}<file_sep>/CHANGELOG.md
1.0.17
* Добавлена возможность указать данные для правил
```
'permissions' => [
'Basic:Site:*' => ['user', 'data' => ['myparam' => 'Произвольные данные'], 'description'=>'Акшены сайта']
]
'permissionsByRole' => [
'user' => ['Basic:Site:*' => ['data' => ['myparam' => 'Произвольные данные'], 'description'=>'Акшены сайта']
]
```
1.0.16
* \carono\yii2rbac\RoleManagerFilter добавлена возможность указать свой клас для проверки прав через $roleManagerClass<file_sep>/src/RbacController.php
<?php
namespace carono\yii2rbac;
use yii\base\InlineAction;
use yii\console\Controller;
use yii\helpers\ArrayHelper;
use yii\helpers\Console;
use yii\helpers\Inflector;
use yii\helpers\StringHelper;
use yii\rbac\Role;
use yii\rbac\Rule;
class RbacController extends Controller
{
public $identityClass;
public $roles = [];
public $permissions = [];
public $permissionsByRole = [];
public $authManager = 'authManager';
public $deny = [];
public $cache = 'cache';
public $rules = [];
public $removeUnusedRoles = true;
public $removeUnusedRules = true;
public $overwritePermissionParams = false;
public $recreateRoles = true;
public $defaultConfigs = [
[
'@app/config/web.php'
],
[
'@common/config/main.php',
'@common/config/main-local.php',
'@backend/config/main.php',
'@backend/config/main-local.php'
],
[
'@common/config/main.php',
'@common/config/main-local.php',
'@frontend/config/main.php',
'@frontend/config/main-local.php'
]
];
public $configs = [];
protected $role;
protected $user;
public function options($actionID)
{
return ArrayHelper::getValue(
[
'role-add' => ['user', 'role'],
'role-revoke' => ['user', 'role']
], $actionID, []
);
}
protected function getIdentityClass($config)
{
if (isset($config['components']['user']['identityClass'])) {
return $config['components']['user']['identityClass'];
} else {
return false;
}
}
public function init()
{
RoleManager::$authManager = $this->authManager;
parent::init();
}
public function manageRole($assign)
{
if (!$this->role || !$this->user) {
return Console::output('Run yii rbac --user=login --role=rolename');
}
if (!$user = CurrentUser::findUser($this->user)) {
return Console::output("User $this->user not found");
};
if (!$role = RoleManager::getRole($this->role)) {
return Console::output("Role $this->role not found");
};
if ($assign) {
if (RoleManager::haveRole($role, $user)) {
Console::output("User $this->user already have role $this->role");
} elseif (RoleManager::assign($role, $user)) {
Console::output("Role '$this->role' successful assigned to $this->user");
} else {
Console::output("Fail assign role $this->role to $this->user");
}
} else {
if (!RoleManager::haveRole($role, $user)) {
Console::output("User $this->user haven't role $this->role");
} elseif (RoleManager::revoke($role, $user)) {
Console::output("Role '$this->role' successful revoked from $this->user");
} else {
Console::output("Fail revoke role $this->role from $this->user");
}
}
Console::output("Current roles: " . join('; ', RoleManager::getRoles($user)));
}
public function actionRoleShow()
{
if (!$user = CurrentUser::findUser($this->user)) {
return Console::output("User $this->user not found");
};
Console::output("Current roles: " . join('; ', RoleManager::getRoles($user)));
}
public function actionRoleAdd()
{
$this->manageRole(true);
}
public function actionRoleRevoke()
{
$this->manageRole(false);
}
public function roles()
{
/*
return [
'guest' => null,
'user' => null,
'manager' => ['user']
];
*/
return [];
}
public function permissions()
{
/*
return [
'*:*:*' => ['root'],
'Basic:Profile:*' => ['user'],
'Basic:Site:Login' => ['guest'],
'Basic:Site:Index' => ['guest','user'],
'Basic:Site:Error' => ['guest','user'],
];
*/
return [];
}
protected function getPermissions()
{
return array_merge($this->permissions, $this->permissions());
}
protected function getRoles()
{
return array_merge($this->roles, $this->roles());
}
protected function applyRoles()
{
$roles = $this->getRoles();
if (!$roles && !$this->permissionsByRole && $this->recreateRoles) {
Console::output('Roles not registered, nothing to do');
exit;
}
foreach ($roles as $role => $data) {
if ($this->recreateRoles || !RoleManager::getRole($role)) {
if (is_string($data)) {
$data = [];
$parents = (array)$data;
} else {
$parents = (array)ArrayHelper::remove($data, 'parent');
}
RoleManager::createRole($role, $data);
RoleManager::removeChildren($role);
if (is_array($parents)) {
foreach ($parents as $parent) {
if (RoleManager::getRole($parent)) {
RoleManager::addParent($role, $parent);
}
}
}
Console::output("Create '$role' role");
}
}
}
protected function applyPermissions()
{
$permissions = $this->getPermissions();
if (!$permissions && !$this->permissionsByRole) {
Console::output('Permissions not registered, nothing to do');
exit;
}
foreach ($permissions as $permission => $roles1) {
foreach ($this->normalizePermission($permission) as $name) {
RoleManager::createPermission($name);
foreach ($roles1 as $key => $role) {
if (is_array($role) && \in_array($key, ['data', 'description'])) {
$params[$key] = $role;
$permissionModel = RoleManager::getPermission($name);
RoleManager::updatePermissionParams($permissionModel, $params);
continue;
}
if (!RoleManager::getRole($role)) {
Console::output("FAIL add '$name' permission for '$role'. Role '$role' not found");
exit;
}
RoleManager::addChild($role, $name);
Console::output("Set '$name' for '$role'");
}
}
}
foreach ($this->permissionsByRole as $role => $permissions) {
foreach ($permissions as $key => $permission) {
$params = [];
if (is_array($permission) && is_string($key)) {
$params = $permission;
$permission = $key;
}
if ($this->overwritePermissionParams) {
$params['data'] = ArrayHelper::getValue($params, 'data');
$params['description'] = ArrayHelper::getValue($params, 'description');
}
foreach ($this->normalizePermission($permission) as $name) {
RoleManager::createPermission($name, $params);
if ($params) {
$permissionModel = RoleManager::getPermission($name);
RoleManager::updatePermissionParams($permissionModel, $params);
}
if (!RoleManager::getRole($role)) {
Console::output("FAIL add '$name' permission for '$role'. Role '$role' not found");
exit;
}
RoleManager::addChild($role, $name);
Console::output("Set '$name' for '$role'");
}
}
}
}
protected function applyDenyPermissions()
{
if (!$this->deny) {
return Console::output('Deny permissions not registered, nothing to do');
}
foreach ($this->deny as $permission => $roles3) {
foreach ($roles3 as $role) {
RoleManager::auth()->removeChild(RoleManager::getRole($role), RoleManager::getPermission($permission));
Console::output("Remove '$permission' for '$role'");
}
}
}
protected function removeUnusedRoles()
{
$roles = $this->getRoles();
$diffRoles = array_diff(array_keys(RoleManager::auth()->getRoles()), array_keys($roles));
if (!$diffRoles) {
return Console::output('There are no roles to delete');
}
foreach ($diffRoles as $role) {
RoleManager::removeRole($role);
Console::output("Remove '$role' role");
}
}
protected function removeUnusedRules()
{
/**
* @var Rule $ruleClass
*/
$ruleNames = [];
foreach ($this->rules as $permission => $ruleClass) {
$ruleNames[] = (new $ruleClass())->name;
}
$diffRules = array_diff(array_keys(RoleManager::auth()->getRules()), $ruleNames);
if (!$diffRules) {
Console::output("There are no rules to delete");
}
foreach ($diffRules as $rule) {
RoleManager::auth()->remove(RoleManager::auth()->getRule($rule));
Console::output("Remove rule '$rule'");
}
}
public function actionIndex()
{
$transaction = \Yii::$app->db->beginTransaction();
Console::output("Creating roles");
$this->applyRoles();
Console::output("\nCreating permissions");
$this->applyPermissions();
Console::output("\nApply deny permissions");
$this->applyDenyPermissions();
if ($this->removeUnusedRoles) {
Console::output("\nRemove unused roles");
$this->removeUnusedRoles();
}
Console::output("\nApply rules");
$this->applyRules();
if ($this->removeUnusedRules) {
Console::output("\nRemove unused rules");
$this->removeUnusedRules();
}
$transaction->commit();
$this->flushCache();
}
protected function applyRules()
{
/**
* @var Rule $ruleClass
*/
if (!$this->rules) {
Console::output("There are no rules for creating");
return;
}
foreach ($this->rules as $permission => $ruleClassName) {
foreach ($this->normalizePermission($permission) as $name) {
$permissionModel = RoleManager::getPermission($name);
if (!$permissionModel) {
Console::output("FAIL add rules. Permission '$name' not found");
exit;
}
$ruleClass = new $ruleClassName();
if (empty($ruleClass->name)) {
Console::output("FAIL add rules. Permission '$name' not found");
exit;
}
if (!RoleManager::auth()->getRule($ruleClass->name)) {
RoleManager::auth()->add($ruleClass);
}
$permissionModel->ruleName = $ruleClass->name;
RoleManager::auth()->update($name, $permissionModel);
Console::output("Set rule '{$ruleClass->name}' for '$name'");
}
}
}
public function flushCache()
{
try {
\Yii::$app->{$this->cache}->flush();
} catch (\Exception $e) {
echo "Fail clear cache: " . $e->getMessage();
}
}
public function normalizePermission($expressionPermission)
{
if (strpos($expressionPermission, '*') !== false) {
$appPattern = RoleManager::getApplicationFromPermission($expressionPermission);
$modulePattern = RoleManager::getModuleFromPermission($expressionPermission);
$controllerPattern = RoleManager::getControllerFromPermission($expressionPermission);
$actionPattern = RoleManager::getActionFromPermission($expressionPermission);
$applications = $this->collectApplications($appPattern);
$permissions = [];
if (!$applications) {
Console::output('ERROR: Applications not found in expression: ' . $appPattern);
exit;
}
foreach ($applications as $application) {
$modules = $this->collectModules($modulePattern, $application);
$controllers = [];
if (!$modulePattern) {
$controllers = $this->collectRegularControllers($controllerPattern, $application);
}
foreach ($modules as $moduleConfig) {
$controllers = array_merge(
$controllers, $this->collectControllers($controllerPattern, $moduleConfig, $applications)
);
}
$actions = $this->collectActions($controllers, $actionPattern);
foreach ($actions as $action) {
RoleManager::$defaultApplicationId = $application;
$permissions[] = RoleManager::formPermissionByAction($action);
}
}
return $permissions;
} else {
return [$expressionPermission];
}
}
public function collectActions($controllers, $id)
{
$actions = [];
foreach ($controllers as $controller) {
$class = new \ReflectionClass($controller['class']);
if ($class->isAbstract()) {
continue;
}
$controller = \Yii::createObject($controller['class'], [$controller['name'], $controller['module']]);
if ($id == "*") {
foreach (get_class_methods($controller) as $method) {
if (strpos($method, 'action') === 0 && $method != "actions") {
$name = substr($method, 6);
$actions[] = new InlineAction($name, $controller, $method);
}
}
if (method_exists($controller, 'actions')) {
foreach ($controller->actions() as $name => $value) {
$actions[] = new InlineAction($name, $controller, $value);
}
}
} elseif (method_exists($controller, $method = 'action' . $id)) {
$actions[] = new InlineAction($id, $controller, $method);
}
}
return $actions;
}
protected static function mergeConfigs($array)
{
$result = [];
foreach ($array as $item) {
try {
$file = \Yii::getAlias($item);
if (file_exists($file)) {
$result = ArrayHelper::merge($result, require $file);
}
} catch (\Exception $e) {
}
}
return $result;
}
protected function getConfigs()
{
return $this->configs ?: $this->defaultConfigs;
}
public function collectRegularControllers($pattern, $applications = [])
{
$f = function ($v) {
return [str_replace('Controller', '', basename($v, '.php')) => $v];
};
$f2 = function ($v) {
return key($v);
};
$controllers = [];
foreach ($this->getConfigs() as $configs) {
$config = static::mergeConfigs($configs);
if (in_array(Inflector::camelize(ArrayHelper::getValue($config, 'id')), (array)$applications)) {
$p = str_replace('\\', '/', ArrayHelper::getValue($config, 'controllerNamespace', 'app\controllers'));
$names = array_filter(array_map($f, glob(\Yii::getAlias("@{$p}/*Controller.php"))), $f2);
foreach ($names as $elem) {
$name = key($elem);
$file = current($elem);
$className = self::extractClassByPath($file);
if (StringHelper::matchWildcard($pattern, Inflector::camelize($name))) {
$controllers[] = ['class' => $className, 'name' => $name, 'module' => null];
}
}
}
}
return $controllers;
}
public function collectControllers($pattern, $moduleConfig, $applications)
{
$f = function ($v) {
return [str_replace('Controller', '', basename($v, '.php')) => $v];
};
$f2 = function ($v) {
return key($v);
};
$controllers = [];
$app = ArrayHelper::remove($moduleConfig[key($moduleConfig)], 'app');
if (!in_array($app, $applications)) {
return [];
}
$moduleModel = \Yii::createObject(current($moduleConfig), [key($moduleConfig), null]);
$alias = '@' . str_replace('\\', '/', $moduleModel->controllerNamespace);
$names = array_filter(array_map($f, glob(\Yii::getAlias($alias . "/*Controller.php"))), $f2);
foreach ($names as $elem) {
$name = key($elem);
$file = current($elem);
$className = self::extractClassByPath($file);
$flag = $moduleModel ? StringHelper::startsWith($className, $moduleModel->controllerNamespace) : true;
if (StringHelper::matchWildcard($pattern, Inflector::camelize($name)) && $flag) {
$controllers[] = ['class' => $className, 'name' => $name, 'module' => $moduleModel];
}
}
return $controllers;
}
public static function extractClassByPath($file)
{
if (file_exists($file)) {
$content = file_get_contents($file);
$namespace = '';
$class = basename($file, '.php');
if (preg_match('/namespace\s+(.+);/i', $content, $m)) {
$namespace = $m[1];
}
return $namespace . '\\' . $class;
}
return false;
}
protected function extractModulesById($id)
{
$modules = [];
foreach ($this->getConfigs() as $configs) {
if ($config = static::mergeConfigs($configs)) {
if (Inflector::camelize(ArrayHelper::getValue($config, 'id')) == Inflector::camelize($id)) {
$modules = ArrayHelper::getValue($config, 'modules', []);
break;
}
}
}
return $modules;
}
public function collectModules($pattern = '*', $applications = [])
{
$items = [];
foreach ((array)$applications as $app) {
$items[$app] = array_merge($this->extractModulesById($app));
}
$result = [];
foreach ($items as $app => $modules) {
if (!in_array(Inflector::camelize($app), (array)$applications)) {
continue;
}
foreach ($modules as $name => $item) {
if (is_string($item)) {
$item = ['class' => $item];
}
if (StringHelper::matchWildcard($pattern, Inflector::camelize($name))) {
$result[] = [$name => $item + ['app' => $app]];
}
}
}
return $result;
}
public function collectApplications($pattern = '*')
{
$result = [];
foreach ($this->getConfigs() as $configs) {
if ($config = static::mergeConfigs($configs)) {
$result[] = Inflector::camelize(ArrayHelper::getValue($config, 'id'));
}
}
return array_filter($result, function ($item) use ($pattern) {
return StringHelper::matchWildcard($pattern, $item);
});
}
}
| a9c5bb324ea23f11271a0902867612738e05c505 | [
"Markdown",
"PHP"
]
| 7 | PHP | carono/yii2-rbac | fb7ffd681ae4b7fe6f04b8d530dadf532c428399 | 9be855d12aaa22814a3e95dbb081f5bf37acb1b8 |
refs/heads/master | <repo_name>Blacksky81/CS202<file_sep>/lesson2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible"
content="ie=edge">
<title>Lesson2 | HTML Basic</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
</head>
<body>
<!--Headings-->
<h1>Heading One</h1>-->
<h2>Heading Two</h2>
<h3>Heading Three</h3>
<h4>Heading Four</h4>
<h5>Heading Five</h5>
<h6 id="top">Heading Six</h6>
<!-- paragraph-->
<p>
Lorem ipsum dolor sit amet, <br>
consectetur adipisicing elit.<u> Blanditiis odit adipisci similique quae.</u> Assumenda, nisi. Fugiat ex ratione dolorem repellat eum tempora. <um>Nisi ducimus quaerat fuga ea,</um> rerum vel <Strong>temporibus!</Strong>
</p>
<!-- list - ordered, unordered, description list -->
<ol type="a">
<lo>item 1</lo>
<lo>item 2</lo>
<lo>item 3</lo>
<lo>item 4</lo>
</ol>
<h3>unordered</h3>
<ul style="list-style-type:circle">
<li>item 5</li>
<li>item 6</li>
<li>item 7</li>
<li>item 8</li>
</ul>
<h3>Desciption</h3>
<dl>
<dt>CSCI202</dt>
<dd>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla laborum, modi voluptatem earum quia expedita. Dolorem pariatur molestias asperiores ipsam officiis provident nihil reiciendis nulla quis! In doloremque dolorem sed?
</dd>
</dl>
<h3>Attributes</h3>
<!-- src="URL of your image"
href="link"
width="200px"
title="Tooltip" -->
<h3>Special Characters</h3>
©
»
«
<
>
▼
▲
<hr>
<hr3>Font Awesome</hr3>
<i class="fas fa-arrow-right"></i>
<i class="fas fa-copyright"></i>
<i class="fas fa-car"></i>
<!-- LInks - absolute, relative, internal, email, sms, -->
<a href="#">Google</a>
<h3>Absolte link</h3>
<a href="http://www.cnn.com"
target="_blank">CNN</a>
<h3> relative</h3>
<a href="intedx.html"></a>
<a href="about.html"></a>
<a href="contact.html"></a>
<h3>Internal link</h3>
<!-- 2 components - idname, link -->
<a href="#Top"></a>
<h3>image</h3>
<img src="images/wester.jpg" alt="Bellingham" width="100%">
<img src="images/dog.jpg" alt="Bellingham" width="100%">
<img src="images/map.jpg" alt="Bellingham" width="100%">
<map name="bell"></map>
<area shape="circle" coords="286,195,20" href="contact.html" alt="">
<div style="margin-top:40px"
</div>
</body>
</html><file_sep>/main.js
//
// // comments
// /* mutiple lines comments */
// //statements
// //window.alert('Hello World')
// //print output information
// window. alert('Enter Your Name')
// document.write('Write is your email');
// prompt('Enter Your Email');
// coonfirm('Do you agree?');
// console.log('In console now')
// parseInt(prompt('Enter Your Age'));
//elementinnerHTML;
// //variables - storage location
// var variablename = 'Julyien';
// var text = 'Year old';
// alert(text);
// document.write(variablename);
// //concatenation +
// document.write('<h2> Hello ' + variablename + '</h2>');
// var date = Date();
// document.write(date);
// var userColor = prompt('Enter your favorite color?');
// document.bgColor = userColor;
//Date types
//Numbers, String, Boolenas, Objects, Arrays
//Integer, float,..
var num = 2333;
var txt = 'Julyien';
var gaveOver = true/false;
var student =(
Name:"Julyien",
Age:"25",
eyeColor:"green",
)
var colors = ('green', 'red', 'black');
//function - blocks of codes that are used for a specific purpose.
function func(){
//run your funtion codes
alert('Hi New User');
}
//call the function
func();
func doSomething(){
document.write();
}
//Event - actions of something that the browser or user reacts to.
//click, load, resize, mouseiver, blur, change, mouseout, | d5e7a44c9128b983d22cd9af9468803ff28315aa | [
"JavaScript",
"HTML"
]
| 2 | HTML | Blacksky81/CS202 | 1bd97fc4381f54451406cb7da93e73ed823259b8 | a8c7d440a42447a7e9336e859ee543d86681a26e |
refs/heads/master | <file_sep>import numpy as np
ko= 5.336
na = 256.
nb = 256.
scale = 25.
t = np.pi/4.
#-----------------UV-Plane--------------#
x=np.arange(na)
y=np.arange(nb)
x,y=np.meshgrid(x,y)
if (na % 2) == 0:
x = (1.*x - (na)/2. )/ na
shiftx = (na)/2.
else:
x = (1.*x - (na-1)/2.)/ na
shiftx = (na-1.)/2.+1
if (nb % 2) == 0:
y = (1.*y-(nb/2.))/nb
shifty = (nb)/2.
else:
y = (1.*y - (nb-1)/2.)/ nb
shifty = (nb-1.)/2+1
#x = np.fft.fftshift(x)
#y = np.fft.fftshift(y)
a = ko * scale
wavFTsh = np.exp( -.5*((a*x - ko*np.cos(t))**2. + (a*y - ko*np.sin(t))**2.))
wavFTsh = wavFTsh * a
wavFT = np.fft.ifftshift(np.complex_(wavFTsh))
#wavFT = np.roll(wavFT, int(shiftx), axis=1)
#wavFT = np.roll(wavFT, int(shifty), axis=0)
wav = np.fft.ifft2(wavFT).real<file_sep>import numpy as np
#definition of atrou, fan, halo wavelet functions
###########################################################################
def fan_trans(image, scales=0, reso=1):
'''
Performs fan transform on 'image' input (<NAME>. (2005),Computers and
Geosciences, 31(7), 846-864). If an array of spatial scales is not specified
returns a quasi-orthogonal basis (<NAME> al. (2014), MNRAS,
440(3), 2726-2741). Right now scale option is broken.
Parameters
----------
image : array_like
Input array, must 2-dimentional and real
scales : array_like, optional
Array of spatial scales in terms of Fourier wavenumber k
reso : float, optional
Resolution of the image in pixel^-1
Returns
-------
wt : data cube of wavelet coefficients (complex array)
wt[scales,nx,ny] -> is the size of the input image
tab_k : Array of spatial scales used for the decomposition
S1a : Wavelet power spectrum
1-dimensional array -> S11(scales)
'''
#--------------------Definitions----------------------#
ko= 5.336
delta = (2.*np.sqrt(-2.*np.log(.75)))/ko
na=float(image.shape[1])
nb=float(image.shape[0])
#--------------Spectral Logarithm--------------------#
if scales == 0:
nx = np.max(image.shape)
M=int(np.log(nx)/delta)
a2=np.zeros(M)
a2[0]=np.log(nx)
for i in range(M-1):
a2[i+1]=a2[i]-delta
a2=np.exp(a2)
tab_k = 1. / a2
else:
tab_k = scales * reso
a2 = 1. / scales
M = scales.size
#-----------------UV-Plane--------------#
x=np.arange(na)
y=np.arange(nb)
x,y=np.meshgrid(x,y)
if (na % 2) == 0:
x = (1.*x - (na)/2. )/ na
shiftx = (na)/2.
ishiftx = (na)/2
else:
x = (1.*x - (na-1)/2.)/ na
shiftx = (na-1.)/2.+1
ishiftx = (na-1.)/2.
if (nb % 2) == 0:
y = (1.*y-(nb/2.))/nb
shifty = (nb)/2.
ishifty = (nb)/2
else:
y = (1.*y - (nb-1)/2.)/ nb
shifty = (nb-1.)/2+1
ishifty = (nb-1.)/2.
#-----------------Variables--------------#
S11 = np.zeros((M,int(nb),int(na)))
wt = np.zeros((M,int(nb),int(na)), dtype=complex)
S1a = np.zeros(M)
a = ko * a2 #Scales in the wavelet space
N = int(np.pi/delta) #Number of orientation for the Morlet wavelet
#----------------Wavelet transfom------------------------#
imFT = np.fft.fft2(image)
#imFTsh = np.fft.fftshift(image)
imFT= np.roll(imFT,int(shiftx), axis=1)
imFT= np.roll(imFT,int(shifty), axis=0)
for j in range(M):
for i in range(N):
uv=0.
t=float(delta*i)
uv=np.exp( -.5*((a[j]*x - ko*np.cos(t))**2. + (a[j]*y - ko*np.sin(t))**2.))
uv = uv * a[j] #Energy normalisation
W1FT = imFT * uv
W1FT2=np.roll(W1FT,int(ishiftx), axis=1)
W1FT2=np.roll(W1FT2,int(ishifty), axis=0)
W1 = np.fft.ifft2(W1FT2)
wt[j,:,:]= wt[j,:,:]+ W1
S11[j,:,:]= S11[j,:,:] + np.abs(W1)**2.
S1a[j]=np.mean(S11[j,:,:]) * delta / float(N)
return wt, tab_k, S1a<file_sep>PYWAVAN is a python library to perform wavelet analysis | 46acb67344dda922b9288677ce8ba1abaf61d928 | [
"Python",
"Text"
]
| 3 | Python | ArloParker/wavan | b49ef4fe72dfcad51e9e88e982e6234b12282444 | 5dda89d042f688db0012f8255b263ec596bf68ce |
refs/heads/master | <file_sep>// Copyright (c) <NAME>, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.LondonTravel.Site.Controllers
{
using System;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Identity;
using MartinCostello.LondonTravel.Site.Swagger;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Models;
using Services.Data;
using Telemetry;
/// <summary>
/// A class representing the controller for the <c>/api</c> resource.
/// </summary>
[Route("api")]
public class ApiController : Controller
{
/// <summary>
/// The <see cref="IDocumentClient"/> to use. This field is read-only.
/// </summary>
private readonly IDocumentClient _client;
/// <summary>
/// The <see cref="ISiteTelemetry"/> to use. This field is read-only.
/// </summary>
private readonly ISiteTelemetry _telemetry;
/// <summary>
/// The <see cref="ILogger"/> to use. This field is read-only.
/// </summary>
private readonly ILogger<ApiController> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ApiController"/> class.
/// </summary>
/// <param name="client">The <see cref="IDocumentClient"/> to use.</param>
/// <param name="telemetry">The <see cref="ISiteTelemetry"/> to use.</param>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
public ApiController(IDocumentClient client, ISiteTelemetry telemetry, ILogger<ApiController> logger)
{
_client = client;
_telemetry = telemetry;
_logger = logger;
}
/// <summary>
/// Gets the result for the <c>/api/</c> action.
/// </summary>
/// <returns>
/// The result for the <c>/api/</c> action.
/// </returns>
[HttpGet]
public IActionResult Index() => View();
/// <summary>
/// Gets the result for the <c>/api/_count</c> action.
/// </summary>
/// <returns>
/// The result for the <c>/api/_count</c> action.
/// </returns>
[ApiExplorerSettings(IgnoreApi = true)]
[Authorize(Roles = "ADMINISTRATOR")]
[HttpGet]
[Produces("application/json")]
[Route("_count")]
public async Task<IActionResult> GetDocumentCount()
{
long count = await _client.GetDocumentCountAsync();
dynamic value = new ExpandoObject();
value.count = count;
return Ok(value);
}
/// <summary>
/// Gets the preferences for a user associated with an access token.
/// </summary>
/// <param name="authorizationHeader">The authorization header.</param>
/// <param name="cancellationToken">The cancellation token to use.</param>
/// <returns>
/// The preferences for a user.
/// </returns>
/// <response code="200">The preferences associated with the provided access token.</response>
/// <response code="401">A valid access token was not provided.</response>
/// <response code="500">An internal error occurred.</response>
[HttpGet]
[Produces("application/json", Type = typeof(PreferencesResponse))]
[ProducesResponseType(typeof(PreferencesResponse), 200)]
[ProducesResponseType(typeof(ErrorResponse), 401)]
[Route("preferences")]
[SwaggerResponseExample(typeof(PreferencesResponse), typeof(PreferencesResponseExampleProvider))]
public async Task<IActionResult> GetPreferences(
[FromHeader(Name = "Authorization")] string authorizationHeader,
CancellationToken cancellationToken = default)
{
_logger?.LogTrace("Received API request for user preferences.");
// TODO Consider allowing implicit access if the user is signed-in (i.e. access from a browser)
if (string.IsNullOrWhiteSpace(authorizationHeader))
{
_logger?.LogInformation(
"API request for preferences denied as no Authorization header/value was specified. IP: {RemoteIP}; User Agent: {UserAgent}.",
HttpContext.Connection.RemoteIpAddress,
Request.Headers["User-Agent"]);
_telemetry.TrackApiPreferencesUnauthorized();
return Unauthorized("No access token specified.");
}
LondonTravelUser user = null;
string accessToken = GetAccessTokenFromAuthorizationHeader(authorizationHeader, out string errorDetail);
if (accessToken != null)
{
user = await FindUserByAccessTokenAsync(accessToken, cancellationToken);
}
if (user == null || !string.Equals(user.AlexaToken, accessToken, StringComparison.Ordinal))
{
_logger?.LogInformation(
"API request for preferences denied as the specified access token is unknown. IP: {RemoteIP}; User Agent: {UserAgent}.",
HttpContext.Connection.RemoteIpAddress,
Request.Headers["User-Agent"]);
_telemetry.TrackApiPreferencesUnauthorized();
return Unauthorized("Unauthorized.", errorDetail);
}
_logger?.LogInformation(
"Successfully authorized API request for preferences for user Id {UserId}. IP: {RemoteIP}; User Agent: {UserAgent}.",
user.Id,
HttpContext.Connection.RemoteIpAddress,
Request.Headers["User-Agent"]);
var data = new PreferencesResponse()
{
FavoriteLines = user.FavoriteLines,
UserId = user.Id,
};
_telemetry.TrackApiPreferencesSuccess(data.UserId);
return Ok(data);
}
/// <summary>
/// Extracts the Alexa access token from the specified Authorize HTTP header value.
/// </summary>
/// <param name="authorizationHeader">The raw Authorization HTTP request header value.</param>
/// <param name="errorDetail">When the method returns contains details about an error if the access token is invalid.</param>
/// <returns>
/// The Alexa access token extracted from <paramref name="authorizationHeader"/>, if anyl otherwise <see langword="null"/>.
/// </returns>
private static string GetAccessTokenFromAuthorizationHeader(string authorizationHeader, out string errorDetail)
{
errorDetail = null;
if (!AuthenticationHeaderValue.TryParse(authorizationHeader, out AuthenticationHeaderValue authorization))
{
errorDetail = "The provided authorization value is not valid.";
return null;
}
if (!string.Equals(authorization.Scheme, "bearer", StringComparison.OrdinalIgnoreCase))
{
errorDetail = "Only the bearer authorization scheme is supported.";
return null;
}
return authorization.Parameter;
}
/// <summary>
/// Finds the user with the specified access token, if any, as an asynchronous operation.
/// </summary>
/// <param name="accessToken">The access token to find the associated user for.</param>
/// <param name="cancellationToken">The cancellation token to use.</param>
/// <returns>
/// A <see cref="Task{TResult}"/> representing the asynchronous operation to
/// find the London Travel user with the specified Alexa access token.
/// </returns>
private async Task<LondonTravelUser> FindUserByAccessTokenAsync(string accessToken, CancellationToken cancellationToken)
{
LondonTravelUser user = null;
if (!string.IsNullOrEmpty(accessToken))
{
try
{
user = (await _client.GetAsync<LondonTravelUser>((p) => p.AlexaToken == accessToken, cancellationToken)).FirstOrDefault();
}
catch (Exception ex)
{
_logger?.LogError(default, ex, "Failed to find user by access token.");
throw;
}
}
return user;
}
/// <summary>
/// Returns a response to use for an unauthorized API request.
/// </summary>
/// <param name="message">The error message.</param>
/// <param name="detail">The optional error detail.</param>
/// <returns>
/// The created instance of <see cref="ObjectResult"/>.
/// </returns>
private ObjectResult Unauthorized(string message, string detail = null)
{
var error = new ErrorResponse()
{
Message = message ?? string.Empty,
RequestId = HttpContext.TraceIdentifier,
StatusCode = (int)HttpStatusCode.Unauthorized,
Details = detail == null ? Array.Empty<string>() : new[] { detail },
};
return StatusCode((int)HttpStatusCode.Unauthorized, error);
}
}
}
| 4fa15e7dc95c9673e7f548c1d63d7dafa12c4b33 | [
"C#"
]
| 1 | C# | KevinMVTransit/alexa-london-travel-site | 692bb815512e6754f80a29f629148afac34a73d8 | d142684d66c23a075f3e60e839a7e8c054413539 |
refs/heads/master | <file_sep>import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sklearn
import pandas as pd
import os
import sys
import time
import tensorflow as tf
import csv
import json
import re
from bs4 import BeautifulSoup
from tensorflow import keras
#%%
# 读取csv文件获取文件名列表
input_dir = r'C:\python_project\ML\OPP-115\consolidation\threshold-0.5-overlap-similarity'
get_filename = tf.io.gfile.listdir(input_dir) # 得到csv文件名列表
filenames = []
path_format = os.path.join(input_dir, '{}')
for filename in get_filename:
print(filename)
part_csv = path_format.format(filename)
filenames.append(part_csv)
#%%
# 逐个读取csv文件将segment_id, type和value三列取出放入type_value列表中
type_value = []
for filename in filenames:
with open(filename, 'r', encoding='gbk') as rf:
reader = csv.reader(rf, dialect=csv.excel)
temp_value = []
for row in reader:
temp_value.append([row[4], row[5], row[6], row[8]])
type_value.append(temp_value)
for filename in type_value:
print(filename)
#%%
# 将Other类改为Other类下的具体取值,即10分类改为12分类
for i in range(len(type_value)):
for j in range(len(type_value[i])):
if type_value[i][j][1] == 'Other':
data = json.loads(type_value[i][j][2])
get_value = data['Other Type']
print(get_value['value'])
type_value[i][j][1] = get_value['value']
for value in type_value:
print(value)
#%%
# 获取具体privacy policy html文件列表
input_dir = r'C:\python_project\ML\OPP-115\sanitized_policies'
get_filename = os.listdir(input_dir)
html_filenames = []
path_format = os.path.join(input_dir, '{}')
for filename in get_filename:
print(filename)
part_csv = path_format.format(filename)
html_filenames.append(part_csv)
#%%
# get privacy policy segment
segments = []
for filename in html_filenames:
soup = BeautifulSoup(open(filename), 'html.parser')
segments.append(re.split('\|\|\|', soup.get_text()))
print(filename)
print(len(re.split('\|\|\|', soup.get_text())))
#%%
# type_value: [[['segment_id', 'type', 'attribute']]]
# segments: [[segment]]
# len(type_values) == len(segments)
# merge(type_values, segments) use segment_id -> dataset
dataset = []
for i in range(len(type_value)):
data = []
for j in range(len(type_value[i])):
for z in range(len(segments[i])):
x = z
y = int(type_value[i][j][0])
if x == y:
data.append([type_value[i][j][0],
segments[i][z],
type_value[i][j][1],
type_value[i][j][2],
type_value[i][j][3]])
dataset.append(data)
#%%
# 根据需求写不同csv文件
output_dir = "clean_data"
if not os.path.exists(output_dir):
os.mkdir(output_dir)
with open(r'clean_data\clean_data_0.5.csv', 'w', encoding='gbk', newline='') as f:
writer = csv.writer(f, dialect=csv.excel, delimiter=',')
for data in dataset:
for single_data in data:
writer.writerow(single_data)
#%%
with open(r'clean_data\clean_data_0.5_no_attribute.csv', 'w', encoding='gbk', newline='') as f:
writer = csv.writer(f, dialect=csv.excel, delimiter=',')
for data in dataset:
for single_data in data:
writer.writerow(single_data)
#%%
# 提取文件名中网站名称的部分用作比较
compare = []
for i in range(len(filenames)):
item = [re.split(r'\.html', re.split(r'\\', html_filenames[i])[5])[0],
re.split(r'\.csv', re.split(r'\\', filenames[i])[6])[0]
]
print(item)
compare.append(item)
#%%
# 读取之前生成的文件
text = []
with open(r'clean_data\clean_data_0.5_no_attribute.csv', 'r', encoding='gbk') as rf:
reader = csv.reader(rf, dialect=csv.excel)
for row in reader:
text.append(row)
#%%
# 去重,合并同segment的不同type
dataset = []
typeset = set()
typeset.add(text[0][2])
for i in range(len(text)-1):
if text[i][0] == text[i+1][0]:
typeset.add(text[i+1][2])
else:
dataset.append([text[i][3], text[i][0], text[i][1], typeset])
typeset = set()
typeset.add(text[i+1][2])
dataset.append([text[len(text)-1][3], text[len(text)-1][0], text[len(text)-1][1], typeset])
#%%
# 形成二进制向量的type并去除‘Other’类与空集
type_dic = {'Introductory/Generic': 0, 'Practice not covered': 1,
'Privacy contact information': 2, 'User Access, Edit and Deletion': 3,
'Data Security': 4, 'International and Specific Audiences': 5,
'Do Not Track': 6, 'User Choice/Control': 7,
'Data Retention': 8, 'Policy Change': 9,
'First Party Collection/Use': 10, 'Third Party Sharing/Collection': 11}
for i in range(len(dataset)):
init_type = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
init_type_list = []
dataset[i][3] = dataset[i][3] - {'Other'}
for j in range(len(list(dataset[i][3]))):
init_type[type_dic[list(dataset[i][3])[j]]] = 1
init_type_list.append(type_dic[list(dataset[i][3])[j]])
dataset[i].append(init_type)
dataset[i].append(init_type_list)
final_dataset = []
for data in dataset:
if len(data[3]) != 0:
final_dataset.append(data)
#%%
# 导出csv文件
with open(r'clean_data\clean_data_0.5_no_repeat.csv', 'w', encoding='gbk', newline='') as f:
writer = csv.writer(f, dialect=csv.excel, delimiter=',')
for data in final_dataset:
writer.writerow(data)
#%%
''' 处理APP350数据 '''
# APP350数据处理
# 读取每一篇隐私政策
input_dir = r'C:\python_project\ML\original_documents'
get_filename = tf.io.gfile.listdir(input_dir) # 得到csv文件名列表
filenames = []
path_format = os.path.join(input_dir, '{}')
for filename in get_filename:
print(filename)
part_csv = path_format.format(filename)
filenames.append(part_csv)
#%%
# 获取隐私政策纯文本内容
segments = []
for filename in filenames:
file = open(filename, encoding='ISO-8859-1', errors='ignore')
soup = BeautifulSoup(file, 'html.parser')
segments.append(soup.get_text())
#%%
# 将数据写入csv文件
with open(r'clean_data\APP350.csv', 'w', encoding='ISO-8859-1', errors='ignore', newline='') as f:
writer = csv.writer(f, dialect=csv.excel, delimiter=',')
for data in segments:
writer.writerow(data)<file_sep>目录:
文件夹
----------------------------------------
OPP-115:OPP-115语料库原始文件
original_documents:APP-350语料库原始html文件
由于文件太大,这里两个文件夹为空文件,可以在www.usableprivacy.org下载
result:不同embedding参数及最大句子长度下分类器的得分
文件
----------------------------------------
clean_data: 经处理后用于训练的OPP-115语料
clean_data_0.5: 0.5代表阈值,自行处理
clean_data_0.5_no_repeat:为去重后的文件,训练使用该文件
clean_data_0.5_no_attribute: 为未去重但去除了各类别属性仅保留类别的文件
10_run_average: 各神经网络算法跑10轮取平均
get_best_score: 不同参数调参取最好结果
SVM_Doc2vec&Word2vec:svm用deoc2vec与word2vec对比
Word2Vec:训练Word2Vec向量
Doc2Vec:训练Doc2Vec向量
OPP115_data_generation:从原始语料库生成训练用数据
load_data:加载训练数据
count_data:统计文本长度及类别数量
| 2f7864a40664aae643307d9c52913a09808b17e7 | [
"Python",
"Text"
]
| 2 | Python | JohnnieWanker/privacy-policy-classification | e97a911e59925e5680b524fac2b02c80cdafbcde | b972089b1a3cef8e2c9d782aa83fc3ba7541cc85 |
refs/heads/master | <file_sep>(function ($) {
$.shoot = function(element, options) {
var defaults = {
vertex_height: 120, // 默认抛物线高度
duration: 0.5,
start: {}, // top, left
end: {},
onEnd: $.noop
};
var self = this,
$element = $(element);
self.init = function(options) {
this.setOptions(options);
this.move();
};
self.setOptions = function(options) {
this.settings = $.extend(true, {}, defaults, options);
};
self.move = function() {
var settings = this.settings,
duration = settings.duration,
vertex_height = settings.vertex_height,
start = settings.start,
end = settings.end;
$element.appendTo('body').css({
'position': 'absolute',
'top': start.top,
'left': start.left
});
window.requestAnimationFrame(moveUp);
function moveUp() {
$element.css({
'transition': duration / 2 + 's left linear, ' + duration / 2 + 's top ease-out, ' + duration / 2 + 's transform ease',
'top': start.top - vertex_height,
'left': Math.abs(end.left - start.left) / 2,
'transform': 'rotate(360deg)'
}).on('transitionend', moveDown);
}
function moveDown() {
if(animateNotComplete()){
return;
}
$element.css({
'transition': duration / 2 + 's left linear, ' + duration / 2 + 's top ease-in, ' + duration / 2 + 's transform ease',
'top': end.top,
'left': end.left,
'transform': 'rotate(720deg)'
}).on('transitionend', moveEnd);
}
function moveEnd() {
if(animateNotComplete()){
return;
}
settings.onEnd.apply(self);
}
var _count = 0;
function animateNotComplete() {
//每个属性的变动都会触发transitionend
_count++;
if(_count < 3) {
return true;
}
_count = 0;
return false;
}
};
self.destroy = function() {
$element.remove();
};
self.init(options);
};
$.fn.shoot = function(options) {
return this.each(function() {
if (undefined == $(this).data('shoot')) {
$(this).data('shoot', new $.shoot(this, options));
}
});
};
})(jQuery); | af1cfdc249ff0b58a4b3a6069590636c50f4d09d | [
"JavaScript"
]
| 1 | JavaScript | huweixuan/slamdunk | d52d6024e9a57abbcbdbddc30fee731f71cc939a | 8afba6cfef186a83d38749661fa81f84a5a6dd9d |
refs/heads/master | <file_sep>schen237Proj7: schen237Proj7.cpp GridDisplay.o Doodlebug.o Ant.o GridControl.o
g++ -o schen237Proj7 schen237Proj7.cpp GridDisplay.o Doodlebug.o
GridDisplay.o: GridDisplay.cpp GridDisplay.h
g++ -c GridDisplay.cpp
Doodlebug.o: Doodlebug.cpp Doodlebug.h
g++ -c Doodlebug.cpp
Ant.o: Ant.cpp Ant.h
g++ -c Ant.cpp
GridControl.o: GridControl.cpp GridControl.h
g++ -c GridControl.cpp
clean:
rm *.o schen237Proj7
<file_sep>#include <cstdio>
#include <stdlib.h>
#include "GridDisplay.h"
#include "Ant.h"
#include "Doodlebug.h"
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3
class GridControl{
private:
int mode[20][20]; // 0 for not set, 1 for doodlebug, 2 for ant
Ant* antData[20][20];
Doodlebug* doodlebugData[20][20];
GridDisplay gd;
// Private method
void clearAt(int x, int y);
public:
GridControl();
bool isEmpty(int x, int y);
void setMode(int x, int y, int newMode);
void moveTo(int fromX, int fromY, int toX, int toY);
void kill(int x, int y);
};
<file_sep>/*
Name: <NAME>
NetID: schen237
File: schen237Proj7.cpp
Project #: 7
Project Name: Doodlebugs and Ants
Description: Ant Class source file
Date: 5/3/2018
Term: Spring 2018
*/
#include "Ant.h"
// default constructor
Ant::Ant(){
dayCountForSpawn = 0;
visited = false;
}
// get the day count used by spawn rule
int Ant::getDayCountForSpawn(){
return dayCountForSpawn;
}
// report spawned, dayCountForSpawn reset to 0
void Ant::spawned(){
dayCountForSpawn = 0;
}
// report survived, dayCountForSpawn + 1
void Ant::survived(){
dayCountForSpawn++;
}
<file_sep>#include <cstdio>
#include <stdlib.h>
class Ant{
private:
int dayCountForSpawn;
public:
bool visited;
Ant();
int getDayCountForSpawn();
void spawned();
void survived();
};
<file_sep>#include "GridControl.h"
#include <time.h>
int main (int argc, char** argv){
int sleepMS = 1000;
for (int i = 0; i < argc; i++){
if ('-' == argv[i][0] && 'd' == argv[i][1] && i+1 < argc){
sleepMS = atoi(argv[i+1]);
}
}
srand(time(NULL));
GridControl earth;
while(true){
earth.aDayControl();
//earth.pause(500);
earth.print();
earth.pause(sleepMS);
printf("\n");
}
return 1;
}
<file_sep>#include <cstdio>
#include <stdlib.h>
#include "GridControl.h"
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3
class Doodlebug{
private:
bool hasMoved;
int posX;
int posY;
int daysNotEat;
int dayCountForSpawn;
// For passing value out
int outputX;
int outputY;
bool actionCode; // 0 for nothing, 1 for move, 2 for new born
public:
Doodlebug(int x, int y); // x, y represent the coordinate
void hunt();
void move(GridControl* control);
void spawn();
bool starve();
bool aDay();
bool getActionCode();
int getOutputX();
int getOutputY();
};
<file_sep>/*
Name: <NAME>
NetID: schen237
File: schen237Proj7.cpp
Project #: 7
Project Name: Doodlebugs and Ants
Description: Doodlebug Class header file
Date: 5/3/2018
Term: Spring 2018
*/
#include <cstdio>
#include <stdlib.h>
// Doodlebug Class, contain information of each individual doodlebug
class Doodlebug{
private:
int daysNotEat; // Days not eating ant
int dayCountForSpawn; // day count for spawn rule
public:
bool visited; // whether visited or not, not a sensitive data, public makes access easier.
Doodlebug(); // default constructor
bool starve(); // Check whether is starve
int getDaysNotEat(); // get the day count for not eating
void noFood(); // report no food, daysNotEat+1
void gotFood(); // report got food, daysNotEat reset to 0
int getDayCountForSpawn(); // get the day count used by spawn rule
void spawned(); // report spawned, dayCountForSpawn reset to 0
void survived(); // report survived, dayCountForSpawn + 1
};
<file_sep>/*
Name: <NAME>
NetID: schen237
File: schen237Proj7.cpp
Project #: 7
Project Name: Doodlebugs and Ants
Description: Doodlebug Class source file
Date: 5/3/2018
Term: Spring 2018
*/
#include "Doodlebug.h"
// default constructor
Doodlebug::Doodlebug(){
// setting default value
daysNotEat = 0;
dayCountForSpawn = 0;
visited = false;
}
// Check whether is starve
bool Doodlebug::starve(){
// Check if the days not eat exceed its limit
if (daysNotEat >= 3){
return true;
}
return false;
}
// get the day count for not eating
int Doodlebug::getDaysNotEat(){
return daysNotEat;
}
// report no food, daysNotEat+1
void Doodlebug::noFood(){
daysNotEat++;
}
// report got food, daysNotEat reset to 0
void Doodlebug::gotFood(){
daysNotEat = 0;
}
// get the day count used by spawn rule
int Doodlebug::getDayCountForSpawn(){
return dayCountForSpawn;
}
// report spawned, dayCountForSpawn reset to 0
void Doodlebug::spawned(){
dayCountForSpawn = 0;
}
// report survived, dayCountForSpawn + 1
void Doodlebug::survived(){
dayCountForSpawn++;
}
<file_sep>#include "Doodlebug.h"
Doodlebug::Doodlebug(int x, int y){
hasMoved = false;
posX = x;
posY = y;
daysNotEat = 0;
dayCountForSpawn = 0;
actionCode = 0;
}
void Doodlebug::hunt(){
if (true/* If ant around*/){
// Process eating
daysNotEat = 0;
}
else{
//Move
daysNotEat++;
}
}
void Doodlebug::move(GridControl* control){
int randomValue;
int moveComplete = false;
bool directionTried[4] = {false};
while(!moveComplete){
randomValue = rand() % 4;
switch(randomValue){
case UP:
directionTried[UP] = true;
if (posY > 0 && control->isEmpty(posX, posY-1)){
posY--;
moveComplete = true;
}
break;
case DOWN:
directionTried[DOWN] = true;
if (posY < 19 && control->isEmpty(posX, posY+1)){
posY++;
moveComplete = true;
}
break;
case LEFT:
directionTried[LEFT] = true;
if (posX > 0 && control->isEmpty(posX-1, posY)){
posX--;
moveComplete = true;
}
break;
case RIGHT:
directionTried[RIGHT] = true;
if (posY < 19 && control->isEmpty(posX+1, posY)){
posX++;
moveComplete = true;
}
break;
default:
printf("Something wrong in Doodlebug::move()");
exit(999);
break;
}
}
}
void Doodlebug::spawn(){
if (dayCountForSpawn >= 8){
// Generate random value
// Check if position occupy
// execute
if (true /* No position to spawn */){
return;
}
dayCountForSpawn = 0;
}
}
bool Doodlebug::starve(){
if (daysNotEat >= 3){
return true;
}
return false;
}
// Return boolean to decide if object should be deallocate
bool Doodlebug::aDay(){
hunt();
spawn();
return starve();
}
bool Doodlebug::getActionCode(){
return actionCode;
}
int Doodlebug::getOutputX(){
return outputX;
}
int Doodlebug::getOutputY(){
return outputY;
}
<file_sep>/*
Name: <NAME>
NetID: schen237
File: schen237Proj7.cpp
Project #: 7
Project Name: Doodlebugs and Ants
Description: GridControl Class header file
Date: 5/3/2018
Term: Spring 2018
*/
#include <cstdio>
#include <stdlib.h>
#include "GridDisplay.h"
#include "Ant.h"
#include "Doodlebug.h"
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3
// GridControl Class, to control ant class and doodlebug class
class GridControl{
private:
int mode[20][20]; // 0 for not set, 1 for doodlebug, 2 for ant
Ant* antData[20][20];
Doodlebug* doodlebugData[20][20];
GridDisplay gd;
// Temp variable set
bool tempOpen; // Determine if temp variable is in use, prevent incomplete transaction
int tempX; // data variable for X
int tempY; // data variable for Y
// Assistant method
bool arrayBoundCheck(int x, int y); // Check if the given x, y are within the bound
void clearAt(int x, int y); // To clear any element at given x, y posiion
void aDay(int x, int y); // Run daily task on given x, y position
bool isEmpty(int x, int y); // Check if given x, y position is empty
void moveTo(int &fromX, int &fromY, int toX, int toY); // Move given From position to given To position
void setMode(int x, int y, int newMode); // Set New Mode on the given position
// Action method
void hunt(int &x, int &y); // hunt ant if any nearby, or move to a random empty nearby position
void spawn(int x, int y); // Spawn a new creature in random nearby position
void starve(int x, int y); // Check if it's starved, if so kill itself
bool randomNearby(int x, int y, int targetMode); // generate a random nearby qualified target
public:
GridControl(); // Default constructor
void aDayControl(); // A method to run daily task on all the elements
void print(); // Print out the grid using the GridDisplay API
void pause(int ms); // Relay method to GridDisplay Class's mySleep
};
<file_sep>#include "Ant.h"
Ant::Ant(int x, int y){
hasMoved = false;
posX = x;
posY = y;
daysNotEat = 0;
dayCountForSpawn = 0;
actionCode = 0;
}
void Ant::move(GridControl* control){
int randomValue;
int moveComplete = false;
bool directionTried[4] = {false};
while(!moveComplete){
randomValue = rand() % 4;
switch(randomValue){
case UP:
directionTried[UP] = true;
if (posY > 0 && control->isEmpty(posX, posY-1)){
posY--;
moveComplete = true;
}
break;
case DOWN:
directionTried[DOWN] = true;
if (posY < 19 && control->isEmpty(posX, posY+1)){
posY++;
moveComplete = true;
}
break;
case LEFT:
directionTried[LEFT] = true;
if (posX > 0 && control->isEmpty(posX-1, posY)){
posX--;
moveComplete = true;
}
break;
case RIGHT:
directionTried[RIGHT] = true;
if (posY < 19 && control->isEmpty(posX+1, posY)){
posX++;
moveComplete = true;
}
break;
default:
printf("Something wrong in Ant::move()");
exit(999);
break;
}
}
}
void Ant::spawn(){
if (dayCountForSpawn >= 3){
// Generate random value
// Check if position occupy
// execute
if (true /* No position to spawn */){
return;
}
dayCountForSpawn = 0;
}
}
// Return boolean to decide if object should be deallocate
void Ant::aDay(){
move();
spawn();
}
<file_sep>#include "GridDisplay.h"
int main ( int argc, char** argv )
{
int i;
GridDisplay gd(20, 20);
gd.showGrid ( );
// show one change ever second
for ( i = 0 ; i < 20 ; i++ )
{
gd.mySleep ( 1000 );
char ch = (char) ( (int) 'a' + i );
gd.setChar(i,i, ch);
gd.showGrid ( );
}
// show multiple positions change "at once"
for ( i = 7 ; i < 17 ; i++ )
{
gd.setChar ( 3, i, '$');
}
gd.showGrid ( );
int j,k;
// alternate between 2 "flashing" values
for ( i = 0 ; i < 20 ; i++ )
{
gd.mySleep ( 250 );
for (j = 0 ; j < 4 ; j++)
for ( k = 0 ; k < 4 ; k++ )
gd.setChar ( 12+j, 4+k, '9');
gd.showGrid ( );
gd.mySleep ( 250 );
for (j = 0 ; j < 4 ; j++)
for ( k = 0 ; k < 4 ; k++ )
gd.setChar ( 12+j, 4+k, '6');
gd.showGrid ( );
}
return 1;
}
<file_sep>#include "Ant.h"
Ant::Ant(){
dayCountForSpawn = 0;
visited = false;
}
int Ant::getDayCountForSpawn(){
return dayCountForSpawn;
}
void Ant::spawned(){
dayCountForSpawn-=3;
}
void Ant::survived(){
dayCountForSpawn++;
}
<file_sep>#include <cstdio>
#include <stdlib.h>
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3
class Ant{
private:
bool hasMoved;
int posX;
int posY;
int daysNotEat;
int dayCountForSpawn;
// For passing value out
int outputX;
int outputY;
bool actionCode; // 0 for nothing, 1 for move, 2 for new born
public:
Ant(int x, int y); // x, y represent the coordinate
void move();
void spawn();
void aDay();
};
<file_sep>#include <cstdio>
#include <stdlib.h>
class Doodlebug{
private:
int daysNotEat;
int dayCountForSpawn;
public:
bool visited;
Doodlebug();
bool starve();
int getDaysNotEat();
void noFood();
void gotFood();
int getDayCountForSpawn();
void spawned();
void survived();
};
<file_sep>#include "GridControl.h"
GridControl::GridControl(){
for (int x = 0; x < 20; x++){
for (int y = 0; y < 20; y++){
mode[x][y] = 0;
antData[x][y] = NULL;
doodlebugData[x][y] = NULL;
}
}
}
// This will clear
void GridControl::setMode(int x, int y, int newMode){
clearAt(x, y);
switch(newMode){
case 0:
/* Do nothing */
break;
case 1:
doodlebugData[x][y] = new Doodlebug(x, y);
break;
case 2:
antData[x][y] = new Ant(x, y);
break;
default:
printf("Something wrong in GridControl::setMode()");
exit(999);
break;
}
}
// Private method
void GridControl::clearAt(int x, int y){
if (antData[x][y] != NULL){
delete antData[x][y];
}
if (doodlebugData[x][y] != NULL){
delete doodlebugData[x][y];
}
if (mode[x][y] != 0){
mode[x][y] = 0;
}
}
// Private method
bool isEmpty(int x, int y){
return mode == 0;
}
void moveTo(int fromX, int fromY, int toX, int toY){
if (isEmpty(fromX, fromY)){
printf("Nothing to move\n");
return;
}
if (isEmpty(toX, toY)){
// Move doodlebug
if (mode[fromX][fromY] == 1){
doodlebugData[toX][toY] = doodlebugData[fromX][fromY];
doodlebugData[fromX][fromY] = NULL;
}
// Move ant
else if (mode[fromX][fromY] == 2){
antData[toX][toY] = antDataData[fromX][fromY];
antDataData[fromX][fromY] = NULL;
}
// Move mode
mode[toX][toY] = mode[fromX][fromY];
mode[fromX][fromY] = 0;
}
}
void kill(int x, int y){
if (mode[20] == 1){
delete doodlebugData[x][y];
}
else if (mode[20] == 2){
delete antData[x][y];
}
else{
printf("Nothing to kill\n");
}
}
<file_sep>/*
Name: <NAME>
NetID: schen237
File: schen237Proj7.cpp
Project #: 7
Project Name: Doodlebugs and Ants
Description: Main Source File
Date: 5/3/2018
Term: Spring 2018
*/
#include "GridControl.h"
#include <time.h>
int main (int argc, char** argv){
int sleepMS = 1000;
for (int i = 0; i < argc; i++){
if ('-' == argv[i][0] && 'd' == argv[i][1] && i+1 < argc){
sleepMS = atoi(argv[i+1]);
}
}
srand(time(NULL));
GridControl earth;
while(true){
earth.aDayControl();
//earth.pause(500);
earth.print();
earth.pause(sleepMS);
printf("\n");
}
return 1;
}
<file_sep>#include <cstdio>
#include <stdlib.h>
#include "GridDisplay.h"
#include "Ant.h"
#include "Doodlebug.h"
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3
class GridControl{
private:
int mode[20][20]; // 0 for not set, 1 for doodlebug, 2 for ant
Ant* antData[20][20];
Doodlebug* doodlebugData[20][20];
GridDisplay gd;
bool tempOpen;
int tempX;
int tempY;
// Private method
void clearAt(int x, int y);
public:
GridControl();
bool isEmpty(int x, int y);
bool isAnt(int x, int y);
void setMode(int x, int y, int newMode);
void moveTo(int &fromX, int &fromY, int toX, int toY);
void kill(int x, int y);
void aDayControl();
void aDay(int x, int y);
void hunt(int &x, int &y);
void spawn(int x, int y);
void starve(int x, int y);
bool randomNearby(int x, int y, int targetMode);
void print();
void pause(int ms);
bool arrayBoundCheck(int x, int y);
};
<file_sep>#include <cstdlib>
#include <ctime>
#include "GridDisplay.h"
class Beetle;
class Island
{
private:
Beetle* **location; // Dynamic 2D array of pointers
int rows;
int cols;
GridDisplay *gd;
public:
Island(GridDisplay *grid)
{
gd = grid;
rows = 20;
cols = 20;
location = new Beetle**[rows];
for ( int i = 0 ; i < rows ; i++ )
{
location[i] = new Beetle*[cols];
for ( int j = 0 ; j < cols ; j++ )
{
location[i][j] = NULL;
}
}
}
int getRows()
{
return rows;
}
int getCols()
{
return cols;
}
bool isValid (int r, int c)
{
if (( r >= 0 && r < rows ) && ( c >= 0 && c < cols))
return true;
else
return false;
}
bool isOccupied (int r, int c)
{
if ( location[r][c] == NULL )
return false;
else
return true;
}
bool addBeetle (Beetle* b, int r, int c)
{
// verify to location is valid
if ( isValid (r, c) == false )
return false;
// verify to location is empty
if ( isOccupied (r, c) == true)
return false;
location[r][c] = b;
gd->setChar (r,c,'@');
return true;
}
bool moveBeetle (int currX, int currY, int nextX, int nextY)
{
// verify to/from locations are valid
if ( isValid (currX, currY) == false )
return false;
if ( isValid (nextX, nextY) == false )
return false;
// verify a beetle exists at current location
if ( isOccupied (currX, currY) == false)
return false;
// verify to location is empty
if ( isOccupied (nextX, nextY) == true)
return false;
location[nextX][nextY] = location[currX][currY];
location[currX][currY] = NULL;
gd->setChar (currX, currY, '.');
gd->setChar (nextX, nextY, '@');
return true;
}
};
class Beetle
{
private:
Island* isl;
int row;
int col;
int dayLastMoved;
public:
Beetle(Island *island)
{
isl = island;
do // randomly select a location until an empty location is found
{
row = rand() % island->getRows();
col = rand() % island->getCols();
}
while ( island->addBeetle (this, row, col) == false );
dayLastMoved = 0;
}
void move()
{
wander();
//spawn();
}
void wander ()
{
int nextX = -999;
int nextY = -999;
int direction = rand() % 4;
if ( direction == 0 ) // attempt to move left
{
nextX = row;
nextY = col-1;
}
else if ( direction == 1 ) // attempt to move right
{
nextX = row;
nextY = col+1;
}
else if ( direction == 2 ) // attempt to move up
{
nextX = row-1;
nextY = col;
}
else if ( direction == 3 ) // attempt to move down
{
nextX = row+1;
nextY = col;
}
if ( isl->moveBeetle ( row, col, nextX, nextY ) == true )
{
row = nextX;
col = nextY;
}
}
};
int main ( int argc, char** argv)
{
srand(time(NULL));
GridDisplay gd;
Island island(&gd);
int day = 0;
int bugCount = 20;
Beetle** bugs; // create an dynamic array of beetle pointers
bugs = new Beetle*[bugCount];
for (int i = 0 ; i < bugCount ; i++)
bugs[i] = new Beetle (&island);
// show the initial locations of the beetles
gd.showGrid();
// loop for 20 days
while ( day < 20 )
{
day++;
// move each beetle in the "bug array"
for (int i = 0 ; i < bugCount ; i++)
{
bugs[i]->move();
}
// pause execution to allow "animation" to be seen
gd.mySleep( 1000 );
gd.showGrid();
}
}
<file_sep>schen237Proj7: schen237Proj7.cpp GridDisplay.o Doodlebug.o Ant.o GridControl.o
g++ -o schen237Proj7 schen237Proj7.cpp GridDisplay.o Doodlebug.o Ant.o GridControl.o
GridDisplay.o: GridDisplay.cpp GridDisplay.h
g++ -c GridDisplay.cpp
Doodlebug.o: Doodlebug.cpp Doodlebug.h
g++ -c Doodlebug.cpp
Ant.o: Ant.cpp Ant.h
g++ -c Ant.cpp
GridControl.o: GridControl.cpp GridControl.h
g++ -c GridControl.cpp
clean:
rm *.o schen237Proj7
run:
./schen237Proj7
<file_sep>/*
Name: <NAME>
NetID: schen237
File: schen237Proj7.cpp
Project #: 7
Project Name: Doodlebugs and Ants
Description: GridControl Class source file
Date: 5/3/2018
Term: Spring 2018
*/
#include "GridControl.h"
//////////////////////////////////////////////////////////////////////////////
// Default constructor
GridControl::GridControl(){
int randomNum; // Variable for randomNumber
int doodlebugRemain = 5; // Remain doodlebug need to be place on board
int antRemain = 100; // Remain ant need to be place on board
// Reset all member data
for (int x = 0; x < 20; x++){
for (int y = 0; y < 20; y++){
mode[x][y] = 0;
antData[x][y] = NULL;
doodlebugData[x][y] = NULL;
gd.setChar (x, y, '*');
}
}
// Randomly insert creature
// loop continue until no more creature need to be place on board
while(doodlebugRemain > 0 || antRemain > 0){
for (int x = 0; x < 20; x++){
for (int y = 0; y < 20; y++){
if (mode[x][y] == 0){
// If no more creature need to be place, then break the loop.
if (antRemain <= 0 && doodlebugRemain <= 0){
x = 99;
y = 99;
break;
}
// The following code help spread the piece out on the board
// Generate random number from 0~8
// Here is why choose 8
// 105 creature in 400 = 105/400, empty space = 1-105/400 = 295/400 = 73.75%
// 1 and 2 are for 2 creatures. Anything other than 1, 2 will be space
// % of space will be (i-2)/i, eg. 1/3, 2/4, 3/5...
// 6/8 = 75% is the closest to 73.75%
randomNum = rand() % 8;
// If doodlebug exceed quota
if (randomNum == 1 && doodlebugRemain <= 0 && antRemain > 0){
randomNum = 2;
}
// If ant exceed quota
if (randomNum == 2 && antRemain <= 0 && doodlebugRemain > 0){
randomNum = 1;
}
// additional chance for space
if (randomNum >= 3){
randomNum = 0;
}
// Place the creature
setMode(x, y, randomNum);
// Adjust counter
if (randomNum == 1){
doodlebugRemain--;
}
else if (randomNum == 2){
antRemain--;
}
}
}
}
}
// Reset temp variable set
tempOpen = false;
tempX = 0;
tempY = 0;
}
//////////////////////////////////////////////////////////////////////////////
// Check if the given x, y are within the bound
bool GridControl::arrayBoundCheck(int x, int y){
if (x > 19 || x < 0 || y > 19 || y < 0){
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
// To clear any element at given x, y posiion
void GridControl::clearAt(int x, int y){
// Reset object* 2d array to NULL
if (antData[x][y] != NULL){
delete antData[x][y];
antData[x][y] = NULL;
}
if (doodlebugData[x][y] != NULL){
delete doodlebugData[x][y];
doodlebugData[x][y] = NULL;
}
// Reset mode to 0
if (mode[x][y] != 0){
mode[x][y] = 0;
}
}
//////////////////////////////////////////////////////////////////////////////
// Run daily task on given x, y position
void GridControl::aDay(int x, int y){
// Doodlebug
if (mode[x][y] == 1){
hunt(x, y);
spawn(x, y);
starve(x, y);
}
// Ant
else if (mode[x][y] == 2){
// Find the new nearby position available
if (randomNearby(x, y, 0)){
if (tempOpen == false){
printf("GridControl::aDay temp var access control fail\n");
abort();
}
// Moving Process
int newX = tempX;
int newY = tempY;
tempOpen = false; // Close temp access
moveTo(x, y, newX, newY);
spawn(x, y);
}
antData[x][y]->survived(); // Report survived
tempOpen = false; // Close temp access
}
}
//////////////////////////////////////////////////////////////////////////////
// Check if given x, y position is empty
bool GridControl::isEmpty(int x, int y){
return mode[x][y] == 0;
}
//////////////////////////////////////////////////////////////////////////////
// Move given From position to given To position
void GridControl::moveTo(int &fromX, int &fromY, int toX, int toY){
if (isEmpty(fromX, fromY)){
printf("Nothing to move\n");
return;
}
if (isEmpty(toX, toY)){
// Move doodlebug
if (mode[fromX][fromY] == 1){
doodlebugData[toX][toY] = doodlebugData[fromX][fromY];
doodlebugData[fromX][fromY] = NULL;
}
// Move ant
else if (mode[fromX][fromY] == 2){
antData[toX][toY] = antData[fromX][fromY];
antData[fromX][fromY] = NULL;
}
// Move mode
mode[toX][toY] = mode[fromX][fromY];
mode[fromX][fromY] = 0;
// Let original caller know position changed
fromX = toX;
fromY = toY;
}
}
//////////////////////////////////////////////////////////////////////////////
// Set New Mode on the given position
void GridControl::setMode(int x, int y, int newMode){
clearAt(x, y);
switch(newMode){
case 0:
/* Do nothing */
break;
case 1:
doodlebugData[x][y] = new Doodlebug();
break;
case 2:
antData[x][y] = new Ant();
break;
default:
printf("Something wrong in GridControl::setMode()");
abort();
break;
}
mode[x][y] = newMode;
}
//////////////////////////////////////////////////////////////////////////////
// hunt ant if any nearby, or move to a random empty nearby position
void GridControl::hunt(int &x, int &y){
if (mode[x][y] != 1){
printf("GridControl::hunt given position is not doodlebug\n");
abort();
}
if (randomNearby(x, y, 2)){
if (tempOpen == false){
printf("GridControl::hunt temp var access control fail\n");
abort();
}
int killX = tempX;
int killY = tempY;
tempOpen = false; // Close temp access
setMode(killX, killY, 0);
doodlebugData[x][y]->gotFood(); // Report got food
}
else{
tempOpen = false; // Close temp access from the if statement
randomNearby(x, y, 0); // Find randomNearby position(return are send back by tempX, Y)
doodlebugData[x][y]->noFood(); // Report no food
// Moving Process
int newX = tempX;
int newY = tempY;
tempOpen = false; // Close temp access
moveTo(x, y, newX, newY);
}
}
//////////////////////////////////////////////////////////////////////////////
// Spawn a new creature in random nearby position
void GridControl::spawn(int x, int y){
// If no spot nearby
if (!randomNearby(x, y, 0)){
tempOpen = false; // Close temp access
return;
}
// Check if access open
if (tempOpen == false){
printf("GridControl::spawn temp var access control fail\n");
abort();
}
// Save send back value
int newX = tempX;
int newY = tempY;
tempOpen = false; // Close temp access
// If is doodlebug
if (mode[x][y] == 1){
if (doodlebugData[x][y]->getDayCountForSpawn() >= 8){
setMode(newX, newY, 1);
doodlebugData[x][y]->spawned();
}
}
// If is ant
else if (mode[x][y] == 2){
if (antData[x][y]->getDayCountForSpawn() >= 3){
setMode(newX, newY, 2);
antData[x][y]->spawned();
}
}
}
//////////////////////////////////////////////////////////////////////////////
// Check if it's starved, if so kill itself, or report survived
void GridControl::starve(int x, int y){
if (mode[x][y] == 1){
if (doodlebugData[x][y]->starve()){
setMode(x, y, 0);
}
else{
doodlebugData[x][y]->survived();
}
}
}
//////////////////////////////////////////////////////////////////////////////
// generate a random nearby qualified target
bool GridControl::randomNearby(int x, int y, int targetMode){
// Check temp variable status
if (tempOpen == true){
printf("GridControl::randomNearby temp var access control fail\n");
abort();
}
tempOpen = true;
tempX = x;
tempY = y;
int randomNum;
bool accessLog[4] = {false};
// Loop until no available position to continue
while(!accessLog[0] || !accessLog[1] || !accessLog[2] || !accessLog[3]){
// Decide by random available nearby position
randomNum = rand() % 4;
switch(randomNum){
case UP:
accessLog[UP] = true;
if (mode[x][y-1] == targetMode){
if (!arrayBoundCheck(tempX, tempY-1)){continue;}
tempY--;
return true;
}
break;
case DOWN:
accessLog[DOWN] = true;
if (mode[x][y+1] == targetMode){
if (!arrayBoundCheck(tempX, tempY+1)){continue;}
tempY++;
return true;
}
break;
case LEFT:
accessLog[LEFT] = true;
if (mode[x-1][y] == targetMode){
if (!arrayBoundCheck(tempX-1, tempY)){continue;}
tempX--;
return true;
}
break;
case RIGHT:
accessLog[RIGHT] = true;
if (mode[x+1][y] == targetMode){
if (!arrayBoundCheck(tempX+1, tempY)){continue;}
tempX++;
return true;
}
break;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
// A method to run daily task on all the elements
void GridControl::aDayControl(){
//reset visited
for (int x = 0; x < 20; x++){
for (int y = 0; y < 20; y++){
if (mode[x][y] == 1){
doodlebugData[x][y]->visited = false;
}
if (mode[x][y] == 2){
antData[x][y]->visited = false;
}
}
}
// doodlebug's turn
for (int x = 0; x < 20; x++){
for (int y = 0; y < 20; y++){
if (mode[x][y] == 1 && !(doodlebugData[x][y]->visited)){
doodlebugData[x][y]->visited = true;
aDay(x, y);
}
}
}
// Ant's turn
for (int x = 0; x < 20; x++){
for (int y = 0; y < 20; y++){
if (mode[x][y] == 2 && !(antData[x][y]->visited)){
antData[x][y]->visited = true;
aDay(x, y);
}
}
}
}
//////////////////////////////////////////////////////////////////////////////
// Print out the grid using the GridDisplay API
void GridControl::print(){
char displayText;
for (int x = 0; x < 20; x++){
for (int y = 0; y < 20; y++){
switch (mode[x][y]){
case 0:
displayText = ' ';
break;
case 1:
displayText = 'D';
break;
case 2:
displayText = 'A';
break;
}
gd.setChar (x, y, displayText);
}
}
gd.showGrid ( );
}
//////////////////////////////////////////////////////////////////////////////
// Relay method to GridDisplay Class's mySleep
void GridControl::pause(int ms){
gd.mySleep(ms);
}
<file_sep>/*
Name: <NAME>
NetID: schen237
File: schen237Proj7.cpp
Project #: 7
Project Name: Doodlebugs and Ants
Description: Ant Class header file
Date: 5/3/2018
Term: Spring 2018
*/
#include <cstdio>
#include <stdlib.h>
class Ant{
private:
int dayCountForSpawn; // day count for spawn rule
public:
bool visited; // whether visited or not, not a sensitive data, public makes access easier.
Ant(); // default constructor
int getDayCountForSpawn(); // get the day count used by spawn rule
void spawned(); // report spawned, dayCountForSpawn reset to 0
void survived(); // report survived, dayCountForSpawn + 1
};
<file_sep>#include "GridControl.h"
GridControl::GridControl(){
int randomNum;
int doodlebugRemain = 5;
int antRemain = 100;
// Reset Board
for (int x = 0; x < 20; x++){
for (int y = 0; y < 20; y++){
mode[x][y] = 0;
antData[x][y] = NULL;
doodlebugData[x][y] = NULL;
gd.setChar (x, y, '*');
}
}
// Randomly insert creature
while(doodlebugRemain > 0 || antRemain > 0){
for (int x = 0; x < 20; x++){
for (int y = 0; y < 20; y++){
if (mode[x][y] == 0){
if (antRemain <= 0 && doodlebugRemain <= 0){
x = 99;
y = 99;
break;
}
randomNum = rand() % 8;
// If doodlebug exceed quota
if (randomNum == 1 && doodlebugRemain <= 0 && antRemain > 0){
randomNum = 2;
}
// If ant exceed quota
if (randomNum == 2 && antRemain <= 0 && doodlebugRemain > 0){
randomNum = 1;
}
// additional chance for space
if (randomNum >= 3){
randomNum = 0;
}
// printf("rand: %d at (%d, %d)\n", randomNum, x, y);
setMode(x, y, randomNum);
if (randomNum == 1){
doodlebugRemain--;
}
else if (randomNum == 2){
antRemain--;
}
}
}
}
}
tempOpen = false;
tempX = 0;
tempY = 0;
//print();
}
// This will clear
void GridControl::setMode(int x, int y, int newMode){
//printf("SetMode at (%d, %d)\n", x, y);
clearAt(x, y);
switch(newMode){
case 0:
/* Do nothing */
break;
case 1:
doodlebugData[x][y] = new Doodlebug();
break;
case 2:
antData[x][y] = new Ant();
break;
default:
printf("Something wrong in GridControl::setMode()");
abort();
break;
}
mode[x][y] = newMode;
}
// Private method
void GridControl::clearAt(int x, int y){
//printf("clearAt at (%d, %d)\n", x, y);
if (antData[x][y] != NULL){
delete antData[x][y];
antData[x][y] = NULL;
}
if (doodlebugData[x][y] != NULL){
delete doodlebugData[x][y];
doodlebugData[x][y] = NULL;
}
if (mode[x][y] != 0){
mode[x][y] = 0;
}
}
// Private method
bool GridControl::isEmpty(int x, int y){
return mode[x][y] == 0;
}
bool GridControl::isAnt(int x, int y){
return mode[x][y] == 2;
}
void GridControl::moveTo(int &fromX, int &fromY, int toX, int toY){
if (isEmpty(fromX, fromY)){
printf("Nothing to move\n");
return;
}
if (isEmpty(toX, toY)){
// Move doodlebug
if (mode[fromX][fromY] == 1){
doodlebugData[toX][toY] = doodlebugData[fromX][fromY];
doodlebugData[fromX][fromY] = NULL;
}
// Move ant
else if (mode[fromX][fromY] == 2){
antData[toX][toY] = antData[fromX][fromY];
antData[fromX][fromY] = NULL;
}
// Move mode
mode[toX][toY] = mode[fromX][fromY];
mode[fromX][fromY] = 0;
// Let original caller know position changed
fromX = toX;
fromY = toY;
}
}
/*
void GridControl::kill(int x, int y){
if (mode[x][y] == 1){
delete doodlebugData[x][y];
doodlebugData[x][y] = NULL;
}
else if (mode[x][y] == 2){
delete antData[x][y];
antData[x][y] = NULL;;
}
else{
printf("Nothing to kill\n");
}
mode[x][y] = 0;
}
*/
void GridControl::aDayControl(){
//reset visited
for (int x = 0; x < 20; x++){
for (int y = 0; y < 20; y++){
if (mode[x][y] == 1){
doodlebugData[x][y]->visited = false;
}
if (mode[x][y] == 2){
antData[x][y]->visited = false;
}
}
}
// doodlebug's turn
for (int x = 0; x < 20; x++){
for (int y = 0; y < 20; y++){
if (mode[x][y] == 1 && !(doodlebugData[x][y]->visited)){
doodlebugData[x][y]->visited = true;
aDay(x, y);
}
}
}
// Ant's turn
for (int x = 0; x < 20; x++){
for (int y = 0; y < 20; y++){
if (mode[x][y] == 2 && !(antData[x][y]->visited)){
antData[x][y]->visited = true;
aDay(x, y);
}
}
}
}
void GridControl::aDay(int x, int y){
// Doodlebug
if (mode[x][y] == 1){
hunt(x, y);
spawn(x, y);
starve(x, y);
}
// Ant
else if (mode[x][y] == 2){
if (randomNearby(x, y, 0)){
if (tempOpen == false){
printf("GridControl::aDay temp var access control fail\n");
abort();
}
// Moving Process
int newX = tempX;
int newY = tempY;
tempOpen = false; // Close temp access
moveTo(x, y, newX, newY);
spawn(x, y);
}
antData[x][y]->survived();
tempOpen = false; // Close temp access
}
}
void GridControl::hunt(int &x, int &y){
if (mode[x][y] != 1){
printf("GridControl::hunt given position is not doodlebug\n");
abort();
}
if (randomNearby(x, y, 2)){
if (tempOpen == false){
printf("GridControl::hunt temp var access control fail\n");
abort();
}
int killX = tempX;
int killY = tempY;
tempOpen = false; // Close temp access
setMode(killX, killY, 0);
doodlebugData[x][y]->gotFood();
}
else{
tempOpen = false; // Close temp access from the if statement
randomNearby(x, y, 0);
doodlebugData[x][y]->noFood();
// Moving Process
int newX = tempX;
int newY = tempY;
tempOpen = false; // Close temp access
moveTo(x, y, newX, newY);
}
}
void GridControl::spawn(int x, int y){
if (!randomNearby(x, y, 0)){
tempOpen = false; // Close temp access
return;
}
// Check if access open
if (tempOpen == false){
printf("GridControl::spawn temp var access control fail\n");
abort();
}
int newX = tempX;
int newY = tempY;
tempOpen = false; // Close temp access
if (mode[x][y] == 1){
if (doodlebugData[x][y]->getDayCountForSpawn() >= 8){
setMode(newX, newY, 1);
doodlebugData[x][y]->spawned();
}
}
else if (mode[x][y] == 2){
if (antData[x][y]->getDayCountForSpawn() >= 3){
setMode(newX, newY, 2);
antData[x][y]->spawned();
}
}
}
void GridControl::starve(int x, int y){
if (mode[x][y] == 1){
if (doodlebugData[x][y]->starve()){
setMode(x, y, 0);
}
else{
doodlebugData[x][y]->survived();
}
}
}
bool GridControl::randomNearby(int x, int y, int targetMode){
if (tempOpen == true){
printf("GridControl::randomNearby temp var access control fail\n");
abort();
}
tempOpen = true;
tempX = x;
tempY = y;
int randomNum;
bool accessLog[4] = {false};
while(!accessLog[0] || !accessLog[1] || !accessLog[2] || !accessLog[3]){
randomNum = rand() % 4;
switch(randomNum){
case UP:
accessLog[UP] = true;
if (mode[x][y-1] == targetMode){
if (!arrayBoundCheck(tempX, tempY-1)){continue;}
tempY--;
return true;
}
break;
case DOWN:
accessLog[DOWN] = true;
if (mode[x][y+1] == targetMode){
if (!arrayBoundCheck(tempX, tempY+1)){continue;}
tempY++;
return true;
}
break;
case LEFT:
accessLog[LEFT] = true;
if (mode[x-1][y] == targetMode){
if (!arrayBoundCheck(tempX-1, tempY)){continue;}
tempX--;
return true;
}
break;
case RIGHT:
accessLog[RIGHT] = true;
if (mode[x+1][y] == targetMode){
if (!arrayBoundCheck(tempX+1, tempY)){continue;}
tempX++;
return true;
}
break;
}
}
return false;
}
void GridControl::print(){
char displayText;
for (int x = 0; x < 20; x++){
for (int y = 0; y < 20; y++){
switch (mode[x][y]){
case 0:
displayText = ' ';
break;
case 1:
displayText = 'D';
break;
case 2:
displayText = 'A';
break;
}
gd.setChar (x, y, displayText);
}
}
gd.showGrid ( );
}
void GridControl::pause(int ms){
gd.mySleep(ms);
}
bool GridControl::arrayBoundCheck(int x, int y){
if (x > 19 || x < 0 || y > 19 || y < 0){
return false;
}
return true;
}
<file_sep>GridMain: GridMain.cpp GridDisplay.o
g++ -o GridMain GridMain.cpp GridDisplay.o
gddemo: gddemo.cpp GridDisplay.o
g++ -o gddemo gddemo.cpp GridDisplay.o
GridDisplay.o: GridDisplay.cpp GridDisplay.h
g++ -c GridDisplay.cpp
clean:
rm -f *.o GridMain
<file_sep>#include "Doodlebug.h"
Doodlebug::Doodlebug(){
daysNotEat = 0;
dayCountForSpawn = 0;
visited = false;
}
bool Doodlebug::starve(){
if (daysNotEat >= 3){
return true;
}
return false;
}
int Doodlebug::getDaysNotEat(){
return daysNotEat;
}
int Doodlebug::getDayCountForSpawn(){
return dayCountForSpawn;
}
void Doodlebug::noFood(){
daysNotEat++;
}
void Doodlebug::gotFood(){
daysNotEat = 0;
}
void Doodlebug::spawned(){
dayCountForSpawn-=8;
}
void Doodlebug::survived(){
dayCountForSpawn++;
}
| df7aaecda2c6eaa1858f33b4958248352986fcb7 | [
"Makefile",
"C++"
]
| 25 | Makefile | clarkchentw/cs211-spring2018-proj7 | 3da80a1efa7459b05da8494b3e975d62ed00fef3 | ee52efe65dd0bc4a4ffb9295e46f7483b9149180 |
refs/heads/master | <repo_name>danmrichards/twirp-examples<file_sep>/helloworld/client/main.go
package main
import (
"context"
"fmt"
"net/http"
pb "github.com/danmrichards/twirp-examples/helloworld/rpc/helloworld"
)
func main() {
client := pb.NewHelloWorldProtobufClient("http://localhost:8080", &http.Client{})
resp, err := client.Hello(context.Background(), &pb.HelloReq{Subject: "Emma"})
if err == nil {
fmt.Println(resp.Text)
}
}
<file_sep>/haberdasher/client/main.go
package main
import (
"context"
"fmt"
"net/http"
pb "github.com/danmrichards/twirp-examples/haberdasher/rpc/haberdasher"
"github.com/twitchtv/twirp"
)
func main() {
client := pb.NewHaberdasherProtobufClient("http://localhost:8080", &http.Client{})
hat, err := client.MakeHat(context.Background(), &pb.Size{Inches: 5})
if err != nil {
if twerr, ok := err.(twirp.Error); ok {
switch twerr.Code() {
case twirp.InvalidArgument:
fmt.Println("Oh no " + twerr.Msg())
default:
fmt.Println(twerr.Error())
}
}
return
}
fmt.Printf("Here is your new %d inch %s %s", hat.Inches, hat.Color, hat.Name)
}
<file_sep>/README.md
# Twirp Examples
Examples using the [Twirp](https://github.com/twitchtv/twirp) RPC framework.
| 58a9da17e50fd4dec5a54a794bf3cf0e5c640f2a | [
"Markdown",
"Go"
]
| 3 | Go | danmrichards/twirp-examples | 7c932dc057feadd492c4dbcb778b092060fb2afc | 8810f361c4864a27ffca7a7b39f2da0605042d4f |
refs/heads/master | <repo_name>oscarphang/elm-webpack<file_sep>/README.md
# elm-webpack-hot-reload
A hot reload playground to build elm app instantly.
## Prerequisites
[Install](https://guide.elm-lang.org/install.html) Elm.
## Build
`yarn install`
## Run
`yarn run dev`
To run webpack web server with hot reload.
`yarn run deploy`
compile the script and ready to deploy.
`yarn run css-build`
compile sass into css<file_sep>/webpack.config.js
var path = require('path');
module.exports = {
mode: 'development',
entry: './js/app.js',
output: {
path: path.join(__dirname, "dist"),
filename: 'index.js',
publicPath: '/dist/'
},
resolve: {
modules: [
path.join(__dirname, "src"),
"node_modules"
],
extensions: ['.js', '.elm']
},
devServer: {
contentBase: __dirname + "/public/",
inline: true,
},
module: {
rules: [{
test: /\.html$/,
exclude: /node_modules/,
use: 'file-loader?name=[name].[ext]'
},
{
test: /\.elm$/,
exclude: [/elm-stuff/, /node_modules/],
use: [{
loader: 'elm-hot-webpack-loader'
},
{
loader: 'elm-webpack-loader',
options: process.env.WEBPACK_MODE === 'production' ? {
optimize: true
} : {
debug: true
}
}
],
}
]
},
devServer: {
inline: true,
stats: 'errors-only'
},
}; | 0e47bf562298b714182b7dd30c9a1ce854a24f83 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | oscarphang/elm-webpack | a54e767a7ad22469d5900ac25d2fbe81a322ac67 | 3885a582ea7cd60742a9ce36b7efafd4bf497309 |
refs/heads/master | <file_sep>CC=g++
CCFLAGS= -Wall -Wno-write-strings -o
FILES= slice2d.cc slice2d.h houghUtility.cc houghUtility.h grid.cc grid.h
all: $(FILES)
$(CC) $(CCFLAGS) slice $(FILES)
<file_sep>#ifndef GRID
#define GRID
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <map>
#include <set>
#include <fstream>
#include <utility>
#include <sstream>
#include <list>
#include "houghUtility.h"
using namespace std;
typedef struct{
int i;
int j;
int count;
list<pair<double, double> > values;
} cell;
class grid{
public:
//constructors
grid(char* datafile, int resolution);
cell* get_cell(double x, double y);
cell* get_cell(int i, int j);
void increase_cell_count(int i, int j);
void increase_cell_count(cell *c);
void print_grid(char *writefile);
void free();
void find_hoodless(char *writefile); //find cells without neighbours
list<cell*> find_hoodless(int min); //find cells without <= min neighbours
void grid_hough(char* writefile); // find lines using hough
list<cell*> get_matched_cells(); //get a list with all cells in grid which have counter > 0
list<cell*> get_hood(cell* c); //get a list of all neighbours of a cell
list<cell*> get_hoodcells(int min); //get cells which have >= min neighbours
void find_lines(); //try to find lines in grid
cell* rek_line(cell* startcell, int direction); //rekursion following each neighbour of a given cell in a given direction to find last cell in line
int which_hood(cell* firstcell, cell* secondcell); //returns direction from firstcell to secondcell interms of the 9 neighbours
void hookers_on_the_grid(char* writefile);
private:
cell** gridcell;
double max_x, max_y, min_x, min_y;
double cellstep_x, cellstep_y;
int resolution;
};
#endif
<file_sep>#include "houghUtility.h"
#include <cstring>
#include <sstream>
#include "grid.h"
grid::grid(char* datafile, int resolution)
{
max_x = max_y = min_x = min_y = cellstep_x = cellstep_y = 0.0;
this->resolution = resolution;
ifstream file(datafile);
if(!file)
{
cerr << "Cannot read file! File " << __FILE__ << " Line: " << __LINE__ << endl;
exit(-1);
}
double x, y;
while(file >> x >> y)
{
if(x > max_x)
max_x = x;
if(x < min_x)
min_x = x;
if(y > max_y)
max_y = y;
if(y < min_y)
min_y = y;
}
cellstep_x = (fabs(min_x) + fabs(max_x)) / resolution;
cellstep_y = (fabs(min_y) + fabs(max_y)) / resolution;
// #ifdef M_DB
cout << "\tmin_x: " << min_x << endl;
cout << "\tmin_y: " << min_y << endl;
cout << "\tmax_x: " << max_x << endl;
cout << "\tmax_y: " << max_y << endl;
cout << "\tresolution: " << resolution << endl;
cout << "\tcellstep_x: " << cellstep_x << "\tcellstep_y: "<< cellstep_y << endl;
//#endif
file.close();
file.open(datafile);
gridcell = new cell*[resolution + 1];
for(int i = 0; i <= resolution; ++i)
{
gridcell[i] = new cell[resolution + 1];
for(int j = 0; j <= resolution; ++j)
{
gridcell[i][j].i = i;
gridcell[i][j].j = j;
gridcell[i][j].count = 0;
}
}
while(file >> x >> y)
{
/*Note: catesian: 2 / 0 is 0/2 in array!
*/
gridcell[(int)((y + fabs(min_y)) / cellstep_y)][(int)((x + fabs(min_x)) / cellstep_x)].count++;
gridcell[(int)((y + fabs(min_y)) / cellstep_y)][(int)((x + fabs(min_x)) / cellstep_x)].values.push_back(make_pair(y, x));
}
}
cell* grid::get_cell(double x, double y){
//assert(cellstep_x > 0 && cellstep_y > 0);
return &gridcell[(int)((x + fabs(min_x)) / cellstep_x)][(int)((y + fabs(min_y)) / cellstep_y)];
}
cell* grid::get_cell(int i, int j){
return &gridcell[i][j];
}
void grid::increase_cell_count(int i, int j){
gridcell[i][j].count++;
}
void increase_cell_count(cell *c){
c->count++;
}
void grid::print_grid(char *writefile){
ofstream target;
target.open(writefile);
for(int i = 0; i <= resolution; ++i){
for(int j = 0; j <= resolution; ++j){
if(gridcell[i][j].count > 0)
target << j << " " << i << endl;
}
}
target.close();
}
void grid::free()
{
for(int i = 0; i <= resolution; ++i)
{
delete[] gridcell[i];
}
delete[] gridcell;
}
void grid::find_hoodless(char *writefile){
ofstream target;
target.open(writefile);
list<cell*> hoodless;
list<cell*> hoods;
list<cell*> matched;
list<cell*>::iterator it;
//get all cells which have count > 0
matched = get_matched_cells();
for(it = matched.begin(); it != matched.end(); it++){
//get neidhborhood of current cell
hoods = get_hood((*it));
//if there are not enough neighbours add cell to hoodless list
if (hoods.size() < 2) hoodless.push_back((*it));
}
for(it = hoodless.begin(); it != hoodless.end(); it++){
target << (*it)->j << " " << (*it)->i << endl;
}
target.close();
}
list<cell*> grid::find_hoodless(int min){
list<cell*> matched;
list<cell*> hoodless;
list<cell*> hoods;
list<cell*>::iterator it;
cell* c;
matched = get_matched_cells();
for(it = matched.begin(); it != matched.end(); it++){
hoods = get_hood(*it);
if(hoods.size() == min) hoodless.push_back(*it);
}
return hoodless;
}
list<cell*> grid::get_matched_cells(){
list <cell*> matched;
for(int i = 0; i <= resolution; i++){
for(int j = 0; j <= resolution; j++){
if(gridcell[i][j].count > 0) matched.push_back(&gridcell[i][j]);
}
}
return matched;
}
void
grid::grid_hough(char *writefile)
{
ofstream file(writefile);
for(int i = 0; i <= resolution; ++i)
{
for(int j = 0; j <= resolution; ++j)
{
if(gridcell[i][j].count > 0){
stringstream in;
stringstream out;
in << "sgrid_hough_" << i << '_' << j << ".txt";
out << "tgrid_hough_"<< i << '_' << j << ".txt";
ofstream source(in.str().c_str());
list<pair<double, double> >::iterator list_iter;
for(list_iter = gridcell[i][j].values.begin(); list_iter != gridcell[i][j].values.end(); ++list_iter)
{
source << list_iter->first << " " << list_iter->second << endl;
}
source.close();
hough(in.str().c_str(), out.str().c_str(), 180);
remove(in.str().c_str());
}
}
}
}
list<cell*> grid::get_hood(cell* c){
list<cell*> hood;
cell* tmp;
for(int k = -1; k <= 1; k++){
for(int l = -1; l <= 1; l++){
//check boundaries
if(c->i + k >= 0 && c->i + k <= resolution)
if(c->j + l >= 0 && c->j + l <= resolution)
{
tmp = &gridcell[c->i + k][c->j + l];
//its in da hood if not itself and count > 0
if(!(k == 0 && l == 0) && tmp->count > 0) hood.push_back(tmp);
}
}
}
return hood;
}
list<cell*> grid::get_hoodcells(int min){
list<cell*> matched;
list<cell*> hoodcells;
list<cell*> hoods;
list<cell*>::iterator it;
cell* c;
matched = get_matched_cells();
for(it = matched.begin(); it != matched.end(); it++){
hoods = get_hood(*it);
if(hoods.size() >= min) hoodcells.push_back(*it);
}
return hoodcells;
}
void grid::find_lines(){
list<cell*> hoodcells;
list<cell*> linestart;
list<cell*>::iterator it;
list<cell*>::iterator it2;
cell *neighbour = 0;
cell *last = 0;
ofstream target;
target.open("grid_lines.txt");
//points with one neighbour are possible line starting points
//linestart = find_hoodless(1);
linestart = find_hoodless(3);
for(it = linestart.begin(); it != linestart.end(); it++){
hoodcells = get_hood(*it);
for(it2 = hoodcells.begin(); it2 != hoodcells.end(); it2++){
//get the only neighbour
//neighbour = get_hood(*it).front();
neighbour = *it2;
//get last cell which follows in direction of the neighbour
last = rek_line(neighbour, which_hood(*it, neighbour));
//cout << "starting line search for " << (*it)->i << " " << (*it)->j << endl;
//cout << "found line end " << last->i << " " << last->j << endl;
//never mind why we have to switch i and j ... FOK!!
target << (*it)->j << " " << (*it)->i << endl;
target << last->j << " " << last->i << endl << endl;
}
}
target.close();
}
cell* grid::rek_line(cell* c, int direction){
list<cell*>::iterator it;
list<cell*> hood;
int count = 0;
hood = get_hood(c);
for(it = hood.begin(); it != hood.end(); it++){
if(which_hood(c, *it) == direction) {
return rek_line(*it, direction);
count++;
}
}
if (count == 0)
return c;
return NULL;
}
// return values for direction from c1 to c2
// 1 2 3
// 4 #c1# 6
// 7 8 9
int grid::which_hood(cell* c1, cell* c2){
if(c1->i - 1 == c2-> i && c1->j + 1 == c2->j) return 1;
if(c1->i == c2-> i && c1->j + 1 == c2->j) return 2;
if(c1->i + 1 == c2-> i && c1->j + 1 == c2->j) return 3;
if(c1->i - 1 == c2-> i && c1->j == c2->j) return 4;
if(c1->i == c2-> i && c1->j == c2->j) return 5;
if(c1->i + 1 == c2-> i && c1->j == c2->j) return 6;
if(c1->i - 1 == c2-> i && c1->j - 1 == c2->j) return 7;
if(c1->i == c2-> i && c1->j - 1 == c2->j) return 8;
if(c1->i + 1 == c2-> i && c1->j - 1 == c2->j) return 9;
cout << "no neighbours" << endl;
return 0;
}
void
grid::hookers_on_the_grid(char *writefile)
{
double theta;
double dist;
int x, y;
list<cell*> hoodcells;// = (1);
list<cell*>::iterator list_iter = hoodcells.begin();
// initialize our voting matrix
houghLine **votingMatrix = new houghLine*[3];
for(int i = 0; i < 3 ; ++i){
votingMatrix[i] = new houghLine[resolution*3];
for(int j = 0; j <resolution*3; ++j){
votingMatrix[i][j].set_start(0.0, 0.0);
votingMatrix[i][j].set_end(0.0, 0.0);
votingMatrix[i][j].set_parameters(0.0, 0.0);
votingMatrix[i][j].set_count(0);
}
}
// fill the voting matrix with neighbours
for(; list_iter != hoodcells.end(); ++list_iter){
x = (*list_iter)->j; // NOTE: ATTENTION: REVERSE: BACKWARDS: FOK!
y = (*list_iter)->i;
// zero angle
theta = 0.0;
dist = x * cos(theta) + y * sin(theta);
if(votingMatrix[0][(int)dist + resolution].value() >= 1){
votingMatrix[0][(int)dist + resolution].set_end(x, y);
} else {
votingMatrix[0][(int)dist + resolution].set_start(x, y);
votingMatrix[0][(int)dist + resolution].set_parameters(theta, dist);
}
votingMatrix[0][(int)dist + resolution].increase();
// angle 45 degree
theta = 45.0;
dist = x * cos(theta) + y * sin(theta);
if(votingMatrix[1][(int)dist + resolution].value() >= 1){
votingMatrix[1][(int)dist + resolution].set_end(x, y);
} else {
votingMatrix[1][(int)dist + resolution].set_start(x, y);
votingMatrix[1][(int)dist + resolution].set_parameters(theta, dist);
}
votingMatrix[1][(int)dist + resolution].increase();
// angle 90 degree
theta = 90.0;
dist = x * cos(theta) + y * sin(theta);
if(votingMatrix[2][(int)dist + resolution].value() >= 1){
votingMatrix[2][(int)dist + resolution].set_end(x, y);
} else {
votingMatrix[2][(int)dist + resolution].set_start(x, y);
votingMatrix[2][(int)dist + resolution].set_parameters(theta, dist);
}
votingMatrix[2][(int)dist + resolution].increase();
}
ofstream target(writefile);
for(int i = 0; i < 3; ++i){
for(int j = 0; j < resolution*3; ++j){
if(votingMatrix[i][j].value() > 3) // print only lines with at least 5 hits!
target << votingMatrix[i][j];
}
}
target.close();
for(int i = 0; i < 3; ++i){
delete[] votingMatrix[i];
}
delete[] votingMatrix;
}
<file_sep>#ifndef HOUGHUTILITY
#define HOUGHUTILITY
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <map>
#include <set>
#include <fstream>
#include <utility>
#include <sstream>
void hough(const char* in,const char* out, int resolution);
int hough_hash(double x, double min, int accuracy);
void hough_get_min_max(const char *in, int resolution, double &min, double &max);
double hough_unhash(int hash);
class houghPoint2D {
public:
houghPoint2D();
houghPoint2D(double start_x, double start_y, double end_x, double end_y);
houghPoint2D(double start_x, double start_y);
void set_start(double x, double y);
void set_end(double x, double y);
void set_points(double start_x, double start_y, double end_x, double end_y);
int get_count();
std::pair<double, double> get_start();
std::pair<double, double> get_end();
houghPoint2D operator++(int unused); // postfix
houghPoint2D& operator++(); // prefix
private:
double s_x, s_y, e_x, e_y;
unsigned int count;
};
class houghLine {
static const double delta_equal = 0.2;
public:
houghLine();
houghLine(double phi_in, double r_in);
houghLine(double phi_in, double r_in, double s1, double s2);
/*
* careful: < operator designed for set:
* < is only true iff lhs != rhs and lhs < rhs!
*/
friend bool operator<(const houghLine& lhs, const houghLine& rhs)
{
return ((lhs.phi - rhs.phi) < 0 && (lhs.r - rhs.r) < 0);
};
bool operator==(const houghLine& other) const;
friend std::ostream& operator<<(std::ostream& os, const houghLine &a);
double dist_to(double nx, double ny);
std::string toString();
houghLine operator++(int unused);
houghLine& operator++();
void increase() const;
void set_start(double s1, double s2);
void set_end(double e1, double e2);
void set_parameters(double phi, double r);
void set_count(int count);
int value() const;
static houghLine *find(std::set<houghLine> &houghset, houghLine &e);
private:
double phi; // angle in houghroom
double r; // distance in houghroom
double sx; // end x
double sy; // end y
mutable double ex; // end x
mutable double ey; // end y
mutable int count;
};
#endif
<file_sep>typedef struct {
double phi;
double r;
} PointPolar;
typedef struct {
double x;
double y;
} PointCartesian;
bool operator<(const PointCartesian &p1, const PointCartesian &p2)
{
return (p1.x < p2.x && p1.y < p2.y);
};
class slice2d {
public:
static void slice_3d_map(double from, double to, char *file);
static void captn_hough(char *file); // hough transformation for line extraction from point clouds
static void delta_method(char *file, double delta); // find holes in data
static void scan_sort_polar(char *readfile, char *writefile); //reading input scan, sorting data among angle and writing output into file
static void scan_sort_cart(char *readfile, char *writefile); //reading input scan, sorting data among first coords and writing output into file
static bool compare_polar_points(PointPolar &a, PointPolar &b);
static bool compare_cart_points(PointCartesian &a, PointCartesian &b);
static void find_lines(char *file);
static void find_lines_captnHough(char *file);
static double dist_polar(double phi1, double r1, double phi2, double r2);
static double dist_polar(PointPolar &p1, PointPolar &p2);
static double dist_cart(double x1, double y1, double x2, double y2);
static double dist_cart(PointCartesian &p1, PointCartesian &p2);
static void find_circuit(char *readfile, char *writefile);
};
<file_sep>#include <map>
#include <fstream>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <list>
#include <vector>
#include <utility>
#include "houghUtility.h"
#include "slice2d.h"
#include "grid.h"
using namespace std;
void
slice2d::slice_3d_map(double from, double to, char* file){
double x_val, y_val, z_val;
ifstream source;
source.open(file);
ofstream target;
target.open("2d_map_sliced.txt");
if(!target.good() || !source.good())
{
cerr<<"Line "<<__LINE__<<" File: "<<__FILE__<<". Unable to open/read file."<<'\n';
exit(-1);
}
if(source.peek() == EOF)
{
cerr<<"Line "<<__LINE__<<" File: "<<__FILE__<<". Empty File:"<< file <<'\n';
exit(-1);
}
while(source.good()){
source >> x_val >> y_val >> z_val;
if (y_val > from && y_val < to){
target << x_val << " " << z_val << '\n';
}
}
source.close();
target.close();
cout<<"Done Slicing!\n";
}
void
slice2d::delta_method(char *file, double delta)
{
double phi1, phi2, r1, r2, d;
ifstream source;
ofstream target;
source.open(file);
target.open("delta_method.txt");
if(!target.good() || !source.good())
{
cerr<<"Line "<<__LINE__<<" File: "<<__FILE__<<". Unable to open/read file."<<'\n';
exit(-1);
}
if(source.peek() == EOF)
{
cerr<<"Line "<<__LINE__<<" File: "<<__FILE__<<". Empty File:"<< file <<'\n';
exit(-1);
}
if (source.good()) source >> phi1 >> r1;
while(source.good()){
source >> phi2 >> r2;
//distance in polar coords
d = sqrt(r1*r1 + r2*r2 - 2*r1*r2*cos(abs(phi2-phi1)));
if(d > delta){
target << r1*cos(phi1) << " " << r1*sin(phi1) << " " << "\n";
target << r2*cos(phi2) << " " << r2*sin(phi2) << " " << "\n\n";
}
phi1 = phi2;
r1 = r2;
//else
//delta = (delta + abs(d1-d2)) / 2;
}
source.close();
target.close();
}
bool slice2d::compare_polar_points(PointPolar &a, PointPolar &b){
return (a.phi < b.phi);
}
void slice2d::scan_sort_polar(char *readfile, char *writefile){
double x,y;
list<PointPolar> liste;
list<PointPolar>::iterator it;
PointPolar p;
ifstream source;
ofstream target;
source.open(readfile);
target.open(writefile);
if(!target.good() || !source.good())
{
cerr<<"Line "<<__LINE__<<" File: "<<__FILE__<<". Unable to open/read file."<<'\n';
exit(-1);
}
if(source.peek() == EOF)
{
cerr<<"Line "<<__LINE__<<" File: "<<__FILE__<<". Empty File:"<< readfile <<'\n';
exit(-1);
}
while (source.good()){
source >> x >> y;
p.r = sqrt(x*x + y*y);
p.phi = atan2(y, x);
liste.insert(liste.end(), p);
}
liste.sort(compare_polar_points);
for(it = liste.begin(); it != liste.end(); it++){
target << (*it).phi << " " << (*it).r << "\n";
}
}
bool slice2d::compare_cart_points(PointCartesian &a, PointCartesian &b){
return (a.x < b.x);
}
void slice2d::scan_sort_cart(char *readfile, char *writefile){
list<PointCartesian> liste;
list<PointCartesian>::iterator it, p_old;
PointCartesian p;
ifstream source;
ofstream target;
source.open(readfile);
target.open(writefile);
if(!target.good() || !source.good())
{
cerr<<"Line "<<__LINE__<<" File: "<<__FILE__<<". Unable to open/read file."<<'\n';
exit(-1);
}
if(source.peek() == EOF)
{
cerr<<"Line "<<__LINE__<<" File: "<<__FILE__<<". Empty File:"<< readfile <<'\n';
exit(-1);
}
while (source.good()){
source >> p.x >> p.y;
liste.push_back(p);
}
liste.sort(compare_cart_points);
for(it = liste.begin(); it != liste.end(); it++){
if (it == liste.begin()){
p_old = liste.begin(); //startwert fuer p_old
target << (*it).x << " " << (*it).y << "\n";
}
else{
//doppelte Punkte nicht verwenden
//if(fabs((*it).x - (*p_old).x) > 0.001 || (fabs((*it).y - (*p_old).y) > 0.001))
target << (*it).x << " " << (*it).y << "\n";
}
p_old = it;
}
}
void slice2d::find_lines(char *file){
ifstream source;
ofstream target;
source.open(file);
target.open("2d_map_sliced_lines.txt");
vector<PointCartesian> line;
double phi, r, e1, e2, e3, tmp;
PointCartesian p;
double constr1, constr2, constr3; //constraints
e1=e2=0.2;
e3 = 30;
while (source.good()){
source >> phi >> r;
p.x = r * cos(phi);
p.y = r * sin(phi);
if(line.size() >= 3){
tmp = 0;
for(int i = 0; i < line.size() - 1; i++) tmp += dist_cart(line[i], line[i+1]);
constr1 = dist_cart(line[0], p) / (tmp + dist_cart(line[line.size() -1], p));
constr2 = dist_cart(line[line.size()-2], p) /
(dist_cart(line[line.size()-2],line[line.size()-1]) +
dist_cart(line[line.size()-1], p));
constr3 = dist_cart(line[line.size()-1],p);
//test if line ends
if(1 >= constr1 && constr1 > 1 - e1 * line.size() && 1 >= constr2 && constr2 > 1 - e2 && constr3 < e3)
line.push_back(p);
else {
//write first and last point of line to file
target << line[0].x << " " << line[0].y << "\n";
target << line[line.size()-1].x << " " << line[line.size()-1].y << "\n\n";
cout << "linie mit punkten " << line.size() << "\n";
cout << constr1 << " " << constr2 << "\n\n";
line.clear();
}
}
else{
//if (!line.empty()) cout << dist_cart(line[line.size()-1], p) << "\n";
if (line.empty() || dist_cart(line[line.size()-1], p) < 30) line.push_back(p);
else line.clear();
}
}
source.close();
target.close();
}
//function assumes polar ordered (phi) data for getting segments
void slice2d::find_circuit(char *readfile, char *writefile){
ifstream source;
ofstream target;
source.open(readfile);
target.open(writefile);
list<PointPolar> segment; //set with small segments for dist comparison
list<PointPolar> hoodless; //set with points which have no other points in neighbourhood
list<PointPolar>::iterator it, it2;
PointPolar p;
while(source){
//a) get new data in small segments
for(int i = 0; i < 10; i++){
if (source){
source >> p.phi >> p.r;
segment.push_back(p); //add element
}
}
//b) delete some farer points from begin of the set
while(segment.size() > 10){
segment.pop_front(); //delete first point
}
//c) check if there are in neighbourhood other points
for(it = segment.begin(); it != segment.end(); it++){
for(it2 = segment.begin(); it2 != segment.end(); it2++){
if(it != it2){
if(dist_polar((*it).phi, (*it).r, (*it2).phi, (*it2).r) < 10)
break;
if(&(*it2) == &segment.back()) //if after last element no neighbour is found add point to hoodless set
hoodless.push_back(*it);
}
}
}
}
for(it = hoodless.begin(); it != hoodless.end(); it++){
target << (*it).r * cos((*it).phi) << " " << (*it).r * sin((*it).phi)<< endl;
}
target.close();
source.close();
}
void slice2d::find_lines_captnHough(char *file){
ifstream source;
ofstream target, debug;
source.open(file);
target.open("2d_map_sliced_lines_hook.txt");
debug.open("mydebug.txt");
set<houghLine> votingSet;
set<houghLine>::iterator votingIterator;
houghLine* hlp;
double x, y, theta, dist;
while(source >> x >> y)
{
cout << x << " " << y << endl;
for(int i = 0; i < 360; i++)
{
theta = static_cast<double>(i) * M_PI / 180;
dist = x * cos(theta) + y * sin(theta);
houghLine tmp(theta, dist, x, y);
hlp = houghLine::find(votingSet, tmp);
if(hlp != NULL)
{
hlp->increase();
hlp->set_end(x, y);
} else
{
if(!(votingSet.insert(tmp).second))
{
cout << "FUUUUUUUUUUUUUUUUUUUUUUUUUUUCK'n";
}
}
}
}
//cout << "in: " << in << "\t out: " << out << endl;
//cout << "VotingSet.size(): " << votingSet.size() << endl;
for(votingIterator = votingSet.begin(); votingIterator != votingSet.end(); ++votingIterator)
{
//cout << "Line: " << *votingIterator<<endl;
if(votingIterator->value() > 1)
{
target << (*votingIterator) << std::endl << std::endl;
}
}
debug.close();
target.close();
source.close();
}
double slice2d::dist_cart(double x1, double y1, double x2, double y2)
{
return (sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)));
}
double slice2d::dist_cart(PointCartesian &p1, PointCartesian &p2){
return (sqrt((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y)));
}
double slice2d::dist_polar(double phi1, double r1, double phi2, double r2)
{
return (sqrt(r2*r2 + r1*r1 - 2*r1*r2*cos(phi2-phi1)));
}
double slice2d::dist_polar(PointPolar &p1, PointPolar &p2){
return (sqrt(p1.r*p1.r + p2.r*p2.r - 2*p1.r*p2.r*cos(p2.phi-p1.phi)));
}
void usage(){
cout<<"\tSlice: A Programm to cut slice 3d points clouds with a given size.\n";
cout<<"\tUsage: ./slice [arg1] .. [arg4]\n";
cout<<"\t\t [arg1] lower bound for slice, real numbered\n";
cout<<"\t\t [arg2] upper bound for slice, real numbered\n";
cout<<"\t\t [arg3] file to be sliced\n";
cout<<"\t\t [arg4] maximum dist for delta_rule method\n";
}
int main(int argc, char *argv[]){
if(argc < 4)
usage();
else{
slice2d::slice_3d_map(atof(argv[1]), atof(argv[2]), argv[3]);
//slice2d::scan_sort_cart("2d_map_sliced.txt", "2d_map_sliced_sort_cart.txt");
//slice2d::scan_sort_polar("2d_map_sliced.txt", "2d_map_sliced_sort_polar.txt");
//slice2d::find_circuit("2d_map_sliced_sort_polar.txt","hoods.txt");
grid g("2d_map_sliced.txt", 50);
//grid g("grid.test", 20);
g.print_grid("grid.txt");
//g.hookers_on_the_grid("hookers_grid.txt");
//g.free();
g.find_lines();
}
}
<file_sep>#include "houghUtility.h"
using namespace std;
houghPoint2D::houghPoint2D():
s_x(0.0), s_y(0.0), e_x(0.0), e_y(0.0), count(0)
{
}
houghPoint2D::houghPoint2D(double start_x, double start_y, double end_x, double end_y):
s_x(start_x), s_y(start_y), e_x(end_x), e_y(end_y), count(0)
{
}
houghPoint2D::houghPoint2D(double start_x, double start_y):
s_x(start_x), s_y(start_y), e_x(0.0), e_y(0.0), count(0)
{
}
void
houghPoint2D::set_start(double x, double y)
{
s_x = x;
s_y = y;
}
void
houghPoint2D::set_end(double x, double y)
{
e_x = x;
e_y = y;
}
void
houghPoint2D::set_points(double start_x, double start_y, double end_x, double end_y)
{
s_x = start_x;
s_y = start_y;
e_x = end_x;
e_y = end_y;
}
int
houghPoint2D::get_count()
{
return count;
}
std::pair<double, double> houghPoint2D::get_start()
{
return std::make_pair(s_x, s_y);
}
std::pair<double, double> houghPoint2D::get_end()
{
return std::make_pair(e_x, e_y);
}
houghPoint2D houghPoint2D::operator++(int unused)
{
houghPoint2D tmp = *this;
++count;
return tmp;
}
houghPoint2D& houghPoint2D::operator++()
{
++count;
return *this;
}
houghLine::houghLine()
{
phi = 0.0;
r = 0.0;
sx = 0.0;
sy = 0.0;
ex = 0.0;
ey = 0.0;
count = 0;
}
houghLine::houghLine(double phi_in, double r_in)
{
phi = phi_in;
r = r_in;
sx = 0.0;
sy = 0.0;
ex = 0.0;
ey = 0.0;
count = 0;
}
houghLine::houghLine(double phi_in, double r_in, double s1, double s2)
{
phi = phi_in;
r = r_in;
sx = s1;
sy = s2;
ex = 0.0;
ey = 0.0;
count = 0;
}
bool
houghLine::operator==(const houghLine& other) const
{
return (fabs(this->phi - other.phi) < delta_equal && fabs(this->r - other.r) < delta_equal);
}
std::ostream&
operator<<(std::ostream& os, const houghLine &a)
{
os << a.sx << " " << a.sy << "\n";
os << a.ex << " " << a.ey <<"\n\n";
return os;
}
std::string
houghLine::toString()
{
stringstream os;
os << sx << " " << sy << " ";
os << ex << " " << ey << "\t phi: " << phi << "\t r: " << r;
return os.str();
}
houghLine
houghLine::operator++(int unused)
{
houghLine tmp = *this;
++count;
return tmp;
}
houghLine&
houghLine::operator++()
{
++count;
return *this;
}
void
houghLine::increase() const
{
count++;
}
void
houghLine::set_start(double e1, double e2)
{
sx = e1;
sy = e2;
}
void
houghLine::set_end(double e1, double e2)
{
ex = e1;
ey = e2;
}
void
houghLine::set_parameters(double phi_in, double r_in)
{
phi = phi_in;
r = r_in;
}
double
houghLine::dist_to(double nx, double ny)
{
return sqrt(pow(sx - nx, 2) + pow(sy - ny, 2));
}
void
houghLine::set_count(int count_in)
{
count = count_in;
}
int
houghLine::value() const
{
return count;
}
houghLine*
houghLine::find(std::set<houghLine> &hset, houghLine &e)
{
std::set<houghLine>::iterator votingIterator;
for (votingIterator = hset.begin(); votingIterator != hset.end(); votingIterator++)
{
if ((*votingIterator) == e)
{
return const_cast<houghLine*>(&(*votingIterator));
}
}
return NULL;
}
int hough_hash(double x, double min, int accuracy)
{
if (x <0) return static_cast<int>(-x * accuracy - 1); //you will never understand
else return static_cast<int>((x + fabs(min)) * accuracy);
}
void hough_get_min_max(const char *in, int resolution, double &min, double &max)
{
double x, y, theta, dist;
ifstream source(in, std::ios::in);
max = 0;
min = 0;
while(source >> x >> y)
{
for(int i = 0; i < resolution; ++i)
{
theta = (float)i * M_PI / 180.0;
dist = x * cos(theta) + y * sin(theta);
if(dist > max)
{
max = dist;
}
if(dist < min)
{
min = dist;
}
}
}
}
double hough_unhash(int hash)
{
double acurracy = 1000.0;
return (hash/acurracy);
}
void hough(const char* in, const char* out, int resolution)
{
double max,min;
int accuracy = 10; // hough accuray
hough_get_min_max(in, resolution, min, max);
double x, y, theta, dist;
houghLine **votingMatrix = new houghLine*[resolution];
int hough_size = (fabs(min) + max) * accuracy;//size of the array
for(int i = 0; i < resolution; ++i)
{
votingMatrix[i] = new houghLine[hough_size];
for(int j = 0; j < hough_size; ++j)
{
votingMatrix[i][j].set_start(0.0, 0.0);
votingMatrix[i][j].set_end(0.0, 0.0);
votingMatrix[i][j].set_parameters(0.0, 0.0);
votingMatrix[i][j].set_count(-1);
}
}
ifstream source(in, std::ios::in);
ofstream target(out, std::ios::out);
while(source >> x >> y)
{
for(int i = 0; i < resolution; i=i+1)
{
theta = (float)i * M_PI / 180.0;
dist = x * cos(theta) + y * sin(theta);
if(votingMatrix[i][hough_hash(dist, min, accuracy)].value() < 0)
{
votingMatrix[i][hough_hash(dist, min, accuracy)].set_start(x,y);
votingMatrix[i][hough_hash(dist, min, accuracy)].set_parameters(theta, dist);
votingMatrix[i][hough_hash(dist, min, accuracy)].increase();
} else
{
votingMatrix[i][hough_hash(dist, min, accuracy)].set_end(x,y);
votingMatrix[i][hough_hash(dist, min, accuracy)].increase();
}
}
}
bool written = false;
for(int i = 0; i < resolution; ++i)
{
for(int j = 0; j < hough_size; ++j)
{
if(votingMatrix[i][j].value() > 2)
{
target << votingMatrix[i][j];
written = true;
}
}
delete[] votingMatrix[i];
}
delete [] votingMatrix;
if(!written)
remove(out);
}
| 4436f8b5193e1b5c49bc8822713696e7aaa561b9 | [
"Makefile",
"C++"
]
| 7 | Makefile | Fotte/Bachelor-Thesis-I | d8b4db9de7f94ef6e67596485a3f0a3165fc66f3 | 37f0820d9095d5bdce7968216038326abdce3c86 |
refs/heads/develop | <file_sep>import Backbone, { $ } from 'backbone';
import Context from '../views/context';
import BaronScroll from 'utils/baronScroll';
import Header from 'components/header';
let instance = null;
const Router = Backbone.Router.extend({
initialize() {
const mainScrollEl = BaronScroll($('[data-js-main-page-container]'));
const header = new Header();
$('[data-js-header-container]').html(header.$el);
this.context = new Context({ mainScrollEl, header });
$('[data-js-main-page-container]').html(this.context.$el);
this.context.onShow();
},
routes: {
'': 'openIndex',
documentation: 'openDocumentation',
'documentation/:id': 'openDocumentation',
'*invalidRoute': 'openIndex',
},
openIndex() {
this.context.renderIndex();
},
openDocumentation(id) {
this.context.renderDocumentation(id);
},
});
function getInstance() {
if (!instance) {
instance = new Router();
}
return instance;
}
export default getInstance();
<file_sep>import Router from 'router';
import { $ } from 'backbone';
import Epoxy from 'backbone.epoxy';
import template from './Header.jade';
import './Header.scss';
import HeaderSocial from './__social';
import GitHubStarsCount from 'components/gitHubStarsCount';
export default Epoxy.View.extend({
template,
className: 'header',
events: {
'click [data-js-link]': 'onClickLink',
'click [data-js-toggle-sideblock]': 'onClickToggleSideblock',
'click [data-js-side-content-close]': 'onClickCloseSideblock',
'click [data-js-href]': 'openSocial',
},
initialize() {
this.renderTemplate();
this.headerSocial = new HeaderSocial();
$('[data-js-social-container]', this.$el).html(this.headerSocial.$el);
this.gitHubStarsCount = new GitHubStarsCount();
$('[data-js-github-stars-container]', this.$el).html(this.gitHubStarsCount.$el);
this.gitTopHubStarsCount = new GitHubStarsCount();
$('[data-js-top-github-stars-container]', this.$el).html(this.gitTopHubStarsCount.$el);
},
onClickLink(e) {
$('body').removeClass('side-open');
const link = $(e.currentTarget).data('js-link') || '';
Router.navigate(link, { trigger: true });
},
onClickToggleSideblock() {
$('body').toggleClass('side-open');
},
onClickCloseSideblock() {
$('body').removeClass('side-open');
},
openSocial(e) {
window.open($(e.currentTarget).attr('data-js-href'));
},
activatePage(context) {
$('[data-js-link]', this.$el).removeClass('active');
$(`[data-js-link="${context}"]`, this.$el).addClass('active');
},
onDestroy() {
this.headerSocial && this.headerSocial.destroy();
this.gitHubStarsCount && this.gitHubStarsCount.destroy();
},
});
<file_sep>import { $ } from 'backbone';
import Epoxy from 'backbone.epoxy';
import template from './GitHubStarsCount.jade';
import './GitHubStarsCount.scss';
export default Epoxy.View.extend({
template,
className: 'github-stars-count',
events: {
},
initialize() {
$.ajax({
type: 'GET',
url: '//api.github.com/repos/reportportal/reportportal',
success: (data) => {
this.renderTemplate({ count: data.stargazers_count });
},
});
},
onDestroy() {
},
});
| 79dd0ea13dffbe6c8115b0bf4aed14d1503174cd | [
"JavaScript"
]
| 3 | JavaScript | ArtsiomYeliseyenka/reportportal.github.io | 10efa8412c912b860faeef4f4db398b6cf29bf7b | 52b2b8454aa1f09a2922e569ef5d82aaca44a358 |
refs/heads/master | <repo_name>Shravankumar45/socialmedia<file_sep>/config/keys-prod.js
module.exports={
MongoURI : process.env.MONGO_URI,
GoogleClientID :process.env.GOOGLE_CLIENT_ID,
GoogleClientSecret:process.env.GOOGLE_CLIENT_SECRET,
FacebookClientID:process.env.FACEBOOK_CLIENT_ID,
FacebookClientSecret:process.env.FACEBOOK_CLIENT_SECRET,
InstagramClientID:process.env.INSTAGRAM_CLIENT_ID,
InstagramClientSecret:process.env.INSTAGRAM_CLIENT_SECRET
}<file_sep>/passport/instagram-passport.js
const passport =require('passport');
const keys=require('../config/keys');
const User=require('../models/user');
const InstagramStrategy=require('passport-instagram').Strategy;
//Session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new InstagramStrategy({
clientID: keys.InstagramClientID,
clientSecret: keys.InstagramClientSecret,
callbackURL: "/auth/instagram/callback",
proxy:true
},
(accessToken, refreshToken, profile, done)=> {
console.log(profile);
User.findOne({instagram:profile.id})
.then((user) => {
if(user){
done(null,user);
}else{
const newUser ={
instagram:profile.id,
firstname:profile.displayName.substring(0,profile.displayName.indexOf(' ')),
lastname:profile.displayName.substring(profile.displayName.indexOf(' '),profile.displayName.length),
fullname:profile.displayName,
image:profile._json.data.profile_picture
}
new User(newUser).save()
.then((user) =>{
done(null,user);
})
}
}).catch((err)=>{
if(err) throw err;
})
}
));<file_sep>/app.js
// Load modules
const express = require('express');
const expressLayouts= require('express-ejs-layouts');
const path=require('path');
const mongoose = require('mongoose');
const passport = require('passport');
const session = require("express-session");
const bodyParser = require("body-parser");
const cookieParser = require('cookie-parser');
const methodOverride=require('method-override');
// Connect to MongoURI exported from external file
const keys = require('./config/keys');
const User = require('./models/user');
const Post = require('./models/post');
//Link Passports to the Server
require('./passport/google-passport');
require('./passport/facebook-passport');
require('./passport/instagram-passport');
//Link Helpers
const {
ensureAuthentication,
ensureGuest
}=require('./helpers/auth');
// initialize application
const app = express();
// Express config
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));
app.use(methodOverride('_method'));
//Passport Config
app.use(passport.initialize());
app.use(passport.session());
//Global variables for users
app.use((req,res,next)=>{
res.locals.user=req.user || null;
next();
});
//Setting up the template
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// setup static folder to serve css, javascript and images
app.use(expressLayouts);
app.use(express.static(path.join(__dirname, 'public')));
// connect to remote database
mongoose.promise=global.Promise;
mongoose.connect(keys.MongoURI, {
useNewUrlParser: true,useUnifiedTopology: true
})
.then(() => {
console.log('Connected to Remote Database....');
}).catch((err) => {
console.log(err);
});
// set environment variable for port
const port = process.env.PORT || 3000;
// Handle routes
app.get('/',ensureGuest,(req, res) => {
res.render('main');
});
app.get('/about', (req, res) => {
res.render('about');
});
// GOOGLE AUTH ROUTE
app.get('/auth/google',
passport.authenticate('google', {
scope: ['profile', 'email']
}));
app.get('/auth/google/callback',
passport.authenticate('google', {
failureRedirect: '/'
}),
(req, res) => {
// Successful authentication, redirect home.
res.redirect('/profile');
});
//Facebook Auth Route
app.get('/auth/facebook',
passport.authenticate('facebook',{
scope:['email']
}));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/' }),
(req, res)=> {
// Successful authentication, redirect home.
res.redirect('/profile');
});
//Handle Instagram Auth ROUTE
app.get('/auth/instagram',
passport.authenticate('instagram'));
app.get('/auth/instagram/callback',
passport.authenticate('instagram', { failureRedirect: '/' }),
(req, res)=> {
// Successful authentication, redirect home.
res.redirect('/profile');
});
//Profile Route
app.get('/profile',ensureAuthentication,(req, res) => {
Post.find({user: req.user._id})
.populate('user')
.sort({date:'desc'})
.then((posts)=>{
res.render('profile',{posts:posts});
});
});
//Handle Route for all Users
app.get('/users',ensureAuthentication,(req,res)=>{
User.find({})
.then((users) =>{
res.render('users',{
users:users
});
});
});
//Display one user profile
app.get('/user/:id',(req,res)=>{
User.findById({_id:req.params.id})
.then((user) =>{
res.render('user',{user:user});
});
});
//Handle email route
app.post('/addEmail',(req,res)=>{
const email =req.body.email;
User.findById({_id:req.user._id})
.then((user)=>{
user.email =email;
user.save()
.then(()=>{
res.redirect('/profile');
});
});
});
//Handle Phone post Route
app.post('/addPhone',(req,res) => {
const phone =req.body.phone;
User.findById({_id :req.user._id})
.then((user) => {
user.phone =phone;
user.save()
.then(() =>{
res.redirect('/profile');
});
});
});
//Handle Location post Route
app.post('/addLocation',(req,res) => {
const location=req.body.location;
User.findById({_id:req.user._id})
.then((user) => {
user.location=location;
user.save()
.then(()=>{
res.redirect('/profile');
});
});
});
//Handle addpost Route
app.get('/addpost',(req,res)=>{
res.render('addpost');
});
//Handle Post route
app.post('/savePost',(req,res)=>{
var allowComments;
if(req.body.allowComments){
allowComments =true;
}else{
allowComments = false;
}
const newPost={
title:req.body.title,
body:req.body.body,
status:req.body.status,
allowComments:allowComments,
user:req.user._id,
}
new Post(newPost).save()
.then(()=>{
res.redirect('/posts');
});
});
//Handle Edit post route
app.get('/editPost/:id',(req,res) => {
Post.findOne({_id:req.params.id})
.then((post)=>{
res.render('editingPost',{
post:post
});
});
});
//Handle put Route to Save edited post
app.put('/editingPost/:id',(req,res)=>{
Post.findOne({_id:req.params.id})
.then((post)=>{
var allowComments;
if(req.body.allowComments){
allowComments=true;
}else{
allowComments=false;
}
post.title=req.body.title;
post.body=req.body.body;
post.status=req.body.status;
post.allowComments=allowComments;
post.save()
.then(()=>{
res.redirect('/profile');
});
});
});
//Handle posts route
app.get('/posts',ensureAuthentication,(req,res)=>{
Post.find({status:'public'})
.populate('user')
.sort({date: 'desc'})
.then((posts)=>{
res.render('publicPosts',{
posts:posts
});
});
});
//Handle User Logout
app.get('/logout',(req,res)=>{
req.logout();
res.redirect('/');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
}); | baac6a92bb463d0a9aae480f4be5ba75703b40ed | [
"JavaScript"
]
| 3 | JavaScript | Shravankumar45/socialmedia | 6eb2894e373c268578f2a5195a541e44eb8dd7d9 | 34df64254ec6b744d522933d97f4299685648482 |
refs/heads/main | <repo_name>YGBM/GOF<file_sep>/observer_event_design/src/main/java/com/fuzs/Subject.java
package com.fuzs;
import java.util.List;
import java.util.ArrayList;
public abstract class Subject{
//maintains a list of its dependents
public List<Observer> observers = new ArrayList<>();
public void add(Observer o){
observers.add(o);
}
public void remove(Observer o){
observers.remove(o);
}
//notifies all observers automatically
public abstract void notifyObservers(String everyThings);
}<file_sep>/chain_of_responsibility_approve/src/main/java/com/fuzs/ApproveApply.java
package com.fuzs;
import lombok.Data;
@Data
public abstract class ApproveApply {
private ApproveApply next;
public abstract void handleRequest(Worker worker);
}
<file_sep>/strategy_wiki/src/main/java/com/fuzs/BillingStrategy.java
package com.fuzs;
public abstract class BillingStrategy{
}<file_sep>/state_3/src/main/java/com/fuzs/ThreadState.java
package com.fuzs;
public abstract class ThreadState {
protected String stateName;
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fuzs</groupId>
<artifactId>observer_exp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>observer_exp</name>
<url>http://maven.apache.org</url>
<modules>
<module>observer_event_design</module>
<module>observer_wiki_demo</module>
<module>observer_util_observer</module>
<module>strategy_demo01</module>
<module>strategy_wiki</module>
<module>command_demo01</module>
<module>chain_of_responsibility</module>
<module>chain_of_responsibility_wiki</module>
<module>state</module>
<module>state_1</module>
<module>state_2</module>
<module>state_3</module>
<module>mediator</module>
<module>iterator</module>
<module>visitor</module>
<module>memento</module>
<module>memento_1</module>
<module>chain_of_responsibility_approve</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<maven.complier.source>1.8</maven.complier.source>
<maven.complier.target>1.8</maven.complier.target>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>/state_1/src/main/java/com/fuzs/AbstractState.java
package com.fuzs;
public abstract class AbstractState {
protected ScoreContext hj;
protected String stateName;
protected int score;
public abstract void checkState();
public void addScore(int x){
score += x;
System.out.print("加上: "+x+"分\t 当前分数: "+score);
checkState();
System.out.println("分 \t 当前状态: "+hj.getState().stateName);
}
}
<file_sep>/chain_of_responsibility/src/main/java/com/fuzs/ConcreteHandler2.java
package com.fuzs;
public class ConcreteHandler2 extends Handler{
public void handleRequest(String request){
if(request.equals("two")){
System.out.println("具体处理者w负责处理该就请");
}else{
if(getNext() != null){
getNext().handleRequest(request);
}else{
System.out.println("没有人处理该请求");
}
}
}
}
<file_sep>/chain_of_responsibility_approve/README.md
在现实生活中,一个事件需要经过多个对象处理是很常见的场景。例如,采购审批流程、请假流程等。
公司员工请假,可批假的领导有部门负责人、副总经理、总经理等,但每个领导能批准的天数不同,
员工必须根据需要请假的天数去找不同的领导签名,也就是说员工必须记住每个领导的姓名、电话和地址等信息,这无疑增加了难度。
设计:
角色列表
Handler:approve
Concrete Handler:
有部门负责人、DeputyGeneralManager
副总经理、
总经理
参数:请假天数<file_sep>/observer_event_design/src/main/java/com/fuzs/Observer.java
package com.fuzs;
public interface Observer{
public void update(String fromSubject);
}<file_sep>/command_demo01/src/main/java/com/fuzs/App.java
package com.fuzs;
/**
* Hello world!
*
*/
public class App {
public static void main( String[] args ) {
System.out.println( "Hello World!" );
Command cmd = new ConcreteCommandA();
Invoker ir = new Invoker(cmd);
System.out.println("客户端访问调用者的call方法");
ir.call();
}
}
<file_sep>/observer_event_design/src/main/java/com/fuzs/ConcreteObserver.java
package com.fuzs;
public class ConcreteObserver implements Observer{
@Override
public void update(String fromSubject){
System.out.println("the subject will change something of this observer: "+fromSubject);
}
}<file_sep>/state/src/main/java/com/fuzs/Context.java
package com.fuzs;
public class Context {
private State state;
public Context(){
this.state = new ConcreteStateA();
}
public void setState(State state){
this.state = state;
}
public State getState(){
return state;
}
public void Handle(){
state.Handler(this);
}
}
| 7186ad88ea8f80c1d040a90fe59c6773592534e4 | [
"Markdown",
"Java",
"Maven POM"
]
| 12 | Java | YGBM/GOF | f95efd7c5b2333ad97f8122699f510d3e01b0bdd | 24ee28a8b73f296fbb8777b8c1fb8906a7ff903b |
refs/heads/master | <repo_name>haxpor/sdl2-samples<file_sep>/android-project/app/jni/src/rectangles.c
/*
* rectangles.c
* written by <NAME>
* use however you want
*
* modified
* as on Android (as tested on Huawei P9 Lite)
* if not clear screen every frame, it's flickering
* so now it will show one new rectangle for every 5 seconds,
* before it clears and repeats the cycle.
*/
#include "SDL.h"
#include <time.h>
#include "common.h"
unsigned int lastTime = 0, currentTime;
SDL_Rect drawingRect;
SDL_Color color;
void
render(SDL_Renderer *renderer)
{
/* Get current time since SDL library initialized */
currentTime = SDL_GetTicks();
/* Check if we should render randomly rectangle */
if (lastTime == 0 || currentTime > lastTime + 5000)
{
int renderW;
int renderH;
SDL_RenderGetLogicalSize(renderer, &renderW, &renderH);
/* Come up with a random rectangle */
drawingRect.w = randomInt(64, 128);
drawingRect.h = randomInt(64, 128);
drawingRect.x = randomInt(0, renderW);
drawingRect.y = randomInt(0, renderH);
/* Come up with a random color */
color.r = randomInt(50, 255);
color.g = randomInt(50, 255);
color.b = randomInt(50, 255);
/* Fill the rectangle in the color */
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 255);
SDL_RenderFillRect(renderer, &drawingRect);
lastTime = currentTime;
}
// otherwise draw the previous rect
else
{
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 255);
SDL_RenderFillRect(renderer, &drawingRect);
}
/* update screen */
SDL_RenderPresent(renderer);
}
int
main(int argc, char *argv[])
{
SDL_Window *window;
SDL_Renderer *renderer;
int done;
SDL_Event event;
int windowW;
int windowH;
/* initialize SDL */
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
fatalError("Could not initialize SDL");
}
/* seed random number generator */
srand(time(NULL));
/* create window and renderer */
window = SDL_CreateWindow(NULL, 0, 0, 320, 480, SDL_WINDOW_ALLOW_HIGHDPI);
if (window == 0) {
fatalError("Could not initialize Window");
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (!renderer) {
fatalError("Could not create renderer");
}
SDL_GetWindowSize(window, &windowW, &windowH);
SDL_RenderSetLogicalSize(renderer, windowW, windowH);
/* Enter render loop, waiting for user to quit */
done = 0;
while (!done) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
done = 1;
}
}
/* Fill screen with black */
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0xff);
SDL_RenderClear(renderer);
render(renderer);
}
/* shutdown SDL */
SDL_Quit();
return 0;
}
<file_sep>/README.md
# SDL2 Sample Code
Sample code along the way of finishing [sdl2-manpage](https://github.com/haxpor/sdl2-manpage)
* Compile and build executable with `gcc -lsdl2 <source-file.c>`
* Clean your local working directory with `make clean`
# Android
To test on android
We have two android project for version 2.0.8 and 2.0.9 (development snapshot as of 1 Oct 2018). Choose one that is suitable for your sample code.
* symlink your SDL2 source code directory to `android-project/app/jni` - do this once
* copy testing `.c` source file into `android-project/app/jni/src`
* modify `Android.mk` in `android-project/app/jni/src` to include testing source file, see comment in the file
* execute `./gradlew installDebug` to build and install the app on your Android device
To test on ios
* remove broken of included sub-project as seen in project navigation pane
* add `<your SDL source directory>/Xcode-iOS/SDL/SDL.xcodeproj` as a sub-project
* add more sdl2 sample source code into `src` directory by right click and add files in Xcode
* set "Header Search Path" in Build Settings for your target properly, it should be aligned with headers as referenced by SDL project as you recently added
* create a new target if needed to run each new sample as you added
> There is rectangles sample already added there, so you can see for example.
You can read more about how to manually come up with this iOS sample project from my blog [here](https://blog.wasin.io/2018/10/19/build-sdl2-application-on-ios.html).
# License
MIT, <NAME>
<file_sep>/allocrw.c
/*
* Sample code for SDL_AllocRW API
* Use related functions as follows to call functions of SDL_RWops*
* - SDL_RWsize
* - SDL_RWread
* - SDL_RWseek
* - SDL_RWwrite
* - SDL_RWclose
* - SDL_RWtell
*
* Implementations of SDL_RWops is up to user.
*/
#include <SDL2/SDL.h>
/* These functions should not be used except from pointers in an SDL_RWops */
static Sint64 mysizefunc(SDL_RWops *context)
{
return -1;
}
static Sint64 myseekfunc(SDL_RWops *context, Sint64 offset, int whence)
{
return SDL_SetError("Can't seek in this kind of SDL_RWops");
}
static size_t myreadfunc(SDL_RWops *context, void *ptr, size_t size, size_t maxnum)
{
SDL_memset(ptr, 0, size*maxnum);
return maxnum;
}
static size_t mywritefunc(SDL_RWops *context, const void *ptr, size_t size, size_t num)
{
return num;
}
static int myclosefunc(SDL_RWops *context)
{
if (context->type != 0xdeadbeef)
{
return SDL_SetError("Wrong kind of SDL_RWops for myclosefunc()");
}
free(context->hidden.unknown.data1);
SDL_FreeRW(context);
return 0;
}
SDL_RWops* MyCustomRWop()
{
SDL_RWops *c = SDL_AllocRW();
if (c == NULL) return NULL;
c->size = mysizefunc;
c->seek = myseekfunc;
c->read = myreadfunc;
c->write = mywritefunc;
c->close = myclosefunc;
c->type = 0xdeadbeef;
c->hidden.unknown.data1 = malloc(256);
return c;
}
void usercode()
{
// user code section
SDL_RWops *myRWops = MyCustomRWop();
// - size
SDL_Log("size: %lld", SDL_RWsize(myRWops));
// - seek
SDL_RWseek(myRWops, 0, RW_SEEK_SET);
SDL_Log("%s", SDL_GetError());
// - read
void* readBuffer = malloc(256);
size_t read = SDL_RWread(myRWops, readBuffer, 1, 256);
SDL_Log("read: %zu", read);
// - write
size_t write = SDL_RWwrite(myRWops, (const void*)readBuffer, 1, 256);
SDL_Log("write: %zu", write);
// free
free(readBuffer);
// - close
SDL_RWclose(myRWops);
}
int main(int argc, char *argv[]) {
SDL_bool done;
SDL_Window *window;
SDL_Event event; // Declare event handle
SDL_Init(SDL_INIT_VIDEO); // SDL2 initialization
window = SDL_CreateWindow( // Create a window
"Sample Code for SDL",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640,
480,
SDL_WINDOW_OPENGL
);
// Check that the window was successfully made
if (window == NULL) {
// In the event that the window could not be made...
SDL_Log("Could not create window: %s", SDL_GetError());
SDL_Quit();
return 1;
}
done = SDL_FALSE;
// execute user code inside this function
usercode();
while (!done) {
while (!done && SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT: { // In case of exit
done = SDL_TRUE;
break;
}
}
}
SDL_Delay(17);
}
SDL_DestroyWindow(window); // Close and destroy the window
SDL_Quit(); // Clean up
return 0;
}
<file_sep>/alloc_palette.c
/*
* Demonstrate how to use SDL_AllocPalette function
*/
#include <SDL2/SDL.h>
int main(int argc, char *argv[]) {
SDL_bool done;
SDL_Window *window;
SDL_Event event; // Declare event handle
SDL_Init(SDL_INIT_VIDEO); // SDL2 initialization
window = SDL_CreateWindow( // Create a window
"Sample Code for SDL",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640,
480,
SDL_WINDOW_OPENGL
);
// Check that the window was successfully made
if (window == NULL) {
// In the event that the window could not be made...
SDL_Log("Could not create window: %s", SDL_GetError());
SDL_Quit();
return 1;
}
done = SDL_FALSE;
// -- user code section
const int colors = 4;
SDL_Palette* palette = SDL_AllocPalette(colors);
SDL_Log("Palette's number of color: %d", palette->ncolors);
// print color information as in palette
SDL_Color tempColor;
// note: all colors are initialized to be in white
for (int i=0; i<colors; i++)
{
tempColor = palette->colors[i];
SDL_Log("\tcolor at index %d => R:%u, G:%u, B:%u, A:%u\n", i, tempColor.r, tempColor.g, tempColor.b, tempColor.a);
}
// modify colors
SDL_Color* colorPtr = NULL;
colorPtr = palette->colors;
// #1 black
colorPtr->r = 0; colorPtr->g = 0; colorPtr->b = 0;
// #2 red
colorPtr = palette->colors + 1;
colorPtr->r = 255; colorPtr->g = 0; colorPtr->b = 0;
// #3 green
colorPtr = palette->colors + 2;
colorPtr->r = 0; colorPtr->g = 255; colorPtr->b = 0;
// #4 blue
colorPtr = palette->colors + 3;
colorPtr->r = 0; colorPtr->g = 0; colorPtr->b = 255;
// print all color information again
SDL_Log("Colors after modification");
for (int i=0; i<colors; i++)
{
tempColor = palette->colors[i];
SDL_Log("\tcolor at index %d => R:%u, G:%u, B:%u, A:%u\n", i, tempColor.r, tempColor.g, tempColor.b, tempColor.a);
}
// free palette created with SDL_AllocPalette()
SDL_FreePalette(palette);
// -- end of user code section
while (!done) {
while (!done && SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT: { // In case of exit
done = SDL_TRUE;
break;
}
}
}
SDL_Delay(17);
}
SDL_DestroyWindow(window); // Close and destroy the window
SDL_Quit(); // Clean up
return 0;
}
<file_sep>/android_getactivity.c
/*
* Sample for JNI calling.
* Involve using the following functions
* - SDL_AndroidGetJNIEnv()
* - SDL_AndroidGetActivity()
*/
#include "SDL.h"
#include <jni.h>
void callJavaTestMethod()
{
// retrieve the JNI environment
JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv();
// retrieve the Java instance of the SDLActivity
jobject activity = (jobject)SDL_AndroidGetActivity();
// find the Java class of the activity. It should be SDLActivity or a subclass of it.
jclass clazz = (*env)->GetObjectClass(env, activity);
// find the identifier of the method to call
// testMethod() will print "Print from testMethod() from Java code" in console
jmethodID method_id = (*env)->GetMethodID(env, clazz, "testMethod", "()V");
// effectively call the Java method
(*env)->CallVoidMethod(env, activity, method_id);
// clean up the local references
(*env)->DeleteLocalRef(env, activity);
(*env)->DeleteLocalRef(env, clazz);
}
int main(int argc, char *argv[]) {
SDL_bool done;
SDL_Window *window;
SDL_Event event; // Declare event handle
SDL_Init(SDL_INIT_VIDEO); // SDL2 initialization
window = SDL_CreateWindow( // Create a window
"Sample Code for SDL",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640,
480,
SDL_WINDOW_OPENGL
);
// Check that the window was successfully made
if (window == NULL) {
// In the event that the window could not be made...
SDL_Log("Could not create window: %s", SDL_GetError());
SDL_Quit();
return 1;
}
done = SDL_FALSE;
// user-defined code
callJavaTestMethod();
while (!done) {
while (!done && SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT: { // In case of exit
done = SDL_TRUE;
break;
}
}
}
SDL_Delay(17);
}
SDL_DestroyWindow(window); // Close and destroy the window
SDL_Quit(); // Clean up
return 0;
}
<file_sep>/template.c
/*
* Template code
*/
#include <SDL2/SDL.h>
int main(int argc, char *argv[]) {
SDL_bool done;
SDL_Window *window;
SDL_Event event; // Declare event handle
SDL_Init(SDL_INIT_VIDEO); // SDL2 initialization
window = SDL_CreateWindow( // Create a window
"Sample Code for SDL",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640,
480,
SDL_WINDOW_OPENGL
);
// Check that the window was successfully made
if (window == NULL) {
// In the event that the window could not be made...
SDL_Log("Could not create window: %s", SDL_GetError());
SDL_Quit();
return 1;
}
done = SDL_FALSE;
// user-defined code here...
while (!done) {
while (!done && SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT: { // In case of exit
done = SDL_TRUE;
break;
}
}
}
SDL_Delay(17);
}
SDL_DestroyWindow(window); // Close and destroy the window
SDL_Quit(); // Clean up
return 0;
}
<file_sep>/Makefile
# Makefile to build samples
#
# template.c is a testing template source code that other samples can base upon.
srcdir = .
CC = clang
EXE = .out
CFLAGS = -g
LIBS = -lsdl2
TARGETS = \
alloc_palette$(EXE) \
allocrw$(EXE) \
timer$(EXE)
all: $(TARGETS)
alloc_palette$(EXE): $(srcdir)/alloc_palette.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
allocrw$(EXE): $(srcdir)/allocrw.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
timer$(EXE): $(srcdir)/timer.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
clean:
rm -rf $(TARGETS) *.dSYM
<file_sep>/timer.c
/*
* Sample code showing how to use SDL_AddTimer which will execute
* code in another non-main thread, along with showing how to send
* parameter to such callback function.
*/
#include <SDL2/SDL.h>
struct Param
{
Uint64 value;
};
struct Param myParam;
Uint32 myTimerCallback(Uint32 interval, void *param)
{
// get information from param
if (param != NULL) {
struct Param* castedParam = ((struct Param*)param);
SDL_Log("hey, get %llu", castedParam->value);
}
else {
SDL_Log("hey, with no param");
}
SDL_Event event;
SDL_UserEvent userevent;
userevent.type = SDL_USEREVENT;
userevent.code = 0;
userevent.data1 = NULL;
userevent.data2 = NULL;
event.type = SDL_USEREVENT;
event.user = userevent;
// push user-defined event to trigger another
SDL_PushEvent(&event);
return interval;
}
void userdefinedCode()
{
// set value of parameter
myParam.value = 1;
Uint32 delay = (2000 / 10) * 10;
SDL_TimerID myTimer = SDL_AddTimer(delay, myTimerCallback, (void*)&myParam);
}
int main(int argc, char *argv[]) {
SDL_bool done;
SDL_Window *window;
SDL_Event event; // Declare event handle
SDL_Init(SDL_INIT_VIDEO); // SDL2 initialization
window = SDL_CreateWindow( // Create a window
"Genearl test for SDL2",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640,
480,
SDL_WINDOW_OPENGL
);
// Check that the window was successfully made
if (window == NULL) {
// In the event that the window could not be made...
SDL_Log("Could not create window: %s", SDL_GetError());
SDL_Quit();
return 1;
}
done = SDL_FALSE;
// add user defined code for this sample app here
userdefinedCode();
while (!done) {
while (!done && SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT: { // In case of exit
done = SDL_TRUE;
break;
}
}
}
SDL_Delay(16);
}
SDL_DestroyWindow(window); // Close and destroy the window
SDL_Quit(); // Clean up
return 0;
}
| fefd1a51e24cf74f5aa23361aae769ee3b6177de | [
"Markdown",
"C",
"Makefile"
]
| 8 | C | haxpor/sdl2-samples | 5b6a211137e45d60f4eb76ae20a432831eb1a329 | d6d3b5540ad0ec13b2d59fe094dfb868cb70e75a |
refs/heads/master | <repo_name>web-servers/noe-core<file_sep>/CONTRIBUTING.md
# Contributing to Noe Core
Thank you for considering contribution to Noe Core. As a potential contributor, your changes and ideas are always welcome. Please do not ever hesitate to ask a question or send a Pull Request.
## How Can I Contribute?
### Reporting Bugs
If you come across what seems to be a bug, please use the Github [issue tracker](https://github.com/web-servers/noe-core/issues) and file an issue. An issue can also be used for discussions.
### Contributing Documentation
Documentation is crucial for success of any project. If you feel like there is lack of documentation in some area, feel free to [file an issue](https://github.com/web-servers/noe-core/issues). If you want to contribute documentation, feel free to open a PR with your changes. Your contribution may or may not be changed with stylistic and grammatical corrections; do not expect to see your changes ad verbum in the code.
### Contributing Code
To limit wasted effort and time, before contributing code, please open up an issue where you describe your desired change in Noe Core. After a debate and review of the idea, follow the Contribution Workflow section to get your patch accepted.
## Contribution Workflow
Noe Core uses the standard Github's [Pull Request](https://help.github.com/articles/about-pull-requests/) workflow. In addition, we expect you to:
1. Adhere to the review provided within the pull request. If you disagree, we are always open to a debate.
1. Adhere to the Apache software Foundation's [Code of Conduct](http://www.apache.org/foundation/policies/conduct.html).
1. Provide integration and unit test where applicable.
1. Provide full documentation for your changes where applicable.
1. Provide reasonable commit messages.
1. Adhere to our codestyle.
We use the same coding style as [Wildfly](https://github.com/wildfly/wildfly-core/tree/master/ide-configs) with the following exceptions:
- Indentation size is 2 spaces.
- Contined indentation is 4 spaces.
- Maximum line length is 160 chars.
## Missing Something?
Are you missing something? Is something confusing? Is something unreasonable? Please let us know!
<file_sep>/core/src/main/groovy/noe/common/newcmd/CmdBuilderInterface.java
package noe.common.newcmd;
/**
* Interface of builders creating commands.
* This is used by executor service to get built {@link CmdCommand}
* that will be executed in the next step.
*/
public interface CmdBuilderInterface {
/**
* Builder method where {@link CmdCommand} is put as output of the builder "process".
* This method needs to be implemented by any builder as it's used to get command
*
* @return built instance of {@link CmdCommand}.
*/
CmdCommand build();
}
<file_sep>/testsuite/src/test/resources/eap7-multiple-jbcs-httpd-test.properties
eap.version=7.0.0
ews.version=5.7.0
context=eap6
apache.core.version=2.4.51
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.jboss.qa.noe</groupId>
<artifactId>noe-core-parent</artifactId>
<version>0.17.14-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Noe core: Parent</name>
<description>
Manage JBoss Web Server (Tomcat), JBoss Core Services (HTTPD), JBoss EAP (Wildfly), and
much more.
</description>
<url>https://repository.jboss.org/nexus/content/repositories/public/</url>
<modules>
<module>core</module>
</modules>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>plodge</id>
<name><NAME></name>
<organization>Red Hat</organization>
</developer>
<developer>
<id>akrajcik</id>
<name><NAME></name>
<organization>Red Hat</organization>
</developer>
<developer>
<id>sgala</id>
<name><NAME></name>
<organization>Red Hat</organization>
</developer>
</developers>
<scm>
<connection>scm:git:git@${env.GIT_URL}:${env.GIT_USER}/noe-core.git</connection>
<developerConnection>scm:git:git@${env.GIT_URL}:${env.GIT_USER}/noe-core.git</developerConnection>
<url>https://${env.GIT_URL}/${env.GIT_USER}/noe-core</url>
<tag>v0.17.13</tag>
</scm>
<distributionManagement>
<repository>
<id>jboss-public-repository</id>
<name>Public JBoss release repository</name>
<url>https://repository.jboss.org/nexus/service/local/staging/deploy/maven2</url>
</repository>
</distributionManagement>
<repositories>
<repository>
<id>jboss-qa-releases</id>
<name>JBoss QA release repository</name>
<url>https://${env.NEXUS_HOST}/nexus/content/repositories/jboss-qa-releases/</url>
</repository>
<repository>
<id>jboss-qa-snapshots</id>
<name>JBoss QA snapshot repository</name>
<url>https://${env.NEXUS_HOST}/nexus/content/repositories/jboss-qa-snapshots/</url>
</repository>
<repository>
<id>jboss-public-repository-group</id>
<name>JBoss Public Maven Repository Group</name>
<url>https://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>rh-ga-repository</id>
<name>Red Hat GA repository</name>
<url>https://maven.repository.redhat.com/ga/</url>
</repository>
</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<version.java>1.6</version.java>
<version.checkstyle-plugin>3.1.1</version.checkstyle-plugin>
<version.findbugs-plugin>3.0.5</version.findbugs-plugin>
<version.codenarc-plugin>0.22-1</version.codenarc-plugin>
<version.source-plugin>3.2.1</version.source-plugin>
<version.javadoc-plugin>2.10.4</version.javadoc-plugin>
<version.release-plugin>3.0.0-M1</version.release-plugin>
<version.groovy-eclipse-compiler>3.6.0-03</version.groovy-eclipse-compiler>
<version.guava>31.0-jre</version.guava>
<version.jgit>5.8.0.202006091008-r</version.jgit>
<version.java.jna>5.6.0</version.java.jna>
<net.sourceforge.htmlunit.version>2.38.0</net.sourceforge.htmlunit.version>
<!-- https://github.com/Karm/okhttp/tree/add_cipher_suites -->
<com.squareup.okhttp3.okhttp.version>4.8.0</com.squareup.okhttp3.okhttp.version>
<org.apache.ant.version>1.10.9</org.apache.ant.version>
<version.org.apache.maven.plugins.maven-surefire-plugin>2.22.0
</version.org.apache.maven.plugins.maven-surefire-plugin>
<version.org.apache.maven.plugins.maven-failsafe-plugin>2.22.0
</version.org.apache.maven.plugins.maven-failsafe-plugin>
<version.org.apache.maven.plugins.maven-deploy-plugin>2.8.2
</version.org.apache.maven.plugins.maven-deploy-plugin>
<junit.version>4.13.1</junit.version>
<org.codehaus.groovy.all.version>2.4.21</org.codehaus.groovy.all.version>
<maven.compiler.plugin.version>3.8.1</maven.compiler.plugin.version>
<org.codehaus.groovy.compiler.version>2.9.2-01</org.codehaus.groovy.compiler.version>
<org.codehaus.groovy.batch.compiler.version>2.4.3-01</org.codehaus.groovy.batch.compiler.version>
<org.codehaus.mojo.build.helper.maven.plugin.version>3.2.0</org.codehaus.mojo.build.helper.maven.plugin.version>
<version.slfj-api>1.7.30</version.slfj-api>
<version.logback>1.2.3</version.logback>
<version.powermock>2.0.7</version.powermock>
<version.org.wildfly.extras.creaper>1.6.1</version.org.wildfly.extras.creaper>
<org.wildfly.core.version>12.0.3.Final</org.wildfly.core.version>
<org.jboss.as.creaper.dependencies.version>7.5.23.Final-redhat-00002</org.jboss.as.creaper.dependencies.version>
<commons-collections4.version>4.4</commons-collections4.version>
<commons-lang3.version>3.4</commons-lang3.version>
<commons-io.version>2.4</commons-io.version>
<xml-apis.version>1.4.01</xml-apis.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.qa.noe</groupId>
<artifactId>noe-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.qa.noe</groupId>
<artifactId>noe-core-testsuite</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>${version.java.jna}</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>${org.apache.ant.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${org.codehaus.groovy.all.version}</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>${net.sourceforge.htmlunit.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${version.guava}</version>
</dependency>
<!-- logging dependencies -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${version.slfj-api}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${version.logback}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${com.squareup.okhttp3.okhttp.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp-urlconnection</artifactId>
<version>${com.squareup.okhttp3.okhttp.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>${version.jgit}</version>
</dependency>
<!-- JUnit test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${version.powermock}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>${version.powermock}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${version.powermock}</version>
<scope>test</scope>
</dependency>
<!-- Creaper -->
<dependency>
<groupId>org.wildfly.extras.creaper</groupId>
<artifactId>creaper-core</artifactId>
<version>${version.org.wildfly.extras.creaper}</version>
</dependency>
<dependency>
<groupId>org.wildfly.extras.creaper</groupId>
<artifactId>creaper-commands</artifactId>
<version>${version.org.wildfly.extras.creaper}</version>
</dependency>
<!-- CLI dependency -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>${xml-apis.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin.version}</version>
<configuration>
<source>${version.java}</source>
<target>${version.java}</target>
<compilerId>groovy-eclipse-compiler</compilerId>
</configuration>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-compiler</artifactId>
<version>${org.codehaus.groovy.compiler.version}</version>
<exclusions>
<exclusion>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-batch</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--> Added due to groovy-eclipse-compiler with IBM JDK BUG http://jira.codehaus.org/browse/GRECLIPSE-1199 -->
<dependency>
<groupId>org.eclipse.core</groupId>
<artifactId>org.eclipse.core.contenttype</artifactId>
<version>3.4.100.v20100505-1235</version>
<exclusions>
<exclusion>
<artifactId>org.eclipse.equinox.preferences</artifactId>
<groupId>org.eclipse.equinox</groupId>
</exclusion>
<exclusion>
<artifactId>org.eclipse.equinox.registry</artifactId>
<groupId>org.eclipse.equinox</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-batch</artifactId>
<version>${org.codehaus.groovy.batch.compiler.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>${org.codehaus.mojo.build.helper.maven.plugin.version}</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/groovy</source>
</sources>
</configuration>
</execution>
<execution>
<id>add-test-source</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/test/groovy</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>${version.source-plugin}</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${version.javadoc-plugin}</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>${version.release-plugin}</version>
<configuration>
<autoVersionSubmodules>true</autoVersionSubmodules>
<tagNameFormat>v@{project.version}</tagNameFormat>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${version.org.apache.maven.plugins.maven-surefire-plugin}</version>
<configuration>
<systemPropertyVariables combine.children="append">
<JDBCLoader.URL>http://exampleurl.com</JDBCLoader.URL>
</systemPropertyVariables>
</configuration>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>${version.org.apache.maven.plugins.maven-surefire-plugin}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${version.org.apache.maven.plugins.maven-failsafe-plugin}</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>${version.org.apache.maven.plugins.maven-surefire-plugin}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>${version.org.apache.maven.plugins.maven-deploy-plugin}</version>
</plugin>
<plugin>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-compiler</artifactId>
<version>${version.groovy-eclipse-compiler}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>codenarc-maven-plugin</artifactId>
<version>${version.codenarc-plugin}</version>
</plugin>
</plugins>
</reporting>
<profiles>
<!-- profile for CI takes much longer to run -->
<profile>
<id>complete</id>
<modules>
<module>testsuite</module>
</modules>
</profile>
<profile>
<id>release</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>jdk8</id>
<activation>
<jdk>[1.8,)</jdk>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>jdk7_eap6-as7</id>
<activation>
<jdk>[1.6,1.7]</jdk>
</activation>
<dependencies>
<dependency>
<groupId>org.jboss.as</groupId>
<artifactId>jboss-as-controller-client</artifactId>
<scope>provided</scope>
<version>${org.jboss.as.creaper.dependencies.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.as</groupId>
<artifactId>jboss-as-cli</artifactId>
<scope>provided</scope>
<version>${org.jboss.as.creaper.dependencies.version}</version>
</dependency>
</dependencies>
</profile>
<profile>
<id>jdk8_eap7-wildfly12</id>
<activation>
<jdk>[1.8,)</jdk>
</activation>
<dependencies>
<dependency>
<groupId>org.wildfly.core</groupId>
<artifactId>wildfly-controller-client</artifactId>
<scope>provided</scope>
<version>${org.wildfly.core.version}</version>
</dependency>
<dependency>
<groupId>org.wildfly.core</groupId>
<artifactId>wildfly-cli</artifactId>
<scope>provided</scope>
<version>${org.wildfly.core.version}</version>
</dependency>
</dependencies>
</profile>
</profiles>
</project>
<file_sep>/core/src/main/resources/java/JavaVersion.java
class JavaVersion {
public static void main(String[] args) {
switch (args[0].toLowerCase()) {
case "-version":
System.out.print(System.getProperty("java.version"));
break;
case "-vendor":
System.out.print(System.getProperty("java.vendor"));
break;
case "-vmname":
System.out.print(System.getProperty("java.vm.name"));
break;
case "-vminfo":
System.out.print(System.getProperty("java.vm.info"));
break;
default:
System.out.print("JavaVersion -version|-vendor|-vmname|-vminfo");
}
}
}
<file_sep>/testsuite/src/test/resources/ews-rhel7-test.properties
ews.version=3.1.0
context=ews
JBPAPP9445_WORKAROUND=true
apache.core.version=2.4.51
tomcat.major.version=8
<file_sep>/core/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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jboss.qa.noe</groupId>
<artifactId>noe-core-parent</artifactId>
<version>0.17.14-SNAPSHOT</version>
</parent>
<artifactId>noe-core</artifactId>
<name>Noe core</name>
<properties>
<!--byteman-->
<version.byteman>4.0.19</version.byteman>
</properties>
<dependencies>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
</dependency>
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<!-- logging dependencies -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp-urlconnection</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
</dependency>
<!-- JUnit test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
</dependency>
<!-- Creaper -->
<dependency>
<groupId>org.wildfly.extras.creaper</groupId>
<artifactId>creaper-core</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.extras.creaper</groupId>
<artifactId>creaper-commands</artifactId>
</dependency>
<!-- CLI dependency -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>copy</id>
<phase>compile</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.jboss.byteman</groupId>
<artifactId>byteman</artifactId>
<version>${version.byteman}</version>
<type>jar</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.outputDirectory}/noe/byteman</outputDirectory>
<destFileName>byteman.jar</destFileName>
</artifactItem>
</artifactItems>
<outputDirectory>${project.build.directory}/wars</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>true</overWriteSnapshots>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>codenarc-maven-plugin</artifactId>
<version>${version.codenarc-plugin}</version>
</plugin>
</plugins>
</reporting>
</project>
<file_sep>/testsuite/src/test/resources/tomcat8-common-test.properties
ews.version=3.1.0
context=ews
JBPAPP9445_WORKAROUND=true
tomcat.major.version=8
<file_sep>/core/src/main/groovy/noe/common/newcmd/PsCmdData.java
package noe.common.newcmd;
import noe.common.utils.Platform;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* Class that contains all data needs to construct the ps command for all supported platforms.
* This means that you find here formatting option, filtering options etc.
*/
@SuppressWarnings("serial")
public class PsCmdData {
private static final Platform platform = new Platform();
/**
* If windows is under use then it's possible to specify what
* command should be used for showing ps info.
*/
public enum WindowsPsType {
WMIC,
WMIC_PERF,
TASKLIST
}
/**
* This specifies information that you can get from data class
* for specific platform.
*/
public enum PsArg {
BASE_COMMAND, // base command (ps or wmic or tasklist)
BASE_COMMAND_ARGS, // wmic needs arguments
BC_ARGS_AFTER_FILTER, // wmic needs to put args after filter
ALL_PROC, // ps -A means all and does not consider any filter (-u, -p)
// if filter is used then -A can't be
FORMAT_SWITCH, // what if format option for listing just some columns
FILTER_USER, // show just processes owned by one user
FILTER_PROCESS_ID // show processes with particular process id
}
// TODO: "tasklist /FO \"CSV\" /FI \"Username eq ${uids.join(', ')}\"" and "ps -f -U ${uids.join(', ')}"
// Maps of PS commands on particular platforms. If there is null as value of some of the
// argument then the command does not support such argument
// What to think about:
// no header param: some of linuxes support --no-header, tasklist has /nh, wmic does not support at all
private static final Map<PsArg, String[]> LINUX_PS = new HashMap<PsArg, String[]>() {{
put(PsArg.BASE_COMMAND, new String[]{"ps"});
put(PsArg.BASE_COMMAND_ARGS, new String[]{""});
put(PsArg.BC_ARGS_AFTER_FILTER, new String[]{""});
put(PsArg.ALL_PROC, new String[]{"-A"}); // if -A then all proc shown but filter (-u,-p) is not used
put(PsArg.FORMAT_SWITCH, new String[]{"-o"});
put(PsArg.FILTER_USER, new String[]{"-u %1$s -U %1$s"});
put(PsArg.FILTER_PROCESS_ID, new String[]{"-p"});
}};
private static final Map<PsArg, String[]> WINDOWS_WMIC = new HashMap<PsArg, String[]>() {{
put(PsArg.BASE_COMMAND, new String[]{"wmic"});
put(PsArg.BASE_COMMAND_ARGS, new String[]{"process"});
put(PsArg.BC_ARGS_AFTER_FILTER, new String[]{"get"});
put(PsArg.ALL_PROC, new String[]{}); // add nothing and all procs are shown
put(PsArg.FORMAT_SWITCH, new String[]{});
put(PsArg.FILTER_USER, new String[]{}); // NOT possible to filter by user with wmic
put(PsArg.FILTER_PROCESS_ID, new String[]{"ProcessId=%s"}); // 'where' not defined
}};
private static final Map<PsArg, String[]> WINDOWS_WMIC_PERF = new HashMap<PsArg, String[]>(WINDOWS_WMIC) {{
put(PsArg.BASE_COMMAND_ARGS, new String[]{"path", "Win32_PerfFormattedData_PerfProc_Process"});
put(PsArg.FILTER_PROCESS_ID, new String[]{"IDProcess=%s"}); // 'where' not defined
}};
private static final Map<PsArg, String[]> WINDOWS_TASKLIST = new HashMap<PsArg, String[]>() {{
put(PsArg.BASE_COMMAND, new String[]{"tasklist"});
put(PsArg.BASE_COMMAND_ARGS, new String[]{"/v"});
put(PsArg.BC_ARGS_AFTER_FILTER, new String[]{""});
put(PsArg.ALL_PROC, new String[]{}); // add nothing and all procs are shown
put(PsArg.FORMAT_SWITCH, new String[]{}); // NOT possible to format output of tasklist command
put(PsArg.FILTER_USER, new String[]{"/FI \"USERNAME eq %s\""});
put(PsArg.FILTER_PROCESS_ID, new String[]{"/FI \"PID eq %s\""});
}};
private static final Map<PsArg, String[]> SOLARIS_PS = new HashMap<PsArg, String[]>(LINUX_PS) {{
}};
private static final Map<PsArg, String[]> HPUX_PS = new HashMap<PsArg, String[]>(LINUX_PS) {{
put(PsArg.FILTER_USER, new String[]{"-u %s"});
}};
private static final Map<PsArg, String[]> AIX_PS = new HashMap<PsArg, String[]>(LINUX_PS) {{
}};
private static final Map<PsArg, String[]> MAC_PS = new HashMap<PsArg, String[]>(LINUX_PS) {{
}};
// Maps of format strings that could be used to define which column to show in listing
// Note:
// - when empty string value is defined then format option is not supported for the command on platform
// - WINDOWS_TASKLIST does not support formatting of output
private static final Map<PsCmdFormat, String[]> FORMAT = new HashMap<PsCmdFormat, String[]>() {{
// OS command matrix: LINUX[0] SOLARIS[1] HPUX[2] AIX[3] MAC[4] WMIC[5] WMIC_PERF[6] EMPTY[7]
put(PsCmdFormat.COMMAND, new String[]{"comm", "comm", "comm", "%c", "comm", "Name", "Name", ""});
put(PsCmdFormat.COMMAND_ARGS, new String[]{"args", "args", "args", "%c %a", "args", "CommandLine", "", ""});
put(PsCmdFormat.PROCESS_ID, new String[]{"pid", "pid", "pid", "%p", "pid", "ProcessId", "IDProcess", ""});
put(PsCmdFormat.PARENT_PROCESS_ID, new String[]{"ppid", "ppid", "ppid", "%P", "ppid", "ParentProcessId", "", ""});
put(PsCmdFormat.PRIORITY, new String[]{"pri", "pri", "pri", "%n", "pri", "Priority", "PriorityBase", ""});
put(PsCmdFormat.TIME, new String[]{"time", "time", "time", "%x", "time", "UserModeTime", "", ""});
put(PsCmdFormat.TTY, new String[]{"tty", "tty", "tty", "%y", "tty", "SessionId", "", ""});
put(PsCmdFormat.VIRT_MEM, new String[]{"vsz", "vsz", "vsz", "%z", "vsz", "VirtualSize", "VirtualBytes", ""});
put(PsCmdFormat.CPU, new String[]{"pcpu", "pcpu", "pcpu", "%C", "pcpu", "", "PercentProcessorTime", ""});
put(PsCmdFormat.ELAPSED_TIME, new String[]{"etime", "etime", "etime", "%t", "etime", "", "ElapsedTime", ""});
put(PsCmdFormat.USER, new String[]{"user", "user", "user", "%U", "user", "", "",/*tasklist needed*/ ""});
// memory percentage is trouble to get on aix and windows, leaving out for now
// put(PsCmdFormat.MEM, new String[]{"pmem", "pmem", "", "", "pmem", "", "", ""});
}};
/**
* Returning map of arguments for ps command based on platform.
*
* @param winPsType when we are on windows (only at such case) what ps command
* will be used
* @return map of ps command arguments
*/
static Map<PsArg, String[]> getPsArgs(final WindowsPsType winPsType) {
if (platform.isLinux()) {
return LINUX_PS;
} else if (platform.isHP()) {
return HPUX_PS;
} else if (platform.isAix()) {
return AIX_PS;
} else if (platform.isMac()) {
return MAC_PS;
} else if (platform.isSolaris()) {
return SOLARIS_PS;
} else if (platform.isWindows()) {
switch (winPsType) {
case TASKLIST:
return WINDOWS_TASKLIST;
case WMIC:
return WINDOWS_WMIC;
case WMIC_PERF:
return WINDOWS_WMIC_PERF;
default:
throw new IllegalArgumentException("The Ps format builder does not support given windows PS type: " + winPsType);
}
} else {
throw new IllegalArgumentException("The Ps command builder does not support os type: " + platform.getOsName());
}
}
/**
* Return environment variables to be used for the ps command based on platform.
*
* @return map of environment variables
*/
static Map<String, String> getPsEnvVars() {
if (platform.isHP()) {
Map<String, String> result = new HashMap<String, String>();
result.put("UNIX95", "1");
return result;
} else {
return new HashMap<String, String>();
}
}
/**
* Returning formating options by platform.
* In case of running on windows returning formating options for wmic command.
*
* @return map of format option and appropriate argument which will go to command line
*/
public static Map<PsCmdFormat, String> getFormat() {
return getFormat(WindowsPsType.WMIC);
}
static Map<PsCmdFormat, String> getFormat(final WindowsPsType winPsType) {
if (platform.isLinux()) {
return getFormatAtIndex(0);
} else if (platform.isSolaris()) {
return getFormatAtIndex(1);
} else if (platform.isHP()) {
return getFormatAtIndex(2);
} else if (platform.isAix()) {
return getFormatAtIndex(3);
} else if (platform.isMac()) {
return getFormatAtIndex(4);
} else if (platform.isWindows()) {
switch (winPsType) {
case TASKLIST:
// all format options are empty for tasklist
return getFormatAtIndex(7);
case WMIC:
return getFormatAtIndex(5);
case WMIC_PERF:
return getFormatAtIndex(6);
default:
throw new IllegalArgumentException("The Ps format builder does not support given windows PS type: " + winPsType);
}
} else {
throw new IllegalArgumentException("The Ps format builder does not support os type: " + platform.getOsName());
}
}
private static Map<PsCmdFormat, String> getFormatAtIndex(final int index) {
Map<PsCmdFormat, String> res = new HashMap<PsCmdFormat, String>();
for (Entry<PsCmdFormat, String[]> entry : FORMAT.entrySet()) {
res.put(entry.getKey(), entry.getValue()[index]);
}
return res;
}
}
<file_sep>/testsuite/src/test/resources/core-test.properties
apache.core.version=2.4.51
ews.version=5.7.0
<file_sep>/testsuite/src/test/resources/ews-test.properties
ews.version=5.7.0
context=ews
JBPAPP9445_WORKAROUND=true
apache.core.version=2.4.51
tomcat.major.version=9
<file_sep>/testsuite/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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jboss.qa.noe</groupId>
<artifactId>noe-core-parent</artifactId>
<version>0.17.14-SNAPSHOT</version>
</parent>
<artifactId>noe-core-testsuite</artifactId>
<name>Noe core: Testsuite</name>
<dependencies>
<dependency>
<groupId>org.jboss.qa.noe</groupId>
<artifactId>noe-core</artifactId>
</dependency>
<!--JUnit dependencies-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${version.org.apache.maven.plugins.maven-failsafe-plugin}</version>
<configuration>
<systemProperties>
<logging.level>6</logging.level>
<project.root.path>.</project.root.path>
<host>127.0.0.1</host>
</systemProperties>
<reuseForks>false</reuseForks>
<trimStackTrace>false</trimStackTrace>
<runOrder>reversealphabetical</runOrder>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-compiler</artifactId>
</plugin>
</plugins>
</build>
</project>
<file_sep>/.gitleaks.toml
[allowlist]
description = "Allowlist"
paths = [
'''core/src/main/resources/ssl/self_signed''',
'''core/src/main/resources/ssl/self_signed_fips'''
]
<file_sep>/core/src/main/groovy/noe/common/newcmd/PsCmdFormat.java
package noe.common.newcmd;
/**
* This represents all the columns that portable ps utility could produce.
*
* The portable term means that not every information is easily accessible on all supported
* platforms and those that are not accessible (or the functionality was not implemented yet)
* are not listed here.
*
* Please for ps listing functionality use util class (TODO: will be added as part of JBQA-10920).
*
* You can use {@link PsCmdBuilder} to get information in raw text format. Builder on its own creates
* each time just one command and especially on windows you need to use more commands to get
* all information what you need.
*
*/
public enum PsCmdFormat {
// linux: ps, windows: wmic
/**
* Command name (without argumens).
*/
COMMAND(true, String.class),
/**
* Command with all arguments.
*/
COMMAND_ARGS(true, String.class),
/**
* Id of process.
*/
PROCESS_ID(false, Long.class),
/**
* Pid of process parent.
*/
PARENT_PROCESS_ID(false, Long.class),
/**
* Priority (nice) of the process.
*/
PRIORITY(false, Integer.class),
/**
* Cumulative CPU time.
*/
TIME(true, String.class),
/**
* Controlling terminal for process.
* For windows this will show session id.
*/
TTY(false, Integer.class),
/**
* Virtual memory size of process in kilobytes.
*/
VIRT_MEM(false, Integer.class),
// windows: wmic path Win32_PerfFormattedData_PerfProc_Process
/**
* Percentage how much the cpu is loaded by process
* This has to be space separated to algorithm of {@link ListProcess} class
* would not shuffle wmic and wmic perf data
*/
CPU(true, String.class),
/**
* How much time elapsed from start of the process
*/
ELAPSED_TIME(true, String.class),
// windows: tasklist
/**
* User running this command.
* Note: windows does not know much about ruser and
* I didn't find way to easily get group so there is left just
* this column to be listed as platform independent record.
* This is not supported in {@link ListProcess} - not easy to parse tasklist.
*/
USER(true, String.class);
/**
* Says that the value could contain spaces. Meaning e.g. process id is always
* one number that can't be separated by space in ps listing.
* On the other hand command with args will be space separated for sure
*/
private boolean isSpaceSeparated;
/**
*
* Type that the result will be tried to cast to e.g. for ordering.
*/
private Class<?> dataType;
PsCmdFormat(final boolean isSpaceSeparated, final Class<?> castType) {
this.isSpaceSeparated = isSpaceSeparated;
this.dataType = castType;
}
/**
* Returning information if the column in listing could be space separated or not.
* This is important for parsing results mainly for utility class {@link ListProcess}
*
* @return true if parsed value for ps column could contain spaces, false otherwise
*/
public boolean isSpaceSeparated() {
return this.isSpaceSeparated;
}
/**
* Returns type of the value (when it's parsed) that we can try to convert to.
* See {@link ListProcessData} comparator.
*
* @return class type that we can convert the parsed value of column to
*/
public Class<?> getDataType() {
return this.dataType;
}
}
<file_sep>/core/src/main/resources/ssl/self_signed_fips/README.txt
This README is the counterpart of the existing README.txt
for the non-fips directory, with the relevant information
to recreate the certificates in the FIPS case.
//generate a NSS keystore (note that key is generated on the fly)
mkdir -p nssdb
modutil -create -dbdir sql:nssdb
chmod a+r nssdb/*.db
modutil -fips true -dbdir sql:nssdb
// java compatibility needs an empty secmod.db
touch nssdb/secmod.db
//store a password for the key
echo 'changeit' >nwpwfile
//don't set a password for the keystore
//modutil -changepw "NSS FIPS 140-2 Certificate DB" -dbdir sql:nssdb -newpwfile nwpwfile
//generate a key
certutil -S -k rsa -n tomcat -t "CTu,Cu,Cu" -x -7 <EMAIL> \
-s 'C=CZ, ST=Czech Republic, L=Brno, O=Corleone Family, OU=Michael Corleone, CN=localhost' -d sql:nssdb -f nwpwfile
// keystore in pkcs12 format (for use in non-FIPS mode)
pk12util -o server.p12 -d nssdb -n tomcat
// certificate
openssl pkcs12 -in server.p12 -out server.crt -clcerts -nokeys -nodes -passin pass:changeit
// key
openssl pkcs12 -in server.p12 -out server.key -nocerts -nodes -password pass:changeit
// set a password for the extracted key???
// transform keystore into jks format (Note it needs to be done in non-FIPS mode)
/usr/lib/jvm/java-11/bin/keytool -J-Dcom.redhat.fips=false -importkeystore -srckeystore server.p12 -srcstorepass changeit -srcstoretype pkcs12 -destkeystore server.jks -deststoretype jks -deststorepass changeit
// list contents (both list the same result)
keytool -list -v -keystore server.jks -storetype jks -protected
keytool -list -v -keystore server.jks -storetype jks -storepass <PASSWORD>
// list contents of the nss
keytool -J-Djava.security.properties==/dev/null -list -storetype pkcs11
<file_sep>/core/src/main/groovy/noe/common/newcmd/SimpleCmdBuilder.java
package noe.common.newcmd;
/**
* Simple raw {@link CmdBuilder}
*/
public class SimpleCmdBuilder extends CmdBuilder<SimpleCmdBuilder> {
/**
* @see CmdBuilder#CmdBuilder(String)
*/
public SimpleCmdBuilder(final String baseCommand) {
super(baseCommand);
}
}
<file_sep>/core/src/main/resources/httpd/.postinstall.jws3.httpd.nosudo.solaris64
#!/bin/sh
# Copyright(c) 2015 Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library in the file COPYING.LIB;
# if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
#
# JBoss Web Server post install script
#
DEFAULT_LOCATION="/opt/jws-3.0"
LIB_DIR="lib64"
if [ -d /usr/xpg4/bin ]
then
PATH=/usr/xpg4/bin:$PATH
export PATH
fi
if type printf > /dev/null
then
XBECHO="printf"
elif [ -x /usr/ucb/echo ]; then
XBECHO="/usr/ucb/echo -n"
else
XBECHO="echo"
fi
if [ ".`id -nu`" = .root ]
then
SUGID="root"
else
SUGID="`id -nu`"
echo "WARNING: This script should be run as superuser to create user \`apache' and directories in \`/var/'." >&2
fi
check_java_home="no"
setattributes()
{
chmod $1 "$4" 2>/dev/null || true
chown $2:$3 "$4" 2>/dev/null || true
}
dirattributes()
{
if [ -d "$4" ]
then
chmod $1 "$4" 2>/dev/null || true
chown -R $2:$3 "$4" 2>/dev/null || true
(
cd "$4"
find . -type d -exec chmod $1 '{}' \;
)
fi
}
createsymlink()
{
rm -rf $2 >/dev/null 2>&1 || true
ln -sf "$1" $2
}
createbasedir()
{
if [ ! -d "$1" ]
then
mkdir -p "$1"
if [ $? -ne 0 ]; then
exit $?
fi
fi
}
copynoreplace()
{
if [ -f "$1".in ]
then
if [ -f "$1" ]
then
echo "Preserving file: $1"
else
sed "s;@installroot@;$INSTALL_ROOT;g" "$1.in" > "$1"
fi
rm "$1.in" 2> /dev/null || true
fi
}
copydoreplace()
{
if [ -f "$1" ]
then
sed "s;@installroot@;$INSTALL_ROOT;g" "$1" > "$1.tmp"
mv "$1.tmp" "$1" 2> /dev/null || true
fi
}
if [ ".$INSTALL_ROOT" = . ]
then
c="`pwd`"
cd ..
INSTALL_ROOT="`pwd`"
cd $c
if [ "$INSTALL_ROOT" != "$DEFAULT_LOCATION" ]
then
echo "WARNING: Using different root directory then \`$DEFAULT_LOCATION'" >&2
fi
fi
#
# Fix directory permissions
#
if [ -d "$INSTALL_ROOT" ]
then
if [ -f "$INSTALL_ROOT/etc/.postinstall.httpd.done" ]
then
echo "Skipping post install. Package is already installed in : \`$INSTALL_ROOT'" >&2
exit 17
else
(
cd "$INSTALL_ROOT"
find . -type d -exec chmod 755 '{}' \;
)
fi
else
echo "Unknown package base directory : \`$INSTALL_ROOT'" >&2
exit 20
fi
if [ ".$LD_LIBRARY_PATH" = . ]
then
LD_LIBRARY_PATH="$INSTALL_ROOT/$LIB_DIR"
else
LD_LIBRARY_PATH="$INSTALL_ROOT/$LIB_DIR:$LD_LIBRARY_PATH"
fi
export LD_LIBRARY_PATH
#
# Apache Httpd post install script
# Privileged execution
# Add the "apache" user
if [ ".$SUGID" = ".root" ]
then
apache_uid=48
apache_osu="`id -u apache 2>/dev/null`"
apache_osg="`id -g apache 2>/dev/null`"
if [ ".$apache_osg" = . ]
then
apache_osg=$apache_uid
/usr/sbin/groupadd -g $apache_osg apache 2> /dev/null || true
if [ $? -eq 0 ]
then
echo "Apache group (id=$apache_osg) created."
fi
else
echo "Apache group (id=$apache_osu) already exists."
fi
dirattributes 0775 root apache "$INSTALL_ROOT/var/www"
if [ ".$apache_osu" = . ]
then
apache_osu=$apache_uid
/usr/sbin/useradd -c "Apache" -u $apache_osu -g apache \
-s /bin/sh -m -d "$INSTALL_ROOT/var/www" apache 2> /dev/null || true
if [ $? -eq 0 ]
then
echo "Apache user (id=$apache_osu) created."
fi
else
echo "Apache user (id=$apache_osu) already exists."
fi
createbasedir /var/log/httpd
createbasedir /var/cache/httpd
createbasedir /var/lock/subsys
createbasedir /var/run/httpd
setattributes 0700 apache $SUGID /var/cache/httpd
for i in dir pag sem
do
if [ ! -f /var/cache/httpd/sslcache.$i ]; then
touch /var/cache/httpd/sslcache.$i
setattributes 0600 apache $SUGID /var/cache/httpd/sslcache.$i
fi
done
setattributes 0700 apache $SUGID /var/run/httpd
setattributes 0700 root $SUGID /var/log/httpd
setattributes 4510 root apache "$INSTALL_ROOT/sbin/suexec"
(
cd httpd
createsymlink "../../$LIB_DIR/httpd/modules" modules
createsymlink /var/log/httpd logs
createsymlink /var/run/httpd run
)
# Unprivileged execution
else
echo "WARNING: Not a superuser. User and group \`apache' will not be created. User \`$SUGID' used instead." >&2
echo "WARNING: Not a superuser. Directories in \`/var/' will not be created. Using \`$INSTALL_ROOT/var/' instead." >&2
dirattributes 0775 $SUGID $SUGID "$INSTALL_ROOT/var/www"
createbasedir "$INSTALL_ROOT/var/log/httpd"
createbasedir "$INSTALL_ROOT/var/cache/httpd"
createbasedir "$INSTALL_ROOT/var/lock/subsys"
createbasedir "$INSTALL_ROOT/var/run/httpd"
setattributes 0700 $SUGID $SUGID "$INSTALL_ROOT/var/cache/httpd"
for i in dir pag sem
do
if [ ! -f "$INSTALL_ROOT/var/cache/httpd/sslcache.$i" ]; then
touch "$INSTALL_ROOT/var/cache/httpd/sslcache.$i"
setattributes 0600 $SUGID $SUGID "$INSTALL_ROOT/var/cache/httpd/sslcache.$i"
fi
done
setattributes 0700 $SUGID $SUGID /var/run/httpd
setattributes 0700 $SUGID $SUGID /var/log/httpd
setattributes 4510 $SUGID $SUGID "$INSTALL_ROOT/sbin/suexec"
(
cd httpd
createsymlink "../../$LIB_DIR/httpd/modules" modules
createsymlink "$INSTALL_ROOT/var/log/httpd" logs
createsymlink "$INSTALL_ROOT/var/run/httpd" run
)
fi
(
sslcert="$INSTALL_ROOT/etc/ssl/certs/localhost.crt"
sslpkey="$INSTALL_ROOT/etc/ssl/private/localhost.key"
sslconf="$INSTALL_ROOT/etc/ssl/openssl.cnf"
sserial=$RANDOM
if [ ".$sserial" = . ]
then
sserial=$$
fi
umask 077
if [ ! -f "$sslpkey" ]
then
$XBECHO "Generating private RSA key ... "
$INSTALL_ROOT/bin/openssl genrsa -rand 1024 > "$sslpkey" 2> /dev/null
if [ $? -eq 0 ]; then echo "OK" ; else echo "Failed: -$?" ; fi
fi
FQDN=`hostname`
if [ ".$FQDN" = . ]
then
FQDN=localhost.localdomain
fi
if [ ! -f "$sslcert" ]
then
$XBECHO "Generating new $FQDN certificate ... "
cat << EOH | $INSTALL_ROOT/bin/openssl req -new -config "$sslconf" -key "$sslpkey" \
-x509 -days 365 -set_serial $sserial \
-out "$sslcert" 2>/dev/null
--
SomeState
SomeCity
SomeOrganization
SomeOrganizationalUnit
$FQDN
root@$FQDN
EOH
if [ $? -eq 0 ]; then echo "OK" ; else echo "Failed: -$?" ; fi
fi
)
(
# Copy .in files preserving existing
cd "$INSTALL_ROOT/etc/httpd/conf.d"
for f in ssl.conf welcome.conf manual.conf proxy_ajp.conf mod_cluster.conf
do
copynoreplace $f
done
copynoreplace "$INSTALL_ROOT/etc/httpd/conf/httpd.conf"
copynoreplace "$INSTALL_ROOT/etc/mime.types"
copynoreplace "$INSTALL_ROOT/etc/sysconfig/httpd"
copynoreplace "$INSTALL_ROOT/etc/logrotate.d/httpd"
copynoreplace "$INSTALL_ROOT/var/www/error/noindex.html"
copynoreplace "$INSTALL_ROOT/sbin/apachectl"
chmod 775 "$INSTALL_ROOT/sbin/apachectl"
)
# In case of unprivileged execution, change Apache Httpd server user
if [ "$SUGID" != "root" ]
then
sed "s;^User apache;User $SUGID;g" "$INSTALL_ROOT/etc/httpd/conf/httpd.conf" > "$INSTALL_ROOT/etc/httpd/conf/httpd.conf.tmp"
mv "$INSTALL_ROOT/etc/httpd/conf/httpd.conf.tmp" "$INSTALL_ROOT/etc/httpd/conf/httpd.conf" 2> /dev/null || true
sed "s;^Group apache;Group $SUGID;g" "$INSTALL_ROOT/etc/httpd/conf/httpd.conf" > "$INSTALL_ROOT/etc/httpd/conf/httpd.conf.tmp"
mv "$INSTALL_ROOT/etc/httpd/conf/httpd.conf.tmp" "$INSTALL_ROOT/etc/httpd/conf/httpd.conf" 2> /dev/null || true
fi
touch "$INSTALL_ROOT/etc/.postinstall.httpd.done"
echo "Done."
<file_sep>/testsuite/src/test/resources/tomcat7-common-test.properties
ews.version=3.1.0
context=ews
JBPAPP9445_WORKAROUND=true
tomcat.major.version=7
<file_sep>/core/src/main/groovy/noe/common/newcmd/ListProcessData.java
package noe.common.newcmd;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* DTO object which consists list of parsed results from system native command
* listing processes.
* This class then offers sorting capabilities over the parsed results.
*/
public class ListProcessData {
/**
* This is a map which represents lines of the output of ps command. Each line is then
* represented by another map where each record is mapped to a column from the ps output.
* This means that e.g. line '1 cat ochaloup' will be transfered to:
* Map<1, Map<PID:1, COMM: cat, USER: ochaloup>>
*/
private Map<String,Map<PsCmdFormat,String>> listing = new HashMap<String, Map<PsCmdFormat,String>>();
/**
* Appending values in process data. The underlying storage uses process id as key - the 'mapValue'
* HAS TO contain {@link PsCmdFormat#PROCESS_ID} otherwise {@link IllegalArgumentException} will be
* thrown.
*
* @param mapValue map of values with {@link PsCmdFormat} as keys and string as parsed value
* @return this
* @throws IllegalArgumentException when param does not contain data for {@link PsCmdFormat#PROCESS_ID}
* @throws NullPointerException when argument is null
*/
public ListProcessData add(final Map<PsCmdFormat,String> mapValue) {
Preconditions.checkNotNull(mapValue, "Data to add can't be null");
if(mapValue.get(PsCmdFormat.PROCESS_ID) == null) {
throw new IllegalArgumentException("mapValue parameter has to contain dat for PsCmdFormat#PROCESS_ID");
}
return this.add(mapValue.get(PsCmdFormat.PROCESS_ID), mapValue);
}
/**
* Appending data of particular process id {@link PsCmdFormat#PROCESS_ID} just in case that
* internal storage already contains data with such id. Otherwise will be done nothing.
* The underlying storage uses process id as key - the 'mapValue'HAS TO contain {@link PsCmdFormat#PROCESS_ID}
* otherwise {@link IllegalArgumentException} will be
* thrown.
*
* @param mapValue value to be added
* @return this
*/
public ListProcessData addIfExists(final Map<PsCmdFormat,String> mapValue) {
Preconditions.checkNotNull(mapValue, "Data to add can't be null");
if(mapValue.get(PsCmdFormat.PROCESS_ID) == null) {
throw new IllegalArgumentException("mapValue parameter has to contain dat for PsCmdFormat#PROCESS_ID");
}
Map<PsCmdFormat,String> listOfValues = listing.get(mapValue.get(PsCmdFormat.PROCESS_ID));
if(listOfValues != null) {
this.add(mapValue.get(PsCmdFormat.PROCESS_ID), mapValue);
}
return this;
}
/**
* Putting the map values to data storage and replacing data for the same PID if they exists in the storage.
* If not just adding them.
* Parameter 'mapValue' HAS TO contain {@link PsCmdFormat#PROCESS_ID} otherwise {@link IllegalArgumentException} will be
* thrown.
*
* @param mapValue data to be added to storage
* @return this
* @throws IllegalArgumentException when param does not contain data for {@link PsCmdFormat#PROCESS_ID}
* @throws NullPointerException when argument is null
*/
public ListProcessData put(final Map<PsCmdFormat,String> mapValue) {
Preconditions.checkNotNull(mapValue, "Data to put can't be null");
if(mapValue.get(PsCmdFormat.PROCESS_ID) == null) {
throw new IllegalArgumentException("mapValue parameter has to contain dat for PsCmdFormat#PROCESS_ID");
}
return this.put(mapValue.get(PsCmdFormat.PROCESS_ID), mapValue);
}
/**
* See {@link #put(Map)} just adding all data from list.
*
* @param mapValues list of map to add to this storage
* @return this
*/
public ListProcessData putAll(final Iterable<Map<PsCmdFormat,String>> mapValues) {
for(Map<PsCmdFormat,String> map: mapValues) {
this.put(map);
}
return this;
}
/**
* Number of lines that were returned by ps command and are currently available from data storage.
* This number could change afte filter is applied.
*
* @return number of lines
*/
public int size() {
return listing.size();
}
/**
* On behalf of process id it returns it's representation in data by Map of keys and values.
* As process id is unique value there can't be any duplication and just one item is returned.
*
* @param processId process id that should be search in data
* @return info on data
*/
public Map<PsCmdFormat,String> get(final long processId) {
String processIdAsString = String.valueOf(processId);
if(listing.get(processIdAsString) == null) {
return null;
}
// creating copy of data
return new HashMap<PsCmdFormat,String>(listing.get(processIdAsString));
}
/**
* Checking if the data contains line with column of {@link PsCmdFormat}
* and value of value
*
* @param psCmdFormat what value to search
* @param value what value should be contained
*/
public boolean contains(final PsCmdFormat psCmdFormat, final String value) {
for(Map<PsCmdFormat, String> line: listing.values()) {
if(line.get(psCmdFormat) != null && line.get(psCmdFormat).equals(value)) {
return true;
}
}
return false;
}
/**
* Returning copy of data from the process listing as string.
*
* @return list where record represents line and map represents columns for that line
*/
public List<Map<PsCmdFormat, String>> getAsList() {
return new ArrayList<Map<PsCmdFormat, String>>(listing.values());
}
/**
* Returning copy of data from the process listing as map with process id used as key.
*
* @return map where each record represents line indexed by process id and
* inner map represents columns of the line
*/
public Map<String,Map<PsCmdFormat,String>> getAsMap() {
return new HashMap<String,Map<PsCmdFormat,String>>(listing);
}
/**
* Returns list of parsed data from native 'ps' (process listing) command sorted
* by some of columns defined as argument.
*
* @param formatsToSort what columns should be taken for sorting
* @return list of map where each record of list means one line of ps command output
* and map represents columns from the ps output
*/
public List<Map<PsCmdFormat, String>> sortByAsList(final PsCmdFormat... formatsToSort) {
return sortBy(false, formatsToSort);
}
/**
* Returns list of parsed data from native 'ps' (process listing) command sorted
* by some of columns defined as argument in reverse order.
*
* @param formatsToSort what columns to sort by
* @return list of map where each record of list means one line of ps command output
* and map represents columns from the ps output in reverse order
*/
public List<Map<PsCmdFormat, String>> sortReverseByAsList(final PsCmdFormat... formatsToSort) {
return sortBy(true, formatsToSort);
}
/**
* Filter out all lines of results that satisfy predicate where {@link PsCmdFormat} value
* is equal to string defined in second argument
*
* @param cmdFormat column where to search for the contains string
* @param equalsString what to search
* @return filtered copy of data
*/
public ListProcessData filterBy(final PsCmdFormat cmdFormat, final String equalsString) {
ListProcessDataPredicate predicate = new ListProcessDataPredicate(cmdFormat, equalsString, true);
return filterBy(predicate);
}
/**
* Filter out all lines of results that satisfy predicate where {@link PsCmdFormat} value
* contains a string defined in second argument
*
* @param cmdFormat column where to search for the contains string
* @param containsString what to search
* @return filtered copy of data
*/
public ListProcessData filterByContains(final PsCmdFormat cmdFormat, final String containsString) {
ListProcessDataPredicate predicate = new ListProcessDataPredicate(cmdFormat, containsString, false);
return filterBy(predicate);
}
/**
* See {@link #filterBy(PsCmdFormat, String)} but removes.
*
* @param cmdFormat cmd format that will define data to remove line by
* @param equalsString what the value of cmdFormat should be
* @return copy of ListProcessData with removed items
*/
public ListProcessData removeBy(final PsCmdFormat cmdFormat, final String equalsString) {
ListProcessDataPredicate predicate = new ListProcessDataPredicate(cmdFormat, equalsString, true);
return removeBy(predicate);
}
/**
* See {@link #filterByContains(PsCmdFormat, String)} but removes.
*
* @param cmdFormat cmd format that will define data to remove line by
* @param containsString what the value of cmdFormat should be
* @return copy of ListProcessData with removed items
*/
public ListProcessData removeByContains(final PsCmdFormat cmdFormat, final String containsString) {
ListProcessDataPredicate predicate = new ListProcessDataPredicate(cmdFormat, containsString, false);
return removeBy(predicate);
}
/**
* Working directly on internal data structure and deletes all records/lines that are not complete.
* Complete means that it does not have all records that is expected to exist for the listing.
* This incompleteness could occur because of sever calls of ps external command and each of the call
* could return a bit different data.
*/
void removeIncomplete(final int expectedNumberOfRecords) {
Iterator<String> listingIterator = listing.keySet().iterator();
while (listingIterator.hasNext()) {
String key = listingIterator.next();
// there could be added some necessary items to listing (e.g. pid) as addition to expected
// records that user wants to work with
if(listing.get(key).size() < expectedNumberOfRecords) {
listingIterator.remove();
}
}
}
private ListProcessData filterBy(final ListProcessDataPredicate predicate) {
Iterable<Map<PsCmdFormat, String>> filteredList = Iterables.filter(getAsList(), predicate);
ListProcessData copyOfData = new ListProcessData();
return copyOfData.putAll(filteredList);
}
private ListProcessData removeBy(final ListProcessDataPredicate predicate) {
List<Map<PsCmdFormat, String>> asList = getAsList();
Iterables.removeIf(asList, predicate);
ListProcessData copyOfData = new ListProcessData();
return copyOfData.putAll(asList);
}
private List<Map<PsCmdFormat, String>> sortBy(final boolean isReverse, final PsCmdFormat... formatsToSort) {
if(formatsToSort == null) {
return getAsList();
}
Ordering<Map<PsCmdFormat, String>> ordering = null;
for(PsCmdFormat psCmdFormat: formatsToSort) {
if(psCmdFormat == null) {
continue;
}
if(ordering == null) {
ordering = isReverse ? (new ListProcessDataOrdering(psCmdFormat)).reverse() : new ListProcessDataOrdering(psCmdFormat);
} else {
ordering = isReverse ? ordering.compound((new ListProcessDataOrdering(psCmdFormat)).reverse()) :
ordering.compound(new ListProcessDataOrdering(psCmdFormat));
}
}
return ordering == null ? getAsList() : ordering.sortedCopy(listing.values());
}
static class ListProcessDataOrdering extends Ordering<Map<PsCmdFormat, String>> {
private PsCmdFormat psCmdFormatToSort;
/**
* Definition of comparator when saying what is the map should be compared by.
*
* @param psCmdFormatToSort is parameter which defines sorting key of the map
* the sorting key is defined as 'ps' command record type - see {@link PsCmdFormat}
*/
public ListProcessDataOrdering(final PsCmdFormat psCmdFormatToSort) {
this.psCmdFormatToSort = psCmdFormatToSort;
}
@Override
public int compare(final Map<PsCmdFormat, String> left, final Map<PsCmdFormat, String> right) {
if(left == null && right == null) {
// both maps are null
return 0;
}
if(left != null && left.get(psCmdFormatToSort) == null &&
right != null && right.get(psCmdFormatToSort) == null) {
// maps are not null but neither one contain the key that we want to sort by
return 0;
}
if(left == null || left.get(psCmdFormatToSort) == null) {
return -1;
}
if(right == null || right.get(psCmdFormatToSort) == null) {
return 1;
}
String str1 = left.get(psCmdFormatToSort);
String str2 = right.get(psCmdFormatToSort);
Class<?> dataType = psCmdFormatToSort.getDataType();
if(dataType.isInstance(Integer.valueOf(0))) {
boolean int1error = false;
Integer int1 = null, int2 = null;
try {
int1 = Integer.valueOf(str1);
} catch (NumberFormatException nfe) {
int1error = true;
}
try {
int2 = Integer.valueOf(str2);
} catch (NumberFormatException nfe) {
// if string from left is not possible to convert to int
// then in case of right is not possible to convert do string comparison
// otherwise left was possible to convert but right is not possible to convert (returns 1)
return int1error ? str1.compareTo(str2) : 1;
}
// if string from left is not possible to convert to int
// then we know that right was converted fine and we return -1
// otherwise both were converted without problem and returning integer comparison
return int1error ? -1 : int1.compareTo(int2);
}
if(dataType.isInstance(Long.valueOf(0))) {
boolean long1error = false;
Long long1 = null, long2 = null;
try {
long1 = Long.valueOf(str1);
} catch (NumberFormatException nfe) {
long1error = true;
}
try {
long2 = Long.valueOf(str2);
} catch (NumberFormatException nfe) {
// if string from left is not possible to convert to long
// then in case of right is not possible to convert do string comparison
// otherwise left was possible to convert but right is not possible to convert (returns 1)
return long1error ? str1.compareTo(str2) : 1;
}
// if string from left is not possible to convert to long
// then we know that right was converted fine and we return -1
// otherwise both were converted without problem and returning integer comparison
return long1error ? -1 : long1.compareTo(long2);
}
return str1.compareTo(str2);
}
}
static class ListProcessDataPredicate implements Predicate<Map<PsCmdFormat, String>> {
private PsCmdFormat psCmdFormatToVerify;
private String stringToVerify;
private boolean isEqual = true;
/**
* Equality set to true
*/
public ListProcessDataPredicate(final PsCmdFormat psCmdFormatToVerify, final String stringToVerify) {
this(psCmdFormatToVerify, stringToVerify, true);
}
public ListProcessDataPredicate(final PsCmdFormat psCmdFormatToVerify, final String stringToVerify, final boolean isEqual) {
Preconditions.checkNotNull(psCmdFormatToVerify, "PsCmdFormat for predicate can't be null");
Preconditions.checkNotNull(stringToVerify, "String to verify for predicate can't be null");
this.psCmdFormatToVerify = psCmdFormatToVerify;
this.stringToVerify = stringToVerify;
this.isEqual = isEqual;
}
public boolean apply(final Map<PsCmdFormat, String> input) {
if(input == null || input.get(psCmdFormatToVerify) == null) {
return false;
}
if(isEqual) {
return input.get(psCmdFormatToVerify).equals(stringToVerify);
} else {
return input.get(psCmdFormatToVerify).contains(stringToVerify);
}
}
}
private ListProcessData add(final String key, final Map<PsCmdFormat,String> mapValue) {
Map<PsCmdFormat,String> listOfValues = listing.get(key);
if(listOfValues == null) {
listOfValues = new HashMap<PsCmdFormat,String>();
listing.put(key, listOfValues);
}
listOfValues.putAll(mapValue);
return this;
}
private ListProcessData put(final String key, final Map<PsCmdFormat, String> mapValue) {
listing.put(key, new HashMap<PsCmdFormat, String>(mapValue));
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(String key: listing.keySet()) {
sb.append("{[" + key + "]");
for(Entry<PsCmdFormat,String> item: listing.get(key).entrySet()) {
sb.append(item.getKey() + ":" + item.getValue() + ",");
}
sb.append("}");
}
return sb.toString();
}
}
<file_sep>/core/src/main/resources/scripts/system/unix/.profile
# Increase the maximum file descriptors if we can
# Use the maximum available, or set MAX_FD != -1 to use that
MAX_FD="maximum"
MAX_FD_LIMIT=`ulimit -H -n`
if [ "$?" -eq 0 ]; then
# Solaris hasn't sysctl
if [ "`uname`" != "SunOS" -a "$MAX_FD_LIMIT" = "unlimited" ]; then
MAX_FD_LIMIT=`/usr/sbin/sysctl -n kern.maxfilesperproc`
fi
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ]; then
# use the system max
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ "$?" -ne 0 ]; then
echo "[WARN] Could not set maximum file descriptor limit: $MAX_FD"
fi
else
echo "[WARN] Could not query system maximum file descriptor limit: $MAX_FD_LIMIT"
fi
<file_sep>/core/src/main/groovy/noe/common/newcmd/CmdBuilder.java
package noe.common.newcmd;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import noe.common.utils.Platform;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
/**
* Builder for creating commands.
* <p>
* This and its children are shortcut for creating {@link CmdCommand} by platform independent way. For formatted output and more
* sophisticated cases, use util classes.
* <p>
* If you use builder or any child builder which depends on this basic class you can influence which environmental properties
* are passed to run native command.
*
* @param <THIS> - return type of the builder methods, e.g. see {@link #addArgument(String)}
*/
@SuppressWarnings("unchecked")
public class CmdBuilder<THIS extends CmdBuilder<THIS>> implements CmdBuilderInterface {
private final CmdCommand cmd;
protected static final Platform platform = new Platform();
private static final String USER_DIR_PROP_NAME = "user.dir";
public static final String[] WINDOWS_SUFFIXES = new String[]{".bat", ".cmd"};
private Map<String, String> envProperties;
/**
* Command builder for user defined base command.
* <br>
*
* @param baseCommand base command of {@link CmdCommand} that will be created
*/
public CmdBuilder(final String baseCommand) {
this.cmd = new CmdCommand(baseCommand);
// env properties could be immutable but we want to let user to change them
envProperties = new HashMap<String, String>();
}
/**
* Command builder for user defined command.
* <br>
*
* @param wholeCommand command of {@link CmdCommand} that will be created
*/
public CmdBuilder(final List wholeCommand) {
if (wholeCommand.size() < 1) throw new IllegalArgumentException("The command must contain at least one item representing basecommand");
String baseCommand = String.valueOf(wholeCommand.get(0));
this.cmd = new CmdCommand(baseCommand);
if (wholeCommand.size() > 1) {
for (int i = 1; i < wholeCommand.size(); i++) {
cmd.addArgument(String.valueOf(wholeCommand.get(i)));
}
}
// env properties could be immutable but we want to let user to change them
envProperties = new HashMap<String, String>();
}
/**
* Main method of builder. From defined arguments and from other setter method builds {@link CmdCommand}.
*
* @return built instance of {@link CmdCommand}.
*/
public CmdCommand build() {
// setting working directory if user did not set it manually
if (cmd.getWorkingDirectory() == null) {
cmd.setWorkingDirectory(new File("."));
}
ImmutableList.Builder<String> prefix = new ImmutableList.Builder<String>();
if (platform.isWindows()) {
envProperties.put("NOPAUSE", "true");
}
cmd.setEnvProperties(envProperties);
// if we are on widows and the command is absolute path then it's a command which
// does not need being prefixed with 'cmd /c'. Furthermore it would cause troubles
// when path with spaces would be used.
// If it's a relative path to a command then we need to use 'cmd /c' as it manages
// change of working directory or stuff around native commands appropriately
if (platform.isWindows() && !new File(cmd.getBaseCommand()).exists()) {
prefix.add("cmd", "/c");
}
cmd.setPrefix(prefix.build());
return cmd;
}
public THIS setExitValues(final int[] values) {
if (values != null) {
cmd.setExitValues(values);
}
return (THIS) this;
}
/**
* Adding argument to command NOT prefixed. Pass the call over {@link CmdCommand#addArgument(String)} method. But if argument is
* empty (or null) it ignores this argument to be added.
*
* @param argument argument to be added to cmd
* @return this
*/
public THIS addArgument(final String argument) {
if (argument != null && !argument.isEmpty()) {
cmd.addArgument(argument);
}
return (THIS) this;
}
/**
* Adding arguments to command NOT prefixed. If some of the arguments in list is empty (or null) such argument is ignored
* from adding it to Cmd (to pass it to {@link CmdCommand#addArgument(String)} method).
*
* @param arguments arguments to be added to cmd
* @return this
*/
public THIS addArguments(final String... arguments) {
for (String argument : arguments) {
addArgument(argument);
}
return (THIS) this;
}
/**
* Adding arguments to command NOT prefixed. Each argument is transformed to String using {@link Object#toString()} method.
* If some of the arguments in list is null or its String representation is empty such argument is ignored from adding it
* to Cmd (to pass it to {@link CmdCommand#addArgument(String)} method).
*
* @param arguments arguments to be added to cmd
* @return this
*/
public THIS addArguments(final Iterable<Object> arguments) {
for (Object arg : arguments) {
if (arg != null) {
addArgument(arg.toString());
}
}
return (THIS) this;
}
/**
* Set based command on inner {@link CmdCommand} instance.
*
* @param baseCommand base command to set
* @return this
*/
public THIS setBaseCommand(final String baseCommand) {
cmd.setBaseCommand(baseCommand);
return (THIS) this;
}
/**
* Setting working directory for built command.
*
* @param workDir where the command will be executed at
* @return this
*/
public THIS setWorkDir(final File workDir) {
cmd.setWorkingDirectory(workDir);
return (THIS) this;
}
/**
* Check whether command contains argument. If match found then argument is returned (first match).
*
* @param regexp regular expression used for searching arguments
* @return first match of found argument
*/
public Optional<String> containsArgument(final String regexp) {
Pattern p = Pattern.compile(regexp);
for (String arg : cmd.getArguments()) {
if (p.matcher(arg).matches()) {
return Optional.of(arg);
}
}
return Optional.absent();
}
/**
* Removes env variables based on settings.
*
* @param sourceEnv source list of env variables
* @param envToRemove env variables to remove from source list
*/
private Map<String, String> filterEnv(final Map<String, String> sourceEnv, final List<String> envToRemove) {
Map<String, String> filteredEnv = new HashMap<String, String>();
for (Entry<String, String> sourceEnvEntry : sourceEnv.entrySet()) {
if (!envToRemove.contains(sourceEnvEntry.getKey())) {
filteredEnv.put(sourceEnvEntry.getKey(), sourceEnvEntry.getValue());
}
}
return filteredEnv;
}
/**
* Putting arguments to cmd but on difference to {@link CmdCommand#addArguments(String...)} it
* check whether arguments are not empty. If so, then such argument
* is ignored to be added to cmd.
* <p>
* Used by childern builders on copied cmd.
*/
protected CmdCommand addArgumentsToCmd(final CmdCommand cmd, final String... arguments) {
for (String argument : arguments) {
if (argument != null && !argument.isEmpty()) {
cmd.addArgument(argument);
}
}
return cmd;
}
}
<file_sep>/testsuite/src/test/resources/eap7-domain-test.properties
eap.version=7.2.0.GA.CR4
context=eap6
<file_sep>/testsuite/src/test/resources/eap7-test.properties
eap.version=7.0.0
context=eap6
<file_sep>/README.md
NOE core
================
Description
-----------------
It is a library containing functionality and abstraction to work with servers (start/stop/kill/configuration) in
a unified way.
It also provides workspace management abstraction which is used to prepare the servers for further testing.
It also contains common libraries such as file manipulation (copy, move, remove, unzip,..), web access and many more.
Coding standards
---------------------------------------------
We use same coding standards like wildfly https://github.com/wildfly/wildfly-core/tree/master/ide-configs with these
exceptions:
* indentation size is 2
* continuation indentation is 4
* maximum line length is 160 chars
Versioning
---------------------------------------------
Version numbering is done in accordance to http://semver.org/spec/v2.0.0.html
Release a snapshot
---------------------------------------------
Release is done using maven to internal JBoss QA maven repositories `mvn clean deploy`
Release a new version
---------------------------------------------
Before releasing, don't forget to check, that integration tests are passing on all platforms, e.g. by checking CI job if it is set up.
Releasing is done using the maven release plugin to internal JBoss QA maven repositories. To perform the release, use the following commands in a sequence:
`mvn release:prepare -Pcomplete -Darguments="-DskipTests"`
`mvn release:perform -Pcomplete -Darguments="-DskipTests"`
These commands automatically change versions, tags, and push the
changes to the `jbossqe-eap/noe-core` repository. Note that the commands exclude running tests; run the tests yourself before releasing.
The `release:prepare` command generates temporary files. If you need to re-generate the temporary files without pushing new tags and versions,
run the following command:
`mvn -DdryRun=true release:prepare -Pcomplete -Darguments="-DskipTests"`
To successfully perform the release, you must set username and password in the `settings.xml` file for the `jboss-qa-releases` server.
Running integration testsuite
--------------------------------------------
`mvn clean verify -Pcomplete` where -Pcomplete stands for also building testsuite module
To run single test run `mvn verify -Pcomplete -Dit.test=SomeTest`
Java requirements
---------------------------------------------
At this moment, Noe Core cannot be built with Java greater than 8. However, it
is tested and used in testsuites with Java up to 11. We now support `SERVER_JAVA_HOME`,
which means the testsuite runs with different Java than the server itself.
Simply export `SERVER_JAVA_HOME` to a JAVA_HOME that will be set for servers
(all Tomcats are supported, some EAPs are supported). This enables you to test
a server with various Javas while running the testsuite on JDK 11+.
<file_sep>/core/src/main/resources/httpd/.postinstall.ews1.httpd.nosudo.solaris64
#!/bin/sh
# Copyright(c) 2010 Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library in the file COPYING.LIB;
# if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
#
# RHATews Post install script
#
if [ ".$INSTALL_ROOT" = . ]
then
c="`pwd`"
cd ..
INSTALL_ROOT="`pwd`"
cd $c
fi
if [ -d /usr/xpg4/bin ]; then
PATH=/usr/xpg4/bin:$PATH
export PATH
fi
if type printf > /dev/null; then
XBECHO="printf"
elif [ -x /usr/ucb/echo ]; then
XBECHO="/usr/ucb/echo -n"
else
XBECHO="echo"
fi
if [ ".`id -nu`" = .root ]; then
SUGID=root
else
"This script must bust be run as superuser" >&2
exit 1
fi
check_java_home="no"
setattributes()
{
chmod $1 "$4" 2>/dev/null || true
chown $2:$3 "$4" 2>/dev/null || true
}
dirattributes()
{
if [ -d "$4" ]; then
chmod $1 "$4" 2>/dev/null || true
chown -R $2:$3 "$4" 2>/dev/null || true
(
cd "$4"
find . -type d -exec chmod $1 '{}' \;
)
fi
}
createsymlink()
{
rm -rf $2 >/dev/null 2>&1 || true
ln -sf "$1" $2
}
createbasedir()
{
if [ ! -d "$1" ]; then
mkdir -p "$1"
if [ $? -ne 0 ]; then
exit $?
fi
fi
}
copynoreplace()
{
if [ ! -f "$1" ]; then
mv "$1.in" "$1" >/dev/null 2>&1 || true
else
rm -f "$1.in" >/dev/null 2>&1 || true
fi
}
#
# Fix directory permissions
#
if [ -d "$INSTALL_ROOT" ]; then
if [ -f "$INSTALL_ROOT/etc/.postinstall.done" ]; then
"Package RHATews already installed in : $INSTALL_ROOT" >&2
exit 17
else
(
cd "$INSTALL_ROOT"
find . -type d -exec chmod 755 '{}' \;
)
fi
else
"Unknown package base directory : $INSTALL_ROOT" >&2
exit 20
fi
if [ ".$LD_LIBRARY_PATH" = . ]; then
LD_LIBRARY_PATH="$INSTALL_ROOT/lib64"
else
LD_LIBRARY_PATH="$INSTALL_ROOT/lib64:$LD_LIBRARY_PATH"
fi
export LD_LIBRARY_PATH
#
# RHATews OpenSSL post install script
#
setattributes 0755 root $SUGID "$INSTALL_ROOT/etc/ssl"
setattributes 0755 root $SUGID "$INSTALL_ROOT/etc/ssl/certs"
setattributes 0700 root $SUGID "$INSTALL_ROOT/etc/ssl/CA"
setattributes 0700 root $SUGID "$INSTALL_ROOT/etc/ssl/private"
#
# RHATews Apache Httpd post install script
#
# Add the "apache" user
apache_uid=48
if [ -x /sbin/nologin ]; then
useshell="/sbin/nologin"
else
useshell="/bin/sh"
fi
apache_osu="`id -u apache 2>/dev/null`"
apache_osg="`id -g apache 2>/dev/null`"
if [ ".$apache_osg" = . ]; then
apache_osg=$apache_uid
/usr/sbin/groupadd -g $apache_osg apache 2> /dev/null || true
if [ $? -eq 0 ]; then
echo "Apache group (id=$apache_osg) created."
fi
else
echo "Apache group (id=$apache_osu) already exists."
fi
if [ ".$apache_osu" = . ]; then
apache_osu=$apache_uid
/usr/sbin/useradd -c "Apache" -u $apache_osu -g apache \
-s $useshell -d "$INSTALL_ROOT/var/www" apache 2> /dev/null || true
if [ $? -eq 0 ]; then
echo "Apache user (id=$apache_osu) created."
fi
else
echo "Apache user (id=$apache_osu) already exists."
fi
createbasedir /var/log/httpd
createbasedir /var/cache/mod_ssl
createbasedir /var/cache/mod_proxy
createbasedir /var/lock/subsys
setattributes 0700 apache $SUGID /var/cache/mod_ssl
for i in dir pag sem
do
if [ ! -f /var/cache/mod_ssl/scache.$i ]; then
touch /var/cache/mod_ssl/scache.$i
setattributes 0600 apache $SUGID /var/cache/mod_ssl/scache.$i
fi
done
setattributes 0700 apache $SUGID /var/cache/mod_proxy
setattributes 0700 root $SUGID /var/log/httpd
setattributes 4510 root apache $INSTALL_ROOT/sbin/suexec
(
sslcert="$INSTALL_ROOT/etc/ssl/certs/localhost.crt"
sslpkey="$INSTALL_ROOT/etc/ssl/private/localhost.key"
sserial=$RANDOM
if [ ".$sserial" = . ]; then
sserial=$$
fi
umask 077
if [ ! -f "$sslpkey" ] ; then
$XBECHO "Generating private RSA key ... "
$INSTALL_ROOT/bin/openssl genrsa -rand 1024 > "$sslpkey" 2> /dev/null
if [ $? -eq 0 ]; then echo "OK" ; else echo "Failed: -$?" ; fi
fi
FQDN=`hostname`
if [ ".$FQDN" = . ]; then
FQDN=localhost.localdomain
fi
if [ ! -f "$sslcert" ] ; then
$XBECHO "Generating new $FQDN certificate ... "
cat << EOF | $INSTALL_ROOT/bin/openssl req -new -key "$sslpkey" \
-x509 -days 365 -set_serial $sserial \
-out "$sslcert" 2>/dev/null
--
SomeState
SomeCity
SomeOrganization
SomeOrganizationalUnit
$FQDN
root@$FQDN
EOF
if [ $? -eq 0 ]; then echo "OK" ; else echo "Failed: -$?" ; fi
fi
)
(
# Copy .in files preserving existing
cd "$INSTALL_ROOT/etc/httpd/conf.d"
for f in ssl.conf welcome.conf manual.conf proxy_ajp.conf
do
copynoreplace $f
done
copynoreplace "$INSTALL_ROOT/etc/httpd/conf/httpd.conf"
copynoreplace "$INSTALL_ROOT/etc/mime.types"
copynoreplace "$INSTALL_ROOT/etc/sysconfig/httpd"
copynoreplace "$INSTALL_ROOT/etc/logrotate.d/httpd"
)
sed "s;\/opt\/redhat\/ews;$INSTALL_ROOT;g" "$INSTALL_ROOT/sbin/apachectl" > "$INSTALL_ROOT/sbin/apachectl.new"
mv "$INSTALL_ROOT/sbin/apachectl.new" "$INSTALL_ROOT/sbin/apachectl"
chmod 755 "$INSTALL_ROOT/sbin/apachectl"
#
# RHATews Apache Tomcat5 post install script
#
tomcat_uid=91
# Add the "tomcat" user
useshell="/bin/sh"
tomcat_osu="`id -u tomcat 2>/dev/null`"
tomcat_osg="`id -g tomcat 2>/dev/null`"
if [ ".$tomcat_osg" = . ]; then
tomcat_osg=$tomcat_uid
/usr/sbin/groupadd -g $tomcat_osg tomcat 2> /dev/null
if [ $? -eq 0 ]; then
echo "Tomcat group (id=$tomcat_osg) created."
fi
else
echo "Tomcat group (id=$tomcat_osu) already exists."
fi
if [ ".$tomcat_osu" = . ]; then
tomcat_osu=$tomcat_uid
/usr/sbin/useradd -c "Apache Tomcat" -u $tomcat_osu -g tomcat \
-s $useshell -d "$INSTALL_ROOT/share/tomcat5" tomcat 2> /dev/null
if [ $? -eq 0 ]; then
echo "Tomcat user (id=$tomcat_osu) created."
fi
else
echo "Tomcat user (id=$tomcat_osu) already exists."
fi
if [ ".$JAVA_HOME" = . ]; then
check_java_home=yes
else
echo "Adding JAVA_HOME=$JAVA_HOME to the configuration"
cat << EOS >> $INSTALL_ROOT/etc/sysconfig/tomcat5
#
# Added by postinstall script
JAVA_HOME="$JAVA_HOME"
EOS
fi
createbasedir /var/log/tomcat5
for i in temp work
do
createbasedir /var/cache/tomcat5/$i
dirattributes 0775 root tomcat /var/cache/tomcat5/$i
done
dirattributes 0775 root tomcat /var/cache/tomcat5
setattributes 0775 root tomcat /var/log/tomcat5
setattributes 0775 root tomcat $INSTALL_ROOT/share/tomcat5
dirattributes 0775 root tomcat $INSTALL_ROOT/share/tomcat5/webapps
dirattributes 0775 root tomcat $INSTALL_ROOT/share/tomcat5/server/webapps
dirattributes 0775 root tomcat $INSTALL_ROOT/share/tomcat5/conf
dirattributes 0775 root tomcat $INSTALL_ROOT/share/tomcat5/conf/Catalina
setattributes 0660 root tomcat $INSTALL_ROOT/share/tomcat5/conf/tomcat-users.xml
if [ -d "$INSTALL_ROOT/share/tomcat5" ]; then
cd "$INSTALL_ROOT/share/tomcat5"
createsymlink /var/log/tomcat5 logs
createsymlink /var/cache/tomcat5/temp temp
createsymlink /var/cache/tomcat5/work work
fi
#
# RHATews Apache Tomcat6 post install script
#
if [ ".$tomcat_uid" = . ]; then
tomcat_uid=91
tomcat_uiv=true
else
tomcat_uiv=false
fi
# Add the "tomcat" user
useshell="/bin/sh"
tomcat_osu="`id -u tomcat 2>/dev/null`"
tomcat_osg="`id -g tomcat 2>/dev/null`"
if [ ".$tomcat_osg" = . ]; then
tomcat_osg=$tomcat_uid
/usr/sbin/groupadd -g $tomcat_osg tomcat 2> /dev/null || true
if [ $? -eq 0 ]; then
echo "Tomcat group (id=$tomcat_osg) created."
fi
elif $tomcat_uiv; then
echo "Tomcat group (id=$tomcat_osu) already exists."
fi
if [ ".$tomcat_osu" = . ]; then
tomcat_osu=$tomcat_uid
/usr/sbin/useradd -c "Apache Tomcat" -u $tomcat_osu -g tomcat \
-s $useshell -d "$INSTALL_ROOT/share/tomcat6" tomcat 2> /dev/null || true
if [ $? -eq 0 ]; then
echo "Tomcat user (id=$tomcat_osu) created."
fi
elif $tomcat_uiv; then
echo "Tomcat user (id=$tomcat_osu) already exists."
fi
if [ ".$JAVA_HOME" = . ]; then
check_java_home=yes
else
echo "Adding JAVA_HOME=$JAVA_HOME to the configuration ..."
cat << EOS >> $INSTALL_ROOT/etc/sysconfig/tomcat6
#
# Added by postinstall script
JAVA_HOME="$JAVA_HOME"
EOS
fi
createbasedir /var/log/tomcat6
for i in temp work
do
createbasedir /var/cache/tomcat6/$i
dirattributes 0775 root tomcat /var/cache/tomcat6/$i
done
dirattributes 0775 root tomcat /var/cache/tomcat6
setattributes 0775 root tomcat /var/log/tomcat6
setattributes 0775 root tomcat $INSTALL_ROOT/share/tomcat6
dirattributes 0775 root tomcat $INSTALL_ROOT/share/tomcat6/webapps
dirattributes 0775 root tomcat $INSTALL_ROOT/share/tomcat6/server/webapps
dirattributes 0775 root tomcat $INSTALL_ROOT/share/tomcat6/conf
setattributes 0660 root tomcat $INSTALL_ROOT/share/tomcat6/conf/tomcat-users.xml
if [ -d "$INSTALL_ROOT/share/tomcat6" ]; then
cd "$INSTALL_ROOT/share/tomcat6"
createsymlink /var/log/tomcat6 logs
createsymlink /var/cache/tomcat6/temp temp
createsymlink /var/cache/tomcat6/work work
fi
#
# Configure Solaris runtime linker environment
#
if [ -x /usr/bin/crle ]; then
/usr/bin/crle -u -l $INSTALL_ROOT/lib64
fi
if [ "$check_java_home" = "yes" ]; then
if [ ".$JAVA_HOME" = . ]; then
echo ""
echo "-----------------------------------------------------------------------"
echo " NOTICE"
echo "-----------------------------------------------------------------------"
echo ""
echo " JAVA_HOME environment variable is not set."
echo " Either set the JAVA_HOME or edit the configuration"
echo " scripts inside \`$INSTALL_ROOT/etc/sysconfig' directory"
echo " and set the JAVA_HOME to the installed JDK location."
echo ""
fi
fi
# End of RHATews Post install script
<file_sep>/testsuite/src/test/resources/jws31-test.properties
ews.version=3.1.0
context=ews
tomcat.major.version=7
<file_sep>/testsuite/src/test/resources/eap7-jbcs-test.properties
eap.version=7.1.0
apache.core.version=2.4.51
context=eap6
<file_sep>/testsuite/src/test/resources/eap6-with-cp-patch.properties
eap.version=6.4.0
eap.cp.version=6.4.2.CP
context=eap6
<file_sep>/testsuite/src/test/resources/jws4-test.properties
ews.version=4.0.0-DR1
context=ews
tomcat.major.version=8<file_sep>/testsuite/src/test/resources/jws5-test.properties
ews.version=5.7.0
context=ews
apache.core.version=2.4.51
tomcat.major.version=9
<file_sep>/testsuite/src/test/resources/eap6-test.properties
eap.version=6.4.0
context=eap6
<file_sep>/core/src/main/resources/ssl/self_signed/README.txt
// key generation
openssl genrsa -des3 -out server.key 4096
passwd: <PASSWORD>
// certificate generation
openssl req -new -x509 -key server.key -out server.crt -days 10950
// keystore in pkcs12 format
openssl pkcs12 -export -in server.crt -inkey server.key -out server.p12
passwd: <PASSWORD>
// transform keystore into jks format
keytool -importkeystore -srckeystore server.p12 -destkeystore server.jks -srcstoretype pkcs12
passwd: <PASSWORD>
<file_sep>/testsuite/src/test/resources/tomcat9-common-test.properties
ews.version=5.7.0
context=ews
JBPAPP9445_WORKAROUND=true
tomcat.major.version=9
<file_sep>/core/src/main/resources/tomcat/.postinstall.jws3.tomcat.nosudo.solaris64
#!/bin/sh
# Copyright(c) 2015 Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library in the file COPYING.LIB;
# if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
#
# JBoss Web Server post install script
#
DEFAULT_LOCATION="/opt/jws-3.0"
LIB_DIR="lib64"
if [ -d /usr/xpg4/bin ]
then
PATH=/usr/xpg4/bin:$PATH
export PATH
fi
if type printf > /dev/null
then
XBECHO="printf"
elif [ -x /usr/ucb/echo ]; then
XBECHO="/usr/ucb/echo -n"
else
XBECHO="echo"
fi
if [ ".`id -nu`" = .root ]
then
SUGID="root"
else
SUGID="`id -nu`"
echo "WARNING: This script should be run as superuser to create user \`tomcat' and directories in \`/var/'." >&2
fi
check_java_home="no"
setattributes()
{
chmod $1 "$4" 2>/dev/null || true
chown $2:$3 "$4" 2>/dev/null || true
}
dirattributes()
{
if [ -d "$4" ]
then
chmod $1 "$4" 2>/dev/null || true
chown -R $2:$3 "$4" 2>/dev/null || true
(
cd "$4"
find . -type d -exec chmod $1 '{}' \;
)
fi
}
createsymlink()
{
rm -rf $2 >/dev/null 2>&1 || true
ln -sf "$1" $2
}
createbasedir()
{
if [ ! -d "$1" ]
then
mkdir -p "$1"
if [ $? -ne 0 ]; then
exit $?
fi
fi
}
copynoreplace()
{
if [ -f "$1" ]
then
echo "Preserving file: $1"
else
sed "s;@installroot@;$INSTALL_ROOT;g" "$1.in" > "$1"
fi
rm "$1.in" 2> /dev/null || true
}
if [ ".$INSTALL_ROOT" = . ]
then
c="`pwd`"
cd ..
INSTALL_ROOT="`pwd`"
cd $c
if [ "$INSTALL_ROOT" != "$DEFAULT_LOCATION" ]
then
echo "WARNING: Using different root directory then \`$DEFAULT_LOCATION'" >&2
fi
fi
#
# Fix directory permissions
#
if [ -d "$INSTALL_ROOT" ]
then
if [ -f "$INSTALL_ROOT/etc/.postinstall.tomcat.done" ]
then
echo "Skipping post install. Package is already installed in : \`$INSTALL_ROOT'" >&2
exit 17
else
(
cd "$INSTALL_ROOT"
find . -type d -exec chmod 755 '{}' \;
)
fi
else
echo "Unknown package base directory : \`$INSTALL_ROOT'" >&2
exit 20
fi
if [ ".$LD_LIBRARY_PATH" = . ]
then
LD_LIBRARY_PATH="$INSTALL_ROOT/$LIB_DIR"
else
LD_LIBRARY_PATH="$INSTALL_ROOT/$LIB_DIR:$LD_LIBRARY_PATH"
fi
export LD_LIBRARY_PATH
# Privileged execution
# Add the "tomcat" user
if [ ".$SUGID" = ".root" ]
then
if [ ".$tomcat_uid" = . ]; then
tomcat_uid=91
tomcat_uiv=true
else
tomcat_uiv=false
fi
tomcat_osu="`id -u tomcat 2>/dev/null`"
tomcat_osg="`id -g tomcat 2>/dev/null`"
if [ ".$tomcat_osg" = . ]; then
tomcat_osg=$tomcat_uid
/usr/sbin/groupadd -g $tomcat_osg tomcat 2> /dev/null || true
if [ $? -eq 0 ]; then
echo "Tomcat group (id=$tomcat_osg) created."
fi
elif $tomcat_uiv; then
echo "Tomcat group (id=$tomcat_osu) already exists."
fi
createbasedir "$INSTALL_ROOT/var/tomcat"
dirattributes 0775 root tomcat "$INSTALL_ROOT/var/tomcat"
if [ ".$tomcat_osu" = . ]; then
tomcat_osu=$tomcat_uid
/usr/sbin/useradd -c "Apache Tomcat" -u $tomcat_osu -g tomcat \
-s /bin/sh -m -d "$INSTALL_ROOT/var/tomcat" tomcat 2> /dev/null || true
if [ $? -eq 0 ]; then
echo "Tomcat user (id=$tomcat_osu) created."
fi
elif $tomcat_uiv; then
echo "Tomcat user (id=$tomcat_osu) already exists."
fi
# Unprivileged execution
else
echo "WARNING: Not a superuser. User and group \`tomcat' will not be created. User \`$SUGID' used instead." >&2
echo "WARNING: Not a superuser. Directories in \`/var/' will not be created. Using \`$INSTALL_ROOT/var/' instead." >&2
fi
#
# Apache Tomcat7 and Tomcat8 post install script
#
TOMCATS="tomcat7 tomcat8"
for TOMCAT in $TOMCATS
do
if [ ".$JAVA_HOME" = . ]; then
check_java_home=yes
else
echo "Adding JAVA_HOME=$JAVA_HOME to the configuration ..."
cat << EOS >> "$INSTALL_ROOT/etc/sysconfig/$TOMCAT"
#
# Added by postinstall script
JAVA_HOME="$JAVA_HOME"
EOS
fi
test ".$INSTALL_ROOT" = "." && INSTALL_ROOT="`cd .. && pwd;`"
# Privileged execution
if [ ".$SUGID" = ".root" ]
then
createbasedir "/var/log/$TOMCAT"
for i in temp work
do
createbasedir "/var/cache/$TOMCAT/$i"
dirattributes 0775 root tomcat "/var/cache/$TOMCAT/$i"
done
dirattributes 0775 root tomcat "/var/cache/$TOMCAT"
setattributes 0775 root tomcat "/var/log/$TOMCAT"
setattributes 0775 root tomcat "$INSTALL_ROOT/share/$TOMCAT"
dirattributes 0775 root tomcat "$INSTALL_ROOT/share/$TOMCAT/webapps"
dirattributes 0775 root tomcat "$INSTALL_ROOT/share/$TOMCAT/server/webapps"
dirattributes 0775 root tomcat "$INSTALL_ROOT/share/$TOMCAT/conf"
setattributes 0660 root tomcat "$INSTALL_ROOT/share/$TOMCAT/conf/tomcat-users.xml"
if [ -d "$INSTALL_ROOT/share/$TOMCAT" ]; then
cd "$INSTALL_ROOT/share/$TOMCAT"
createsymlink "/var/log/$TOMCAT" logs
createsymlink "/var/cache/$TOMCAT/temp" temp
createsymlink "/var/cache/$TOMCAT/work" work
cd bin
createsymlink '../../java/commons-daemon-*.jar' commons-daemon.jar
cd ..
fi
# Unprivileged execution
else
createbasedir "$INSTALL_ROOT/var/log/$TOMCAT"
for i in temp work
do
createbasedir "$INSTALL_ROOT/var/cache/$TOMCAT/$i"
dirattributes 0775 $SUGID $SUGID "$INSTALL_ROOT/var/cache/$TOMCAT/$i"
done
dirattributes 0775 $SUGID $SUGID "$INSTALL_ROOT/var/cache/$TOMCAT"
setattributes 0775 $SUGID $SUGID "$INSTALL_ROOT/var/log/$TOMCAT"
setattributes 0775 $SUGID $SUGID "$INSTALL_ROOT/share/$TOMCAT"
dirattributes 0775 $SUGID $SUGID "$INSTALL_ROOT/share/$TOMCAT/webapps"
dirattributes 0775 $SUGID $SUGID "$INSTALL_ROOT/share/$TOMCAT/server/webapps"
dirattributes 0775 $SUGID $SUGID "$INSTALL_ROOT/share/$TOMCAT/conf"
setattributes 0660 $SUGID $SUGID "$INSTALL_ROOT/share/$TOMCAT/conf/tomcat-users.xml"
if [ -d "$INSTALL_ROOT/share/$TOMCAT" ]; then
cd "$INSTALL_ROOT/share/$TOMCAT"
createsymlink "$INSTALL_ROOT/var/log/$TOMCAT" logs
createsymlink "$INSTALL_ROOT/var/cache/$TOMCAT/temp" temp
createsymlink "$INSTALL_ROOT/var/cache/$TOMCAT/work" work
cd bin
createsymlink '../../java/commons-daemon-*.jar' commons-daemon.jar
cd ..
fi
# Unprivileged execution, set current user as TOMCAT_USER
echo "WARNING: Not a superuser. User \`$SUGID' used as TOMCAT_USER in $INSTALL_ROOT/etc/sysconfig/$TOMCAT." >&2
echo "TOMCAT_USER=$SUGID" >> "$INSTALL_ROOT/etc/sysconfig/$TOMCAT"
fi
for i in "$INSTALL_ROOT/sbin/$TOMCAT" \
"$INSTALL_ROOT/etc/sysconfig/$TOMCAT" \
"$INSTALL_ROOT/etc/logrotate.d/$TOMCAT" \
"$INSTALL_ROOT/share/$TOMCAT/bin/catalina.sh"
do
if [ -r "$i" ]
then
echo "Preserving file: $i"
else
sed "s;@installroot@;$INSTALL_ROOT;g" "$i.in" > "$i"
fi
rm "$i.in" 2> /dev/null || true
done
for i in "$INSTALL_ROOT/sbin/$TOMCAT" \
"$INSTALL_ROOT/share/$TOMCAT/bin/catalina.sh"
do
chmod 775 "$i"
done
done
#
# Configure Solaris runtime linker environment
#
# Privileged execution
if [ ".$SUGID" = ".root" ]
then
if [ -x /usr/bin/crle ]
then
if [ ".$LIB_DIR" = ".lib64" ]
then
/usr/bin/crle -u -64 -l "$INSTALL_ROOT/$LIB_DIR"
else
/usr/bin/crle -u -l "$INSTALL_ROOT/$LIB_DIR"
fi
fi
else
echo "WARNING: Not a superuser. Solaris runtime linker environment \`crle' was not updated." >&2
fi
if [ "$check_java_home" = "yes" ]
then
if [ ".$JAVA_HOME" = . ]
then
echo ""
echo "-----------------------------------------------------------------------"
echo " NOTICE"
echo "-----------------------------------------------------------------------"
echo ""
echo " JAVA_HOME environment variable is not set."
echo " Either set the JAVA_HOME or edit the configuration"
echo " scripts inside \`$INSTALL_ROOT/etc/sysconfig' directory"
echo " and set the JAVA_HOME to the installed JDK location."
echo ""
fi
fi
touch "$INSTALL_ROOT/etc/.postinstall.tomcat.done"
echo "Done"
<file_sep>/core/src/main/groovy/noe/common/StreamConsumer.java
package noe.common;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Simple stream consumer for textual outputs.
*/
public class StreamConsumer extends Thread {
private static final Logger log = LoggerFactory.getLogger(StreamConsumer.class);
public static final String NEW_LINE = System.getProperty("line.separator");
InputStream input;
StringBuffer output;
public StreamConsumer(InputStream is) {
this(is, null);
}
public StreamConsumer(InputStream input, StringBuffer redirect) {
this.input = input;
this.output = redirect;
}
/**
* creates readers to handle the text created by the external program
*/
public void run() {
InputStreamReader isr = null;
BufferedReader br = null;
try {
isr = new InputStreamReader(input);
br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
if (output != null) {
output.append(line);
output.append(NEW_LINE);
}
}
} catch (IOException ioe) {
log.warn("Exception detected when processing output", ioe);
} finally {
IOUtils.closeQuietly(br);
IOUtils.closeQuietly(isr);
}
}
}
<file_sep>/core/src/main/groovy/noe/common/utils/processid/Kernel32.java
/* Copyright (c) 2007, 2013 <NAME>, <NAME>, All Rights Reserved
*
* The contents of this file is dual-licensed under 2
* alternative Open Source/Free licenses: LGPL 2.1 or later and
* Apache License 2.0. (starting with JNA version 4.0.0).
*
* You can freely decide which license you want to apply to
* the project.
*
* You may obtain a copy of the LGPL License at:
*
* http://www.gnu.org/licenses/licenses.html
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "LGPL2.1".
*
* You may obtain a copy of the Apache License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "AL2.0".
*
* You can find JNA original source files at:
*
* https://github.com/java-native-access/jna
*/
package noe.common.utils.processid;
import com.sun.jna.Native;
/* https://jna.dev.java.net/ */
public interface Kernel32 extends W32API {
Kernel32 INSTANCE = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class, DEFAULT_OPTIONS);
/* http://msdn.microsoft.com/en-us/library/ms683179(VS.85).aspx */
HANDLE GetCurrentProcess();
/* http://msdn.microsoft.com/en-us/library/ms683215.aspx */
int GetProcessId(HANDLE Process);
}
| 72e01e102d7ac2cfc889a5910476afdc4a2b390c | [
"Markdown",
"TOML",
"Maven POM",
"INI",
"Java",
"Text",
"Shell"
]
| 36 | Markdown | web-servers/noe-core | d6d09892090f808e73a2ec3bc4a4fe8fe5bc0d8c | 41d6f906b9debd526212049e0a35ee2e2ba8c0b1 |
refs/heads/master | <repo_name>campGROMP/Computer_vision<file_sep>/openCV_tryout
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import cv2
cv2.__version__
# In[2]:
# importing other necessary libraries
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[3]:
# importing a test img
img = cv2.imread('D:/Users/JOHANOT/Pictures/profiel foto.jpg')
plt.imshow(img)
# image colour from matplot is different from the usual colour. We need to transform the colour from BGR to RGB
# In[4]:
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
# that's better!
# In[5]:
# In order to simplify the amount of variabels, we can reduce the image colour scheme to grayscale.
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
plt.imshow(img_gray,cmap = 'gray')
# if we want to see how the different scales from Red, Green and Blue afect the image, we can run the following code
# In[6]:
# Plot the three channels of the image
fig, axs = plt.subplots(nrows = 1, ncols = 3, figsize = (20, 20))
axs[0].set_title('R channel')
axs[1].set_title('G channel')
axs[2].set_title('B channel')
for i in range(0, 3):
ax = axs[i]
ax.imshow(img_rgb[:, :, i], cmap = 'gray')
plt.show()
# Other colour modes are also possible. HSV and HLS are more closely related to the perception of human eyes. We will try these out next.
# In[7]:
# Transform the image into HSV and HLS models
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
img_hls = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)
fig, (ax1, ax2) = plt.subplots(nrows = 1, ncols = 2, figsize = (20, 20))
ax1.imshow(img_hsv)
ax1.set_title('HSV')
ax2.imshow(img_hls)
ax2.set_title('HLS')
plt.show()
# In[8]:
# Lets try something else, lets add some stuff to an image
wol_img = cv2.imread('D:/Users/JOHANOT/Pictures/wall_of_love.png')
wol_copy = wol_img.copy()
cv2.rectangle(wol_copy, pt1 = (400, 100), pt2 = (450, 150),
color = (255, 0, 0), thickness = 5)
plt.imshow(wol_copy)
# Above we hardcoded the location of the square, we can also just draw on the image with the following code.
# In[10]:
# Step 1. Define callback function
drawing = False
ix = -1
iy = -1
def draw_rectangle(event, x, y, flags, params):
global ix, iy, drawing
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
cv2.rectangle(img_x, pt1 = (ix, iy), pt2 = (x, y),
color = (87, 184, 237), thickness = -1)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
cv2.rectangle(img_x, pt1 = (ix, iy), pt2 = (x, y),
color = (87, 184, 237), thickness = -1)
# Step 2. Call the window
img_x = cv2.imread('D:/Users/JOHANOT/Pictures/wall_of_love.png')
cv2.namedWindow(winname = 'my_drawing')
cv2.setMouseCallback('my_drawing', draw_rectangle)
# Step 3. Execution
while True:
cv2.imshow('my_drawing', img_x)
if cv2.waitKey(100)& 0xFF == 27:
break
cv2.destroyAllWindows()
# In[17]:
# In[ ]:
| fb7fff1577cc8851361c78b38afe7eb56bc11a3e | [
"Python"
]
| 1 | Python | campGROMP/Computer_vision | cbed1c33571dfdbc465fb4669e87a00fbe984b0f | a02956f001dc8b16dd3ebf1da0de004c4e5cd029 |
refs/heads/main | <repo_name>RituAgrawal1384/canvas-bdd-api-template-project<file_sep>/README.md
# tat-api-template-project
This is the template project to show how to use testautomationtools project for api automation
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.api.template</groupId>
<artifactId>canvas-bdd-api-automation-template</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>io.github.rituagrawal1384</groupId>
<artifactId>test-automation-canvas</artifactId>
<version>1.0.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
<systemPropertyVariables>
<jacoco-agent.destfile>target/jacoco.exec</jacoco-agent.destfile>
<!--suppress UnresolvedMavenProperty -->
<phantomjs.binary>${phantomjs.binary}</phantomjs.binary>
</systemPropertyVariables>
<includes>
<include>**/*CucumberRunner.java</include>
</includes>
<properties>
<!--suppress UnresolvedMavenProperty -->
<osType>${osType}</osType>
</properties>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>/src/test/java/com/api/runner/CucumberRunner.java
package com.api.runner;
import com.automation.platform.config.Configvariable;
import com.automation.platform.config.TapBeansLoad;
import com.automation.platform.filehandling.FileReaderUtil;
import com.automation.platform.reporting.TapReporting;
import com.automation.platform.selenium.SeleniumBase;
import com.github.mkolisnyk.cucumber.runner.ExtendedCucumberOptions;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import java.util.TimeZone;
@ComponentScan(basePackages = {"com.automation.platform"})
@Configuration
@ExtendedCucumberOptions(
jsonReport = "reports/cucumber/cucumber.json"
, retryCount = 3
, detailedReport = true
, detailedAggregatedReport = true
, overviewReport = true
, jsonUsageReport = "reports/cucumber-usage.json"
, usageReport = true
, toPDF = true
, outputFolder = "reports")
@CucumberOptions(
monochrome = true,
features = "classpath:features",
glue = {"com/automation/platform/tapsteps"},
tags = {"@api_test", "~@ignore"},
plugin = {"pretty",
"html:reports/cucumber/cucumber-html",
"json:reports/cucumber/cucumber.json",
"usage:reports/cucumber-usage.json",
"junit:reports/newrelic-report/cucumber-junit.xml"}
)
public class CucumberRunner extends AbstractTestNGCucumberTests {
private static final Logger LOGGER = LoggerFactory.getLogger(CucumberRunner.class);
public static ConfigurableApplicationContext context;
private Configvariable configvariable;
@BeforeSuite(alwaysRun = true)
public void setUpEnvironmentToTest() {
// write if anything needs to be set up once before tests run. e.g. connection to database
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
TapBeansLoad.setConfigClass(CucumberRunner.class);
TapBeansLoad.init();
configvariable = (Configvariable) TapBeansLoad.getBean(Configvariable.class);
LOGGER.info("Setting environment file....");
//configvariable.setupEnvironmentProperties(System.getProperty("api.env"), System.getProperty("api.lbu"));
}
@AfterSuite(alwaysRun = true)
public void cleanUp() {
// close if something enabled in @before suite. e.g. closing connection to DB
LOGGER.info("Copying and generating reports....");
String deviceFarmLogDir = System.getenv("DEVICEFARM_LOG_DIR");
TapReporting.generateReportForJsonFiles(deviceFarmLogDir);
LOGGER.info("Quiting driver if needed....");
if (SeleniumBase.driver != null) {
SeleniumBase.driver.quit();
}
FileReaderUtil.deleteFile("reports/api-test-results.pdf");
TapReporting.detailedReport("reports/cucumber/cucumber.json", "api");
}
}
| d977d68c5d4d38c070b71f675458994153f957d0 | [
"Markdown",
"Java",
"Maven POM"
]
| 3 | Markdown | RituAgrawal1384/canvas-bdd-api-template-project | 9ad41f83903b0a2f94e9c5883c45fe0335604f9b | e19fe54708ea6392583a477e8b26357fbfdea81e |
refs/heads/master | <file_sep>package microavatar.framework;
import microavatar.framework.perm.PermTestSuite;
import microavatar.framework.base.BaseTestSuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
PermTestSuite.class,
BaseTestSuite.class
})
public class TestSuite {
}
<file_sep>/***********************************************************************
* @模块: 用户业务逻辑实现
* @模块说明: 用户模块服务
***********************************************************************/
package microavatar.framework.perm.controller;
import lombok.extern.slf4j.Slf4j;
import microavatar.framework.core.mvc.BaseController;
import microavatar.framework.perm.criteria.UserCriteria;
import microavatar.framework.perm.dao.UserDao;
import microavatar.framework.perm.entity.User;
import microavatar.framework.perm.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/perm/user")
@Slf4j
public class UserController extends BaseController<UserCriteria, UserDao, User, UserService> {
@Resource
private UserService userService;
private List<Long> cache;
@Override
protected UserService getService() {
return userService;
}
//@Override
//@RequestMapping("/id/{id}")
//public User getById(@PathVariable Long id) {
// return super.getById(id);
//}
@GetMapping("/t/{loop}")
public void test(@PathVariable("loop") int loop) {
long startTime = System.currentTimeMillis();
Long start = 1000L;
cache = new ArrayList<>(loop);
int count = 0;
for (int i = 0; i < loop; i++) {
count++;
cache.add(++start);
}
long endTime = System.currentTimeMillis();
log.info("count:{},cache.size:{},loop:{},cost:{}ms", count, cache.size(), loop, endTime - startTime);
}
}<file_sep>/*===================== Table: Auth_User =====================*/
drop table if exists Auth_User;
create table Auth_User (
id varchar(36) not null,
account varchar(16),
pwd varchar(32),
createTime bigint,
name varchar(16) comment '取值为第一次登录系统时所携带的昵称
例如第一次采用微信登录,则此字段赋值为微信登录的昵称
以后次登录时,该用户采用新浪账号绑定并登录,此时本字段不变。
用户的后台个人信息页面中,显示的昵称为本字段,本字段可供用户主动修改
因“昵称”为常用字段,所以放在本类,以便业务快速获取',
status tinyint,
primary key (id)
);
alter table Auth_User comment '1:不存放基本的用户信息,与业务无关。
2:用户可以采用用户名密码、微信、新浪等方式登录或绑定账号,但是user只有一条记录,因为他们是同一个用户
3:如果业务系统需要更多userInfo里没有的用户信息,需要自己定义userExt扩展表来记录用户的信息';
/*===================== Table: Auth_UserInfo =====================*/
drop table if exists Auth_UserInfo;
create table Auth_UserInfo (
id varchar(36) not null,
userId varchar(36),
realName varchar(16),
gender tinyint,
qq varchar(16),
telephone varchar(16),
mobilePhone varchar(16),
email varchar(32),
birthday bigint,
remark varchar(4096),
primary key (id)
);
alter table Auth_UserInfo comment '用户信息实体,存放基本的用户信息';
/*===================== Table: Auth_ThirdPartyUser =====================*/
drop table if exists Auth_ThirdPartyUser;
create table Auth_ThirdPartyUser (
id varchar(36) not null,
userId varchar(36),
loginType tinyint,
accessTime bigint,
uniqueId varchar(64),
primary key (id)
);
alter table Auth_ThirdPartyUser comment '第三方系统与本系统的绑定关系';
/*===================== Table: Auth_LoginLog =====================*/
drop table if exists Auth_LoginLog;
create table Auth_LoginLog (
id varchar(36) not null,
userId varchar(36),
loginType tinyint,
clientIp varchar(16),
loginTime bigint,
logoutTime bigint,
status tinyint,
primary key (id)
);
alter table Auth_LoginLog comment '只要有登录请求,无论登录成功与否,都记录';
/*===================== Table: Auth_SysResource =====================*/
drop table if exists Auth_SysResource;
create table Auth_SysResource (
id varchar(36) not null,
parentId varchar(36),
name varchar(64),
type tinyint,
host varchar(64),
url varchar(256),
orderNum tinyint,
enabled tinyint,
remark varchar(4096),
primary key (id)
);
alter table Auth_SysResource comment '资源,包括菜单(页面)、按钮等可以访问的资源';
/*===================== Table: Auth_Role =====================*/
drop table if exists Auth_Role;
create table Auth_Role (
id varchar(36) not null,
parentId varchar(36),
name varchar(64),
errorCode varchar(64),
orderNum tinyint,
createdUserId varchar(36),
enabled tinyint,
remark varchar(4096),
primary key (id)
);
alter table Auth_Role comment '角色';
/*===================== Table: Auth_RoleSysResource =====================*/
drop table if exists Auth_RoleSysResource;
create table Auth_RoleSysResource (
id varchar(36) not null,
roleId varchar(36),
sysResourceId varchar(36),
primary key (id)
);
alter table Auth_RoleSysResource comment '角色资源关系';
/*===================== Table: Auth_UserRole =====================*/
drop table if exists Auth_UserRole;
create table Auth_UserRole (
id varchar(36) not null,
userId varchar(36),
roleId varchar(36),
primary key (id)
);
alter table Auth_UserRole comment '用户角色关系';
/*===================== Table: Auth_Org =====================*/
drop table if exists Auth_Org;
create table Auth_Org (
id varchar(36) not null,
parentId varchar(36),
name varchar(64),
abbreviation varchar(64),
address varchar(256),
contact varchar(256) comment '可以写email、固话、手机等一切联系方式',
orderNum tinyint,
createdUserId varchar(36),
enabled tinyint,
remark varchar(4096),
primary key (id)
);
alter table Auth_Org comment '组织,包括集团公司、分公司、事业群、部门、小组、分队等所有团队性质的组织';
/*===================== Table: Auth_UserOrg =====================*/
drop table if exists Auth_UserOrg;
create table Auth_UserOrg (
id varchar(36) not null,
userId varchar(36),
orgId varchar(36),
primary key (id)
);
alter table Auth_UserOrg comment '用户组织关系';
/*===================== Table: Auth_SysPermission =====================*/
drop table if exists Auth_SysPermission;
create table Auth_SysPermission (
id varchar(36) not null,
sysResourceId varchar(36),
name varchar(64),
errorCode varchar(64),
orderNum tinyint,
remark varchar(4096),
primary key (id)
);
alter table Auth_SysPermission comment '系统权限,对资源的操作权限、如对用户添加、删除、修改';
/*===================== Table: Auth_RoleSysPermission =====================*/
drop table if exists Auth_RoleSysPermission;
create table Auth_RoleSysPermission (
id varchar(36) not null,
roleId varchar(36),
sysPermissionId varchar(36),
primary key (id)
);
alter table Auth_RoleSysPermission comment '角色权限关系';
/*===================== Table: Base_Param =====================*/
drop table if exists Base_Param;
create table Base_Param (
id varchar(36) not null,
name varchar(32) comment '参数名',
type tinyint comment '参数类型。1:系统框架参数;2:业务系统参数',
keyStr varchar(64) comment '参数的key',
valueStr varchar(256) comment '参数的值',
valueType tinyint comment '值的格式
1:字符串;2:整形;3:浮点型;4:布尔
5:字符串数组;6:整形数组;7:浮点型数组;8:布尔数组',
remark varchar(256),
primary key (id)
);
alter table Base_Param comment '参数表,存放所有系统参数和业务参数';
/*===================== Table: Base_ErrorInfo =====================*/
drop table if exists Base_ErrorInfo;
create table Base_ErrorInfo (
id varchar(36) not null,
keyStr varchar(64) comment '错误代码的key',
errorCode int comment '错误代码',
errorMsg varchar(128) comment '发生错误时,具体的错误信息',
primary key (id)
);
alter table Base_ErrorInfo comment '错误信息表,存放系统所有的自定义错误信息,系统初始化时,会加载全部信息到内存';<file_sep>package microavatar.framework.core.net.tcp.coder;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import microavatar.framework.core.net.tcp.netpackage.Package;
import microavatar.framework.core.net.tcp.netpackage.item.*;
/**
* 发送数据给客户端的时,执行此类进行编码
*
* @author Rain
*/
@Slf4j
public class AvatarEncoder extends MessageToByteEncoder<Package> {
@Override
protected void encode(ChannelHandlerContext ctx, Package packageData, ByteBuf out) throws Exception {
for (Item item : packageData.getItems()) {
switch (item.getItemTypeEnum()) {
case INT:
out.writeInt(((IntItem) item).getData());
break;
case LONG:
out.writeLong(((LongItem) item).getData());
break;
case FLOAT:
out.writeFloat(((FloatItem) item).getData());
break;
case DOUBLE:
out.writeDouble(((DoubleItem) item).getData());
break;
case BOOLEAN:
out.writeBoolean(((BooleanItem) item).isData());
break;
case BYTE_ARRAY:
out.writeBytes(((ByteArrayItem) item).getData());
break;
default:
log.error("未实现类型为{}的编码器!", item.getItemTypeEnum());
break;
}
}
}
}
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<groupId>microavatar.framework</groupId>
<artifactId>parent</artifactId>
<version>1.0.0</version>
<name>parent</name>
<packaging>pom</packaging>
<modules>
<!-- 基础组件,供上层服务依赖 -->
<module>common-protobuf</module>
<!-- 核心组件,供上层服务依赖 -->
<module>core</module>
<module>core-net-tcp</module>
<module>core-cache</module>
<module>core-mvc</module>
<module>core-database</module>
<module>core-database-listener</module>
<module>core-mq</module>
<!-- 应用组件 -->
<module>perm-api</module>
<!-- 基础服务,端口80xx -->
<module>server-base-eureka</module><!-- 8001 -->
<module>server-base-config</module><!-- 8011 -->
<!-- 应用服务,端口81xx -->
<module>tcp-gateway</module><!-- 8131 8132 -->
<module>tcp-test</module>
<module>im</module><!-- 8101 8102-->
<module>order</module><!-- 8111-->
<module>goods</module><!-- 8121-->
<module>perm</module><!-- 8131 8132-->
</modules>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<hutool.version>4.0.9</hutool.version>
<rocketmq.version>4.1.0-incubating</rocketmq.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- microavatar.framework 系列 -->
<dependency>
<groupId>microavatar.framework</groupId>
<artifactId>common-protobuf</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>microavatar.framework</groupId>
<artifactId>core</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>microavatar.framework</groupId>
<artifactId>core-net-tcp</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>microavatar.framework</groupId>
<artifactId>core-database</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>microavatar.framework</groupId>
<artifactId>core-mvc</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>microavatar.framework</groupId>
<artifactId>core-database-listener</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>microavatar.framework</groupId>
<artifactId>core-mq</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>microavatar.framework</groupId>
<artifactId>perm-api</artifactId>
<version>1.0.0</version>
</dependency>
<!-- spring cloud 指定spring cloud 的版本,让子项目引用 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- rocketmq -->
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>${rocketmq.version}</version>
</dependency>
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-common</artifactId>
<version>${rocketmq.version}</version>
</dependency>
<!-- 数据库 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.36</version>
</dependency>
<!-- protobuf -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.6.1</version>
<!--<version>2.4.1</version>-->
</dependency>
<!-- protobuf与json转换-->
<dependency>
<groupId>com.googlecode.protobuf-java-format</groupId>
<artifactId>protobuf-java-format</artifactId>
<version>1.2</version>
</dependency>
<!-- netty -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.15.Final</version>
</dependency>
<!-- 工具类 -->
<!--<dependency>-->
<!--<groupId>org.apache.commons</groupId>-->
<!--<artifactId>commons-lang3</artifactId>-->
<!--<version>3.5</version>-->
<!--</dependency>-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>${hutool.version}</version>
</dependency>
<!-- alibaba canal-->
<dependency>
<groupId>com.alibaba.otter</groupId>
<artifactId>canal.client</artifactId>
<version>1.0.25</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!--
绝大部分的服务都需要依赖的jar包,可以配置这里,达到全局通用的效果
工具类、数据库连接等jar,不应该放到这里,因为有些服务不需要,例如服务注册与发现中心。
如果把这些不需要的jar也放到这里,则在服务打包时,会把这些不需要的jar也打包了,造成服务的jar包臃肿。
-->
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-devtools</artifactId>-->
<!--<optional>true</optional>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-dependencies</artifactId>-->
<!--<version>1.5.6.RELEASE</version>-->
<!--<type>pom</type>-->
<!--<scope>import</scope>-->
<!--</dependency>-->
<!-- 日志 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-maven-plugin</artifactId>
<version>1.16.18.1</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>delombok</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<proc>none</proc>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep> ## 核心包
数据库连接池<file_sep>package microavatar.framework.core.mq.rocketmq;
import lombok.extern.slf4j.Slf4j;
import microavatar.framework.core.mq.rocketmq.property.RocketmqProperties;
import microavatar.framework.core.mq.rocketmq.property.Subscription;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.ServiceState;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import static microavatar.framework.core.mq.rocketmq.property.RocketmqProperties.PREFIX;
@Configuration
@EnableConfigurationProperties(RocketmqProperties.class)
@ConditionalOnProperty(prefix = PREFIX, value = "namesrvAddr")
@Slf4j
public class RocketmqAutoConfiguration implements ApplicationListener<ContextRefreshedEvent> {
@Resource
private RocketmqProperties properties;
@Resource
private ApplicationEventPublisher publisher;
private DefaultMQPushConsumer consumer;
/**
* 初始化向rocketmq发送普通消息的生产者
*/
@Bean
@ConditionalOnProperty(prefix = PREFIX, value = "producer.instanceName")
public DefaultMQProducer defaultProducer() throws MQClientException {
/*
* 一个应用创建一个Producer,由应用来维护此对象,可以设置为全局对象或者单例
* 注意:ProducerGroupName需要由应用来保证唯一
* ProducerGroup这个概念发送普通的消息时,作用不大,但是发送分布式事务消息时,比较关键,
* 因为服务器会回查这个Group下的任意一个Producer
*/
DefaultMQProducer producer = new DefaultMQProducer(properties.getProducerGroupName());
producer.setNamesrvAddr(properties.getNamesrvAddr());
producer.setVipChannelEnabled(false);
/*
* Producer对象在使用之前必须要调用start初始化,初始化一次即可<br>
* 注意:切记不可以在每次发送消息时,都调用start方法
*/
producer.start();
log.info("RocketMq defaultProducer 已启动。");
Message msg = new Message("p2pMessage",
"tagP2P",
"key1",
("Hello p2p").getBytes());
try {
SendResult sendResult = producer.send(msg);
} catch (Exception e) {
log.error("RocketMq defaultProducer 发送消息失败。{}", e.getMessage(), e);
}
Message msg2 = new Message("p2gMessage", ("Hello p2g").getBytes());
try {
SendResult sendResult = producer.send(msg2);
} catch (Exception e) {
log.error("RocketMq defaultProducer 发送消息失败。{}", e.getMessage(), e);
}
return producer;
}
/**
* 初始化向rocketmq发送事务消息的生产者
*/
@Bean
@ConditionalOnProperty(prefix = PREFIX, value = "producer.tranInstanceName")
public TransactionMQProducer transactionProducer() throws MQClientException {
/*
* 一个应用创建一个Producer,由应用来维护此对象,可以设置为全局对象或者单例
* 注意:ProducerGroupName需要由应用来保证唯一
* ProducerGroup这个概念发送普通的消息时,作用不大,但是发送分布式事务消息时,比较关键,
* 因为服务器会回查这个Group下的任意一个Producer
*/
TransactionMQProducer producer = new TransactionMQProducer(properties.getProducerGroupName() + "Tran");
producer.setNamesrvAddr(properties.getNamesrvAddr());
// 事务回查最小并发数
producer.setCheckThreadPoolMinSize(2);
// 事务回查最大并发数
producer.setCheckThreadPoolMaxSize(2);
// 队列数
producer.setCheckRequestHoldMax(2000);
// 由于社区版本的服务器阉割调了消息回查的功能,所以这个地方没有意义
//TransactionCheckListener transactionCheckListener = new TransactionCheckListenerImpl();
//producer.setTransactionCheckListener(transactionCheckListener);
/*
* Producer对象在使用之前必须要调用start初始化,初始化一次即可
* 注意:切记不可以在每次发送消息时,都调用start方法
*/
producer.start();
log.info("RocketMq TransactionMQProducer 已启动。");
// Message msg = new Message("sendMsgToUser",// topic
// "TagA",// tag
// "OrderID001",// key
// ("Hello MetaQA").getBytes());// body
// try {
// SendResult sendResult = producer.send(msg);
// } catch (Exception e) {
// log.error("RocketMq TransactionMQProducer 启动失败。{}", e.getMessage(), e);
// }
return producer;
}
/**
* 初始化rocketmq消息监听方式的消费者
*/
@Bean
@ConditionalOnProperty(prefix = PREFIX, value = "consumer.instanceName")
public DefaultMQPushConsumer pushConsumer() throws MQClientException {
/*
* 一个应用创建一个Consumer,由应用来维护此对象,可以设置为全局对象或者单例
* 注意:ConsumerGroupName需要由应用来保证唯一
*/
consumer = new DefaultMQPushConsumer(properties.getConsumerGroupName());
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
consumer.setNamesrvAddr(properties.getNamesrvAddr());
consumer.setConsumeMessageBatchMaxSize(1);//设置批量消费,以提升消费吞吐量,默认是1
/*
* 订阅指定topic下tags
*/
Map<String, Subscription> subscriptions = properties.getConsumer().getSubscriptions();
subscriptions.forEach((k, v) -> {
try {
consumer.subscribe(v.getTopic(), (v.getTag() == null || v.getTag().length() == 0) ? "*" : v.getTag());
} catch (MQClientException e) {
log.error(e.getMessage(), e);
}
});
consumer.registerMessageListener((List<MessageExt> msgs, ConsumeConcurrentlyContext context) -> {
// 默认msgs里只有一条消息,可以通过设置consumeMessageBatchMaxSize参数来批量接收消息
log.debug("接受到rocketmq消息:size={}", msgs.size());
for (MessageExt msg : msgs) {
try {
// 发布消息到达的事件,以便分发到每个tag的监听方法
log.debug("发布rocketmq消息:topic[{}],tags[{}]", msg.getTopic(), msg.getTags());
this.publisher.publishEvent(new RocketmqEvent(msg, consumer));
} catch (Exception e) {
log.error("处理rocketmq消息失败:topic[{}],tags[{}],{}", msg.getTopic(), msg.getTags(), e.getMessage(), e);
if (msg.getReconsumeTimes() <= 3) {//重复消费3次
log.error("等待重新消费消息,重试次数:{}", msg.getReconsumeTimes());
return ConsumeConcurrentlyStatus.RECONSUME_LATER;
}
}
}
//如果没有return success,consumer会重复消费此信息,直到success。
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
});
return consumer;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (consumer != null && consumer.getDefaultMQPushConsumerImpl().getServiceState() == ServiceState.CREATE_JUST) {
try {
/*
* Consumer对象在使用之前必须要调用start初始化,初始化一次即可
* 等待spring事件监听相关程序初始化完成,才调用start,否则,会出现对RocketMQ的消息进行消费后立即发布消息到达的事件,
* 然而此事件的监听程序还未初始化,从而造成消息的丢失
*/
consumer.start();
log.info("RocketMq consumer 已启动。");
} catch (MQClientException e) {
log.error("RocketMq consumer 启动失败。{}", e.getMessage(), e);
}
}
}
}
<file_sep>package microavatar.framework.core.mvc;
import cn.hutool.core.util.RandomUtil;
import lombok.Getter;
import lombok.Setter;
import microavatar.framework.core.support.sequence.impl.LongSequence;
import org.apache.commons.lang.math.RandomUtils;
import java.io.Serializable;
/**
* @author rain
*/
@Getter
@Setter
public abstract class BaseEntity<E> implements Serializable {
// 数据库字段名
public static final String ID = "id";
public static final String CREATE_TIME = "create_time";
public static final String MODIFY_TIME = "modify_time";
public static final String DELETED = "is_deleted";
/**
* 主键 id
*
* @dbColumnName id
* @dbColumnType bigint(20)
*/
protected Long id;
/**
* 创建时间戳
*
* @dbColumnName create_time
* @dbColumnType bigint(20)
*/
protected Long createTime;
/**
* 最后修改时间戳
* insert、update时,需要设置为系统当前时间戳
*
* @dbColumnName modify_time
* @dbColumnType bigint(20)
*/
protected Long modifyTime;
/**
* 是否删除
*
* @dbColumnName is_deleted
* @dbColumnType tinyint(1)
*/
protected Boolean deleted;
/**
* 生成随机的entity
* 所有字段都随机赋值
*/
abstract public E randomEntity();
protected void randomBaseEntity() {
this.computeIdIfAbsent();
this.createTime = System.currentTimeMillis();
this.modifyTime = System.currentTimeMillis();
this.deleted = randomBoolean();
}
public void computeIdIfAbsent() {
if (this.id == null) {
this.id = LongSequence.get();
}
}
protected String randomString() {
return RandomUtil.randomString(6);
}
protected Byte randomByte() {
return (byte) RandomUtil.randomInt(Byte.MAX_VALUE);
}
protected Boolean randomBoolean() {
return RandomUtils.nextBoolean();
}
protected Integer randomInteger() {
return RandomUtil.randomInt();
}
protected Long randomLong() {
return RandomUtil.randomLong();
}
@Override
public String toString() {
return "{\"BaseEntity\":{"
+ "\"id\":\"" + id + "\""
+ ", \"createTime\":\"" + createTime + "\""
+ ", \"modifyTime\":\"" + modifyTime + "\""
+ ", \"deleted\":\"" + deleted + "\""
+ "}}";
}
}
<file_sep>package microavatar.framework.core.cache;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* 启动avatarCache功能的条件
*/
public class StarterCacheCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), "spring.cache.");
String env = resolver.getProperty("custom-type");
if (env == null) {
return false;
}
return "avatarCache".equalsIgnoreCase(env.toLowerCase());
}
}
<file_sep> ## 核心包-网络框架-tcp<file_sep>```
-Xms64M -Xmx256M -XX:MetaspaceSize=64M -XX:MaxMetaspaceSize=128M -Dspring.profiles.active=dev1
```
蓝色(blue)在汉英语言中都是天空和海洋的颜色,并且给人以高远、宁静、博大、深邃、宽容的感觉。
首先我们看bigint, MySQL的整型类型有这样几种:
类型 占用字节
tinyint 1
smallint 2
mediumint 3
int 4
bigint 8
这是决定存储需要占用多少字节,那么后边的数字(M)代表什么意思呢
tinyint(M), M默认为4;
SMALLINT(M), M默认为6;
MEDIUMINT(M), M默认为9;
INT(M),M默认为11;
BIGINT(M),M默认为20.<file_sep>#### 权限服务,提供用户、部门、角色、菜单等数据给上层系统
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>microavatar.framework</groupId>
<artifactId>parent</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>core-cache</artifactId>
<name>core-cache</name>
<version>1.0.0</version>
<dependencies>
<!-- core -->
<dependency>
<groupId>microavatar.framework</groupId>
<artifactId>core</artifactId>
</dependency>
<!-- 缓存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
</dependencies>
</project><file_sep>### http请求中,token存放的地方
- header:token=xxx
- queryParam:token=xxx
### tcp请求中,token存放的地方
- header:token=xxx<file_sep> ## 核心包
放置工具类、数据库连接池、缓存、网络框架等核心类,供其他服务依赖<file_sep>package microavatar.framework.core.cache.redis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.core.RedisOperations;
import javax.cache.event.EventType;
/**
* l2级缓存
*/
@Slf4j
public class L2RedisCache extends RedisCache {
/**
* l1级缓存管理器
*/
private CacheManager l1CacheManager;
/**
* l2级缓存管理器
*/
private L2RedisCacheManager l2RedisCacheManager;
/**
* 构造方法
*
* @param l2RedisCacheManager l2级缓存管理器
* @param l1CacheManager l1级缓存管理器
* @param cacheName 缓存名称
* @param prefix 前缀
* @param redisOperations redis操作类
* @param expiration 过期时间
*/
L2RedisCache(CacheManager l1CacheManager,
L2RedisCacheManager l2RedisCacheManager,
String cacheName,
byte[] prefix,
RedisOperations<? extends Object, ? extends Object> redisOperations,
long expiration) {
super(cacheName, prefix, redisOperations, expiration);
this.l2RedisCacheManager = l2RedisCacheManager;
this.l1CacheManager = l1CacheManager;
}
@Override
public ValueWrapper get(Object key) {
if (key == null) {
return null;
}
String cacheName = super.getName();
Cache l1Cache = l1CacheManager.getCache(cacheName);
log.debug("get,l1CacheManager:{}", l1CacheManager);
log.debug("get,cacheName:{}", cacheName);
log.debug("get,l1Cache:{}", l1Cache);
ValueWrapper valueWrapper = null;
if (l1Cache == null) {
log.warn("没有配置缓存名称为[]的L1缓存。", cacheName);
} else {
valueWrapper = l1Cache.get(key);
}
Object value = null;
if (log.isDebugEnabled()) {
if (valueWrapper != null && valueWrapper.get() != null) {
value = valueWrapper.get();
}
log.debug("获取L1缓存: key: {}, value: {}", key, value);
}
if (valueWrapper == null) {
valueWrapper = super.get(key);
if (valueWrapper != null && valueWrapper.get() != null) {
value = valueWrapper.get();
}
if (log.isDebugEnabled()) {
log.debug("获取L2缓存: key: {}, value: {}", key, value);
}
if (l1Cache != null && value != null) {
l1Cache.put(key, valueWrapper.get());
}
}
return valueWrapper;
}
@Override
public void put(final Object key, final Object value) {
if (key == null || value == null) {
return;
}
String cacheName = super.getName();
Cache l1Cache = l1CacheManager.getCache(cacheName);
if (l1Cache != null) {
l1Cache.put(key, value);
}
super.put(key, value);
l2RedisCacheManager.onCacheChanged(EventType.CREATED, super.getName(), key);
}
@Override
public void evict(Object key) {
String cacheName = super.getName();
Cache l1Cache = l1CacheManager.getCache(cacheName);
if (l1Cache != null) {
l1Cache.evict(key);
}
super.evict(key);
l2RedisCacheManager.onCacheChanged(EventType.REMOVED, super.getName(), key);
}
@Override
public ValueWrapper putIfAbsent(Object key, final Object value) {
if (key == null || value == null) {
return null;
}
String cacheName = super.getName();
Cache l1Cache = l1CacheManager.getCache(cacheName);
if (l1Cache != null) {
l1Cache.putIfAbsent(key, value);
}
ValueWrapper wrapper = super.putIfAbsent(key, value);
l2RedisCacheManager.onCacheChanged(EventType.CREATED, super.getName(), key);
return wrapper;
}
@Override
public void clear() {
super.clear();
l2RedisCacheManager.onCacheChanged(EventType.REMOVED, super.getName(), "");
}
}
<file_sep>package microavatar.framework.security.filter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
@Component
public class AvatarInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource, InitializingBean {
/**
* key: RequestMatcher,可以理解为url
* value: 角色集合
*/
private static Map<RequestMatcher, Collection<ConfigAttribute>> resourceMap = null;
private Collection<ConfigAttribute> allAttribute = new HashSet<>();
/**
* 加载url资源和角色
*/
private void loadResources() {
//List<Role> roles = new ArrayList<>();
//List<SysResource> resources = new ArrayList<>();
//List<RoleResource> roleResources = new ArrayList<>();
//resourceMap = new HashMap<>(roles.size());
resourceMap = new HashMap<>();
RequestMatcher matcher = new AntPathRequestMatcher("/auth/test");
Collection<ConfigAttribute> configAttributes = new ArrayList<>(2);
resourceMap.put(matcher, configAttributes);
}
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
HttpServletRequest request = ((FilterInvocation) object).getRequest();
Collection<ConfigAttribute> matchAttributes = new HashSet<>();
for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : resourceMap.entrySet()) {
if (entry.getKey().matches(request)) {
matchAttributes.addAll(entry.getValue());
}
}
if (matchAttributes.size() > 0) {
return new ArrayList<>(matchAttributes);
}
return Collections.emptyList();
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public boolean supports(Class<?> clazz) {
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
loadResources();
}
}
<file_sep>package microavatar.framework.core.net.tcp.netpackage.item;
import lombok.*;
import microavatar.framework.core.net.tcp.netpackage.ItemTypeEnum;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BooleanItem implements Item {
/**
* 选项类型
*/
private static final ItemTypeEnum ITEM_TYPE_ENUM = ItemTypeEnum.BOOLEAN;
/**
* 选项名称
*/
private String name;
/**
* 选项数据
*/
private boolean data;
public static BooleanItem emptyItem(String name) {
return new BooleanItemBuilder()
.name(name)
.build();
}
@Override
public ItemTypeEnum getItemTypeEnum() {
return ITEM_TYPE_ENUM;
}
}<file_sep>package microavatar.framework.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.Filter;
/**
* @author Administrator
*/
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource(name = "avatarAuthenticationProvider")
private AuthenticationProvider authenticationProvider;
@Resource(name = "avatarFilterSecurityInterceptor")
private Filter avatarFilterSecurityInterceptor;
@Override
protected void configure(HttpSecurity http) throws Exception {
/*
logoutSuccessUrl(String logoutSuccessUrl):
The URL to redirect to after logout has occurred. The default is /login?logout
*/
http
.addFilterBefore(avatarFilterSecurityInterceptor, FilterSecurityInterceptor.class)
.authorizeRequests().antMatchers("/", "/static/**", "/js/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/auth/login")
.successHandler(new LoginSuccessHandler()).failureHandler(new LoginFailureHandler()).permitAll()
.and()
.logout().logoutSuccessUrl("/auth/logout").permitAll()
;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
}
<file_sep>#### 配置中心服务
<file_sep>package microavatar.framework.core.net.tcp;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* 启动TcpServer的条件
*/
public class TcpServerCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), "avatar.tcpServer.");
String env = resolver.getProperty("enable");
if (env == null) {
return false;
}
return "true".equalsIgnoreCase(env.toLowerCase());
}
}
<file_sep>package microavatar.framework.core.database.listener;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry.*;
import com.alibaba.otter.canal.protocol.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
// @Component
@Slf4j
public class CanalClient implements ApplicationListener<ContextRefreshedEvent>, DisposableBean {
@Value("${canal.server.ip:192.168.0.31}")
private String canalServerIp;
@Value("${canal.server.port:11111}")
private int canalServerPort;
/**
* 支持正则表达式
* 1. 所有表:.* or .*\\..*
* 2. canal schema下所有表: canal\\..*
* 3. canal下的以canal打头的表:canal\\.canal.*
* 4. canal schema下的一张表:canal.test1
* 5. 多个规则组合使用:canal\\..*,mysql.test1,mysql.test2 (逗号分隔)
* 6 匹配多个类似库: canal_.*\\..*
*/
@Value("${canal.server.subscribe:.*}")
private String subscribe;
/**
* 断线重连相隔时间,毫秒
*/
@Value("${canal.client.reconnectMills:5000}")
private int reconnectMills;
/**
* 向canal服务器获取一次事件的相隔时间,毫秒
*/
@Value("${canal.client.periodMills:1000}")
private long periodMills;
private ExecutorService executor = Executors.newSingleThreadExecutor();
private CanalConnector connector;
@Resource
private ApplicationEventPublisher applicationEventPublisher;
private boolean isStart = false;
private void start() {
executor.submit(new CanalClientRunnable());
}
@Override
public void destroy() throws Exception {
System.out.println("===============destroy");
if (connector != null) {
connector.disconnect();
}
}
private void loopGetMessage() {
int batchSize = 10000;
while (true) {
Message message = connector.getWithoutAck(batchSize, periodMills, TimeUnit.MILLISECONDS);
long batchId = message.getId();
int size = message.getEntries().size();
log.trace("接受到{}条数据库事件,batchId:{}", size, batchId);
try {
if (batchId != -1 && size > 0) {
processEntries(message.getEntries());
}
// 提交确认
connector.ack(batchId);
} catch (Exception e) {
// 处理失败, 回滚数据
connector.rollback(batchId);
log.error(e.getMessage(), e);
}
}
}
private void processEntries(List<Entry> entries) {
for (Entry entry : entries) {
// 过滤事务开始与结束的事件
if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND) {
continue;
}
RowChange rowChange = null;
try {
rowChange = RowChange.parseFrom(entry.getStoreValue());
} catch (Exception e) {
throw new RuntimeException("解析bonlog事件错误 , data:" + entry.toString(), e);
}
EventType eventType = rowChange.getEventType();
String schemaName = entry.getHeader().getSchemaName();
String tableName = entry.getHeader().getTableName();
if (log.isTraceEnabled()) {
log.trace(formatEventDetail(eventType, entry, rowChange));
}
}
}
private String formatEventDetail(EventType eventType, Entry entry, RowChange rowChange) {
StringBuilder sb = new StringBuilder();
sb.append("================> binlog[").append(entry.getHeader().getLogfileName())
.append(":")
.append(entry.getHeader().getLogfileOffset())
.append("] , name[")
.append(entry.getHeader().getSchemaName())
.append(",")
.append(entry.getHeader().getTableName())
.append("] , eventType : ")
.append(eventType);
for (RowData rowData : rowChange.getRowDatasList()) {
if (eventType == EventType.DELETE) {
for (Column column : rowData.getBeforeColumnsList()) {
sb.append("\n").append(column.getName()).append(": ").append(column.getValue()).append(" update=").append(column.getUpdated());
}
} else if (eventType == EventType.INSERT) {
for (Column column : rowData.getAfterColumnsList()) {
sb.append("\n").append(column.getName()).append(": ").append(column.getValue()).append(" update=").append(column.getUpdated());
}
} else {
sb.append("\n").append("-------> before");
for (Column column : rowData.getBeforeColumnsList()) {
sb.append("\n").append(column.getName()).append(": ").append(column.getValue()).append(" update=").append(column.getUpdated());
}
System.out.println();
sb.append("\n").append("-------> after");
for (Column column : rowData.getAfterColumnsList()) {
sb.append("\n").append(column.getName()).append(": ").append(column.getValue()).append(" update=").append(column.getUpdated());
}
}
}
return sb.toString();
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (!this.isStart) {
this.isStart = true;
start();
}
}
private class CanalClientRunnable implements Runnable {
@Override
public void run() {
// 创建链接
connector = CanalConnectors.newSingleConnector(
new InetSocketAddress(canalServerIp, canalServerPort), "example", "", "");
Runtime.getRuntime().addShutdownHook(new Thread(connector::disconnect));
log.info("正在连接canalServer:{}:{},subscribe:{}", canalServerIp, canalServerPort, subscribe);
try {
connector.connect();
connector.subscribe(subscribe);
connector.rollback();
log.info("canalClient启动成功,正在监听的canalServerIp:{}:{}", canalServerIp, canalServerPort);
loopGetMessage();
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
connector.disconnect();
}
log.info("连接canalServer:{}:{} 失败,{}毫秒后重试", canalServerIp, canalServerPort, reconnectMills);
try {
Thread.sleep(reconnectMills);
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
}
// 此处应该提交新任务,而不能用死循环的方式来重连,因为采用死循环重连方案,以后用了热更技术,就会有越来越多的runnable执行死循环
executor.submit(new CanalClientRunnable());
}
}
}
<file_sep>package microavatar.framework.core.cache.redis;
import lombok.extern.slf4j.Slf4j;
import microavatar.framework.core.cache.CacheConfig;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCachePrefix;
import org.springframework.data.redis.core.RedisOperations;
import javax.cache.event.EventType;
/**
* l2级缓存管理器
*/
@Slf4j
public class L2RedisCacheManager extends RedisCacheManager {
/**
* 系统启动时的缓存配置
*/
private CacheConfig cacheConfig;
/**
* l1级缓存管理器
*/
private CacheManager l1CacheManager;
/**
* 构造方法
*
* @param redisOperations redis操作类
* @param l1CacheManager l1级缓存管理器
* @param cacheConfig 缓存配置
*/
public L2RedisCacheManager(CacheConfig cacheConfig,
CacheManager l1CacheManager,
RedisOperations redisOperations,
RedisCachePrefix redisCachePrefix) {
super(redisOperations);
this.cacheConfig = cacheConfig;
this.l1CacheManager = l1CacheManager;
setUsePrefix(true);
setCachePrefix(redisCachePrefix);
}
/**
* 创建一个缓存
*
* @param cacheName 缓存名称
* @return RedisCache
*/
@SuppressWarnings("unchecked")
@Override
protected RedisCache createCache(String cacheName) {
long expiration = computeExpiration(cacheName);
return new L2RedisCache(
l1CacheManager,
this,
cacheName,
(this.isUsePrefix() ? this.getCachePrefix().prefix(cacheName) : null),
this.getRedisOperations(),
expiration);
}
/**
* 当缓存发生变化时,调用此方法
*
* @param cacheName 缓存名称
* @param key key
*/
public void onCacheChanged(EventType eventType, String cacheName, Object key) {
/*
redis缓存发生变化时,则发布一条消息:
topic格式: ${spring.application.name}-cache
内容格式: cacheName:EventType:key
EventType为javax.cache.event.EventType的枚举值
*/
String topicName;
if (EventType.CREATED == eventType) {
topicName = cacheConfig.getCreateEventTopic();
} else if (EventType.REMOVED == eventType) {
topicName = cacheConfig.getRemoveEventTopic();
} else {
log.warn("l2缓存发生变化,未捕捉名称为{}的事件,将不会通知其他进程进行缓存更新!", eventType);
return;
}
String message = new StringBuilder()
.append(cacheName)
.append(((AvatarRedisCachePrefix) this.getCachePrefix()).getDelimiter())
.append(key.toString())
.toString();
this.getRedisOperations().convertAndSend(topicName, message);
log.debug("l2缓存发生变化,已发出名称为{}的事件,通知其他进程进行缓存更新!", eventType);
}
public AvatarRedisCachePrefix getL2RedisCachePrefix() {
return (AvatarRedisCachePrefix) this.getCachePrefix();
}
}<file_sep>package microavatar.framework.core.net.tcp.request;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import microavatar.framework.core.net.tcp.netpackage.Package;
import microavatar.framework.core.net.tcp.session.Session;
/**
* 一个网络包请求就是一个系统的事件.类似一个task任务
*
* @author Rain
*/
@Slf4j
public class Request<P extends Package, S extends Session> {
@Getter
private final P packageData;
@Getter
private final S session;
public Request(P packageData, S session) {
this.packageData = packageData;
this.session = session;
}
}
<file_sep>package microavatar.framework;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.ConfigurableApplicationContext;
/*
SpringCLoud中的“Discovery Service”有多种实现,比如:eureka, consul, zookeeper。
1,@EnableDiscoveryClient注解是基于spring-cloud-commons依赖,并且在classpath中实现;
2,@EnableEurekaClient注解是基于spring-cloud-netflix依赖,只能为eureka作用;
*/
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class GoodsApplication {
//启动服务时,开启debug日志模式:java -jar xxx.jar --debug
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext run = new SpringApplicationBuilder(GoodsApplication.class)
.web(true)
.run(args);
}
}
<file_sep>package microavatar.framework.im.controller;
import microavatar.framework.im.model.TestInput;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/test")
public class TestController {
@RequestMapping(path = "/hello")
public String hello(@RequestBody TestInput testInput) {
System.out.println(testInput.toString());
System.out.println("imServer: allMethod /test/hello");
return "{\"status\":true}";
}
@RequestMapping(value = "/hello/{toUserId}", method = RequestMethod.POST)
public String hello1(@PathVariable("toUserId") Integer toUserId) {
System.out.println("toUserId:" + toUserId);
System.out.println("imServer: GET /test/hello1");
return "imServer: GET /test/hello1";
}
}
<file_sep>package microavatar.framework.security;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Administrator
*/
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
response.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
System.out.println("LoginSuccessHandler");
response.getWriter().write("{\"hello你好,登录成功\":2}");
}
}
<file_sep>/***********************************************************************
* @模块: 用户
* @模块说明: 用户模块数据库操作
***********************************************************************/
package microavatar.framework.perm.dao;
import microavatar.framework.perm.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserDaoExt {
User getByAccount(String account);
}<file_sep>/***********************************************************************
* @模块: 用户业务逻辑实现
* @模块说明: 用户模块服务
***********************************************************************/
package microavatar.framework.perm.service;
import microavatar.framework.core.mvc.BaseService;
import microavatar.framework.perm.criteria.UserCriteria;
import microavatar.framework.perm.entity.User;
import microavatar.framework.perm.dao.UserDao;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class UserService extends BaseService<UserCriteria, UserDao, User> {
@Resource
private UserDao userDao;
@Override
protected UserDao getDao() {
return userDao;
}
}<file_sep>package microavatar.framework.perm.fegin;
import microavatar.framework.perm.entity.User;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author Administrator
*/
@FeignClient(name = "avatar-perm", fallback = UserFegin.UserFallback.class)
public interface UserFegin {
@RequestMapping("/perm/user/name/{name}")
User getByName(@PathVariable(value = "name") String name);
@Component
class UserFallback implements UserFegin {
@Override
public User getByName(String name) {
return null;
}
}
}
<file_sep>package microavatar.framework.core.mq.rocketmq.property;
public class Producer {
private String instanceName;
public String getInstanceName() {
return instanceName;
}
public void setInstanceName(String instanceName) {
this.instanceName = instanceName;
}
}
<file_sep>package microavatar.framework.index;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author Administrator
*/
@Controller()
@RequestMapping("/")
public class IndexController {
@GetMapping("/")
public String index() {
return "index";
}
@ResponseBody
@GetMapping("test")
public String test(){
return "test";
}
}
<file_sep>package microavatar.framework.core.mvc;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
/**
* @author rain
*/
public abstract class BaseController<
C extends BaseCriteria,
D extends BaseDao<C, E>,
E extends BaseEntity,
S extends BaseService<C, D, E>> {
protected abstract S getService();
@PostMapping("")
public int add(@RequestBody @Valid E entity) {
return getService().add(entity);
}
@PostMapping("/batch")
public int batchAdd(@RequestBody ArrayList<E> entitys) {
return getService().batchAdd(entitys);
}
@DeleteMapping("/hard/{id}")
public int hardDeleteById(@PathVariable Long id) {
return getService().hardDeleteById(id);
}
@DeleteMapping("/hard/batch")
public int hardDeleteByIds(@RequestBody HashSet<Long> ids) {
return getService().hardDeleteByIds(ids);
}
@DeleteMapping("/{id}")
public int softDeleteById(@PathVariable Long id) {
return getService().softDeleteById(id);
}
@DeleteMapping("/batch")
public int softDeleteByIds(@RequestBody HashSet<Long> ids) {
return getService().softDeleteByIds(ids);
}
@PutMapping("/allColumns")
public int updateAllColumnsById(@RequestBody @Valid E entity) {
return getService().updateAllColumnsById(entity);
}
@PutMapping("")
public int updateExcludeNullFieldsById(@RequestBody @Valid E entity) {
return getService().updateExcludeNullFieldsById(entity);
}
@PutMapping("/allColumns/criteria")
public int updateAllColumnsByCriteria(@Valid E entity, C criteria) {
return getService().updateAllColumnsByCriteria(entity, criteria);
}
@PutMapping("/criteria")
public int updateExcludeNullFieldsByCriteria(@RequestBody @Valid E entity, @RequestBody C criteria) {
return getService().updateExcludeNullFieldsByCriteria(entity, criteria);
}
@GetMapping("/{id}")
public E getById(@PathVariable Long id) {
return getService().getById(id);
}
@PostMapping("/criteria")
public List<E> findByCriteria(@RequestBody C criteria) {
return getService().findByCriteria(criteria);
}
@PostMapping("/count/criteria")
public long countByCriteria(@RequestBody C criteria) {
return getService().countByCriteria(criteria);
}
@GetMapping("/all")
public List<E> findAll() {
return getService().findAll();
}
@GetMapping("/count/all")
public long countAll() {
return getService().countAll();
}
}
<file_sep>package microavatar.framework.core.net.tcp.netpackage.impl;
import com.google.protobuf.ByteString;
import lombok.extern.slf4j.Slf4j;
import microavatar.framework.base.protobuf.Base;
import microavatar.framework.core.net.tcp.netpackage.Package;
import microavatar.framework.core.net.tcp.netpackage.item.ByteArrayItem;
import microavatar.framework.core.net.tcp.netpackage.item.IntItem;
import microavatar.framework.core.net.tcp.request.Request;
import microavatar.framework.core.net.tcp.request.RequestHandler;
import microavatar.framework.core.serialization.SerializationMode;
import microavatar.framework.core.serialization.Serializer;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* blue请求处理器
*
* @author Rain
*/
@Component
@Slf4j
public class BlueRequestHandler implements RequestHandler {
private Map<SerializationMode, Serializer<String, Object>> serializers;
@Resource
@LoadBalanced
private RestTemplate restTemplate;
@Override
public boolean supports(Request request) {
return request.getPackageData() instanceof BluePackage;
}
@Override
public void handle(Request request) throws Exception {
Package packageData = request.getPackageData();
BluePackage httpPackage = (BluePackage) packageData;
// 获取请求类型
BluePackage.HttpMethodEnum httpMethod = getHttpMethod(httpPackage);
// 获取请求url
String url = getUrlString(httpPackage);
if (url == null || url.length() == 0) {
log.error("请求的url字符串为空,跳过请求!");
// todo 发送消息给客户端
return;
}
String result = "";
switch (httpMethod) {
case GET:
result = doGet(url);
break;
case PUT:
String putBody = getBodyStr(httpPackage);
result = doPut(url, putBody);
break;
case POST:
String postBody = getBodyStr(httpPackage);
result = doPost(url, postBody);
break;
case DELETE:
break;
default:
throw new RuntimeException("HttpMethodEnum 错误,请检查改值!");
}
log.debug("restTemplate执行结果:{}", result);
}
private String doPut(String url, String body) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON.toString());
HttpEntity<String> formEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> resp = restTemplate.exchange(url, HttpMethod.PUT, formEntity, String.class);
return resp.getBody();
}
private String doPost(String url, String body) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON.toString());
HttpEntity<String> formEntity = new HttpEntity<>(body, headers);
return restTemplate.postForObject(url, formEntity, String.class);
}
private String doGet(String url) {
return restTemplate.getForObject(url, String.class);
}
private BluePackage.HttpMethodEnum getHttpMethod(BluePackage httpPackage) {
IntItem item = (IntItem) httpPackage.getItem(BluePackage.HTTP_METHOD_ITEM_NAME);
return BluePackage.HttpMethodEnum.getById(item.getData());
}
private String getUrlString(BluePackage httpPackage) {
String url = null;
ByteArrayItem urlItem = (ByteArrayItem) httpPackage.getItem(BluePackage.URL_ITEM_NAME);
byte[] urlByteArray = urlItem.getData();
if (urlByteArray == null) {
log.error("请求的url字节数据为null,跳过请求!");
return null;
}
try {
url = new String(urlByteArray, BluePackage.CHART_SET);
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
return url;
}
private String getBodyStr(BluePackage httpPackage) throws Exception {
String bodyStr = "";
// 获取body字节数组
ByteArrayItem bodyArrayItem = (ByteArrayItem) httpPackage.getItem(BluePackage.BODY_ITEM_NAME);
byte[] bodyByteArray = bodyArrayItem.getData();
// 如果body字节数组为null,则返回空字符串
if (bodyByteArray == null) {
return bodyStr;
}
// 获取body数据的类型
SerializationMode serializationMode = getBodySerializationMode(httpPackage);
// 根据body的类型,反序列化body字节数组
switch (serializationMode) {
case JSON:
case STRING_BYTES:
bodyStr = new String(bodyByteArray, BluePackage.CHART_SET);
break;
case PROTOBUF2:
Serializer<String, Object> stringSerializer = serializers.get(serializationMode);
// 使用baseFrame反序列化body字节数组
Base.Frame frame = Base.Frame.parseFrom(bodyByteArray);
String javaProtobufClassC2S = frame.getJavaProtobufClassC2S();
if (javaProtobufClassC2S == null || javaProtobufClassC2S.length() == 0) {
}
ByteString payload = frame.getPayload();
stringSerializer.prepare(javaProtobufClassC2S);
bodyStr = stringSerializer.deserialize(payload);
break;
case PROTOBUF3:
throw new RuntimeException(String.format("未实现类型为%s的反序列化方式!", serializationMode));
default:
throw new RuntimeException(String.format("未实现类型为%s的反序列化方式!", serializationMode));
}
return bodyStr;
}
private SerializationMode getBodySerializationMode(Package packageData) {
SerializationMode serializationMode = null;
IntItem bodyTypeItem = (IntItem) packageData.getItem(BluePackage.BODY_TYPE_ITEM_NAME);
int bodyType = bodyTypeItem.getData();
for (SerializationMode tempMode : SerializationMode.values()) {
if (tempMode.geId() == bodyType) {
serializationMode = tempMode;
break;
}
}
if (serializationMode == null) {
throw new RuntimeException(String.format("给定的bodyType=%s,系统不支持该序列化类型。", bodyType));
}
return serializationMode;
}
@Resource
public void setSerializers(List<Serializer<String, Object>> serializers) {
if (serializers == null || serializers.isEmpty()) {
this.serializers = Collections.emptyMap();
return;
}
if (this.serializers == null) {
this.serializers = new HashMap<>((int) Math.max(Math.ceil(serializers.size() / 0.75f), 16));
}
for (Serializer<String, Object> serializer : serializers) {
this.serializers.put(serializer.getSupport(), serializer);
}
}
}
<file_sep>package microavatar.framework.core.net.tcp.netpackage.item;
import lombok.*;
import microavatar.framework.core.net.tcp.netpackage.ItemTypeEnum;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ByteArrayItem implements Item {
/**
* 选项类型
*/
private static final ItemTypeEnum ITEM_TYPE_ENUM = ItemTypeEnum.BYTE_ARRAY;
/**
* 选项名称
*/
private String name;
/**
* 选项数据
*/
private byte[] data;
public static ByteArrayItem emptyItem(String name) {
return new ByteArrayItemBuilder()
.name(name)
.build();
}
@Override
public ItemTypeEnum getItemTypeEnum() {
return ITEM_TYPE_ENUM;
}
}<file_sep>package microavatar.framework.perm.criteria;
import lombok.*;
import microavatar.framework.core.mvc.BaseCriteria;
import java.util.Set;
@Getter
@Setter
public class UserCriteria extends BaseCriteria {
// ********** 账号 account **********
/**
* 账号的值等于
*/
private String accountEquals;
/**
* 账号的值不等于
*/
private String accountNotEquals;
/**
* 账号的值开始于
*/
private String accountStartWith;
/**
* 账号的值类似
*/
private String accountLike;
/**
* 账号的值不类似
*/
private String accountNotLike;
/**
* 账号的值包含在
*/
private Set<String> accountIn;
/**
* 账号的值不包含在
*/
private Set<String> accountNotIn;
// ********** 密码 pwd **********
/**
* 密码的值等于
*/
private String pwdEquals;
/**
* 密码的值不等于
*/
private String pwdNotEquals;
/**
* 密码的值开始于
*/
private String pwdStartWith;
/**
* 密码的值类似
*/
private String pwdLike;
/**
* 密码的值不类似
*/
private String pwdNotLike;
/**
* 密码的值包含在
*/
private Set<String> pwdIn;
/**
* 密码的值不包含在
*/
private Set<String> pwdNotIn;
// ********** 名称 name **********
/**
* 名称的值等于
*/
private String nameEquals;
/**
* 名称的值不等于
*/
private String nameNotEquals;
/**
* 名称的值开始于
*/
private String nameStartWith;
/**
* 名称的值类似
*/
private String nameLike;
/**
* 名称的值不类似
*/
private String nameNotLike;
/**
* 名称的值包含在
*/
private Set<String> nameIn;
/**
* 名称的值不包含在
*/
private Set<String> nameNotIn;
// ********** 状态 status **********
/**
* 状态的值的值小于
*/
private Byte statusLessThan;
/**
* 状态的值的值小于等于
*/
private Byte statusLessThanEquals;
/**
* 状态的值的值等于
*/
private Byte statusEquals;
/**
* 状态的值的值大于等于
*/
private Byte statusGreaterThanEquals;
/**
* 状态的值的值大于
*/
private Byte statusGreaterThan;
/**
* 状态的值的值不等于
*/
private Byte statusNotEquals;
/**
* 状态的值的值包含在
*/
private Set<Byte> statusIn;
/**
* 状态的值的值不包含在
*/
private Set<Byte> statusNotIn;
/**
* 状态的值的值介于开始
* mysql between是包含边界值
*/
private Byte statusBetweenStart;
/**
* 状态的值的值介于结束
* mysql between是包含边界值
*/
private Byte statusBetweenEnd;
// ********** Constructor **********
public UserCriteria() {
}
@Builder
public UserCriteria(@Singular("selectColumns") Set<String> selectColumns,
Long idLessThan, Long idLessThanEquals, Long idEquals, Long idGreaterThanEquals, Long idGreaterThan, Long idNotEquals, @Singular("idIn") Set<Long> idIn, @Singular("idNotIn") Set<Long> idNotIn, Long idBetweenStart, Long idBetweenEnd,
Long createTimeLessThan, Long createTimeLessThanEquals, Long createTimeEquals, Long createTimeGreaterThanEquals, Long createTimeGreaterThan, Long createTimeNotEquals, @Singular("createTimeIn") Set<Long> createTimeIn, @Singular("createTimeNotIn") Set<Long> createTimeNotIn, Long createTimeBetweenStart, Long createTimeBetweenEnd,
Long modifyTimeLessThan, Long modifyTimeLessThanEquals, Long modifyTimeEquals, Long modifyTimeGreaterThanEquals, Long modifyTimeGreaterThan, Long modifyTimeNotEquals, @Singular("modifyTimeIn") Set<Long> modifyTimeIn, @Singular("modifyTimeNotIn") Set<Long> modifyTimeNotIn, Long modifyTimeBetweenStart, Long modifyTimeBetweenEnd,
Boolean deletedEquals, int pageNum, int pageSize, String orderBy,
String accountEquals, String accountNotEquals, String accountStartWith, String accountLike, String accountNotLike, @Singular("accountIn") Set<String> accountIn, @Singular("accountNotIn") Set<String> accountNotIn,
String pwdEquals, String pwdNotEquals, String pwdStartWith, String pwdLike, String pwdNotLike, @Singular("pwdIn") Set<String> pwdIn, @Singular("pwdNotIn") Set<String> pwdNotIn,
String nameEquals, String nameNotEquals, String nameStartWith, String nameLike, String nameNotLike, @Singular("nameIn") Set<String> nameIn, @Singular("nameNotIn") Set<String> nameNotIn,
Byte statusLessThan, Byte statusLessThanEquals, Byte statusEquals, Byte statusGreaterThanEquals, Byte statusGreaterThan, Byte statusNotEquals, @Singular("statusIn") Set<Byte> statusIn, @Singular("statusNotIn") Set<Byte> statusNotIn, Byte statusBetweenStart, Byte statusBetweenEnd
) {
super(selectColumns,
idLessThan, idLessThanEquals, idEquals, idGreaterThanEquals, idGreaterThan, idNotEquals, idIn, idNotIn, idBetweenStart, idBetweenEnd,
createTimeLessThan, createTimeLessThanEquals, createTimeEquals, createTimeGreaterThanEquals, createTimeGreaterThan, createTimeNotEquals, createTimeIn, createTimeNotIn, createTimeBetweenStart, createTimeBetweenEnd,
modifyTimeLessThan, modifyTimeLessThanEquals, modifyTimeEquals, modifyTimeGreaterThanEquals, modifyTimeGreaterThan, modifyTimeNotEquals, modifyTimeIn, modifyTimeNotIn, modifyTimeBetweenStart, modifyTimeBetweenEnd,
deletedEquals, pageNum, pageSize, orderBy);
this.accountEquals = accountEquals;
this.accountNotEquals = accountNotEquals;
this.accountStartWith = accountStartWith;
this.accountLike = accountLike;
this.accountNotLike = accountNotLike;
this.accountIn = accountIn;
this.accountNotIn = accountNotIn;
this.pwdEquals = pwdEquals;
this.pwdNotEquals = pwdNotEquals;
this.pwdStartWith = pwdStartWith;
this.pwdLike = pwdLike;
this.pwdNotLike = pwdNotLike;
this.pwdIn = pwdIn;
this.pwdNotIn = pwdNotIn;
this.nameEquals = nameEquals;
this.nameNotEquals = nameNotEquals;
this.nameStartWith = nameStartWith;
this.nameLike = nameLike;
this.nameNotLike = nameNotLike;
this.nameIn = nameIn;
this.nameNotIn = nameNotIn;
this.statusLessThan = statusLessThan;
this.statusLessThanEquals = statusLessThanEquals;
this.statusEquals = statusEquals;
this.statusGreaterThanEquals = statusGreaterThanEquals;
this.statusGreaterThan = statusGreaterThan;
this.statusNotEquals = statusNotEquals;
this.statusIn = statusIn;
this.statusNotIn = statusNotIn;
this.statusBetweenStart = statusBetweenStart;
this.statusBetweenEnd = statusBetweenEnd;
}
}
<file_sep>## 核心包-mvc
<file_sep>## 核心包-mq<file_sep>package microavatar.framework;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;
@Configuration
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
@ComponentScan
@EnableCaching
@EnableScheduling
@EnableEurekaClient
@SpringCloudApplication
public class PermApplication {
//启动服务时,开启debug日志模式:java -jar xxx.jar --debug
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext run = SpringApplication.run(PermApplication.class, args);
}
@Bean
public RestTemplate noBalanceRestTemplate() {
return new RestTemplate();
}
}
<file_sep> ## 核心包
数据库监听
采用阿里巴巴的开源项目canal
原理:基于mysql数据库binlog的增量订阅&消费<file_sep>## 核心包-缓存
[ ] 一级缓存(本地缓存):ehcache
[ ] 二级缓存(分布式缓存):redis<file_sep>package microavatar.framework.perm.status;
/**
* 登录状态
* tinyint
*/
public enum LoginStatus {
ONLINE((byte) 1, "在线"),
OFFLINE((byte) 2, "离线"),
FAIL((byte) 3, "登录失败");
private byte id;
private String desc;
LoginStatus(byte id, String desc) {
this.id = id;
this.desc = desc;
}
public byte getId() {
return id;
}
public String getDesc() {
return desc;
}
}
| 2d63bad384d81feea655568b7b2faea262a918e4 | [
"Markdown",
"Java",
"Maven POM",
"SQL"
]
| 42 | Java | bellmit/microavatar-framework | 9b328252561471891fa786a43a8a7a114510d3f8 | 4915baee835e794c945099732b8876a5c0e839a3 |
refs/heads/master | <file_sep># Getting Started With Data Visualisation Using Chart JS & React
INTRODUCTION: Data Visualisation might sound like a big word but essentially it is just visualising a given dataset for understanding it better. Data Visualisation is key when it comes to sharing one's research or even deriving meaningful insights and conclusions from it. There are many tools used for Data Visualisation and one can dive deep into this field. For purposes of this study we will learn how to create basic charts and graphs for given data using Chart js & React.
<file_sep>import React, {useEffect} from 'react'
import Chart from 'chart.js/auto'
import zoomPlugin from 'chartjs-plugin-zoom';
Chart.register(zoomPlugin);
let LineChart;
function Charts() {
useEffect(() => {
buildChart();
}, []);
const buildChart = () => {
var ctx = document.getElementById("LineChart").getContext("2d");
if (typeof LineChart !== "undefined") LineChart.destroy();
LineChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'],
datasets: [{
label: 'My First Dataset',
data: [65, 59, 80, 81, 56, 55, 40],
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
},
options: {
scales: {
x: {
grid: {
display: false,
},
},
y: {
min: 30,
max: 90,
}
},
animation: {
duration: 750,
},
plugins: {
zoom: {
zoom: {
wheel: {
enabled: true,
},
pinch: {
enabled: true
},
mode: 'xy',
},
}
}
}
});
}
return (
<div>
<h2>My first Chart</h2>
<canvas id="LineChart" width="1000" height="400"/>
</div>
)
}
export default Charts
| 3690837b7028461aa13922fb13bd1e521549efa1 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | labhmanmohan25/Medium_Getting_Started_With_Data_Visualisation_Using_Chart_JS_And_React | 9f055b96271d3592adf48c9b94fdab57eb16e3da | a880ec3f2c797b3654d05489bda67c6b9324e775 |
refs/heads/master | <file_sep>class Series:
def _init_(self, seriesName, season, numberOfEpisodes, episodeList):
self.seriesName = seriesName
self.season = season
self.numberOfEpisodes = numberOfEpisodes
self.episodeList = episodeList
def getName(self):
return self.seriesName
def getSeason(self):
return self.season
def getnumberOfEpisodes(self):
return self.numberOfEpisodes
def getEpisode(self, numberOfEpisodes):
return self.episodeList[numberOfEpisodes]<file_sep>import os, re, time
from app.BLL.lcm import LCM
print (LCM.lcmm ([10, 16, 24]))
print (LCM.lcmm ([6, 13, 22, 24]))
print (LCM.lcmm ([12, 15, 25]))
time.sleep(5)
<file_sep>import os, re, time
from app.BLL.lcm import LCM
# Testing Least Common Multiple
print ("Testing Least Common Multiple")
print ("LCM of 10, 16, 24", LCM.lcmm ([10, 16, 24]))
print ("LCM of 6, 13, 22, 24", LCM.lcmm ([6, 13, 22, 24]))
print ("LCM of 12, 15, 25", LCM.lcmm ([12, 15, 25]))
time.sleep(1)
#Testing Series Object
print ("Testing Creation of Series Object")
for subdir, dirs, files in os.walk('app\TestFiles\Test\Series'):
for dir in dirs:
print (dir)
time.sleep(1)
time.sleep(5) | 3f42d6b190951c81d546b6c2f2360c0556ab1a2d | [
"Python"
]
| 3 | Python | rednaz/Unraid-Media-Handler | 0e7090d5122486cbb6ebe8fc672a2e0f6ea349f7 | 464007af7bb2fd6abb5be5ad0d9bd0bae1840974 |
refs/heads/master | <repo_name>shaine/bitbucket-pull-request-metrics<file_sep>/lib/utils.test.js
const { describe, it } = require('mocha');
const chai = require('chai');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
const proxyquire = require('proxyquire');
const { expect } = chai;
chai.use(sinonChai);
const fetchStub = sinon.stub().returns('fetchStubReturn');
const { createBitBucketUrl, fetchFromBitBucket } = proxyquire('./utils', {
'node-fetch': fetchStub
});
describe('utils', () => {
describe('createBitBucketUrl', () => {
it('creates a BitBucket URL', () => {
expect(createBitBucketUrl({
host: 'https://test.com',
project: 'TEST',
repo: 'test-repo'
})('/my/path')).to.equal('https://test.com/rest/api/1.0/projects/TEST/repos/test-repo/my/path');
});
});
describe('fetchFromBitBucket', () => {
it('makes a BitBucket request', () => {
const value = fetchFromBitBucket({
host: 'https://test.com',
project: 'TEST',
repo: 'test-repo',
username: 'foobar',
authToken: 'my token'
})('/my/path');
expect(value).to.equal('fetchStubReturn');
expect(fetchStub).to.have.been.calledWith(
'https://test.com/rest/api/1.0/projects/TEST/repos/test-repo/my/path',
{
headers: {
'X-Auth-User': 'foobar',
'X-Auth-Token': 'my token'
}
}
);
});
});
});
<file_sep>/README.md
# bitbucket-pull-request-metrics
A tool to evaluate BitBucket pull requests and report back various metrics about
how the pull request impacts a project. Presently, only designed to support
JavaScript ES6 projects.
## Installation
NOTE: This project is not currently published.
`$ npm install --save-dev bitbucket-pull-request-metrics`
## Usage
### CLI
Assuming the module was installed globally:
```bash
$ bitbucket-pull-request-metrics \
--username foobar \
--authToken <PASSWORD> \
--project DEV \
--repo my-repo \
--pr 123
```
#### Arguments
**--username, -u** (string, required)
User's BitBucket username.
**--authToken, -t** (string, required)
User's BitBucket auth token.
**--project, -p** (string, required)
BitBucket project's key/name.
**--repo, -r** (string, required)
The BitBucket project's repository which contains the pull request.
**--pr** (number, required)
The pull request to inspect.
**--host** (string, optional)
The protocol and hostname of the BitBucket server. Defaults to "https://bitbucket.org".
### Programmatic
```javascript
// Initialize metrics lib
const metrics = require('bitbucket-pull-request-metrics')({
host: 'https://bitbucket.org', // Optional parameter. This is the default.
// The following are all required.
project: 'DEV',
repo: 'my-repo',
username: 'foobar',
authToken: '<PASSWORD>'
});
// Fetch details about PR 123
metrics(123, (err, prMetrics) => {
console.log(prMetrics);
});
```
### TODO
#### General
- Design to review one PR versus a list of PRs, maybe all currently open, and
all for a project? Pagination?
- Design hooks for static code analysis. Unit test coverage hook,
#### BitBucket
- Number of images (screenshots?)
- Number of commits
- Number of subsequent additional commits
- Number of original author comments
- Number of follow up comments (non-author, or replies)
- Min/max/median comment thread length
- Number of days in development
- Number of days PR stayed open
- Number of approvals
- Number of "Needs Work" reviews
- Number of contributing reviewers (submitted some sort of PR review activity)
- Number of contributing reviewers who did not approve PR
- User IDs of contributing reviewers
- Author user ID
- PR number, link
- PR approval status (open/merged/declined)
- Number of open, completed tasks
- Min/max/median per-file LOC changes
- Number of files changed, added, deleted, moved
#### Supplemental Analysis
- Plato LOC, complexity, bug estimate, maintainability, deltas per-file
- Instanbul code coverage delta
- Esprima comment density delta
#### Someday/Maybe
- Suggested PR quality score
| 815ed2e429c7ac559088f965f3f18f165fe41ae6 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | shaine/bitbucket-pull-request-metrics | 22ae7a002a02946de4b5c23006eadf3c5ce340cb | f4d46b6f9beb72018e8bf098ade3ae1d3010afed |
refs/heads/master | <repo_name>guitardave/VS_Projects<file_sep>/TCG_Projects/MarketAnalyzer-master/LICENSE.MD
This code is not licensed.
Copyright 2018 <NAME>, All Rights Reserved.
<file_sep>/TCG_Projects/MarketAnalyzer-master/MarketAnalyzer/Extensions/TraceWriterExtensions.cs
using Microsoft.Azure.WebJobs.Host;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MarketAnalyzer.Extensions
{
public static class TraceWriterExtensions
{
public static async Task<T> Try<T>(this TraceWriter log, string msg, Func<Task<T>> func)
{
try
{
var task = await func();
log.Info($"SUCCESS : {msg}");
if (task is IEnumerable)
log.Info($" COUNT : {(task as IEnumerable).OfType<object>().Count()}");
return task;
}
catch (Exception ex)
{
log.Warning($"FAILURE : {msg}");
log.Error(msg, ex);
throw;
}
}
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/PricingTool/Commands/SearchCommand.cs
using MoreLinq;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Input;
namespace PricingTool.Commands
{
public class SearchCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter) => true;
public async void Execute(object parameter)
{
var vm = parameter as MainViewModel;
var client = new TCGPlayer.TCGPlayerClient(new System.Net.Http.HttpClient(), TCGPlayer.Settings.StoreToken, TCGPlayer.Settings.Secrets);
vm.Title = "Fetching Groups ...";
if (vm.Groups == null)
vm.Groups = new Dictionary<int, Dictionary<int, string>>();
if (vm.Groups.ContainsKey(vm.SelectedCategory.Id) == false)
{
var groups = await client.ListCategoryGroups(vm.SelectedCategory.Id);
vm.Groups.Add(vm.SelectedCategory.Id, groups.ToDictionary(e => e["groupId"].Value<int>(), e => e["name"].Value<string>()));
}
vm.Title = "Searching ...";
var productIds = await client.SearchCategory(vm.SelectedCategory.Id, new JObject
{
{ "includeAggregates", "true" },
{ "filters", new JArray
{
new JObject
{
{ "name", "ProductName" },
{ "values", new JArray { vm.SearchText } }
}
}
}
});
int[] ids = productIds.Select(e => e.Value<int>()).ToArray();
vm.Results.Clear();
if (ids.Count() == 0)
{
vm.Title = "No Results Found";
return;
}
vm.Title = "Fetching Product Details ...";
var details = await client.GetProductDetails(ids);
vm.Title = "Fetching Product Prices ...";
var prices = await client.ListProductMarketPrices(ids);
vm.Title = "Updating ...";
foreach (var data in details)
{
string productName = data["productName"].ToString();
string rarity = data["extendedData"].FirstOrDefault(e => e["name"].ToString() == "Rarity")?["value"]?.ToString() ?? "";
string set = vm.Groups[vm.SelectedCategory.Id][data["groupId"].Value<int>()];
string link = data["url"].ToString();
string image = data["image"].ToString();
var pricing = prices
.Where(e => e["productId"].Value<int>() == data["productId"].Value<int>())
.Select(e => new
{
PrintingType = e["subTypeName"].Value<string>(),
LowPrice = e["lowPrice"].Value<double?>() ?? 0,
MidPrice = e["midPrice"].Value<double?>() ?? 0,
HighPrice = e["highPrice"].Value<double?>() ?? 0,
MarketPrice = e["marketPrice"].Value<double?>() ?? 0
})
.Select(e => new
{
e.PrintingType,
e.LowPrice,
e.MidPrice,
e.HighPrice,
e.MarketPrice,
BuyPrice = (e.MidPrice > e.MarketPrice) ? e.MarketPrice * .5 : e.MidPrice * .5,
StoreCreditBuyPrice = (e.MidPrice > e.MarketPrice) ? e.MarketPrice * .7 : e.MidPrice * .7,
SellPrice = (e.MidPrice > e.MarketPrice) ? e.MidPrice : e.MarketPrice
})
.ToList();
var item = new
{
Name = productName,
Rarity = rarity,
Set = set,
Link = link,
Image = image,
Conditions = pricing
};
vm.Results.Add(item);
}
vm.IsCardListFocused = false;
vm.IsCardListFocused = true;
vm.Title = $"Searched {vm.SearchText} and found {vm.Results.Count} items";
vm.SelectedItem = vm.Results.First();
vm.SearchText = null;
}
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/MarketAnalyzer/Messages/UpdateProductsRequest.cs
using System;
namespace MarketAnalyzer.Messages
{
public class UpdateProductsRequest
{
public int GroupId { get; set; }
public bool IsEnabled { get; set; }
public dynamic Group { get; set; }
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/README.md
# Ownership
All code in this repository is Copyright 2018 <NAME>, All Rights Reserved. This is not open source, you have no right to distribute. Any code taken from this repository and used elsewhere is theft.
<file_sep>/TCG_Projects/MarketAnalyzer-master/TCGPlayer/HttpResponseMessageExtensions.cs
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace TCGPlayer
{
public static class HttpResponseMessageExtensions
{
public static async Task<JObject> ParseResults(this HttpResponseMessage msg)
{
var content = await msg.GetContentAsJObject();
if (content["success"].Value<bool>())
return content;
else
{
var errors = content["errors"].Value<JArray>();
throw new AggregateException(errors.Select(e => new Exception(e.Value<string>())));
}
}
public static async Task<JObject> GetContentAsJObject(this HttpResponseMessage msg)
{
using (var streamReader = new StreamReader(await msg.Content.ReadAsStreamAsync()))
using (var jsonTextReader = new JsonTextReader(streamReader))
{
return JObject.Load(jsonTextReader);
}
}
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/MarketAnalyzer/Infrastructure/Settings.cs
using System;
using System.Collections.Generic;
namespace MarketAnalyzer.Infrastructure
{
public static class Settings
{
public const string DbName = "MarketAnalyzer";
public const string CollName = "Documents";
public const string ConnStringSetting = "CosmosDBConnection";
public const string QueueConnString = "AzureWebJobsStorage";
public static readonly Dictionary<string, string> Secrets = new Dictionary<string, string>() {
{ "grant_type", "client_credentials" },
{ "client_id", "FD31A057-1EAF-4C66-8186-072A1BEDA911" },
{ "client_secret", "35F387AB-87E8-423A-9931-B0DC01352CEF" }
};
public static string StoreToken = "<PASSWORD>";
public static class Queues
{
public const string StoreCategory = "store-category";
public const string UpdateCategoryGroups = "update-category-groups";
public const string StoreGroup = "store-group";
}
public static class ChronTimings
{
public const string EveryTenSeconds = "*/10 * * * * *";
public const string EveryMinute = "0 * * * * *";
public const string EveryHour = "0 0 * * * *";
}
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/MarketAnalyzer/LookupDataToDb.cs
using MarketAnalyzer.Entities;
using MarketAnalyzer.Extensions;
using MarketAnalyzer.Infrastructure;
using MarketAnalyzer.Messages;
using MarketAnalyzer.TCGPlayer;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace MarketAnalyzer
{
public static class GroupFunctions
{
[FunctionName("UpdateGroup")]
public static async Task UpdateGroup(
[QueueTrigger(Settings.Queues.UpdateCategoryGroups, Connection = Settings.QueueConnString)]
UpdateGroupsRequest request,
[Queue(Settings.Queues.StoreGroup, Connection = Settings.QueueConnString)]
IAsyncCollector<Document> asyncCollector,
TraceWriter log
)
{
var client = new TCGPlayerClient(new HttpClient(), Settings.StoreToken, Settings.Secrets);
var token = await log.Try("Get store access token", client.GetAccessTokenAsync);
var groups = await log.Try($"Get groups from TCGPlayer for category {request.CategoryId}", () => client.ListCategoryGroups(request.CategoryId));
foreach (var group in groups)
{
string id = group["groupId"].ToString();
string name = group["name"].ToString();
JToken firstProp = group.First();
firstProp.AddBeforeSelf(new JProperty("categoryId", request.CategoryId));
firstProp.AddAfterSelf(new JProperty("category", request.Category));
await asyncCollector.AddAsync(new Document()
{
id = $"group-{id}",
type = "group",
typeId = Convert.ToInt32(id),
name = name,
enabled = request.IsEnabled,
data = group
});
}
}
[FunctionName("StoreGroup")]
public static async Task StoreGroup(
[QueueTrigger(Settings.Queues.StoreGroup, Connection = Settings.QueueConnString)]
Document doc,
[CosmosDB(Settings.DbName, Settings.CollName, ConnectionStringSetting = Settings.ConnStringSetting)]
DocumentClient docClient,
[Queue(Settings.Queues.UpdateCategoryGroups, Connection = Settings.QueueConnString)]
IAsyncCollector<UpdateProductsRequest> asyncCollector,
TraceWriter log
)
{
Uri collectionUri = UriFactory.CreateDocumentCollectionUri(Settings.DbName, Settings.CollName);
var resp = await docClient.UpsertDocumentAsync(collectionUri, doc);
//await asyncCollector.AddAsync(new UpdateProductsRequest { GroupId = doc.typeId, Group = doc.data });
}
}
public static class CategoryFunctions
{
[FunctionName("UpdateCategories")]
public static async Task UpdateCategories(
[TimerTrigger(Settings.ChronTimings.EveryHour)] TimerInfo myTimer,
[Queue(Settings.Queues.StoreCategory, Connection = Settings.QueueConnString)] IAsyncCollector<Document> asyncCollector,
TraceWriter log
)
{
var client = new TCGPlayerClient(new HttpClient(), Settings.StoreToken, Settings.Secrets);
var token = await log.Try("Get store access token", client.GetAccessTokenAsync);
var categories = await log.Try("Get categories from TCGPlayer", client.ListCategories);
var transformedDocs = categories.Select(category =>
{
string id = category["categoryId"].ToString();
string name = category["name"].ToString();
return new Document()
{
id = $"category-{id}",
type = "category",
typeId = Convert.ToInt32(id),
name = name,
enabled = id == "1" ? true : false,
data = category
};
});
foreach (var doc in transformedDocs)
{
await asyncCollector.AddAsync(doc);
}
}
[FunctionName("StoreCategories")]
public static async Task StoreCategories(
[QueueTrigger(Settings.Queues.StoreCategory, Connection = Settings.QueueConnString)]
Document doc,
[CosmosDB(Settings.DbName, Settings.CollName, ConnectionStringSetting = Settings.ConnStringSetting)]
DocumentClient docClient,
[Queue(Settings.Queues.UpdateCategoryGroups, Connection = Settings.QueueConnString)]
IAsyncCollector<UpdateGroupsRequest> asyncCollector,
TraceWriter log
)
{
Uri collectionUri = UriFactory.CreateDocumentCollectionUri(Settings.DbName, Settings.CollName);
var resp = await docClient.UpsertDocumentAsync(collectionUri, doc);
if (doc.enabled)
await asyncCollector.AddAsync(new UpdateGroupsRequest { CategoryId = doc.typeId, Category = doc.data, IsEnabled = doc.enabled });
}
//[FunctionName("UpdateGroups")]
//public static async Task UpdateGroups(
// [TimerTrigger(Settings.ChronTimings.EveryHour)] TimerInfo myTimer,
// [CosmosDB(Settings.DbName, Settings.CollName,
// SqlQuery = "select * from Documents d where d.type='category' and d.enabled",
// ConnectionStringSetting = Settings.ConnStringSetting)] IEnumerable<Document> categories,
// [CosmosDB(Settings.DbName, Settings.CollName,
// ConnectionStringSetting = Settings.ConnStringSetting)] DocumentClient docClient,
// TraceWriter log
//)
//{
// log.Warning($" GIVEN : {nameof(UpdateGroups)} {categories.Count()} categories");
// Uri collectionUri = UriFactory.CreateDocumentCollectionUri(Settings.DbName, Settings.CollName);
// var client = new TCGPlayerClient(new HttpClient(), Settings.StoreToken, Settings.Secrets);
// var token = await log.Try("Get store access token", client.GetAccessTokenAsync);
// foreach (var category in categories)
// {
// var groups = await log.Try($"Get groups from TCGPlayer for category {category.typeId}", () => client.ListCategoryGroups(category.typeId));
// foreach (var group in groups)
// {
// string id = group["groupId"].ToString();
// string name = group["name"].ToString();
// JToken firstProp = group.First();
// firstProp.AddBeforeSelf(new JProperty("categoryId", category.typeId));
// firstProp.AddAfterSelf(new JProperty("category", category.data));
// await docClient.UpsertDocumentAsync(collectionUri, new Document()
// {
// id = $"group-{id}",
// type = "group",
// typeId = Convert.ToInt32(id),
// name = name,
// enabled = true,
// data = group
// });
// }
// }
//}
//[FunctionName("UpdateProducts")]
//public static async Task UpdateProducts(
// [TimerTrigger(Settings.ChronTimings.EveryTenSeconds)] TimerInfo myTimer,
// [CosmosDB(Settings.DbName, Settings.CollName,
// SqlQuery = "select * from Documents d where d.type='group' and d.enabled",
// ConnectionStringSetting = Settings.ConnStringSetting)] IEnumerable<Document> groups,
// [CosmosDB(Settings.DbName, Settings.CollName,
// ConnectionStringSetting = Settings.ConnStringSetting)] DocumentClient docClient,
// TraceWriter log
//)
//{
// log.Warning($" GIVEN : {nameof(UpdateProducts)} {groups.Count()} groups");
// Uri collectionUri = UriFactory.CreateDocumentCollectionUri(Settings.DbName, Settings.CollName);
// var client = new TCGPlayerClient(new HttpClient(), Settings.StoreToken, Settings.Secrets);
// var token = await log.Try("Get store access token", client.GetAccessTokenAsync);
// foreach (var group in groups)
// {
// var categoryId = (int)group.data.categoryId;
// var products = await log.Try($"Get groups from TCGPlayer for category {group.typeId}", () => client.ListProductsInGroup(categoryId, group.typeId));
// foreach (var product in products)
// {
// string id = product["productId"].ToString();
// string name = product["productName"].ToString();
// await docClient.UpsertDocumentAsync(collectionUri, new Document()
// {
// id = $"product-{id}",
// type = "product",
// typeId = Convert.ToInt32(id),
// name = name,
// enabled = true,
// data = product
// });
// }
// }
//}
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/TCGPlayer/Settings.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace TCGPlayer
{
public static class Settings
{
public static readonly Dictionary<string, string> Secrets = new Dictionary<string, string>() {
{ "grant_type", "client_credentials" },
{ "client_id", "FD31A057-1EAF-4C66-8186-072A1BEDA911" },
{ "client_secret", "35F387AB-87E8-423A-9931-B0DC01352CEF" }
};
public static string StoreToken = "<PASSWORD>";
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/MarketAnalyzer/Messages/UpdateGroupsRequest.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace MarketAnalyzer.Messages
{
public class UpdateGroupsRequest
{
public int CategoryId { get; set; }
public bool IsEnabled { get; set; }
public dynamic Category { get; set; }
}
}
<file_sep>/pedid/pedid/Startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(pedid.Startup))]
namespace pedid
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/PricingTool/Category.cs
using System;
using System.Linq;
namespace PricingTool
{
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public int Popularity { get; set; }
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/PricingTool/MainViewModel.cs
using PricingTool.Commands;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows.Input;
namespace PricingTool
{
public class MainViewModel : INotifyPropertyChanged
{
public ICommand SearchCommand { get; } = new SearchCommand();
public ICommand FocusOnSearchCommand { get; } = new FocusOnSearchCommand();
public ICommand LoadedCommand { get; } = new LoadedCommand();
string title = "Pricing Tool";
public string Title
{
get { return title; }
set
{
string newVal = "Pricing Tool";
if (value != null)
newVal += $"- {value}";
if (title == newVal)
return;
title = newVal;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Title)));
}
}
Category selectedCategory;
public Category SelectedCategory
{
get { return selectedCategory; }
set
{
if (selectedCategory == value)
return;
selectedCategory = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedCategory)));
}
}
string searchText;
public string SearchText
{
get { return searchText; }
set
{
if (searchText == value)
return;
searchText = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SearchText)));
}
}
bool isSearchBoxFocused = true;
public bool IsSearchBoxFocused
{
get { return isSearchBoxFocused; }
set
{
if (isSearchBoxFocused == value)
return;
isSearchBoxFocused = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsSearchBoxFocused)));
}
}
bool isCardListFocused;
public bool IsCardListFocused
{
get { return isCardListFocused; }
set
{
if (isCardListFocused == value)
return;
isCardListFocused = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsCardListFocused)));
}
}
dynamic selectedItem;
public dynamic SelectedItem
{
get { return selectedItem; }
set
{
if (selectedItem == value)
return;
selectedItem = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItem)));
}
}
public ObservableCollection<Category> Categories { get; set; } = new ObservableCollection<Category>();
public ObservableCollection<dynamic> Results { get; set; } = new ObservableCollection<dynamic>();
public Dictionary<int, Dictionary<int, string>> Groups { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/MarketAnalyzer.Server/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MarketAnalyzer.Server
{
class Program
{
public static readonly string appId = "1642";
public static readonly Dictionary<string, string> secrets = new Dictionary<string, string>() {
{ "grant_type", "client_credentials" },
{ "client_id", "FD31A057-1EAF-4C66-8186-072A1BEDA911" },
{ "client_secret", "35F387AB-87E8-423A-9931-B0DC01352CEF" }
};
public static string authCode = "";
public static string storeToken = "<PASSWORD>";
public static async Task Main(string[] args)
{
if (string.IsNullOrWhiteSpace(storeToken))
{
var appAuthUrl = $"https://store.tcgplayer.com/admin/Apps/{appId}";
Console.WriteLine("Please open the following URL, authorize this application and then enter the code below:");
Console.WriteLine(appAuthUrl);
Console.Write("Code: ");
authCode = Console.ReadLine();
}
var client = new TCGPlayerClient(new HttpClient(), storeToken, secrets);
await Try("Get Store Token", client.GetAccessTokenAsync);
var categories = await Try("Get Categories", client.ListCategories);
Total(categories);
var groups = await Try("Get Magic Groups", () => client.ListCategoryGroups("1"));
Total(groups);
//var rarities = await Try("Get Magic Rarities", () => client.ListCategoryRarities("1"));
//Total(rarities);
//var printings = await Try("Get Magic Printings", () => client.ListCategoryPrintings("1"));
//Total(printings);
//var conditions = await Try("Get Magic conditions", () => client.ListCategoryConditions("1"));
//Total(conditions);
//var languages = await Try("Get Magic languages", () => client.ListCategoryLanguages("1"));
//Total(languages);
//var media = await Try("Get Magic media", () => client.ListCategoryMedia("1"));
//Total(media);
foreach (var item in groups)
{
Console.WriteLine(item.ToString());
}
Console.ReadLine();
}
public static void Total(JArray input) => Console.WriteLine($" TOTAL : {input.Count}");
public static async Task<T> Try<T>(string msg, Func<Task<T>> func)
{
try
{
var task = await func();
Console.WriteLine($"SUCCESS : {msg}");
return task;
}
catch (Exception ex)
{
Console.WriteLine($"FAILURE : {msg}");
Console.WriteLine(ex.ToString());
throw;
}
}
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/TCGPlayer/TCGPlayerClient.cs
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace TCGPlayer
{
public class TCGPlayerClient
{
public static readonly string rootUrl = "https://api.tcgplayer.com";
private readonly HttpClient client;
private readonly Dictionary<string, string> secrets;
private readonly string storeToken;
private readonly object lockObject;
public TCGPlayerClient(HttpClient client, string storeToken, Dictionary<string, string> secrets)
{
this.client = client;
this.secrets = secrets;
this.storeToken = storeToken;
this.lockObject = new object();
}
public int Limit { get; set; } = 100;
public string AccessToken { get; set; }
private async Task<string> GetAccessTokenAsync()
{
client.DefaultRequestHeaders.Add("X-Tcg-Access-Token", storeToken);
var getTokenResult = await client.PostAsync($"{rootUrl}/token", new FormUrlEncodedContent(secrets));
if (getTokenResult.IsSuccessStatusCode == false) throw new Exception(getTokenResult.ReasonPhrase);
AccessToken = (await getTokenResult.GetContentAsJObject())["access_token"].Value<string>();
return AccessToken;
}
private async Task<JArray> Post(string urlFragment, JObject data, int offset = 0)
{
await GetAccessTokenAsync();
var url = $"{rootUrl}{urlFragment}";
if (data.ContainsKey("offset"))
data["offset"] = offset;
else
data.Children().First().AddBeforeSelf(new JProperty("offset", offset));
if (data.ContainsKey("offset"))
data["limit"] = Limit;
else
data.Children().First().AddBeforeSelf(new JProperty("limit", Limit));
if (client.DefaultRequestHeaders.Contains("X-Tcg-Access-Token"))
client.DefaultRequestHeaders.Remove("X-Tcg-Access-Token");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
string payload = data.ToString();
var result = await client.PostAsync(url, new StringContent(payload,System.Text.Encoding.ASCII, "application/json"));
if (result.IsSuccessStatusCode == false) throw new Exception(result.ReasonPhrase);
var response = await result.ParseResults();
var results = response["results"].Value<JArray>();
int totalItems = response.ContainsKey("totalItems") ? response["totalItems"].Value<int>() : results.Count;
int receivedCount = offset + results.Count;
Console.WriteLine($"Fetching {Limit} / {offset} / {receivedCount} / {totalItems} of {url}");
if (totalItems > receivedCount)
return new JArray(results.Union(await Post(urlFragment, data, receivedCount)));
else
return results;
}
private async Task<JArray> Get(string urlFragment, int? offset = 0)
{
await GetAccessTokenAsync();
var url = $"{rootUrl}{urlFragment}";
if (offset.HasValue)
url = $"{url}&offset={offset}";
if (client.DefaultRequestHeaders.Contains("X-Tcg-Access-Token"))
client.DefaultRequestHeaders.Remove("X-Tcg-Access-Token");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
var result = await client.GetAsync(url);
if (result.IsSuccessStatusCode == false) throw new Exception(result.ReasonPhrase);
var response = await result.ParseResults();
var results = response["results"].Value<JArray>();
int totalItems = response.ContainsKey("totalItems") ? response["totalItems"].Value<int>() : results.Count;
int receivedCount = (offset ?? 0) + results.Count;
Console.WriteLine($"Fetching {Limit} / {offset} / {receivedCount} / {totalItems} of {url}");
if (totalItems > receivedCount)
return new JArray(results.Union(await Get(urlFragment, receivedCount)));
else
return results;
}
private Task<JArray> GetCategorySubItem(int categoryId, string item) => Get($"/catalog/categories/{categoryId}/{item}?limit={Limit}");
public Task<JArray> SearchCategory(int categoryId, JObject data) => Post($"/catalog/categories/{categoryId}/search", data);
public Task<JArray> GetProductDetails(int[] productIds) => Get($"/catalog/products/{string.Join(",", productIds.Select(s => s.ToString()).ToArray())}?getExtendedFields=true");
public Task<JArray> ListProductMarketPrices(int[] skus) => Get($"/pricing/product/{string.Join(",", skus.Select(s => s.ToString()).ToArray())}", null);
public Task<JArray> ListSkuMarketPrices(int[] skus) => Get($"/pricing/sku/{string.Join(",", skus.Select(s => s.ToString()).ToArray())}", null);
public Task<JArray> ListCategories() => Get($"/catalog/categories?limit={Limit}");
public Task<JArray> ListProductsInGroup(int categoryId, int groupId) => Get($"/catalog/products?categoryId={categoryId}&groupId={groupId}&getExtendedFields=true&limit={Limit}");
public Task<JArray> ListCategoryGroups(int categoryId) => GetCategorySubItem(categoryId, "groups");
public Task<JArray> ListCategoryRarities(int categoryId) => GetCategorySubItem(categoryId, "rarities");
public Task<JArray> ListCategoryPrintings(int categoryId) => GetCategorySubItem(categoryId, "printings");
public Task<JArray> ListCategoryConditions(int categoryId) => GetCategorySubItem(categoryId, "conditions");
public Task<JArray> ListCategoryLanguages(int categoryId) => GetCategorySubItem(categoryId, "languages");
public Task<JArray> ListCategoryMedia(int categoryId) => GetCategorySubItem(categoryId, "media");
}
}
<file_sep>/AudioFileComparison/AudioFileComparison/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AudioFileComparison
{
class Program
{
static string[] filenames = { "88005f.wav",
"88006f.wav",
"88007f.wav",
"88007m.wav",
"88008f.wav",
"88008m.wav",
"88009f.wav",
"88009m.wav",
"88010f.wav",
"88010m.wav",
"88011f.wav",
"88011m.wav",
"88012f.wav",
"88012m.wav",
"88013f.wav",
"88013m.wav",
"88014f.wav",
"88014m.wav",
"88015f.wav",
"88015m.wav",
"88016f.wav",
"88016m.wav",
"88017f.wav",
"88017m.wav",
"88018f.wav",
"88041f.wav",
"88065f.wav",
"88075f.wav",
"88076f.wav",
"88077f.wav",
"88078f.wav",
"88086f.wav",
"88110f.wav",
"88111f.wav",
"88112f.wav",
"88113f.wav",
"88115f.wav",
"88121f.wav",
"88125f.wav",
"88126f.wav",
"88127f.wav",
"88128f.wav",
"88129f.wav",
"88130f.wav",
"88131f.wav",
"88132f.wav",
"88133f.wav",
"88134f.wav",
"88135f.wav",
"88136f.wav",
"88137f.wav",
"88138f.wav",
"88138m.wav",
"88139f.wav",
"88139m.wav",
"88140f.wav",
"88140m.wav",
"88141f.wav",
"88141m.wav",
"88142f.wav",
"88142m.wav",
"88143f.wav",
"88143m.wav",
"88144f.wav",
"88144m.wav",
"88145f.wav",
"88145m.wav",
"88146f.wav",
"88146m.wav",
"88161f.wav",
"88161m.wav",
"88162f.wav",
"88162m.wav",
"88163f.wav",
"88163m.wav",
"88164f.wav",
"88164m.wav",
"88165f.wav",
"88165m.wav",
"88166f.wav",
"88166m.wav",
"88167f.wav",
"88167m.wav",
"88168f.wav",
"88168m.wav",
"88169f.wav",
"88169m.wav",
"88170f.wav",
"88170m.wav",
"88171f.wav",
"88171m.wav",
"88172f.wav",
"88172m.wav",
"88189f.wav",
"88196f.wav",
"88202f.wav",
"88203f.wav",
"88204f.wav",
"88221f.wav",
"88222f.wav",
"88223f.wav",
"88224f.wav",
"88225f.wav",
"88226f.wav",
"88227f.wav",
"88233f.wav",
"88239f.wav",
"88240f.wav",
"88241f.wav",
"88242f.wav",
"88243f.wav",
"88244f.wav",
"88245f.wav",
"88246f.wav",
"88247f.wav",
"88248f.wav",
"88249f.wav",
"88298f.wav",
"88308f.wav",
"88309f.wav",
"88310f.wav",
"88311f.wav",
"88312f.wav",
"88313f.wav",
"88314f.wav",
"88315f.wav",
"88316f.wav",
"88317f.wav",
"88318f.wav",
"88319f.wav",
"88320f.wav",
"88333f.wav",
"88347f.wav",
"88365f.wav",
"88381f.wav",
"88393f.wav",
"88410m.wav",
"88424f.wav",
"88437f.wav",
"88449f.wav",
"88457f.wav",
"88479f.wav",
"88490f.wav",
"88491f.wav",
"88497f.wav",
"88498f.wav",
"88499f.wav",
"88500f.wav",
"88501f.wav",
"88509f.wav",
"88512f.wav",
"88528f.wav",
"88531f.wav",
"88552f.wav",
"88553f.wav",
"88557f.wav",
"88558f.wav",
"88559f.wav",
"88581f.wav",
"88586f.wav",
"88587f.wav",
"88589f.wav",
"88607f.wav",
"88615f.wav",
"88631f.wav",
"88632f.wav",
"88633f.wav",
"88634f.wav",
"88635f.wav",
"88636f.wav",
"88646f.wav",
"88647f.wav",
"88648f.wav",
"88649f.wav",
"88689f.wav",
"88693f.wav",
"88693m.wav",
"88694f.wav",
"88694m.wav",
"88695f.wav",
"88695m.wav",
"88696f.wav",
"88696m.wav",
"88697f.wav",
"88697m.wav",
"88698f.wav",
"88698m.wav",
"88700f.wav",
"88704f.wav",
"88705f.wav",
"88706f.wav",
"88707f.wav",
"88708f.wav",
"88709f.wav",
"88710f.wav",
"88713f.wav",
"88714f.wav",
"88717f.wav",
"88718f.wav",
"88719f.wav",
"88720f.wav",
"88721f.wav",
"88722f.wav",
"88724f.wav",
"88725f.wav",
"88730f.wav",
"88731f.wav",
"88732f.wav",
"88764m.wav",
"88765f.wav",
"88770f.wav",
"88771f.wav",
"88772f.wav",
"88773f.wav",
"88774f.wav",
"88775f.wav",
"88776f.wav",
"88777f.wav",
"88778f.wav",
"88779f.wav",
"88780f.wav",
"88781f.wav",
"88782f.wav",
"88783f.wav",
"88784f.wav",
"88785f.wav",
"88786f.wav",
"88787f.wav",
"88788f.wav",
"88790f.wav",
"88791f.wav",
"88793f.wav",
"88794f.wav",
"88795f.wav",
"88796f.wav",
"88809f.wav",
"88810f.wav",
"88811f.wav",
"88812f.wav",
"88829f.wav",
"88849f.wav",
"88850f.wav",
"88851f.wav",
"88874f.wav",
"88903f.wav",
"88903m.wav",
"88904f.wav",
"88904m.wav",
"88905f.wav",
"88905m.wav",
"88906f.wav",
"88906m.wav",
"88907f.wav",
"88907m.wav",
"88908f.wav",
"88908m.wav",
"88914f.wav",
"88929f.wav",
"88931f.wav",
"88932f.wav",
"88943f.wav",
"88965f.wav",
"88974f.wav",
"88975f.wav",
"88976f.wav",
"88977f.wav",
"88978f.wav",
"88979f.wav",
"88980f.wav",
"88981f.wav",
"89005f.wav",
"89011f.wav",
"89016f.wav",
"89055f.wav",
"89137f.wav",
"89149f.wav",
"89152f.wav",
"89163f.wav",
"89164f.wav",
"89165f.wav",
"89166f.wav",
"89185f.wav",
"89189f.wav",
"89254f.wav",
"89255f.wav",
"89256f.wav",
"89257f.wav",
"89258f.wav",
"89260f.wav",
"89261f.wav",
"89263f.wav",
"89281f.wav",
"89282f.wav",
"89291f.wav",
"89293f.wav",
"89295f.wav",
"89296f.wav",
"89297f.wav",
"89298f.wav",
"89299f.wav",
"89300f.wav",
"89301f.wav",
"89303f.wav",
"89304f.wav",
"89307f.wav",
"89309f.wav",
"89310f.wav",
"89311f.wav",
"89312f.wav",
"89313f.wav",
"89314f.wav",
"89317f.wav",
"89318f.wav",
"89320f.wav",
"89413f.wav",
"89476f.wav",
"89477f.wav",
"89478f.wav",
"89479f.wav",
"89480f.wav",
"89481f.wav",
"89482f.wav",
"89483f.wav",
"89484f.wav",
"89485f.wav",
"89486f.wav",
"89487f.wav",
"89488f.wav",
"89489f.wav",
"89514f.wav",
"89515f.wav",
"89516f.wav",
"89517f.wav",
"89518f.wav",
"89519f.wav",
"89520f.wav",
"89521f.wav",
"89522f.wav",
"89523f.wav",
"89524f.wav",
"89525f.wav",
"89526f.wav",
"89527f.wav",
"89528f.wav",
"89529f.wav",
"89530f.wav",
"89531f.wav",
"89532f.wav",
"89533f.wav",
"89536m.wav",
"89553f.wav",
"89554f.wav",
"89555f.wav",
"89556f.wav",
"89578f.wav",
"89611f.wav",
"89620f.wav",
"89699f.wav",
"89753f.wav",
"89754f.wav",
"89827f.wav",
"89828f.wav",
"89830f.wav",
"89833f.wav",
"89834f.wav",
"89835f.wav",
"89836f.wav",
"89837f.wav",
"89848f.wav",
"89858f.wav",
"89859f.wav",
"89860f.wav",
"89861f.wav",
"89862f.wav",
"89880f.wav",
"89881f.wav",
"89882f.wav",
"89883f.wav",
"89885f.wav",
"89886f.wav",
"89887f.wav",
"89889f.wav",
"89890f.wav",
"89892f.wav",
"89893f.wav",
"89906f.wav",
"89913f.wav",
"89949f.wav",
"89951f.wav" };
static void Main(string[] args)
{
foreach (string file in filenames) {
if (FileExists("\\\\192.168.3.241\\Audio_MP3\\" + file))
{
if (!FileExists("\\\\192.168.3.241\\ManualMix\\mp3samples\\" + file))
{
File.Copy("\\\\192.168.3.241\\Audio_MP3\\" + file, "\\\\192.168.3.241\\ManualMix\\mp3samples\\" + file);
//System.Console.WriteLine(file + " SUCCESSFUL");
}
}
else
System.Console.WriteLine(file + " DOES NOT EXIST");
}
Console.WriteLine("Done.");
Console.Read();
}
static bool FileExists(string file)
{
if (File.Exists(file))
return true;
else
return false;
}
}
}
<file_sep>/Mailer/Mailer/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace Mailer
{
class Program
{
static void Main(string[] args)
{
SendEmail();
Console.Read();
}
static void SendEmail()
{
MailAddress from = new MailAddress("<EMAIL>", "<NAME>", Encoding.UTF8);
MailAddress to = new MailAddress("<EMAIL>");
MailMessage m = new MailMessage(from, to);
SmtpClient client = new SmtpClient("smtp.office365.com", 587);
client.Credentials = new NetworkCredential("<EMAIL>", "4WizPlayerz");
client.EnableSsl = true;
m.Subject = String.Format("App generated email test: {0}", DateTime.Now.ToLocalTime());
m.Body = "New mail server test from applicatino.";
client.Send(m);
client.Dispose();
m.Dispose();
Console.WriteLine("Mail sent...");
}
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/PricingTool/Commands/FocusOnSearchCommand.cs
using System;
using System.Linq;
using System.Windows.Input;
namespace PricingTool.Commands
{
public class FocusOnSearchCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter) => true;
public void Execute(object parameter)
{
var vm = parameter as MainViewModel;
vm.IsSearchBoxFocused = false;
vm.IsSearchBoxFocused = true;
}
}
}
<file_sep>/WebApplication1/WebApplication1/WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connstring = "";
SqlConnection oCn = new SqlConnection(connstring);
string sSql = "select * from mytable";
oCn.Open();
SqlCommand oCmd = new SqlCommand(sSql, oCn);
SqlDataReader rdr = oCmd.ExecuteReader();
while (rdr.Read())
{
// dynamic output
string s = "<div class=\"myclass\"></div>";
}
}
}
}<file_sep>/ProdTablesTruncate/ProdTablesTruncate/Program.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProdTablesTruncate
{
class Program
{
static string dt = "1/1/2015";
static void Main(string[] args)
{
Console.WriteLine(String.Format("Starting at {0}", DateTime.Now.ToLocalTime()));
GetProds(GetProdsSql());
Console.Read();
}
static void GetProds(string s)
{
SqlConnection oCn = new SqlConnection("Data Source=OHMG-DEV77\\SQLEXPRESS;Initial Catalog=OhHold;User ID=ohusr;Password=<PASSWORD>");
oCn.Open();
SqlCommand oCmd = new SqlCommand(s, oCn);
SqlDataReader oRdr = oCmd.ExecuteReader();
string outputfile = "output08232016prods.txt";
string output = "";
FileStream fs;
if (oRdr.HasRows)
{
if (!File.Exists(outputfile))
File.Create(outputfile);
while (oRdr.Read())
{
try
{
DelProds(DelProdLocsSql(Convert.ToInt64(oRdr["autProductionID"])));
DelProds(DelProdContentSql(Convert.ToInt64(oRdr["autProductionID"])));
DelProds(DelProdsSql(Convert.ToInt64(oRdr["autProductionID"])));
output = String.Format("{0}\t-\t{1}\t-\tdeleted", oRdr["autProductionID"], oRdr["dtmUploaded"]);
fs = File.Open(outputfile, FileMode.Append, FileAccess.Write);
byte[] bLogHeader = Encoding.Unicode.GetBytes(output + "\r\n");
fs.Write(bLogHeader, 0, bLogHeader.Length);
fs.Close();
Console.WriteLine(output);
}
catch (OverflowException e)
{
Console.WriteLine(e.Message.ToString() + "\t" + oRdr["autProductionID"].ToString());
}
}
}
else
Console.WriteLine("No records");
}
public static void DelProds(string s)
{
SqlConnection oCn = new SqlConnection("Data Source=OHMG-DEV77\\SQLEXPRESS;Initial Catalog=OhHold;User ID=ohusr;Password=<PASSWORD>");
oCn.Open();
SqlCommand oCmd = new SqlCommand(s, oCn);
oCmd.ExecuteNonQuery();
oCn.Close();
}
#region SQL Statements
public static string GetProdsMP3Sql()
{
string s = String.Format("select autProductionID, dtmUploaded from tblProductionsMP3 where (dtmUploaded <= '{0}') order by dtmUploaded desc", dt);
return s;
}
static string GetProdsSql()
{
string s = String.Format("select autProductionID, dtmUploaded from tblProductions where (dtmUploaded <= '{0}') order by dtmUploaded desc", dt);
return s;
}
static string DelProdContentMP3Sql(Int64 ProdID)
{
string s = String.Format("delete from tblProductionContentMP3 where (intProductionID = {0})", ProdID);
return s;
}
static string DelProdContentSql(Int64 ProdID)
{
string s = String.Format("delete from tblProductionContent where (intProductionID = {0})", ProdID);
return s;
}
static string DelProdLocsMP3Sql(Int64 ProdID)
{
string s = String.Format("delete from tblProductionLocationsMP3 where (numProductionID = {0})", ProdID);
return s;
}
static string DelProdLocsSql(Int64 ProdID)
{
string s = String.Format("delete from tblProductionLocations where (numProductionID = {0})", ProdID);
return s;
}
static string DelProdsMP3Sql(Int64 ProdID)
{
string s = String.Format("delete from tblProductionsMP3 where (autProductionID = {0})", ProdID);
return s;
}
static string DelProdsSql(Int64 ProdID)
{
string s = String.Format("delete from tblProductions where (autProductionID = {0})", ProdID);
return s;
}
#endregion
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/MarketAnalyzer.Server/TCGPlayerClient.cs
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace MarketAnalyzer.Server
{
public class TCGPlayerClient
{
public static readonly string rootUrl = "https://api.tcgplayer.com";
private readonly HttpClient client;
private readonly Dictionary<string, string> secrets;
private readonly string storeToken;
public TCGPlayerClient(HttpClient client, string storeToken, Dictionary<string, string> secrets)
{
this.client = client;
this.secrets = secrets;
this.storeToken = storeToken;
}
public int Limit { get; set; } = 100000;
public string AccessToken { get; set; }
public async Task<string> GetAccessTokenAsync()
{
client.DefaultRequestHeaders.Add("X-Tcg-Access-Token", storeToken);
var getTokenResult = await client.PostAsync($"{rootUrl}/token", new FormUrlEncodedContent(secrets));
AccessToken = (await getTokenResult.GetContentAsJObject())["access_token"].Value<string>();
return AccessToken;
}
public async Task<JArray> ListCategories()
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
var getCategoriesResult = await client.GetAsync($"{rootUrl}/catalog/categories?limit={Limit}");
return await getCategoriesResult.ParseResults();
}
private async Task<JArray> GetCategorySubItem(string categoryId, string item)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
var getCategoriesResult = await client.GetAsync($"{rootUrl}/catalog/categories/{categoryId}/{item}?limit={Limit}");
return await getCategoriesResult.ParseResults();
}
public Task<JArray> ListCategoryGroups(string categoryId) => GetCategorySubItem(categoryId, "groups");
public Task<JArray> ListCategoryRarities(string categoryId) => GetCategorySubItem(categoryId, "rarities");
public Task<JArray> ListCategoryPrintings(string categoryId) => GetCategorySubItem(categoryId, "printings");
public Task<JArray> ListCategoryConditions(string categoryId) => GetCategorySubItem(categoryId, "conditions");
public Task<JArray> ListCategoryLanguages(string categoryId) => GetCategorySubItem(categoryId, "languages");
public Task<JArray> ListCategoryMedia(string categoryId) => GetCategorySubItem(categoryId, "media");
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/PricingTool/Commands/LoadedCommand.cs
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net.Http;
using System.Windows.Input;
using TCGPlayer;
namespace PricingTool.Commands
{
public class LoadedCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter) => true;
public async void Execute(object parameter)
{
var vm = parameter as MainViewModel;
var client = new TCGPlayerClient(new HttpClient(), Settings.StoreToken, Settings.Secrets);
var categories = await client.ListCategories();
foreach (JObject category in categories.OrderByDescending(e => e.Value<int>("popularity")))
{
vm.Categories.Add(new Category
{
Id = category["categoryId"].Value<int>(),
Name = category["displayName"].Value<string>(),
Popularity = category["popularity"].Value<int>()
});
}
vm.SelectedCategory = vm.Categories.First();
}
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/MarketAnalyzer/TCGPlayer/TCGPlayerClient.cs
using MarketAnalyzer.Extensions;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace MarketAnalyzer.TCGPlayer
{
public class TCGPlayerClient
{
public static readonly string rootUrl = "https://api.tcgplayer.com";
private readonly HttpClient client;
private readonly Dictionary<string, string> secrets;
private readonly string storeToken;
public TCGPlayerClient(HttpClient client, string storeToken, Dictionary<string, string> secrets)
{
this.client = client;
this.secrets = secrets;
this.storeToken = storeToken;
}
public int Limit { get; set; } = 100;
public string AccessToken { get; set; }
public async Task<string> GetAccessTokenAsync()
{
client.DefaultRequestHeaders.Add("X-Tcg-Access-Token", storeToken);
var getTokenResult = await client.PostAsync($"{rootUrl}/token", new FormUrlEncodedContent(secrets));
if (getTokenResult.IsSuccessStatusCode == false) throw new Exception(getTokenResult.ReasonPhrase);
AccessToken = (await getTokenResult.GetContentAsJObject())["access_token"].Value<string>();
return AccessToken;
}
private async Task<JArray> Get(string urlFragment, int offset = 0)
{
var url = $"{rootUrl}{urlFragment}&offset={offset}";
Console.WriteLine(url);
if (client.DefaultRequestHeaders.Contains("X-Tcg-Access-Token"))
client.DefaultRequestHeaders.Remove("X-Tcg-Access-Token");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
var result = await client.GetAsync(url);
if (result.IsSuccessStatusCode == false) throw new Exception(result.ReasonPhrase);
var response = await result.ParseResults();
var results = response["results"].Value<JArray>();
int totalItems = response.ContainsKey("totalItems") ? response["totalItems"].Value<int>() : results.Count;
int receivedCount = offset + results.Count;
Console.WriteLine($"Fetching {Limit} / {offset} / {receivedCount} / {totalItems} of {url}");
if (totalItems > receivedCount)
return new JArray(results.Union(await Get(urlFragment, receivedCount)));
else
return results;
}
private Task<JArray> GetCategorySubItem(int categoryId, string item) => Get($"/catalog/categories/{categoryId}/{item}?limit={Limit}");
public Task<JArray> ListCategories() => Get($"/catalog/categories?limit={Limit}");
public Task<JArray> ListProductsInGroup(int categoryId, int groupId) => Get($"/catalog/products?categoryId={categoryId}&groupId={groupId}&getExtendedFields=true&limit={Limit}");
public Task<JArray> ListCategoryGroups(int categoryId) => GetCategorySubItem(categoryId, "groups");
public Task<JArray> ListCategoryRarities(int categoryId) => GetCategorySubItem(categoryId, "rarities");
public Task<JArray> ListCategoryPrintings(int categoryId) => GetCategorySubItem(categoryId, "printings");
public Task<JArray> ListCategoryConditions(int categoryId) => GetCategorySubItem(categoryId, "conditions");
public Task<JArray> ListCategoryLanguages(int categoryId) => GetCategorySubItem(categoryId, "languages");
public Task<JArray> ListCategoryMedia(int categoryId) => GetCategorySubItem(categoryId, "media");
}
}
<file_sep>/TCG_Projects/MarketAnalyzer-master/MarketAnalyzer/Entities/Document.cs
using System;
using System.Linq;
namespace MarketAnalyzer.Entities
{
public class Document
{
public string id { get; set; }
public int typeId { get; set; }
public string type { get; set; }
public string name { get; set; }
public bool enabled { get; set; }
public dynamic data { get; set; }
}
}
<file_sep>/Refresh2/Refresh2/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
namespace Refresh2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void bStart_Click(object sender, EventArgs e)
{
bStart.Visible = false;
bStart.Enabled = false;
bStop.Visible = true;
bStop.Enabled = true;
refresh_proc();
timer1.Start();
}
private void bStop_Click(object sender, EventArgs e)
{
bStart.Visible = true;
bStart.Enabled = true;
bStop.Visible = false;
bStop.Enabled = false;
timer1.Stop();
}
private void refresh_proc()
{
int x = 1;
int y = -1;
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X + x, Cursor.Position.Y + y);
textBox1.Text += DateTime.Now.ToLocalTime() + "\r\n";
x += 1;
y += 1;
}
private void timer1_Tick(object sender, EventArgs e)
{
refresh_proc();
}
}
}
| 921b2dba4d7d16bb5566def706828fe89ff4cc89 | [
"Markdown",
"C#"
]
| 25 | Markdown | guitardave/VS_Projects | 9cd7e0bb120657ccae649d7aea7df5f4c23ecf15 | 68d756708fd68005b53d869068c3ef20f525f317 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.